state.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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, StateObjectCell } from './object';
  7. import { StateTree } from './tree';
  8. import { StateTransform } from './transform';
  9. import { StateTransformer } from './transformer';
  10. import { RuntimeContext, Task } from 'mol-task';
  11. import { StateSelection } from './state/selection';
  12. import { RxEventHelper } from 'mol-util/rx-event-helper';
  13. import { StateBuilder } from './state/builder';
  14. import { StateAction } from './action';
  15. import { StateActionManager } from './action/manager';
  16. import { TransientTree } from './tree/transient';
  17. import { LogEntry } from 'mol-util/log-entry';
  18. import { now, formatTimespan } from 'mol-util/now';
  19. import { ParamDefinition } from 'mol-util/param-definition';
  20. export { State }
  21. class State {
  22. private _tree: TransientTree;
  23. protected errorFree = true;
  24. private transformCache = new Map<StateTransform.Ref, unknown>();
  25. private ev = RxEventHelper.create();
  26. readonly globalContext: unknown = void 0;
  27. readonly events = {
  28. cell: {
  29. stateUpdated: this.ev<State.ObjectEvent & { cellState: StateObjectCell.State }>(),
  30. created: this.ev<State.ObjectEvent & { cell: StateObjectCell }>(),
  31. removed: this.ev<State.ObjectEvent & { parent: StateTransform.Ref }>(),
  32. },
  33. object: {
  34. updated: this.ev<State.ObjectEvent & { action: 'in-place' | 'recreate', obj: StateObject, oldObj?: StateObject }>(),
  35. created: this.ev<State.ObjectEvent & { obj: StateObject }>(),
  36. removed: this.ev<State.ObjectEvent & { obj?: StateObject }>()
  37. },
  38. log: this.ev<LogEntry>(),
  39. changed: this.ev<void>(),
  40. isUpdating: this.ev<boolean>()
  41. };
  42. readonly behaviors = {
  43. currentObject: this.ev.behavior<State.ObjectEvent>({ state: this, ref: StateTransform.RootRef })
  44. };
  45. readonly actions = new StateActionManager();
  46. get tree(): StateTree { return this._tree; }
  47. get transforms() { return (this._tree as StateTree).transforms; }
  48. get cellStates() { return (this._tree as StateTree).cellStates; }
  49. get current() { return this.behaviors.currentObject.value.ref; }
  50. build() { return new StateBuilder.Root(this._tree); }
  51. readonly cells: State.Cells = new Map();
  52. getSnapshot(): State.Snapshot {
  53. return { tree: StateTree.toJSON(this._tree) };
  54. }
  55. setSnapshot(snapshot: State.Snapshot) {
  56. const tree = StateTree.fromJSON(snapshot.tree);
  57. return this.updateTree(tree);
  58. }
  59. setCurrent(ref: StateTransform.Ref) {
  60. this.behaviors.currentObject.next({ state: this, ref });
  61. }
  62. updateCellState(ref: StateTransform.Ref, stateOrProvider: ((old: StateObjectCell.State) => Partial<StateObjectCell.State>) | Partial<StateObjectCell.State>) {
  63. const update = typeof stateOrProvider === 'function'
  64. ? stateOrProvider(this.tree.cellStates.get(ref))
  65. : stateOrProvider;
  66. if (this._tree.updateCellState(ref, update)) {
  67. this.events.cell.stateUpdated.next({ state: this, ref, cellState: this.tree.cellStates.get(ref) });
  68. }
  69. }
  70. dispose() {
  71. this.ev.dispose();
  72. }
  73. /**
  74. * Select Cells using the provided selector.
  75. * @example state.query(StateSelection.Generators.byRef('test').ancestorOfType([type]))
  76. * @example state.query('test')
  77. */
  78. select(selector: StateSelection.Selector) {
  79. return StateSelection.select(selector, this)
  80. }
  81. /**
  82. * Select Cells by building a query generated on the fly.
  83. * @example state.select(q => q.byRef('test').subtree())
  84. */
  85. selectQ(selector: (q: typeof StateSelection.Generators) => StateSelection.Selector) {
  86. if (typeof selector === 'string') return StateSelection.select(selector, this);
  87. return StateSelection.select(selector(StateSelection.Generators), this)
  88. }
  89. /**
  90. * Creates a Task that applies the specified StateAction (i.e. must use run* on the result)
  91. * If no ref is specified, apply to root.
  92. */
  93. applyAction<A extends StateAction>(action: A, params: StateAction.Params<A>, ref: StateTransform.Ref = StateTransform.RootRef): Task<void> {
  94. return Task.create('Apply Action', ctx => {
  95. const cell = this.cells.get(ref);
  96. if (!cell) throw new Error(`'${ref}' does not exist.`);
  97. if (cell.status !== 'ok') throw new Error(`Action cannot be applied to a cell with status '${cell.status}'`);
  98. return runTask(action.definition.run({ ref, cell, a: cell.obj!, params, state: this }, this.globalContext), ctx);
  99. });
  100. }
  101. /**
  102. * Reconcialites the existing state tree with the new version.
  103. *
  104. * If the tree is StateBuilder.To<T>, the corresponding StateObject is returned by the task.
  105. * @param tree Tree instance or a tree builder instance
  106. * @param doNotReportTiming Indicates whether to log timing of the individual transforms
  107. */
  108. updateTree<T extends StateObject>(tree: StateBuilder.To<T>, options?: Partial<State.UpdateOptions>): Task<T>
  109. updateTree(tree: StateTree | StateBuilder, options?: Partial<State.UpdateOptions>): Task<void>
  110. updateTree(tree: StateTree | StateBuilder, options?: Partial<State.UpdateOptions>): Task<any> {
  111. return Task.create('Update Tree', async taskCtx => {
  112. this.events.isUpdating.next(true);
  113. let updated = false;
  114. const ctx = this.updateTreeAndCreateCtx(tree, taskCtx, options);
  115. try {
  116. updated = await update(ctx);
  117. if (StateBuilder.isTo(tree)) {
  118. const cell = this.select(tree.ref)[0];
  119. return cell && cell.obj;
  120. }
  121. } finally {
  122. if (updated) this.events.changed.next();
  123. this.events.isUpdating.next(false);
  124. for (const ref of ctx.stateChanges) {
  125. this.events.cell.stateUpdated.next({ state: this, ref, cellState: this.tree.cellStates.get(ref) });
  126. }
  127. }
  128. });
  129. }
  130. private updateTreeAndCreateCtx(tree: StateTree | StateBuilder, taskCtx: RuntimeContext, options: Partial<State.UpdateOptions> | undefined) {
  131. const _tree = (StateBuilder.is(tree) ? tree.getTree() : tree).asTransient();
  132. const oldTree = this._tree;
  133. this._tree = _tree;
  134. const ctx: UpdateContext = {
  135. parent: this,
  136. editInfo: StateBuilder.is(tree) ? tree.editInfo : void 0,
  137. errorFree: this.errorFree,
  138. taskCtx,
  139. oldTree,
  140. tree: _tree,
  141. cells: this.cells as Map<StateTransform.Ref, StateObjectCell>,
  142. transformCache: this.transformCache,
  143. results: [],
  144. stateChanges: [],
  145. options: { ...StateUpdateDefaultOptions, ...options },
  146. changed: false,
  147. hadError: false,
  148. newCurrent: void 0
  149. };
  150. this.errorFree = true;
  151. return ctx;
  152. }
  153. constructor(rootObject: StateObject, params?: { globalContext?: unknown, rootProps?: StateTransform.Props }) {
  154. this._tree = StateTree.createEmpty(StateTransform.createRoot(params && params.rootProps)).asTransient();
  155. const tree = this._tree;
  156. const root = tree.root;
  157. (this.cells as Map<StateTransform.Ref, StateObjectCell>).set(root.ref, {
  158. transform: root,
  159. sourceRef: void 0,
  160. obj: rootObject,
  161. status: 'ok',
  162. errorText: void 0,
  163. params: {
  164. definition: {},
  165. values: {}
  166. }
  167. });
  168. this.globalContext = params && params.globalContext;
  169. }
  170. }
  171. namespace State {
  172. export type Cells = ReadonlyMap<StateTransform.Ref, StateObjectCell>
  173. export type Tree = StateTree
  174. export type Builder = StateBuilder
  175. export interface ObjectEvent {
  176. state: State,
  177. ref: Ref
  178. }
  179. export interface Snapshot {
  180. readonly tree: StateTree.Serialized
  181. }
  182. export interface UpdateOptions {
  183. doNotLogTiming: boolean,
  184. doNotUpdateCurrent: boolean
  185. }
  186. export function create(rootObject: StateObject, params?: { globalContext?: unknown, rootProps?: StateTransform.Props }) {
  187. return new State(rootObject, params);
  188. }
  189. }
  190. const StateUpdateDefaultOptions: State.UpdateOptions = {
  191. doNotLogTiming: false,
  192. doNotUpdateCurrent: false
  193. };
  194. type Ref = StateTransform.Ref
  195. interface UpdateContext {
  196. parent: State,
  197. editInfo: StateBuilder.EditInfo | undefined
  198. errorFree: boolean,
  199. taskCtx: RuntimeContext,
  200. oldTree: StateTree,
  201. tree: TransientTree,
  202. cells: Map<StateTransform.Ref, StateObjectCell>,
  203. transformCache: Map<Ref, unknown>,
  204. results: UpdateNodeResult[],
  205. stateChanges: StateTransform.Ref[],
  206. // suppress timing messages
  207. options: State.UpdateOptions,
  208. changed: boolean,
  209. hadError: boolean,
  210. newCurrent?: Ref
  211. }
  212. async function update(ctx: UpdateContext) {
  213. // if only a single node was added/updated, we can skip potentially expensive diffing
  214. const fastTrack = !!(ctx.errorFree && ctx.editInfo && ctx.editInfo.count === 1 && ctx.editInfo.lastUpdate && ctx.editInfo.sourceTree === ctx.oldTree);
  215. let deletes: StateTransform.Ref[], deletedObjects: (StateObject | undefined)[] = [], roots: StateTransform.Ref[];
  216. if (fastTrack) {
  217. deletes = [];
  218. roots = [ctx.editInfo!.lastUpdate!];
  219. } else {
  220. // find all nodes that will definitely be deleted.
  221. // this is done in "post order", meaning that leaves will be deleted first.
  222. deletes = findDeletes(ctx);
  223. const current = ctx.parent.current;
  224. let hasCurrent = false;
  225. for (const d of deletes) {
  226. if (d === current) {
  227. hasCurrent = true;
  228. break;
  229. }
  230. }
  231. if (hasCurrent) {
  232. const newCurrent = findNewCurrent(ctx.oldTree, current, deletes, ctx.cells);
  233. ctx.parent.setCurrent(newCurrent);
  234. }
  235. for (const d of deletes) {
  236. const obj = ctx.cells.has(d) ? ctx.cells.get(d)!.obj : void 0;
  237. ctx.cells.delete(d);
  238. ctx.transformCache.delete(d);
  239. deletedObjects.push(obj);
  240. }
  241. // Find roots where transform version changed or where nodes will be added.
  242. roots = findUpdateRoots(ctx.cells, ctx.tree);
  243. }
  244. let newCellStates: StateTree.CellStates;
  245. if (!ctx.editInfo) {
  246. newCellStates = ctx.tree.cellStatesSnapshot();
  247. syncOldStates(ctx);
  248. }
  249. // Init empty cells where not present
  250. // this is done in "pre order", meaning that "parents" will be created 1st.
  251. const addedCells = initCells(ctx, roots);
  252. // Notify additions of new cells.
  253. for (const cell of addedCells) {
  254. ctx.parent.events.cell.created.next({ state: ctx.parent, ref: cell.transform.ref, cell });
  255. }
  256. for (let i = 0; i < deletes.length; i++) {
  257. const d = deletes[i];
  258. const parent = ctx.oldTree.transforms.get(d).parent;
  259. ctx.parent.events.object.removed.next({ state: ctx.parent, ref: d, obj: deletedObjects[i] });
  260. ctx.parent.events.cell.removed.next({ state: ctx.parent, ref: d, parent: parent });
  261. }
  262. if (deletedObjects.length) deletedObjects = [];
  263. // Set status of cells that will be updated to 'pending'.
  264. initCellStatus(ctx, roots);
  265. // Sequentially update all the subtrees.
  266. for (const root of roots) {
  267. await updateSubtree(ctx, root);
  268. }
  269. // Sync cell states
  270. if (!ctx.editInfo) {
  271. syncNewStates(ctx, newCellStates!);
  272. }
  273. let newCurrent: StateTransform.Ref | undefined = ctx.newCurrent;
  274. // Raise object updated events
  275. for (const update of ctx.results) {
  276. if (update.action === 'created') {
  277. ctx.parent.events.object.created.next({ state: ctx.parent, ref: update.ref, obj: update.obj! });
  278. if (!ctx.newCurrent) {
  279. const transform = ctx.tree.transforms.get(update.ref);
  280. if (!(transform.props && transform.props.isGhost) && update.obj !== StateObject.Null) newCurrent = update.ref;
  281. }
  282. } else if (update.action === 'updated') {
  283. ctx.parent.events.object.updated.next({ state: ctx.parent, ref: update.ref, action: 'in-place', obj: update.obj });
  284. } else if (update.action === 'replaced') {
  285. ctx.parent.events.object.updated.next({ state: ctx.parent, ref: update.ref, action: 'recreate', obj: update.obj, oldObj: update.oldObj });
  286. }
  287. }
  288. if (newCurrent) {
  289. if (!ctx.options.doNotUpdateCurrent) ctx.parent.setCurrent(newCurrent);
  290. } else {
  291. // check if old current or its parent hasn't become null
  292. const current = ctx.parent.current;
  293. const currentCell = ctx.cells.get(current);
  294. if (currentCell && (currentCell.obj === StateObject.Null
  295. || (currentCell.status === 'error' && currentCell.errorText === ParentNullErrorText))) {
  296. newCurrent = findNewCurrent(ctx.oldTree, current, [], ctx.cells);
  297. ctx.parent.setCurrent(newCurrent);
  298. }
  299. }
  300. return deletes.length > 0 || roots.length > 0 || ctx.changed;
  301. }
  302. function findUpdateRoots(cells: Map<StateTransform.Ref, StateObjectCell>, tree: StateTree) {
  303. const findState = { roots: [] as Ref[], cells };
  304. StateTree.doPreOrder(tree, tree.root, findState, findUpdateRootsVisitor);
  305. return findState.roots;
  306. }
  307. function findUpdateRootsVisitor(n: StateTransform, _: any, s: { roots: Ref[], cells: Map<Ref, StateObjectCell> }) {
  308. const cell = s.cells.get(n.ref);
  309. if (!cell || cell.transform.version !== n.version || cell.status === 'error') {
  310. s.roots.push(n.ref);
  311. return false;
  312. }
  313. // nothing below a Null object can be an update root
  314. if (cell && cell.obj === StateObject.Null) return false;
  315. return true;
  316. }
  317. type FindDeletesCtx = { newTree: StateTree, cells: State.Cells, deletes: Ref[] }
  318. function checkDeleteVisitor(n: StateTransform, _: any, ctx: FindDeletesCtx) {
  319. if (!ctx.newTree.transforms.has(n.ref) && ctx.cells.has(n.ref)) ctx.deletes.push(n.ref);
  320. }
  321. function findDeletes(ctx: UpdateContext): Ref[] {
  322. const deleteCtx: FindDeletesCtx = { newTree: ctx.tree, cells: ctx.cells, deletes: [] };
  323. StateTree.doPostOrder(ctx.oldTree, ctx.oldTree.root, deleteCtx, checkDeleteVisitor);
  324. return deleteCtx.deletes;
  325. }
  326. function syncOldStatesVisitor(n: StateTransform, tree: StateTree, oldState: StateTree.CellStates) {
  327. if (oldState.has(n.ref)) {
  328. (tree as TransientTree).updateCellState(n.ref, oldState.get(n.ref));
  329. }
  330. }
  331. function syncOldStates(ctx: UpdateContext) {
  332. StateTree.doPreOrder(ctx.tree, ctx.tree.root, ctx.oldTree.cellStates, syncOldStatesVisitor);
  333. }
  334. function syncNewStatesVisitor(n: StateTransform, tree: StateTree, ctx: { newState: StateTree.CellStates, changes: StateTransform.Ref[] }) {
  335. if (ctx.newState.has(n.ref)) {
  336. const changed = (tree as TransientTree).updateCellState(n.ref, ctx.newState.get(n.ref));
  337. if (changed) {
  338. ctx.changes.push(n.ref);
  339. }
  340. }
  341. }
  342. function syncNewStates(ctx: UpdateContext, newState: StateTree.CellStates) {
  343. StateTree.doPreOrder(ctx.tree, ctx.tree.root, { newState, changes: ctx.stateChanges }, syncNewStatesVisitor);
  344. }
  345. function setCellStatus(ctx: UpdateContext, ref: Ref, status: StateObjectCell.Status, errorText?: string) {
  346. const cell = ctx.cells.get(ref)!;
  347. const changed = cell.status !== status;
  348. cell.status = status;
  349. cell.errorText = errorText;
  350. if (changed) ctx.parent.events.cell.stateUpdated.next({ state: ctx.parent, ref, cellState: ctx.tree.cellStates.get(ref) });
  351. }
  352. function initCellStatusVisitor(t: StateTransform, _: any, ctx: UpdateContext) {
  353. ctx.cells.get(t.ref)!.transform = t;
  354. setCellStatus(ctx, t.ref, 'pending');
  355. }
  356. function initCellStatus(ctx: UpdateContext, roots: Ref[]) {
  357. for (const root of roots) {
  358. StateTree.doPreOrder(ctx.tree, ctx.tree.transforms.get(root), ctx, initCellStatusVisitor);
  359. }
  360. }
  361. type InitCellsCtx = { ctx: UpdateContext, added: StateObjectCell[] }
  362. function initCellsVisitor(transform: StateTransform, _: any, { ctx, added }: InitCellsCtx) {
  363. if (ctx.cells.has(transform.ref)) {
  364. return;
  365. }
  366. const cell: StateObjectCell = {
  367. transform,
  368. sourceRef: void 0,
  369. status: 'pending',
  370. errorText: void 0,
  371. params: void 0
  372. };
  373. ctx.cells.set(transform.ref, cell);
  374. added.push(cell);
  375. }
  376. function initCells(ctx: UpdateContext, roots: Ref[]) {
  377. const initCtx: InitCellsCtx = { ctx, added: [] };
  378. for (const root of roots) {
  379. StateTree.doPreOrder(ctx.tree, ctx.tree.transforms.get(root), initCtx, initCellsVisitor);
  380. }
  381. return initCtx.added;
  382. }
  383. function findNewCurrent(tree: StateTree, start: Ref, deletes: Ref[], cells: Map<Ref, StateObjectCell>) {
  384. const deleteSet = new Set(deletes);
  385. return _findNewCurrent(tree, start, deleteSet, cells);
  386. }
  387. function _findNewCurrent(tree: StateTree, ref: Ref, deletes: Set<Ref>, cells: Map<Ref, StateObjectCell>): Ref {
  388. if (ref === StateTransform.RootRef) return ref;
  389. const node = tree.transforms.get(ref)!;
  390. const siblings = tree.children.get(node.parent)!.values();
  391. let prevCandidate: Ref | undefined = void 0, seenRef = false;
  392. while (true) {
  393. const s = siblings.next();
  394. if (s.done) break;
  395. if (deletes.has(s.value)) continue;
  396. const cell = cells.get(s.value);
  397. if (!cell || cell.status === 'error' || cell.obj === StateObject.Null) {
  398. continue;
  399. }
  400. const t = tree.transforms.get(s.value);
  401. if (t.props && t.props.isGhost) continue;
  402. if (s.value === ref) {
  403. seenRef = true;
  404. if (!deletes.has(ref)) prevCandidate = ref;
  405. continue;
  406. }
  407. if (seenRef) return t.ref;
  408. prevCandidate = t.ref;
  409. }
  410. if (prevCandidate) return prevCandidate;
  411. return _findNewCurrent(tree, node.parent, deletes, cells);
  412. }
  413. /** Set status and error text of the cell. Remove all existing objects in the subtree. */
  414. function doError(ctx: UpdateContext, ref: Ref, errorText: string | undefined, silent: boolean) {
  415. if (!silent) {
  416. ctx.hadError = true;
  417. (ctx.parent as any as { errorFree: boolean }).errorFree = false;
  418. }
  419. const cell = ctx.cells.get(ref)!;
  420. if (errorText) {
  421. setCellStatus(ctx, ref, 'error', errorText);
  422. if (!silent) ctx.parent.events.log.next({ type: 'error', timestamp: new Date(), message: errorText });
  423. } else {
  424. cell.params = void 0;
  425. }
  426. if (cell.obj) {
  427. const obj = cell.obj;
  428. cell.obj = void 0;
  429. ctx.parent.events.object.removed.next({ state: ctx.parent, ref, obj });
  430. ctx.transformCache.delete(ref);
  431. }
  432. // remove the objects in the child nodes if they exist
  433. const children = ctx.tree.children.get(ref).values();
  434. while (true) {
  435. const next = children.next();
  436. if (next.done) return;
  437. doError(ctx, next.value, void 0, silent);
  438. }
  439. }
  440. type UpdateNodeResult =
  441. | { ref: Ref, action: 'created', obj: StateObject }
  442. | { ref: Ref, action: 'updated', obj: StateObject }
  443. | { ref: Ref, action: 'replaced', oldObj?: StateObject, obj: StateObject }
  444. | { action: 'none' }
  445. const ParentNullErrorText = 'Parent is null';
  446. async function updateSubtree(ctx: UpdateContext, root: Ref) {
  447. setCellStatus(ctx, root, 'processing');
  448. let isNull = false;
  449. try {
  450. const start = now();
  451. const update = await updateNode(ctx, root);
  452. const time = now() - start;
  453. if (update.action !== 'none') ctx.changed = true;
  454. setCellStatus(ctx, root, 'ok');
  455. ctx.results.push(update);
  456. if (update.action === 'created') {
  457. isNull = update.obj === StateObject.Null;
  458. if (!isNull && !ctx.options.doNotLogTiming) ctx.parent.events.log.next(LogEntry.info(`Created ${update.obj.label} in ${formatTimespan(time)}.`));
  459. } else if (update.action === 'updated') {
  460. isNull = update.obj === StateObject.Null;
  461. if (!isNull && !ctx.options.doNotLogTiming) ctx.parent.events.log.next(LogEntry.info(`Updated ${update.obj.label} in ${formatTimespan(time)}.`));
  462. } else if (update.action === 'replaced') {
  463. isNull = update.obj === StateObject.Null;
  464. if (!isNull && !ctx.options.doNotLogTiming) ctx.parent.events.log.next(LogEntry.info(`Updated ${update.obj.label} in ${formatTimespan(time)}.`));
  465. }
  466. } catch (e) {
  467. ctx.changed = true;
  468. if (!ctx.hadError) ctx.newCurrent = root;
  469. doError(ctx, root, '' + e, false);
  470. console.error(e);
  471. return;
  472. }
  473. const children = ctx.tree.children.get(root).values();
  474. while (true) {
  475. const next = children.next();
  476. if (next.done) return;
  477. if (isNull) doError(ctx, next.value, void 0, true);
  478. else await updateSubtree(ctx, next.value);
  479. }
  480. }
  481. function resolveParams(ctx: UpdateContext, transform: StateTransform, src: StateObject) {
  482. const prms = transform.transformer.definition.params;
  483. const definition = prms ? prms(src, ctx.parent.globalContext) : {};
  484. const values = transform.params ? transform.params : ParamDefinition.getDefaultValues(definition);
  485. return { definition, values };
  486. }
  487. async function updateNode(ctx: UpdateContext, currentRef: Ref): Promise<UpdateNodeResult> {
  488. const { oldTree, tree } = ctx;
  489. const current = ctx.cells.get(currentRef)!;
  490. const transform = current.transform;
  491. // special case for Root
  492. if (current.transform.ref === StateTransform.RootRef) {
  493. return { action: 'none' };
  494. }
  495. let parentCell = transform.transformer.definition.from.length === 0
  496. ? ctx.cells.get(current.transform.parent)
  497. : StateSelection.findAncestorOfType(tree, ctx.cells, currentRef, transform.transformer.definition.from);
  498. if (!parentCell) {
  499. throw new Error(`No suitable parent found for '${currentRef}'`);
  500. }
  501. const parent = parentCell.obj!;
  502. current.sourceRef = parentCell.transform.ref;
  503. const params = resolveParams(ctx, transform, parent);
  504. if (!oldTree.transforms.has(currentRef) || !current.params) {
  505. current.params = params;
  506. const obj = await createObject(ctx, currentRef, transform.transformer, parent, params.values);
  507. updateTag(obj, transform);
  508. current.obj = obj;
  509. return { ref: currentRef, action: 'created', obj };
  510. } else {
  511. const oldParams = current.params.values;
  512. const newParams = params.values;
  513. current.params = params;
  514. const updateKind = !!current.obj && current.obj !== StateObject.Null
  515. ? await updateObject(ctx, currentRef, transform.transformer, parent, current.obj!, oldParams, newParams)
  516. : StateTransformer.UpdateResult.Recreate;
  517. switch (updateKind) {
  518. case StateTransformer.UpdateResult.Recreate: {
  519. const oldObj = current.obj;
  520. const newObj = await createObject(ctx, currentRef, transform.transformer, parent, newParams);
  521. updateTag(newObj, transform);
  522. current.obj = newObj;
  523. return { ref: currentRef, action: 'replaced', oldObj, obj: newObj };
  524. }
  525. case StateTransformer.UpdateResult.Updated:
  526. updateTag(current.obj, transform);
  527. return { ref: currentRef, action: 'updated', obj: current.obj! };
  528. default:
  529. return { action: 'none' };
  530. }
  531. }
  532. }
  533. function updateTag(obj: StateObject | undefined, transform: StateTransform) {
  534. if (!obj || obj === StateObject.Null) return;
  535. (obj.tag as string | undefined) = transform.props.tag;
  536. }
  537. function runTask<T>(t: T | Task<T>, ctx: RuntimeContext) {
  538. if (typeof (t as any).runInContext === 'function') return (t as Task<T>).runInContext(ctx);
  539. return t as T;
  540. }
  541. function createObject(ctx: UpdateContext, ref: Ref, transformer: StateTransformer, a: StateObject, params: any) {
  542. const cache = Object.create(null);
  543. ctx.transformCache.set(ref, cache);
  544. return runTask(transformer.definition.apply({ a, params, cache }, ctx.parent.globalContext), ctx.taskCtx);
  545. }
  546. async function updateObject(ctx: UpdateContext, ref: Ref, transformer: StateTransformer, a: StateObject, b: StateObject, oldParams: any, newParams: any) {
  547. if (!transformer.definition.update) {
  548. return StateTransformer.UpdateResult.Recreate;
  549. }
  550. let cache = ctx.transformCache.get(ref);
  551. if (!cache) {
  552. cache = Object.create(null);
  553. ctx.transformCache.set(ref, cache);
  554. }
  555. return runTask(transformer.definition.update({ a, oldParams, b, newParams, cache }, ctx.parent.globalContext), ctx.taskCtx);
  556. }