param-definition.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import { Color as ColorData } from './color';
  8. import { shallowEqualObjects } from './index';
  9. import { Vec2 as Vec2Data, Vec3 as Vec3Data, Mat4 as Mat4Data, EPSILON } from '../mol-math/linear-algebra';
  10. import { deepClone } from './object';
  11. import { Script as ScriptData } from '../mol-script/script';
  12. import { Legend } from './legend';
  13. import { stringToWords } from './string';
  14. import { getColorListFromName, ColorListName } from './color/lists';
  15. import { Asset } from './assets';
  16. import { ColorListEntry } from './color/color';
  17. export namespace ParamDefinition {
  18. export interface Info {
  19. label?: string,
  20. description?: string,
  21. legend?: Legend,
  22. fieldLabels?: { [name: string]: string },
  23. isHidden?: boolean,
  24. shortLabel?: boolean,
  25. twoColumns?: boolean,
  26. isEssential?: boolean,
  27. category?: string,
  28. hideIf?: (currentGroup: any) => boolean,
  29. help?: (value: any) => { description?: string, legend?: Legend }
  30. }
  31. export const Essential = { isEssential: true };
  32. function setInfo<T extends Base<any>>(param: T, info?: Info): T {
  33. if (!info) return param;
  34. if (info.label) param.label = info.label;
  35. if (info.description) param.description = info.description;
  36. if (info.legend) param.legend = info.legend;
  37. if (info.fieldLabels) param.fieldLabels = info.fieldLabels;
  38. if (info.isHidden) param.isHidden = info.isHidden;
  39. if (info.shortLabel) param.shortLabel = info.shortLabel;
  40. if (info.twoColumns) param.twoColumns = info.twoColumns;
  41. if (info.isEssential) param.isEssential = info.isEssential;
  42. if (info.category) param.category = info.category;
  43. if (info.hideIf) param.hideIf = info.hideIf;
  44. if (info.help) param.help = info.help;
  45. return param;
  46. }
  47. export interface Base<T> extends Info {
  48. isOptional?: boolean,
  49. defaultValue: T
  50. }
  51. export interface Optional<T extends Any = Any> extends Base<T['defaultValue'] | undefined> {
  52. type: T['type']
  53. }
  54. export function Optional<T>(p: Base<T>): Base<T | undefined> {
  55. const ret = { ...p };
  56. ret.isOptional = true;
  57. return ret;
  58. }
  59. export interface Value<T> extends Base<T> {
  60. type: 'value'
  61. }
  62. export function Value<T>(defaultValue: T, info?: Info): Value<T> {
  63. return setInfo<Value<T>>({ type: 'value', defaultValue }, info);
  64. }
  65. export interface Select<T> extends Base<T> {
  66. type: 'select'
  67. /** array of (value, label) tuples */
  68. options: readonly (readonly [T, string] | readonly [T, string, string | undefined])[]
  69. cycle?: boolean
  70. }
  71. export function Select<T>(defaultValue: T, options: readonly (readonly [T, string] | readonly [T, string, string | undefined])[], info?: Info & { cycle?: boolean }): Select<T> {
  72. return setInfo<Select<T>>({ type: 'select', defaultValue: checkDefaultKey(defaultValue, options), options, cycle: info?.cycle }, info);
  73. }
  74. export interface MultiSelect<E extends string> extends Base<E[]> {
  75. type: 'multi-select'
  76. /** array of (value, label) tuples */
  77. options: readonly (readonly [E, string])[],
  78. emptyValue?: string
  79. }
  80. export function MultiSelect<E extends string>(defaultValue: E[], options: readonly (readonly [E, string])[], info?: Info & { emptyValue?: string }): MultiSelect<E> {
  81. // TODO: check if default value is a subset of options?
  82. const ret = setInfo<MultiSelect<E>>({ type: 'multi-select', defaultValue, options }, info);
  83. if (info?.emptyValue) ret.emptyValue = info.emptyValue;
  84. return ret;
  85. }
  86. export interface BooleanParam extends Base<boolean> {
  87. type: 'boolean'
  88. }
  89. export function Boolean(defaultValue: boolean, info?: Info): BooleanParam {
  90. return setInfo<BooleanParam>({ type: 'boolean', defaultValue }, info);
  91. }
  92. export interface Text<T extends string = string> extends Base<T> {
  93. type: 'text'
  94. }
  95. export function Text<T extends string = string>(defaultValue: string = '', info?: Info): Text<T> {
  96. return setInfo<Text<T>>({ type: 'text', defaultValue: defaultValue as any }, info);
  97. }
  98. export interface Color extends Base<ColorData> {
  99. type: 'color'
  100. isExpanded?: boolean
  101. }
  102. export function Color(defaultValue: ColorData, info?: Info & { isExpanded?: boolean }): Color {
  103. const ret = setInfo<Color>({ type: 'color', defaultValue }, info);
  104. if (info?.isExpanded) ret.isExpanded = info.isExpanded;
  105. return ret;
  106. }
  107. export interface ColorList extends Base<{ kind: 'interpolate' | 'set', colors: ColorListEntry[] }> {
  108. type: 'color-list'
  109. offsets: boolean
  110. presetKind: 'all' | 'scale' | 'set'
  111. }
  112. export function ColorList(defaultValue: { kind: 'interpolate' | 'set', colors: ColorListEntry[] } | ColorListName, info?: Info & { presetKind?: ColorList['presetKind'], offsets?: boolean }): ColorList {
  113. let def: ColorList['defaultValue'];
  114. if (typeof defaultValue === 'string') {
  115. const colors = getColorListFromName(defaultValue);
  116. def = { kind: colors.type !== 'qualitative' ? 'interpolate' : 'set', colors: colors.list };
  117. } else {
  118. def = defaultValue;
  119. }
  120. return setInfo<ColorList>({ type: 'color-list', presetKind: info?.presetKind || 'all', defaultValue: def, offsets: !!info?.offsets }, info);
  121. }
  122. export interface Vec3 extends Base<Vec3Data>, Range {
  123. type: 'vec3'
  124. }
  125. export function Vec3(defaultValue: Vec3Data, range?: { min?: number, max?: number, step?: number }, info?: Info): Vec3 {
  126. return setInfo<Vec3>(setRange({ type: 'vec3', defaultValue }, range), info);
  127. }
  128. export interface Mat4 extends Base<Mat4Data> {
  129. type: 'mat4'
  130. }
  131. export function Mat4(defaultValue: Mat4Data, info?: Info): Mat4 {
  132. return setInfo<Mat4>({ type: 'mat4', defaultValue }, info);
  133. }
  134. export interface UrlParam extends Base<Asset.Url | string> {
  135. type: 'url'
  136. }
  137. export function Url(url: string | { url: string, body?: string }, info?: Info): UrlParam {
  138. const defaultValue = typeof url === 'string' ? Asset.Url(url) : Asset.Url(url.url, { body: url.body });
  139. const ret = setInfo<UrlParam>({ type: 'url', defaultValue }, info);
  140. return ret;
  141. }
  142. export interface FileParam extends Base<Asset.File | null> {
  143. type: 'file'
  144. accept?: string
  145. }
  146. export function File(info?: Info & { accept?: string, multiple?: boolean }): FileParam {
  147. const ret = setInfo<FileParam>({ type: 'file', defaultValue: null }, info);
  148. if (info?.accept) ret.accept = info.accept;
  149. return ret;
  150. }
  151. export interface FileListParam extends Base<Asset.File[] | null> {
  152. type: 'file-list'
  153. accept?: string
  154. }
  155. export function FileList(info?: Info & { accept?: string, multiple?: boolean }): FileListParam {
  156. const ret = setInfo<FileListParam>({ type: 'file-list', defaultValue: null }, info);
  157. if (info?.accept) ret.accept = info.accept;
  158. return ret;
  159. }
  160. export interface Range {
  161. /** If given treat as a range. */
  162. min?: number
  163. /** If given treat as a range. */
  164. max?: number
  165. /**
  166. * If given treat as a range.
  167. * If an `integer` parse value with parseInt, otherwise use parseFloat.
  168. */
  169. step?: number
  170. }
  171. function setRange<T extends Numeric | Interval | Vec3>(p: T, range?: { min?: number, max?: number, step?: number }) {
  172. if (!range) return p;
  173. if (typeof range.min !== 'undefined') p.min = range.min;
  174. if (typeof range.max !== 'undefined') p.max = range.max;
  175. if (typeof range.step !== 'undefined') p.step = range.step;
  176. return p;
  177. }
  178. export interface Numeric extends Base<number>, Range {
  179. type: 'number',
  180. immediateUpdate?: boolean
  181. }
  182. export function Numeric(defaultValue: number, range?: { min?: number, max?: number, step?: number }, info?: Info & { immediateUpdate?: boolean }): Numeric {
  183. const ret = setInfo<Numeric>(setRange({ type: 'number', defaultValue }, range), info);
  184. if (info?.immediateUpdate) ret.immediateUpdate = true;
  185. return ret;
  186. }
  187. export interface Interval extends Base<[number, number]>, Range {
  188. type: 'interval'
  189. }
  190. export function Interval(defaultValue: [number, number], range?: { min?: number, max?: number, step?: number }, info?: Info): Interval {
  191. return setInfo<Interval>(setRange({ type: 'interval', defaultValue }, range), info);
  192. }
  193. export interface LineGraph extends Base<Vec2Data[]> {
  194. type: 'line-graph'
  195. }
  196. export function LineGraph(defaultValue: Vec2Data[], info?: Info): LineGraph {
  197. return setInfo<LineGraph>({ type: 'line-graph', defaultValue }, info);
  198. }
  199. export interface Group<T> extends Base<T> {
  200. type: 'group',
  201. params: Params,
  202. presets?: Select<T>['options'],
  203. isExpanded?: boolean,
  204. isFlat?: boolean,
  205. pivot?: keyof T
  206. }
  207. export function Group<T>(params: For<T>, info?: Info & { isExpanded?: boolean, isFlat?: boolean, customDefault?: any, pivot?: keyof T, presets?: Select<T>['options'] }): Group<Normalize<T>> {
  208. const ret = setInfo<Group<Normalize<T>>>({ type: 'group', defaultValue: info?.customDefault || getDefaultValues(params as any as Params) as any, params: params as any as Params }, info);
  209. if (info?.presets) ret.presets = info.presets;
  210. if (info?.isExpanded) ret.isExpanded = info.isExpanded;
  211. if (info?.isFlat) ret.isFlat = info.isFlat;
  212. if (info?.pivot) ret.pivot = info.pivot as any;
  213. return ret;
  214. }
  215. export function EmptyGroup(info?: Info) {
  216. return Group({}, info);
  217. }
  218. export interface NamedParams<T = any, K = string> { name: K, params: T }
  219. export type NamedParamUnion<P extends Params, K extends keyof P = keyof P> = K extends any ? NamedParams<P[K]['defaultValue'], K> : never
  220. export interface Mapped<T extends NamedParams<any, any>> extends Base<T> {
  221. type: 'mapped',
  222. select: Select<string>,
  223. map(name: string): Any
  224. }
  225. export function Mapped<T>(defaultKey: string, names: ([string, string] | [string, string, string])[], map: (name: string) => Any, info?: Info & { cycle?: boolean }): Mapped<NamedParams<T>> {
  226. const name = checkDefaultKey(defaultKey, names);
  227. return setInfo<Mapped<NamedParams<T>>>({
  228. type: 'mapped',
  229. defaultValue: { name, params: map(name).defaultValue as any },
  230. select: Select<string>(name, names, info),
  231. map
  232. }, info);
  233. }
  234. export function MappedStatic<C extends Params>(defaultKey: keyof C, map: C, info?: Info & { options?: [keyof C, string][], cycle?: boolean }): Mapped<NamedParamUnion<C>> {
  235. const options: [string, string][] = info?.options
  236. ? info.options as [string, string][]
  237. : Object.keys(map).map(k => [k, map[k].label || stringToWords(k)]) as [string, string][];
  238. const name = checkDefaultKey(defaultKey, options);
  239. return setInfo<Mapped<NamedParamUnion<C>>>({
  240. type: 'mapped',
  241. defaultValue: { name, params: map[name].defaultValue } as any,
  242. select: Select<string>(name as string, options, info),
  243. map: key => map[key]
  244. }, info);
  245. }
  246. export interface ObjectList<T = any> extends Base<T[]> {
  247. type: 'object-list',
  248. element: Params,
  249. ctor(): T,
  250. getLabel(t: T): string
  251. }
  252. export function ObjectList<T>(element: For<T>, getLabel: (e: T) => string, info?: Info & { defaultValue?: T[], ctor?: () => T }): ObjectList<Normalize<T>> {
  253. return setInfo<ObjectList<Normalize<T>>>({ type: 'object-list', element: element as any as Params, getLabel, ctor: _defaultObjectListCtor, defaultValue: (info?.defaultValue) || [] }, info);
  254. }
  255. function _defaultObjectListCtor(this: ObjectList) { return getDefaultValues(this.element) as any; }
  256. function unsetGetValue() {
  257. throw new Error('getValue not set. Fix runtime.');
  258. }
  259. // getValue needs to be assigned by a runtime because it might not be serializable
  260. export interface ValueRef<T = any> extends Base<{ ref: string, getValue: () => T }> {
  261. type: 'value-ref',
  262. resolveRef: (ref: string, getData: (ref: string) => any) => T,
  263. // a provider because the list changes over time
  264. getOptions: (ctx: any) => Select<string>['options'],
  265. }
  266. export function ValueRef<T>(getOptions: ValueRef['getOptions'], resolveRef: ValueRef<T>['resolveRef'], info?: Info & { defaultRef?: string }) {
  267. return setInfo<ValueRef<T>>({ type: 'value-ref', defaultValue: { ref: info?.defaultRef ?? '', getValue: unsetGetValue as any }, getOptions, resolveRef }, info);
  268. }
  269. export interface DataRef<T = any> extends Base<{ ref: string, getValue: () => T }> {
  270. type: 'data-ref'
  271. }
  272. export function DataRef<T>(info?: Info & { defaultRef?: string }) {
  273. return setInfo<DataRef<T>>({ type: 'data-ref', defaultValue: { ref: info?.defaultRef ?? '', getValue: unsetGetValue as any } }, info);
  274. }
  275. export interface Converted<T, C> extends Base<T> {
  276. type: 'converted',
  277. converted: Any,
  278. /** converts from prop value to display value */
  279. fromValue(v: T): C,
  280. /** converts from display value to prop value */
  281. toValue(v: C): T
  282. }
  283. export function Converted<T, C extends Any>(fromValue: (v: T) => C['defaultValue'], toValue: (v: C['defaultValue']) => T, converted: C): Converted<T, C['defaultValue']> {
  284. return { type: 'converted', defaultValue: toValue(converted.defaultValue), converted, fromValue, toValue };
  285. }
  286. export interface Conditioned<T, P extends Base<T>, C = { [k: string]: P }> extends Base<T> {
  287. type: 'conditioned',
  288. select: Select<string>,
  289. conditionParams: C
  290. conditionForValue(v: T): keyof C
  291. conditionedValue(v: T, condition: keyof C): T,
  292. }
  293. export function Conditioned<T, P extends Base<T>, C extends {} = { [k: string]: P }>(defaultValue: T, conditionParams: C, conditionForValue: (v: T) => keyof C, conditionedValue: (v: T, condition: keyof C) => T, info?: Info): Conditioned<T, P, C> {
  294. const options = Object.keys(conditionParams).map(k => [k, k]) as [string, string][];
  295. return setInfo({ type: 'conditioned', select: Select<string>(conditionForValue(defaultValue) as string, options, info), defaultValue, conditionParams, conditionForValue, conditionedValue }, info);
  296. }
  297. export interface Script extends Base<ScriptData> {
  298. type: 'script'
  299. }
  300. export function Script(defaultValue: Script['defaultValue'], info?: Info): Script {
  301. return setInfo<Script>({ type: 'script', defaultValue }, info);
  302. }
  303. export type Any =
  304. | Value<any> | Select<any> | MultiSelect<any> | BooleanParam | Text | Color | Vec3 | Mat4 | Numeric | FileParam | UrlParam | FileListParam | Interval | LineGraph
  305. | ColorList | Group<any> | Mapped<any> | Converted<any, any> | Conditioned<any, any, any> | Script | ObjectList | ValueRef | DataRef
  306. export type Params = { [k: string]: Any }
  307. export type Values<T extends Params> = { [k in keyof T]: T[k]['defaultValue'] }
  308. /** This is required for params with optional values */
  309. export type ValuesFor<T extends For<any>> = Normalize<{ [k in keyof T]: T[k]['defaultValue'] }>
  310. type Optionals<P> = { [K in keyof P]-?: undefined extends P[K] ? K : never }[keyof P]
  311. type NonOptionals<P> = { [K in keyof P]-?: undefined extends P[K] ? never : K }[keyof P]
  312. export type Normalize<P> = Pick<P, NonOptionals<P>> & Partial<Pick<P, Optionals<P>>>
  313. export type For<P> = { [K in keyof P]-?: Base<P[K]> }
  314. export type Def<P> = { [K in keyof P]: Any }
  315. export function For<P>(params: For<P>): For<P> {
  316. return 0 as any;
  317. }
  318. export function getDefaultValues<T extends Params>(params: T) {
  319. const d: { [k: string]: any } = {};
  320. for (const k of Object.keys(params)) {
  321. if (params[k].isOptional) continue;
  322. d[k] = params[k].defaultValue;
  323. }
  324. return d as Values<T>;
  325. }
  326. function _resolveRef(resolve: (ref: string, getData: (ref: string) => any) => any, ref: string, getData: (ref: string) => any) {
  327. return () => resolve(ref, getData);
  328. }
  329. function resolveRefValue(p: Any, value: any, getData: (ref: string) => any) {
  330. if (!value) return;
  331. if (p.type === 'value-ref') {
  332. const v = value as ValueRef['defaultValue'];
  333. if (!v.ref) v.getValue = () => { throw new Error('Unset ref in ValueRef value.'); };
  334. else v.getValue = _resolveRef(p.resolveRef, v.ref, getData);
  335. } else if (p.type === 'data-ref') {
  336. const v = value as ValueRef['defaultValue'];
  337. if (!v.ref) v.getValue = () => { throw new Error('Unset ref in ValueRef value.'); };
  338. else v.getValue = _resolveRef(getData, v.ref, getData);
  339. } else if (p.type === 'group') {
  340. resolveRefs(p.params, value, getData);
  341. } else if (p.type === 'mapped') {
  342. const v = value as NamedParams;
  343. const param = p.map(v.name);
  344. resolveRefValue(param, v.params, getData);
  345. } else if (p.type === 'object-list') {
  346. if (!hasValueRef(p.element)) return;
  347. for (const e of value) {
  348. resolveRefs(p.element, e, getData);
  349. }
  350. }
  351. }
  352. function hasParamValueRef(p: Any) {
  353. if (p.type === 'value-ref' || p.type === 'data-ref') {
  354. return true;
  355. } else if (p.type === 'group') {
  356. if (hasValueRef(p.params)) return true;
  357. } else if (p.type === 'mapped') {
  358. for (const [o] of p.select.options) {
  359. if (hasParamValueRef(p.map(o))) return true;
  360. }
  361. } else if (p.type === 'object-list') {
  362. return hasValueRef(p.element);
  363. }
  364. return false;
  365. }
  366. function hasValueRef(params: Params) {
  367. for (const n of Object.keys(params)) {
  368. if (hasParamValueRef(params[n])) return true;
  369. }
  370. return false;
  371. }
  372. export function resolveRefs(params: Params, values: any, getData: (ref: string) => any) {
  373. for (const n of Object.keys(params)) {
  374. resolveRefValue(params[n], values?.[n], getData);
  375. }
  376. }
  377. export function setDefaultValues<T extends Params>(params: T, defaultValues: Values<T>) {
  378. for (const k of Object.keys(params)) {
  379. if (params[k].isOptional) continue;
  380. params[k].defaultValue = defaultValues[k];
  381. }
  382. }
  383. export function clone<P extends Params>(params: P): P {
  384. return deepClone(params);
  385. }
  386. /**
  387. * List of [error text, pathToValue]
  388. * i.e. ['Missing Nested Id', ['group1', 'id']]
  389. */
  390. export type ParamErrors = [string, string | string[]][]
  391. export function validate(params: Params, values: any): ParamErrors | undefined {
  392. // TODO
  393. return void 0;
  394. }
  395. export function areEqual(params: Params, a: any, b: any): boolean {
  396. if (a === b) return true;
  397. if (typeof a !== 'object' || typeof b !== 'object') return false;
  398. for (const k of Object.keys(params)) {
  399. if (!isParamEqual(params[k], a[k], b[k])) return false;
  400. }
  401. return true;
  402. }
  403. export function isParamEqual(p: Any, a: any, b: any): boolean {
  404. if (a === b) return true;
  405. if (p.type === 'group') {
  406. return areEqual(p.params, a, b);
  407. } else if (p.type === 'mapped') {
  408. const u = a as NamedParams, v = b as NamedParams;
  409. if (u.name !== v.name) return false;
  410. const map = p.map(u.name);
  411. return isParamEqual(map, u.params, v.params);
  412. } else if (p.type === 'multi-select') {
  413. const u = a as MultiSelect<any>['defaultValue'], v = b as MultiSelect<any>['defaultValue'];
  414. if (u.length !== v.length) return false;
  415. if (u.length < 10) {
  416. for (let i = 0, _i = u.length; i < _i; i++) {
  417. if (u[i] === v[i]) continue;
  418. if (v.indexOf(u[i]) < 0) return false;
  419. }
  420. } else {
  421. // TODO: should the value of multiselect be a set?
  422. const vSet = new Set(v);
  423. for (let i = 0, _i = u.length; i < _i; i++) {
  424. if (u[i] === v[i]) continue;
  425. if (!vSet.has(u[i])) return false;
  426. }
  427. }
  428. return true;
  429. } else if (p.type === 'interval') {
  430. return a[0] === b[0] && a[1] === b[1];
  431. } else if (p.type === 'line-graph') {
  432. const u = a as LineGraph['defaultValue'], v = b as LineGraph['defaultValue'];
  433. if (u.length !== v.length) return false;
  434. for (let i = 0, _i = u.length; i < _i; i++) {
  435. if (!Vec2Data.areEqual(u[i], v[i])) return false;
  436. }
  437. return true;
  438. } else if (p.type === 'vec3') {
  439. return Vec3Data.equals(a, b);
  440. } else if (p.type === 'mat4') {
  441. return Mat4Data.areEqual(a, b, EPSILON);
  442. } else if (p.type === 'script') {
  443. const u = a as Script['defaultValue'], v = b as Script['defaultValue'];
  444. return u.language === v.language && u.expression === v.expression;
  445. } else if (p.type === 'object-list') {
  446. const u = a as ObjectList['defaultValue'], v = b as ObjectList['defaultValue'];
  447. const l = u.length;
  448. if (l !== v.length) return false;
  449. for (let i = 0; i < l; i++) {
  450. if (!areEqual(p.element, u[i], v[i])) return false;
  451. }
  452. return true;
  453. } else if (typeof a === 'object' && typeof b === 'object') {
  454. return shallowEqualObjects(a, b);
  455. }
  456. // a === b was checked at the top.
  457. return false;
  458. }
  459. export function merge<P extends Params>(params: P, a: any, b: any): Values<P> {
  460. if (a === undefined) return { ...b };
  461. if (b === undefined) return { ...a };
  462. const o = Object.create(null);
  463. for (const k of Object.keys(params)) {
  464. o[k] = mergeParam(params[k], a[k], b[k]);
  465. }
  466. return o;
  467. }
  468. export function mergeParam(p: Any, a: any, b: any): any {
  469. if (a === undefined) return typeof b === 'object' && !Array.isArray(b) ? { ...b } : b;
  470. if (b === undefined) return typeof a === 'object' && !Array.isArray(a) ? { ...a } : a;
  471. if (p.type === 'group') {
  472. return merge(p.params, a, b);
  473. } else if (p.type === 'mapped') {
  474. const u = a as NamedParams, v = b as NamedParams;
  475. if (u.name !== v.name) return { ...v };
  476. const map = p.map(v.name);
  477. return {
  478. name: v.name,
  479. params: mergeParam(map, u.params, v.params)
  480. };
  481. } else if (p.type === 'value') {
  482. return b;
  483. } else if (typeof a === 'object' && typeof b === 'object') {
  484. if (Array.isArray(b)) {
  485. return b;
  486. }
  487. return { ...a, ...b };
  488. } else {
  489. return b;
  490. }
  491. }
  492. function selectHasOption(p: Select<any> | MultiSelect<any>, v: any) {
  493. for (const o of p.options) {
  494. if (o[0] === v) return true;
  495. }
  496. return false;
  497. }
  498. function normalizeParam(p: Any, value: any, defaultIfUndefined: boolean): any {
  499. if (value === void 0 || value === null) {
  500. return defaultIfUndefined ? p.defaultValue : void 0;
  501. }
  502. // TODO: is this a good idea and will work well?
  503. // if (typeof p.defaultValue !== typeof value) {
  504. // return p.defaultValue;
  505. // }
  506. if (p.type === 'value') {
  507. return value;
  508. } else if (p.type === 'group') {
  509. const ret = Object.create(null);
  510. for (const key of Object.keys(p.params)) {
  511. const param = p.params[key];
  512. if (value[key] === void 0) {
  513. if (defaultIfUndefined) ret[key] = param.defaultValue;
  514. } else {
  515. ret[key] = normalizeParam(param, value[key], defaultIfUndefined);
  516. }
  517. }
  518. return ret;
  519. } else if (p.type === 'mapped') {
  520. const v = value as NamedParams;
  521. if (typeof v.name !== 'string') {
  522. return p.defaultValue;
  523. }
  524. if (typeof v.params === 'undefined') {
  525. return defaultIfUndefined ? p.defaultValue : void 0;
  526. }
  527. if (!selectHasOption(p.select, v.name)) {
  528. return p.defaultValue;
  529. }
  530. const param = p.map(v.name);
  531. return {
  532. name: v.name,
  533. params: normalizeParam(param, v.params, defaultIfUndefined)
  534. };
  535. } else if (p.type === 'select') {
  536. if (!selectHasOption(p, value)) return p.defaultValue;
  537. return value;
  538. } else if (p.type === 'multi-select') {
  539. if (!Array.isArray(value)) return p.defaultValue;
  540. const ret = value.filter(function (this: MultiSelect<any>, v: any) { return selectHasOption(this, v); }, p);
  541. if (value.length > 0 && ret.length === 0) return p.defaultValue;
  542. return ret;
  543. } else if (p.type === 'object-list') {
  544. if (!Array.isArray(value)) return p.defaultValue;
  545. return value.map(v => normalizeParams(p.element, v, defaultIfUndefined ? 'all' : 'skip'));
  546. }
  547. // TODO: validate/normalize all param types "properly"??
  548. return value;
  549. }
  550. export function normalizeParams(p: Params, value: any, defaultIfUndefined: 'all' | 'children' | 'skip') {
  551. if (typeof value !== 'object' || value === null) {
  552. return defaultIfUndefined ? getDefaultValues(p) : value;
  553. }
  554. const ret = Object.create(null);
  555. for (const key of Object.keys(p)) {
  556. const param = p[key];
  557. if (value[key] === void 0) {
  558. if (defaultIfUndefined === 'all') ret[key] = param.defaultValue;
  559. } else {
  560. ret[key] = normalizeParam(param, value[key], defaultIfUndefined !== 'skip');
  561. }
  562. }
  563. return ret;
  564. }
  565. /**
  566. * Map an object to a list of [K, string][] to be used as options, stringToWords for key used by default (or identity of null).
  567. *
  568. * if options is { [string]: string } and mapping is not provided, use the Value.
  569. */
  570. export function objectToOptions<K extends string, V>(options: { [k in K]: V }, f?: null | ((k: K, v: V) => string | [string, string])): [K, string][] {
  571. const ret: ([K, string] | [K, string, string])[] = [];
  572. for (const k of Object.keys(options) as K[]) {
  573. if (!f) {
  574. if (typeof options[k as K] === 'string') ret.push([k as K, options[k as K] as any]);
  575. else ret.push([k as K, f === null ? k : stringToWords(k)]);
  576. } else {
  577. const o = f(k as K, options[k as K]);
  578. ret.push(typeof o === 'string' ? [k, o] : [k, o[0], o[1]]);
  579. }
  580. }
  581. return ret as [K, string][];
  582. }
  583. /**
  584. * Map array of options using stringToWords by default (or identity of null).
  585. */
  586. export function arrayToOptions<V extends string>(xs: readonly V[], f?: null | ((v: V) => string)): [V, string][] {
  587. const ret: [V, string][] = [];
  588. for (const x of xs) {
  589. if (!f) {
  590. ret.push([x, f === null ? x : stringToWords(x)]);
  591. } else {
  592. ret.push([x, f(x)]);
  593. }
  594. }
  595. return ret;
  596. }
  597. export function optionLabel<T>(param: Select<T>, value: T) {
  598. for (const o of param.options) {
  599. if (o[0] === value) return o[1];
  600. }
  601. return '';
  602. }
  603. function checkDefaultKey<T>(k: T, options: readonly (readonly [T, string] | readonly [T, string, string | undefined])[]) {
  604. for (const o of options) {
  605. if (o[0] === k) return k;
  606. }
  607. return options.length > 0 ? options[0][0] : void 0 as any as T;
  608. }
  609. }