object.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 { UUID } from 'mol-util';
  7. import { Transform } from './transform';
  8. export { StateObject, StateObjectCell }
  9. interface StateObject<D = any, T extends StateObject.Type = { name: string, typeClass: any }> {
  10. readonly id: UUID,
  11. readonly type: T,
  12. readonly data: D,
  13. readonly label: string,
  14. readonly description?: string,
  15. }
  16. namespace StateObject {
  17. export function factory<T extends Type>() {
  18. return <D = { }>(type: T) => create<D, T>(type);
  19. }
  20. export type Type<Cls extends string = string> = { name: string, typeClass: Cls }
  21. export type Ctor = { new(...args: any[]): StateObject, type: any }
  22. export function create<Data, T extends Type>(type: T) {
  23. return class implements StateObject<Data, T> {
  24. static type = type;
  25. static is(obj?: StateObject): obj is StateObject<Data, T> { return !!obj && type === obj.type; }
  26. id = UUID.create22();
  27. type = type;
  28. label: string;
  29. description?: string;
  30. constructor(public data: Data, props?: { label: string, description?: string }) {
  31. this.label = props && props.label || type.name;
  32. this.description = props && props.description;
  33. }
  34. }
  35. }
  36. }
  37. interface StateObjectCell {
  38. transform: Transform,
  39. // Which object was used as a parent to create data in this cell
  40. sourceRef: Transform.Ref | undefined,
  41. version: string
  42. status: StateObjectCell.Status,
  43. errorText?: string,
  44. obj?: StateObject
  45. }
  46. namespace StateObjectCell {
  47. export type Status = 'ok' | 'error' | 'pending' | 'processing'
  48. export interface State {
  49. isHidden: boolean,
  50. isCollapsed: boolean
  51. }
  52. export const DefaultState: State = { isHidden: false, isCollapsed: false };
  53. export function areStatesEqual(a: State, b: State) {
  54. return a.isHidden !== b.isHidden || a.isCollapsed !== b.isCollapsed;
  55. }
  56. export function isStateChange(a: State, b?: Partial<State>) {
  57. if (!b) return false;
  58. if (typeof b.isCollapsed !== 'undefined' && a.isCollapsed !== b.isCollapsed) return true;
  59. if (typeof b.isHidden !== 'undefined' && a.isHidden !== b.isHidden) return true;
  60. return false;
  61. }
  62. }