@gramlot/gramlot 0.3.36 → 0.3.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/dist/components/charts/__init__.py +1 -1
  2. package/dist/components/charts/assets/collection.js +9 -9
  3. package/dist/components/charts/assets/index.js +1 -1
  4. package/dist/components/charts/grammar.json +0 -30
  5. package/dist/components/drawing/__init__.py +1 -1
  6. package/dist/components/drawing/assets/collection.js +3 -3
  7. package/dist/components/drawing/assets/index.js +1 -1
  8. package/dist/components/grid/__init__.py +1 -1
  9. package/dist/components/grid/assets/collection.js +6 -6
  10. package/dist/components/grid/assets/index.js +1 -1
  11. package/dist/components/grid/grammar.json +0 -2
  12. package/dist/components/inputs/__init__.py +1 -1
  13. package/dist/components/inputs/assets/collection.js +8 -8
  14. package/dist/components/inputs/assets/index.js +1 -1
  15. package/dist/components/inputs/grammar.json +2 -1
  16. package/dist/components/layout/__init__.py +1 -1
  17. package/dist/components/layout/assets/collection.js +9 -9
  18. package/dist/components/layout/assets/index.js +1 -1
  19. package/dist/components/layout/grammar.json +2 -2
  20. package/dist/components/selection_trial/__init__.py +1 -1
  21. package/dist/components/selection_trial/assets/collection.js +3 -3
  22. package/dist/components/selection_trial/assets/index.js +1 -1
  23. package/dist/components/tree/__init__.py +1 -1
  24. package/dist/components/tree/assets/collection.js +6 -6
  25. package/dist/components/tree/assets/index.js +1 -1
  26. package/dist/components/tree/grammar.json +0 -1
  27. package/dist/components/uploads/__init__.py +1 -1
  28. package/dist/components/uploads/assets/collection.js +3 -3
  29. package/dist/components/uploads/assets/index.js +1 -1
  30. package/dist/components/uploads/grammar.json +0 -3
  31. package/dist/gramlot.js +1205 -627
  32. package/dist/gramlot.min.js +45 -45
  33. package/dist/standard-collections.js +1 -1
  34. package/package.json +2 -3
  35. package/src/binding/data-binder.js +11 -3
  36. package/src/binding/grid-struct.js +7 -4
  37. package/src/binding/runtime.js +203 -46
  38. package/src/builder/binding.json +23 -1
  39. package/src/builder/gramlot-builder.d.ts +1 -4
  40. package/src/builder/source.js +185 -29
  41. package/src/chat.js +26 -20
  42. package/src/components/attachment-manager.js +38 -34
  43. package/src/components/chart-data-view.js +4 -7
  44. package/src/components/chart-fields.js +18 -6
  45. package/src/components/chart-renderer.js +10 -3
  46. package/src/components/chart-timeline.js +7 -5
  47. package/src/components/charts.js +74 -67
  48. package/src/components/check-box-text-editor.js +3 -3
  49. package/src/components/check-box-text.js +7 -22
  50. package/src/components/check-box-tree.js +20 -16
  51. package/src/components/choice-editor.js +1 -1
  52. package/src/components/drawing.js +47 -34
  53. package/src/components/grid-cell-editor.js +72 -29
  54. package/src/components/grid-column-filters.js +47 -40
  55. package/src/components/grid-formulas.js +22 -17
  56. package/src/components/grid-header-interaction.js +9 -11
  57. package/src/components/grid-row-interaction.js +25 -24
  58. package/src/components/grid-row-layout.js +28 -29
  59. package/src/components/grid-search-box.js +3 -3
  60. package/src/components/grid-search.js +3 -8
  61. package/src/components/grid-selection.js +33 -29
  62. package/src/components/grid-structure.js +48 -10
  63. package/src/components/grid-tools.js +14 -14
  64. package/src/components/grid.js +83 -79
  65. package/src/components/image-crop-dialog.js +2 -2
  66. package/src/components/image-crop.js +16 -9
  67. package/src/components/image-uploader.js +21 -28
  68. package/src/components/inputs.js +19 -1
  69. package/src/components/registry.js +3 -5
  70. package/src/components/tray-pane.js +85 -61
  71. package/src/components/tree.js +332 -239
  72. package/src/components/upload-engine.js +10 -2
  73. package/src/components/uploader.js +31 -27
  74. package/src/editing-session.d.ts +4 -1
  75. package/src/editing-session.js +120 -83
  76. package/src/experiments/window-selection.js +4 -6
  77. package/src/filesystem.js +2 -2
  78. package/src/gramlot.js +1 -0
  79. package/src/handlers/device-handler.js +219 -213
  80. package/src/handlers/rpc-handler.d.ts +17 -0
  81. package/src/handlers/rpc-handler.js +22 -0
  82. package/src/ide-documents.js +29 -11
  83. package/src/ide-runtime.js +33 -31
  84. package/src/index-page-runtime.d.ts +2 -2
  85. package/src/index-page-runtime.js +67 -48
  86. package/src/message-port-connection.js +100 -0
  87. package/src/message-port-store.js +158 -0
  88. package/src/page-store-connection.js +6 -1
  89. package/src/renderer/gramlot-renderer.js +21 -2
  90. package/src/source-picker.d.ts +2 -2
  91. package/src/source-picker.js +15 -6
  92. package/src/stores/bag-collection-store.js +25 -7
  93. package/src/stores/bag-collection-view.js +23 -22
  94. package/src/view/controls.js +1 -1
  95. package/src/view/html.js +40 -20
  96. package/src/visual-editor-canvas.js +1 -1
  97. package/src/visual-editor.js +18 -19
  98. package/tools/gramlot-tools-inspector.js +400 -374
  99. package/tools/inspector-agent.js +223 -49
  100. package/dist/components/vizabi/__init__.py +0 -13
  101. package/dist/components/vizabi/assets/collection.js +0 -4
  102. package/dist/components/vizabi/assets/index.js +0 -3
  103. package/dist/components/vizabi/commands.json +0 -7
  104. package/dist/components/vizabi/grammar.json +0 -128
  105. package/src/components/vizabi-session.js +0 -66
  106. package/src/components/vizabi.js +0 -66
@@ -48,12 +48,29 @@ export class RpcError extends Error {
48
48
  constructor(outcome: RpcErrorOutcome);
49
49
  }
50
50
 
51
+ /** The dataBinder connection of one name: its binders and the MessagePort that carries them now. */
52
+ export interface MessagePortConnection {
53
+ readonly name: string;
54
+ /** `waiting` without a port, `open` with one, `closed` after the other end closed it. */
55
+ readonly state: 'waiting' | 'open' | 'closed';
56
+ readonly error: Error | null;
57
+ readonly port: MessagePort | null;
58
+ }
59
+
51
60
  /** The exchange with the server. */
52
61
  export class RpcHandler extends Handler {
53
62
  /** The server transport, or null. */
54
63
  transport: RpcTransport | null;
55
64
  /** The calls in flight, by envelope id, with the AbortController of each; written only by `call`. */
56
65
  remoteRequests: Map<string, AbortController>;
66
+ /** The dataBinder connections over a MessagePort, by name. */
67
+ connections: Map<string, MessagePortConnection>;
68
+ /** The dataBinder connection of `name`; created waiting for a port when the name is new. */
69
+ connection(name: string): MessagePortConnection;
70
+ /** Carry the binders of the connection `name` on `port`; a new port replaces the previous one. */
71
+ registerConnection(name: string, port: MessagePort): void;
72
+ /** Release the port of the connection `name`: its binders wait for the next port. */
73
+ unregisterConnection(name: string): void;
57
74
  /** Create the transport of `gramlot`: the given one, none for `false`, else the one of `gramlot.serverAdapter`. */
58
75
  constructor(gramlot: Gramlot, options: {rpcUrl: string; closeUrl: string; document: DomDocument;
59
76
  transport?: RpcTransport | false | null});
@@ -8,6 +8,7 @@ import {fromTytx, toTytx} from '@genrojs/tytx';
8
8
  import {Handler} from './handler.js';
9
9
  import {assertTransportData} from '../references.js';
10
10
  import {randomId} from '../random-id.js';
11
+ import {MessagePortConnection} from '../message-port-connection.js';
11
12
 
12
13
  /** An error outcome answered by the server inside the response envelope. */
13
14
  export class RpcError extends Error {
@@ -29,6 +30,27 @@ export class RpcHandler extends Handler {
29
30
  gramlot.serverAdapter.createTransport({rpcUrl, closeUrl, document, channel: gramlot._pageStore});
30
31
  // The AbortController of each call in flight, by envelope id; written only by `call`.
31
32
  this.remoteRequests = new Map();
33
+ // The dataBinder connections over a MessagePort, by name; written by `connection`.
34
+ this.connections = new Map();
35
+ }
36
+
37
+ /** The dataBinder connection of `name`; created waiting for a port when the name is new. */
38
+ connection(name) {
39
+ if (!this.connections.has(name)) this.connections.set(name, new MessagePortConnection(this.gramlot, name));
40
+ return this.connections.get(name);
41
+ }
42
+
43
+ /** Carry the binders of the connection `name` on `port`; a new port replaces the previous one. */
44
+ registerConnection(name, port) {
45
+ this.connection(name).setPort(port);
46
+ }
47
+
48
+ /** Release the port of the connection `name`: its binders wait for the next port. */
49
+ unregisterConnection(name) {
50
+ const connection = this.connections.get(name);
51
+ if (!connection) return;
52
+ connection.setPort(null);
53
+ if (!connection.binders.size) this.connections.delete(name);
32
54
  }
33
55
  /**
34
56
  * Send one envelope of `contentType` to `name` with `params`; resolves with the value or rejects with an
@@ -7,12 +7,22 @@ export const documentKey = (root, path) => 'd_' + [...new TextEncoder().encode(J
7
7
 
8
8
  /** Source-owned document requests; drafts and saved baselines are relative Data. */
9
9
  export class IdeDocuments {
10
+ #registrations = new Map();
10
11
  constructor(gramlot, source) {
11
12
  this.gramlot = gramlot; this.source = source;
12
13
  this.pending = new Map(); this.disposed = false;
13
14
  }
14
15
  get state() { return this.source.getRelativeData('.'); }
15
16
  get documents() { return this.state.getItem('documents'); }
17
+ /** An image document's annotations, observed at their Data path, are serialized into its content. */
18
+ #observeAnnotations(key) {
19
+ const path = this.source.absDatapath(`.documents.${key}.annotations`);
20
+ this.#registrations.set(key, this.gramlot.src.binding.router.register({path, subtree:true,
21
+ recipient:{receive:() => {
22
+ const doc = this.documents.getItem(key);
23
+ doc.setItem('content',doc.getItem('annotations').toTytx());
24
+ }}}));
25
+ }
16
26
  async open(root, path) {
17
27
  // Only registered IDE document types may create an editor tab.
18
28
  if (!/\.(?:py|js|mjs|ts|json|html|css|xml|md|markdown|sql|typ|txt|png|jpg|jpeg|webp)$/i.test(path)) return null;
@@ -26,12 +36,9 @@ export class IdeDocuments {
26
36
  const document = new Bag();
27
37
  const content = result.language === 'image' ? result.content.toTytx() : result.content;
28
38
  for (const [name,value] of Object.entries({...result, content, root, saved:content, busy:false})) document.setItem(name,value);
29
- if (result.language === 'image') {
30
- const annotations = result.content;
31
- document.setItem('annotations',annotations);
32
- annotations.subscribe('ide-annotations',{any:()=>document.setItem('content',annotations.toTytx())});
33
- }
39
+ if (result.language === 'image') document.setItem('annotations',result.content);
34
40
  this.documents.setItem(key, document);
41
+ if (result.language === 'image') this.#observeAnnotations(key);
35
42
  return key;
36
43
  }).finally(() => this.pending.delete(key));
37
44
  this.pending.set(key,{request,promise});
@@ -58,6 +65,7 @@ export class IdeDocuments {
58
65
  const promise = this.gramlot.rpc.call('data','document_create',{root,path,content},
59
66
  {signal:request.signal}).then(result => {
60
67
  if (this.disposed || request.signal.aborted) return false;
68
+ const doc = this.documents.getItem(key);
61
69
  doc.setItem('root',result.root);
62
70
  doc.setItem('path',result.path);
63
71
  doc.setItem('revision',result.revision);
@@ -65,7 +73,7 @@ export class IdeDocuments {
65
73
  doc.setItem('isNew',false);
66
74
  doc.setItem('createHidden',true);
67
75
  return true;
68
- }).finally(() => { this.pending.delete(key); if (!this.disposed) doc.setItem('busy',false); });
76
+ }).finally(() => { this.pending.delete(key); if (!this.disposed) this.documents.getItem(key).setItem('busy',false); });
69
77
  this.pending.set(key,{request,promise});
70
78
  return promise;
71
79
  }
@@ -88,17 +96,19 @@ export class IdeDocuments {
88
96
  doc.setItem('renderStatus','Generating Typst on the server…');
89
97
  const promise = this.gramlot.rpc.call('data','document_render_typst',{content},
90
98
  {signal:request.signal}).then(result => {
91
- if (this.disposed || request.signal.aborted || doc.getItem('content') !== content) return false;
99
+ if (this.disposed || request.signal.aborted) return false;
100
+ const doc = this.documents.getItem(key);
101
+ if (doc.getItem('content') !== content) return false;
92
102
  doc.setItem('typstSource',result.source);
93
103
  doc.setItem('previewHidden',false);
94
104
  doc.setItem('renderStatus','Typst generated from the current recipe.');
95
105
  return true;
96
106
  }).catch(error => {
97
- if (!this.disposed && !request.signal.aborted) doc.setItem('renderStatus',error.message);
107
+ if (!this.disposed && !request.signal.aborted) this.documents.getItem(key).setItem('renderStatus',error.message);
98
108
  return false;
99
109
  }).finally(() => {
100
110
  this.pending.delete(key);
101
- if (!this.disposed) { doc.setItem('rendering',false); doc.setItem('busy',false); }
111
+ if (!this.disposed) { const doc = this.documents.getItem(key); doc.setItem('rendering',false); doc.setItem('busy',false); }
102
112
  });
103
113
  this.pending.set(key,{request,promise});
104
114
  return promise;
@@ -120,10 +130,11 @@ export class IdeDocuments {
120
130
  ...(creating ? {} : {revision:doc.getItem('revision')})
121
131
  }, {signal:request.signal}).then(result => {
122
132
  if (this.disposed || request.signal.aborted) return false;
133
+ const doc = this.documents.getItem(key);
123
134
  doc.setItem('revision',result.revision);
124
135
  doc.setItem('saved',content);
125
136
  return true;
126
- }).finally(() => { this.pending.delete(key); if (!this.disposed) doc.setItem('busy',false); });
137
+ }).finally(() => { this.pending.delete(key); if (!this.disposed) this.documents.getItem(key).setItem('busy',false); });
127
138
  this.pending.set(key,{request,promise});
128
139
  return promise;
129
140
  }
@@ -142,11 +153,18 @@ export class IdeDocuments {
142
153
  }
143
154
  close(key, discard = false) {
144
155
  if (!this.canClose(key,discard)) return false;
156
+ this.#registrations.get(key)?.close();
157
+ this.#registrations.delete(key);
145
158
  this.documents.popNode(key);
146
159
  if (this.state.getItem('active') === key) this.state.setItem('active',this.documents.getNodes()[0]?.label ?? null);
147
160
  return true;
148
161
  }
149
- dispose() { this.disposed = true; for (const {request} of this.pending.values()) request.abort(); }
162
+ dispose() {
163
+ this.disposed = true;
164
+ for (const {request} of this.pending.values()) request.abort();
165
+ for (const registration of this.#registrations.values()) registration.close();
166
+ this.#registrations.clear();
167
+ }
150
168
  }
151
169
 
152
170
  /** Preferences only: six successfully opened roots, never document content. */
@@ -7,7 +7,7 @@ import {codeMirrorWithOptions} from './components/editor-options.js';
7
7
  /** Resolve the owner through Source ancestry, independently of DOM placement. */
8
8
  function ideContext(node) {
9
9
  for (let scope = node; scope; scope = scope.parentNode) {
10
- const context = scope.ideContext;
10
+ const context = scope._internal.ideContext;
11
11
  if (context) return context;
12
12
  }
13
13
  throw new Error('IDE operation requires a node inside a mounted IDE');
@@ -21,41 +21,43 @@ export class IdeLogic {
21
21
  const scope = node.parentNode;
22
22
  const context = {scope, documents:new IdeDocuments(this.page,scope), requested:0,
23
23
  editorPrefix:`ide_${randomId()}`, recent:new RecentWorkspaces(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage)};
24
- Object.defineProperty(scope,'ideContext',{value:context,configurable:true});
24
+ scope._internal.ideContext = context;
25
25
  const {documents, recent} = context;
26
- const state = scope.getRelativeData('.');
26
+ const state = () => scope.getRelativeData('.');
27
27
  const roots = recent.read();
28
- state.setItem('recent',recent.choices(roots));
29
- state.setItem('workspace',roots[0] ?? '');
30
- const browser = state.getItem('browser');
31
- browser.subscribe('ide-browser',{any:event => {
32
- if (event.node === browser.getNode('root')) {
33
- const root = browser.getItem('root');
34
- state.setItem('workspace',root);
35
- state.setItem('recent',recent.choices(recent.remember(root)));
36
- state.setItem('status',`Workspace: ${root}`);
37
- } else if (event.node === browser.getNode('selectedPath')) {
28
+ state().setItem('recent',recent.choices(roots));
29
+ state().setItem('workspace',roots[0] ?? '');
30
+ // Data is observed at its paths; the Bags are read when a change arrives.
31
+ const router = this.page.src.binding.router;
32
+ const statePath = scope.absDatapath('.');
33
+ const documentsPath = `${statePath}.documents`;
34
+ const registrations = [
35
+ router.register({path:`${statePath}.browser.root`, recipient:{receive:() => {
36
+ const root = state().getItem('browser.root');
37
+ state().setItem('workspace',root);
38
+ state().setItem('recent',recent.choices(recent.remember(root)));
39
+ state().setItem('status',`Workspace: ${root}`);
40
+ }}}),
41
+ router.register({path:`${statePath}.browser.selectedPath`, recipient:{receive:() => {
42
+ const browser = state().getItem('browser');
38
43
  const path = browser.getItem('selectedPath');
39
44
  const item = path === null ? null : browser.getItem('store').getNode(path);
40
45
  if (item && !item.attr.is_directory) void this.ideOpenDocument(scope,browser.getItem('root'),item.attr.path);
41
- }
42
- }});
43
- const documentBag = documents.documents;
44
- documentBag.subscribe('ide-documents',{any:event => {
45
- if (!['content','saved','busy','writable','view','isNew','path','root'].includes(event.node.label)) return;
46
- for (const pane of scope.value.getNode('frame.center.tabs').value?.getNodes() ?? []) {
47
- const key = pane.getAttr('documentKey');
48
- const doc = documents.documents.getItem(key);
49
- if (doc) {
50
- if (event.node === doc.getNode('content')) documents.invalidateRecipe(key);
51
- this.ideDocumentState(scope,key);
52
- pane.setAttr({title:`${documents.dirty(key) ? '● ' : ''}${doc.getItem('path')}`});
46
+ }}}),
47
+ router.register({path:documentsPath, subtree:true, recipient:{receive:change => {
48
+ if (!['content','saved','busy','writable','view','isNew','path','root'].includes(change.node.label)) return;
49
+ for (const pane of scope.value.getNode('frame.center.tabs').value?.getNodes() ?? []) {
50
+ const key = pane.getAttr('documentKey');
51
+ const doc = documents.documents.getItem(key);
52
+ if (doc) {
53
+ if (change.path === `${documentsPath}.${key}.content`) documents.invalidateRecipe(key);
54
+ this.ideDocumentState(scope,key);
55
+ pane.setAttr({title:`${documents.dirty(key) ? '● ' : ''}${doc.getItem('path')}`});
56
+ }
53
57
  }
54
- }
55
- }});
58
+ }}})];
56
59
  this.page.src.renderer.onDispose(context.scope,() => {
57
- browser.unsubscribe('ide-browser',{any:true});
58
- documentBag.unsubscribe('ide-documents',{any:true});
60
+ for (const registration of registrations) registration.close();
59
61
  documents.dispose();
60
62
  });
61
63
  }
@@ -69,7 +71,7 @@ export class IdeLogic {
69
71
  const context=ideContext(node), state=context.scope.getRelativeData('.');
70
72
  if (state.getItem('browser.root') !== result.root) return;
71
73
  state.setItem('upload.open',false);
72
- const controller=context.scope.value.getNode('frame.left.browser').fileSystemController;
74
+ const controller=context.scope.value.getNode('frame.left.browser')._internal.fileSystemController;
73
75
  if (controller.request) return;
74
76
  const opened=await controller.open(result.root);
75
77
  if (opened === result.root && !context.documents.disposed && state.getItem('browser.root') === result.root)
@@ -215,7 +217,7 @@ export class IdeLogic {
215
217
  if (!documents.disposed && saved) {
216
218
  state.setItem('status','File created.');
217
219
  const browser = state.getItem('browser');
218
- if (browser.getItem('root')) await context.scope.value.getNode('frame.left.browser').fileSystemController.open(browser.getItem('root'));
220
+ if (browser.getItem('root')) await context.scope.value.getNode('frame.left.browser')._internal.fileSystemController.open(browser.getItem('root'));
219
221
  }
220
222
  } catch (error) { if (!documents.disposed) state.setItem('status',error.message); }
221
223
  }
@@ -1,9 +1,9 @@
1
1
  import type {Bag, BagNode} from '@genrojs/bag';
2
- export interface IndexEntry {url: string; path: string; node: BagNode; pane: any; title: string; loading: boolean;}
2
+ export interface IndexEntry {url: string; path: string; paneLabel: string; readonly node: BagNode; readonly pane: any; title: string; loading: boolean;}
3
3
  export function mountIndexPage(renderer: any, root: any,
4
4
  onSelection?: (entries: Map<string, IndexEntry>, active: string | null) => void,
5
5
  prepareEntry?: (entry: IndexEntry) => void,
6
- options?: {state?: Bag; createEntry?: (entry: IndexEntry) => Promise<void>;
6
+ options?: {state?: string; createEntry?: (entry: IndexEntry) => Promise<void>;
7
7
  onLoad?: (url: string, status: 'loading' | 'ready' | 'error' | 'cancelled', error?: Error) => void}): {entries: Map<string, IndexEntry>; dispose(): void};
8
8
  export class IndexLogic {indexMount(node: any): void;}
9
9
  export const THEME_READY: string;
@@ -1,25 +1,32 @@
1
1
  /* @ts-self-types="./index-page-runtime.d.ts" */
2
2
  import {Bag} from '@genrojs/bag';
3
- import {sourceTarget} from '@genrojs/builders';
4
3
 
5
4
  /** Coordinate a declared navigation Bag and tabContainer through Source and Data.
6
5
  * Region contents, drawer presentation, themes and application controls belong to the Page.
7
6
  */
8
7
  export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEntry = () => {},
9
- {state = root.getRelativeData('.'), createEntry = null,
8
+ {state = root.absDatapath('.'), createEntry = null,
10
9
  onLoad = () => {}} = {}) {
11
- const navigation = state.getItem('navigation');
12
- if (!(navigation instanceof Bag)) throw new TypeError('IndexPage navigation must be a Bag');
13
- const tabs = root.value.getNode('frame.center.tabs');
10
+ // The coordinator keeps the Data path of its state and its own Source node; every Bag and every
11
+ // other node is read at its address when it is used.
12
+ if (typeof state !== 'string' || !state) throw new TypeError('IndexPage state must be a Data path');
13
+ const data = renderer.binding.gramlot.data;
14
+ const read = name => data.getItem(`${state}.${name}`);
15
+ const write = (name, value) => data.setItem(`${state}.${name}`, value);
16
+ const navigation = () => read('navigation');
17
+ if (!(navigation() instanceof Bag)) throw new TypeError('IndexPage navigation must be a Bag');
18
+ const tabs = () => root.value.getNode('frame.center.tabs');
14
19
  const builder = root.builder;
15
20
  const entries = new Map();
16
21
  const context = {entries, disposed: false, selecting: false, sequence: 0, requested: null};
17
- Object.defineProperty(root, 'indexContext', {value: context, configurable: true});
18
- const opened = state.getItem('opened');
19
- for (const record of opened.getNodes()) {
22
+ root._internal.indexContext = context;
23
+ // `pane` and `node` resolve the tab panel and the navigation node by label and path on each access.
24
+ const createRecord = ({url, path, title, paneLabel, loading}) => ({url, path, title, paneLabel, loading,
25
+ get pane() { return tabs().value?.getNode(this.paneLabel) ?? null; },
26
+ get node() { return navigation().getNode(this.path); }});
27
+ for (const record of read('opened').getNodes()) {
20
28
  const {url, path, title} = record.attr;
21
- const pane = tabs.value.getNode(record.label);
22
- const entry = {url, path, title, pane, node: navigation.getNode(path), loading: false};
29
+ const entry = createRecord({url, path, title, paneLabel: record.label, loading: false});
23
30
  prepareEntry(entry);
24
31
  entries.set(url, entry);
25
32
  context.sequence++;
@@ -37,11 +44,14 @@ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEn
37
44
  if (context.disposed) return;
38
45
  context.selecting = true;
39
46
  try {
40
- state.setItem('active', entry.url);
41
- state.setItem('navigationSelection', entry.path);
47
+ write('active', entry.url);
48
+ write('navigationSelection', entry.path);
42
49
  onSelection(entries, entry.url);
43
50
  } finally { context.selecting = false; }
44
51
  };
52
+ const forget = paneLabel => {
53
+ if (read('opened').getNode(paneLabel)) read('opened').popNode(paneLabel);
54
+ };
45
55
  // Includes validation and preparation errors before the asynchronous load starts.
46
56
  function requestSelection(path) {
47
57
  void select(path).catch(error => {
@@ -49,7 +59,7 @@ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEn
49
59
  });
50
60
  }
51
61
  async function select(path) {
52
- const node = navigation.getNode(path);
62
+ const node = navigation().getNode(path);
53
63
  if (!node) throw new Error(`Unknown index navigation path: ${path}`);
54
64
  const url = node.attr.url;
55
65
  if (url == null) return; // A folder may have children without its own page.
@@ -61,11 +71,13 @@ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEn
61
71
  activate(entry);
62
72
  return;
63
73
  }
64
- while (tabs.value !== null && tabs.value.getNode(`page${context.sequence}`)) context.sequence++;
65
- const pane = sourceTarget(builder.wrapSource(tabs).contentPane({node_label: `page${context.sequence++}`,
66
- title: node.attr.title ?? node.label, pageName: url, height: '100%', closable: true}));
67
- const previous = state.getItem('active');
68
- entry = {url, path, node, pane, title: node.attr.title ?? node.label, loading: true};
74
+ while (tabs().value !== null && tabs().value.getNode(`page${context.sequence}`)) context.sequence++;
75
+ const paneLabel = `page${context.sequence++}`;
76
+ const title = node.attr.title ?? node.label;
77
+ builder.wrapSource(tabs()).contentPane({node_label: paneLabel,
78
+ title, pageName: url, height: '100%', closable: true});
79
+ const previous = read('active');
80
+ entry = createRecord({url, path, title, paneLabel, loading: true});
69
81
  entries.set(url, entry);
70
82
  try {
71
83
  notifyLoad(entry, 'loading');
@@ -75,20 +87,21 @@ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEn
75
87
  if (createEntry) await createEntry(entry);
76
88
  else {
77
89
  const selection = new Bag();
78
- selection.setItem(node.label, null, {...node.attr});
79
- const mounted = await renderer.binding.gramlot.src.remoteSource(pane, 'index_panel', {selection});
90
+ const selected = entry.node;
91
+ selection.setItem(selected.label, null, {...selected.attr});
92
+ const mounted = await renderer.binding.gramlot.src.remoteSource(entry.pane, 'index_panel', {selection});
80
93
  if (!mounted) throw new Error('Panel loading was cancelled');
81
94
  }
82
95
  if (context.disposed || entries.get(url) !== entry) return;
83
- opened.setItem(pane.label, null, {url, path: entry.path, title: entry.title});
96
+ read('opened').setItem(paneLabel, null, {url, path: entry.path, title: entry.title});
84
97
  prepareEntry(entry);
85
98
  } catch (error) {
86
99
  if (context.disposed || entries.get(url) !== entry) return;
87
100
  try {
88
101
  renderer.binding.reportError(error, 'Page could not be opened');
89
102
  entries.delete(url);
90
- if (opened.getNode(pane.label)) opened.popNode(pane.label);
91
- if (pane.parentBag) pane.parentBag.popNode(pane.label);
103
+ forget(paneLabel);
104
+ if (entry.pane) tabs().value.popNode(paneLabel);
92
105
  if (!context.disposed && context.requested === url) {
93
106
  const restored = entries.get(previous);
94
107
  context.requested = restored?.url ?? null;
@@ -96,8 +109,8 @@ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEn
96
109
  else {
97
110
  context.selecting = true;
98
111
  try {
99
- state.setItem('active', null);
100
- state.setItem('navigationSelection', null);
112
+ write('active', null);
113
+ write('navigationSelection', null);
101
114
  onSelection(entries, null);
102
115
  } finally { context.selecting = false; }
103
116
  }
@@ -109,56 +122,62 @@ export function mountIndexPage(renderer, root, onSelection = () => {}, prepareEn
109
122
  finishLoad(entry, 'ready');
110
123
  if (!context.disposed && entries.get(url) === entry && context.requested === url) activate(entry);
111
124
  }
125
+ // Source structure: a panel removed from the tabs, by the user or by the application, closes its entry.
126
+ // The subscription is on the Source root; the tabs are recognised by their path below the coordinator.
112
127
  const sourceSubscription = `${root.getAttr('id')}-page-close`;
113
- root.value.subscribe(sourceSubscription, {any: event => {
114
- if (event.evt !== 'del') return;
115
- const entry = [...entries.values()].find(candidate => candidate.pane === event.node);
128
+ const source = builder.source;
129
+ const tabsPath = [...root.fullpath.split('.').slice(1), 'frame', 'center', 'tabs'].join('.');
130
+ source.subscribe(sourceSubscription, {any: event => {
131
+ if (event.evt !== 'del' || (event.pathlist ?? []).join('.') !== tabsPath) return;
132
+ const entry = [...entries.values()].find(candidate => candidate.paneLabel === event.node.label);
116
133
  if (!entry) return;
117
- const {url, pane} = entry;
134
+ const {url, paneLabel} = entry;
118
135
  if (context.disposed || renderer.disposed || entries.get(url) !== entry) return;
119
136
  entries.delete(url);
120
- if (opened.getNode(pane.label)) opened.popNode(pane.label);
137
+ forget(paneLabel);
121
138
  try {
122
- if (state.getItem('active') === url) {
139
+ if (read('active') === url) {
123
140
  const next = [...entries.values()].at(-1);
124
141
  context.requested = next?.url ?? null;
125
142
  if (next) activate(next);
126
143
  else {
127
144
  context.selecting = true;
128
- try { state.setItem('active', null); state.setItem('navigationSelection', null); onSelection(entries, null); }
145
+ try { write('active', null); write('navigationSelection', null); onSelection(entries, null); }
129
146
  finally { context.selecting = false; }
130
147
  }
131
- } else onSelection(entries, state.getItem('active'));
148
+ } else onSelection(entries, read('active'));
132
149
  } finally { finishLoad(entry, 'cancelled'); }
133
150
  }});
134
- const subscription = `${root.getAttr('id')}-selection`;
135
- state.subscribe(subscription, {any: event => {
136
- if (context.selecting || context.disposed) return;
137
- if (event.node === state.getNode('navigationSelection')) {
138
- const path = state.getItem('navigationSelection');
151
+ // Data: a change at navigationSelection or active, written by the tree or the tabs, selects a page.
152
+ const router = renderer.binding.router;
153
+ const registrations = [
154
+ router.register({path: `${state}.navigationSelection`, recipient: {receive: () => {
155
+ if (context.selecting || context.disposed) return;
156
+ const path = read('navigationSelection');
139
157
  if (path !== null) requestSelection(path);
140
- } else if (event.node === state.getNode('active')) {
141
- const entry = entries.get(state.getItem('active'));
158
+ }}}),
159
+ router.register({path: `${state}.active`, recipient: {receive: () => {
160
+ if (context.selecting || context.disposed) return;
161
+ const entry = entries.get(read('active'));
142
162
  if (entry) { context.requested = entry.url; activate(entry); }
143
- }
144
- }});
163
+ }}})];
145
164
  const dispose = () => {
146
165
  if (context.disposed) return;
147
166
  context.disposed = true;
148
- state.unsubscribe(subscription, {any: true});
149
- root.value.unsubscribe(sourceSubscription, {any: true});
167
+ for (const registration of registrations) registration.close();
168
+ source.unsubscribe(sourceSubscription, {any: true});
150
169
  for (const entry of entries.values()) if (entry.loading) {
151
- if (entry.pane.parentBag) entry.pane.parentBag.popNode(entry.pane.label);
170
+ if (entry.pane) tabs().value.popNode(entry.paneLabel);
152
171
  finishLoad(entry, 'cancelled');
153
172
  }
154
173
  entries.clear();
155
- if (root.indexContext === context) delete root.indexContext;
174
+ if (root._internal.indexContext === context) delete root._internal.indexContext;
156
175
  };
157
176
  context.dispose = dispose;
158
177
  renderer.onDispose(root, dispose);
159
- const active = entries.get(state.getItem('active'));
178
+ const active = entries.get(read('active'));
160
179
  if (active) activate(active);
161
- else if (state.getItem('navigationSelection') !== null) requestSelection(state.getItem('navigationSelection'));
180
+ else if (read('navigationSelection') !== null) requestSelection(read('navigationSelection'));
162
181
  return context;
163
182
  }
164
183
 
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The client side of the dataBinder protocol over one MessagePort, registered by name on
3
+ * `gramlot.rpc`. The other end is a store side (`MessagePortStore`) that answers as a `PageStore`.
4
+ *
5
+ * @module
6
+ */
7
+ import {Bag} from '@genrojs/bag';
8
+ import {fromTytx, toTytx} from '@genrojs/tytx';
9
+
10
+ /** One message as the TYTX text of a Bag of its fields, as `MessagePortStore.post` sends it. */
11
+ export function messageText(message) {
12
+ const wire = new Bag();
13
+ for (const [name, value] of Object.entries(message)) {
14
+ if (value !== undefined) wire.setItem(name, value);
15
+ }
16
+ return toTytx(wire);
17
+ }
18
+
19
+ /** The dataBinder connection of one name: its binders and the MessagePort that carries them now. */
20
+ export class MessagePortConnection {
21
+ #port = null;
22
+ // A protocol error is reported once per port; `closed` is a state and reports nothing.
23
+ #reported = false;
24
+
25
+ constructor(gramlot, name) {
26
+ this.gramlot = gramlot;
27
+ this.name = name;
28
+ this.binders = new Map();
29
+ // `waiting` without a port, `open` with one, `closed` after the other end closed it.
30
+ this.state = 'waiting';
31
+ this.error = null;
32
+ }
33
+
34
+ get port() { return this.#port; }
35
+
36
+ /**
37
+ * Carry the binders on `port`, or on none for null. The binders leave the previous port and
38
+ * subscribe again on the new one: each snapshot replaces the branch of its binder.
39
+ */
40
+ setPort(port) {
41
+ if (port === this.#port) return;
42
+ this.#release();
43
+ this.#port = port;
44
+ this.error = null;
45
+ this.#reported = false;
46
+ this.state = port ? 'open' : 'waiting';
47
+ if (!port) return;
48
+ port.addEventListener('message', this.#receive);
49
+ port.start();
50
+ for (const binder of this.binders.values()) this.#subscribe(binder);
51
+ }
52
+
53
+ #release() {
54
+ const port = this.#port;
55
+ if (!port) return;
56
+ port.removeEventListener('message', this.#receive);
57
+ for (const binder of this.binders.values()) {
58
+ // Local writes wait for the snapshot of the next port.
59
+ binder.ready = false;
60
+ if (this.state === 'open') port.postMessage(messageText({op: 'unsubscribe', binderId: binder.id}));
61
+ }
62
+ this.#port = null;
63
+ }
64
+
65
+ register(binder) {
66
+ this.binders.set(binder.id, binder);
67
+ if (this.state === 'open') this.#subscribe(binder);
68
+ }
69
+
70
+ #subscribe(binder) {
71
+ this.#port.postMessage(messageText({op: 'subscribe', binderId: binder.id, path: binder.serverPath}));
72
+ }
73
+
74
+ unregister(binder) {
75
+ if (!this.binders.delete(binder.id)) return;
76
+ if (this.state === 'open') this.#port.postMessage(messageText({op: 'unsubscribe', binderId: binder.id}));
77
+ }
78
+
79
+ send(message) {
80
+ if (this.state !== 'open') throw new Error(`Connection '${this.name}' is not open`);
81
+ this.#port.postMessage(messageText(message));
82
+ }
83
+
84
+ #receive = event => {
85
+ const message = fromTytx(event.data).asDict();
86
+ if (message.op === 'snapshot' || message.op === 'change') this.binders.get(message.binderId)?.apply(message);
87
+ else if (message.op === 'closed') this.#closed();
88
+ else if (message.op === 'error' && !this.#reported) {
89
+ this.#reported = true;
90
+ this.gramlot.src.binding.reportError(new Error(`Connection '${this.name}': ${message.error}`), 'dataBinder');
91
+ }
92
+ };
93
+
94
+ /** The other end closed: the binders stop and their copies keep the last values. */
95
+ #closed() {
96
+ this.state = 'closed';
97
+ this.#release();
98
+ this.error = new Error(`Connection '${this.name}' was closed by the other end`);
99
+ }
100
+ }