param-definition.ts 21 KB

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