@gramlot/gramlot 0.3.24 → 0.3.27

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 (144) hide show
  1. package/dist/components/chat/__init__.py +1 -1
  2. package/dist/components/chat/assets/collection.js +3 -3
  3. package/dist/components/chat/assets/index.js +1 -1
  4. package/dist/components/editors/__init__.py +2 -2
  5. package/dist/components/editors/assets/collection.js +21 -20
  6. package/dist/components/editors/assets/index.js +1 -1
  7. package/dist/components/editors/assets/modules/chunk-74O4WKIV.js +1 -0
  8. package/dist/components/editors/assets/modules/{code-mirror-engine-QX4A5FVO.js → code-mirror-engine-RWQTR5G5.js} +29 -29
  9. package/dist/components/editors/assets/modules/{jodit-engine-MMSPIWM7.js → jodit-engine-MTSA4GZ3.js} +292 -292
  10. package/dist/components/editors/assets/modules/markdown-document-VFC23FAY.js +1 -0
  11. package/dist/components/editors/assets/modules/{prose-mirror-engine-IXTRTG6B.js → prose-mirror-engine-GMZPJPNN.js} +13 -13
  12. package/dist/components/grid/__init__.py +3 -2
  13. package/dist/components/grid/assets/collection.js +77 -17
  14. package/dist/components/grid/assets/index.js +1 -1
  15. package/dist/components/grid/grammar.json +78 -1
  16. package/dist/components/grouplets/__init__.py +2 -2
  17. package/dist/components/grouplets/assets/collection.js +3 -20
  18. package/dist/components/grouplets/assets/index.js +1 -1
  19. package/dist/components/grouplets/assets/modules/chunk-BLMUM44K.js +1 -0
  20. package/dist/components/grouplets/assets/modules/markdown-document-YWNZTOKK.js +1 -0
  21. package/dist/components/inputs/__init__.py +1 -1
  22. package/dist/components/inputs/assets/collection.js +59 -34
  23. package/dist/components/inputs/assets/index.js +1 -1
  24. package/dist/components/inputs/grammar.json +64 -0
  25. package/dist/components/layout/__init__.py +1 -1
  26. package/dist/components/layout/assets/collection.js +67 -57
  27. package/dist/components/layout/assets/index.js +1 -1
  28. package/dist/components/layout/grammar.json +35 -0
  29. package/dist/components/selection_trial/__init__.py +1 -1
  30. package/dist/components/selection_trial/assets/collection.js +3 -3
  31. package/dist/components/selection_trial/assets/index.js +1 -1
  32. package/dist/components/selection_trial/grammar.json +35 -0
  33. package/dist/components/tree/__init__.py +1 -1
  34. package/dist/components/tree/assets/collection.js +26 -23
  35. package/dist/components/tree/assets/index.js +1 -1
  36. package/dist/components/tree/grammar.json +341 -1
  37. package/dist/components/typst/__init__.py +1 -1
  38. package/dist/components/typst/assets/collection.js +3 -3
  39. package/dist/components/typst/assets/index.js +1 -1
  40. package/dist/components/uploads/__init__.py +13 -0
  41. package/dist/components/uploads/assets/collection.js +67 -0
  42. package/dist/components/uploads/assets/index.js +3 -0
  43. package/dist/components/uploads/commands.json +7 -0
  44. package/dist/components/uploads/grammar.json +789 -0
  45. package/dist/{components/editors/assets/modules/chunk-OCFLP2K4.js → gramlot-markdown.js} +12 -12
  46. package/dist/gramlot.js +5455 -573
  47. package/dist/gramlot.min.js +1588 -43
  48. package/dist/runtime-notices.json +28 -0
  49. package/package.json +4 -2
  50. package/src/binding/grid-struct.js +1 -1
  51. package/src/binding/providers.js +4 -1
  52. package/src/binding/remote-resolver.js +1 -8
  53. package/src/binding/runtime.js +40 -1
  54. package/src/binding/validation-context.js +41 -0
  55. package/src/browser-camera-provider.d.ts +8 -0
  56. package/src/browser-camera-provider.js +104 -0
  57. package/src/builder/source.js +13 -2
  58. package/src/components/attachment-manager.js +160 -0
  59. package/src/components/bases.js +19 -6
  60. package/src/components/border-container.js +86 -8
  61. package/src/components/buttons.js +11 -1
  62. package/src/components/choice-editor.js +44 -16
  63. package/src/components/database-choices.js +13 -8
  64. package/src/components/editing-status-styles.js +26 -0
  65. package/src/components/editing-status.js +115 -0
  66. package/src/components/field-state.js +44 -58
  67. package/src/components/grid-cell-editor.js +245 -0
  68. package/src/components/grid-grammar.json +42 -0
  69. package/src/components/grid-structure.js +5 -1
  70. package/src/components/grid-styles.js +60 -1
  71. package/src/components/grid.js +103 -11
  72. package/src/components/grouplet-card.js +11 -3
  73. package/src/components/html-preview.js +17 -4
  74. package/src/components/image-crop-dialog.js +272 -0
  75. package/src/components/image-crop.js +79 -0
  76. package/src/components/image-uploader.js +252 -0
  77. package/src/components/inputs.js +4 -3
  78. package/src/components/jodit-engine.js +1 -1
  79. package/src/components/markdown-document.js +2 -2
  80. package/src/components/parameters.js +6 -2
  81. package/src/components/screen-capture.js +43 -0
  82. package/src/components/selected-container.js +6 -2
  83. package/src/components/tree.js +417 -17
  84. package/src/components/typed-editor.js +19 -9
  85. package/src/components/upload-engine.js +156 -0
  86. package/src/components/uploader.js +208 -0
  87. package/src/components/uploads.js +7 -0
  88. package/src/components/validation.js +1 -1
  89. package/src/editing-session.d.ts +26 -0
  90. package/src/editing-session.js +494 -0
  91. package/src/editor-values.js +57 -0
  92. package/src/experiments/selection-trial.js +18 -2
  93. package/src/format.js +22 -7
  94. package/src/gramlot.d.ts +3 -0
  95. package/src/gramlot.js +9 -5
  96. package/src/handlers/device-handler.d.ts +2 -1
  97. package/src/handlers/rpc-handler.d.ts +3 -3
  98. package/src/index-page-styles.js +1 -0
  99. package/src/index.d.ts +14 -1
  100. package/src/index.js +13 -0
  101. package/src/inout.d.ts +2 -0
  102. package/src/inout.js +6 -0
  103. package/src/markdown-loader.d.ts +1 -0
  104. package/src/markdown-loader.js +4 -0
  105. package/src/markdown.d.ts +1 -0
  106. package/src/markdown.js +2 -0
  107. package/src/media-frame.js +9 -0
  108. package/src/renderer/attributes.js +7 -1
  109. package/src/renderer/gramlot-renderer.d.ts +3 -0
  110. package/src/renderer/gramlot-renderer.js +42 -2
  111. package/src/server/assets.d.ts +1 -1
  112. package/src/server/assets.js +1 -1
  113. package/src/server/gramlot-server.d.ts +8 -1
  114. package/src/server/gramlot-server.js +83 -7
  115. package/src/server/index.d.ts +2 -0
  116. package/src/server/index.js +2 -0
  117. package/src/server/page-base.js +17 -4
  118. package/src/server/page.d.ts +13 -1
  119. package/src/server/page.js +6 -0
  120. package/src/server/source-import.d.ts +2 -0
  121. package/src/server/source-import.js +35 -0
  122. package/src/server/upload.d.ts +20 -0
  123. package/src/server/upload.js +142 -0
  124. package/src/server/visual-editor.d.ts +11 -0
  125. package/src/server/visual-editor.js +159 -0
  126. package/src/source-picker.d.ts +9 -0
  127. package/src/source-picker.js +56 -0
  128. package/src/tree-store.d.ts +24 -0
  129. package/src/tree-store.js +193 -0
  130. package/src/validation-run.js +50 -0
  131. package/src/view/button.js +8 -5
  132. package/src/view/controls.js +9 -42
  133. package/src/view/html.js +10 -2
  134. package/src/visual-editor-canvas.js +29 -0
  135. package/src/visual-editor-catalogue.js +34 -0
  136. package/src/visual-editor-icons.js +10 -0
  137. package/src/visual-editor.d.ts +61 -0
  138. package/src/visual-editor.js +1062 -0
  139. package/themes/gramlot-base/theme.css +141 -0
  140. package/tools/gramlot-tools-inspector.js +1 -1
  141. package/tools/inspector-agent.js +1 -1
  142. package/dist/components/editors/assets/modules/chunk-MMJXUHRQ.js +0 -3
  143. package/src/form-state.d.ts +0 -20
  144. package/src/form-state.js +0 -198
@@ -0,0 +1,494 @@
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
+ this.validationSources = new Set();
32
+ this.validationDependencies = new Map();
33
+ this.validationRevision = 0;
34
+ this.validatedRevision = -1;
35
+ this.fullValidation = null;
36
+ if (!(this.data instanceof Bag)) throw new TypeError('A form requires a Bag at its datapath.');
37
+ this.registers.setItem('baseline', copy(this.data));
38
+ for (const name of ['changes', 'errors', 'pending', 'drafts']) this.registers.setItem(name, new Bag());
39
+ this.subscription = runtime.router.register({path:this.path, recipient:this, subtree:true});
40
+ runtime.bindingFor(node).track(() => this.dispose());
41
+ }
42
+ rebind() {
43
+ const path = this.node.absDatapath('.');
44
+ if (path === this.path) return;
45
+ if (!(this.data instanceof Bag)) throw new TypeError('A form requires a Bag at its datapath.');
46
+ this.subscription.close();
47
+ for (const name of ['errors','pending','drafts']) this.registers.setItem(name,new Bag());
48
+ this.path = path;
49
+ this.subscription = this.runtime.router.register({path, recipient:this, subtree:true});
50
+ this.updateChanges();
51
+ for (const adapter of this.fields.values()) {
52
+ adapter.element.cancelValidation();
53
+ this.clearDraft(adapter.node);
54
+ this.scheduleValidation(adapter);
55
+ }
56
+ }
57
+ get data() { return this.runtime.gramlot.data.getItem(this.path); }
58
+ subscribe(listener) { this.listeners.add(listener); return () => this.listeners.delete(listener); }
59
+ /** Read-only reports derived from the canonical registers, never a second journal. */
60
+ get errorEntries() {
61
+ return this.registers.getItem('errors').getNodes().map(node => ({
62
+ path:decodeURIComponent(node.label),
63
+ message:node.value.getNodes().map(part => part.value).join('\n')
64
+ }));
65
+ }
66
+ get changeEntries() {
67
+ const entries = [];
68
+ for (const node of this.registers.getItem('changes').getNodes()) {
69
+ const change = node.value;
70
+ const path = [this.path,change.getItem('path')].filter(Boolean).join('.');
71
+ const existed = change.getItem('existed'), exists = change.getItem('exists');
72
+ const previous = change.getItem('previous'), current = change.getItem('current');
73
+ if (!existed || !exists || !same(previous,current)) entries.push({path,previous,current,existed,exists});
74
+ if (existed && exists) {
75
+ const before = change.getItem('previousAttributes'), after = change.getItem('currentAttributes');
76
+ for (const attr of new Set([...before.getNodes(),...after.getNodes()].map(node => node.label))) {
77
+ const had = before.getNode(attr) !== null, has = after.getNode(attr) !== null;
78
+ if (had !== has || !same(before.getItem(attr),after.getItem(attr))) entries.push({
79
+ path:path+'?'+attr, previous:before.getItem(attr), current:after.getItem(attr), existed:had, exists:has
80
+ });
81
+ }
82
+ }
83
+ }
84
+ return entries;
85
+ }
86
+ registerNavigator(navigator) {
87
+ this.navigators.add(navigator);
88
+ return () => this.navigators.delete(navigator);
89
+ }
90
+ focusField(path) {
91
+ if (this.disposed) return false;
92
+ for (const adapter of this.fields.values()) {
93
+ if (fieldPath(adapter.node) === path && adapter.element.isConnected) {
94
+ adapter.element.control.focus();
95
+ return true;
96
+ }
97
+ }
98
+ for (const navigate of this.navigators) if (navigate(path)) return true;
99
+ return false;
100
+ }
101
+ retainField(path) { this.retainedFields.set(path, (this.retainedFields.get(path) ?? 0) + 1); }
102
+ releaseField(path) {
103
+ const count = this.retainedFields.get(path);
104
+ if (count > 1) { this.retainedFields.set(path, count - 1); return; }
105
+ this.retainedFields.delete(path);
106
+ if ([...this.validations.values()].some(field => field.path === path)) return;
107
+ for (const name of ['errors', 'pending', 'drafts']) {
108
+ const bag = this.registers.getItem(name), label = encoded(path);
109
+ if (bag.getNode(label)) bag.popNode(label);
110
+ }
111
+ this.notify();
112
+ }
113
+ fieldStatus(path) {
114
+ const label = encoded(path);
115
+ return {error:this.registers.getItem('errors').getItem(label),
116
+ pending:this.registers.getItem('pending').getItem(label),
117
+ draft:this.registers.getItem('drafts').getItem(label)};
118
+ }
119
+ get status() {
120
+ const dirty = this.registers.getItem('changes').length > 0;
121
+ const pending = this.fullValidation !== null || this.registers.getItem('pending').length > 0;
122
+ const invalid = this.registers.getItem('errors').length > 0;
123
+ const incomplete = this.registers.getItem('drafts').length > 0;
124
+ return {dirty, pending, valid:!invalid && !incomplete, canSave:dirty && !invalid && !incomplete && !pending,
125
+ status:invalid ? 'error' : pending || incomplete ? 'pending' : dirty ? 'changed' : 'ok'};
126
+ }
127
+ register(adapter) {
128
+ const node = adapter.node;
129
+ this.fields.set(node, adapter);
130
+ const field = this.registerField(node,adapter.element.constructor);
131
+ field.selection = adapter.element.validationSelection();
132
+ this.schedule(() => {
133
+ if (this.fields.get(node) !== adapter) return;
134
+ const draft = this.registers.getItem('drafts').getNode(key(node));
135
+ if (draft) { node.formDraft = draft.value; adapter.element.restoreFormDraft(draft.value); }
136
+ if (field.result) adapter.element.presentValidation(field.result);
137
+ const errors = this.registers.getItem('errors').getItem(key(node));
138
+ if (errors) adapter.element.error(errors.getNodes().map(n => n.value).join('\n'));
139
+ adapter.element.setFieldState({invalid:Boolean(errors), pending:Boolean(this.fieldStatus(field.path).pending)});
140
+ });
141
+ return () => { this.fields.delete(node); };
142
+ }
143
+ /** A real Source declaration can validate without an element or ControlAdapter. */
144
+ registerField(node, component, schedule = true) {
145
+ let field = this.validations.get(node);
146
+ if (field) return field;
147
+ if (!component.validationExecutor) throw new TypeError('Grid editors require shared input validation.');
148
+ const binding = this.runtime.bindingFor(node), context = validationContext(binding);
149
+ field = {node,binding,context,component,run:new ValidationRun(),
150
+ execute:component.validationExecutor,checkValue:component.validationValueCheck(context),
151
+ path:fieldPath(node),rules:null,value:undefined,target:null,result:null,selection:null};
152
+ this.validations.set(node,field);
153
+ binding.editingSession = this;
154
+ field.release = binding.track(() => this.forgetField(node));
155
+ this.refreshField(node,schedule);
156
+ return field;
157
+ }
158
+ registerValidationSource(fields) {
159
+ this.validationSources.add(fields);
160
+ this.invalidateValidation();
161
+ return () => { this.validationSources.delete(fields); this.invalidateValidation(); };
162
+ }
163
+ invalidateValidation() {
164
+ this.validationRevision++;
165
+ if (this.fullValidation) for (const node of this.fullValidation.active) this.cancelValidation(node);
166
+ }
167
+ trackValidationDependency(absolute) {
168
+ if (absolute === null || this.validationDependencies.has(absolute)) return;
169
+ const [path,attr = null] = absolute.split('?',2);
170
+ this.validationDependencies.set(absolute,this.runtime.router.register({path,attr,subtree:true,
171
+ recipient:{receive:() => this.invalidateValidation()}}));
172
+ }
173
+ clearValidationDependencies() {
174
+ for (const registration of this.validationDependencies.values()) registration.close();
175
+ this.validationDependencies.clear();
176
+ }
177
+ /** Validate the complete declared scope. Bounded work keeps remote checks and UI responsive. */
178
+ validate() {
179
+ if (this.disposed) return Promise.resolve(false);
180
+ if (this.fullValidation) return this.fullValidation.promise;
181
+ for (const adapter of this.fields.values()) if (Object.hasOwn(adapter.node,'formDraft')) adapter.commit();
182
+ this.clearValidationDependencies();
183
+ const pass = {revision:this.validationRevision,promise:null,active:new Set(),failed:false,complete:true};
184
+ this.fullValidation = pass;
185
+ this.notify();
186
+ const fields = this.validationFields();
187
+ const current = () => !this.disposed && !pass.failed && pass.revision === this.validationRevision;
188
+ const seen = new WeakSet();
189
+ const worker = async () => {
190
+ let count = 0;
191
+ while (current()) {
192
+ const next = fields.next();
193
+ if (next.done) return;
194
+ const {node,release} = next.value;
195
+ try {
196
+ if (seen.has(node)) continue;
197
+ seen.add(node);
198
+ for (const [name,pointer] of node.pointers()) if (name !== 'value') {
199
+ this.trackValidationDependency((name === 'datapath' ? node.parentNode : node).absDatapath(pointer));
200
+ }
201
+ pass.active.add(node);
202
+ const outcome = await this.validateField(node);
203
+ if (!outcome?.ok) pass.complete = false;
204
+ } finally { pass.active.delete(node); release(); }
205
+ if (++count % 20 === 0) await new Promise(resolve => setTimeout(resolve,0));
206
+ }
207
+ };
208
+ pass.promise = Promise.resolve().then(async () => {
209
+ const outcomes = await Promise.allSettled(Array.from({length:8},() => worker().catch(error => {
210
+ pass.failed = true;
211
+ for (const node of pass.active) this.cancelValidation(node);
212
+ throw error;
213
+ })));
214
+ const failure = outcomes.find(outcome => outcome.status === 'rejected');
215
+ if (failure) throw failure.reason;
216
+ if (!current()) return false;
217
+ // fullValidation itself is pending until finally; inspect field registers here.
218
+ const valid = pass.complete && this.status.valid && this.registers.getItem('pending').length === 0;
219
+ if (valid) this.validatedRevision = this.validationRevision;
220
+ return valid;
221
+ }).finally(() => {
222
+ fields.return();
223
+ this.fullValidation = null;
224
+ this.notify();
225
+ });
226
+ return pass.promise;
227
+ }
228
+ *validationFields() {
229
+ const existing = [...this.validations.keys()];
230
+ for (const fields of this.validationSources) yield* fields();
231
+ for (const node of existing) if (this.validations.has(node)) yield {node,release:() => {}};
232
+ }
233
+ forgetField(node) {
234
+ const field = this.validations.get(node);
235
+ if (!field) return;
236
+ field.run.cancel(); field.release();
237
+ if (field.binding.editingSession === this) field.binding.editingSession = null;
238
+ this.validations.delete(node); this.validationQueue.delete(node);
239
+ for (const name of ['errors','pending']) {
240
+ const parts = this.registers.getItem(name).getItem(encoded(field.path));
241
+ if (parts) {
242
+ for (const part of [...parts.getNodes()]) if (part.label.startsWith(encoded(node.fullpath) + ':')) parts.popNode(part.label);
243
+ if (!parts.length) this.registers.getItem(name).popNode(encoded(field.path));
244
+ }
245
+ }
246
+ if (![...this.validations.values()].some(other => other.path === field.path)) {
247
+ const drafts = this.registers.getItem('drafts');
248
+ if (drafts.getNode(encoded(field.path))) drafts.popNode(encoded(field.path));
249
+ }
250
+ delete node.formDraft;
251
+ this.notify();
252
+ }
253
+ refreshField(node, schedule = true) {
254
+ const field = this.validations.get(node);
255
+ if (!field || this.disposed || this.writing) return;
256
+ const [, attrs] = node.rootBuilder.runtimeValues(node);
257
+ const resolved = field.component.validationParameters(this.runtime.renderer.evaluateExpressions(node,attrs));
258
+ const rules = Object.fromEntries(Object.entries(resolved).filter(([name]) => name.startsWith('validate_')));
259
+ const configuration = toTytx(Object.fromEntries(Object.entries(resolved).filter(([name]) => name !== 'value')));
260
+ const path = fieldPath(node), target = this.runtime.gramlot.data.getNode(path.split('?')[0]);
261
+ const value = node.getRelativeData(node.getAttr('value'));
262
+ const dataChanged = field.path !== path || field.target !== target || !same(field.value,value);
263
+ if (!dataChanged && field.configuration === configuration) return;
264
+ if (field.rules !== null) this.invalidateValidation();
265
+ this.cancelValidation(node);
266
+ if (field.path !== path) {
267
+ for (const name of ['errors','pending','drafts']) {
268
+ const bag = this.registers.getItem(name);
269
+ if (bag.getNode(encoded(field.path))) bag.popNode(encoded(field.path));
270
+ }
271
+ }
272
+ Object.assign(field,{path,target,value,rules,configuration,result:null,
273
+ selection:field.component.validationSelection(resolved,field.context)});
274
+ if (dataChanged) this.clearDraft(node);
275
+ if (schedule) this.scheduleField(node);
276
+ }
277
+ cancelValidation(node) {
278
+ this.validations.get(node)?.run.cancel();
279
+ this.validationQueue.delete(node);
280
+ this.pendingPart(node,'validation',null);
281
+ }
282
+ writeCandidate(node,value) {
283
+ this.clearDraft(node);
284
+ this.writing++;
285
+ try { this.runtime.renderer.html.writeParameter(node,'value',value); }
286
+ finally { this.writing--; }
287
+ const field = this.validations.get(node);
288
+ if (field) {
289
+ field.value = node.getRelativeData(node.getAttr('value'));
290
+ field.target = this.runtime.gramlot.data.getNode(field.path.split('?')[0]);
291
+ }
292
+ for (const other of this.validations.keys()) if (other !== node) this.refreshField(other);
293
+ }
294
+ validateCandidate(node,value,selection) {
295
+ this.invalidateValidation();
296
+ this.cancelValidation(node);
297
+ this.writeCandidate(node,value);
298
+ const field = this.validations.get(node);
299
+ field.selection = selection;
300
+ return this.validateField(node,false);
301
+ }
302
+ scheduleField(node) {
303
+ if (this.disposed || !this.validations.has(node) || this.validationQueue.has(node)) return;
304
+ if (this.registers.getItem('drafts').getNode(key(node))) return;
305
+ this.validationQueue.add(node);
306
+ this.pendingPart(node,'validation','scheduled');
307
+ this.schedule(() => { if (this.validationQueue.delete(node)) this.validateField(node); });
308
+ }
309
+ scheduleValidation(adapter) {
310
+ this.refreshField(adapter.node);
311
+ const field = this.validations.get(adapter.node);
312
+ if (field && !field.result && !field.run.controller) this.scheduleField(adapter.node);
313
+ }
314
+ validateField(node, refreshSelection = true) {
315
+ const field = this.validations.get(node);
316
+ if (!field || this.disposed || field.binding.closed) return;
317
+ this.validationQueue.delete(node);
318
+ if (this.registers.getItem('drafts').getNode(key(node))) return;
319
+ if (this.registers.getItem('pending').getItem(key(node))?.getItem(contribution(node,'selection'))) return;
320
+ const value = node.getRelativeData(node.getAttr('value'));
321
+ const adapter = this.fields.get(node);
322
+ if (refreshSelection && adapter) field.selection = adapter.element.validationSelection();
323
+ const selection = field.selection;
324
+ const target = field.target;
325
+ const current = field.context.validationCurrent();
326
+ return field.run.start(value,field.rules,{...field.context,
327
+ validationCurrent:() => () => !this.disposed && current() && this.validations.get(node) === field
328
+ && this.runtime.gramlot.data.getNode(field.path.split('?')[0]) === target,
329
+ selection
330
+ },field.execute,outcome => {
331
+ if (outcome.ok) {
332
+ try { field.checkValue(outcome.value,value); }
333
+ catch (error) { outcome.ok = false; outcome.result.error = error.message; }
334
+ }
335
+ this.result(node,outcome.result);
336
+ field.result = outcome.result;
337
+ if (outcome.ok) this.writeCandidate(node,outcome.value);
338
+ const mounted = this.fields.get(node);
339
+ if (mounted) mounted.element.presentValidation(outcome.result);
340
+ field.context.finishValidation(outcome);
341
+ },() => {
342
+ this.pendingPart(node,'validation','active');
343
+ this.fields.get(node)?.element.setFieldState({pending:true});
344
+ });
345
+ }
346
+ remove(name, node) {
347
+ const bag = this.registers.getItem(name), label = key(node);
348
+ if (bag.getNode(label)) bag.popNode(label);
349
+ }
350
+ set(name, node, value) {
351
+ if (value == null) this.remove(name,node);
352
+ else this.registers.getItem(name).setItem(key(node), value);
353
+ this.notify();
354
+ }
355
+ draft(node, text) {
356
+ this.invalidateValidation();
357
+ this.cancelValidation(node);
358
+ node.formDraft = text;
359
+ this.set('drafts',node,text);
360
+ }
361
+ clearDraft(node) {
362
+ delete node.formDraft;
363
+ this.set('drafts',node,null);
364
+ this.issue(node,'parse',null);
365
+ }
366
+ result(node, result) {
367
+ this.pendingPart(node,'validation',null);
368
+ this.issue(node,'validation',result.error || null);
369
+ }
370
+ part(register, node, kind, value) {
371
+ kind = contribution(node,kind);
372
+ const bag = this.registers.getItem(register), label = key(node);
373
+ let row = bag.getItem(label);
374
+ if (!row && value != null) { row = new Bag(); bag.setItem(label,row); }
375
+ if (row) {
376
+ if (value == null) { if (row.getNode(kind)) row.popNode(kind); }
377
+ else row.setItem(kind,value);
378
+ if (!row.length) this.remove(register,node);
379
+ }
380
+ this.notify();
381
+ }
382
+ issue(node, kind, message) { this.part('errors',node,kind,message || null); }
383
+ pendingPart(node, kind, value) { this.part('pending',node,kind,value); }
384
+ parseError(node, message) { this.issue(node,'parse',message); }
385
+ schedule(callback) {
386
+ queueMicrotask(() => { if (!this.disposed) callback(); });
387
+ }
388
+ receive(change) {
389
+ if (this.disposed) return;
390
+ this.updateChanges(change.path);
391
+ if (this.writing) return;
392
+ this.invalidateValidation();
393
+ for (const node of this.validations.keys()) this.refreshField(node);
394
+ }
395
+
396
+ updateChanges(changedPath = null) {
397
+ const changes = this.registers.getItem('changes');
398
+ const relative = changedPath === this.path ? '' : changedPath?.startsWith(this.path + '.')
399
+ ? changedPath.slice(this.path.length + 1).split('?')[0] : '';
400
+ const visit = (a, b, path) => {
401
+ if (a && b && a.value instanceof Bag && b.value instanceof Bag && same(a.attr,b.attr)) {
402
+ const labels = new Set([...a.value.getNodes(), ...b.value.getNodes()].map(n => n.label));
403
+ for (const label of labels) visit(a.value.getNode(label), b.value.getNode(label), path ? path + '.' + label : label);
404
+ } else if (!a || !b || !same([a.value,a.attr],[b.value,b.attr])) {
405
+ changes.setItem(encoded(path), new Bag({path, existed:Boolean(a), exists:Boolean(b),
406
+ previous:a ? copy(a.value) : null, current:b ? copy(b.value) : null,
407
+ previousAttributes:a ? copy(a.attr) : null, currentAttributes:b ? copy(b.attr) : null}));
408
+ }
409
+ };
410
+ const baseline = this.registers.getItem('baseline');
411
+ // Preserve an existing changed ancestor (insert, delete or attributes).
412
+ // Reconcile only this affected subtree, never unrelated resident rows.
413
+ let path = relative;
414
+ for (const entry of changes.getNodes()) {
415
+ const ancestor = entry.value.getItem('path');
416
+ if (path.startsWith(ancestor + '.')) path = ancestor;
417
+ }
418
+ let ancestor = path;
419
+ while (ancestor.includes('.')) {
420
+ ancestor = ancestor.slice(0,ancestor.lastIndexOf('.'));
421
+ const before = baseline.getNode(ancestor), after = this.data.getNode(ancestor);
422
+ if (!before || !after || !same(before.attr,after.attr)) path = ancestor;
423
+ }
424
+ for (const entry of [...changes.getNodes()]) {
425
+ const current = entry.value.getItem('path');
426
+ if (!path || current === path || current.startsWith(path + '.')) changes.popNode(entry.label);
427
+ }
428
+ if (path) visit(baseline.getNode(path), this.data.getNode(path), path);
429
+ else visit({value:baseline,attr:{}}, {value:this.data,attr:{}}, '');
430
+ this.notify();
431
+ }
432
+ notify() {
433
+ if (this.disposed || this.scheduled) return;
434
+ this.scheduled = true;
435
+ this.schedule(() => { this.scheduled = false; const status = this.status;
436
+ const previous = this.registers.getItem('status');
437
+ if (!previous || !same(previous,new Bag(status))) {
438
+ this.registers.setItem('status',new Bag(status));
439
+ this.node.publish('formStatus',status);
440
+ }
441
+ for (const listener of this.listeners) listener(); });
442
+ }
443
+ commitField(path) {
444
+ for (const adapter of this.fields.values()) {
445
+ if (fieldPath(adapter.node) === path && Object.hasOwn(adapter.node,'formDraft')) adapter.commit();
446
+ }
447
+ }
448
+ /** Flush active drafts. Refuse errors/pending checks; accept only a valid local snapshot. */
449
+ accept() {
450
+ if (this.disposed) return false;
451
+ for (const adapter of this.fields.values()) {
452
+ if (Object.hasOwn(adapter.node,'formDraft')) adapter.commit();
453
+ }
454
+ if (!this.status.valid || this.status.pending) return false;
455
+ if (this.validationSources.size && this.validatedRevision !== this.validationRevision) return false;
456
+ this.registers.setItem('baseline',copy(this.data));
457
+ this.updateChanges();
458
+ return true;
459
+ }
460
+ load(data) {
461
+ if (!(data instanceof Bag)) throw new TypeError('Editing load requires a Bag.');
462
+ if (this.disposed) return;
463
+ this.registers.setItem('baseline',copy(data));
464
+ this.restore();
465
+ }
466
+ restore() {
467
+ if (this.disposed) return;
468
+ this.invalidateValidation();
469
+ for (const node of this.validations.keys()) this.cancelValidation(node);
470
+ for (const adapter of this.fields.values()) {
471
+ adapter.element.cancelValidation();
472
+ this.clearDraft(adapter.node);
473
+ adapter.element.restoreFormValue(this.registers.getItem('baseline').getItem(
474
+ adapter.node.absDatapath(adapter.node.getAttr('value')).slice(this.path ? this.path.length + 1 : 0)));
475
+ }
476
+ this.runtime.gramlot.data.setItem(this.path,copy(this.registers.getItem('baseline')));
477
+ for (const name of ['errors','pending','drafts']) this.registers.setItem(name,new Bag());
478
+ this.updateChanges();
479
+ for (const node of this.validations.keys()) this.scheduleField(node);
480
+ }
481
+ dispose() {
482
+ if (this.disposed) return;
483
+ this.disposed = true;
484
+ this.subscription.close();
485
+ for (const node of this.validations.keys()) this.forgetField(node);
486
+ this.fields.clear();
487
+ this.validationQueue.clear();
488
+ this.retainedFields.clear();
489
+ this.listeners.clear();
490
+ this.navigators.clear();
491
+ this.validationSources.clear();
492
+ this.clearValidationDependencies();
493
+ }
494
+ }
@@ -0,0 +1,57 @@
1
+ /** Scalar editor contract. Containers and unsupported objects remain inspectable. */
2
+ export const editorTypes = ['string', 'number', 'integer', 'boolean', 'date', 'time', 'datetime', 'null'];
3
+
4
+ export function scalarType(value) {
5
+ if (value === null) return 'null';
6
+ if (['string', 'boolean'].includes(typeof value)) return typeof value;
7
+ if (typeof value === 'number' && Number.isFinite(value)) return Number.isSafeInteger(value) ? 'integer' : 'number';
8
+ if (value instanceof Date && Number.isFinite(value.getTime())) {
9
+ const iso = value.toISOString();
10
+ return iso.slice(0, 10) === '1970-01-01' ? 'time' : iso.endsWith('T00:00:00.000Z') ? 'date' : 'datetime';
11
+ }
12
+ return null;
13
+ }
14
+
15
+ export function scalarText(value, type) {
16
+ if (type === 'null') return '';
17
+ if (value instanceof Date) {
18
+ const iso = value.toISOString();
19
+ return type === 'date' ? iso.slice(0, 10) : type === 'time' ? iso.slice(11, 23) : iso;
20
+ }
21
+ return String(value);
22
+ }
23
+
24
+ export function parseScalar(type, text) {
25
+ if (type === 'string') return text;
26
+ if (type === 'null') return null;
27
+ if (type === 'boolean' && ['true', 'false'].includes(text)) return text === 'true';
28
+ if (type === 'number' || type === 'integer') {
29
+ if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(text.trim())) {
30
+ const value = Number(text);
31
+ if (Number.isFinite(value) && (type !== 'integer' || Number.isSafeInteger(value))) return value;
32
+ }
33
+ }
34
+ if (['date', 'time', 'datetime'].includes(type)) {
35
+ const pattern = type === 'date' ? /^\d{4}-\d{2}-\d{2}$/
36
+ : type === 'time' ? /^\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?$/
37
+ : /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?Z$/;
38
+ if (pattern.test(text)) {
39
+ const input = type === 'date' ? `${text}T00:00:00Z` : type === 'time' ? `1970-01-01T${text}Z` : text;
40
+ const date = new Date(input);
41
+ if (Number.isFinite(date.getTime())) {
42
+ // Reject Date's normalization of invalid calendar dates and 24:00.
43
+ const iso = date.toISOString();
44
+ const supplied = input.replace(/Z$/, '').split(/[T:.]/);
45
+ const actual = iso.replace(/Z$/, '').split(/[T:.]/);
46
+ if (supplied.every((part, index) => index === 4 ? Number(part.padEnd(3, '0')) === Number(actual[index]) : part === actual[index])) return date;
47
+ }
48
+ }
49
+ }
50
+ throw new Error(`Invalid ${type} value: ${text || '(empty)'}`);
51
+ }
52
+
53
+ /** Read the portable component contract from a real Source node. */
54
+ export function readParameterEnums(node) {
55
+ return Object.fromEntries(Object.entries(node._getMeta('gramlot_component')?.parameters ?? {})
56
+ .filter(([, spec]) => spec.enum).map(([name, spec]) => [name, spec.enum]));
57
+ }
@@ -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
  }