@gramlot/gramlot 0.3.19 → 0.3.24

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 (102) hide show
  1. package/dist/components/chat/__init__.py +13 -0
  2. package/dist/components/chat/assets/collection.js +9 -0
  3. package/dist/components/chat/assets/index.js +3 -0
  4. package/dist/components/chat/commands.json +7 -0
  5. package/dist/components/chat/grammar.json +48 -0
  6. package/dist/components/editors/__init__.py +2 -2
  7. package/dist/components/editors/assets/collection.js +22 -120909
  8. package/dist/components/editors/assets/index.js +2 -1
  9. package/dist/components/editors/assets/modules/chunk-AU4HFPIY.js +1 -0
  10. package/dist/components/editors/assets/modules/chunk-MMJXUHRQ.js +3 -0
  11. package/dist/components/editors/assets/modules/chunk-OCFLP2K4.js +16 -0
  12. package/dist/components/editors/assets/modules/chunk-YSGSC7KM.js +1 -0
  13. package/dist/components/editors/assets/modules/code-mirror-engine-QX4A5FVO.js +92 -0
  14. package/dist/components/editors/assets/modules/jodit-engine-MMSPIWM7.js +1853 -0
  15. package/dist/components/editors/assets/modules/prose-mirror-engine-IXTRTG6B.js +24 -0
  16. package/dist/components/grid/__init__.py +13 -0
  17. package/dist/components/grid/assets/collection.js +211 -0
  18. package/dist/components/grid/assets/index.js +3 -0
  19. package/dist/components/grid/commands.json +7 -0
  20. package/dist/components/grid/grammar.json +714 -0
  21. package/dist/components/grouplets/__init__.py +13 -0
  22. package/dist/components/grouplets/assets/collection.js +202 -0
  23. package/dist/components/grouplets/assets/index.js +3 -0
  24. package/dist/components/grouplets/commands.json +7 -0
  25. package/dist/components/grouplets/grammar.json +355 -0
  26. package/dist/components/inputs/__init__.py +1 -1
  27. package/dist/components/inputs/assets/collection.js +32 -24503
  28. package/dist/components/inputs/assets/index.js +2 -1
  29. package/dist/components/inputs/grammar.json +214 -6
  30. package/dist/components/layout/__init__.py +1 -1
  31. package/dist/components/layout/assets/collection.js +27 -26701
  32. package/dist/components/layout/assets/index.js +2 -1
  33. package/dist/components/layout/grammar.json +4 -0
  34. package/dist/components/selection_trial/__init__.py +13 -0
  35. package/dist/components/selection_trial/assets/collection.js +4 -0
  36. package/dist/components/selection_trial/assets/index.js +3 -0
  37. package/dist/components/selection_trial/commands.json +7 -0
  38. package/dist/components/selection_trial/grammar.json +552 -0
  39. package/dist/components/tree/__init__.py +1 -1
  40. package/dist/components/tree/assets/collection.js +24 -24612
  41. package/dist/components/tree/assets/index.js +2 -1
  42. package/dist/components/typst/__init__.py +2 -2
  43. package/dist/components/typst/assets/collection.js +12 -4
  44. package/dist/components/typst/assets/index.js +2 -1
  45. package/dist/components/typst/assets/modules/chunk-BLMUM44K.js +1 -0
  46. package/dist/components/typst/assets/modules/typst-client-JHC6UVYG.js +4 -0
  47. package/dist/gramlot.js +2749 -1627
  48. package/dist/gramlot.min.js +46 -41
  49. package/package.json +7 -2
  50. package/src/binding/grid-struct.js +63 -0
  51. package/src/binding/installation.js +5 -2
  52. package/src/binding/runtime.js +51 -6
  53. package/src/builder/gramlot-builder.d.ts +5 -0
  54. package/src/builder/gramlot-builder.js +16 -0
  55. package/src/builder/source.js +23 -0
  56. package/src/chat.d.ts +12 -0
  57. package/src/chat.js +198 -0
  58. package/src/collection-artifact.js +1 -1
  59. package/src/components/bases.js +2 -0
  60. package/src/components/chat.js +28 -0
  61. package/src/components/choice-editor.js +89 -34
  62. package/src/components/database-choices.js +131 -9
  63. package/src/components/field-state.js +10 -1
  64. package/src/components/grid-grammar.json +237 -0
  65. package/src/components/grid-header-interaction.js +196 -0
  66. package/src/components/grid-row-interaction.js +184 -0
  67. package/src/components/grid-row-layout.js +96 -0
  68. package/src/components/grid-rows.js +28 -0
  69. package/src/components/grid-search-box.js +142 -0
  70. package/src/components/grid-search-styles.js +42 -0
  71. package/src/components/grid-search.js +37 -0
  72. package/src/components/grid-structure.js +84 -0
  73. package/src/components/grid-styles.js +151 -0
  74. package/src/components/grid.js +589 -0
  75. package/src/components/grouplet-card.js +437 -0
  76. package/src/components/grouplets.js +17 -0
  77. package/src/components/menus.js +1 -0
  78. package/src/components/registry.js +4 -3
  79. package/src/components/tray-pane.js +32 -4
  80. package/src/components/typed-editor.js +4 -2
  81. package/src/experiments/selection-transfer.js +78 -0
  82. package/src/experiments/selection-trial.js +48 -0
  83. package/src/experiments/window-selection.js +124 -0
  84. package/src/form-state.d.ts +20 -0
  85. package/src/form-state.js +198 -0
  86. package/src/index-page-styles.js +1 -1
  87. package/src/index.d.ts +3 -1
  88. package/src/index.js +3 -1
  89. package/src/renderer/gramlot-renderer.js +8 -1
  90. package/src/server/gramlot-server.d.ts +2 -0
  91. package/src/server/gramlot-server.js +13 -1
  92. package/src/stores/bag-collection-store.js +51 -0
  93. package/src/stores/bag-collection-view.js +127 -0
  94. package/src/stores/collection-filter.js +77 -0
  95. package/src/view/controls.js +33 -1
  96. package/src/view/grouplet-card.js +54 -0
  97. package/src/view/html.js +20 -3
  98. package/src/view/labelbox.js +7 -3
  99. package/themes/gramlot-base/theme.css +28 -0
  100. package/themes/gramlot-compact/theme.css +8 -0
  101. package/themes/joanna/theme.css +8 -0
  102. package/themes/mimi/theme.css +8 -0
@@ -17,6 +17,7 @@ export function ChoiceEditor(HTMLElement) {
17
17
  #separator;
18
18
  #cleanup;
19
19
  #requestController;
20
+ #resolvingValue = false;
20
21
  #searchTimer;
21
22
  constructor() {
22
23
  super();
@@ -25,9 +26,11 @@ export function ChoiceEditor(HTMLElement) {
25
26
  style.textContent = `.option{position:relative} #control{width:100%;padding-right:calc(var(--gramlot-choice-toggle-width,1.6em) + .2em)}
26
27
  #control:focus-visible{outline:1px solid var(--gramlot-border-control,#7a8798);outline-offset:-3px}
27
28
  .toggle{position:absolute;right:0;top:0;bottom:0;width:var(--gramlot-choice-toggle-width,1.6em);min-width:0;min-height:0;font:inherit;font-size:var(--gramlot-field-font-size,1em);padding:0;border:0;background:transparent;color:inherit}
28
- .choices{max-width:var(--gramlot-popup-available-width,100vw);position:fixed;inset:auto;margin:0;padding:var(--gramlot-popup-padding,4px);box-sizing:border-box;max-height:min(var(--gramlot-choice-max-height,12rem),var(--gramlot-popup-available-height,100vh));overflow:auto;
29
- border:1px solid var(--gramlot-border-control,#aab4c2);border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-surface,Canvas);color:var(--gramlot-ink,CanvasText);font:inherit;box-shadow:var(--gramlot-shadow,0 3px 9px #0002)}
30
- .choices[hidden]{display:none} .choice{min-height:var(--gramlot-touch-target,0px);display:flex;align-items:center;padding:.25em .5em;cursor:pointer}
29
+ .choices{min-width:min(var(--gramlot-choice-popup-min-width,0px),var(--gramlot-popup-available-width,100vw));max-width:var(--gramlot-popup-available-width,100vw);position:fixed;inset:auto;margin:0;padding:var(--gramlot-popup-padding,4px);box-sizing:border-box;max-height:min(var(--gramlot-choice-max-height,20rem),var(--gramlot-popup-available-height,100vh));overflow:auto;
30
+ border:1px solid var(--gramlot-border-control,#aab4c2);border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-surface,Canvas);color:var(--gramlot-ink,CanvasText);font:inherit;font-size:var(--gramlot-field-font-size,1em);line-height:1.4;box-shadow:var(--gramlot-shadow,0 3px 9px #0002)}
31
+ .choices[hidden]{display:none} .choice{min-height:var(--gramlot-touch-target,0px);display:flex;align-items:center;padding:var(--gramlot-choice-item-padding,.25em .5em);border-radius:var(--gramlot-radius-sm,4px);cursor:pointer}
32
+ .choice:nth-child(even){background:var(--gramlot-choice-alternate-background,var(--gramlot-surface-subtle,transparent))}
33
+ .choice:hover{background:var(--gramlot-selected,Highlight)}
31
34
  .choice-detail{margin-inline-start:var(--gramlot-space-3,.75rem);color:var(--gramlot-text-secondary,GrayText)}
32
35
  .choice[aria-selected=true]{background:var(--gramlot-selected,Highlight);color:var(--gramlot-ink,HighlightText)}`;
33
36
  this.toggle = doc.createElement('button');
@@ -54,18 +57,24 @@ export function ChoiceEditor(HTMLElement) {
54
57
  if (event.isComposing || this.locked) return;
55
58
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
56
59
  event.preventDefault();
57
- if (!this.#opened) this.search('');
58
- else this.activate(this.#active + (event.key === 'ArrowDown' ? 1 : -1));
60
+ const direction = event.key === 'ArrowDown' ? 1 : -1;
61
+ if (!this.#opened) this.search('', direction);
62
+ else this.activate(this.#active < 0 ? (direction > 0 ? 0 : this.#rows.length - 1) : Math.max(0, this.#active + direction));
59
63
  } else if (event.key === 'Enter') {
60
64
  event.preventDefault();
61
65
  if (this.#opened && this.#rows[this.#active]) this.choose(this.#rows[this.#active]);
62
66
  else this.commitDraft();
63
67
  } else if (event.key === 'Escape') {
64
68
  this.closeChoices(); this.#dirty = false; this.#picked = null;
65
- this.resolveValue();
69
+ if (this.constrained) this.resolveValue();
70
+ else { this.control.value = this.#value ?? ''; this.error(''); }
66
71
  }
67
72
  });
68
- this.control.addEventListener('blur', () => { if (this.#dirty) this.commitDraft(); this.closeChoices(); });
73
+ this.control.addEventListener('blur', () => {
74
+ if (!this.autoHighlight && this.#opened && this.#rows[this.#active]) this.choose(this.#rows[this.#active]);
75
+ else if (this.#dirty) this.commitDraft();
76
+ this.closeChoices();
77
+ });
69
78
  }
70
79
  createControl() {
71
80
  const input = this.ownerDocument.createElement('input'); input.type = 'text';
@@ -74,6 +83,10 @@ export function ChoiceEditor(HTMLElement) {
74
83
  input.autocomplete = 'off'; return input;
75
84
  }
76
85
  get constrained() { return true; }
86
+ get revalidateDraftOnSourceChange() { return false; }
87
+ get autoHighlight() { return true; }
88
+ get matchTypedChoice() { return true; }
89
+ get emptyChoice() { return null; }
77
90
  get choiceSource() { return this.parameters.store ?? this.parameters.callback ?? this.parameters.values; }
78
91
  get searchDelay() { return 0; }
79
92
  textValue(text) { return text; }
@@ -95,28 +108,37 @@ export function ChoiceEditor(HTMLElement) {
95
108
  this.#separator = this.parameters.separator;
96
109
  this.#source = source;
97
110
  this.toggle.disabled = this.locked;
111
+ if (changed && this.revalidateDraftOnSourceChange) this.#dirty = false;
98
112
  if (changed) { this.#rows = []; this.#picked = null; }
99
- if (changed || this.locked) this.closeChoices();
113
+ if (changed || this.locked) this.closeChoices({cancelLookup: changed});
100
114
  if (changed && this.active && !this.#dirty) this.resolveValue();
101
115
  return rest;
102
116
  }
103
117
  setPageContext(context) { super.setPageContext(context); this.resolveValue(); }
104
- connectedCallback() { this.resolveValue(); }
118
+ connectedCallback() { super.connectedCallback(); this.resolveValue(); }
105
119
  readControlValue() { return this.#value; }
106
120
  writeControlValue(value) {
107
121
  if (Object.is(value, this.#value)) return;
108
122
  this.#value = value; this.#dirty = false; this.#picked = null;
109
- this.closeChoices(); this.resolveValue();
123
+ this.closeChoices({cancelLookup: true}); this.resolveValue();
124
+ }
125
+ restoreFormValue(value) {
126
+ this.#value = value; this.#dirty = false; this.#picked = null;
127
+ this.closeChoices({cancelLookup:true}); this.resolveValue();
110
128
  }
111
129
  validateSelection(value) {
112
130
  if (!this.constrained) return super.validateSelection(value);
113
- if (value == null || this.#rows.some(row => row.id === value) || this.#picked?.id === value) return true;
131
+ const row = this.#picked?.id === value ? this.#picked : this.#rows.find(row => row.id === value);
132
+ if (row?.error) return {errorcode:'condition', message:row.error};
133
+ if (value == null || row) return true;
114
134
  return {errorcode:'missing', message:'Choose a value from the list.'};
115
135
  }
116
136
  acceptControlValue() {
117
137
  if (!this.#dirty) return this.validateCandidate(this.#value, accepted => this.writeControlValue(accepted));
118
- const text = this.control.value;
119
- const matches = this.#picked ? [this.#picked] : this.#rows.filter(row => row.caption === text);
138
+ const picked = this.#picked ?? (!this.autoHighlight && this.#opened ? this.#rows[this.#active] : null);
139
+ const text = picked && !this.constrained ? picked.caption : this.control.value;
140
+ const matches = picked ? [picked] : this.matchTypedChoice
141
+ ? this.#rows.filter(row => row.caption === text) : [];
120
142
  if (this.constrained && text !== '' && matches.length !== 1) {
121
143
  this.error('Choose a value from the list.'); return {ok: false};
122
144
  }
@@ -124,22 +146,27 @@ export function ChoiceEditor(HTMLElement) {
124
146
  return this.validateCandidate(value, accepted => {
125
147
  if (accepted !== value && this.constrained) throw new Error('Validation cannot replace a selected code; update the Data explicitly.');
126
148
  this.#value = accepted; this.#dirty = false; this.#picked = null;
127
- if (!this.constrained) this.control.value = accepted ?? '';
128
- this.selectionAccepted(matches.length === 1 && accepted === value ? matches[0] : null);
149
+ if (accepted == null || !this.constrained) this.control.value = accepted ?? '';
150
+ this.selectionAccepted(matches.length === 1 && accepted === value && matches[0].id !== null ? matches[0] : null);
151
+ if (picked && !this.autoHighlight) this.closeChoices();
129
152
  });
130
153
  }
131
154
  commitDraft() {
155
+ this.closeChoices();
132
156
  const Event = this.ownerDocument.defaultView.Event;
133
157
  this.control.dispatchEvent(new Event('change', {bubbles: true}));
134
158
  }
135
159
  choose(row) {
136
160
  if (this.locked || !this.active) return;
137
- this.#picked = row; this.#dirty = true; this.control.value = row.caption;
161
+ if (this.pageContext.form) this.pageContext.formSelectionError(row.error ?? '');
162
+ this.#picked = row; this.#dirty = true; this.control.value = row.id === null ? '' : row.caption;
138
163
  this.closeChoices(); this.commitDraft();
139
164
  }
140
- async request(keywords) {
165
+ async request(keywords, {selection = false} = {}) {
141
166
  this.#requestController?.abort();
142
167
  const controller = new AbortController(); this.#requestController = controller;
168
+ this.#resolvingValue = selection || Object.hasOwn(keywords, '_id');
169
+ if (this.pageContext.form && this.#resolvingValue) this.pageContext.formSelectionPending(true);
143
170
  const generation = ++this.#generation;
144
171
  this.control.setAttribute('aria-busy', 'true'); this.error('');
145
172
  try {
@@ -147,43 +174,65 @@ export function ChoiceEditor(HTMLElement) {
147
174
  if (generation !== this.#generation || !this.active) return null;
148
175
  return rows;
149
176
  } catch (error) {
150
- if (generation === this.#generation && this.active) this.error(error.message);
177
+ if (generation === this.#generation && this.active) {
178
+ this.error(error.message);
179
+ if (this.pageContext.form && this.#resolvingValue) this.pageContext.formSelectionError(error.message);
180
+ }
151
181
  return null;
152
182
  } finally {
153
- if (generation === this.#generation) { this.#requestController = null; this.control.setAttribute('aria-busy', 'false'); }
183
+ if (generation === this.#generation) {
184
+ if (this.pageContext.form && this.#resolvingValue) this.pageContext.formSelectionPending(false);
185
+ this.#requestController = null; this.#resolvingValue = false; this.control.setAttribute('aria-busy', 'false'); }
154
186
  }
155
187
  }
156
188
  async resolveValue() {
157
- if (this.#value == null || this.#value === '') { this.control.value = ''; this.error(''); if (this.active) this.selectionResolved(null); return; }
189
+ if (this.#value == null || this.#value === '') {
190
+ if (this.pageContext?.form) { this.pageContext.formSelectionPending(false); this.pageContext.formSelectionError(''); }
191
+ this.control.value = ''; this.error(''); if (this.active) this.selectionResolved(null); return; }
158
192
  if (!this.active) return;
159
193
  this.control.value = this.#value;
160
194
  if (!this.constrained) { this.error(''); this.selectionResolved(null); return; }
161
- const rows = await this.request({_id: this.#value});
162
- if (!rows) return;
195
+ const pending = this.request({_id: this.#value});
196
+ const generation = this.#generation;
197
+ const rows = await pending;
198
+ if (!rows) {
199
+ if (generation === this.#generation && this.active) {
200
+ this.selectionResolved(null);
201
+ if (this.pageContext.form) this.pageContext.formValidate();
202
+ }
203
+ return;
204
+ }
163
205
  const row = rows.find(item => item.id === this.#value);
164
206
  this.#rows = rows;
165
207
  this.control.value = row ? row.caption : this.#value;
166
- this.error(row ? '' : 'Value is not in the list.');
208
+ const error = row ? row.error ?? '' : 'Value is not in the list.';
209
+ this.error(error);
210
+ if (this.pageContext.form) { this.pageContext.formSelectionError(error); this.pageContext.formValidate(); }
167
211
  this.selectionResolved(row ?? null);
168
212
  }
169
- async search(query) {
213
+ async search(query, navigation = 0) {
170
214
  if (this.locked || !this.active) return;
171
215
  this.closeChoices(); this.#rows = [];
172
216
  const rows = await this.request({_querystring: query});
173
217
  if (!rows || this.locked || this.shadowRoot.activeElement !== this.control) return;
174
- this.#rows = rows;
218
+ const emptyChoice = this.emptyChoice;
219
+ this.#rows = emptyChoice ? [emptyChoice, ...rows] : rows;
175
220
  const doc = this.ownerDocument;
176
- this.choices.replaceChildren(...rows.map((row, index) => {
221
+ this.choices.replaceChildren(...this.#rows.map((row, index) => {
177
222
  const item = doc.createElement('div'); item.id = `choice-${index}`;
178
223
  item.className = 'choice'; item.setAttribute('role', 'option'); this.renderChoice(row, item);
179
224
  item.addEventListener('click', () => this.choose(row)); return item;
180
225
  }));
181
- if (!rows.length) this.choices.textContent = 'No results';
226
+ if (!this.#rows.length) this.choices.textContent = 'No results';
182
227
  const view = doc.defaultView;
183
228
  this.choices.hidden = false; this.choices.showPopover(); this.#opened = true;
184
229
  const inset = parseFloat(view.getComputedStyle(this).getPropertyValue('--gramlot-choice-popup-inset') || '2');
185
230
  positionPopup(this.choices, this.control, {matchWidth: true, inset});
186
- this.control.setAttribute('aria-expanded', 'true'); this.activate(0);
231
+ this.control.setAttribute('aria-expanded', 'true');
232
+ const reopening = this.constrained && !this.#dirty && query === '' && this.#value != null;
233
+ this.activate(reopening ? this.#rows.findIndex(row => row.id === this.#value)
234
+ : navigation < 0 ? this.#rows.length - 1 : navigation > 0 ? 0
235
+ : this.autoHighlight && rows.length ? (emptyChoice ? 1 : 0) : -1);
187
236
  const close = () => this.closeChoices();
188
237
  const outside = event => { if (!event.composedPath().includes(this)) close(); };
189
238
  const scroll = event => { if (!event.composedPath().includes(this.choices)) close(); };
@@ -195,7 +244,7 @@ export function ChoiceEditor(HTMLElement) {
195
244
  };
196
245
  }
197
246
  activate(index) {
198
- this.#active = this.#rows.length ? Math.max(0, Math.min(index, this.#rows.length - 1)) : -1;
247
+ this.#active = this.#rows.length && index >= 0 ? Math.min(index, this.#rows.length - 1) : -1;
199
248
  for (const [i, item] of [...this.choices.children].entries()) {
200
249
  item.setAttribute('aria-selected', String(i === this.#active));
201
250
  if (i === this.#active) item.scrollIntoView({block: 'nearest'});
@@ -203,16 +252,22 @@ export function ChoiceEditor(HTMLElement) {
203
252
  if (this.#active < 0) this.control.removeAttribute('aria-activedescendant');
204
253
  else this.control.setAttribute('aria-activedescendant', `choice-${this.#active}`);
205
254
  }
206
- closeChoices() {
255
+ closeChoices({cancelLookup = false} = {}) {
207
256
  clearTimeout(this.#searchTimer); this.#searchTimer = null;
208
- this.#requestController?.abort(); this.#requestController = null;
209
- ++this.#generation; this.#cleanup?.(); this.#cleanup = null;
257
+ // Closing suggestions must not cancel resolution of the selected Data value.
258
+ if (cancelLookup || !this.#resolvingValue) {
259
+ if (this.pageContext?.form && this.#resolvingValue) this.pageContext.formSelectionPending(false);
260
+ this.#requestController?.abort(); this.#requestController = null;
261
+ this.#resolvingValue = false; ++this.#generation;
262
+ this.control.setAttribute('aria-busy', 'false');
263
+ }
264
+ this.#cleanup?.(); this.#cleanup = null;
210
265
  if (this.#opened) this.choices.hidePopover();
211
266
  this.#opened = false; this.choices.hidden = true;
212
- this.control.setAttribute('aria-expanded', 'false'); this.control.setAttribute('aria-busy', 'false');
267
+ this.control.setAttribute('aria-expanded', 'false');
213
268
  this.control.removeAttribute('aria-activedescendant');
214
269
  }
215
- releaseControl() { this.closeChoices(); }
270
+ releaseControl() { this.closeChoices({cancelLookup: true}); }
216
271
  disconnectedCallback() { this.releaseControl(); }
217
272
  };
218
273
  }
@@ -1,35 +1,61 @@
1
+ import createDOMPurify from 'dompurify';
2
+
1
3
  /** Database suggestions share the choice editor and the ordinary data RPC. */
2
4
  export const databaseParameters = {
3
5
  dbtable: {dtype:'T', binding:'read'},
6
+ condition: {dtype:'T', binding:'read'},
7
+ weakCondition: {dtype:['B','T'], default:false, binding:'read'},
4
8
  method: {dtype:'T', default:'dbSelect', binding:'read'},
5
9
  columns: {dtype:'T', binding:'read'},
6
10
  hiddenColumns: {dtype:'T', binding:'read'},
11
+ auxColumns: {dtype:'T', binding:'read'},
12
+ template: {dtype:'T', binding:'read'},
13
+ templateNull: {dtype:'T', default:'', binding:'read'},
7
14
  order_by: {dtype:'T', binding:'read'},
8
15
  limit: {dtype:'L', default:10, binding:'read'},
9
16
  searchDelay: {dtype:'L', default:300, binding:'read'},
10
17
  ignoreCase: {dtype:'B', default:true, binding:'read'},
11
18
  hasDownArrow: {dtype:'B', default:true, binding:'read'},
12
- emptyLabel: {dtype:'T', default:'', binding:'read'},
19
+ emptyLabel: {dtype:'T', qualification:'intl_str', default:'Clear selection', binding:'read'},
13
20
  selectedCaption: {dtype:'T'},
14
21
  selectedRecord: {dtype:'T'},
15
22
  selectedCb: {dtype:'T'}
16
23
  };
17
- const requestParameters = ['dbtable','method','columns','hiddenColumns','order_by','limit','ignoreCase'];
24
+ const requestParameters = ['dbtable','method','columns','hiddenColumns','auxColumns','order_by','limit','ignoreCase','condition','weakCondition'];
18
25
 
19
26
  export function databaseChoices(Base) {
20
27
  return class extends Base {
21
28
  #configuration = {};
29
+ #conditionChanged = false;
22
30
  #outputs = {};
23
31
  #revision = 0;
24
32
  #acceptedRow;
33
+ #template;
34
+ #sanitizer;
35
+ constructor() {
36
+ super();
37
+ this.#sanitizer = createDOMPurify(this.ownerDocument.defaultView);
38
+ }
25
39
  get choiceSource() { return this.#revision; }
26
40
  get searchDelay() { return this.parameters.searchDelay; }
41
+ get revalidateDraftOnSourceChange() { return this.constrained; }
42
+ get autoHighlight() { return this.constrained; }
43
+ get matchTypedChoice() { return this.constrained; }
44
+ get emptyChoice() {
45
+ return this.constrained && !this.parameters.validate_notnull
46
+ ? {id:null, caption:this.parameters.emptyLabel} : null;
47
+ }
27
48
  // Database writes wait for a complete choice/free-text edit, even with live=True.
28
49
  get commitOnChange() { return true; }
29
50
  textValue(text) { return text === '' ? null : text; }
30
51
  projectAttributes(attrs, adapt) {
31
52
  const configuration = Object.fromEntries(Object.entries(attrs).filter(([key]) =>
32
- requestParameters.includes(key) || key === 'autoSelect' || key.startsWith('condition_')));
53
+ requestParameters.includes(key) || ['autoSelect','template','templateNull','emptyLabel','validate_notnull'].includes(key)
54
+ || key.startsWith('condition_') || key.startsWith('selected_')));
55
+ const conditionKeys = new Set([...Object.keys(configuration), ...Object.keys(this.#configuration)]
56
+ .filter(key => key === 'condition' || key === 'weakCondition' || key.startsWith('condition_')));
57
+ if (Object.keys(this.#configuration).length && [...conditionKeys].some(key =>
58
+ !Object.is(configuration[key], this.#configuration[key]))) this.#conditionChanged = true;
33
59
  const keys = new Set([...Object.keys(configuration), ...Object.keys(this.#configuration)]);
34
60
  if ([...keys].some(key => !Object.is(configuration[key], this.#configuration[key]))) {
35
61
  this.cancelValidation(); this.#acceptedRow = undefined;
@@ -37,18 +63,49 @@ export function databaseChoices(Base) {
37
63
  }
38
64
  this.#outputs = Object.fromEntries(Object.entries(attrs).filter(([key]) => key.startsWith('selected_')));
39
65
  const rest = super.projectAttributes(attrs, adapt);
40
- const {limit, searchDelay, hasDownArrow, emptyLabel} = this.parameters;
66
+ this.#template = null;
67
+ if (this.parameters.template != null) {
68
+ this.#template = this.#sanitizer.sanitize(this.parameters.template, {
69
+ USE_PROFILES: {html:true}, RETURN_DOM_FRAGMENT:true,
70
+ FORBID_TAGS: ['style','form','input','button','select','textarea','a','audio','video','details','summary'],
71
+ FORBID_ATTR: ['id','name','role','tabindex','contenteditable','autofocus']
72
+ });
73
+ for (const element of this.#template.querySelectorAll('*')) {
74
+ if ([...element.attributes].some(attr => /\{[A-Za-z0-9_]+\}/.test(attr.value))) {
75
+ this.#template = null;
76
+ throw new TypeError('Selector template placeholders belong in text, not HTML attributes.');
77
+ }
78
+ }
79
+ }
80
+ this.choices.style.minWidth = this.#template
81
+ ? 'min(var(--gramlot-choice-popup-min-width,28rem),var(--gramlot-popup-available-width,100vw))' : '';
82
+ if (this.parameters.condition != null && !this.parameters.condition.trim()) throw new TypeError('condition must be a nonempty expression.');
83
+ if (typeof this.parameters.weakCondition !== 'boolean' &&
84
+ (typeof this.parameters.weakCondition !== 'string' || !this.parameters.weakCondition.trim())) {
85
+ throw new TypeError('weakCondition must be boolean or a nonempty expression.');
86
+ }
87
+ const {limit, searchDelay, hasDownArrow} = this.parameters;
41
88
  if (!Number.isInteger(limit) || limit < 1) throw new TypeError('limit must be a positive integer.');
42
89
  if (!Number.isInteger(searchDelay) || searchDelay < 0) throw new TypeError('searchDelay must be a non-negative integer.');
43
90
  this.toggle.hidden = !hasDownArrow;
44
91
  this.control.style.paddingRight = hasDownArrow ? '' : 'var(--gramlot-field-padding, .25em)';
45
- if (!this.parameters.placeholder) this.control.placeholder = emptyLabel;
46
92
  for (const key of Object.keys(rest)) if (key.startsWith('condition_') || key.startsWith('selected_')) delete rest[key];
47
93
  return rest;
48
94
  }
49
95
  async loadChoices(keywords, signal) {
50
96
  const parameters = Object.fromEntries(requestParameters.filter(key => key !== 'method' && this.parameters[key] != null)
51
97
  .map(key => [key, this.parameters[key]]));
98
+ if (parameters.weakCondition === false) delete parameters.weakCondition;
99
+ const required = new Set(Object.entries(this.#outputs).filter(([, path]) => path).map(([name]) => name.slice(9)));
100
+ if (this.#template) {
101
+ const walker = this.ownerDocument.createTreeWalker(this.#template, 4);
102
+ while (walker.nextNode()) {
103
+ for (const match of walker.currentNode.data.matchAll(/\{([A-Za-z0-9_]+)\}/g)) required.add(match[1]);
104
+ }
105
+ }
106
+ if (required.size) parameters.hiddenColumns = [...new Set([
107
+ ...(parameters.hiddenColumns ?? '').split(',').map(name => name.trim()).filter(Boolean), ...required
108
+ ])].join(',');
52
109
  for (const [key, value] of Object.entries(this.#configuration)) {
53
110
  if (key.startsWith('condition_')) {
54
111
  const name = key.slice(10);
@@ -60,17 +117,71 @@ export function databaseChoices(Base) {
60
117
  if (!result || !Array.isArray(result.rows) || typeof result.identifier !== 'string' || typeof result.caption !== 'string') {
61
118
  throw new TypeError('Database selectors require {rows, identifier, caption}.');
62
119
  }
120
+ if (parameters.auxColumns != null) {
121
+ if (!Array.isArray(result.columns) || !Array.isArray(result.headers)
122
+ || result.columns.length !== result.headers.length || !result.columns.length
123
+ || result.columns.some(name => typeof name !== 'string' || !name)
124
+ || result.headers.some(label => typeof label !== 'string')
125
+ || new Set(result.columns).size !== result.columns.length) {
126
+ throw new TypeError('auxColumns requires columns and headers display metadata.');
127
+ }
128
+ for (const name of result.columns) required.add(name);
129
+ }
130
+ if (result.errors != null && (typeof result.errors !== 'string' || !Object.hasOwn(keywords, '_id'))) {
131
+ throw new TypeError('Selector errors must be literal text attached to identity lookup.');
132
+ }
63
133
  const ids = new Set();
64
134
  return result.rows.map(record => {
65
135
  const id = record[result.identifier], caption = record[result.caption];
66
136
  if (!((typeof id === 'string' && id.length) || Number.isSafeInteger(id)) || typeof caption !== 'string' || ids.has(id)) {
67
137
  throw new TypeError('Invalid or duplicate database choice identity/caption.');
68
138
  }
69
- ids.add(id); return {id, caption, record, captionField:result.caption};
139
+ for (const name of required) if (!Object.hasOwn(record, name)) {
140
+ throw new TypeError(`Missing requested selector column: ${name}`);
141
+ }
142
+ ids.add(id); return {id, caption, record, error:result.errors, captionField:result.caption,
143
+ columns:parameters.auxColumns != null ? result.columns : null,
144
+ headers:parameters.auxColumns != null ? result.headers : null};
70
145
  });
71
146
  }
72
147
  selectionAccepted(row) { this.#acceptedRow = row; }
73
148
  renderChoice(row, item) {
149
+ if (row.id === null) {
150
+ super.renderChoice(row, item);
151
+ item.style.color = 'var(--gramlot-text-secondary,GrayText)';
152
+ item.style.borderBottom = '1px solid var(--gramlot-border,#d5dce5)';
153
+ item.style.marginBottom = 'var(--gramlot-space-1,.25rem)';
154
+ return;
155
+ }
156
+ if (this.#template) {
157
+ const content = this.#template.cloneNode(true);
158
+ const walker = this.ownerDocument.createTreeWalker(content, 4);
159
+ while (walker.nextNode()) {
160
+ walker.currentNode.data = walker.currentNode.data.replace(/\{([A-Za-z0-9_]+)\}/g,
161
+ (_, name) => row.record[name] == null ? this.parameters.templateNull : String(row.record[name]));
162
+ }
163
+ item.style.display = 'block';
164
+ item.style.overflowWrap = 'anywhere';
165
+ item.replaceChildren(content);
166
+ return;
167
+ }
168
+ if (row.columns) {
169
+ item.style.display = 'grid';
170
+ item.style.gridTemplateColumns = `repeat(${row.columns.length}, minmax(0, 1fr))`;
171
+ item.style.gap = 'var(--gramlot-space-3,.75rem)';
172
+ item.style.alignItems = 'start';
173
+ item.replaceChildren(...row.columns.map((name, index) => {
174
+ const cell = this.ownerDocument.createElement('span');
175
+ cell.style.overflowWrap = 'anywhere';
176
+ const label = this.ownerDocument.createElement('small');
177
+ label.textContent = row.headers[index];
178
+ label.style.display = 'block'; label.style.opacity = '.7';
179
+ const value = this.ownerDocument.createElement('span');
180
+ value.textContent = row.record[name] ?? '';
181
+ cell.append(label, value); return cell;
182
+ }));
183
+ return;
184
+ }
74
185
  super.renderChoice(row, item);
75
186
  for (const name of (this.parameters.columns ?? '').split(',').map(name => name.trim()).filter(name => name && name !== row.captionField)) {
76
187
  const detail = this.ownerDocument.createElement('span');
@@ -100,9 +211,20 @@ export function databaseChoices(Base) {
100
211
  super.finishValidation(outcome);
101
212
  }
102
213
  async resolveValue() {
103
- await super.resolveValue();
104
- if (this.active && !this.locked && this.parameters.autoSelect && this.readControlValue() == null) {
105
- const rows = await this.request({_querystring:'', limit:2});
214
+ const changed = this.#conditionChanged;
215
+ this.#conditionChanged = false;
216
+ if (changed && this.active && !this.locked && this.constrained && this.parameters.validate_notnull) {
217
+ const rows = await this.request({_querystring:'', limit:2}, {selection:true});
218
+ if (!rows) return;
219
+ if (rows.length === 1) { this.choose(rows[0]); return; }
220
+ }
221
+ const value = this.readControlValue();
222
+ const pending = super.resolveValue();
223
+ // Identity resolution must not start autoSelect after a later clear/edit.
224
+ if (value != null && value !== '') return pending;
225
+ await pending;
226
+ if (this.active && !this.locked && this.parameters.autoSelect && this.readControlValue() == null && this.control.value === '') {
227
+ const rows = await this.request({_querystring:'', limit:2}, {selection:true});
106
228
  if (rows?.length === 1 && this.readControlValue() == null && !this.locked) this.choose(rows[0]);
107
229
  }
108
230
  }
@@ -7,6 +7,8 @@ const MESSAGE_FADE_DURATION = 200;
7
7
  /** Shared candidate validation and presentation; ControlAdapter alone writes Data. */
8
8
  export function FieldState(Base) {
9
9
  return class extends Base {
10
+ get supportsFormValidation() { return true; }
11
+ connectedCallback() { super.connectedCallback(); if (this.pageContext?.form) this.pageContext.formValidate(); }
10
12
  #rejected = false;
11
13
  #projected;
12
14
  #messageTimer;
@@ -80,13 +82,16 @@ export function FieldState(Base) {
80
82
  this.message.textContent = message;
81
83
  if (message) this.#showMessage(); else this.#hideMessage();
82
84
  }
85
+ restoreFormValue(value) { this.error(''); this.#rejected = false; super.restoreFormValue(value); }
83
86
  cancelValidation() {
87
+ if (this.pageContext?.form) this.pageContext.formPending(false);
84
88
  this.#validationEpoch++;
85
89
  this.#validation?.abort(); this.#validation = null; this.#validationCurrent = null;
86
90
  this.control.setAttribute('aria-busy', 'false');
87
91
  }
88
92
  validateCandidate(value, accept) {
89
93
  this.cancelValidation();
94
+ if (this.pageContext.form) this.pageContext.formCandidate(value);
90
95
  const controller = new AbortController(); this.#validation = controller;
91
96
  const epoch = this.#validationEpoch;
92
97
  const rules = this.#rules;
@@ -100,8 +105,9 @@ export function FieldState(Base) {
100
105
  }
101
106
  this.#validation = null; this.#validationCurrent = null;
102
107
  this.control.setAttribute('aria-busy', 'false');
103
- try { if (!result.error) accept(result.value); }
108
+ try { if (!result.error || this.pageContext.form) accept(result.value); }
104
109
  catch (error) { result = failure(error); }
110
+ if (this.pageContext.form) this.pageContext.formResult(result);
105
111
  this.validationResult = result;
106
112
  this.error(result.error || ''); this.message.dataset.severity = result.error ? 'error' : 'warning'; this.#rejected = Boolean(result.error);
107
113
  if (!result.error && result.warnings.length) {
@@ -118,6 +124,7 @@ export function FieldState(Base) {
118
124
  }
119
125
  catch (error) { return finish(failure(error)); }
120
126
  if (!(result instanceof Promise)) return finish(result);
127
+ if (this.pageContext.form) this.pageContext.formPending(true);
121
128
  this.control.setAttribute('aria-busy', 'true');
122
129
  return new Promise(resolve => {
123
130
  let timer;
@@ -151,7 +158,9 @@ export function FieldState(Base) {
151
158
  const rules = Object.fromEntries(Object.entries(attrs).filter(([name]) => name.startsWith('validate_')));
152
159
  const keys = new Set([...Object.keys(rules), ...Object.keys(this.#rules)]);
153
160
  if ([...keys].some(key => !Object.is(rules[key], this.#rules[key])) || attrs.disabled || attrs.readonly) this.cancelValidation();
161
+ const rulesChanged = [...keys].some(key => !Object.is(rules[key], this.#rules[key]));
154
162
  this.#rules = rules;
163
+ if (rulesChanged && this.pageContext?.form) this.pageContext.formValidate();
155
164
  for (const key of Object.keys(rules)) delete rest[key];
156
165
  const required = Boolean(this.parameters.validate_notnull);
157
166
  this.control.setAttribute('aria-required', String(required));