transformer.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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. }
  39. export interface UpdateParams<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> {
  40. a: A,
  41. b: B,
  42. oldParams: P,
  43. newParams: P,
  44. /** A cache object that is purged each time the corresponding StateObject is removed or recreated. */
  45. cache: unknown,
  46. spine: StateTreeSpine
  47. }
  48. export interface AutoUpdateParams<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> {
  49. a: A,
  50. b: B,
  51. oldParams: P,
  52. newParams: P
  53. }
  54. export enum UpdateResult { Unchanged, Updated, Recreate, Null }
  55. /** Specify default control descriptors for the parameters */
  56. // export type ParamsDefinition<A extends StateObject = StateObject, P = any> = (a: A, globalCtx: unknown) => { [K in keyof P]: PD.Any }
  57. export interface DefinitionBase<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> {
  58. /**
  59. * Apply the actual transformation. It must be pure (i.e. with no side effects).
  60. * Returns a task that produces the result of the result directly.
  61. */
  62. apply(params: ApplyParams<A, P>, globalCtx: unknown): Task<B> | B,
  63. /**
  64. * Attempts to update the entity in a non-destructive way.
  65. * For example changing a color scheme of a visual does not require computing new geometry.
  66. * Return/resolve to undefined if the update is not possible.
  67. */
  68. update?(params: UpdateParams<A, B, P>, globalCtx: unknown): Task<UpdateResult> | UpdateResult,
  69. /** Determine if the transformer can be applied automatically on UI change. Default is false. */
  70. canAutoUpdate?(params: AutoUpdateParams<A, B, P>, globalCtx: unknown): boolean,
  71. /** Test if the transform can be applied to a given node */
  72. isApplicable?(a: A, globalCtx: unknown): boolean,
  73. /** By default, returns true */
  74. isSerializable?(params: P): { isSerializable: true } | { isSerializable: false; reason: string },
  75. /** Parameter interpolation */
  76. interpolate?(src: P, target: P, t: number, globalCtx: unknown): P
  77. /** Custom conversion to and from JSON */
  78. readonly customSerialization?: { toJSON(params: P, obj?: B): any, fromJSON(data: any): P }
  79. }
  80. export interface Definition<A extends StateObject = StateObject, B extends StateObject = StateObject, P extends {} = {}> extends DefinitionBase<A, B, P> {
  81. readonly name: string,
  82. readonly from: StateObject.Ctor[],
  83. readonly to: StateObject.Ctor[],
  84. readonly display: { readonly name: string, readonly description?: string },
  85. params?(a: A | undefined, globalCtx: unknown): { [K in keyof P]: PD.Any }
  86. }
  87. const registry = new Map<Id, Transformer<any, any>>();
  88. const fromTypeIndex: Map<StateObject.Type, Transformer[]> = new Map();
  89. function _index(tr: Transformer) {
  90. for (const t of tr.definition.from) {
  91. if (fromTypeIndex.has(t.type)) {
  92. fromTypeIndex.get(t.type)!.push(tr);
  93. } else {
  94. fromTypeIndex.set(t.type, [tr]);
  95. }
  96. }
  97. }
  98. export function getAll() {
  99. return Array.from(registry.values());
  100. }
  101. export function get(id: string): Transformer {
  102. const t = registry.get(id as Id);
  103. if (!t) {
  104. throw new Error(`A transformer with signature '${id}' is not registered.`);
  105. }
  106. return t;
  107. }
  108. export function fromType(type: StateObject.Type): ReadonlyArray<Transformer> {
  109. return fromTypeIndex.get(type) || [];
  110. }
  111. export function create<A extends StateObject, B extends StateObject, P extends {} = {}>(namespace: string, definition: Definition<A, B, P>) {
  112. const { name } = definition;
  113. const id = `${namespace}.${name}` as Id;
  114. if (registry.has(id)) {
  115. 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.`);
  116. }
  117. const t: Transformer<A, B, P> = {
  118. apply(parent, params, props) { return StateTransform.create<Transformer<A, B, P>>(parent, t, params, props); },
  119. toAction() { return StateAction.fromTransformer(t); },
  120. namespace,
  121. id,
  122. definition,
  123. createDefaultParams(a, globalCtx) { return definition.params ? PD.getDefaultValues( definition.params(a, globalCtx)) : {} as any; }
  124. };
  125. registry.set(id, t);
  126. _index(t);
  127. return t;
  128. }
  129. export function factory(namespace: string) {
  130. return <A extends StateObject, B extends StateObject, P extends {} = {}>(definition: Definition<A, B, P>) => create(namespace, definition);
  131. }
  132. export function builderFactory(namespace: string) {
  133. return Builder.build(namespace);
  134. }
  135. export namespace Builder {
  136. export interface Type<A extends StateObject.Ctor, B extends StateObject.Ctor, P extends { }> {
  137. name: string,
  138. from: A | A[],
  139. to: B | B[],
  140. /** The source StateObject can be undefined: used for generating docs. */
  141. params?: PD.For<P> | ((a: StateObject.From<A> | undefined, globalCtx: any) => PD.For<P>),
  142. display?: string | { name: string, description?: string }
  143. }
  144. export interface Root {
  145. <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>>
  146. }
  147. export interface Define<A extends StateObject, B extends StateObject, P> {
  148. (def: DefinitionBase<A, B, P>): Transformer<A, B, P>
  149. }
  150. function root(namespace: string, info: Type<any, any, any>): Define<any, any, any> {
  151. return def => create(namespace, {
  152. name: info.name,
  153. from: info.from instanceof Array ? info.from : [info.from],
  154. to: info.to instanceof Array ? info.to : [info.to],
  155. display: typeof info.display === 'string'
  156. ? { name: info.display }
  157. : !!info.display
  158. ? info.display
  159. : { name: capitalize(info.name.replace(/[-]/g, ' ')) },
  160. params: typeof info.params === 'object'
  161. ? () => info.params as any
  162. : !!info.params
  163. ? info.params as any
  164. : void 0,
  165. ...def
  166. });
  167. }
  168. export function build(namespace: string): Root {
  169. return (info: any) => root(namespace, info);
  170. }
  171. }
  172. export function build(namespace: string): Builder.Root {
  173. return Builder.build(namespace);
  174. }
  175. export const ROOT = create<any, any, {}>('build-in', {
  176. name: 'root',
  177. from: [],
  178. to: [],
  179. display: { name: 'Root', description: 'For internal use.' },
  180. apply() { throw new Error('should never be applied'); },
  181. update() { return UpdateResult.Unchanged; }
  182. })
  183. }