param-definition.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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. isExpanded?: boolean,
  203. isFlat?: boolean,
  204. pivot?: keyof T
  205. }
  206. export function Group<T>(params: For<T>, info?: Info & { isExpanded?: boolean, isFlat?: boolean, customDefault?: any, pivot?: keyof T }): Group<Normalize<T>> {
  207. 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);
  208. if (info?.isExpanded) ret.isExpanded = info.isExpanded;
  209. if (info?.isFlat) ret.isFlat = info.isFlat;
  210. if (info?.pivot) ret.pivot = info.pivot as any;
  211. return ret;
  212. }
  213. export function EmptyGroup(info?: Info) {
  214. return Group({}, info);
  215. }
  216. export interface NamedParams<T = any, K = string> { name: K, params: T }
  217. export type NamedParamUnion<P extends Params, K extends keyof P = keyof P> = K extends any ? NamedParams<P[K]['defaultValue'], K> : never
  218. export interface Mapped<T extends NamedParams<any, any>> extends Base<T> {
  219. type: 'mapped',
  220. select: Select<string>,
  221. map(name: string): Any
  222. }
  223. export function Mapped<T>(defaultKey: string, names: ([string, string] | [string, string, string])[], map: (name: string) => Any, info?: Info & { cycle?: boolean }): Mapped<NamedParams<T>> {
  224. const name = checkDefaultKey(defaultKey, names);
  225. return setInfo<Mapped<NamedParams<T>>>({
  226. type: 'mapped',
  227. defaultValue: { name, params: map(name).defaultValue as any },
  228. select: Select<string>(name, names, info),
  229. map
  230. }, info);
  231. }
  232. export function MappedStatic<C extends Params>(defaultKey: keyof C, map: C, info?: Info & { options?: [keyof C, string][], cycle?: boolean }): Mapped<NamedParamUnion<C>> {
  233. const options: [string, string][] = info?.options
  234. ? info.options as [string, string][]
  235. : Object.keys(map).map(k => [k, map[k].label || stringToWords(k)]) as [string, string][];
  236. const name = checkDefaultKey(defaultKey, options);
  237. return setInfo<Mapped<NamedParamUnion<C>>>({
  238. type: 'mapped',
  239. defaultValue: { name, params: map[name].defaultValue } as any,
  240. select: Select<string>(name as string, options, info),
  241. map: key => map[key]
  242. }, info);
  243. }
  244. export interface ObjectList<T = any> extends Base<T[]> {
  245. type: 'object-list',
  246. element: Params,
  247. ctor(): T,
  248. getLabel(t: T): string
  249. }
  250. export function ObjectList<T>(element: For<T>, getLabel: (e: T) => string, info?: Info & { defaultValue?: T[], ctor?: () => T }): ObjectList<Normalize<T>> {
  251. return setInfo<ObjectList<Normalize<T>>>({ type: 'object-list', element: element as any as Params, getLabel, ctor: _defaultObjectListCtor, defaultValue: (info?.defaultValue) || [] }, info);
  252. }
  253. function _defaultObjectListCtor(this: ObjectList) { return getDefaultValues(this.element) as any; }
  254. function unsetGetValue() {
  255. throw new Error('getValue not set. Fix runtime.');
  256. }
  257. // getValue needs to be assigned by a runtime because it might not be serializable
  258. export interface ValueRef<T = any> extends Base<{ ref: string, getValue: () => T }> {
  259. type: 'value-ref',
  260. resolveRef: (ref: string) => T,
  261. // a provider because the list changes over time
  262. getOptions: () => Select<string>['options'],
  263. }
  264. export function ValueRef<T>(getOptions: ValueRef['getOptions'], resolveRef: ValueRef<T>['resolveRef'], info?: Info & { defaultRef?: string }) {
  265. return setInfo<ValueRef<T>>({ type: 'value-ref', defaultValue: { ref: info?.defaultRef ?? '', getValue: unsetGetValue as any }, getOptions, resolveRef }, info);
  266. }
  267. export interface DataRef<T = any> extends Base<{ ref: string, getValue: () => T }> {
  268. type: 'data-ref'
  269. }
  270. export function DataRef<T>(info?: Info & { defaultRef?: string }) {
  271. return setInfo<DataRef<T>>({ type: 'data-ref', defaultValue: { ref: info?.defaultRef ?? '', getValue: unsetGetValue as any } }, info);
  272. }
  273. export interface Converted<T, C> extends Base<T> {
  274. type: 'converted',
  275. converted: Any,
  276. /** converts from prop value to display value */
  277. fromValue(v: T): C,
  278. /** converts from display value to prop value */
  279. toValue(v: C): T
  280. }
  281. export function Converted<T, C extends Any>(fromValue: (v: T) => C['defaultValue'], toValue: (v: C['defaultValue']) => T, converted: C): Converted<T, C['defaultValue']> {
  282. return { type: 'converted', defaultValue: toValue(converted.defaultValue), converted, fromValue, toValue };
  283. }
  284. export interface Conditioned<T, P extends Base<T>, C = { [k: string]: P }> extends Base<T> {
  285. type: 'conditioned',
  286. select: Select<string>,
  287. conditionParams: C
  288. conditionForValue(v: T): keyof C
  289. conditionedValue(v: T, condition: keyof C): T,
  290. }
  291. export function Conditioned<T, P extends Base<T>, C = { [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> {
  292. const options = Object.keys(conditionParams).map(k => [k, k]) as [string, string][];
  293. return setInfo({ type: 'conditioned', select: Select<string>(conditionForValue(defaultValue) as string, options, info), defaultValue, conditionParams, conditionForValue, conditionedValue }, info);
  294. }
  295. export interface Script extends Base<ScriptData> {
  296. type: 'script'
  297. }
  298. export function Script(defaultValue: Script['defaultValue'], info?: Info): Script {
  299. return setInfo<Script>({ type: 'script', defaultValue }, info);
  300. }
  301. export type Any =
  302. | Value<any> | Select<any> | MultiSelect<any> | BooleanParam | Text | Color | Vec3 | Mat4 | Numeric | FileParam | UrlParam | FileListParam | Interval | LineGraph
  303. | ColorList | Group<any> | Mapped<any> | Converted<any, any> | Conditioned<any, any, any> | Script | ObjectList | ValueRef | DataRef
  304. export type Params = { [k: string]: Any }
  305. export type Values<T extends Params> = { [k in keyof T]: T[k]['defaultValue'] }
  306. /** This is required for params with optional values */
  307. export type ValuesFor<T extends For<any>> = Normalize<{ [k in keyof T]: T[k]['defaultValue'] }>
  308. type Optionals<P> = { [K in keyof P]-?: undefined extends P[K] ? K : never }[keyof P]
  309. type NonOptionals<P> = { [K in keyof P]-?: undefined extends P[K] ? never : K }[keyof P]
  310. export type Normalize<P> = Pick<P, NonOptionals<P>> & Partial<Pick<P, Optionals<P>>>
  311. export type For<P> = { [K in keyof P]-?: Base<P[K]> }
  312. export type Def<P> = { [K in keyof P]: Any }
  313. export function For<P>(params: For<P>): For<P> {
  314. return 0 as any;
  315. }
  316. export function getDefaultValues<T extends Params>(params: T) {
  317. const d: { [k: string]: any } = {};
  318. for (const k of Object.keys(params)) {
  319. if (params[k].isOptional) continue;
  320. d[k] = params[k].defaultValue;
  321. }
  322. return d as Values<T>;
  323. }
  324. function _resolveRef(resolve: (ref: string) => any, ref: string) {
  325. return () => resolve(ref);
  326. }
  327. function resolveRefValue(p: Any, value: any, getData: (ref: string) => any) {
  328. if (!value) return;
  329. if (p.type === 'value-ref') {
  330. const v = value as ValueRef['defaultValue'];
  331. if (!v.ref) v.getValue = () => { throw new Error('Unset ref in ValueRef value.'); };
  332. else v.getValue = _resolveRef(p.resolveRef, v.ref);
  333. } else if (p.type === 'data-ref') {
  334. const v = value as ValueRef['defaultValue'];
  335. if (!v.ref) v.getValue = () => { throw new Error('Unset ref in ValueRef value.'); };
  336. else v.getValue = _resolveRef(getData, v.ref);
  337. } else if (p.type === 'group') {
  338. resolveRefs(p.params, value, getData);
  339. } else if (p.type === 'mapped') {
  340. const v = value as NamedParams;
  341. const param = p.map(v.name);
  342. resolveRefValue(param, v.params, getData);
  343. } else if (p.type === 'object-list') {
  344. if (!hasValueRef(p.element)) return;
  345. for (const e of value) {
  346. resolveRefs(p.element, e, getData);
  347. }
  348. }
  349. }
  350. function hasParamValueRef(p: Any) {
  351. if (p.type === 'value-ref' || p.type === 'data-ref') {
  352. return true;
  353. } else if (p.type === 'group') {
  354. if (hasValueRef(p.params)) return true;
  355. } else if (p.type === 'mapped') {
  356. for (const [o] of p.select.options) {
  357. if (hasParamValueRef(p.map(o))) return true;
  358. }
  359. } else if (p.type === 'object-list') {
  360. return hasValueRef(p.element);
  361. }
  362. return false;
  363. }
  364. function hasValueRef(params: Params) {
  365. for (const n of Object.keys(params)) {
  366. if (hasParamValueRef(params[n])) return true;
  367. }
  368. return false;
  369. }
  370. export function resolveRefs(params: Params, values: any, getData: (ref: string) => any) {
  371. for (const n of Object.keys(params)) {
  372. resolveRefValue(params[n], values?.[n], getData);
  373. }
  374. }
  375. export function setDefaultValues<T extends Params>(params: T, defaultValues: Values<T>) {
  376. for (const k of Object.keys(params)) {
  377. if (params[k].isOptional) continue;
  378. params[k].defaultValue = defaultValues[k];
  379. }
  380. }
  381. export function clone<P extends Params>(params: P): P {
  382. return deepClone(params);
  383. }
  384. /**
  385. * List of [error text, pathToValue]
  386. * i.e. ['Missing Nested Id', ['group1', 'id']]
  387. */
  388. export type ParamErrors = [string, string | string[]][]
  389. export function validate(params: Params, values: any): ParamErrors | undefined {
  390. // TODO
  391. return void 0;
  392. }
  393. export function areEqual(params: Params, a: any, b: any): boolean {
  394. if (a === b) return true;
  395. if (typeof a !== 'object' || typeof b !== 'object') return false;
  396. for (const k of Object.keys(params)) {
  397. if (!isParamEqual(params[k], a[k], b[k])) return false;
  398. }
  399. return true;
  400. }
  401. export function isParamEqual(p: Any, a: any, b: any): boolean {
  402. if (a === b) return true;
  403. if (p.type === 'group') {
  404. return areEqual(p.params, a, b);
  405. } else if (p.type === 'mapped') {
  406. const u = a as NamedParams, v = b as NamedParams;
  407. if (u.name !== v.name) return false;
  408. const map = p.map(u.name);
  409. return isParamEqual(map, u.params, v.params);
  410. } else if (p.type === 'multi-select') {
  411. const u = a as MultiSelect<any>['defaultValue'], v = b as MultiSelect<any>['defaultValue'];
  412. if (u.length !== v.length) return false;
  413. if (u.length < 10) {
  414. for (let i = 0, _i = u.length; i < _i; i++) {
  415. if (u[i] === v[i]) continue;
  416. if (v.indexOf(u[i]) < 0) return false;
  417. }
  418. } else {
  419. // TODO: should the value of multiselect be a set?
  420. const vSet = new Set(v);
  421. for (let i = 0, _i = u.length; i < _i; i++) {
  422. if (u[i] === v[i]) continue;
  423. if (!vSet.has(u[i])) return false;
  424. }
  425. }
  426. return true;
  427. } else if (p.type === 'interval') {
  428. return a[0] === b[0] && a[1] === b[1];
  429. } else if (p.type === 'line-graph') {
  430. const u = a as LineGraph['defaultValue'], v = b as LineGraph['defaultValue'];
  431. if (u.length !== v.length) return false;
  432. for (let i = 0, _i = u.length; i < _i; i++) {
  433. if (!Vec2Data.areEqual(u[i], v[i])) return false;
  434. }
  435. return true;
  436. } else if (p.type === 'vec3') {
  437. return Vec3Data.equals(a, b);
  438. } else if (p.type === 'mat4') {
  439. return Mat4Data.areEqual(a, b, EPSILON);
  440. } else if (p.type === 'script') {
  441. const u = a as Script['defaultValue'], v = b as Script['defaultValue'];
  442. return u.language === v.language && u.expression === v.expression;
  443. } else if (p.type === 'object-list') {
  444. const u = a as ObjectList['defaultValue'], v = b as ObjectList['defaultValue'];
  445. const l = u.length;
  446. if (l !== v.length) return false;
  447. for (let i = 0; i < l; i++) {
  448. if (!areEqual(p.element, u[i], v[i])) return false;
  449. }
  450. return true;
  451. } else if (typeof a === 'object' && typeof b === 'object') {
  452. return shallowEqualObjects(a, b);
  453. }
  454. // a === b was checked at the top.
  455. return false;
  456. }
  457. export function merge<P extends Params>(params: P, a: any, b: any): Values<P> {
  458. if (a === undefined) return { ...b };
  459. if (b === undefined) return { ...a };
  460. const o = Object.create(null);
  461. for (const k of Object.keys(params)) {
  462. o[k] = mergeParam(params[k], a[k], b[k]);
  463. }
  464. return o;
  465. }
  466. export function mergeParam(p: Any, a: any, b: any): any {
  467. if (a === undefined) return typeof b === 'object' && !Array.isArray(b) ? { ...b } : b;
  468. if (b === undefined) return typeof a === 'object' && !Array.isArray(a) ? { ...a } : a;
  469. if (p.type === 'group') {
  470. return merge(p.params, a, b);
  471. } else if (p.type === 'mapped') {
  472. const u = a as NamedParams, v = b as NamedParams;
  473. if (u.name !== v.name) return { ...v };
  474. const map = p.map(v.name);
  475. return {
  476. name: v.name,
  477. params: mergeParam(map, u.params, v.params)
  478. };
  479. } else if (p.type === 'value') {
  480. return b;
  481. } else if (typeof a === 'object' && typeof b === 'object') {
  482. if (Array.isArray(b)) {
  483. return b;
  484. }
  485. return { ...a, ...b };
  486. } else {
  487. return b;
  488. }
  489. }
  490. function selectHasOption(p: Select<any> | MultiSelect<any>, v: any) {
  491. for (const o of p.options) {
  492. if (o[0] === v) return true;
  493. }
  494. return false;
  495. }
  496. function normalizeParam(p: Any, value: any, defaultIfUndefined: boolean): any {
  497. if (value === void 0 || value === null) {
  498. return defaultIfUndefined ? p.defaultValue : void 0;
  499. }
  500. // TODO: is this a good idea and will work well?
  501. // if (typeof p.defaultValue !== typeof value) {
  502. // return p.defaultValue;
  503. // }
  504. if (p.type === 'value') {
  505. return value;
  506. } else if (p.type === 'group') {
  507. const ret = Object.create(null);
  508. for (const key of Object.keys(p.params)) {
  509. const param = p.params[key];
  510. if (value[key] === void 0) {
  511. if (defaultIfUndefined) ret[key] = param.defaultValue;
  512. } else {
  513. ret[key] = normalizeParam(param, value[key], defaultIfUndefined);
  514. }
  515. }
  516. return ret;
  517. } else if (p.type === 'mapped') {
  518. const v = value as NamedParams;
  519. if (typeof v.name !== 'string') {
  520. return p.defaultValue;
  521. }
  522. if (typeof v.params === 'undefined') {
  523. return defaultIfUndefined ? p.defaultValue : void 0;
  524. }
  525. if (!selectHasOption(p.select, v.name)) {
  526. return p.defaultValue;
  527. }
  528. const param = p.map(v.name);
  529. return {
  530. name: v.name,
  531. params: normalizeParam(param, v.params, defaultIfUndefined)
  532. };
  533. } else if (p.type === 'select') {
  534. if (!selectHasOption(p, value)) return p.defaultValue;
  535. return value;
  536. } else if (p.type === 'multi-select') {
  537. if (!Array.isArray(value)) return p.defaultValue;
  538. const ret = value.filter(function (this: MultiSelect<any>, v: any) { return selectHasOption(this, v); }, p);
  539. if (value.length > 0 && ret.length === 0) return p.defaultValue;
  540. return ret;
  541. } else if (p.type === 'object-list') {
  542. if (!Array.isArray(value)) return p.defaultValue;
  543. return value.map(v => normalizeParams(p.element, v, defaultIfUndefined ? 'all' : 'skip'));
  544. }
  545. // TODO: validate/normalize all param types "properly"??
  546. return value;
  547. }
  548. export function normalizeParams(p: Params, value: any, defaultIfUndefined: 'all' | 'children' | 'skip') {
  549. if (typeof value !== 'object' || value === null) {
  550. return defaultIfUndefined ? getDefaultValues(p) : value;
  551. }
  552. const ret = Object.create(null);
  553. for (const key of Object.keys(p)) {
  554. const param = p[key];
  555. if (value[key] === void 0) {
  556. if (defaultIfUndefined === 'all') ret[key] = param.defaultValue;
  557. } else {
  558. ret[key] = normalizeParam(param, value[key], defaultIfUndefined !== 'skip');
  559. }
  560. }
  561. return ret;
  562. }
  563. /**
  564. * Map an object to a list of [K, string][] to be used as options, stringToWords for key used by default (or identity of null).
  565. *
  566. * if options is { [string]: string } and mapping is not provided, use the Value.
  567. */
  568. export function objectToOptions<K extends string, V>(options: { [k in K]: V }, f?: null | ((k: K, v: V) => string | [string, string])): [K, string][] {
  569. const ret: ([K, string] | [K, string, string])[] = [];
  570. for (const k of Object.keys(options) as K[]) {
  571. if (!f) {
  572. if (typeof options[k as K] === 'string') ret.push([k as K, options[k as K] as any]);
  573. else ret.push([k as K, f === null ? k : stringToWords(k)]);
  574. } else {
  575. const o = f(k as K, options[k as K]);
  576. ret.push(typeof o === 'string' ? [k, o] : [k, o[0], o[1]]);
  577. }
  578. }
  579. return ret as [K, string][];
  580. }
  581. /**
  582. * Map array of options using stringToWords by default (or identity of null).
  583. */
  584. export function arrayToOptions<V extends string>(xs: readonly V[], f?: null | ((v: V) => string)): [V, string][] {
  585. const ret: [V, string][] = [];
  586. for (const x of xs) {
  587. if (!f) {
  588. ret.push([x, f === null ? x : stringToWords(x)]);
  589. } else {
  590. ret.push([x, f(x)]);
  591. }
  592. }
  593. return ret;
  594. }
  595. export function optionLabel<T>(param: Select<T>, value: T) {
  596. for (const o of param.options) {
  597. if (o[0] === value) return o[1];
  598. }
  599. return '';
  600. }
  601. function checkDefaultKey<T>(k: T, options: readonly (readonly [T, string] | readonly [T, string, string | undefined])[]) {
  602. for (const o of options) {
  603. if (o[0] === k) return k;
  604. }
  605. return options.length > 0 ? options[0][0] : void 0 as any as T;
  606. }
  607. }