transformer.ts 8.3 KB

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