state.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. /**
  2. * Copyright (c) 2018-2020 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. import { StateTreeSpine } from './tree/spine';
  21. import { AsyncQueue } from '../mol-util/async-queue';
  22. import { isProductionMode } from '../mol-util/debug'
  23. import { arraySetAdd, arraySetRemove } from '../mol-util/array';
  24. import { UniqueArray } from '../mol-data/generic';
  25. import { assignIfUndefined } from '../mol-util/object';
  26. export { State }
  27. class State {
  28. private _tree: TransientTree;
  29. protected errorFree = true;
  30. private ev = RxEventHelper.create();
  31. readonly globalContext: unknown = void 0;
  32. readonly events = {
  33. cell: {
  34. stateUpdated: this.ev<State.ObjectEvent & { cell: StateObjectCell }>(),
  35. created: this.ev<State.ObjectEvent & { cell: StateObjectCell }>(),
  36. removed: this.ev<State.ObjectEvent & { parent: StateTransform.Ref }>(),
  37. },
  38. object: {
  39. updated: this.ev<State.ObjectEvent & { action: 'in-place' | 'recreate', obj: StateObject, oldObj?: StateObject }>(),
  40. created: this.ev<State.ObjectEvent & { obj: StateObject }>(),
  41. removed: this.ev<State.ObjectEvent & { obj?: StateObject }>()
  42. },
  43. log: this.ev<LogEntry>(),
  44. changed: this.ev<{ state: State, inTransaction: boolean }>(),
  45. isUpdating: this.ev<boolean>()
  46. };
  47. readonly behaviors = {
  48. currentObject: this.ev.behavior<State.ObjectEvent>({ state: this, ref: StateTransform.RootRef })
  49. };
  50. readonly actions = new StateActionManager();
  51. get tree(): StateTree { return this._tree; }
  52. get transforms() { return (this._tree as StateTree).transforms; }
  53. get current() { return this.behaviors.currentObject.value.ref; }
  54. build() { return new StateBuilder.Root(this.tree, this); }
  55. readonly cells: State.Cells = new Map();
  56. private spine = new StateTreeSpine.Impl(this.cells);
  57. getSnapshot(): State.Snapshot {
  58. return { tree: StateTree.toJSON(this._tree) };
  59. }
  60. setSnapshot(snapshot: State.Snapshot) {
  61. const tree = StateTree.fromJSON(snapshot.tree);
  62. return this.updateTree(tree);
  63. }
  64. setCurrent(ref: StateTransform.Ref) {
  65. this.behaviors.currentObject.next({ state: this, ref });
  66. }
  67. updateCellState(ref: StateTransform.Ref, stateOrProvider: ((old: StateTransform.State) => Partial<StateTransform.State>) | Partial<StateTransform.State>) {
  68. const cell = this.cells.get(ref);
  69. if (!cell) return;
  70. const update = typeof stateOrProvider === 'function' ? stateOrProvider(cell.state) : stateOrProvider;
  71. if (StateTransform.assignState(cell.state, update)) {
  72. cell.transform = this._tree.assignState(cell.transform.ref, update);
  73. this.events.cell.stateUpdated.next({ state: this, ref, cell });
  74. }
  75. }
  76. dispose() {
  77. this.ev.dispose();
  78. }
  79. /**
  80. * Select Cells using the provided selector.
  81. * @example state.query(StateSelection.Generators.byRef('test').ancestorOfType([type]))
  82. * @example state.query('test')
  83. */
  84. select<C extends StateObjectCell>(selector: StateSelection.Selector<C>) {
  85. return StateSelection.select(selector, this)
  86. }
  87. /**
  88. * Select Cells by building a query generated on the fly.
  89. * @example state.select(q => q.byRef('test').subtree())
  90. */
  91. selectQ<C extends StateObjectCell>(selector: (q: typeof StateSelection.Generators) => StateSelection.Selector<C>) {
  92. if (typeof selector === 'string') return StateSelection.select(selector, this);
  93. return StateSelection.select(selector(StateSelection.Generators), this)
  94. }
  95. /**
  96. * Creates a Task that applies the specified StateAction (i.e. must use run* on the result)
  97. * If no ref is specified, apply to root.
  98. */
  99. applyAction<A extends StateAction>(action: A, params: StateAction.Params<A>, ref: StateTransform.Ref = StateTransform.RootRef): Task<void> {
  100. return Task.create('Apply Action', ctx => {
  101. const cell = this.cells.get(ref);
  102. if (!cell) throw new Error(`'${ref}' does not exist.`);
  103. if (cell.status !== 'ok') throw new Error(`Action cannot be applied to a cell with status '${cell.status}'`);
  104. return runTask(action.definition.run({ ref, cell, a: cell.obj!, params, state: this }, this.globalContext), ctx);
  105. });
  106. }
  107. private inTransaction = false;
  108. /** Apply series of updates to the state. If any of them fail, revert to the original state. */
  109. transaction(edits: () => Promise<void> | void) {
  110. return Task.create('State Transaction', async ctx => {
  111. const isNested = this.inTransaction;
  112. const snapshot = this._tree.asImmutable();
  113. let restored = false;
  114. try {
  115. if (!isNested) this.events.isUpdating.next(true);
  116. this.inTransaction = true;
  117. await edits();
  118. let hasError = false;
  119. this.cells.forEach(c => hasError = hasError || c.state === 'error');
  120. if (hasError) {
  121. restored = true;
  122. await this.updateTree(snapshot).runInContext(ctx);
  123. }
  124. } catch (e) {
  125. if (!restored) {
  126. await this.updateTree(snapshot).runInContext(ctx);
  127. this.events.log.error(e);
  128. }
  129. if (isNested) throw e;
  130. } finally {
  131. if (!isNested) {
  132. this.inTransaction = false;
  133. this.events.changed.next({ state: this, inTransaction: false });
  134. this.events.isUpdating.next(false);
  135. }
  136. }
  137. });
  138. }
  139. /**
  140. * Queues up a reconciliation of the existing state tree.
  141. *
  142. * If the tree is StateBuilder.To<T>, the corresponding StateObject is returned by the task.
  143. * @param tree Tree instance or a tree builder instance
  144. * @param doNotReportTiming Indicates whether to log timing of the individual transforms
  145. */
  146. updateTree<T extends StateObject>(tree: StateBuilder.To<T, any>, options?: Partial<State.UpdateOptions>): Task<T>
  147. updateTree(tree: StateTree | StateBuilder, options?: Partial<State.UpdateOptions>): Task<void>
  148. updateTree(tree: StateTree | StateBuilder, options?: Partial<State.UpdateOptions>): Task<any> {
  149. const params: UpdateParams = { tree, options };
  150. return Task.create('Update Tree', async taskCtx => {
  151. const removed = await this.updateQueue.enqueue(params);
  152. if (!removed) return;
  153. if (!this.inTransaction) this.events.isUpdating.next(true);
  154. try {
  155. const ret = options && (options.revertIfAborted || options.revertOnError)
  156. ? await this._revertibleTreeUpdate(taskCtx, params, options)
  157. : await this._updateTree(taskCtx, params);
  158. return ret.cell;
  159. } finally {
  160. this.updateQueue.handled(params);
  161. if (!this.inTransaction) this.events.isUpdating.next(false);
  162. }
  163. }, () => {
  164. this.updateQueue.remove(params);
  165. });
  166. }
  167. private updateQueue = new AsyncQueue<UpdateParams>();
  168. private async _revertibleTreeUpdate(taskCtx: RuntimeContext, params: UpdateParams, options: Partial<State.UpdateOptions>) {
  169. const old = this.tree;
  170. const ret = await this._updateTree(taskCtx, params);
  171. let revert = ((ret.ctx.hadError || ret.ctx.wasAborted) && options.revertOnError) || (ret.ctx.wasAborted && options.revertIfAborted);
  172. if (revert) return await this._updateTree(taskCtx, { tree: old, options: params.options });
  173. return ret;
  174. }
  175. private async _updateTree(taskCtx: RuntimeContext, params: UpdateParams) {
  176. let updated = false;
  177. const ctx = this.updateTreeAndCreateCtx(params.tree, taskCtx, params.options);
  178. try {
  179. updated = await update(ctx);
  180. if (StateBuilder.isTo(params.tree)) {
  181. const cell = this.select(params.tree.ref)[0];
  182. return { ctx, cell: cell && cell.obj };
  183. }
  184. return { ctx };
  185. } finally {
  186. this.spine.current = undefined;
  187. if (updated) this.events.changed.next({ state: this, inTransaction: this.inTransaction });
  188. }
  189. }
  190. private updateTreeAndCreateCtx(tree: StateTree | StateBuilder, taskCtx: RuntimeContext, options: Partial<State.UpdateOptions> | undefined) {
  191. const _tree = (StateBuilder.is(tree) ? tree.getTree() : tree).asTransient();
  192. const oldTree = this._tree;
  193. this._tree = _tree;
  194. const ctx: UpdateContext = {
  195. parent: this,
  196. editInfo: StateBuilder.is(tree) ? tree.editInfo : void 0,
  197. errorFree: this.errorFree,
  198. taskCtx,
  199. oldTree,
  200. tree: _tree,
  201. cells: this.cells as Map<StateTransform.Ref, StateObjectCell>,
  202. spine: this.spine,
  203. results: [],
  204. options: { ...StateUpdateDefaultOptions, ...options },
  205. changed: false,
  206. hadError: false,
  207. wasAborted: false,
  208. newCurrent: void 0
  209. };
  210. this.errorFree = true;
  211. return ctx;
  212. }
  213. constructor(rootObject: StateObject, params?: { globalContext?: unknown, rootState?: StateTransform.State }) {
  214. this._tree = StateTree.createEmpty(StateTransform.createRoot(params && params.rootState)).asTransient();
  215. const tree = this._tree;
  216. const root = tree.root;
  217. (this.cells as Map<StateTransform.Ref, StateObjectCell>).set(root.ref, {
  218. parent: this,
  219. transform: root,
  220. sourceRef: void 0,
  221. obj: rootObject,
  222. status: 'ok',
  223. state: { ...root.state },
  224. errorText: void 0,
  225. params: {
  226. definition: {},
  227. values: {}
  228. },
  229. dependencies: { dependentBy: [], dependsOn: [] },
  230. cache: { }
  231. });
  232. this.globalContext = params && params.globalContext;
  233. }
  234. }
  235. namespace State {
  236. export type Cells = ReadonlyMap<StateTransform.Ref, StateObjectCell>
  237. export type Tree = StateTree
  238. export type Builder = StateBuilder
  239. export interface ObjectEvent {
  240. state: State,
  241. ref: Ref
  242. }
  243. export namespace ObjectEvent {
  244. export function isCell(e: ObjectEvent, cell: StateObjectCell) {
  245. return e.ref === cell.transform.ref && e.state === cell.parent
  246. }
  247. }
  248. export interface Snapshot {
  249. readonly tree: StateTree.Serialized
  250. }
  251. export interface UpdateOptions {
  252. doNotLogTiming: boolean,
  253. doNotUpdateCurrent: boolean,
  254. revertIfAborted: boolean,
  255. revertOnError: boolean
  256. }
  257. export function create(rootObject: StateObject, params?: { globalContext?: unknown, rootState?: StateTransform.State }) {
  258. return new State(rootObject, params);
  259. }
  260. }
  261. const StateUpdateDefaultOptions: State.UpdateOptions = {
  262. doNotLogTiming: false,
  263. doNotUpdateCurrent: false,
  264. revertIfAborted: false,
  265. revertOnError: false
  266. };
  267. type Ref = StateTransform.Ref
  268. type UpdateParams = { tree: StateTree | StateBuilder, options?: Partial<State.UpdateOptions> }
  269. interface UpdateContext {
  270. parent: State,
  271. editInfo: StateBuilder.EditInfo | undefined
  272. errorFree: boolean,
  273. taskCtx: RuntimeContext,
  274. oldTree: StateTree,
  275. tree: TransientTree,
  276. cells: Map<StateTransform.Ref, StateObjectCell>,
  277. spine: StateTreeSpine.Impl,
  278. results: UpdateNodeResult[],
  279. // suppress timing messages
  280. options: State.UpdateOptions,
  281. changed: boolean,
  282. hadError: boolean,
  283. wasAborted: boolean,
  284. newCurrent?: Ref
  285. }
  286. async function update(ctx: UpdateContext) {
  287. // if only a single node was added/updated, we can skip potentially expensive diffing
  288. const fastTrack = !!(ctx.errorFree && ctx.editInfo && ctx.editInfo.count === 1 && ctx.editInfo.lastUpdate && ctx.editInfo.sourceTree === ctx.oldTree);
  289. let deletes: StateTransform.Ref[], deletedObjects: (StateObject | undefined)[] = [], roots: StateTransform.Ref[];
  290. if (fastTrack) {
  291. deletes = [];
  292. roots = [ctx.editInfo!.lastUpdate!];
  293. } else {
  294. // find all nodes that will definitely be deleted.
  295. // this is done in "post order", meaning that leaves will be deleted first.
  296. deletes = findDeletes(ctx);
  297. const current = ctx.parent.current;
  298. let hasCurrent = false;
  299. for (const d of deletes) {
  300. if (d === current) {
  301. hasCurrent = true;
  302. break;
  303. }
  304. }
  305. if (hasCurrent) {
  306. const newCurrent = findNewCurrent(ctx.oldTree, current, deletes, ctx.cells);
  307. ctx.parent.setCurrent(newCurrent);
  308. }
  309. for (const d of deletes) {
  310. const cell = ctx.cells.get(d);
  311. if (cell) unlinkCell(cell);
  312. const obj = cell && cell.obj;
  313. ctx.cells.delete(d);
  314. deletedObjects.push(obj);
  315. }
  316. // Find roots where transform version changed or where nodes will be added.
  317. roots = findUpdateRoots(ctx.cells, ctx.tree);
  318. }
  319. // Init empty cells where not present
  320. // this is done in "pre order", meaning that "parents" will be created 1st.
  321. const init = initCells(ctx, roots);
  322. // Notify additions of new cells.
  323. for (const cell of init.added) {
  324. ctx.parent.events.cell.created.next({ state: ctx.parent, ref: cell.transform.ref, cell });
  325. }
  326. for (let i = 0; i < deletes.length; i++) {
  327. const d = deletes[i];
  328. const parent = ctx.oldTree.transforms.get(d).parent;
  329. ctx.parent.events.object.removed.next({ state: ctx.parent, ref: d, obj: deletedObjects[i] });
  330. ctx.parent.events.cell.removed.next({ state: ctx.parent, ref: d, parent: parent });
  331. }
  332. if (deletedObjects.length) deletedObjects = [];
  333. if (init.dependent) {
  334. for (const cell of init.dependent) {
  335. roots.push(cell.transform.ref);
  336. }
  337. }
  338. // Set status of cells that will be updated to 'pending'.
  339. initCellStatus(ctx, roots);
  340. // Sequentially update all the subtrees.
  341. for (const root of roots) {
  342. await updateSubtree(ctx, root);
  343. }
  344. // Sync cell states
  345. if (!ctx.editInfo) {
  346. syncNewStates(ctx);
  347. }
  348. let newCurrent: StateTransform.Ref | undefined = ctx.newCurrent;
  349. // Raise object updated events
  350. for (const update of ctx.results) {
  351. if (update.action === 'created') {
  352. ctx.parent.events.object.created.next({ state: ctx.parent, ref: update.ref, obj: update.obj! });
  353. if (!ctx.newCurrent) {
  354. const transform = ctx.tree.transforms.get(update.ref);
  355. if (!transform.state.isGhost && update.obj !== StateObject.Null) newCurrent = update.ref;
  356. }
  357. } else if (update.action === 'updated') {
  358. ctx.parent.events.object.updated.next({ state: ctx.parent, ref: update.ref, action: 'in-place', obj: update.obj });
  359. } else if (update.action === 'replaced') {
  360. ctx.parent.events.object.updated.next({ state: ctx.parent, ref: update.ref, action: 'recreate', obj: update.obj, oldObj: update.oldObj });
  361. }
  362. }
  363. if (newCurrent) {
  364. if (!ctx.options.doNotUpdateCurrent) ctx.parent.setCurrent(newCurrent);
  365. } else {
  366. // check if old current or its parent hasn't become null
  367. const current = ctx.parent.current;
  368. const currentCell = ctx.cells.get(current);
  369. if (currentCell && (currentCell.obj === StateObject.Null
  370. || (currentCell.status === 'error' && currentCell.errorText === ParentNullErrorText))) {
  371. newCurrent = findNewCurrent(ctx.oldTree, current, [], ctx.cells);
  372. ctx.parent.setCurrent(newCurrent);
  373. }
  374. }
  375. return deletes.length > 0 || roots.length > 0 || ctx.changed;
  376. }
  377. function findUpdateRoots(cells: Map<StateTransform.Ref, StateObjectCell>, tree: StateTree) {
  378. const findState = { roots: [] as Ref[], cells };
  379. StateTree.doPreOrder(tree, tree.root, findState, findUpdateRootsVisitor);
  380. return findState.roots;
  381. }
  382. function findUpdateRootsVisitor(n: StateTransform, _: any, s: { roots: Ref[], cells: Map<Ref, StateObjectCell> }) {
  383. const cell = s.cells.get(n.ref);
  384. if (!cell || cell.transform.version !== n.version || cell.status === 'error') {
  385. s.roots.push(n.ref);
  386. return false;
  387. }
  388. // nothing below a Null object can be an update root
  389. if (cell && cell.obj === StateObject.Null) return false;
  390. return true;
  391. }
  392. type FindDeletesCtx = { newTree: StateTree, cells: State.Cells, deletes: Ref[] }
  393. function checkDeleteVisitor(n: StateTransform, _: any, ctx: FindDeletesCtx) {
  394. if (!ctx.newTree.transforms.has(n.ref) && ctx.cells.has(n.ref)) ctx.deletes.push(n.ref);
  395. }
  396. function findDeletes(ctx: UpdateContext): Ref[] {
  397. const deleteCtx: FindDeletesCtx = { newTree: ctx.tree, cells: ctx.cells, deletes: [] };
  398. StateTree.doPostOrder(ctx.oldTree, ctx.oldTree.root, deleteCtx, checkDeleteVisitor);
  399. return deleteCtx.deletes;
  400. }
  401. function syncNewStatesVisitor(n: StateTransform, tree: StateTree, ctx: UpdateContext) {
  402. const cell = ctx.cells.get(n.ref);
  403. if (!cell || !StateTransform.syncState(cell.state, n.state)) return;
  404. ctx.parent.events.cell.stateUpdated.next({ state: ctx.parent, ref: n.ref, cell });
  405. }
  406. function syncNewStates(ctx: UpdateContext) {
  407. StateTree.doPreOrder(ctx.tree, ctx.tree.root, ctx, syncNewStatesVisitor);
  408. }
  409. function setCellStatus(ctx: UpdateContext, ref: Ref, status: StateObjectCell.Status, errorText?: string) {
  410. const cell = ctx.cells.get(ref)!;
  411. const changed = cell.status !== status;
  412. cell.status = status;
  413. cell.errorText = errorText;
  414. if (changed) ctx.parent.events.cell.stateUpdated.next({ state: ctx.parent, ref, cell });
  415. }
  416. function initCellStatusVisitor(t: StateTransform, _: any, ctx: UpdateContext) {
  417. ctx.cells.get(t.ref)!.transform = t;
  418. setCellStatus(ctx, t.ref, 'pending');
  419. }
  420. function initCellStatus(ctx: UpdateContext, roots: Ref[]) {
  421. for (const root of roots) {
  422. StateTree.doPreOrder(ctx.tree, ctx.tree.transforms.get(root), ctx, initCellStatusVisitor);
  423. }
  424. }
  425. function unlinkCell(cell: StateObjectCell) {
  426. for (const other of cell.dependencies.dependsOn) {
  427. arraySetRemove(other.dependencies.dependentBy, cell);
  428. }
  429. }
  430. type InitCellsCtx = { ctx: UpdateContext, visited: Set<Ref>, added: StateObjectCell[] }
  431. function addCellsVisitor(transform: StateTransform, _: any, { ctx, added, visited }: InitCellsCtx) {
  432. visited.add(transform.ref);
  433. if (ctx.cells.has(transform.ref)) {
  434. return;
  435. }
  436. const cell: StateObjectCell = {
  437. parent: ctx.parent,
  438. transform,
  439. sourceRef: void 0,
  440. status: 'pending',
  441. state: { ...transform.state },
  442. errorText: void 0,
  443. params: void 0,
  444. dependencies: { dependentBy: [], dependsOn: [] },
  445. cache: void 0
  446. };
  447. ctx.cells.set(transform.ref, cell);
  448. added.push(cell);
  449. }
  450. // type LinkCellsCtx = { ctx: UpdateContext, visited: Set<Ref>, dependent: UniqueArray<Ref, StateObjectCell> }
  451. function linkCells(target: StateObjectCell, ctx: UpdateContext) {
  452. if (!target.transform.dependsOn) return;
  453. for (const ref of target.transform.dependsOn) {
  454. const t = ctx.tree.transforms.get(ref);
  455. if (!t) {
  456. throw new Error(`Cannot depend on a non-existent transform.`);
  457. }
  458. const cell = ctx.cells.get(ref)!;
  459. arraySetAdd(target.dependencies.dependsOn, cell);
  460. arraySetAdd(cell.dependencies.dependentBy, target);
  461. }
  462. }
  463. function initCells(ctx: UpdateContext, roots: Ref[]) {
  464. const initCtx: InitCellsCtx = { ctx, visited: new Set(), added: [] };
  465. // Add new cells
  466. for (const root of roots) {
  467. StateTree.doPreOrder(ctx.tree, ctx.tree.transforms.get(root), initCtx, addCellsVisitor);
  468. }
  469. // Update links for newly added cells
  470. for (const cell of initCtx.added) {
  471. linkCells(cell, ctx);
  472. }
  473. let dependent: UniqueArray<Ref, StateObjectCell>;
  474. // Find dependent cells
  475. initCtx.visited.forEach(ref => {
  476. const cell = ctx.cells.get(ref)!;
  477. for (const by of cell.dependencies.dependentBy) {
  478. if (initCtx.visited.has(by.transform.ref)) continue;
  479. if (!dependent) dependent = UniqueArray.create();
  480. UniqueArray.add(dependent, by.transform.ref, by);
  481. }
  482. });
  483. // TODO: check if dependent cells are all "proper roots"
  484. return { added: initCtx.added, dependent: dependent! ? dependent!.array : void 0 };
  485. }
  486. function findNewCurrent(tree: StateTree, start: Ref, deletes: Ref[], cells: Map<Ref, StateObjectCell>) {
  487. const deleteSet = new Set(deletes);
  488. return _findNewCurrent(tree, start, deleteSet, cells);
  489. }
  490. function _findNewCurrent(tree: StateTree, ref: Ref, deletes: Set<Ref>, cells: Map<Ref, StateObjectCell>): Ref {
  491. if (ref === StateTransform.RootRef) return ref;
  492. const node = tree.transforms.get(ref)!;
  493. const siblings = tree.children.get(node.parent)!.values();
  494. let prevCandidate: Ref | undefined = void 0, seenRef = false;
  495. while (true) {
  496. const s = siblings.next();
  497. if (s.done) break;
  498. if (deletes.has(s.value)) continue;
  499. const cell = cells.get(s.value);
  500. if (!cell || cell.status === 'error' || cell.obj === StateObject.Null) {
  501. continue;
  502. }
  503. const t = tree.transforms.get(s.value);
  504. if (t.state.isGhost) continue;
  505. if (s.value === ref) {
  506. seenRef = true;
  507. if (!deletes.has(ref)) prevCandidate = ref;
  508. continue;
  509. }
  510. if (seenRef) return t.ref;
  511. prevCandidate = t.ref;
  512. }
  513. if (prevCandidate) return prevCandidate;
  514. return _findNewCurrent(tree, node.parent, deletes, cells);
  515. }
  516. /** Set status and error text of the cell. Remove all existing objects in the subtree. */
  517. function doError(ctx: UpdateContext, ref: Ref, errorObject: any | undefined, silent: boolean) {
  518. if (!silent) {
  519. ctx.hadError = true;
  520. (ctx.parent as any as { errorFree: boolean }).errorFree = false;
  521. }
  522. const cell = ctx.cells.get(ref)!;
  523. if (errorObject) {
  524. ctx.wasAborted = ctx.wasAborted || Task.isAbort(errorObject);
  525. const message = '' + errorObject;
  526. setCellStatus(ctx, ref, 'error', message);
  527. if (!silent) ctx.parent.events.log.next({ type: 'error', timestamp: new Date(), message });
  528. } else {
  529. cell.params = void 0;
  530. }
  531. if (cell.obj) {
  532. const obj = cell.obj;
  533. cell.obj = void 0;
  534. cell.cache = void 0;
  535. ctx.parent.events.object.removed.next({ state: ctx.parent, ref, obj });
  536. }
  537. // remove the objects in the child nodes if they exist
  538. const children = ctx.tree.children.get(ref).values();
  539. while (true) {
  540. const next = children.next();
  541. if (next.done) return;
  542. doError(ctx, next.value, void 0, silent);
  543. }
  544. }
  545. type UpdateNodeResult =
  546. | { ref: Ref, action: 'created', obj: StateObject }
  547. | { ref: Ref, action: 'updated', obj: StateObject }
  548. | { ref: Ref, action: 'replaced', oldObj?: StateObject, obj: StateObject }
  549. | { action: 'none' }
  550. const ParentNullErrorText = 'Parent is null';
  551. async function updateSubtree(ctx: UpdateContext, root: Ref) {
  552. setCellStatus(ctx, root, 'processing');
  553. let isNull = false;
  554. try {
  555. const start = now();
  556. const update = await updateNode(ctx, root);
  557. const time = now() - start;
  558. if (update.action !== 'none') ctx.changed = true;
  559. setCellStatus(ctx, root, 'ok');
  560. ctx.results.push(update);
  561. if (update.action === 'created') {
  562. isNull = update.obj === StateObject.Null;
  563. if (!isNull && !ctx.options.doNotLogTiming) ctx.parent.events.log.next(LogEntry.info(`Created ${update.obj.label} in ${formatTimespan(time)}.`));
  564. } else if (update.action === 'updated') {
  565. isNull = update.obj === StateObject.Null;
  566. if (!isNull && !ctx.options.doNotLogTiming) ctx.parent.events.log.next(LogEntry.info(`Updated ${update.obj.label} in ${formatTimespan(time)}.`));
  567. } else if (update.action === 'replaced') {
  568. isNull = update.obj === StateObject.Null;
  569. if (!isNull && !ctx.options.doNotLogTiming) ctx.parent.events.log.next(LogEntry.info(`Updated ${update.obj.label} in ${formatTimespan(time)}.`));
  570. }
  571. } catch (e) {
  572. ctx.changed = true;
  573. if (!ctx.hadError) ctx.newCurrent = root;
  574. doError(ctx, root, e, false);
  575. if (!isProductionMode) console.error(e);
  576. return;
  577. }
  578. const children = ctx.tree.children.get(root).values();
  579. while (true) {
  580. const next = children.next();
  581. if (next.done) return;
  582. if (isNull) doError(ctx, next.value, void 0, true);
  583. else await updateSubtree(ctx, next.value);
  584. }
  585. }
  586. function resolveParams(ctx: UpdateContext, transform: StateTransform, src: StateObject) {
  587. const prms = transform.transformer.definition.params;
  588. const definition = prms ? prms(src, ctx.parent.globalContext) : {};
  589. const defaultValues = ParamDefinition.getDefaultValues(definition);
  590. (transform.params as any) = transform.params
  591. ? assignIfUndefined(transform.params, defaultValues)
  592. : defaultValues;
  593. return { definition, values: transform.params };
  594. }
  595. async function updateNode(ctx: UpdateContext, currentRef: Ref): Promise<UpdateNodeResult> {
  596. const { oldTree, tree } = ctx;
  597. const current = ctx.cells.get(currentRef)!;
  598. const transform = current.transform;
  599. // special case for Root
  600. if (current.transform.ref === StateTransform.RootRef) {
  601. return { action: 'none' };
  602. }
  603. let parentCell = transform.transformer.definition.from.length === 0
  604. ? ctx.cells.get(current.transform.parent)
  605. : StateSelection.findAncestorOfType(tree, ctx.cells, currentRef, transform.transformer.definition.from);
  606. if (!parentCell) {
  607. throw new Error(`No suitable parent found for '${currentRef}'`);
  608. }
  609. ctx.spine.current = current;
  610. const parent = parentCell.obj!;
  611. current.sourceRef = parentCell.transform.ref;
  612. const params = resolveParams(ctx, transform, parent);
  613. if (!oldTree.transforms.has(currentRef) || !current.params) {
  614. current.params = params;
  615. const obj = await createObject(ctx, current, transform.transformer, parent, params.values);
  616. updateTag(obj, transform);
  617. current.obj = obj;
  618. return { ref: currentRef, action: 'created', obj };
  619. } else {
  620. const oldParams = current.params.values;
  621. const newParams = params.values;
  622. current.params = params;
  623. const updateKind = !!current.obj && current.obj !== StateObject.Null
  624. ? await updateObject(ctx, current, transform.transformer, parent, current.obj!, oldParams, newParams)
  625. : StateTransformer.UpdateResult.Recreate;
  626. switch (updateKind) {
  627. case StateTransformer.UpdateResult.Recreate: {
  628. const oldObj = current.obj;
  629. const newObj = await createObject(ctx, current, transform.transformer, parent, newParams);
  630. updateTag(newObj, transform);
  631. current.obj = newObj;
  632. return { ref: currentRef, action: 'replaced', oldObj, obj: newObj };
  633. }
  634. case StateTransformer.UpdateResult.Updated:
  635. updateTag(current.obj, transform);
  636. return { ref: currentRef, action: 'updated', obj: current.obj! };
  637. case StateTransformer.UpdateResult.Null: {
  638. current.obj = StateObject.Null;
  639. return { ref: currentRef, action: 'updated', obj: current.obj! };
  640. }
  641. default:
  642. return { action: 'none' };
  643. }
  644. }
  645. }
  646. function updateTag(obj: StateObject | undefined, transform: StateTransform) {
  647. if (!obj || obj === StateObject.Null) return;
  648. (obj.tags as string[] | undefined) = transform.tags;
  649. }
  650. function runTask<T>(t: T | Task<T>, ctx: RuntimeContext) {
  651. if (typeof (t as any).runInContext === 'function') return (t as Task<T>).runInContext(ctx);
  652. return t as T;
  653. }
  654. function createObject(ctx: UpdateContext, cell: StateObjectCell, transformer: StateTransformer, a: StateObject, params: any) {
  655. if (!cell.cache) cell.cache = Object.create(null);
  656. return runTask(transformer.definition.apply({ a, params, cache: cell.cache, spine: ctx.spine, dependencies: resolveDependencies(ctx, cell) }, ctx.parent.globalContext), ctx.taskCtx);
  657. }
  658. function resolveDependencies(ctx: UpdateContext, cell: StateObjectCell) {
  659. if (cell.dependencies.dependsOn.length === 0) return void 0;
  660. const deps = Object.create(null);
  661. for (const dep of cell.dependencies.dependsOn) {
  662. if (!dep.obj) {
  663. throw new Error('Unresolved dependency.');
  664. }
  665. deps[dep.transform.ref] = dep.obj;
  666. }
  667. return deps;
  668. }
  669. async function updateObject(ctx: UpdateContext, cell: StateObjectCell, transformer: StateTransformer, a: StateObject, b: StateObject, oldParams: any, newParams: any) {
  670. if (!transformer.definition.update) {
  671. return StateTransformer.UpdateResult.Recreate;
  672. }
  673. if (!cell.cache) cell.cache = Object.create(null);
  674. return runTask(transformer.definition.update({ a, oldParams, b, newParams, cache: cell.cache, spine: ctx.spine, dependencies: resolveDependencies(ctx, cell) }, ctx.parent.globalContext), ctx.taskCtx);
  675. }