transformer.ts 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 | undefined, 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 getAll() {
  90. return Array.from(registry.values());
  91. }
  92. export function get(id: string): Transformer {
  93. const t = registry.get(id as Id);
  94. if (!t) {
  95. throw new Error(`A transformer with signature '${id}' is not registered.`);
  96. }
  97. return t;
  98. }
  99. export function fromType(type: StateObject.Type): ReadonlyArray<Transformer> {
  100. return fromTypeIndex.get(type) || [];
  101. }
  102. export function create<A extends StateObject, B extends StateObject, P extends {} = {}>(namespace: string, definition: Definition<A, B, P>) {
  103. const { name } = definition;
  104. const id = `${namespace}.${name}` as Id;
  105. if (registry.has(id)) {
  106. 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.`);
  107. }
  108. const t: Transformer<A, B, P> = {
  109. apply(parent, params, props) { return Transform.create<A, B, P>(parent, t, params, props); },
  110. toAction() { return StateAction.fromTransformer(t); },
  111. namespace,
  112. id,
  113. definition
  114. };
  115. registry.set(id, t);
  116. _index(t);
  117. return t;
  118. }
  119. export function factory(namespace: string) {
  120. return <A extends StateObject, B extends StateObject, P extends {} = {}>(definition: Definition<A, B, P>) => create(namespace, definition);
  121. }
  122. export function builderFactory(namespace: string) {
  123. return Builder.build(namespace);
  124. }
  125. export namespace Builder {
  126. export interface Type<A extends StateObject.Ctor, B extends StateObject.Ctor, P extends { }> {
  127. name: string,
  128. from: A | A[],
  129. to: B | B[],
  130. /** The source StateObject can be undefined: used for generating docs. */
  131. params?: PD.For<P> | ((a: StateObject.From<A> | undefined, globalCtx: any) => PD.For<P>),
  132. display?: string | { name: string, description?: string }
  133. }
  134. export interface Root {
  135. <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>>
  136. }
  137. export interface Define<A extends StateObject, B extends StateObject, P> {
  138. (def: DefinitionBase<A, B, P>): Transformer<A, B, P>
  139. }
  140. function root(namespace: string, info: Type<any, any, any>): Define<any, any, any> {
  141. return def => create(namespace, {
  142. name: info.name,
  143. from: info.from instanceof Array ? info.from : [info.from],
  144. to: info.to instanceof Array ? info.to : [info.to],
  145. display: typeof info.display === 'string'
  146. ? { name: info.display }
  147. : !!info.display
  148. ? info.display
  149. : { name: capitalize(info.name.replace(/[-]/g, ' ')) },
  150. params: typeof info.params === 'object'
  151. ? () => info.params as any
  152. : !!info.params
  153. ? info.params as any
  154. : void 0,
  155. ...def
  156. });
  157. }
  158. export function build(namespace: string): Root {
  159. return (info: any) => root(namespace, info);
  160. }
  161. }
  162. export function build(namespace: string): Builder.Root {
  163. return Builder.build(namespace);
  164. }
  165. export const ROOT = create<any, any, {}>('build-in', {
  166. name: 'root',
  167. from: [],
  168. to: [],
  169. display: { name: 'Root', description: 'For internal use.' },
  170. apply() { throw new Error('should never be applied'); },
  171. update() { return UpdateResult.Unchanged; }
  172. })
  173. }