transformer.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { Task } from '../mol-task';
  7. import { StateObject, StateObjectCell } from './object';
  8. import { StateTransform } from './transform';
  9. import { ParamDefinition as PD } from '../mol-util/param-definition';
  10. import { StateAction } from './action';
  11. import { capitalize } from '../mol-util/string';
  12. import { StateTreeSpine } from './tree/spine';
  13. export { Transformer as StateTransformer }
  14. interface Transformer<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = any> {
  15. apply(parent: StateTransform.Ref, params?: P, props?: Partial<StateTransform.Options>): StateTransform<this>,
  16. toAction(): StateAction<A, void, P>,
  17. readonly namespace: string,
  18. readonly id: Transformer.Id,
  19. readonly definition: Transformer.Definition<A, B, P>,
  20. /** create a fresh copy of the params which can be edited in place */
  21. createDefaultParams(a: A, globalCtx: unknown): P
  22. }
  23. namespace Transformer {
  24. export type Id = string & { '@type': 'transformer-id' }
  25. export type Params<T extends Transformer<any, any, any>> = T extends Transformer<any, any, infer P> ? P : unknown;
  26. export type From<T extends Transformer<any, any, any>> = T extends Transformer<infer A, any, any> ? A : unknown;
  27. export type To<T extends Transformer<any, any, any>> = T extends Transformer<any, infer B, any> ? B : unknown;
  28. export type Cell<T extends Transformer<any, any, any>> = T extends Transformer<any, infer B, any> ? StateObjectCell<B> : unknown;
  29. export function is(obj: any): obj is Transformer {
  30. return !!obj && typeof (obj as Transformer).toAction === 'function' && typeof (obj as Transformer).apply === 'function';
  31. }
  32. export interface ApplyParams<A extends StateObject = StateObject, P extends {} = {}> {
  33. a: A,
  34. params: P,
  35. /** A cache object that is purged each time the corresponding StateObject is removed or recreated. */
  36. cache: unknown,
  37. spine: StateTreeSpine,
  38. dependencies?: { [k: string]: StateObject<unknown> }
  39. }
  40. export interface UpdateParams<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> {
  41. a: A,
  42. b: B,
  43. oldParams: P,
  44. newParams: P,
  45. /** A cache object that is purged each time the corresponding StateObject is removed or recreated. */
  46. cache: unknown,
  47. spine: StateTreeSpine,
  48. dependencies?: { [k: string]: StateObject<unknown> }
  49. }
  50. export interface AutoUpdateParams<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> {
  51. a: A,
  52. b: B,
  53. oldParams: P,
  54. newParams: P
  55. }
  56. export enum UpdateResult { Unchanged, Updated, Recreate, Null }
  57. /** Specify default control descriptors for the parameters */
  58. // export type ParamsDefinition<A extends StateObject = StateObject, P = any> = (a: A, globalCtx: unknown) => { [K in keyof P]: PD.Any }
  59. export interface DefinitionBase<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> {
  60. /**
  61. * Apply the actual transformation. It must be pure (i.e. with no side effects).
  62. * Returns a task that produces the result of the result directly.
  63. */
  64. apply(params: ApplyParams<A, P>, globalCtx: unknown): Task<B> | B,
  65. /**
  66. * Attempts to update the entity in a non-destructive way.
  67. * For example changing a color scheme of a visual does not require computing new geometry.
  68. * Return/resolve to undefined if the update is not possible.
  69. */
  70. update?(params: UpdateParams<A, B, P>, globalCtx: unknown): Task<UpdateResult> | UpdateResult,
  71. /** Determine if the transformer can be applied automatically on UI change. Default is false. */
  72. canAutoUpdate?(params: AutoUpdateParams<A, B, P>, globalCtx: unknown): boolean,
  73. /** Test if the transform can be applied to a given node */
  74. isApplicable?(a: A, globalCtx: unknown): boolean,
  75. /** By default, returns true */
  76. isSerializable?(params: P): { isSerializable: true } | { isSerializable: false; reason: string },
  77. /** Parameter interpolation */
  78. interpolate?(src: P, target: P, t: number, globalCtx: unknown): P
  79. /** Custom conversion to and from JSON */
  80. readonly customSerialization?: { toJSON(params: P, obj?: B): any, fromJSON(data: any): P }
  81. }
  82. export interface Definition<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> extends DefinitionBase<A, B, P> {
  83. readonly name: string,
  84. readonly from: StateObject.Ctor[],
  85. readonly to: StateObject.Ctor[],
  86. readonly display: { readonly name: string, readonly description?: string },
  87. params?(a: A | undefined, globalCtx: unknown): { [K in keyof P]: PD.Any }
  88. }
  89. const registry = new Map<Id, Transformer<any, any>>();
  90. const fromTypeIndex: Map<StateObject.Type, Transformer[]> = new Map();
  91. function _index(tr: Transformer) {
  92. for (const t of tr.definition.from) {
  93. if (fromTypeIndex.has(t.type)) {
  94. fromTypeIndex.get(t.type)!.push(tr);
  95. } else {
  96. fromTypeIndex.set(t.type, [tr]);
  97. }
  98. }
  99. }
  100. export function getAll() {
  101. return Array.from(registry.values());
  102. }
  103. export function get(id: string): Transformer {
  104. const t = registry.get(id as Id);
  105. if (!t) {
  106. throw new Error(`A transformer with signature '${id}' is not registered.`);
  107. }
  108. return t;
  109. }
  110. export function fromType(type: StateObject.Type): ReadonlyArray<Transformer> {
  111. return fromTypeIndex.get(type) || [];
  112. }
  113. export function create<A extends StateObject, B extends StateObject, P extends {} = {}>(namespace: string, definition: Definition<A, B, P>) {
  114. const { name } = definition;
  115. const id = `${namespace}.${name}` as Id;
  116. if (registry.has(id)) {
  117. throw new Error(`A transform with id '${name}' is already registered. Please pick a unique identifier for your transforms and/or register them only once. This is to ensure that transforms can be serialized and replayed.`);
  118. }
  119. const t: Transformer<A, B, P> = {
  120. apply(parent, params, props) { return StateTransform.create<Transformer<A, B, P>>(parent, t, params, props); },
  121. toAction() { return StateAction.fromTransformer(t); },
  122. namespace,
  123. id,
  124. definition,
  125. createDefaultParams(a, globalCtx) { return definition.params ? PD.getDefaultValues( definition.params(a, globalCtx)) : {} as any; }
  126. };
  127. registry.set(id, t);
  128. _index(t);
  129. return t;
  130. }
  131. export function factory(namespace: string) {
  132. return <A extends StateObject, B extends StateObject, P extends {} = {}>(definition: Definition<A, B, P>) => create(namespace, definition);
  133. }
  134. export function builderFactory(namespace: string) {
  135. return Builder.build(namespace);
  136. }
  137. export namespace Builder {
  138. export interface Type<A extends StateObject.Ctor, B extends StateObject.Ctor, P extends { }> {
  139. name: string,
  140. from: A | A[],
  141. to: B | B[],
  142. /** The source StateObject can be undefined: used for generating docs. */
  143. params?: PD.For<P> | ((a: StateObject.From<A> | undefined, globalCtx: any) => PD.For<P>),
  144. display?: string | { name: string, description?: string }
  145. }
  146. export interface Root {
  147. <A extends StateObject.Ctor, B extends StateObject.Ctor, P extends { }>(info: Type<A, B, P>): Define<StateObject.From<A>, StateObject.From<B>, PD.Normalize<P>>
  148. }
  149. export interface Define<A extends StateObject, B extends StateObject, P> {
  150. (def: DefinitionBase<A, B, P>): Transformer<A, B, P>
  151. }
  152. function root(namespace: string, info: Type<any, any, any>): Define<any, any, any> {
  153. return def => create(namespace, {
  154. name: info.name,
  155. from: info.from instanceof Array ? info.from : [info.from],
  156. to: info.to instanceof Array ? info.to : [info.to],
  157. display: typeof info.display === 'string'
  158. ? { name: info.display }
  159. : !!info.display
  160. ? info.display
  161. : { name: capitalize(info.name.replace(/[-]/g, ' ')) },
  162. params: typeof info.params === 'object'
  163. ? () => info.params as any
  164. : !!info.params
  165. ? info.params as any
  166. : void 0,
  167. ...def
  168. });
  169. }
  170. export function build(namespace: string): Root {
  171. return (info: any) => root(namespace, info);
  172. }
  173. }
  174. export function build(namespace: string): Builder.Root {
  175. return Builder.build(namespace);
  176. }
  177. export const ROOT = create<any, any, {}>('build-in', {
  178. name: 'root',
  179. from: [],
  180. to: [],
  181. display: { name: 'Root', description: 'For internal use.' },
  182. apply() { throw new Error('should never be applied'); },
  183. update() { return UpdateResult.Unchanged; }
  184. })
  185. }