@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,26 @@
1
+ /** Theme-owned colors; compact reports are shared by forms and grids. */
2
+ export const editingStatusStyles = `
3
+ :host{display:inline-block;font:inherit;color:var(--gramlot-ink,CanvasText)}
4
+ .control-box{display:flex;align-items:center;gap:.35rem}
5
+ button{font:inherit;color:inherit;cursor:pointer;border:0;background:transparent;border-radius:var(--gramlot-radius-sm,4px)}
6
+ .control-box>button{display:inline-flex;align-items:center;gap:.4rem;padding:.3rem .5rem;white-space:nowrap}
7
+ button:hover{background:var(--gramlot-surface-subtle,ButtonFace)}
8
+ button:focus-visible{outline:1px solid var(--gramlot-focus-ring,Highlight);outline-offset:-1px}
9
+ svg{width:1rem;height:1rem;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linejoin:round;stroke-linecap:round}
10
+ .count{font-variant-numeric:tabular-nums;color:var(--gramlot-text-secondary,GrayText)}
11
+ .invalid{color:var(--gramlot-error,#b3261e)}
12
+ .report{position:fixed;inset:auto;margin:0;padding:.65rem;min-width:15rem;width:28rem;
13
+ max-width:var(--gramlot-popup-available-width,calc(100vw - 16px));max-height:var(--gramlot-popup-available-height,60vh);overflow:auto;
14
+ border:1px solid var(--gramlot-border,ButtonBorder);border-radius:var(--gramlot-radius-md,8px);
15
+ background:var(--gramlot-surface,Canvas);color:var(--gramlot-ink,CanvasText);box-shadow:0 6px 24px #0002;font:inherit}
16
+ header{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:0 .35rem .45rem}
17
+ header button{font-size:1.2em;line-height:1;padding:.25rem .4rem}
18
+ ul{list-style:none;margin:0;padding:0}
19
+ li+li{border-top:1px solid var(--gramlot-border,ButtonBorder)}
20
+ li button{display:block;width:100%;text-align:start;padding:.55rem .35rem}
21
+ .field{display:block;font-weight:600;overflow-wrap:anywhere}
22
+ .detail{display:block;white-space:pre-wrap;overflow-wrap:anywhere;margin-top:.2rem}
23
+ .previous,.notice{color:var(--gramlot-text-secondary,GrayText)}
24
+ .arrow{padding:0 .5rem}
25
+ .notice{font-size:.9em;margin:.5rem .35rem .15rem}
26
+ `;
@@ -0,0 +1,115 @@
1
+ import {Bag} from '@gramlot/gramlot';
2
+ import {defineComponent} from './registry.js';
3
+ import {Container} from './container.js';
4
+ import {SVG_NS} from '../renderer/attributes.js';
5
+ import {positionPopup} from './popup.js';
6
+ import {editingStatusStyles} from './editing-status-styles.js';
7
+
8
+ /** Presentation of the nearest shared session. Registers and validation stay in EditingSession. */
9
+ export const EditingStatus = defineComponent({
10
+ name:'editingStatus', tag:'gramlot-editing-status', base:Container, sourceContext:true,
11
+ parameters:{},
12
+ implementation:Base => class extends Base {
13
+ #session; #release; #buttons = new Map(); #popup; #title; #list; #notice; #kind;
14
+ constructor() {
15
+ super();
16
+ const doc = this.ownerDocument;
17
+ const style = doc.createElement('style'); style.textContent = editingStatusStyles;
18
+ this.shadowRoot.append(style);
19
+ this.control.replaceChildren();
20
+ this.control.setAttribute('role','group'); this.control.setAttribute('aria-label','Editing reports');
21
+ for (const [kind,caption,path] of [
22
+ ['errors','Errors','M12 3L22 21H2ZM12 9V14M12 17V17.1'],
23
+ ['changes','Changes','M4 5H14M4 10H10M4 15H8M13 20L20 13L17 10L10 17L9 21Z']
24
+ ]) {
25
+ const button = doc.createElement('button'); button.type = 'button'; button.dataset.kind = kind;
26
+ button.setAttribute('aria-haspopup','dialog'); button.setAttribute('aria-expanded','false'); button.setAttribute('aria-controls','editing-report');
27
+ const svg = doc.createElementNS(SVG_NS,'svg'); svg.setAttribute('viewBox','0 0 24 24'); svg.setAttribute('aria-hidden','true');
28
+ const shape = doc.createElementNS(SVG_NS,'path'); shape.setAttribute('d',path); svg.append(shape);
29
+ const label = doc.createElement('span'); label.textContent = caption;
30
+ const count = doc.createElement('span'); count.className = 'count'; count.textContent = '0';
31
+ button.append(svg,label,count); this.control.append(button);
32
+ this.#buttons.set(kind,{button,count});
33
+ button.addEventListener('click',() => {
34
+ const open = this.#popup.matches(':popover-open');
35
+ if (open && this.#kind === kind) { this.#popup.hidePopover(); return; }
36
+ this.#kind = kind; this.#renderList();
37
+ if (!open) this.#popup.showPopover();
38
+ this.#expanded(); positionPopup(this.#popup,button,{align:'end'});
39
+ });
40
+ }
41
+ this.#popup = doc.createElement('section'); this.#popup.id = 'editing-report';
42
+ this.#popup.className = 'report'; this.#popup.setAttribute('popover','auto');
43
+ this.#popup.setAttribute('role','dialog'); this.#popup.setAttribute('aria-labelledby','report-title');
44
+ const heading = doc.createElement('header');
45
+ this.#title = doc.createElement('strong'); this.#title.id = 'report-title';
46
+ const close = doc.createElement('button'); close.type = 'button'; close.textContent = '×'; close.setAttribute('aria-label','Close report');
47
+ close.addEventListener('click',() => this.#popup.hidePopover()); heading.append(this.#title,close);
48
+ this.#list = doc.createElement('ul');
49
+ this.#notice = doc.createElement('p'); this.#notice.className = 'notice'; this.#notice.setAttribute('role','status');
50
+ this.#popup.append(heading,this.#list,this.#notice); this.shadowRoot.append(this.#popup);
51
+ this.#popup.addEventListener('toggle',() => this.#expanded());
52
+ }
53
+ setSourceContext(context) {
54
+ this.#release?.(); this.#release = null;
55
+ this.#session = context.sourceNode.formState;
56
+ if (!this.#session) throw new Error('editingStatus requires a shared editing session.');
57
+ this.#connect();
58
+ }
59
+ connectedCallback() { this.#connect(); }
60
+ disconnectedCallback() {
61
+ this.#release?.(); this.#release = null;
62
+ if (this.#popup.matches(':popover-open')) this.#popup.hidePopover();
63
+ }
64
+ #connect() {
65
+ if (!this.#session || this.#release || !this.isConnected) return;
66
+ this.#release = this.#session.subscribe(() => this.#refresh()); this.#refresh();
67
+ }
68
+ #expanded() {
69
+ const open = this.#popup.matches(':popover-open');
70
+ for (const [kind,{button}] of this.#buttons) button.setAttribute('aria-expanded',String(open && kind === this.#kind));
71
+ }
72
+ #refresh() {
73
+ this.#buttons.get('errors').count.textContent = String(this.#session.errorEntries.length);
74
+ this.#buttons.get('changes').count.textContent = String(this.#session.changeEntries.length);
75
+ this.#buttons.get('errors').button.classList.toggle('invalid',this.#session.errorEntries.length > 0);
76
+ if (this.#popup.matches(':popover-open')) this.#renderList();
77
+ }
78
+ #value(value,exists) {
79
+ if (!exists) return 'Not present';
80
+ if (value == null) return '∅';
81
+ if (value instanceof Bag) return `${value.length} fields`;
82
+ if (value instanceof Date) return value.toLocaleString();
83
+ return String(value);
84
+ }
85
+ #renderList() {
86
+ const errors = this.#kind === 'errors';
87
+ const entries = errors ? this.#session.errorEntries : this.#session.changeEntries;
88
+ this.#title.textContent = errors ? 'Validation errors' : 'Unsaved changes';
89
+ this.#notice.textContent = entries.length ? 'Select an entry to return to its field.' : (errors ? 'No validation errors.' : 'No changes since the accepted snapshot.');
90
+ // Preserve list focus when asynchronous validation updates another entry.
91
+ const focusedPath = this.shadowRoot.activeElement?.dataset.path;
92
+ this.#list.replaceChildren();
93
+ for (const entry of entries) {
94
+ const doc = this.ownerDocument, item = doc.createElement('li'), button = doc.createElement('button');
95
+ button.type = 'button'; button.dataset.path = entry.path;
96
+ const field = doc.createElement('span'); field.className = 'field';
97
+ field.textContent = entry.path.slice(this.#session.path ? this.#session.path.length+1 : 0);
98
+ const detail = doc.createElement('span'); detail.className = 'detail';
99
+ if (errors) detail.textContent = entry.message;
100
+ else {
101
+ const before = doc.createElement('span'); before.className = 'previous'; before.textContent = this.#value(entry.previous,entry.existed);
102
+ const arrow = doc.createElement('span'); arrow.className = 'arrow'; arrow.textContent = '→';
103
+ const after = doc.createElement('span'); after.className = 'current'; after.textContent = this.#value(entry.current,entry.exists);
104
+ detail.append(before,arrow,after);
105
+ }
106
+ button.append(field,detail); item.append(button); this.#list.append(item);
107
+ button.addEventListener('click',() => {
108
+ if (this.#session.focusField(entry.path)) this.#popup.hidePopover();
109
+ else this.#notice.textContent = 'This field is not visible. Check the grid filter or whether the row still exists.';
110
+ });
111
+ if (entry.path === focusedPath) button.focus({preventScroll:true});
112
+ }
113
+ }
114
+ }
115
+ });
@@ -1,20 +1,28 @@
1
1
  import {validateInput, validationParameters} from './validation.js';
2
+ import {ValidationRun} from '../validation-run.js';
2
3
  import {positionPopup} from './popup.js';
4
+ import {parameterValues} from './parameters.js';
3
5
 
4
6
  const MESSAGE_DURATION = 1800;
5
7
  const MESSAGE_FADE_DURATION = 200;
6
8
 
7
- /** Shared candidate validation and presentation; ControlAdapter alone writes Data. */
9
+ /** Validation presentation; sessions own execution independently of mounted controls. */
8
10
  export function FieldState(Base) {
9
11
  return class extends Base {
10
12
  get supportsFormValidation() { return true; }
13
+ static validationParameters(attrs) {
14
+ const parameters = {...parameterValues(this.gramlotComponent,attrs),...attrs};
15
+ if (this.constrained && parameters.validate_select == null) parameters.validate_select = true;
16
+ return parameters;
17
+ }
18
+ static get validationExecutor() { return validateInput; }
19
+ get validationExecutor() { return this.constructor.validationExecutor; }
11
20
  connectedCallback() { super.connectedCallback(); if (this.pageContext?.form) this.pageContext.formValidate(); }
12
21
  #rejected = false;
13
22
  #projected;
14
23
  #messageTimer;
15
24
  #messageEvents;
16
- #validation;
17
- #validationEpoch = 0;
25
+ #validation = new ValidationRun();
18
26
  #validationCurrent;
19
27
  #rules = {};
20
28
  validationResult = null;
@@ -69,7 +77,7 @@ export function FieldState(Base) {
69
77
  view.addEventListener('scroll', () => this.#hideMessage(), options);
70
78
  view.addEventListener('resize', () => this.#hideMessage(), options);
71
79
  }
72
- releaseControl() { this.cancelValidation(); this.#hideMessage(); super.releaseControl(); }
80
+ releaseControl() { this.#validation.cancel(); this.#hideMessage(); super.releaseControl(); }
73
81
  disconnectedCallback() { this.releaseControl(); }
74
82
  setFieldState({invalid = false, pending = false} = {}) {
75
83
  this.control.setAttribute('aria-invalid', String(invalid));
@@ -84,71 +92,49 @@ export function FieldState(Base) {
84
92
  }
85
93
  restoreFormValue(value) { this.error(''); this.#rejected = false; super.restoreFormValue(value); }
86
94
  cancelValidation() {
87
- if (this.pageContext?.form) this.pageContext.formPending(false);
88
- this.#validationEpoch++;
89
- this.#validation?.abort(); this.#validation = null; this.#validationCurrent = null;
95
+ if (this.pageContext?.form) this.pageContext.formCancelValidation();
96
+ this.#validation.cancel(); this.#validationCurrent = null;
90
97
  this.control.setAttribute('aria-busy', 'false');
91
98
  }
99
+ presentValidation(result) {
100
+ this.validationResult = result;
101
+ this.control.setAttribute('aria-busy','false');
102
+ this.error(result.error || '');
103
+ this.message.dataset.severity = result.error ? 'error' : 'warning';
104
+ this.#rejected = Boolean(result.error);
105
+ if (!result.error && result.warnings.length) {
106
+ this.message.textContent = result.warnings.join('\n'); this.#showMessage();
107
+ }
108
+ }
92
109
  validateCandidate(value, accept) {
93
- this.cancelValidation();
94
- if (this.pageContext.form) this.pageContext.formCandidate(value);
95
- const controller = new AbortController(); this.#validation = controller;
96
- const epoch = this.#validationEpoch;
97
- const rules = this.#rules;
98
- const current = this.pageContext.validationCurrent(); this.#validationCurrent = current;
99
- const valid = () => this.#validationEpoch === epoch && !controller.signal.aborted && current();
100
- const failure = error => ({value, modified:false, error:error.message, warnings:[], issues:[], datachanges:[]});
101
- const finish = result => {
102
- if (!valid()) {
103
- if (this.#validation === controller) this.cancelValidation();
104
- return {ok:false};
105
- }
106
- this.#validation = null; this.#validationCurrent = null;
107
- this.control.setAttribute('aria-busy', 'false');
108
- try { if (!result.error || this.pageContext.form) accept(result.value); }
109
- catch (error) { result = failure(error); }
110
- if (this.pageContext.form) this.pageContext.formResult(result);
111
- this.validationResult = result;
112
- this.error(result.error || ''); this.message.dataset.severity = result.error ? 'error' : 'warning'; this.#rejected = Boolean(result.error);
113
- if (!result.error && result.warnings.length) {
114
- this.message.textContent = result.warnings.join('\n'); this.#showMessage();
115
- }
116
- const outcome = {ok:!result.error, value:result.value, result, rules, isCurrent:valid};
117
- if (!outcome.ok) this.finishValidation(outcome);
118
- return outcome;
119
- };
120
- let result;
121
- try {
122
- if (rules.validate_timeout != null && (!Number.isInteger(rules.validate_timeout) || rules.validate_timeout <= 0)) throw new TypeError('validate_timeout must be a positive integer in milliseconds.');
123
- result = validateInput(value, rules, {...this.pageContext, signal:controller.signal, selection:value => this.validateSelection(value)});
110
+ if (this.pageContext.form) {
111
+ // Capture selection evidence before accepting clears the choice's picked row.
112
+ const selection = this.validationSelection();
113
+ accept(value);
114
+ return this.pageContext.formValidateCandidate(value,selection);
124
115
  }
125
- catch (error) { return finish(failure(error)); }
126
- if (!(result instanceof Promise)) return finish(result);
127
- if (this.pageContext.form) this.pageContext.formPending(true);
128
- this.control.setAttribute('aria-busy', 'true');
129
- return new Promise(resolve => {
130
- let timer;
131
- const abort = () => { clearTimeout(timer); resolve({ok:false}); };
132
- controller.signal.addEventListener('abort', abort, {once:true});
133
- const settle = answer => {
134
- clearTimeout(timer); controller.signal.removeEventListener('abort', abort);
135
- resolve(finish(answer));
136
- };
137
- if (rules.validate_timeout != null) timer = setTimeout(() => {
138
- settle(failure(new Error('Validation timed out.'))); controller.abort();
139
- }, rules.validate_timeout);
140
- result.then(settle, error => settle(failure(error)));
141
- });
116
+ this.cancelValidation();
117
+ this.#validationCurrent = this.pageContext.validationCurrent();
118
+ return this.#validation.start(value,this.#rules,
119
+ {...this.pageContext,selection:value => this.validateSelection(value)},validateInput,outcome => {
120
+ this.#validationCurrent = null;
121
+ if (outcome.ok) {
122
+ try { accept(outcome.value); }
123
+ catch (error) { outcome.ok = false; outcome.result.error = error.message; }
124
+ }
125
+ this.presentValidation(outcome.result);
126
+ if (!outcome.ok) this.finishValidation(outcome);
127
+ },() => this.control.setAttribute('aria-busy','true'));
142
128
  }
143
129
  finishValidation(outcome) {
144
130
  if (!outcome.result) return;
145
131
  this.pageContext.finishValidation(outcome);
146
132
  }
147
133
  shouldProjectControlValue(value) {
148
- if (this.#validationCurrent && !this.#validationCurrent()) this.cancelValidation();
134
+ if (!this.pageContext?.form && this.#validationCurrent && !this.#validationCurrent()) this.cancelValidation();
149
135
  const same = this.sameControlValue(value, this.#projected);
150
136
  if (same && this.#rejected) return false;
151
- if (!same) this.cancelValidation();
137
+ if (!same && !this.pageContext?.form) this.cancelValidation();
152
138
  this.#projected = value;
153
139
  if (!same && this.#rejected) this.error('');
154
140
  return true;
@@ -157,7 +143,7 @@ export function FieldState(Base) {
157
143
  const rest = super.projectAttributes(attrs, adapt);
158
144
  const rules = Object.fromEntries(Object.entries(attrs).filter(([name]) => name.startsWith('validate_')));
159
145
  const keys = new Set([...Object.keys(rules), ...Object.keys(this.#rules)]);
160
- if ([...keys].some(key => !Object.is(rules[key], this.#rules[key])) || attrs.disabled || attrs.readonly) this.cancelValidation();
146
+ if (!this.pageContext?.form && ([...keys].some(key => !Object.is(rules[key], this.#rules[key])) || attrs.disabled || attrs.readonly)) this.cancelValidation();
161
147
  const rulesChanged = [...keys].some(key => !Object.is(rules[key], this.#rules[key]));
162
148
  this.#rules = rules;
163
149
  if (rulesChanged && this.pageContext?.form) this.pageContext.formValidate();
@@ -0,0 +1,245 @@
1
+ import {sourceTarget, toTytx} from '@gramlot/gramlot';
2
+
3
+ /** Grid navigation and temporary Source controls; all editing registers belong to the shared session. */
4
+ export class GridCellEditor {
5
+ constructor(grid, context, cellFor, store, renderedRows, navigate, focusField) {
6
+ this.grid = grid;
7
+ this.context = context;
8
+ this.cellFor = cellFor;
9
+ this.store = store;
10
+ this.renderedRows = renderedRows;
11
+ this.navigate = navigate;
12
+ this.focusField = focusField;
13
+ this.retained = new Map();
14
+ this.declarations = new Map();
15
+ this.checking = new Set();
16
+ this.columns = [];
17
+ this.layer = grid.ownerDocument.createElement('div');
18
+ this.layer.className = 'cell-editor'; this.layer.hidden = true;
19
+ const slot = grid.ownerDocument.createElement('slot'); slot.name = 'cell-editor'; this.layer.append(slot);
20
+ grid.control.append(this.layer);
21
+ this.keydown = event => {
22
+ if (!this.active || event.isComposing) return;
23
+ if (event.key === 'Escape') {
24
+ event.preventDefault();
25
+ const cell = this.cellFor(this.active.row,this.active.column.field);
26
+ this.session.clearDraft(this.active.source);
27
+ this.close(); cell?.focus({preventScroll:true});
28
+ } else if (event.key === 'Enter' || event.key === 'Tab') {
29
+ if (event.key === 'Enter' && this.active.element.control.localName === 'textarea' && !event.ctrlKey && !event.metaKey) return;
30
+ event.preventDefault();
31
+ const active = this.active;
32
+ this.session.commitField(active.path);
33
+ const cell = this.cellFor(active.row,active.column.field);
34
+ this.close(); cell?.focus({preventScroll:true});
35
+ if (event.key === 'Tab') this.navigate(active.row,active.column.field,event.shiftKey ? -1 : 1);
36
+ }
37
+ };
38
+ this.arrowKeydown = event => {
39
+ if (!this.active || event.isComposing || !['ArrowUp','ArrowDown','ArrowLeft','ArrowRight'].includes(event.key) || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
40
+ const control = this.active.element.control;
41
+ if (control.localName === 'textarea' || ['range','date','time','datetime-local'].includes(control.type)) return;
42
+ // Composite controls own their popup arrows; date/time fields own their editing keys.
43
+ if (['gramlot-date-text-box','gramlot-time-text-box','gramlot-date-calendar'].includes(this.active.element.localName)) return;
44
+ if (control.getAttribute('aria-expanded') === 'true' || (event.key === 'ArrowDown' && control.getAttribute('role') === 'combobox')) return;
45
+ const horizontal = event.key === 'ArrowLeft' || event.key === 'ArrowRight';
46
+ const backwards = event.key === 'ArrowLeft' || event.key === 'ArrowUp';
47
+ if (horizontal) {
48
+ if (typeof control.selectionStart !== 'number' || control.selectionStart !== control.selectionEnd) return;
49
+ if (control.selectionStart !== (backwards ? 0 : control.value.length)) return;
50
+ }
51
+ event.preventDefault(); event.stopPropagation();
52
+ const active = this.active;
53
+ this.session.commitField(active.path);
54
+ this.navigate(active.row,active.column.field,horizontal ? (backwards ? -1 : 1) : {row:backwards ? -1 : 1});
55
+ if (horizontal && this.active && this.active !== active) {
56
+ const target = this.active.element.control;
57
+ if (typeof target.selectionStart === 'number') {
58
+ const caret = backwards ? target.value.length : 0;
59
+ target.setSelectionRange(caret,caret);
60
+ }
61
+ }
62
+ };
63
+ this.connect();
64
+ context.sourceNode.rootBuilder.binding.bindingFor(context.sourceNode).track(() => this.dispose());
65
+ }
66
+ connect() {
67
+ this.grid.addEventListener('keydown',this.keydown);
68
+ this.grid.addEventListener('keydown',this.arrowKeydown,true);
69
+ if (this.session && !this.releaseNavigator) this.releaseNavigator = this.session.registerNavigator(this.focusField);
70
+ }
71
+ disconnect() {
72
+ this.close();
73
+ this.grid.removeEventListener('keydown',this.keydown);
74
+ this.grid.removeEventListener('keydown',this.arrowKeydown,true);
75
+ this.releaseNavigator?.(); this.releaseNavigator = null;
76
+ }
77
+ path(row, field) {
78
+ const {mode} = this.store();
79
+ return this.context.sourceNode.absDatapath(this.context.sourceNode.getAttr('storepath')) + '.' + row.label + (mode === 'attributes' ? '?' : '.') + field;
80
+ }
81
+ configure(columns) {
82
+ const editable = columns.filter(column => column.edit);
83
+ if (editable.length) {
84
+ if (this.store().window !== null) throw new Error('Editing requires a fully resident Bag; remote windows are read-only.');
85
+ const owner = this.context.sourceNode;
86
+ this.session = owner.editCollection(owner.absDatapath(owner.getAttr('storepath')));
87
+ }
88
+ const signature = toTytx(editable.map(({field,dtype,edit}) => ({field,dtype,edit})));
89
+ if (signature === this.validationSignature) return;
90
+ this.validationSignature = signature;
91
+ this.columns = editable;
92
+ for (const [path,declaration] of this.declarations) {
93
+ const column = editable.find(column => column.field === declaration.field);
94
+ if (!column) {
95
+ if (this.active?.path === path) this.close();
96
+ this.releaseField(path);
97
+ } else {
98
+ const {tag,options} = this.definition(column);
99
+ if (tag !== declaration.tag) {
100
+ if (this.active?.path === path) this.close();
101
+ this.releaseField(path);
102
+ } else {
103
+ declaration.source.setAttr({...Object.fromEntries(Object.keys(declaration.options).map(key => [key,null])),...options});
104
+ declaration.options = options;
105
+ }
106
+ }
107
+ }
108
+ if (!editable.length) {
109
+ this.releaseValidation?.(); this.releaseValidation = null;
110
+ return;
111
+ }
112
+ if (!this.releaseStatus) this.releaseStatus = this.session.subscribe(() => this.refresh());
113
+ if (!this.releaseNavigator) this.releaseNavigator = this.session.registerNavigator(this.focusField);
114
+ if (!this.releaseValidation) this.releaseValidation = this.session.registerValidationSource(() => this.validationFields());
115
+ else this.session.invalidateValidation();
116
+ }
117
+ definition(column) {
118
+ const options = column.edit === true ? {} : {...column.edit};
119
+ const tag = options.tag ?? ({L:'numberTextBox',R:'numberTextBox',N:'numberTextBox',D:'dateTextBox',H:'timeTextBox',B:'checkBox'}[column.dtype] ?? 'textbox');
120
+ if (column.dtype === 'DHZ' && !options.tag) throw new Error('A datetime column requires an explicitly declared supported editor.');
121
+ delete options.tag;
122
+ return {tag,options:{...options,dtype:column.dtype ?? 'T'}};
123
+ }
124
+ *validationFields() {
125
+ const owner = this.context.sourceNode;
126
+ this.session.trackValidationDependency(owner.absDatapath(owner.getAttr('structpath')));
127
+ const bag = this.store().bag;
128
+ for (const row of bag.getNodes()) for (const column of this.columns) {
129
+ if (row.parentBag !== bag) continue;
130
+ const path = this.path(row,column.field);
131
+ this.checking.add(path);
132
+ try {
133
+ const declaration = this.declare(row,column,false);
134
+ yield {node:declaration.source,release:() => {
135
+ this.checking.delete(path);
136
+ if (path !== this.active?.path) this.releaseCleanField(path);
137
+ }};
138
+ } catch (error) { this.checking.delete(path); this.releaseCleanField(path); throw error; }
139
+ }
140
+ }
141
+ open(row, column, cell) {
142
+ if (this.store().window !== null) throw new Error('Editing requires a fully resident Bag; remote windows are read-only.');
143
+ if (this.active?.row === row && this.active.column.field === column.field) { this.active.element.control.focus(); return; }
144
+ this.close();
145
+ const path = this.path(row,column.field), declaration = this.declare(row,column,true);
146
+ const element = this.grid.ownerDocument.getElementById(declaration.id);
147
+ this.active = {row,column,path,...declaration,element};
148
+ this.layer.hidden = false;
149
+ this.position(cell);
150
+ element.control.focus();
151
+ }
152
+ declare(row,column,mount) {
153
+ const owner = this.context.sourceNode, path = this.path(row,column.field);
154
+ if (!this.retained.has(path)) { this.session.retainField(path); this.retained.set(path,row); }
155
+ let declaration = this.declarations.get(path);
156
+ if (!declaration) {
157
+ const {tag,options} = this.definition(column);
158
+ if (!owner.rootBuilder.schemaTag(tag)) throw new Error(`Grid editor requires the ${tag} input collection.`);
159
+ const builder = owner.rootBuilder, id = `grid-cell-${crypto.randomUUID()}`;
160
+ const container = builder.wrapSource(owner).div({node_label:id, slot:'cell-editor'});
161
+ // Unmount the branch before declaring a control: no editor element is constructed.
162
+ if (!mount) builder.binding.renderer.unmountView(sourceTarget(container));
163
+ try {
164
+ const control = container[tag]({...options, value:'^'+path, id, width:'100%', margin:'0'});
165
+ declaration = {container:sourceTarget(container),source:sourceTarget(control),id,tag,options,field:column.field};
166
+ const component = this.grid.ownerDocument.defaultView.customElements.get(declaration.source._getMeta('render_tag'));
167
+ this.session.registerField(declaration.source,component,mount);
168
+ this.declarations.set(path,declaration);
169
+ } catch (error) {
170
+ const node = sourceTarget(container); node.parentBag.popNode(node.label);
171
+ this.releaseCleanField(path);
172
+ throw error;
173
+ }
174
+ } else if (mount) owner.rootBuilder.binding.renderer.mountView(declaration.container);
175
+ return declaration;
176
+ }
177
+ close() {
178
+ const active = this.active;
179
+ this.active = null; this.layer.hidden = true;
180
+ if (active) {
181
+ this.context.sourceNode.rootBuilder.binding.renderer.unmountView(active.container);
182
+ this.releaseCleanField(active.path);
183
+ }
184
+ }
185
+ releaseCleanField(path) {
186
+ if (this.checking.has(path)) return;
187
+ const state = this.session.fieldStatus(path);
188
+ if (state.error === null && state.pending === null && state.draft === null && this.retained.has(path)) {
189
+ this.releaseField(path);
190
+ }
191
+ }
192
+ releaseField(path) {
193
+ const declaration = this.declarations.get(path);
194
+ this.declarations.delete(path);
195
+ if (declaration?.container.parentBag) declaration.container.parentBag.popNode(declaration.container.label);
196
+ this.session.releaseField(path); this.retained.delete(path);
197
+ }
198
+ position(cell = null) {
199
+ if (!this.active) return;
200
+ cell ??= this.cellFor(this.active.row,this.active.column.field);
201
+ if (!cell) { this.close(); return; }
202
+ const rect = cell.getBoundingClientRect(), host = this.grid.control.getBoundingClientRect();
203
+ const viewport = this.grid.shadowRoot.querySelector('.body-viewport').getBoundingClientRect();
204
+ Object.assign(this.layer.style,{
205
+ left:`${rect.left-host.left-this.grid.control.clientLeft}px`,
206
+ top:`${rect.top-host.top-this.grid.control.clientTop}px`,width:`${rect.width}px`
207
+ });
208
+ this.layer.style.setProperty('--grid-editor-height',`${rect.height}px`);
209
+ const maxHeight = cell.style.getPropertyValue('--grid-cell-max-height');
210
+ if (maxHeight) this.layer.style.setProperty('--grid-cell-max-height',maxHeight);
211
+ else this.layer.style.removeProperty('--grid-cell-max-height');
212
+ const editor = this.layer.getBoundingClientRect();
213
+ if (viewport.height && (editor.top < viewport.top || editor.bottom > viewport.bottom || editor.right <= viewport.left || editor.left >= viewport.right)) this.close();
214
+ }
215
+ decorate(tr, row) {
216
+ if (!this.session) return;
217
+ for (const cell of tr.querySelectorAll('td[data-field]')) {
218
+ const state = this.session.fieldStatus(this.path(row,cell.dataset.field));
219
+ cell.classList.toggle('invalid-cell',Boolean(state.error));
220
+ cell.classList.toggle('draft-cell',state.draft !== null);
221
+ if (state.error) { cell.setAttribute('aria-invalid','true'); cell.title = state.error.getNodes().map(n => n.value).join('\n'); }
222
+ else { cell.removeAttribute('aria-invalid'); cell.removeAttribute('title'); }
223
+ }
224
+ }
225
+ refresh() {
226
+ const bag = this.store().bag;
227
+ for (const [path,row] of this.retained) if (row.parentBag !== bag) {
228
+ this.releaseField(path);
229
+ if (this.active?.row === row) this.close();
230
+ }
231
+ for (const path of this.retained.keys()) if (path !== this.active?.path) this.releaseCleanField(path);
232
+ for (const [row,tr] of this.renderedRows()) this.decorate(tr,row);
233
+ }
234
+ replaceData() {
235
+ this.close();
236
+ if (this.session) {
237
+ for (const path of this.retained.keys()) this.releaseField(path);
238
+ this.retained.clear();
239
+ }
240
+ }
241
+ dispose() {
242
+ this.releaseValidation?.(); this.releaseValidation = null;
243
+ this.disconnect(); this.replaceData(); this.releaseStatus?.(); this.layer.remove();
244
+ }
245
+ }
@@ -101,6 +101,27 @@
101
101
  "has_default": true,
102
102
  "default": null
103
103
  },
104
+ {
105
+ "name": "max_height",
106
+ "kind": "keyword_only",
107
+ "role": "attribute",
108
+ "annotation": {
109
+ "kind": "annotated",
110
+ "base": {
111
+ "kind": "dtype",
112
+ "dtype": "T"
113
+ },
114
+ "metadata": [
115
+ {
116
+ "kind": "regex",
117
+ "pattern": "^[0-9]+([.][0-9]+)?(px|em|rem)$",
118
+ "flags": 0
119
+ }
120
+ ]
121
+ },
122
+ "has_default": true,
123
+ "default": null
124
+ },
104
125
  {
105
126
  "name": "align",
106
127
  "kind": "keyword_only",
@@ -153,6 +174,27 @@
153
174
  },
154
175
  "has_default": true,
155
176
  "default": null
177
+ },
178
+ {
179
+ "name": "edit",
180
+ "kind": "keyword_only",
181
+ "role": "attribute",
182
+ "annotation": {
183
+ "kind": "union",
184
+ "items": [
185
+ {
186
+ "kind": "dtype",
187
+ "dtype": "B"
188
+ },
189
+ {
190
+ "kind": "type",
191
+ "module": "builtins",
192
+ "name": "dict"
193
+ }
194
+ ]
195
+ },
196
+ "has_default": true,
197
+ "default": false
156
198
  }
157
199
  ],
158
200
  "accepts_var_keyword": false,
@@ -1,7 +1,7 @@
1
1
  import {Bag} from '@gramlot/gramlot';
2
2
 
3
3
  const TYPES = new Set(['T', 'B', 'L', 'R', 'N', 'D', 'H', 'DHZ']);
4
- const COLUMN_KEYS = new Set(['tag', 'field', 'name', 'dtype', 'width', 'align', 'format', 'columnset', 'white_space']);
4
+ const COLUMN_KEYS = new Set(['tag', 'field', 'name', 'dtype', 'width', 'align', 'format', 'columnset', 'white_space', 'max_height', 'edit']);
5
5
  const GROUP_KEYS = new Set(['tag', 'code', 'name', 'background', 'color']);
6
6
 
7
7
  /** Legacy Data contract: ordered cells and independent columnset definitions. */
@@ -39,8 +39,12 @@ export class GridStructure {
39
39
  if (attrs.width != null && (typeof attrs.width !== 'string' || !/^(?:\d+(?:\.\d+)?)(?:px|em|rem|ch|%)$/.test(attrs.width))) {
40
40
  throw new TypeError('grid width requires a nonnegative CSS length (px, em, rem, ch or %)');
41
41
  }
42
+ if (attrs.max_height != null && (typeof attrs.max_height !== 'string' || !/^(?:\d+(?:\.\d+)?)(?:px|em|rem)$/.test(attrs.max_height))) {
43
+ throw new TypeError('grid max_height requires a nonnegative CSS length (px, em or rem)');
44
+ }
42
45
  if (attrs.white_space != null && !['normal','nowrap','pre-wrap'].includes(attrs.white_space)) throw new TypeError('grid white_space requires normal, nowrap or pre-wrap');
43
46
  for (const key of ['name', 'format']) if (attrs[key] != null && typeof attrs[key] !== 'string') throw new TypeError(`grid ${key} must be text`);
47
+ if (attrs.edit != null && typeof attrs.edit !== 'boolean' && (typeof attrs.edit !== 'object' || Array.isArray(attrs.edit))) throw new TypeError('grid edit requires a boolean or editor options');
44
48
  const column = Object.freeze({...attrs, name: attrs.name ?? attrs.field,
45
49
  align: attrs.align ?? (['L', 'R', 'N'].includes(attrs.dtype) ? 'end' : 'start')});
46
50
  this.columns.push(column);