param-definition.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 { shallowEqual } 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. export namespace ParamDefinition {
  14. export interface Info {
  15. label?: string,
  16. description?: string,
  17. legend?: Legend,
  18. fieldLabels?: { [name: string]: string },
  19. isHidden?: boolean,
  20. shortLabel?: boolean,
  21. twoColumns?: boolean,
  22. help?: (value: any) => { description?: string, legend?: Legend }
  23. }
  24. function setInfo<T extends Info>(param: T, info?: Info): T {
  25. if (!info) return param;
  26. if (info.label) param.label = info.label;
  27. if (info.description) param.description = info.description;
  28. if (info.legend) param.legend = info.legend;
  29. if (info.fieldLabels) param.fieldLabels = info.fieldLabels;
  30. if (info.isHidden) param.isHidden = info.isHidden;
  31. if (info.shortLabel) param.shortLabel = info.shortLabel;
  32. if (info.twoColumns) param.twoColumns = info.twoColumns;
  33. if (info.help) param.help = info.help;
  34. return param;
  35. }
  36. export interface Base<T> extends Info {
  37. isOptional?: boolean,
  38. defaultValue: T
  39. }
  40. export interface Optional<T extends Any = Any> extends Base<T['defaultValue'] | undefined> {
  41. type: T['type']
  42. }
  43. export function Optional<T>(p: Base<T>): Base<T | undefined> {
  44. const ret = { ...p };
  45. ret.isOptional = true;
  46. return ret;
  47. }
  48. export interface Value<T> extends Base<T> {
  49. type: 'value'
  50. }
  51. export function Value<T>(defaultValue: T, info?: Info): Value<T> {
  52. return setInfo<Value<T>>({ type: 'value', defaultValue }, info);
  53. }
  54. export interface Select<T extends string | number> extends Base<T> {
  55. type: 'select'
  56. /** array of (value, label) tuples */
  57. options: [T, string][]
  58. }
  59. export function Select<T extends string | number>(defaultValue: T, options: [T, string][], info?: Info): Select<T> {
  60. return setInfo<Select<T>>({ type: 'select', defaultValue, options }, info)
  61. }
  62. export interface ColorList<T extends string> extends Base<T> {
  63. type: 'color-list'
  64. /** array of (value, label) tuples */
  65. options: [T, string][]
  66. }
  67. export function ColorList<T extends string>(defaultValue: T, options: [T, string][], info?: Info): ColorList<T> {
  68. return setInfo<ColorList<T>>({ type: 'color-list', defaultValue, options }, info)
  69. }
  70. export interface MultiSelect<E extends string, T = E[]> extends Base<T> {
  71. type: 'multi-select'
  72. /** array of (value, label) tuples */
  73. options: [E, string][]
  74. }
  75. export function MultiSelect<E extends string, T = E[]>(defaultValue: T, options: [E, string][], info?: Info): MultiSelect<E, T> {
  76. return setInfo<MultiSelect<E, T>>({ type: 'multi-select', defaultValue, options }, info)
  77. }
  78. export interface BooleanParam extends Base<boolean> {
  79. type: 'boolean'
  80. }
  81. export function Boolean(defaultValue: boolean, info?: Info): BooleanParam {
  82. return setInfo<BooleanParam>({ type: 'boolean', defaultValue }, info)
  83. }
  84. export interface Text<T extends string = string> extends Base<T> {
  85. type: 'text'
  86. }
  87. export function Text<T extends string = string>(defaultValue: string = '', info?: Info): Text<T> {
  88. return setInfo<Text<T>>({ type: 'text', defaultValue: defaultValue as any }, info)
  89. }
  90. export interface Color extends Base<ColorData> {
  91. type: 'color'
  92. }
  93. export function Color(defaultValue: ColorData, info?: Info): Color {
  94. return setInfo<Color>({ type: 'color', defaultValue }, info)
  95. }
  96. export interface Vec3 extends Base<Vec3Data> {
  97. type: 'vec3'
  98. }
  99. export function Vec3(defaultValue: Vec3Data, info?: Info): Vec3 {
  100. return setInfo<Vec3>({ type: 'vec3', defaultValue }, info)
  101. }
  102. export interface FileParam extends Base<File> {
  103. type: 'file',
  104. accept?: string
  105. }
  106. export function File(info?: Info & { accept?: string }): FileParam {
  107. const ret = setInfo<FileParam>({ type: 'file', defaultValue: void 0 as any }, info);
  108. if (info && info.accept) ret.accept = info.accept;
  109. return ret;
  110. }
  111. export interface Range {
  112. /** If given treat as a range. */
  113. min?: number
  114. /** If given treat as a range. */
  115. max?: number
  116. /**
  117. * If given treat as a range.
  118. * If an `integer` parse value with parseInt, otherwise use parseFloat.
  119. */
  120. step?: number
  121. }
  122. function setRange<T extends Numeric | Interval>(p: T, range?: { min?: number, max?: number, step?: number }) {
  123. if (!range) return p;
  124. if (typeof range.min !== 'undefined') p.min = range.min;
  125. if (typeof range.max !== 'undefined') p.max = range.max;
  126. if (typeof range.step !== 'undefined') p.step = range.step;
  127. return p;
  128. }
  129. export interface Numeric extends Base<number>, Range {
  130. type: 'number'
  131. }
  132. export function Numeric(defaultValue: number, range?: { min?: number, max?: number, step?: number }, info?: Info): Numeric {
  133. return setInfo<Numeric>(setRange({ type: 'number', defaultValue }, range), info)
  134. }
  135. export interface Interval extends Base<[number, number]>, Range {
  136. type: 'interval'
  137. }
  138. export function Interval(defaultValue: [number, number], range?: { min?: number, max?: number, step?: number }, info?: Info): Interval {
  139. return setInfo<Interval>(setRange({ type: 'interval', defaultValue }, range), info)
  140. }
  141. export interface LineGraph extends Base<Vec2Data[]> {
  142. type: 'line-graph'
  143. }
  144. export function LineGraph(defaultValue: Vec2Data[], info?: Info): LineGraph {
  145. return setInfo<LineGraph>({ type: 'line-graph', defaultValue }, info)
  146. }
  147. export interface Group<T> extends Base<T> {
  148. type: 'group',
  149. params: Params,
  150. isExpanded?: boolean,
  151. isFlat?: boolean
  152. }
  153. export function Group<T>(params: For<T>, info?: Info & { isExpanded?: boolean, isFlat?: boolean }): Group<Normalize<T>> {
  154. const ret = setInfo<Group<Normalize<T>>>({ type: 'group', defaultValue: getDefaultValues(params as any as Params) as any, params: params as any as Params }, info);
  155. if (info && info.isExpanded) ret.isExpanded = info.isExpanded;
  156. if (info && info.isFlat) ret.isFlat = info.isFlat;
  157. return ret;
  158. }
  159. export interface NamedParams<T = any, K = string> { name: K, params: T }
  160. export type NamedParamUnion<P extends Params, K extends keyof P = keyof P> = K extends any ? NamedParams<P[K]['defaultValue'], K> : never
  161. export interface Mapped<T extends NamedParams<any, any>> extends Base<T> {
  162. type: 'mapped',
  163. select: Select<string>,
  164. map(name: string): Any
  165. }
  166. export function Mapped<T>(defaultKey: string, names: [string, string][], map: (name: string) => Any, info?: Info): Mapped<NamedParams<T>> {
  167. return setInfo<Mapped<NamedParams<T>>>({
  168. type: 'mapped',
  169. defaultValue: { name: defaultKey, params: map(defaultKey).defaultValue as any },
  170. select: Select<string>(defaultKey, names, info),
  171. map
  172. }, info);
  173. }
  174. export function MappedStatic<C extends Params>(defaultKey: keyof C, map: C, info?: Info & { options?: [keyof C, string][] }): Mapped<NamedParamUnion<C>> {
  175. const options: [string, string][] = info && info.options
  176. ? info.options as [string, string][]
  177. : Object.keys(map).map(k => [k, k]) as [string, string][];
  178. return setInfo<Mapped<NamedParamUnion<C>>>({
  179. type: 'mapped',
  180. defaultValue: { name: defaultKey, params: map[defaultKey].defaultValue } as any,
  181. select: Select<string>(defaultKey as string, options, info),
  182. map: key => map[key]
  183. }, info);
  184. }
  185. export interface ObjectList<T = any> extends Base<T[]> {
  186. type: 'object-list',
  187. element: Params,
  188. ctor(): T,
  189. getLabel(t: T): string
  190. }
  191. export function ObjectList<T>(element: For<T>, getLabel: (e: T) => string, info?: Info & { defaultValue?: T[], ctor?: () => T }): ObjectList<Normalize<T>> {
  192. return setInfo<ObjectList<Normalize<T>>>({ type: 'object-list', element: element as any as Params, getLabel, ctor: _defaultObjectListCtor, defaultValue: (info && info.defaultValue) || [] }, info);
  193. }
  194. function _defaultObjectListCtor(this: ObjectList) { return getDefaultValues(this.element) as any; }
  195. export interface Converted<T, C> extends Base<T> {
  196. type: 'converted',
  197. converted: Any,
  198. /** converts from prop value to display value */
  199. fromValue(v: T): C,
  200. /** converts from display value to prop value */
  201. toValue(v: C): T
  202. }
  203. export function Converted<T, C extends Any>(fromValue: (v: T) => C['defaultValue'], toValue: (v: C['defaultValue']) => T, converted: C): Converted<T, C['defaultValue']> {
  204. return { type: 'converted', defaultValue: toValue(converted.defaultValue), converted, fromValue, toValue };
  205. }
  206. export interface Conditioned<T, P extends Base<T>, C = { [k: string]: P }> extends Base<T> {
  207. type: 'conditioned',
  208. select: Select<string>,
  209. conditionParams: C
  210. conditionForValue(v: T): keyof C
  211. conditionedValue(v: T, condition: keyof C): T,
  212. }
  213. 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> {
  214. const options = Object.keys(conditionParams).map(k => [k, k]) as [string, string][];
  215. return { type: 'conditioned', select: Select<string>(conditionForValue(defaultValue) as string, options), defaultValue, conditionParams, conditionForValue, conditionedValue };
  216. }
  217. export interface Script extends Base<ScriptData> {
  218. type: 'script'
  219. }
  220. export function Script(defaultValue: Script['defaultValue'], info?: Info): Script {
  221. return setInfo<Script>({ type: 'script', defaultValue }, info)
  222. }
  223. export type Any =
  224. | Value<any> | Select<any> | MultiSelect<any> | BooleanParam | Text | Color | Vec3 | Numeric | FileParam | Interval | LineGraph
  225. | ColorList<any> | Group<any> | Mapped<any> | Converted<any, any> | Conditioned<any, any, any> | Script | ObjectList
  226. export type Params = { [k: string]: Any }
  227. export type Values<T extends Params> = { [k in keyof T]: T[k]['defaultValue'] }
  228. type Optionals<P> = { [K in keyof P]-?: undefined extends P[K] ? K : never }[keyof P]
  229. type NonOptionals<P> = { [K in keyof P]-?: undefined extends P[K] ? never: K }[keyof P]
  230. export type Normalize<P> = Pick<P, NonOptionals<P>> & Partial<Pick<P, Optionals<P>>>
  231. export type For<P> = { [K in keyof P]-?: Base<P[K]> }
  232. export function getDefaultValues<T extends Params>(params: T) {
  233. const d: { [k: string]: any } = {}
  234. for (const k of Object.keys(params)) {
  235. if (params[k].isOptional) continue;
  236. d[k] = params[k].defaultValue;
  237. }
  238. return d as Values<T>;
  239. }
  240. export function clone<P extends Params>(params: P): P {
  241. return deepClone(params)
  242. }
  243. /**
  244. * List of [error text, pathToValue]
  245. * i.e. ['Missing Nested Id', ['group1', 'id']]
  246. */
  247. export type ParamErrors = [string, string | string[]][]
  248. export function validate(params: Params, values: any): ParamErrors | undefined {
  249. // TODO
  250. return void 0;
  251. }
  252. export function areEqual(params: Params, a: any, b: any): boolean {
  253. if (a === b) return true;
  254. if (!a) return !b;
  255. if (!b) return !a;
  256. if (typeof a !== 'object' || typeof b !== 'object') return false;
  257. for (const k of Object.keys(params)) {
  258. if (!isParamEqual(params[k], a[k], b[k])) return false;
  259. }
  260. return true;
  261. }
  262. export function isParamEqual(p: Any, a: any, b: any): boolean {
  263. if (a === b) return true;
  264. if (!a) return !b;
  265. if (!b) return !a;
  266. if (p.type === 'group') {
  267. return areEqual(p.params, a, b);
  268. } else if (p.type === 'mapped') {
  269. const u = a as NamedParams, v = b as NamedParams;
  270. if (u.name !== v.name) return false;
  271. const map = p.map(u.name);
  272. return isParamEqual(map, u.params, v.params);
  273. } else if (p.type === 'multi-select') {
  274. const u = a as MultiSelect<any>['defaultValue'], v = b as MultiSelect<any>['defaultValue'];
  275. if (u.length !== v.length) return false;
  276. if (u.length < 10) {
  277. for (let i = 0, _i = u.length; i < _i; i++) {
  278. if (u[i] === v[i]) continue;
  279. if (v.indexOf(u[i]) < 0) return false;
  280. }
  281. } else {
  282. // TODO: should the value of multiselect be a set?
  283. const vSet = new Set(v);
  284. for (let i = 0, _i = u.length; i < _i; i++) {
  285. if (u[i] === v[i]) continue;
  286. if (!vSet.has(u[i])) return false;
  287. }
  288. }
  289. return true;
  290. } else if (p.type === 'interval') {
  291. return a[0] === b[0] && a[1] === b[1];
  292. } else if (p.type === 'line-graph') {
  293. const u = a as LineGraph['defaultValue'], v = b as LineGraph['defaultValue'];
  294. if (u.length !== v.length) return false;
  295. for (let i = 0, _i = u.length; i < _i; i++) {
  296. if (!Vec2Data.areEqual(u[i], v[i])) return false;
  297. }
  298. return true;
  299. } else if (p.type === 'vec3') {
  300. return Vec3Data.equals(a, b);
  301. } else if (p.type === 'script') {
  302. const u = a as Script['defaultValue'], v = b as Script['defaultValue'];
  303. return u.language === v.language && u.expression === v.expression;
  304. } else if (p.type === 'object-list') {
  305. const u = a as ObjectList['defaultValue'], v = b as ObjectList['defaultValue'];
  306. const l = u.length;
  307. if (l !== v.length) return false;
  308. for (let i = 0; i < l; i++) {
  309. if (!areEqual(p.element, u[i], v[i])) return false;
  310. }
  311. return true;
  312. } else if (typeof a === 'object' && typeof b === 'object') {
  313. return shallowEqual(a, b);
  314. }
  315. // a === b was checked at the top.
  316. return false;
  317. }
  318. }