@gramlot/gramlot 0.3.24 → 0.3.26

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 (131) hide show
  1. package/dist/components/editors/__init__.py +2 -2
  2. package/dist/components/editors/assets/collection.js +20 -19
  3. package/dist/components/editors/assets/index.js +1 -1
  4. package/dist/components/editors/assets/modules/chunk-74O4WKIV.js +1 -0
  5. package/dist/components/editors/assets/modules/{code-mirror-engine-QX4A5FVO.js → code-mirror-engine-RWQTR5G5.js} +29 -29
  6. package/dist/components/editors/assets/modules/{jodit-engine-MMSPIWM7.js → jodit-engine-MTSA4GZ3.js} +292 -292
  7. package/dist/components/editors/assets/modules/markdown-document-VFC23FAY.js +1 -0
  8. package/dist/components/editors/assets/modules/{prose-mirror-engine-IXTRTG6B.js → prose-mirror-engine-GMZPJPNN.js} +13 -13
  9. package/dist/components/grid/__init__.py +3 -2
  10. package/dist/components/grid/assets/collection.js +68 -17
  11. package/dist/components/grid/assets/index.js +1 -1
  12. package/dist/components/grid/grammar.json +57 -1
  13. package/dist/components/grouplets/__init__.py +2 -2
  14. package/dist/components/grouplets/assets/collection.js +3 -20
  15. package/dist/components/grouplets/assets/index.js +1 -1
  16. package/dist/components/grouplets/assets/modules/chunk-BLMUM44K.js +1 -0
  17. package/dist/components/grouplets/assets/modules/markdown-document-YWNZTOKK.js +1 -0
  18. package/dist/components/inputs/__init__.py +1 -1
  19. package/dist/components/inputs/assets/collection.js +59 -34
  20. package/dist/components/inputs/assets/index.js +1 -1
  21. package/dist/components/inputs/grammar.json +64 -0
  22. package/dist/components/layout/__init__.py +1 -1
  23. package/dist/components/layout/assets/collection.js +67 -57
  24. package/dist/components/layout/assets/index.js +1 -1
  25. package/dist/components/layout/grammar.json +35 -0
  26. package/dist/components/selection_trial/__init__.py +1 -1
  27. package/dist/components/selection_trial/assets/collection.js +3 -3
  28. package/dist/components/selection_trial/assets/index.js +1 -1
  29. package/dist/components/selection_trial/grammar.json +35 -0
  30. package/dist/components/tree/__init__.py +1 -1
  31. package/dist/components/tree/assets/collection.js +26 -23
  32. package/dist/components/tree/assets/index.js +1 -1
  33. package/dist/components/tree/grammar.json +341 -1
  34. package/dist/components/uploads/__init__.py +13 -0
  35. package/dist/components/uploads/assets/collection.js +67 -0
  36. package/dist/components/uploads/assets/index.js +3 -0
  37. package/dist/components/uploads/commands.json +7 -0
  38. package/dist/components/uploads/grammar.json +789 -0
  39. package/dist/{components/editors/assets/modules/chunk-OCFLP2K4.js → gramlot-markdown.js} +12 -12
  40. package/dist/gramlot.js +4910 -566
  41. package/dist/gramlot.min.js +1587 -43
  42. package/dist/runtime-notices.json +28 -0
  43. package/package.json +4 -2
  44. package/src/binding/grid-struct.js +1 -1
  45. package/src/binding/providers.js +4 -1
  46. package/src/binding/remote-resolver.js +1 -8
  47. package/src/binding/runtime.js +40 -1
  48. package/src/binding/validation-context.js +40 -0
  49. package/src/browser-camera-provider.d.ts +8 -0
  50. package/src/browser-camera-provider.js +104 -0
  51. package/src/builder/source.js +13 -2
  52. package/src/components/attachment-manager.js +160 -0
  53. package/src/components/bases.js +17 -6
  54. package/src/components/border-container.js +86 -8
  55. package/src/components/buttons.js +11 -1
  56. package/src/components/choice-editor.js +20 -7
  57. package/src/components/database-choices.js +4 -2
  58. package/src/components/editing-status-styles.js +26 -0
  59. package/src/components/editing-status.js +115 -0
  60. package/src/components/field-state.js +37 -58
  61. package/src/components/grid-cell-editor.js +181 -0
  62. package/src/components/grid-grammar.json +21 -0
  63. package/src/components/grid-structure.js +2 -1
  64. package/src/components/grid-styles.js +51 -1
  65. package/src/components/grid.js +87 -10
  66. package/src/components/grouplet-card.js +11 -3
  67. package/src/components/html-preview.js +17 -4
  68. package/src/components/image-crop-dialog.js +272 -0
  69. package/src/components/image-crop.js +79 -0
  70. package/src/components/image-uploader.js +252 -0
  71. package/src/components/inputs.js +2 -1
  72. package/src/components/jodit-engine.js +1 -1
  73. package/src/components/markdown-document.js +2 -2
  74. package/src/components/screen-capture.js +43 -0
  75. package/src/components/selected-container.js +6 -2
  76. package/src/components/tree.js +416 -17
  77. package/src/components/typed-editor.js +19 -9
  78. package/src/components/upload-engine.js +156 -0
  79. package/src/components/uploader.js +208 -0
  80. package/src/components/uploads.js +7 -0
  81. package/src/editing-session.d.ts +25 -0
  82. package/src/editing-session.js +396 -0
  83. package/src/experiments/selection-trial.js +18 -2
  84. package/src/format.js +22 -7
  85. package/src/gramlot.d.ts +2 -0
  86. package/src/gramlot.js +2 -1
  87. package/src/handlers/device-handler.d.ts +2 -1
  88. package/src/handlers/rpc-handler.d.ts +3 -3
  89. package/src/index-page-styles.js +1 -0
  90. package/src/index.d.ts +13 -0
  91. package/src/index.js +13 -0
  92. package/src/inout.d.ts +2 -0
  93. package/src/inout.js +6 -0
  94. package/src/markdown-loader.d.ts +1 -0
  95. package/src/markdown-loader.js +4 -0
  96. package/src/markdown.d.ts +1 -0
  97. package/src/markdown.js +2 -0
  98. package/src/media-frame.js +9 -0
  99. package/src/renderer/attributes.js +7 -1
  100. package/src/renderer/gramlot-renderer.d.ts +2 -0
  101. package/src/renderer/gramlot-renderer.js +31 -2
  102. package/src/server/assets.d.ts +1 -1
  103. package/src/server/assets.js +1 -1
  104. package/src/server/gramlot-server.d.ts +8 -1
  105. package/src/server/gramlot-server.js +83 -7
  106. package/src/server/index.d.ts +2 -0
  107. package/src/server/index.js +2 -0
  108. package/src/server/page-base.js +17 -4
  109. package/src/server/page.d.ts +13 -1
  110. package/src/server/page.js +6 -0
  111. package/src/server/source-import.d.ts +2 -0
  112. package/src/server/source-import.js +31 -0
  113. package/src/server/upload.d.ts +20 -0
  114. package/src/server/upload.js +142 -0
  115. package/src/server/visual-editor.d.ts +11 -0
  116. package/src/server/visual-editor.js +149 -0
  117. package/src/source-picker.d.ts +9 -0
  118. package/src/source-picker.js +57 -0
  119. package/src/tree-store.d.ts +24 -0
  120. package/src/tree-store.js +193 -0
  121. package/src/validation-run.js +50 -0
  122. package/src/view/button.js +8 -5
  123. package/src/view/controls.js +9 -42
  124. package/src/view/html.js +10 -2
  125. package/src/visual-editor-icons.js +10 -0
  126. package/src/visual-editor.d.ts +56 -0
  127. package/src/visual-editor.js +844 -0
  128. package/themes/gramlot-base/theme.css +99 -0
  129. package/dist/components/editors/assets/modules/chunk-MMJXUHRQ.js +0 -3
  130. package/src/form-state.d.ts +0 -20
  131. package/src/form-state.js +0 -198
@@ -0,0 +1,396 @@
1
+ /* @ts-self-types="./editing-session.d.ts" */
2
+ import {Bag} from '@genrojs/bag';
3
+ import {fromTytx, toTytx} from '@genrojs/tytx';
4
+ import {ValidationRun} from './validation-run.js';
5
+ import {validationContext} from './binding/validation-context.js';
6
+
7
+ // TYTX is the existing typed snapshot format (dates, Decimal and nested Bags included).
8
+ const copy = value => fromTytx(toTytx(value));
9
+ const same = (a, b) => toTytx(a) === toTytx(b);
10
+ const fieldPath = node => node.absDatapath(node.getAttr('value'));
11
+ const encoded = path => encodeURIComponent(path).replaceAll('.', '%2E');
12
+ const key = node => encoded(fieldPath(node));
13
+ const contribution = (node, kind) => encoded(node.fullpath) + ":" + kind;
14
+
15
+ /** Source-owned local editing lifecycle shared by forms and grids. Logic and DOM never own the registers. */
16
+ export class EditingSession {
17
+ constructor(node, runtime, path = node.absDatapath('.')) {
18
+ this.node = node;
19
+ this.runtime = runtime;
20
+ this.registers = new Bag();
21
+ this.validationQueue = new Set();
22
+ this.fields = new Map(); // mounted presentations only
23
+ this.validations = new Map(); // semantic fields, independent of their views
24
+ this.disposed = false;
25
+ this.scheduled = false;
26
+ this.writing = 0;
27
+ this.path = path;
28
+ this.retainedFields = new Map();
29
+ this.listeners = new Set();
30
+ this.navigators = new Set();
31
+ if (!(this.data instanceof Bag)) throw new TypeError('A form requires a Bag at its datapath.');
32
+ this.registers.setItem('baseline', copy(this.data));
33
+ for (const name of ['changes', 'errors', 'pending', 'drafts']) this.registers.setItem(name, new Bag());
34
+ this.subscription = runtime.router.register({path:this.path, recipient:this, subtree:true});
35
+ runtime.bindingFor(node).track(() => this.dispose());
36
+ }
37
+ rebind() {
38
+ const path = this.node.absDatapath('.');
39
+ if (path === this.path) return;
40
+ if (!(this.data instanceof Bag)) throw new TypeError('A form requires a Bag at its datapath.');
41
+ this.subscription.close();
42
+ for (const name of ['errors','pending','drafts']) this.registers.setItem(name,new Bag());
43
+ this.path = path;
44
+ this.subscription = this.runtime.router.register({path, recipient:this, subtree:true});
45
+ this.updateChanges();
46
+ for (const adapter of this.fields.values()) {
47
+ adapter.element.cancelValidation();
48
+ this.clearDraft(adapter.node);
49
+ this.scheduleValidation(adapter);
50
+ }
51
+ }
52
+ get data() { return this.runtime.gramlot.data.getItem(this.path); }
53
+ subscribe(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
54
+ /** Read-only reports derived from the canonical registers, never a second journal. */
55
+ get errorEntries() {
56
+ return this.registers.getItem('errors').getNodes().map(node => ({
57
+ path:decodeURIComponent(node.label),
58
+ message:node.value.getNodes().map(part => part.value).join('\n')
59
+ }));
60
+ }
61
+ get changeEntries() {
62
+ const entries = [];
63
+ for (const node of this.registers.getItem('changes').getNodes()) {
64
+ const change = node.value;
65
+ const path = [this.path,change.getItem('path')].filter(Boolean).join('.');
66
+ const existed = change.getItem('existed'), exists = change.getItem('exists');
67
+ const previous = change.getItem('previous'), current = change.getItem('current');
68
+ if (!existed || !exists || !same(previous,current)) entries.push({path,previous,current,existed,exists});
69
+ if (existed && exists) {
70
+ const before = change.getItem('previousAttributes'), after = change.getItem('currentAttributes');
71
+ for (const attr of new Set([...before.getNodes(),...after.getNodes()].map(node => node.label))) {
72
+ const had = before.getNode(attr) !== null, has = after.getNode(attr) !== null;
73
+ if (had !== has || !same(before.getItem(attr),after.getItem(attr))) entries.push({
74
+ path:path+'?'+attr, previous:before.getItem(attr), current:after.getItem(attr), existed:had, exists:has
75
+ });
76
+ }
77
+ }
78
+ }
79
+ return entries;
80
+ }
81
+ registerNavigator(navigator) {
82
+ this.navigators.add(navigator);
83
+ return () => this.navigators.delete(navigator);
84
+ }
85
+ focusField(path) {
86
+ if (this.disposed) return false;
87
+ for (const adapter of this.fields.values()) {
88
+ if (fieldPath(adapter.node) === path && adapter.element.isConnected) {
89
+ adapter.element.control.focus();
90
+ return true;
91
+ }
92
+ }
93
+ for (const navigate of this.navigators) if (navigate(path)) return true;
94
+ return false;
95
+ }
96
+ retainField(path) { this.retainedFields.set(path, (this.retainedFields.get(path) ?? 0) + 1); }
97
+ releaseField(path) {
98
+ const count = this.retainedFields.get(path);
99
+ if (count > 1) { this.retainedFields.set(path, count - 1); return; }
100
+ this.retainedFields.delete(path);
101
+ if ([...this.validations.values()].some(field => field.path === path)) return;
102
+ for (const name of ['errors', 'pending', 'drafts']) {
103
+ const bag = this.registers.getItem(name), label = encoded(path);
104
+ if (bag.getNode(label)) bag.popNode(label);
105
+ }
106
+ this.notify();
107
+ }
108
+ fieldStatus(path) {
109
+ const label = encoded(path);
110
+ return {error:this.registers.getItem('errors').getItem(label),
111
+ pending:this.registers.getItem('pending').getItem(label),
112
+ draft:this.registers.getItem('drafts').getItem(label)};
113
+ }
114
+ get status() {
115
+ const dirty = this.registers.getItem('changes').length > 0;
116
+ const pending = this.registers.getItem('pending').length > 0;
117
+ const invalid = this.registers.getItem('errors').length > 0;
118
+ const incomplete = this.registers.getItem('drafts').length > 0;
119
+ return {dirty, pending, valid:!invalid && !incomplete, canSave:dirty && !invalid && !incomplete && !pending,
120
+ status:invalid ? 'error' : pending || incomplete ? 'pending' : dirty ? 'changed' : 'ok'};
121
+ }
122
+ register(adapter) {
123
+ const node = adapter.node;
124
+ this.fields.set(node, adapter);
125
+ let field = this.validations.get(node);
126
+ if (!field) {
127
+ field = {node, binding:adapter.binding, context:validationContext(adapter.binding), run:new ValidationRun(),
128
+ execute:adapter.element.validationExecutor, checkValue:adapter.element.validationValueCheck(), path:fieldPath(node), rules:null, value:undefined, target:null, result:null, selection:adapter.element.validationSelection()};
129
+ this.validations.set(node,field);
130
+ adapter.binding.editingSession = this;
131
+ field.release = adapter.binding.track(() => this.forgetField(node));
132
+ this.refreshField(node);
133
+ }
134
+ this.schedule(() => {
135
+ if (this.fields.get(node) !== adapter) return;
136
+ const draft = this.registers.getItem('drafts').getNode(key(node));
137
+ if (draft) { node.formDraft = draft.value; adapter.element.restoreFormDraft(draft.value); }
138
+ if (field.result) adapter.element.presentValidation(field.result);
139
+ const errors = this.registers.getItem('errors').getItem(key(node));
140
+ if (errors) adapter.element.error(errors.getNodes().map(n => n.value).join('\n'));
141
+ adapter.element.setFieldState({invalid:Boolean(errors), pending:Boolean(this.fieldStatus(field.path).pending)});
142
+ });
143
+ return () => { this.fields.delete(node); };
144
+ }
145
+ forgetField(node) {
146
+ const field = this.validations.get(node);
147
+ if (!field) return;
148
+ field.run.cancel(); field.release();
149
+ if (field.binding.editingSession === this) field.binding.editingSession = null;
150
+ this.validations.delete(node); this.validationQueue.delete(node);
151
+ for (const name of ['errors','pending']) {
152
+ const parts = this.registers.getItem(name).getItem(encoded(field.path));
153
+ if (parts) {
154
+ for (const part of [...parts.getNodes()]) if (part.label.startsWith(encoded(node.fullpath) + ':')) parts.popNode(part.label);
155
+ if (!parts.length) this.registers.getItem(name).popNode(encoded(field.path));
156
+ }
157
+ }
158
+ if (![...this.validations.values()].some(other => other.path === field.path)) {
159
+ const drafts = this.registers.getItem('drafts');
160
+ if (drafts.getNode(encoded(field.path))) drafts.popNode(encoded(field.path));
161
+ }
162
+ delete node.formDraft;
163
+ this.notify();
164
+ }
165
+ refreshField(node) {
166
+ const field = this.validations.get(node);
167
+ if (!field || this.disposed || this.writing) return;
168
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
169
+ const resolved = this.runtime.renderer.evaluateExpressions(node,attrs);
170
+ const rules = Object.fromEntries(Object.entries(resolved).filter(([name]) => name.startsWith('validate_')));
171
+ const path = fieldPath(node), target = this.runtime.gramlot.data.getNode(path.split('?')[0]);
172
+ const value = node.getRelativeData(node.getAttr('value'));
173
+ const dataChanged = field.path !== path || field.target !== target || !same(field.value,value);
174
+ if (!dataChanged && same(field.rules,rules)) return;
175
+ this.cancelValidation(node);
176
+ if (field.path !== path) {
177
+ for (const name of ['errors','pending','drafts']) {
178
+ const bag = this.registers.getItem(name);
179
+ if (bag.getNode(encoded(field.path))) bag.popNode(encoded(field.path));
180
+ }
181
+ }
182
+ Object.assign(field,{path,target,value,rules,result:null});
183
+ if (dataChanged) this.clearDraft(node);
184
+ this.scheduleField(node);
185
+ }
186
+ cancelValidation(node) {
187
+ this.validations.get(node)?.run.cancel();
188
+ this.validationQueue.delete(node);
189
+ this.pendingPart(node,'validation',null);
190
+ }
191
+ writeCandidate(node,value) {
192
+ this.clearDraft(node);
193
+ this.writing++;
194
+ try { this.runtime.renderer.html.writeParameter(node,'value',value); }
195
+ finally { this.writing--; }
196
+ const field = this.validations.get(node);
197
+ if (field) {
198
+ field.value = node.getRelativeData(node.getAttr('value'));
199
+ field.target = this.runtime.gramlot.data.getNode(field.path.split('?')[0]);
200
+ }
201
+ for (const other of this.validations.keys()) if (other !== node) this.refreshField(other);
202
+ }
203
+ validateCandidate(node,value,selection) {
204
+ this.cancelValidation(node);
205
+ this.writeCandidate(node,value);
206
+ const field = this.validations.get(node);
207
+ field.selection = selection;
208
+ return this.validateField(node,false);
209
+ }
210
+ scheduleField(node) {
211
+ if (this.disposed || !this.validations.has(node) || this.validationQueue.has(node)) return;
212
+ if (this.registers.getItem('drafts').getNode(key(node))) return;
213
+ this.validationQueue.add(node);
214
+ this.pendingPart(node,'validation','scheduled');
215
+ this.schedule(() => { if (this.validationQueue.delete(node)) this.validateField(node); });
216
+ }
217
+ scheduleValidation(adapter) {
218
+ this.refreshField(adapter.node);
219
+ const field = this.validations.get(adapter.node);
220
+ if (field && !field.result && !field.run.controller) this.scheduleField(adapter.node);
221
+ }
222
+ validateField(node, refreshSelection = true) {
223
+ const field = this.validations.get(node);
224
+ if (!field || this.disposed || field.binding.closed) return;
225
+ this.validationQueue.delete(node);
226
+ if (this.registers.getItem('drafts').getNode(key(node))) return;
227
+ if (this.registers.getItem('pending').getItem(key(node))?.getItem(contribution(node,'selection'))) return;
228
+ const value = node.getRelativeData(node.getAttr('value'));
229
+ const adapter = this.fields.get(node);
230
+ if (refreshSelection && adapter) field.selection = adapter.element.validationSelection();
231
+ const selection = field.selection;
232
+ const target = field.target;
233
+ const current = field.context.validationCurrent();
234
+ return field.run.start(value,field.rules,{...field.context,
235
+ validationCurrent:() => () => !this.disposed && current() && this.validations.get(node) === field
236
+ && this.runtime.gramlot.data.getNode(field.path.split('?')[0]) === target,
237
+ selection
238
+ },field.execute,outcome => {
239
+ if (outcome.ok) {
240
+ try { field.checkValue(outcome.value,value); }
241
+ catch (error) { outcome.ok = false; outcome.result.error = error.message; }
242
+ }
243
+ this.result(node,outcome.result);
244
+ field.result = outcome.result;
245
+ if (outcome.ok) this.writeCandidate(node,outcome.value);
246
+ const mounted = this.fields.get(node);
247
+ if (mounted) mounted.element.presentValidation(outcome.result);
248
+ field.context.finishValidation(outcome);
249
+ },() => {
250
+ this.pendingPart(node,'validation','active');
251
+ this.fields.get(node)?.element.setFieldState({pending:true});
252
+ });
253
+ }
254
+ remove(name, node) {
255
+ const bag = this.registers.getItem(name), label = key(node);
256
+ if (bag.getNode(label)) bag.popNode(label);
257
+ }
258
+ set(name, node, value) {
259
+ if (value == null) this.remove(name,node);
260
+ else this.registers.getItem(name).setItem(key(node), value);
261
+ this.notify();
262
+ }
263
+ draft(node, text) {
264
+ this.cancelValidation(node);
265
+ node.formDraft = text;
266
+ this.set('drafts',node,text);
267
+ }
268
+ clearDraft(node) {
269
+ delete node.formDraft;
270
+ this.set('drafts',node,null);
271
+ this.issue(node,'parse',null);
272
+ }
273
+ result(node, result) {
274
+ this.pendingPart(node,'validation',null);
275
+ this.issue(node,'validation',result.error || null);
276
+ }
277
+ part(register, node, kind, value) {
278
+ kind = contribution(node,kind);
279
+ const bag = this.registers.getItem(register), label = key(node);
280
+ let row = bag.getItem(label);
281
+ if (!row && value != null) { row = new Bag(); bag.setItem(label,row); }
282
+ if (row) {
283
+ if (value == null) { if (row.getNode(kind)) row.popNode(kind); }
284
+ else row.setItem(kind,value);
285
+ if (!row.length) this.remove(register,node);
286
+ }
287
+ this.notify();
288
+ }
289
+ issue(node, kind, message) { this.part('errors',node,kind,message || null); }
290
+ pendingPart(node, kind, value) { this.part('pending',node,kind,value); }
291
+ parseError(node, message) { this.issue(node,'parse',message); }
292
+ schedule(callback) {
293
+ queueMicrotask(() => { if (!this.disposed) callback(); });
294
+ }
295
+ receive(change) {
296
+ if (this.disposed) return;
297
+ this.updateChanges(change.path);
298
+ if (this.writing) return;
299
+ for (const node of this.validations.keys()) this.refreshField(node);
300
+ }
301
+
302
+ updateChanges(changedPath = null) {
303
+ const changes = this.registers.getItem('changes');
304
+ const relative = changedPath === this.path ? '' : changedPath?.startsWith(this.path + '.')
305
+ ? changedPath.slice(this.path.length + 1).split('?')[0] : '';
306
+ const visit = (a, b, path) => {
307
+ if (a && b && a.value instanceof Bag && b.value instanceof Bag && same(a.attr,b.attr)) {
308
+ const labels = new Set([...a.value.getNodes(), ...b.value.getNodes()].map(n => n.label));
309
+ for (const label of labels) visit(a.value.getNode(label), b.value.getNode(label), path ? path + '.' + label : label);
310
+ } else if (!a || !b || !same([a.value,a.attr],[b.value,b.attr])) {
311
+ changes.setItem(encoded(path), new Bag({path, existed:Boolean(a), exists:Boolean(b),
312
+ previous:a ? copy(a.value) : null, current:b ? copy(b.value) : null,
313
+ previousAttributes:a ? copy(a.attr) : null, currentAttributes:b ? copy(b.attr) : null}));
314
+ }
315
+ };
316
+ const baseline = this.registers.getItem('baseline');
317
+ // Preserve an existing changed ancestor (insert, delete or attributes).
318
+ // Reconcile only this affected subtree, never unrelated resident rows.
319
+ let path = relative;
320
+ for (const entry of changes.getNodes()) {
321
+ const ancestor = entry.value.getItem('path');
322
+ if (path.startsWith(ancestor + '.')) path = ancestor;
323
+ }
324
+ let ancestor = path;
325
+ while (ancestor.includes('.')) {
326
+ ancestor = ancestor.slice(0,ancestor.lastIndexOf('.'));
327
+ const before = baseline.getNode(ancestor), after = this.data.getNode(ancestor);
328
+ if (!before || !after || !same(before.attr,after.attr)) path = ancestor;
329
+ }
330
+ for (const entry of [...changes.getNodes()]) {
331
+ const current = entry.value.getItem('path');
332
+ if (!path || current === path || current.startsWith(path + '.')) changes.popNode(entry.label);
333
+ }
334
+ if (path) visit(baseline.getNode(path), this.data.getNode(path), path);
335
+ else visit({value:baseline,attr:{}}, {value:this.data,attr:{}}, '');
336
+ this.notify();
337
+ }
338
+ notify() {
339
+ if (this.disposed || this.scheduled) return;
340
+ this.scheduled = true;
341
+ this.schedule(() => { this.scheduled = false; const status = this.status;
342
+ const previous = this.registers.getItem('status');
343
+ if (!previous || !same(previous,new Bag(status))) {
344
+ this.registers.setItem('status',new Bag(status));
345
+ this.node.publish('formStatus',status);
346
+ }
347
+ for (const listener of this.listeners) listener(); });
348
+ }
349
+ commitField(path) {
350
+ for (const adapter of this.fields.values()) {
351
+ if (fieldPath(adapter.node) === path && Object.hasOwn(adapter.node,'formDraft')) adapter.commit();
352
+ }
353
+ }
354
+ /** Flush active drafts. Refuse errors/pending checks; accept only a valid local snapshot. */
355
+ accept() {
356
+ if (this.disposed) return false;
357
+ for (const adapter of this.fields.values()) {
358
+ if (Object.hasOwn(adapter.node,'formDraft')) adapter.commit();
359
+ }
360
+ if (!this.status.valid || this.status.pending) return false;
361
+ this.registers.setItem('baseline',copy(this.data));
362
+ this.updateChanges();
363
+ return true;
364
+ }
365
+ load(data) {
366
+ if (!(data instanceof Bag)) throw new TypeError('Editing load requires a Bag.');
367
+ if (this.disposed) return;
368
+ this.registers.setItem('baseline',copy(data));
369
+ this.restore();
370
+ }
371
+ restore() {
372
+ if (this.disposed) return;
373
+ for (const node of this.validations.keys()) this.cancelValidation(node);
374
+ for (const adapter of this.fields.values()) {
375
+ adapter.element.cancelValidation();
376
+ this.clearDraft(adapter.node);
377
+ adapter.element.restoreFormValue(this.registers.getItem('baseline').getItem(
378
+ adapter.node.absDatapath(adapter.node.getAttr('value')).slice(this.path ? this.path.length + 1 : 0)));
379
+ }
380
+ this.runtime.gramlot.data.setItem(this.path,copy(this.registers.getItem('baseline')));
381
+ for (const name of ['errors','pending','drafts']) this.registers.setItem(name,new Bag());
382
+ this.updateChanges();
383
+ for (const node of this.validations.keys()) this.scheduleField(node);
384
+ }
385
+ dispose() {
386
+ if (this.disposed) return;
387
+ this.disposed = true;
388
+ this.subscription.close();
389
+ for (const node of this.validations.keys()) this.forgetField(node);
390
+ this.fields.clear();
391
+ this.validationQueue.clear();
392
+ this.retainedFields.clear();
393
+ this.listeners.clear();
394
+ this.navigators.clear();
395
+ }
396
+ }
@@ -12,6 +12,7 @@ const SelectionTrial = defineComponent({
12
12
  limit:{dtype:'T',binding:'read'},reload:{dtype:'L',default:0,binding:'read'},
13
13
  result:{dtype:'X',nullable:true,default:null,binding:'write'},
14
14
  metrics:{dtype:'X',nullable:true,default:null,binding:'write'},
15
+ loading:{dtype:'B',default:false,binding:'write'},
15
16
  status:{dtype:'T',default:'',binding:'write'}
16
17
  },
17
18
  implementation:Base => class extends Base {
@@ -23,7 +24,14 @@ const SelectionTrial = defineComponent({
23
24
  return rest;
24
25
  }
25
26
  connectedCallback() { this.#load(); }
26
- disconnectedCallback() { this.#controller?.abort(); this.#key=undefined; }
27
+ disconnectedCallback() {
28
+ const controller=this.#controller;
29
+ this.#controller=null; this.#key=undefined;
30
+ if (controller) {
31
+ controller.abort();
32
+ this.#context.writeParameter('loading',false);
33
+ }
34
+ }
27
35
  async #load() {
28
36
  const {url,method,limit,reload}=this.parameters;
29
37
  const key=JSON.stringify([url,method,limit,reload]);
@@ -31,8 +39,10 @@ const SelectionTrial = defineComponent({
31
39
  this.#key=key; this.#controller?.abort();
32
40
  const controller=new AbortController(); this.#controller=controller;
33
41
  const page=this.#context.sourceNode.rootBuilder.binding.gramlot;
34
- this.#context.writeParameter('status','Loading…');
35
42
  try {
43
+ this.#context.writeParameter('loading',true);
44
+ this.#context.writeParameter('status','Loading…');
45
+ if(this.#controller!==controller || !this.isConnected) return;
36
46
  const {selection,metrics}=await loadSelectionTrial({url,method,limit,pageId:page.pageId,signal:controller.signal});
37
47
  if(this.#controller!==controller || !this.isConnected) return;
38
48
  this.#context.writeParameter('result',selection);
@@ -41,6 +51,12 @@ const SelectionTrial = defineComponent({
41
51
  } catch(error) {
42
52
  if(controller.signal.aborted || this.#controller!==controller) return;
43
53
  this.#context.writeParameter('status',`Failed: ${error.message}`);
54
+ } finally {
55
+ // Only the current request can end the shared loading state.
56
+ if(this.#controller===controller) {
57
+ this.#controller=null;
58
+ this.#context.writeParameter('loading',false);
59
+ }
44
60
  }
45
61
  }
46
62
  }
package/src/format.js CHANGED
@@ -1,6 +1,23 @@
1
1
  import {getDateType, isDecimal} from '@genrojs/tytx';
2
2
  /** Bounded numeric patterns and temporal styles for Gramlot's formatting contract. */
3
3
 
4
+ // Intl construction is expensive. Reuse configuration, never formatted values or
5
+ // row data. The bound also limits retention when pages use many locales/patterns.
6
+ const intlFormatters = new Map();
7
+ function intlFormatter(temporal, locale, options) {
8
+ const key = JSON.stringify([temporal, locale, options]);
9
+ let formatter = intlFormatters.get(key);
10
+ if (formatter) intlFormatters.delete(key);
11
+ else {
12
+ const Type = temporal ? Intl.DateTimeFormat : Intl.NumberFormat;
13
+ if (!Type.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
14
+ formatter = new Type(locale, options);
15
+ if (intlFormatters.size === 64) intlFormatters.delete(intlFormatters.keys().next().value);
16
+ }
17
+ intlFormatters.set(key, formatter);
18
+ return formatter;
19
+ }
20
+
4
21
  export function validateMask(mask) {
5
22
  if (mask != null && (typeof mask !== 'string' || /[{}]/.test(mask.replaceAll('{}', '')))) {
6
23
  throw new RangeError('This formatter mask supports only {} placeholders');
@@ -32,7 +49,7 @@ function temporalText(value, dtype, {pattern = 'short', locale, timeZone}) {
32
49
  const options = {timeZone: dtype === 'DHZ' ? timeZone : 'UTC'};
33
50
  if (dtype !== 'H') options.dateStyle = pattern;
34
51
  if (dtype !== 'D') options.timeStyle = pattern;
35
- return new Intl.DateTimeFormat(locale, options).format(value);
52
+ return intlFormatter(true, locale, options).format(value);
36
53
  }
37
54
 
38
55
  function numericSection(section) {
@@ -90,32 +107,30 @@ export function formatValue(value, options = {}, context = {}) {
90
107
  const {pattern, locale, mask} = options;
91
108
  if (!temporal && typeof pattern !== 'string') throw new TypeError('Numeric formatting currently requires an explicit pattern');
92
109
  if (typeof locale !== 'string' || !locale) throw new TypeError('Formatting currently requires an explicit locale');
93
- // Do not silently select the browser locale when the requested locale is unavailable.
94
- const intl = temporal ? Intl.DateTimeFormat : Intl.NumberFormat;
95
- if (!intl.supportedLocalesOf([locale]).length) throw new RangeError(`Unsupported format locale: ${locale}`);
96
110
  validateMask(mask);
97
111
  if (temporal) {
98
112
  const text = temporalText(value, dtype, options);
99
113
  return applyMask(text, mask);
100
114
  }
101
115
  const {positive, zero, negative} = numericPattern(pattern);
116
+ const formatter = intlFormatter(false, locale, positive.intl);
102
117
  const decimal = isDecimal(value);
103
118
  const zeroValue = decimal ? value.eq(0) : value === 0;
104
119
  const negativeValue = decimal ? value.lt(0) : value < 0;
105
- if (decimal && new Intl.NumberFormat('en', {useGrouping: false}).format('9007199254740993') !== '9007199254740993') throw new Error('This browser cannot format Decimal without precision loss');
120
+ if (decimal && intlFormatter(false, 'en', {useGrouping: false}).format('9007199254740993') !== '9007199254740993') throw new Error('This browser cannot format Decimal without precision loss');
106
121
  let text;
107
122
  if (zeroValue && zero !== null) {
108
123
  if (zero === '') return '';
109
124
  if (zero === '-') text = '-';
110
125
  else {
111
126
  const section = numericSection(zero);
112
- text = section.prefix + new Intl.NumberFormat(locale, section.intl).format(0) + section.suffix;
127
+ text = section.prefix + intlFormatter(false, locale, section.intl).format(0) + section.suffix;
113
128
  }
114
129
  } else {
115
130
  const affix = negativeValue && negative ? negative : positive;
116
131
  const number = decimal ? (negativeValue && negative ? value.abs() : value).toString()
117
132
  : negativeValue && negative ? -value : (value === 0 ? 0 : value);
118
- text = affix.prefix + new Intl.NumberFormat(locale, positive.intl).format(number) + affix.suffix;
133
+ text = affix.prefix + formatter.format(number) + affix.suffix;
119
134
  }
120
135
  return applyMask(text, mask);
121
136
  }
package/src/gramlot.d.ts CHANGED
@@ -30,6 +30,7 @@ export interface GramlotOptions {
30
30
  /** The id of the server page, as registered by the server. */
31
31
  pageId?: string;
32
32
  /** The URL of the rpc endpoint that receives the envelopes. */
33
+ uploadUrl?: string | null;
33
34
  rpcUrl?: string;
34
35
  /** The URL of the page close endpoint. */
35
36
  closeUrl?: string;
@@ -82,6 +83,7 @@ export class Gramlot {
82
83
  timeZone: string;
83
84
  /** The id of the server page. */
84
85
  pageId: string | undefined;
86
+ uploadUrl: string | null;
85
87
  /** The capabilities announced by the server in the bootstrap, frozen. */
86
88
  capabilities: readonly string[];
87
89
  /** The server-dependent behaviour the core consults (the transport); not a proxy, page authors do not call it. */
package/src/gramlot.js CHANGED
@@ -28,7 +28,7 @@ import {formatValue} from './format.js';
28
28
  */
29
29
  export class Gramlot {
30
30
  #mobileEnvironment;
31
- constructor({pageId, rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close', rootId = 'gramlot-root', capabilities = [],
31
+ constructor({pageId, uploadUrl = null, rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close', rootId = 'gramlot-root', capabilities = [],
32
32
  element = null, document = element?.ownerDocument ?? globalThis.document, transport = null, collections = [],
33
33
  locale = null, timeZone = null, devices = [], serverAdapter = new ServerAdapter(), nameSyntax = null,
34
34
  websocketUrl = null} = {}) {
@@ -38,6 +38,7 @@ export class Gramlot {
38
38
  }
39
39
  this.commands = new CommandRegistry();
40
40
  this.pageId = pageId;
41
+ this.uploadUrl = uploadUrl;
41
42
  const browserContext = locale == null || timeZone == null
42
43
  ? document.defaultView.Intl.DateTimeFormat().resolvedOptions() : null;
43
44
  this.devices = Object.freeze([...devices]);
@@ -6,6 +6,7 @@ export interface DeviceDatabase {
6
6
  }
7
7
  import type {Handler} from './handler.js';
8
8
  import type {Gramlot} from '../gramlot.js';
9
+ import type {BrowserCameraProvider} from '../browser-camera-provider.js';
9
10
 
10
11
  export type DeviceName = 'appinfo' | 'location';
11
12
  export interface AppInfo { id: string; name: string; version: string; build: string; }
@@ -67,7 +68,7 @@ export interface DeviceProvider {
67
68
  /** Owns device resolvers, Data attributes and native operation cleanup for one page. */
68
69
  export class DeviceHandler extends Handler {
69
70
  constructor(gramlot: Gramlot);
70
- attach(provider: DeviceProvider, options?: {dispose?: () => void | Promise<void>}): void;
71
+ attach(provider: DeviceProvider | BrowserCameraProvider, options?: {dispose?: () => void | Promise<void>}): void;
71
72
  openDatabase(name: string): Promise<DeviceDatabase>;
72
73
  invalidate(name: DeviceName): void;
73
74
  refresh(name: DeviceName): void;
@@ -62,15 +62,15 @@ export class RpcHandler extends Handler {
62
62
  * `RpcError`. `signal` and the dispose of the page (`gramlot.abort`) abort the call, which then rejects at
63
63
  * once with the abort reason; a call aborted before it starts is not sent.
64
64
  */
65
- call(contentType: 'source' | 'data', name: string, params?: Record<string, unknown>,
65
+ call(contentType: 'source' | 'data' | 'upload', name: string, params?: Record<string, unknown>,
66
66
  options?: {signal?: AbortSignal}): Promise<unknown>;
67
67
  /** Whether the transport sends a synchronous call (`supportsCallSync`). */
68
68
  readonly supportsCallSync: boolean;
69
69
  /** Return the checked response envelope, including optional initial-main Data. */
70
- callEnvelope(contentType: 'source' | 'data', name: string, params?: Record<string, unknown>,
70
+ callEnvelope(contentType: 'source' | 'data' | 'upload', name: string, params?: Record<string, unknown>,
71
71
  options?: {signal?: AbortSignal | null}): Promise<{
72
72
  id: string; contentType: string; value: unknown; data?: import('@genrojs/bag').Bag;
73
73
  }>;
74
74
  /** Send one envelope synchronously; only with a transport that supports it. */
75
- callSync(contentType: 'source' | 'data', name: string, params?: Record<string, unknown>): unknown;
75
+ callSync(contentType: 'source' | 'data' | 'upload', name: string, params?: Record<string, unknown>): unknown;
76
76
  }