@gramlot/gramlot 0.2.19 → 0.3.0

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 (66) hide show
  1. package/dist/gramlot.js +2145 -224
  2. package/dist/gramlot.min.js +363 -21
  3. package/package.json +6 -3
  4. package/src/binding/ask-dialog.js +2 -2
  5. package/src/binding/inline.js +11 -12
  6. package/src/binding/installation.js +4 -1
  7. package/src/binding/pointer.js +63 -0
  8. package/src/binding/providers.js +8 -4
  9. package/src/binding/runtime.js +11 -5
  10. package/src/bootstrap.d.ts +2 -0
  11. package/src/bootstrap.js +9 -2
  12. package/src/builder/gramlot-builder.js +24 -3
  13. package/src/builder/source.js +33 -9
  14. package/src/components/bases.js +182 -0
  15. package/src/components/buttons.js +254 -0
  16. package/src/components/choice-editor.js +221 -0
  17. package/src/components/choices.js +13 -0
  18. package/src/components/date-calendar.js +139 -0
  19. package/src/components/field-state.js +166 -0
  20. package/src/components/formlet-labels.js +80 -0
  21. package/src/components/index.js +5 -0
  22. package/src/components/inputs.js +196 -0
  23. package/src/components/labelbox.js +74 -0
  24. package/src/components/layout.js +190 -0
  25. package/src/components/parameters.js +6 -0
  26. package/src/components/popup.js +22 -0
  27. package/src/components/registry.js +83 -0
  28. package/src/components/typed-editor.js +260 -0
  29. package/src/components/validation.js +138 -0
  30. package/src/date-parser/civil.js +61 -0
  31. package/src/date-parser/index.d.ts +18 -0
  32. package/src/date-parser/index.js +196 -0
  33. package/src/date-parser/locales.js +257 -0
  34. package/src/format.js +128 -0
  35. package/src/gramlot.d.ts +25 -0
  36. package/src/gramlot.js +15 -1
  37. package/src/handlers/dom-handler.d.ts +1 -0
  38. package/src/handlers/dom-handler.js +7 -0
  39. package/src/index-page-runtime.js +78 -30
  40. package/src/index-page-styles.js +2 -2
  41. package/src/index-theme.js +1 -1
  42. package/src/index.d.ts +4 -1
  43. package/src/index.js +2 -0
  44. package/src/renderer/attributes.js +25 -50
  45. package/src/renderer/gramlot-html-renderer.js +4 -3
  46. package/src/renderer/gramlot-renderer.js +63 -3
  47. package/src/server/gramlot-server.d.ts +5 -0
  48. package/src/server/gramlot-server.js +14 -5
  49. package/src/server/index-page.d.ts +1 -0
  50. package/src/server/index-page.js +8 -3
  51. package/src/server/page-base.js +3 -0
  52. package/src/server/page.d.ts +3 -0
  53. package/src/server/resources.d.ts +2 -0
  54. package/src/view/button.js +17 -13
  55. package/src/view/controls.js +152 -4
  56. package/src/view/html.js +18 -0
  57. package/themes/gramlot-base/README.md +6 -0
  58. package/themes/gramlot-base/theme.css +34 -6
  59. package/themes/gramlot-compact/README.md +6 -0
  60. package/themes/gramlot-compact/theme.css +8 -4
  61. package/themes/joanna/README.md +23 -0
  62. package/themes/joanna/theme.css +89 -0
  63. package/themes/mimi/README.md +23 -0
  64. package/themes/mimi/theme.css +89 -0
  65. package/tools/gramlot-tools-inspector.js +42 -18
  66. package/tools/inspector-agent.js +8 -4
@@ -0,0 +1,182 @@
1
+ import {projectParameters} from './parameters.js';
2
+ import {parseChoices} from './choices.js';
3
+
4
+ /** Internal control DOM; Source/Data binding remains in ControlAdapter. */
5
+ export function controlElement(HTMLElement) {
6
+ return class extends HTMLElement {
7
+ constructor() {
8
+ super();
9
+ const shadow = this.attachShadow({mode: 'open'});
10
+ const style = this.ownerDocument.createElement('style');
11
+ style.textContent = `:host{display:inline-block;font:inherit} *,*::before,*::after{box-sizing:border-box}
12
+ input,textarea{font:inherit;max-width:100%} .control-box{min-width:0;color:var(--gramlot-ink,CanvasText)}
13
+ input:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea{
14
+ appearance:none;box-sizing:border-box;border:1px solid var(--gramlot-border-control,#7a8798);
15
+ border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-field-background,Canvas);color:var(--gramlot-ink,CanvasText);
16
+ min-height:var(--gramlot-field-height,28px);padding:var(--gramlot-field-padding,.25em .5em);font-size:var(--gramlot-field-font-size,1em);line-height:var(--gramlot-field-line-height,inherit)}
17
+ input:read-only:not([type=checkbox]):not([type=radio]):not([type=range]):not([type=color]),textarea:read-only{
18
+ background:var(--gramlot-field-readonly-background,Canvas)}
19
+ input:disabled,textarea:disabled{opacity:.6;cursor:not-allowed}
20
+ input::placeholder,textarea::placeholder{color:var(--gramlot-text-secondary,GrayText)}
21
+ input:focus-visible,textarea:focus-visible,button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:1px}
22
+ input[type=checkbox],input[type=radio],input[type=range]{accent-color:var(--gramlot-brand-blue,Highlight)}
23
+ input[type=range],input[type=color],button{min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
24
+ input[type=checkbox],input[type=radio]{min-width:calc(var(--gramlot-touch-target,0px) / 2);min-height:calc(var(--gramlot-touch-target,0px) / 2)}
25
+ .options{display:grid;gap:.3em .8em} .option{display:flex;align-items:center;gap:.35em;min-width:var(--gramlot-touch-target,0px);min-height:var(--gramlot-touch-target,0px)}
26
+ .caption:empty{display:none}`;
27
+ this.controlBox = this.ownerDocument.createElement('div');
28
+ this.controlBox.className = 'control-box';
29
+ shadow.append(style, this.controlBox);
30
+ }
31
+ projectAttributes(attrs) {
32
+ return projectParameters(this, attrs);
33
+ }
34
+ setPageContext(context) { this.pageContext = context; }
35
+ releaseControl() {}
36
+ validateCandidate(value, accept) {
37
+ accept(value);
38
+ return {ok:true, value, isCurrent:() => this.pageContext.isActive()};
39
+ }
40
+ finishValidation() {}
41
+ validateSelection() { throw new TypeError('validate_select requires a constrained choice editor.'); }
42
+ shouldProjectControlValue() { return true; }
43
+ acceptControlValue() {
44
+ const value = this.readControlValue();
45
+ return this.validateCandidate(value, accepted => {
46
+ if (accepted == null && !this.constructor.gramlotComponent.parameters.value.nullable) throw new TypeError('This component requires a non-null value.');
47
+ if (accepted != null && value != null && typeof accepted !== typeof value) throw new TypeError('Validation must preserve the component value type.');
48
+ if (!this.sameControlValue(value, accepted)) this.writeControlValue(accepted);
49
+ });
50
+ }
51
+ sameControlValue(a, b) { return Object.is(a, b); }
52
+ focus(options) { this.control.focus(options); }
53
+ };
54
+ }
55
+
56
+ export function NativeControl(HTMLElement) {
57
+ return class extends controlElement(HTMLElement) {
58
+ constructor() {
59
+ super();
60
+ this.control = this.createControl();
61
+ if (this.control.localName === 'textarea' || this.control.localName === 'input' && ['text', 'password'].includes(this.control.type)) {
62
+ this.control.setAttribute('autocomplete', 'off');
63
+ this.control.setAttribute('autocorrect', 'off');
64
+ this.control.setAttribute('autocapitalize', 'off');
65
+ this.control.setAttribute('spellcheck', 'false');
66
+ }
67
+ this.control.id = 'control';
68
+ const option = this.ownerDocument.createElement('label');
69
+ option.className = 'option';
70
+ this.optionCaption = this.ownerDocument.createElement('span');
71
+ this.optionCaption.className = 'caption';
72
+ option.append(this.control, this.optionCaption);
73
+ this.controlBox.append(option);
74
+ }
75
+ projectAttributes(attrs, adapt) {
76
+ const rest = super.projectAttributes(attrs, adapt);
77
+ const {disabled, readonly} = this.parameters;
78
+ this.control.disabled = Boolean(disabled);
79
+ this.control.readOnly = Boolean(readonly);
80
+ for (const [name, spec] of Object.entries(this.constructor.gramlotComponent.parameters)) {
81
+ if (spec.target === 'control') {
82
+ const value = this.parameters[name] ?? '';
83
+ if (String(this.control[name]) !== String(value)) this.control[name] = value;
84
+ }
85
+ if (spec.target === 'optionCaption') this.optionCaption.textContent = this.parameters[name] ?? '';
86
+ }
87
+ return rest;
88
+ }
89
+ };
90
+ }
91
+ NativeControl.parameters = {
92
+ disabled: {dtype: 'B', default: false, binding: 'read'},
93
+ readonly: {dtype: 'B', default: false, binding: 'read'},
94
+ live: {dtype: 'B', default: false, binding: 'read'}
95
+ };
96
+
97
+ export function ChoiceGroup(HTMLElement) {
98
+ return class extends controlElement(HTMLElement) {
99
+ #options = new Map();
100
+ #values;
101
+ #value = null;
102
+ constructor() {
103
+ super();
104
+ this.control = this.ownerDocument.createElement('div');
105
+ this.control.className = 'options';
106
+ this.control.id = 'control';
107
+ this.control.setAttribute('role', this.multiple ? 'group' : 'radiogroup');
108
+ this.controlBox.append(this.control);
109
+ this.control.addEventListener('keydown', event => {
110
+ if (!this.multiple || !['ArrowDown', 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
111
+ const items = [...this.control.querySelectorAll('input:not(:disabled)')];
112
+ const index = items.indexOf(event.target);
113
+ if (index < 0) return;
114
+ event.preventDefault();
115
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1
116
+ : Math.max(0, Math.min(items.length - 1, index + (['ArrowDown', 'ArrowRight'].includes(event.key) ? 1 : -1)));
117
+ items[next].focus();
118
+ });
119
+ }
120
+ projectAttributes(attrs, adapt) {
121
+ const rest = super.projectAttributes(attrs, adapt);
122
+ const values = this.parameters.values ?? '';
123
+ if (values !== this.#values) {
124
+ const options = parseChoices(values);
125
+ const retained = new Set();
126
+ let previous = null;
127
+ for (const {id: code, caption} of options) {
128
+ let item = this.#options.get(code);
129
+ if (!item) {
130
+ const label = this.ownerDocument.createElement('label');
131
+ label.className = 'option';
132
+ const input = this.ownerDocument.createElement('input');
133
+ input.type = this.choiceType; input.name = 'choice'; input.value = code;
134
+ const text = this.ownerDocument.createElement('span');
135
+ label.append(input, text); item = {label, input, text};
136
+ this.#options.set(code, item);
137
+ }
138
+ item.text.textContent = caption;
139
+ const expected = previous ? previous.nextSibling : this.control.firstChild;
140
+ if (expected !== item.label) this.control.insertBefore(item.label, expected);
141
+ previous = item.label; retained.add(code);
142
+ }
143
+ for (const [code, item] of this.#options) if (!retained.has(code)) {
144
+ item.label.remove(); this.#options.delete(code);
145
+ }
146
+ this.#values = values;
147
+ }
148
+ const cols = this.parameters.cols;
149
+ if (!Number.isInteger(cols) || cols < 1) throw new TypeError('cols must be a positive integer');
150
+ this.control.style.gridTemplateColumns = `repeat(${cols}, minmax(0, 1fr))`;
151
+ this.control.disabled = Boolean(this.parameters.disabled);
152
+ this.control.readOnly = Boolean(this.parameters.readonly);
153
+ for (const {input} of this.#options.values()) input.disabled = this.control.disabled || this.control.readOnly;
154
+ return rest;
155
+ }
156
+ readControlValue() {
157
+ if (this.multiple) {
158
+ const codes = this.#value ? this.#value.split(',') : [];
159
+ const selected = codes.filter(code => !this.#options.has(code) || this.#options.get(code).input.checked);
160
+ for (const [code, {input}] of this.#options) if (input.checked && !selected.includes(code)) selected.push(code);
161
+ return selected.join(',') || null;
162
+ }
163
+ for (const [code, {input}] of this.#options) if (input.checked) return code;
164
+ return null;
165
+ }
166
+ writeControlValue(value) {
167
+ this.#value = value;
168
+ const selected = this.multiple ? new Set(value ? value.split(',') : []) : null;
169
+ for (const [code, {input}] of this.#options) input.checked = this.multiple ? selected.has(code) : code === value;
170
+ }
171
+ acceptControlValue() {
172
+ const value = this.readControlValue();
173
+ return this.validateCandidate(value, accepted => this.writeControlValue(accepted));
174
+ }
175
+ focus(options) {
176
+ const items = [...this.#options.values()];
177
+ (items.find(({input}) => input.checked && !input.disabled) ?? items.find(({input}) => !input.disabled))?.input.focus(options);
178
+ }
179
+ };
180
+ }
181
+ ChoiceGroup.parameters = {disabled: {dtype: 'B', default: false, binding: 'read'},
182
+ readonly: {dtype: 'B', default: false, binding: 'read'}};
@@ -0,0 +1,254 @@
1
+ /** Built-in command surfaces. Execution stays in ButtonBinding, state in ControlAdapter. */
2
+ import {defineComponent, defineCollection} from './registry.js';
3
+ import {controlElement} from './bases.js';
4
+ import {projectParameters} from './parameters.js';
5
+ import {positionPopup} from './popup.js';
6
+
7
+ function Command(HTMLElement) {
8
+ return class extends controlElement(HTMLElement) {
9
+ constructor() {
10
+ super();
11
+ const doc = this.ownerDocument;
12
+ this.control = doc.createElement('button');
13
+ this.control.type = 'button';
14
+ this.control.id = 'control';
15
+ this.icon = doc.createElement('span');
16
+ this.icon.className = 'icon';
17
+ this.icon.setAttribute('aria-hidden', 'true');
18
+ this.caption = doc.createElement('slot');
19
+ this.control.append(this.icon, this.caption);
20
+ this.controlBox.append(this.control);
21
+ const style = doc.createElement('style');
22
+ style.textContent = `:host{vertical-align:middle} .control-box{display:flex;align-items:stretch}
23
+ button{display:inline-flex;align-items:center;justify-content:center;gap:var(--gramlot-button-gap,.35em);font:inherit;
24
+ color:var(--gramlot-ink,CanvasText);background:var(--gramlot-button-background,var(--gramlot-field-background,Canvas));
25
+ border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
26
+ min-height:max(var(--gramlot-field-height,28px),var(--gramlot-touch-target,0px));
27
+ padding:var(--gramlot-button-padding,.25em .65em);cursor:pointer}
28
+ button:hover:not(:disabled){background:var(--gramlot-button-hover,var(--gramlot-field-readonly-background,#eee))}
29
+ button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none}
30
+ .led{display:inline-block;width:.6em;height:.6em;border-radius:50%;background:var(--gramlot-button-led-off,#888)}
31
+ [aria-pressed=true] .led{background:var(--gramlot-button-led-on,#2b9a46)}
32
+ .arrow{border-start-start-radius:0;border-end-start-radius:0;border-inline-start:0}
33
+ .split{border-start-end-radius:0;border-end-end-radius:0}
34
+ .popup{position:fixed;inset:auto;margin:0;padding:var(--gramlot-popup-padding,4px);overflow:auto;
35
+ max-width:var(--gramlot-popup-available-width);max-height:var(--gramlot-popup-available-height);
36
+ border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
37
+ color:var(--gramlot-ink,CanvasText);background:var(--gramlot-field-background,Canvas);box-shadow:0 3px 12px #0003}
38
+ :host([role=menuitem]){display:block} :host([role=menuitem]) button{width:100%;justify-content:start;border:0;background:transparent}
39
+ :host([role=separator]){display:block;border-top:1px solid var(--gramlot-border-control,#888);margin:.25em}
40
+ :host([role=separator]) button{display:none}`;
41
+ this.shadowRoot.append(style);
42
+ }
43
+ get disabled() { return this.control.disabled; }
44
+ set disabled(value) { this.control.disabled = Boolean(value); }
45
+ projectAttributes(attrs, adapt) {
46
+ const rest = super.projectAttributes(attrs, adapt);
47
+ this.control.disabled = Boolean(this.parameters.disabled);
48
+ this.control.readOnly = Boolean(this.parameters.readonly);
49
+ this.icon.textContent = this.parameters.icon ?? '';
50
+ if (attrs['aria-label'] != null) this.control.setAttribute('aria-label', attrs['aria-label']);
51
+ else this.control.removeAttribute('aria-label');
52
+ return rest;
53
+ }
54
+ attachCommand() {}
55
+ releaseCommand() {}
56
+ commandTarget() { return this; }
57
+ prepareCommand() { return !this.disabled; }
58
+ };
59
+ }
60
+ Command.parameters = {
61
+ disabled: {dtype: 'B', default: false, binding: 'read'},
62
+ icon: {dtype: 'T', default: '', binding: 'read'}
63
+ };
64
+ export const Button = defineComponent({name: 'button', tag: 'gramlot-button', base: Command,
65
+ command: true, subTags: '*', implementation: Base => class extends Base {}});
66
+ export const ToggleButton = defineComponent({name: 'toggleButton', tag: 'gramlot-toggle-button', base: Command,
67
+ command: true, subTags: '*', parameters: {value: {dtype: 'B', default: false, binding: 'twoWay'},
68
+ readonly: {dtype: 'B', default: false, binding: 'read'}},
69
+ implementation: Base => class extends Base {
70
+ #value = false;
71
+ constructor() {
72
+ super();
73
+ const led = this.ownerDocument.createElement('span');
74
+ led.className = 'led'; led.setAttribute('aria-hidden', 'true');
75
+ this.control.prepend(led);
76
+ this.writeControlValue(false);
77
+ }
78
+ get commitOnChange() { return true; }
79
+ readControlValue() { return this.#value; }
80
+ writeControlValue(value) {
81
+ this.#value = value;
82
+ this.control.setAttribute('aria-pressed', String(value));
83
+ }
84
+ prepareCommand(event) {
85
+ if (!super.prepareCommand(event) || this.control.readOnly) return false;
86
+ this.writeControlValue(!this.#value);
87
+ this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('change'));
88
+ return true;
89
+ }
90
+ }
91
+ });
92
+ function MenuContainer(HTMLElement) {
93
+ return class extends HTMLElement {
94
+ constructor() {
95
+ super();
96
+ this.attachShadow({mode: 'open'}).append(this.ownerDocument.createElement('slot'));
97
+ }
98
+ connectedCallback() { this.slot = 'menu'; this.setAttribute('role', 'menu'); }
99
+ projectAttributes(attrs) { return projectParameters(this, attrs); }
100
+ };
101
+ }
102
+ export const Menu = defineComponent({name: 'menu', tag: 'gramlot-menu', base: MenuContainer,
103
+ subTags: 'menuline', implementation: Base => class extends Base {}});
104
+ export const MenuLine = defineComponent({name: 'menuline', tag: 'gramlot-menu-line', base: Command,
105
+ command: true, subTags: '*', parameters: {code: {dtype: 'T', nullable: true}},
106
+ implementation: Base => class extends Base {
107
+ attachCommand() {
108
+ const separator = this.textContent.trim() === '-';
109
+ if (!separator && !this.parameters.code) throw new TypeError('menuline requires a stable code');
110
+ this.setAttribute('role', separator ? 'separator' : 'menuitem');
111
+ this.control.tabIndex = -1;
112
+ this.disabled ||= separator;
113
+ }
114
+ get disabled() {
115
+ return super.disabled || Boolean(this.closest('gramlot-drop-down-button')?.parameters.disabled);
116
+ }
117
+ set disabled(value) { super.disabled = value; }
118
+ prepareCommand(event) {
119
+ if (!super.prepareCommand(event)) return false;
120
+ this.closest('gramlot-drop-down-button').selectCommand(this, event.shiftKey);
121
+ return true;
122
+ }
123
+ }
124
+ });
125
+ export const DropDownButton = defineComponent({name: 'dropDownButton', tag: 'gramlot-drop-down-button', base: Command,
126
+ command: true, subTags: '*', parameters: {persist: {dtype: 'B', default: false}},
127
+ implementation: Base => class extends Base {
128
+ #selected = null;
129
+ #observer = null;
130
+ #viewport = null;
131
+ #storageKey = null;
132
+ #popup;
133
+ #arrow;
134
+ #chosenCaption;
135
+ constructor() {
136
+ super();
137
+ const doc = this.ownerDocument;
138
+ this.control.classList.add('split');
139
+ this.#chosenCaption = doc.createElement('span');
140
+ this.#chosenCaption.hidden = true;
141
+ this.control.append(this.#chosenCaption);
142
+ this.#arrow = doc.createElement('button');
143
+ this.#arrow.type = 'button'; this.#arrow.className = 'arrow'; this.#arrow.textContent = '▾';
144
+ this.#arrow.setAttribute('aria-label', 'Open menu');
145
+ this.#arrow.setAttribute('aria-haspopup', 'menu');
146
+ this.#arrow.setAttribute('aria-expanded', 'false');
147
+ this.controlBox.append(this.#arrow);
148
+ this.#popup = doc.createElement('div');
149
+ this.#popup.className = 'popup'; this.#popup.id = 'menu'; this.#popup.setAttribute('popover', 'auto');
150
+ this.#arrow.setAttribute('aria-controls', 'menu');
151
+ const slot = doc.createElement('slot'); slot.name = 'menu';
152
+ this.#popup.append(slot); this.shadowRoot.append(this.#popup);
153
+ this.#arrow.addEventListener('click', event => {
154
+ event.stopPropagation();
155
+ if (this.#popup.matches(':popover-open')) this.closeMenu(); else this.openMenu();
156
+ });
157
+ this.#arrow.addEventListener('keydown', event => {
158
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
159
+ event.preventDefault(); this.openMenu(event.key === 'ArrowUp');
160
+ }
161
+ });
162
+ this.addEventListener('keydown', event => {
163
+ if (!this.#popup.matches(':popover-open')) return;
164
+ const items = this.menuItems.filter(item => !item.disabled);
165
+ const index = items.indexOf(event.composedPath().find(item => items.includes(item)));
166
+ let next;
167
+ if (event.key === 'ArrowDown') next = (index + 1) % items.length;
168
+ if (event.key === 'ArrowUp') next = (index - 1 + items.length) % items.length;
169
+ if (event.key === 'Home') next = 0;
170
+ if (event.key === 'End') next = items.length - 1;
171
+ if (next !== undefined) { event.preventDefault(); items[next]?.focus(); }
172
+ if (event.key === 'Escape' || event.key === 'Tab') {
173
+ if (event.key === 'Escape') event.preventDefault();
174
+ this.closeMenu();
175
+ }
176
+ });
177
+ this.#popup.addEventListener('toggle', () => {
178
+ const open = this.#popup.matches(':popover-open');
179
+ this.#arrow.setAttribute('aria-expanded', String(open));
180
+ if (!open) { this.#viewport?.abort(); this.#viewport = null; }
181
+ });
182
+ }
183
+ get menuItems() { return [...this.querySelectorAll(':scope > gramlot-menu > gramlot-menu-line')]; }
184
+ projectAttributes(attrs, adapt) {
185
+ const rest = super.projectAttributes(attrs, adapt);
186
+ this.#arrow.disabled = this.disabled;
187
+ if (this.disabled && this.#popup.matches(':popover-open')) this.closeMenu();
188
+ this.#refreshCaption();
189
+ return rest;
190
+ }
191
+ attachCommand() {
192
+ if (this.parameters.persist) {
193
+ if (!this.id) throw new TypeError('dropDownButton persist requires an explicit id');
194
+ this.#storageKey = `gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;
195
+ try { this.#selected = this.ownerDocument.defaultView.localStorage.getItem(this.#storageKey); } catch { /* Storage may be disabled. */ }
196
+ }
197
+ this.#refreshCaption();
198
+ this.#observer = new this.ownerDocument.defaultView.MutationObserver(() => this.#refreshCaption());
199
+ this.#observer.observe(this, {childList: true, subtree: true, characterData: true});
200
+ }
201
+ releaseCommand() {
202
+ this.#observer?.disconnect(); this.#observer = null;
203
+ this.#viewport?.abort(); this.#viewport = null;
204
+ if (this.#popup.matches(':popover-open')) this.#popup.hidePopover();
205
+ }
206
+ commandTarget(event) {
207
+ if (event?.composedPath().includes(this.#popup)) return null;
208
+ return this.menuItems.find(item => item.parameters.code === this.#selected) ?? this;
209
+ }
210
+ selectCommand(item, remember) {
211
+ if (remember) {
212
+ this.#selected = item.parameters.code;
213
+ if (this.#storageKey) {
214
+ try { this.ownerDocument.defaultView.localStorage.setItem(this.#storageKey, this.#selected); } catch { /* Keep the in-memory choice. */ }
215
+ }
216
+ this.#refreshCaption();
217
+ }
218
+ this.closeMenu();
219
+ }
220
+ #refreshCaption() {
221
+ const codes = this.menuItems.filter(item => item.parameters.code).map(item => item.parameters.code);
222
+ if (new Set(codes).size !== codes.length) throw new TypeError('Dropdown menu codes must be unique');
223
+ const target = this.commandTarget();
224
+ const selected = target !== this;
225
+ this.caption.hidden = selected;
226
+ this.#chosenCaption.hidden = !selected;
227
+ this.#chosenCaption.textContent = selected ? target.textContent : '';
228
+ this.icon.textContent = selected ? target.parameters.icon : this.parameters.icon;
229
+ }
230
+ openMenu(last = false) {
231
+ if (this.disabled) return;
232
+ const items = this.menuItems.filter(item => !item.disabled);
233
+ if (!items.length) return;
234
+ this.#popup.showPopover();
235
+ this.#arrow.setAttribute('aria-expanded', 'true');
236
+ const place = () => positionPopup(this.#popup, this.controlBox);
237
+ place();
238
+ this.#viewport?.abort();
239
+ this.#viewport = new this.ownerDocument.defaultView.AbortController();
240
+ const options = {signal: this.#viewport.signal, capture: true};
241
+ this.ownerDocument.defaultView.addEventListener('resize', place, options);
242
+ this.ownerDocument.addEventListener('scroll', place, options);
243
+ items[last ? items.length - 1 : 0].focus();
244
+ }
245
+ closeMenu() {
246
+ if (!this.#popup.matches(':popover-open')) return;
247
+ this.#popup.hidePopover();
248
+ this.#arrow.setAttribute('aria-expanded', 'false');
249
+ this.#viewport?.abort(); this.#viewport = null;
250
+ this.#arrow.focus();
251
+ }
252
+ }
253
+ });
254
+ export default defineCollection({name: 'buttons', components: [Button, ToggleButton, DropDownButton, Menu, MenuLine]});
@@ -0,0 +1,221 @@
1
+ import {NativeControl} from './bases.js';
2
+ import {parseChoices} from './choices.js';
3
+ import {positionPopup} from './popup.js';
4
+
5
+ /** Shared suggestions: constrained controls commit codes; comboBox commits text. */
6
+ export function ChoiceEditor(HTMLElement) {
7
+ return class extends NativeControl(HTMLElement) {
8
+ #value;
9
+ #rows = [];
10
+ #active = -1;
11
+ #generation = 0;
12
+ #opened = false;
13
+ #dirty = false;
14
+ #picked = null;
15
+ #source;
16
+ #cleanup;
17
+ constructor() {
18
+ super();
19
+ const doc = this.ownerDocument;
20
+ const style = doc.createElement('style');
21
+ style.textContent = `.option{position:relative} #control{width:100%;padding-right:calc(var(--gramlot-choice-toggle-width,1.6em) + .2em)}
22
+ .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}
23
+ .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;
24
+ 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)}
25
+ .choices[hidden]{display:none} .choice{min-height:var(--gramlot-touch-target,0px);display:flex;align-items:center;padding:.25em .5em;cursor:pointer}
26
+ .choice[aria-selected=true]{background:var(--gramlot-selected,Highlight);color:var(--gramlot-ink,HighlightText)}`;
27
+ this.toggle = doc.createElement('button');
28
+ this.toggle.className = 'toggle'; this.toggle.type = 'button'; this.toggle.tabIndex = -1;
29
+ this.toggle.textContent = '▾'; this.toggle.setAttribute('aria-label', 'Show options');
30
+ this.control.parentElement.append(this.toggle);
31
+ this.choices = doc.createElement('div');
32
+ this.choices.id = 'choices'; this.choices.className = 'choices'; this.choices.hidden = true;
33
+ this.choices.setAttribute('role', 'listbox'); this.choices.setAttribute('popover', 'manual');
34
+ this.controlBox.append(style, this.choices);
35
+ this.toggle.addEventListener('mousedown', event => event.preventDefault());
36
+ this.toggle.addEventListener('click', () => {
37
+ if (this.locked) return;
38
+ this.control.focus();
39
+ if (this.#opened) this.closeChoices(); else this.search('');
40
+ });
41
+ this.choices.addEventListener('mousedown', event => event.preventDefault());
42
+ this.control.addEventListener('input', event => {
43
+ this.#dirty = true; this.#picked = null;
44
+ if (!event.isComposing) this.search(this.control.value);
45
+ });
46
+ this.control.addEventListener('compositionend', () => this.search(this.control.value));
47
+ this.control.addEventListener('keydown', event => {
48
+ if (event.isComposing || this.locked) return;
49
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
50
+ event.preventDefault();
51
+ if (!this.#opened) this.search('');
52
+ else this.activate(this.#active + (event.key === 'ArrowDown' ? 1 : -1));
53
+ } else if (event.key === 'Enter') {
54
+ event.preventDefault();
55
+ if (this.#opened && this.#rows[this.#active]) this.choose(this.#rows[this.#active]);
56
+ else this.commitDraft();
57
+ } else if (event.key === 'Escape') {
58
+ this.closeChoices(); this.#dirty = false; this.#picked = null;
59
+ this.resolveValue();
60
+ }
61
+ });
62
+ this.control.addEventListener('blur', () => { if (this.#dirty) this.commitDraft(); this.closeChoices(); });
63
+ }
64
+ createControl() {
65
+ const input = this.ownerDocument.createElement('input'); input.type = 'text';
66
+ input.setAttribute('role', 'combobox'); input.setAttribute('aria-autocomplete', 'list');
67
+ input.setAttribute('aria-controls', 'choices'); input.setAttribute('aria-expanded', 'false');
68
+ input.autocomplete = 'off'; return input;
69
+ }
70
+ get constrained() { return true; }
71
+ get commitOnChange() { return this.constrained; }
72
+ get locked() { return this.control.disabled || this.control.readOnly; }
73
+ get active() { return this.isConnected && this.pageContext?.isActive(); }
74
+ projectAttributes(attrs, adapt) {
75
+ const rest = super.projectAttributes(attrs, adapt);
76
+ const source = this.parameters.callback ?? this.parameters.values;
77
+ const changed = source !== this.#source;
78
+ this.#source = source;
79
+ this.toggle.disabled = this.locked;
80
+ if (changed || this.locked) this.closeChoices();
81
+ if (changed && this.active && !this.#dirty) this.resolveValue();
82
+ return rest;
83
+ }
84
+ setPageContext(context) { super.setPageContext(context); this.resolveValue(); }
85
+ connectedCallback() { this.resolveValue(); }
86
+ readControlValue() { return this.#value; }
87
+ writeControlValue(value) {
88
+ if (Object.is(value, this.#value)) return;
89
+ this.#value = value; this.#dirty = false; this.#picked = null;
90
+ this.closeChoices(); this.resolveValue();
91
+ }
92
+ validateSelection(value) {
93
+ if (!this.constrained) return super.validateSelection(value);
94
+ if (value == null || this.#rows.some(row => row.id === value) || this.#picked?.id === value) return true;
95
+ return {errorcode:'missing', message:'Choose a value from the list.'};
96
+ }
97
+ acceptControlValue() {
98
+ if (!this.#dirty) return this.validateCandidate(this.#value, accepted => this.writeControlValue(accepted));
99
+ const text = this.control.value;
100
+ const matches = this.#picked ? [this.#picked] : this.#rows.filter(row => row.caption === text);
101
+ if (this.constrained && text !== '' && matches.length !== 1) {
102
+ this.error('Choose a value from the list.'); return {ok: false};
103
+ }
104
+ const value = this.constrained ? (text === '' ? null : matches[0].id) : text;
105
+ return this.validateCandidate(value, accepted => {
106
+ if (accepted !== value && this.constrained) throw new Error('Validation cannot replace a selected code; update the Data explicitly.');
107
+ this.#value = accepted; this.#dirty = false; this.#picked = null;
108
+ if (!this.constrained) this.control.value = accepted ?? '';
109
+ });
110
+ }
111
+ commitDraft() {
112
+ const Event = this.ownerDocument.defaultView.Event;
113
+ this.control.dispatchEvent(new Event('change', {bubbles: true}));
114
+ }
115
+ choose(row) {
116
+ if (this.locked || !this.active) return;
117
+ this.#picked = row; this.#dirty = true; this.control.value = row.caption;
118
+ this.closeChoices(); this.commitDraft();
119
+ }
120
+ async request(keywords) {
121
+ const generation = ++this.#generation;
122
+ this.control.setAttribute('aria-busy', 'true'); this.error('');
123
+ try {
124
+ const rows = await this.loadChoices(keywords);
125
+ if (generation !== this.#generation || !this.active) return null;
126
+ return rows;
127
+ } catch (error) {
128
+ if (generation === this.#generation && this.active) this.error(error.message);
129
+ return null;
130
+ } finally {
131
+ if (generation === this.#generation) this.control.setAttribute('aria-busy', 'false');
132
+ }
133
+ }
134
+ async resolveValue() {
135
+ if (this.#value == null || this.#value === '') { this.control.value = ''; this.error(''); return; }
136
+ if (!this.active) return;
137
+ this.control.value = this.#value;
138
+ if (!this.constrained) { this.error(''); return; }
139
+ const rows = await this.request({_id: this.#value});
140
+ if (!rows) return;
141
+ const row = rows.find(item => item.id === this.#value);
142
+ this.#rows = rows;
143
+ this.control.value = row ? row.caption : this.#value;
144
+ this.error(row ? '' : 'Value is not in the list.');
145
+ }
146
+ async search(query) {
147
+ if (this.locked || !this.active) return;
148
+ this.closeChoices(); this.#rows = [];
149
+ const rows = await this.request({_querystring: query});
150
+ if (!rows || this.locked || this.shadowRoot.activeElement !== this.control) return;
151
+ this.#rows = rows;
152
+ const doc = this.ownerDocument;
153
+ this.choices.replaceChildren(...rows.map((row, index) => {
154
+ const item = doc.createElement('div'); item.id = `choice-${index}`;
155
+ item.className = 'choice'; item.setAttribute('role', 'option'); item.textContent = row.caption;
156
+ item.addEventListener('click', () => this.choose(row)); return item;
157
+ }));
158
+ if (!rows.length) this.choices.textContent = 'No results';
159
+ const view = doc.defaultView;
160
+ this.choices.hidden = false; this.choices.showPopover(); this.#opened = true;
161
+ positionPopup(this.choices, this.control, {matchWidth: true});
162
+ this.control.setAttribute('aria-expanded', 'true'); this.activate(0);
163
+ const close = () => this.closeChoices();
164
+ const outside = event => { if (!event.composedPath().includes(this)) close(); };
165
+ const scroll = event => { if (!event.composedPath().includes(this.choices)) close(); };
166
+ doc.addEventListener('pointerdown', outside, true); doc.addEventListener('scroll', scroll, true);
167
+ view.addEventListener('resize', close);
168
+ this.#cleanup = () => {
169
+ doc.removeEventListener('pointerdown', outside, true); doc.removeEventListener('scroll', scroll, true);
170
+ view.removeEventListener('resize', close);
171
+ };
172
+ }
173
+ activate(index) {
174
+ this.#active = this.#rows.length ? Math.max(0, Math.min(index, this.#rows.length - 1)) : -1;
175
+ for (const [i, item] of [...this.choices.children].entries()) {
176
+ item.setAttribute('aria-selected', String(i === this.#active));
177
+ if (i === this.#active) item.scrollIntoView({block: 'nearest'});
178
+ }
179
+ if (this.#active < 0) this.control.removeAttribute('aria-activedescendant');
180
+ else this.control.setAttribute('aria-activedescendant', `choice-${this.#active}`);
181
+ }
182
+ closeChoices() {
183
+ ++this.#generation; this.#cleanup?.(); this.#cleanup = null;
184
+ if (this.#opened) this.choices.hidePopover();
185
+ this.#opened = false; this.choices.hidden = true;
186
+ this.control.setAttribute('aria-expanded', 'false'); this.control.setAttribute('aria-busy', 'false');
187
+ this.control.removeAttribute('aria-activedescendant');
188
+ }
189
+ releaseControl() { this.closeChoices(); }
190
+ disconnectedCallback() { this.releaseControl(); }
191
+ };
192
+ }
193
+ ChoiceEditor.parameters = {...NativeControl.parameters,
194
+ value: {dtype: 'T', nullable: true, binding: 'twoWay'},
195
+ placeholder: {dtype: 'T', qualification: 'intl_str', default: '', target: 'control'}};
196
+
197
+ export function localChoices(Base) {
198
+ return class extends Base {
199
+ loadChoices(keywords) {
200
+ const rows = parseChoices(this.parameters.values ?? '');
201
+ return rows.filter(row => Object.hasOwn(keywords, '_id') ? row.id === keywords._id
202
+ : row.caption.toLocaleLowerCase().includes(keywords._querystring.toLocaleLowerCase()));
203
+ }
204
+ };
205
+ }
206
+ export function callbackChoices(Base) {
207
+ return class extends Base {
208
+ async loadChoices(keywords) {
209
+ const result = await this.pageContext.callLogic(this.parameters.callback, keywords);
210
+ if (!result || !Array.isArray(result.rows) || typeof result.identifier !== 'string' || typeof result.caption !== 'string') {
211
+ throw new TypeError('callbackSelect requires {rows, identifier, caption}');
212
+ }
213
+ const ids = new Set();
214
+ return result.rows.map(record => {
215
+ const id = record[result.identifier], caption = record[result.caption];
216
+ if (typeof id !== 'string' || !id || typeof caption !== 'string' || ids.has(id)) throw new TypeError('Invalid or duplicate choice code/caption');
217
+ ids.add(id); return {id, caption};
218
+ });
219
+ }
220
+ };
221
+ }