param-definition.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  1. /**
  2. * Copyright (c) 2018 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 } 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. export namespace ParamDefinition {
  15. export interface Info {
  16. label?: string,
  17. description?: string,
  18. legend?: Legend,
  19. fieldLabels?: { [name: string]: string },
  20. isHidden?: boolean,
  21. shortLabel?: boolean,
  22. twoColumns?: boolean,
  23. isEssential?: boolean,
  24. category?: string,
  25. hideIf?: (currentGroup: any) => boolean,
  26. help?: (value: any) => { description?: string, legend?: Legend }
  27. }
  28. export const Essential = { isEssential: true };
  29. function setInfo<T extends Base<any>>(param: T, info?: Info): T {
  30. if (!info) return param;
  31. if (info.label) param.label = info.label;
  32. if (info.description) param.description = info.description;
  33. if (info.legend) param.legend = info.legend;
  34. if (info.fieldLabels) param.fieldLabels = info.fieldLabels;
  35. if (info.isHidden) param.isHidden = info.isHidden;
  36. if (info.shortLabel) param.shortLabel = info.shortLabel;
  37. if (info.twoColumns) param.twoColumns = info.twoColumns;
  38. if (info.isEssential) param.isEssential = info.isEssential;
  39. if (info.category) param.category = info.category;
  40. if (info.hideIf) param.hideIf = info.hideIf;
  41. if (info.help) param.help = info.help;
  42. return param;
  43. }
  44. export interface Base<T> extends Info {
  45. isOptional?: boolean,
  46. defaultValue: T
  47. }
  48. export interface Optional<T extends Any = Any> extends Base<T['defaultValue'] | undefined> {
  49. type: T['type']
  50. }
  51. export function Optional<T>(p: Base<T>): Base<T | undefined> {
  52. const ret = { ...p };
  53. ret.isOptional = true;
  54. return ret;
  55. }
  56. export interface Value<T> extends Base<T> {
  57. type: 'value'
  58. }
  59. export function Value<T>(defaultValue: T, info?: Info): Value<T> {
  60. return setInfo<Value<T>>({ type: 'value', defaultValue }, info);
  61. }
  62. export interface Select<T> extends Base<T> {
  63. type: 'select'
  64. /** array of (value, label) tuples */
  65. options: readonly (readonly [T, string] | readonly [T, string, string])[]
  66. cycle?: boolean
  67. }
  68. export function Select<T>(defaultValue: T, options: readonly (readonly [T, string] | readonly [T, string, string])[], info?: Info & { cycle?: boolean }): Select<T> {
  69. return setInfo<Select<T>>({ type: 'select', defaultValue: checkDefaultKey(defaultValue, options), options, cycle: info?.cycle }, info)
  70. }
  71. export interface ColorList<T extends string> extends Base<T> {
  72. type: 'color-list'
  73. /** array of (value, label) tuples */
  74. options: [T, string][]
  75. }
  76. export function ColorList<T extends string>(defaultValue: T, options: [T, string][], info?: Info): ColorList<T> {
  77. return setInfo<ColorList<T>>({ type: 'color-list', defaultValue, options }, info)
  78. }
  79. export interface MultiSelect<E extends string, T = E[]> extends Base<T> {
  80. type: 'multi-select'
  81. /** array of (value, label) tuples */
  82. options: readonly (readonly [E, string])[],
  83. emptyValue?: string
  84. }
  85. export function MultiSelect<E extends string, T = E[]>(defaultValue: T, options: readonly (readonly [E, string])[], info?: Info & { emptyValue?: string }): MultiSelect<E, T> {
  86. // TODO: check if default value is a subset of options?
  87. const ret = setInfo<MultiSelect<E, T>>({ type: 'multi-select', defaultValue, options }, info);
  88. if (info?.emptyValue) ret.emptyValue = info.emptyValue;
  89. return ret;
  90. }
  91. export interface BooleanParam extends Base<boolean> {
  92. type: 'boolean'
  93. }
  94. export function Boolean(defaultValue: boolean, info?: Info): BooleanParam {
  95. return setInfo<BooleanParam>({ type: 'boolean', defaultValue }, info)
  96. }
  97. export interface Text<T extends string = string> extends Base<T> {
  98. type: 'text'
  99. }
  100. export function Text<T extends string = string>(defaultValue: string = '', info?: Info): Text<T> {
  101. return setInfo<Text<T>>({ type: 'text', defaultValue: defaultValue as any }, info)
  102. }
  103. export interface Color extends Base<ColorData> {
  104. type: 'color'
  105. isExpanded?: boolean
  106. }
  107. export function Color(defaultValue: ColorData, info?: Info & { isExpanded?: boolean }): Color {
  108. const ret = setInfo<Color>({ type: 'color', defaultValue }, info);
  109. if (info?.isExpanded) ret.isExpanded = info.isExpanded;
  110. return ret;
  111. }
  112. export interface Vec3 extends Base<Vec3Data>, Range {
  113. type: 'vec3'
  114. }
  115. export function Vec3(defaultValue: Vec3Data, range?: { min?: number, max?: number, step?: number }, info?: Info): Vec3 {
  116. return setInfo<Vec3>(setRange({ type: 'vec3', defaultValue }, range), info)
  117. }
  118. export interface FileParam extends Base<File> {
  119. type: 'file'
  120. accept?: string
  121. }
  122. export function File(info?: Info & { accept?: string, multiple?: boolean }): FileParam {
  123. const ret = setInfo<FileParam>({ type: 'file', defaultValue: void 0 as any }, info);
  124. if (info?.accept) ret.accept = info.accept;
  125. return ret;
  126. }
  127. export interface FileListParam extends Base<FileList> {
  128. type: 'file-list'
  129. accept?: string
  130. }
  131. export function FileList(info?: Info & { accept?: string, multiple?: boolean }): FileListParam {
  132. const ret = setInfo<FileListParam>({ type: 'file-list', defaultValue: void 0 as any }, info);
  133. if (info?.accept) ret.accept = info.accept;
  134. return ret;
  135. }
  136. export interface Range {
  137. /** If given treat as a range. */
  138. min?: number
  139. /** If given treat as a range. */
  140. max?: number
  141. /**
  142. * If given treat as a range.
  143. * If an `integer` parse value with parseInt, otherwise use parseFloat.
  144. */
  145. step?: number
  146. }
  147. function setRange<T extends Numeric | Interval | Vec3>(p: T, range?: { min?: number, max?: number, step?: number }) {
  148. if (!range) return p;
  149. if (typeof range.min !== 'undefined') p.min = range.min;
  150. if (typeof range.max !== 'undefined') p.max = range.max;
  151. if (typeof range.step !== 'undefined') p.step = range.step;
  152. return p;
  153. }
  154. export interface Numeric extends Base<number>, Range {
  155. type: 'number'
  156. }
  157. export function Numeric(defaultValue: number, range?: { min?: number, max?: number, step?: number }, info?: Info): Numeric {
  158. return setInfo<Numeric>(setRange({ type: 'number', defaultValue }, range), info)
  159. }
  160. export interface Interval extends Base<[number, number]>, Range {
  161. type: 'interval'
  162. }
  163. export function Interval(defaultValue: [number, number], range?: { min?: number, max?: number, step?: number }, info?: Info): Interval {
  164. return setInfo<Interval>(setRange({ type: 'interval', defaultValue }, range), info)
  165. }
  166. export interface LineGraph extends Base<Vec2Data[]> {
  167. type: 'line-graph'
  168. }
  169. export function LineGraph(defaultValue: Vec2Data[], info?: Info): LineGraph {
  170. return setInfo<LineGraph>({ type: 'line-graph', defaultValue }, info)
  171. }
  172. export interface Group<T> extends Base<T> {
  173. type: 'group',
  174. params: Params,
  175. isExpanded?: boolean,
  176. isFlat?: boolean,
  177. pivot?: keyof T
  178. }
  179. export function Group<T>(params: For<T>, info?: Info & { isExpanded?: boolean, isFlat?: boolean, customDefault?: any, pivot?: keyof T }): Group<Normalize<T>> {
  180. 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);
  181. if (info?.isExpanded) ret.isExpanded = info.isExpanded;
  182. if (info?.isFlat) ret.isFlat = info.isFlat;
  183. if (info?.pivot) ret.pivot = info.pivot as any;
  184. return ret;
  185. }
  186. export function EmptyGroup(info?: Info) {
  187. return Group({}, info);
  188. }
  189. export interface NamedParams<T = any, K = string> { name: K, params: T }
  190. export type NamedParamUnion<P extends Params, K extends keyof P = keyof P> = K extends any ? NamedParams<P[K]['defaultValue'], K> : never
  191. export interface Mapped<T extends NamedParams<any, any>> extends Base<T> {
  192. type: 'mapped',
  193. select: Select<string>,
  194. map(name: string): Any
  195. }
  196. export function Mapped<T>(defaultKey: string, names: ([string, string] | [string, string, string])[], map: (name: string) => Any, info?: Info & { cycle?: boolean }): Mapped<NamedParams<T>> {
  197. const name = checkDefaultKey(defaultKey, names);
  198. return setInfo<Mapped<NamedParams<T>>>({
  199. type: 'mapped',
  200. defaultValue: { name, params: map(name).defaultValue as any },
  201. select: Select<string>(name, names, info),
  202. map
  203. }, info);
  204. }
  205. export function MappedStatic<C extends Params>(defaultKey: keyof C, map: C, info?: Info & { options?: [keyof C, string][], cycle?: boolean }): Mapped<NamedParamUnion<C>> {
  206. const options: [string, string][] = info?.options
  207. ? info.options as [string, string][]
  208. : Object.keys(map).map(k => [k, map[k].label || stringToWords(k)]) as [string, string][];
  209. const name = checkDefaultKey(defaultKey, options);
  210. return setInfo<Mapped<NamedParamUnion<C>>>({
  211. type: 'mapped',
  212. defaultValue: { name, params: map[name].defaultValue } as any,
  213. select: Select<string>(name as string, options, info),
  214. map: key => map[key]
  215. }, info);
  216. }
  217. export interface ObjectList<T = any> extends Base<T[]> {
  218. type: 'object-list',
  219. element: Params,
  220. ctor(): T,
  221. getLabel(t: T): string
  222. }
  223. export function ObjectList<T>(element: For<T>, getLabel: (e: T) => string, info?: Info & { defaultValue?: T[], ctor?: () => T }): ObjectList<Normalize<T>> {
  224. return setInfo<ObjectList<Normalize<T>>>({ type: 'object-list', element: element as any as Params, getLabel, ctor: _defaultObjectListCtor, defaultValue: (info?.defaultValue) || [] }, info);
  225. }
  226. function _defaultObjectListCtor(this: ObjectList) { return getDefaultValues(this.element) as any; }
  227. export interface Converted<T, C> extends Base<T> {
  228. type: 'converted',
  229. converted: Any,
  230. /** converts from prop value to display value */
  231. fromValue(v: T): C,
  232. /** converts from display value to prop value */
  233. toValue(v: C): T
  234. }
  235. export function Converted<T, C extends Any>(fromValue: (v: T) => C['defaultValue'], toValue: (v: C['defaultValue']) => T, converted: C): Converted<T, C['defaultValue']> {
  236. return { type: 'converted', defaultValue: toValue(converted.defaultValue), converted, fromValue, toValue };
  237. }
  238. export interface Conditioned<T, P extends Base<T>, C = { [k: string]: P }> extends Base<T> {
  239. type: 'conditioned',
  240. select: Select<string>,
  241. conditionParams: C
  242. conditionForValue(v: T): keyof C
  243. conditionedValue(v: T, condition: keyof C): T,
  244. }
  245. 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): Conditioned<T, P, C> {
  246. const options = Object.keys(conditionParams).map(k => [k, k]) as [string, string][];
  247. return { type: 'conditioned', select: Select<string>(conditionForValue(defaultValue) as string, options), defaultValue, conditionParams, conditionForValue, conditionedValue };
  248. }
  249. export interface Script extends Base<ScriptData> {
  250. type: 'script'
  251. }
  252. export function Script(defaultValue: Script['defaultValue'], info?: Info): Script {
  253. return setInfo<Script>({ type: 'script', defaultValue }, info)
  254. }
  255. export type Any =
  256. | Value<any> | Select<any> | MultiSelect<any> | BooleanParam | Text | Color | Vec3 | Numeric | FileParam | FileListParam | Interval | LineGraph
  257. | ColorList<any> | Group<any> | Mapped<any> | Converted<any, any> | Conditioned<any, any, any> | Script | ObjectList
  258. export type Params = { [k: string]: Any }
  259. export type Values<T extends Params> = { [k in keyof T]: T[k]['defaultValue'] }
  260. /** This is required for params with optional values */
  261. export type ValuesFor<T extends For<any>> = Normalize<{ [k in keyof T]: T[k]['defaultValue'] }>
  262. type Optionals<P> = { [K in keyof P]-?: undefined extends P[K] ? K : never }[keyof P]
  263. type NonOptionals<P> = { [K in keyof P]-?: undefined extends P[K] ? never: K }[keyof P]
  264. export type Normalize<P> = Pick<P, NonOptionals<P>> & Partial<Pick<P, Optionals<P>>>
  265. export type For<P> = { [K in keyof P]-?: Base<P[K]> }
  266. export type Def<P> = { [K in keyof P]: Any }
  267. export function For<P>(params: For<P>): For<P> {
  268. return 0 as any;
  269. }
  270. export function getDefaultValues<T extends Params>(params: T) {
  271. const d: { [k: string]: any } = {}
  272. for (const k of Object.keys(params)) {
  273. if (params[k].isOptional) continue;
  274. d[k] = params[k].defaultValue;
  275. }
  276. return d as Values<T>;
  277. }
  278. export function clone<P extends Params>(params: P): P {
  279. return deepClone(params)
  280. }
  281. /**
  282. * List of [error text, pathToValue]
  283. * i.e. ['Missing Nested Id', ['group1', 'id']]
  284. */
  285. export type ParamErrors = [string, string | string[]][]
  286. export function validate(params: Params, values: any): ParamErrors | undefined {
  287. // TODO
  288. return void 0;
  289. }
  290. export function areEqual(params: Params, a: any, b: any): boolean {
  291. if (a === b) return true;
  292. if (!a) return !b;
  293. if (!b) return !a;
  294. if (typeof a !== 'object' || typeof b !== 'object') return false;
  295. for (const k of Object.keys(params)) {
  296. if (!isParamEqual(params[k], a[k], b[k])) return false;
  297. }
  298. return true;
  299. }
  300. export function isParamEqual(p: Any, a: any, b: any): boolean {
  301. if (a === b) return true;
  302. if (!a) return !b;
  303. if (!b) return !a;
  304. if (p.type === 'group') {
  305. return areEqual(p.params, a, b);
  306. } else if (p.type === 'mapped') {
  307. const u = a as NamedParams, v = b as NamedParams;
  308. if (u.name !== v.name) return false;
  309. const map = p.map(u.name);
  310. return isParamEqual(map, u.params, v.params);
  311. } else if (p.type === 'multi-select') {
  312. const u = a as MultiSelect<any>['defaultValue'], v = b as MultiSelect<any>['defaultValue'];
  313. if (u.length !== v.length) return false;
  314. if (u.length < 10) {
  315. for (let i = 0, _i = u.length; i < _i; i++) {
  316. if (u[i] === v[i]) continue;
  317. if (v.indexOf(u[i]) < 0) return false;
  318. }
  319. } else {
  320. // TODO: should the value of multiselect be a set?
  321. const vSet = new Set(v);
  322. for (let i = 0, _i = u.length; i < _i; i++) {
  323. if (u[i] === v[i]) continue;
  324. if (!vSet.has(u[i])) return false;
  325. }
  326. }
  327. return true;
  328. } else if (p.type === 'interval') {
  329. return a[0] === b[0] && a[1] === b[1];
  330. } else if (p.type === 'line-graph') {
  331. const u = a as LineGraph['defaultValue'], v = b as LineGraph['defaultValue'];
  332. if (u.length !== v.length) return false;
  333. for (let i = 0, _i = u.length; i < _i; i++) {
  334. if (!Vec2Data.areEqual(u[i], v[i])) return false;
  335. }
  336. return true;
  337. } else if (p.type === 'vec3') {
  338. return Vec3Data.equals(a, b);
  339. } else if (p.type === 'script') {
  340. const u = a as Script['defaultValue'], v = b as Script['defaultValue'];
  341. return u.language === v.language && u.expression === v.expression;
  342. } else if (p.type === 'object-list') {
  343. const u = a as ObjectList['defaultValue'], v = b as ObjectList['defaultValue'];
  344. const l = u.length;
  345. if (l !== v.length) return false;
  346. for (let i = 0; i < l; i++) {
  347. if (!areEqual(p.element, u[i], v[i])) return false;
  348. }
  349. return true;
  350. } else if (typeof a === 'object' && typeof b === 'object') {
  351. return shallowEqualObjects(a, b);
  352. }
  353. // a === b was checked at the top.
  354. return false;
  355. }
  356. export function merge(params: Params, a: any, b: any): any {
  357. if (a === undefined) return { ...b };
  358. if (b === undefined) return { ...a };
  359. const o = Object.create(null)
  360. for (const k of Object.keys(params)) {
  361. o[k] = mergeParam(params[k], a[k], b[k])
  362. }
  363. return o;
  364. }
  365. export function mergeParam(p: Any, a: any, b: any): any {
  366. if (a === undefined) return typeof b === 'object' ? { ...b } : b;
  367. if (b === undefined) return typeof a === 'object' ? { ...a } : a;
  368. if (p.type === 'group') {
  369. return merge(p.params, a, b);
  370. } else if (p.type === 'mapped') {
  371. const u = a as NamedParams, v = b as NamedParams;
  372. if (u.name !== v.name) return { ...v };
  373. const map = p.map(v.name);
  374. return {
  375. name: v.name,
  376. params: mergeParam(map, u.params, v.params)
  377. };
  378. } else if (typeof a === 'object' && typeof b === 'object') {
  379. return { ...a, ...b };
  380. } else {
  381. return b
  382. }
  383. }
  384. /**
  385. * Map an object to a list of [K, string][] to be used as options, stringToWords for key used by default (or identity of null).
  386. *
  387. * if options is { [string]: string } and mapping is not provided, use the Value.
  388. */
  389. export function objectToOptions<K extends string, V>(options: { [k in K]: V }, f?: null | ((k: K, v: V) => string)): [K, string][] {
  390. const ret: [K, string][] = [];
  391. for (const k of Object.keys(options) as K[]) {
  392. if (!f) {
  393. if (typeof options[k as K] === 'string') ret.push([k as K, options[k as K] as any]);
  394. else ret.push([k as K, f === null ? k : stringToWords(k)]);
  395. } else {
  396. ret.push([k, f(k as K, options[k as K])])
  397. }
  398. }
  399. return ret;
  400. }
  401. /**
  402. * Map array of options using stringToWords by default (or identity of null).
  403. */
  404. export function arrayToOptions<V extends string>(xs: readonly V[], f?: null | ((v: V) => string)): [V, string][] {
  405. const ret: [V, string][] = [];
  406. for (const x of xs) {
  407. if (!f) {
  408. ret.push([x, f === null ? x : stringToWords(x)]);
  409. } else {
  410. ret.push([x, f(x)])
  411. }
  412. }
  413. return ret;
  414. }
  415. function checkDefaultKey<T>(k: T, options: readonly (readonly [T, string] | readonly [T, string, string])[]) {
  416. for (const o of options) {
  417. if (o[0] === k) return k;
  418. }
  419. return options.length > 0 ? options[0][0] : void 0 as any as T;
  420. }
  421. }