transform.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 { StateObject } from '../object';
  7. import { Transformer } from '../transformer';
  8. import { UUID } from 'mol-util';
  9. export interface Transform<A extends StateObject = StateObject, B extends StateObject = StateObject, P = unknown> {
  10. readonly transformer: Transformer<A, B, P>,
  11. readonly params: P,
  12. readonly ref: Transform.Ref,
  13. readonly version: string,
  14. readonly defaultProps?: unknown
  15. }
  16. export namespace Transform {
  17. export type Ref = string
  18. export interface Props {
  19. ref: Ref
  20. }
  21. export enum Flags {
  22. // Indicates that the transform was generated by a behaviour and should not be automatically updated
  23. Generated
  24. }
  25. export function create<A extends StateObject, B extends StateObject, P>(transformer: Transformer<A, B, P>, params?: P, props?: Partial<Props>): Transform<A, B, P> {
  26. const ref = props && props.ref ? props.ref : UUID.create() as string as Ref;
  27. return {
  28. transformer,
  29. params: params || { } as any,
  30. ref,
  31. version: UUID.create()
  32. }
  33. }
  34. export function updateParams<T>(t: Transform, params: any): Transform {
  35. return { ...t, params, version: UUID.create() };
  36. }
  37. export function createRoot(ref: Ref): Transform {
  38. return create(Transformer.ROOT, {}, { ref });
  39. }
  40. export interface Serialized {
  41. transformer: string,
  42. params: any,
  43. ref: string,
  44. version: string,
  45. defaultProps?: unknown
  46. }
  47. function _id(x: any) { return x; }
  48. export function toJSON(t: Transform): Serialized {
  49. const pToJson = t.transformer.definition.customSerialization
  50. ? t.transformer.definition.customSerialization.toJSON
  51. : _id;
  52. return {
  53. transformer: t.transformer.id,
  54. params: pToJson(t.params),
  55. ref: t.ref,
  56. version: t.version,
  57. defaultProps: t.defaultProps
  58. };
  59. }
  60. export function fromJSON(t: Serialized): Transform {
  61. const transformer = Transformer.get(t.transformer);
  62. const pFromJson = transformer.definition.customSerialization
  63. ? transformer.definition.customSerialization.toJSON
  64. : _id;
  65. return {
  66. transformer,
  67. params: pFromJson(t.params),
  68. ref: t.ref,
  69. version: t.version,
  70. defaultProps: t.defaultProps
  71. };
  72. }
  73. }