@gramlot/gramlot 0.2.20 → 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 (60) hide show
  1. package/dist/gramlot.js +1343 -303
  2. package/dist/gramlot.min.js +363 -24
  3. package/package.json +6 -3
  4. package/src/binding/ask-dialog.js +2 -2
  5. package/src/binding/inline.js +3 -10
  6. package/src/binding/installation.js +2 -1
  7. package/src/binding/pointer.js +12 -148
  8. package/src/binding/providers.js +2 -1
  9. package/src/binding/runtime.js +2 -1
  10. package/src/bootstrap.d.ts +2 -0
  11. package/src/bootstrap.js +9 -2
  12. package/src/builder/gramlot-builder.js +21 -4
  13. package/src/builder/source.js +11 -10
  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/format.js +13 -6
  31. package/src/gramlot.d.ts +5 -1
  32. package/src/gramlot.js +8 -1
  33. package/src/handlers/dom-handler.d.ts +1 -0
  34. package/src/handlers/dom-handler.js +7 -0
  35. package/src/index-page-runtime.js +78 -30
  36. package/src/index-page-styles.js +2 -2
  37. package/src/index-theme.js +1 -1
  38. package/src/renderer/attributes.js +3 -40
  39. package/src/renderer/gramlot-html-renderer.js +4 -3
  40. package/src/renderer/gramlot-renderer.js +62 -4
  41. package/src/server/gramlot-server.d.ts +3 -0
  42. package/src/server/gramlot-server.js +9 -3
  43. package/src/server/index-page.d.ts +1 -0
  44. package/src/server/index-page.js +8 -3
  45. package/src/server/page-base.js +1 -0
  46. package/src/server/page.d.ts +1 -0
  47. package/src/server/resources.d.ts +2 -0
  48. package/src/view/button.js +17 -13
  49. package/src/view/controls.js +152 -4
  50. package/src/view/html.js +18 -0
  51. package/themes/gramlot-base/README.md +6 -0
  52. package/themes/gramlot-base/theme.css +34 -6
  53. package/themes/gramlot-compact/README.md +6 -0
  54. package/themes/gramlot-compact/theme.css +8 -4
  55. package/themes/joanna/README.md +23 -0
  56. package/themes/joanna/theme.css +89 -0
  57. package/themes/mimi/README.md +23 -0
  58. package/themes/mimi/theme.css +89 -0
  59. package/tools/gramlot-tools-inspector.js +42 -18
  60. package/tools/inspector-agent.js +8 -4
@@ -0,0 +1,74 @@
1
+ /** One stable label/control composition for single controls and groups. */
2
+ const POSITIONS = ['TL', 'TC', 'TR', 'L', 'R', 'BL', 'BC', 'BR'];
3
+ function project(element, attrs, adapt, previous) {
4
+ const next = adapt(attrs);
5
+ for (const key of new Set([...Object.keys(previous), ...Object.keys(next)])) {
6
+ if (next[key] == null) element.removeAttribute(key);
7
+ else element.setAttribute(key, String(next[key]));
8
+ }
9
+ return next;
10
+ }
11
+ export function Labelbox(Base) {
12
+ return class extends Base {
13
+ #previous = {box: {}, label: {}, labelBox: {}, controlBox: {}};
14
+ constructor() {
15
+ super();
16
+ this.box = this.ownerDocument.createElement('div');
17
+ this.box.className = 'labelbox';
18
+ this.labelBox = this.ownerDocument.createElement('div');
19
+ this.labelBox.className = 'label-box';
20
+ this.fieldLabel = this.ownerDocument.createElement('label');
21
+ this.fieldLabel.id = 'field-label';
22
+ this.fieldLabel.htmlFor = 'control';
23
+ this.labelBox.append(this.fieldLabel);
24
+ this.box.append(this.labelBox, this.controlBox);
25
+ const style = this.ownerDocument.createElement('style');
26
+ style.textContent = `.labelbox{--gramlot-label-width:initial;--gramlot-formlet-label-width:initial;display:grid;gap:var(--gramlot-label-gap,.25em);grid-template-areas:'label' 'control'}
27
+ .label-box{grid-area:label;color:var(--gramlot-label-color,var(--gramlot-text-secondary,inherit));font-size:var(--gramlot-label-size,1em)} .control-box{grid-area:control}
28
+ .labelbox[data-position='L']{grid-template-areas:'label control';align-items:center}
29
+ .labelbox[data-position='R']{grid-template-areas:'control label';align-items:center}
30
+ .labelbox[data-position^='B']{grid-template-areas:'control' 'label'}
31
+ .labelbox[data-position$='C']>.label-box{text-align:center}
32
+ .labelbox[data-position$='R']>.label-box{text-align:right}
33
+ .label-box[hidden]{display:none} .label-box label{display:block}
34
+ .labelbox[data-position='L']>.label-box{text-align:right;padding-right:2px}
35
+ .labelbox[data-formlet-aligned]>.label-box>label{width:max-content;margin-left:auto}
36
+ .labelbox[data-position='L']{grid-template-columns:var(--gramlot-label-width,var(--gramlot-formlet-label-width,max-content)) minmax(0,1fr)}`;
37
+ this.shadowRoot.append(style, this.box);
38
+ }
39
+ projectAttributes(attrs, adapt) {
40
+ const rest = super.projectAttributes(attrs, adapt);
41
+ const {lbl, lbl_position = 'TL'} = this.parameters;
42
+ if (!POSITIONS.includes(lbl_position)) throw new TypeError(`Invalid lbl_position: ${lbl_position}`);
43
+ const groups = {box: {}, label: {}, labelBox: {}, controlBox: {}};
44
+ const prefixes = [['box_l_', 'labelBox'], ['box_c_', 'controlBox'], ['lbl_', 'label'], ['box_', 'box']];
45
+ for (const [name, value] of Object.entries(rest)) {
46
+ const match = prefixes.find(([prefix]) => name.startsWith(prefix));
47
+ if (match) { groups[match[1]][name.slice(match[0].length)] = value; delete rest[name]; }
48
+ }
49
+ const elements = {box: this.box, label: this.fieldLabel, labelBox: this.labelBox, controlBox: this.controlBox};
50
+ for (const [name, element] of Object.entries(elements)) {
51
+ this.#previous[name] = project(element, groups[name], adapt, this.#previous[name]);
52
+ }
53
+ if (attrs.lbl_width == null) this.box.style.removeProperty('--gramlot-label-width');
54
+ else this.box.style.setProperty('--gramlot-label-width', attrs.lbl_width);
55
+ this.box.classList.add('labelbox');
56
+ this.labelBox.classList.add('label-box');
57
+ this.controlBox.classList.add('control-box');
58
+ this.box.dataset.position = lbl_position;
59
+ this.fieldLabel.textContent = lbl ?? '';
60
+ this.labelBox.hidden = lbl == null || lbl === '';
61
+ // Native label association applies to input; a group uses aria-labelledby.
62
+ if (this.control.localName !== 'input') {
63
+ if (this.labelBox.hidden) this.control.removeAttribute('aria-labelledby');
64
+ else this.control.setAttribute('aria-labelledby', 'field-label');
65
+ }
66
+ this.dispatchEvent(new this.ownerDocument.defaultView.Event('gramlot-label-layout', {bubbles:true}));
67
+ return rest;
68
+ }
69
+ };
70
+ }
71
+ Labelbox.parameters = {
72
+ lbl: {dtype: 'T', qualification: 'intl_str', nullable: true, binding: 'read'},
73
+ lbl_position: {dtype: 'T', default: 'TL', binding: 'read', enum: POSITIONS}
74
+ };
@@ -0,0 +1,190 @@
1
+ /** Slotted layout components; Source owns children and Data owns field values. */
2
+ import {defineComponent, defineCollection} from './registry.js';
3
+ import {Labelbox} from './labelbox.js';
4
+ import {projectParameters} from './parameters.js';
5
+ import {positionPopup} from './popup.js';
6
+ import {FormletLabels} from './formlet-labels.js';
7
+
8
+ const COPY_FEEDBACK_DURATION = 1600;
9
+
10
+ function Container(HTMLElement) {
11
+ return class extends HTMLElement {
12
+ constructor() {
13
+ super();
14
+ const shadow = this.attachShadow({mode: 'open'});
15
+ const style = this.ownerDocument.createElement('style');
16
+ style.textContent = `:host{display:block;min-width:0;font:inherit;color:var(--gramlot-ink,CanvasText)}
17
+ *,*::before,*::after{box-sizing:border-box}.control-box{min-width:0}slot{display:contents}
18
+ ::slotted(*){min-width:0;max-width:100%}`;
19
+ this.controlBox = this.ownerDocument.createElement('div');
20
+ this.controlBox.className = 'control-box';
21
+ this.control = this.controlBox; this.control.id = 'control';
22
+ this.control.append(this.ownerDocument.createElement('slot'));
23
+ shadow.append(style, this.controlBox);
24
+ }
25
+ projectAttributes(attrs) {
26
+ return projectParameters(this, attrs);
27
+ }
28
+ };
29
+ }
30
+ Container.parameters = {};
31
+
32
+ export const Formlet = defineComponent({
33
+ name: 'formlet', tag: 'gramlot-formlet', base: Container, subTags: '*', presentationDefaults: ['lbl_', 'box_'],
34
+ parameters: {
35
+ columns: {dtype: ['L', 'T'], default: 1, binding: 'read'},
36
+ col_min_width: {dtype: 'T', nullable: true, binding: 'read'},
37
+ },
38
+ implementation: Base => class extends Base {
39
+ #labels;
40
+ constructor() {
41
+ super();
42
+ const style = this.ownerDocument.createElement('style');
43
+ style.textContent = `.control-box{display:grid;gap:inherit;align-items:start}
44
+ :host{gap:var(--gramlot-formlet-gap,8px 16px)}`;
45
+ this.shadowRoot.append(style);
46
+ this.#labels = new FormletLabels(this);
47
+ }
48
+ connectedCallback() { this.#labels.connect(); }
49
+ disconnectedCallback() { this.#labels.disconnect(); }
50
+ projectAttributes(attrs, adapt) {
51
+ const rest = super.projectAttributes(attrs, adapt);
52
+ const {columns, col_min_width} = this.parameters;
53
+ if (typeof columns === 'number' && (!Number.isInteger(columns) || columns < 1)) {
54
+ throw new TypeError('formlet columns must be a positive integer or CSS track list');
55
+ }
56
+ this.control.style.gridTemplateColumns = col_min_width
57
+ ? `repeat(auto-fit, minmax(min(100%, ${col_min_width}), 1fr))`
58
+ : typeof columns === 'number' ? `repeat(${columns}, minmax(0, 1fr))` : columns;
59
+ this.#labels.schedule();
60
+ // Presentation defaults belong to descendants, not this container's DOM.
61
+ return Object.fromEntries(Object.entries(rest).filter(([name]) => !/^(lbl_|box_)/.test(name)));
62
+ }
63
+ }
64
+ });
65
+
66
+ export const GroupBox = defineComponent({
67
+ name: 'groupBox', tag: 'gramlot-group-box', base: Container, subTags: '*', dataScope: true, mixins: [Labelbox],
68
+ parameters: {
69
+ copy: {dtype: 'B', default: false, binding: 'read'},
70
+ lbl_variant: {dtype: 'T', default: 'bar', binding: 'read', enum: ['bar', 'underline']},
71
+ },
72
+ implementation: Base => class extends Base {
73
+ #generation = 0;
74
+ #timer;
75
+ #busy = false;
76
+ #menuEvents;
77
+ #menuOpen = false;
78
+ constructor() {
79
+ super();
80
+ this.control.setAttribute('role', 'group');
81
+ this.fieldLabel.removeAttribute('for');
82
+ const doc = this.ownerDocument;
83
+ const style = doc.createElement('style');
84
+ style.textContent = `.labelbox{gap:0;border:1px solid var(--gramlot-border-control,#aaa);border-radius:var(--gramlot-radius-sm,4px)}
85
+ .label-box{display:flex;align-items:center;gap:.4em;padding:var(--gramlot-group-header-padding,.35em .65em);background:var(--gramlot-surface-subtle,#eef1f5)}
86
+ .label-box[hidden]{display:none}.label-box label{flex:1;min-width:0}
87
+ .control-box{padding:var(--gramlot-group-padding,.65em)}.labelbox[data-variant=underline]{border:0}
88
+ [data-variant=underline]>.label-box{background:transparent;border-bottom:1px solid var(--gramlot-border-control,#aaa)}
89
+ .actions{display:flex;align-items:center}.actions[hidden]{display:none}
90
+ button{font:inherit;color:inherit;cursor:pointer;border:0;border-radius:var(--gramlot-radius-sm,4px);background:transparent;
91
+ padding:var(--gramlot-group-action-padding,.2em .4em);min-width:var(--gramlot-touch-target,var(--gramlot-group-action-size,24px));min-height:var(--gramlot-touch-target,var(--gramlot-group-action-size,24px))}
92
+ button:hover{background:var(--gramlot-field-readonly-background,#ddd)}button:disabled{opacity:.5}
93
+ button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight)}
94
+ .copy-menu{max-width:var(--gramlot-popup-available-width,100vw);position:fixed;inset:auto;margin:0;padding:var(--gramlot-popup-padding,4px);max-height:var(--gramlot-popup-available-height,100vh);overflow:auto;border:1px solid var(--gramlot-border-control,#aaa);
95
+ background:var(--gramlot-field-background,Canvas);color:var(--gramlot-ink,CanvasText);border-radius:var(--gramlot-radius-sm,4px)}
96
+ .copy-menu button{display:block;width:100%;text-align:left}
97
+ .status{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)}`;
98
+ this.actions = doc.createElement('span'); this.actions.className = 'actions';
99
+ this.copyButton = doc.createElement('button'); this.copyButton.type = 'button';
100
+ this.copyButton.textContent = '⧉'; this.copyButton.title = 'Copy TYTX';
101
+ this.copyButton.setAttribute('aria-label', 'Copy TYTX');
102
+ this.menuButton = doc.createElement('button'); this.menuButton.type = 'button';
103
+ this.menuButton.textContent = '▾'; this.menuButton.setAttribute('aria-label', 'Choose copy format');
104
+ this.menuButton.setAttribute('aria-expanded', 'false');
105
+ this.copyMenu = doc.createElement('div'); this.copyMenu.className = 'copy-menu';
106
+ this.copyMenu.id = 'copy-menu'; this.copyMenu.setAttribute('popover', 'auto');
107
+ this.menuButton.setAttribute('aria-controls', 'copy-menu');
108
+ for (const format of ['TYTX', 'JSON']) {
109
+ const button = doc.createElement('button'); button.type = 'button'; button.textContent = `Copy ${format}`;
110
+ button.addEventListener('click', () => { this.closeCopyMenu(); this.copyData(format); });
111
+ this.copyMenu.append(button);
112
+ }
113
+ this.status = doc.createElement('span'); this.status.className = 'status';
114
+ this.status.setAttribute('role', 'status');
115
+ this.copyButton.addEventListener('click', () => this.copyData('TYTX'));
116
+ this.menuButton.addEventListener('click', () => {
117
+ if (this.#menuOpen) { this.closeCopyMenu(); return; }
118
+ this.copyMenu.showPopover(); this.#menuOpen = true;
119
+ positionPopup(this.copyMenu, this.menuButton, {align: 'end'});
120
+ const view = doc.defaultView;
121
+ this.#menuEvents = new view.AbortController();
122
+ const options = {capture: true, signal: this.#menuEvents.signal};
123
+ view.addEventListener('scroll', event => {
124
+ if (!event.composedPath().includes(this.copyMenu)) this.closeCopyMenu();
125
+ }, options);
126
+ view.addEventListener('resize', () => this.closeCopyMenu(), options);
127
+ this.copyMenu.firstElementChild.focus();
128
+ });
129
+ this.copyMenu.addEventListener('toggle', event => {
130
+ this.menuButton.setAttribute('aria-expanded', String(event.newState === 'open'));
131
+ if (event.newState === 'closed') {
132
+ this.#menuOpen = false; this.#menuEvents?.abort(); this.#menuEvents = null;
133
+ }
134
+ });
135
+ this.actions.append(this.copyButton, this.menuButton, this.status);
136
+ this.labelBox.append(this.actions);
137
+ this.shadowRoot.append(style, this.copyMenu);
138
+ }
139
+ closeCopyMenu() {
140
+ if (this.#menuOpen) this.copyMenu.hidePopover();
141
+ this.#menuOpen = false;
142
+ this.#menuEvents?.abort(); this.#menuEvents = null;
143
+ this.menuButton.setAttribute('aria-expanded', 'false');
144
+ }
145
+ projectAttributes(attrs, adapt) {
146
+ const rest = super.projectAttributes(attrs, adapt);
147
+ if (!this.constructor.gramlotComponent.parameters.lbl_variant.enum.includes(this.parameters.lbl_variant)) throw new TypeError('groupBox lbl_variant must be bar or underline');
148
+ this.box.dataset.variant = this.parameters.lbl_variant;
149
+ this.actions.hidden = !this.parameters.copy;
150
+ if (!this.parameters.copy) this.closeCopyMenu();
151
+ this.labelBox.hidden = this.labelBox.hidden && !this.parameters.copy;
152
+ this.copyButton.disabled = this.#busy;
153
+ this.menuButton.disabled = this.#busy;
154
+ return rest;
155
+ }
156
+ async copyData(format = 'TYTX') {
157
+ if (!['TYTX', 'JSON'].includes(format)) throw new TypeError('Copy format must be TYTX or JSON');
158
+ if (!this.parameters.copy || this.#busy || !this.isConnected) return;
159
+ const generation = ++this.#generation;
160
+ this.copyButton.title = 'Copy TYTX';
161
+ this.copyButton.textContent = '⧉'; this.status.textContent = '';
162
+ this.#busy = true; this.copyButton.disabled = this.menuButton.disabled = true;
163
+ this.ownerDocument.defaultView.clearTimeout(this.#timer);
164
+ try {
165
+ const bag = this.readDataScope();
166
+ const text = format === 'TYTX' ? bag.toTytx() : JSON.stringify(bag.asDict(false, false, true), null, 2);
167
+ await this.ownerDocument.defaultView.navigator.clipboard.writeText(text);
168
+ if (generation !== this.#generation || !this.isConnected) return;
169
+ this.copyButton.textContent = '✓'; this.status.textContent = `Copied ${format}`;
170
+ this.#timer = this.ownerDocument.defaultView.setTimeout(() => {
171
+ this.copyButton.textContent = '⧉'; this.status.textContent = '';
172
+ }, COPY_FEEDBACK_DURATION);
173
+ } catch (error) {
174
+ if (generation !== this.#generation || !this.isConnected) return;
175
+ this.copyButton.textContent = '!';
176
+ this.copyButton.title = this.status.textContent = `Copy failed: ${error.message}`;
177
+ } finally {
178
+ if (generation === this.#generation) {
179
+ this.#busy = false; this.copyButton.disabled = this.menuButton.disabled = false;
180
+ }
181
+ }
182
+ }
183
+ disconnectedCallback() {
184
+ this.closeCopyMenu();
185
+ this.#generation++; this.#busy = false;
186
+ this.ownerDocument.defaultView.clearTimeout(this.#timer);
187
+ }
188
+ }
189
+ });
190
+ export default defineCollection({name: 'layout', components: [Formlet, GroupBox]});
@@ -0,0 +1,6 @@
1
+ /** Resolve descriptor defaults once and return attributes owned by other layers. */
2
+ export function projectParameters(element, attrs) {
3
+ element.parameters = Object.fromEntries(Object.entries(element.constructor.gramlotComponent.parameters)
4
+ .map(([name, spec]) => [name, Object.hasOwn(attrs, name) ? attrs[name] : spec.default]));
5
+ return Object.fromEntries(Object.entries(attrs).filter(([name]) => !Object.hasOwn(element.parameters, name)));
6
+ }
@@ -0,0 +1,22 @@
1
+ /** Geometry only: each component owns opening, focus, events and cleanup. */
2
+ const VIEWPORT_MARGIN = 8;
3
+ const ANCHOR_GAP = 3;
4
+
5
+ export function positionPopup(popup, anchor, {align = 'start', matchWidth = false} = {}) {
6
+ const view = anchor.ownerDocument.defaultView;
7
+ const field = anchor.getBoundingClientRect();
8
+ const availableWidth = Math.max(0, view.innerWidth - 2 * VIEWPORT_MARGIN);
9
+ popup.style.setProperty('--gramlot-popup-available-width', `${availableWidth}px`);
10
+ if (matchWidth) popup.style.width = `${Math.min(field.width, availableWidth)}px`;
11
+ popup.style.removeProperty('--gramlot-popup-available-height');
12
+ const natural = popup.getBoundingClientRect();
13
+ const below = Math.max(0, view.innerHeight - VIEWPORT_MARGIN - field.bottom - ANCHOR_GAP);
14
+ const above = Math.max(0, field.top - VIEWPORT_MARGIN - ANCHOR_GAP);
15
+ const upwards = natural.height > below && above > below;
16
+ popup.style.setProperty('--gramlot-popup-available-height', `${upwards ? above : below}px`);
17
+ const size = popup.getBoundingClientRect();
18
+ const left = align === 'end' ? field.right - size.width : field.left;
19
+ const top = upwards ? field.top - size.height - ANCHOR_GAP : field.bottom + ANCHOR_GAP;
20
+ popup.style.left = `${Math.max(VIEWPORT_MARGIN, Math.min(left, view.innerWidth - size.width - VIEWPORT_MARGIN))}px`;
21
+ popup.style.top = `${Math.max(VIEWPORT_MARGIN, Math.min(top, view.innerHeight - size.height - VIEWPORT_MARGIN))}px`;
22
+ }
@@ -0,0 +1,83 @@
1
+ /** DOM-free component definitions and their portable Builder declarations. */
2
+ import {webcomponentCode} from '../webcomponent.js';
3
+
4
+ function freeze(value) {
5
+ for (const child of Object.values(value)) if (child && typeof child === 'object') freeze(child);
6
+ return Object.freeze(value);
7
+ }
8
+ function annotation(parameter) {
9
+ if (typeof parameter.dtype !== 'string' && !Array.isArray(parameter.dtype)) throw new TypeError('Component parameter requires dtype');
10
+ const alternatives = (Array.isArray(parameter.dtype) ? parameter.dtype : [parameter.dtype]).map(dtype => ({kind: 'dtype', dtype}));
11
+ if (parameter.nullable) alternatives.push({kind: 'dtype', dtype: 'NN'});
12
+ if (parameter.binding && parameter.dtype !== 'T') alternatives.push({kind: 'annotated',
13
+ base: {kind: 'dtype', dtype: 'T'},
14
+ metadata: [{kind: 'regex', pattern: '^[\\^=].+', flags: 0}]});
15
+ return alternatives.length === 1 ? alternatives[0] : {kind: 'union', items: alternatives};
16
+ }
17
+
18
+ /** Compose effective metadata without invoking a DOM class factory. */
19
+ export function defineComponent({name, tag, base, mixins = [], parameters = {}, subTags = '', presentationDefaults = [], dataScope = false, command = false, implementation}) {
20
+ webcomponentCode({code: tag});
21
+ if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(name)) throw new TypeError('Invalid component authoring name');
22
+ const effective = {...base.parameters};
23
+ for (const mixin of mixins) {
24
+ for (const [key, spec] of Object.entries(mixin.parameters)) {
25
+ if (Object.hasOwn(effective, key)) throw new Error(`Duplicate mixin parameter: ${key}`);
26
+ effective[key] = spec;
27
+ }
28
+ }
29
+ Object.assign(effective, parameters);
30
+ for (const spec of Object.values(effective)) annotation(spec);
31
+ return Object.freeze({name, tag, base, subTags, presentationDefaults: Object.freeze([...presentationDefaults]), dataScope, command, mixins: Object.freeze([...mixins]),
32
+ parameters: freeze(structuredClone(effective)), implementation});
33
+ }
34
+
35
+ export class ComponentCollection {
36
+ #classes = new WeakMap();
37
+ constructor({name, components}) {
38
+ this.name = name;
39
+ this.components = Object.freeze([...components]);
40
+ const names = new Set(), tags = new Set();
41
+ for (const component of components) {
42
+ if (names.has(component.name.toLowerCase()) || tags.has(component.tag)) {
43
+ throw new Error(`Duplicate component: ${component.name}`);
44
+ }
45
+ names.add(component.name.toLowerCase()); tags.add(component.tag);
46
+ }
47
+ }
48
+ /** Same JSON consumed by Python and JavaScript Builders. */
49
+ toDocument() {
50
+ return {document_format: {name: 'builder_grammar', version: '1.1'},
51
+ grammar: {name: this.name, version: null, title: this.name, description: null},
52
+ abstracts: {}, elements: Object.fromEntries(this.components.map(component => [component.name, {
53
+ doc: null, sub_tags: component.subTags, parent_tags: null, inherits_from: null, ns: null,
54
+ node_label: null, collection_key: null,
55
+ attributes: {parameters: [
56
+ ...Object.entries(component.parameters).map(([name, spec]) => ({name,
57
+ kind: 'keyword_only', role: 'attribute', annotation: annotation(spec),
58
+ has_default: true, default: spec.default ?? null})),
59
+ {name: 'attr', kind: 'var_keyword', role: 'attribute',
60
+ annotation: {kind: 'any'}, has_default: false}],
61
+ accepts_var_keyword: true, accepts_var_positional: false},
62
+ _meta: {render_tag: component.tag, gramlot_component: {parameters: structuredClone(component.parameters),
63
+ presentationDefaults: [...component.presentationDefaults], dataScope: component.dataScope, command: component.command}}
64
+ }]))};
65
+ }
66
+ /** Register once per document realm, only when the collection is activated. */
67
+ register(window) {
68
+ if (this.#classes.has(window)) return;
69
+ const classes = [];
70
+ for (const component of this.components) {
71
+ if (window.customElements.get(component.tag)) throw new Error(`Custom element already registered: ${component.tag}`);
72
+ let Base = component.base(window.HTMLElement);
73
+ for (const mixin of component.mixins) Base = mixin(Base);
74
+ const Class = component.implementation(Base);
75
+ Object.defineProperty(Class, 'gramlotComponent', {value: component});
76
+ classes.push([component.tag, Class]);
77
+ }
78
+ for (const [tag, Class] of classes) window.customElements.define(tag, Class);
79
+ this.#classes.set(window, classes);
80
+ }
81
+ }
82
+
83
+ export function defineCollection(options) { return new ComponentCollection(options); }
@@ -0,0 +1,260 @@
1
+ /** Typed text drafts. Components parse/present; ControlAdapter alone writes Data. */
2
+ import {parseDateExpression} from '../date-parser/index.js';
3
+ import {CalendarView, checkCivilDate} from './date-calendar.js';
4
+ import {SVG_NS} from '../renderer/attributes.js';
5
+ import {NativeControl} from './bases.js';
6
+ import {positionPopup} from './popup.js';
7
+
8
+ const same = (a, b, isDecimal) => a instanceof Date && b instanceof Date ? a.getTime() === b.getTime()
9
+ : isDecimal(a) && isDecimal(b) ? a.eq(b) : Object.is(a, b);
10
+ const finiteDecimal = v => !['NaN', 'Infinity', '-Infinity'].includes(v.toString());
11
+ const pad = v => String(v).padStart(2, '0');
12
+ function numberSymbols(locale) {
13
+ const parts = new Intl.NumberFormat(locale).formatToParts(-12345.6);
14
+ return {decimal: parts.find(p => p.type === 'decimal').value,
15
+ group: parts.find(p => p.type === 'group')?.value,
16
+ minus: parts.find(p => p.type === 'minusSign').value};
17
+ }
18
+
19
+ export function TypedEditor(HTMLElement) {
20
+ return class extends NativeControl(HTMLElement) {
21
+ #value = null;
22
+ #dirty = false;
23
+ #focused = false;
24
+ #policy = null;
25
+ #selection = null;
26
+ #selecting = false;
27
+ constructor() {
28
+ super();
29
+ this.control.addEventListener('focus', () => {
30
+ this.#focused = true;
31
+ if (!this.#dirty) {
32
+ const start = this.control.selectionStart, end = this.control.selectionEnd;
33
+ const all = start === 0 && end === this.control.value.length;
34
+ this.#policy = this.context(); this.display();
35
+ this.control.setSelectionRange(start, all ? this.control.value.length : end);
36
+ }
37
+ });
38
+ this.control.addEventListener('input', () => {
39
+ if (!this.#selecting) this.#selection = null;
40
+ this.#dirty = true; this.#policy ??= this.context(); this.error('');
41
+ });
42
+ this.control.addEventListener('blur', () => {
43
+ this.#focused = false;
44
+ if (this.#dirty) this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('change'));
45
+ if (!this.#dirty) { this.#policy = null; this.display(); }
46
+ });
47
+ this.control.addEventListener('keydown', event => {
48
+ if (event.isComposing || this.control.disabled || this.control.readOnly) return;
49
+ if (event.key === 'Escape') {
50
+ event.preventDefault(); this.#selection = null; this.#dirty = false; this.#policy = null; this.error(''); this.display();
51
+ } else if (event.key === 'Enter') {
52
+ event.preventDefault(); this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('change'));
53
+ }
54
+ });
55
+ }
56
+ createControl() {
57
+ const input = this.ownerDocument.createElement('input'); input.type = 'text'; return input;
58
+ }
59
+ context() {
60
+ return {locale: this.parameters.locale ?? this.pageContext.locale,
61
+ timeZone: this.pageContext.timeZone, pattern: this.parameters.format,
62
+ dtype: this.parameters.dtype};
63
+ }
64
+ readControlValue() { return this.#value; }
65
+ readDraftValue() {
66
+ return !this.#dirty ? this.#value : this.control.value.trim() === '' ? null
67
+ : this.parse(this.control.value, this.#policy ?? this.context());
68
+ }
69
+ sameControlValue(a, b) { return same(a, b, this.pageContext.isDecimal); }
70
+ writeControlValue(value) {
71
+ this.checkValue(value);
72
+ if (this.sameControlValue(value, this.#value)) { if (!this.#dirty && !this.#focused) this.display(); return; }
73
+ this.#value = value; this.#selection = null; this.#dirty = false; this.#policy = null; this.error(''); this.display();
74
+ }
75
+ selectControlValue(value) {
76
+ this.checkValue(value);
77
+ this.control.value = value === null ? '' : this.editText(value, this.context());
78
+ this.#selection = {value}; this.#selecting = true;
79
+ try {
80
+ // Carry the selected typed value through the same live/commit adapter events.
81
+ // Do not parse a localized short-year caption back into a different century.
82
+ for (const type of ['input', 'change']) this.control.dispatchEvent(new this.ownerDocument.defaultView.Event(type, {bubbles:true}));
83
+ } finally { this.#selecting = false; }
84
+ }
85
+ acceptControlValue() {
86
+ if (!this.#dirty) return {ok: false};
87
+ try {
88
+ const value = this.#selection ? this.#selection.value : this.readDraftValue();
89
+ this.checkValue(value);
90
+ return this.validateCandidate(value, accepted => {
91
+ this.checkValue(accepted);
92
+ this.#value = accepted; this.#selection = null; this.#dirty = false;
93
+ // Preserve accepted spelling unless validation normalized the candidate.
94
+ if (!this.#focused || !this.sameControlValue(value, accepted)) { this.#policy = null; this.display(); }
95
+ });
96
+ } catch (error) { this.error(error.message); return {ok: false}; }
97
+ }
98
+ display() {
99
+ if (!this.pageContext || !this.parameters) return;
100
+ const text = this.#value == null ? '' : this.#focused
101
+ ? this.editText(this.#value, this.#policy ?? this.context())
102
+ : this.pageContext.format(this.#value, this.context());
103
+ if (this.control.value !== text) this.control.value = text;
104
+ }
105
+ projectAttributes(attrs, adapt) {
106
+ const rest = super.projectAttributes(attrs, adapt);
107
+ if (!this.#dirty && !this.#focused) this.display();
108
+ return rest;
109
+ }
110
+ };
111
+ }
112
+ TypedEditor.parameters = {...NativeControl.parameters,
113
+ placeholder: {dtype: 'T', qualification: 'intl_str', default: '', target: 'control'},
114
+ locale: {dtype: 'T', nullable: true, binding: 'read'},
115
+ format: {dtype: 'T', nullable: true, binding: 'read'}};
116
+
117
+ export const numberEditor = Base => class extends Base {
118
+ createControl() { const control = super.createControl(); control.inputMode = 'decimal'; return control; }
119
+ checkValue(value) {
120
+ if (value === null) return;
121
+ if (!(typeof value === 'number' && Number.isFinite(value)) && !(this.pageContext.isDecimal(value) && finiteDecimal(value))) {
122
+ throw new TypeError('Expected a finite number or Decimal');
123
+ }
124
+ }
125
+ context() { return {...super.context(), pattern: this.parameters.format ?? '0.####################'}; }
126
+ editText(value, context) { return String(value).replace('.', numberSymbols(context.locale).decimal); }
127
+ parse(text, context) {
128
+ const {decimal, group, minus} = numberSymbols(context.locale);
129
+ let draft = text.trim().replaceAll(minus, '-');
130
+ if (group && draft.includes(group)) throw new Error('Enter the number without grouping separators.');
131
+ draft = draft.replace(decimal, '.');
132
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(draft)) throw new Error('Enter a complete number.');
133
+ const exact = context.dtype === 'N' || this.pageContext.isDecimal(this.readControlValue());
134
+ if (exact && this.pageContext.getDecimalLibrary() === 'number') throw new Error('A Decimal backend is required.');
135
+ const value = exact ? this.pageContext.createDecimal(draft) : Number(draft);
136
+ this.checkValue(value);
137
+ if (context.dtype === 'L' && !Number.isSafeInteger(value)) throw new Error('Enter a safe integer.');
138
+ for (const [key, sign] of [['min', -1], ['max', 1]]) {
139
+ const bound = this.parameters[key];
140
+ if (bound != null && (exact ? value.cmp(bound) : Math.sign(value - bound)) === sign) throw new Error(`${key}: ${bound}`);
141
+ }
142
+ return value;
143
+ }
144
+ };
145
+
146
+ export const dateEditor = Base => class extends Base {
147
+ #opened = false;
148
+ #cleanup;
149
+ constructor() {
150
+ super();
151
+ const doc = this.ownerDocument;
152
+ const style = doc.createElement('style');
153
+ style.textContent = `.date-entry{position:relative;max-width:100%}
154
+ .date-entry #control{display:block;min-width:0;width:100%}
155
+ .date-entry:has(.calendar-toggle:not([hidden])) #control{padding-right:calc(var(--gramlot-touch-target,1.6em) + .4em)}
156
+ .calendar-toggle{position:absolute;right:0;top:0;bottom:0;width:var(--gramlot-touch-target,1.6em);min-width:0;min-height:0;font:inherit;font-size:var(--gramlot-field-font-size,1em);line-height:inherit;padding:0;border:0;border-radius:var(--gramlot-radius-sm,4px);background:transparent;color:inherit;cursor:pointer}
157
+ .calendar-toggle:disabled{cursor:default;opacity:.6}
158
+ .calendar-toggle svg{display:block;width:1.1em;height:1.1em;margin:auto;pointer-events:none}
159
+ .calendar-popup{position:fixed;inset:auto;margin:0;padding:.5em;max-width:var(--gramlot-popup-available-width,100vw);max-height:var(--gramlot-popup-available-height,100vh);overflow:auto;
160
+ border:1px solid var(--gramlot-border-control,#aab4c4);border-radius:var(--gramlot-radius,5px);background:var(--gramlot-surface,Canvas);color:var(--gramlot-ink,CanvasText);box-shadow:var(--gramlot-shadow,0 3px 12px #0003);font:inherit}`;
161
+ this.shadowRoot.append(style);
162
+ // A tool button is a sibling of the input, not nested inside its label.
163
+ const entry = doc.createElement('div'); entry.className = 'date-entry';
164
+ this.control.parentElement.replaceWith(entry); entry.append(this.control);
165
+ this.calendarButton = doc.createElement('button'); this.calendarButton.type = 'button';
166
+ this.calendarButton.className = 'calendar-toggle';
167
+ const icon = doc.createElementNS(SVG_NS, 'svg');
168
+ for (const [name, value] of Object.entries({viewBox:'0 0 24 24', fill:'none', stroke:'currentColor',
169
+ 'stroke-width':'1.8', 'stroke-linecap':'round', 'stroke-linejoin':'round',
170
+ 'aria-hidden':'true', focusable:'false'})) icon.setAttribute(name, value);
171
+ const outline = doc.createElementNS(SVG_NS, 'path');
172
+ outline.setAttribute('d', 'M5 5h14a2 2 0 0 1 2 2v13a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2Z M7 2v6 M17 2v6 M3 11h18 M7 15h2 M15 15h2 M7 18h2 M15 18h2');
173
+ icon.append(outline); this.calendarButton.append(icon);
174
+ this.calendarButton.setAttribute('aria-label','Open calendar'); this.calendarButton.setAttribute('aria-haspopup','dialog');
175
+ this.calendarButton.setAttribute('aria-expanded','false'); this.calendarButton.setAttribute('aria-controls','calendar-popup');
176
+ entry.append(this.calendarButton);
177
+ this.calendarPopup = doc.createElement('div'); this.calendarPopup.className = 'calendar-popup';
178
+ this.calendarPopup.id = 'calendar-popup'; this.calendarPopup.setAttribute('popover','auto');
179
+ this.calendarPopup.setAttribute('role','dialog'); this.calendarPopup.setAttribute('aria-label','Choose date');
180
+ this.shadowRoot.append(this.calendarPopup);
181
+ const view = doc.createElement('div'); this.calendarPopup.append(view);
182
+ this.calendarView = new CalendarView(view, value => {
183
+ if (this.control.disabled || this.control.readOnly || !this.pageContext.isActive()) return;
184
+ this.closeCalendar(); this.control.focus();
185
+ this.selectControlValue(value);
186
+ });
187
+ this.calendarButton.addEventListener('click', () => this.#opened ? this.closeCalendar() : this.openCalendar());
188
+ this.control.addEventListener('keydown', event => {
189
+ if (event.altKey && event.key === 'ArrowDown') {event.preventDefault(); this.openCalendar();}
190
+ });
191
+ this.calendarPopup.addEventListener('keydown', event => {
192
+ if (event.key === 'Escape') {event.preventDefault(); event.stopPropagation(); this.closeCalendar(); this.control.focus();}
193
+ });
194
+ this.calendarPopup.addEventListener('toggle', event => {
195
+ if (event.newState === 'closed') {this.#opened = false; this.cleanupCalendar();}
196
+ });
197
+ }
198
+ openCalendar() {
199
+ if (!this.parameters.calendar || this.control.disabled || this.control.readOnly || !this.pageContext.isActive()) return;
200
+ let value = this.readControlValue();
201
+ try { value = this.readDraftValue(); } catch { /* Invalid draft: open on the committed date. */ }
202
+ this.calendarView.configure({value, locale:this.context().locale, workdate:this.parameters.workdate});
203
+ this.calendarPopup.showPopover(); this.#opened = true; this.calendarButton.setAttribute('aria-expanded','true');
204
+ const win = this.ownerDocument.defaultView;
205
+ const position = () => positionPopup(this.calendarPopup, this.control);
206
+ this.#cleanup?.(); position();
207
+ win.addEventListener('resize', position); win.addEventListener('scroll', position, true);
208
+ this.#cleanup = () => {win.removeEventListener('resize', position); win.removeEventListener('scroll', position, true);};
209
+ this.calendarView.focusDay();
210
+ }
211
+ cleanupCalendar() {
212
+ this.#cleanup?.(); this.#cleanup = null; this.calendarButton.setAttribute('aria-expanded','false');
213
+ }
214
+ closeCalendar() {
215
+ if (this.#opened) this.calendarPopup.hidePopover();
216
+ this.#opened = false; this.cleanupCalendar();
217
+ }
218
+ projectAttributes(attrs, adapt) {
219
+ const rest = super.projectAttributes(attrs, adapt);
220
+ this.calendarButton.hidden = !this.parameters.calendar;
221
+ this.calendarButton.disabled = this.control.disabled || this.control.readOnly;
222
+ if (!this.parameters.calendar || this.calendarButton.disabled) this.closeCalendar();
223
+ else if (this.#opened) this.calendarView.configure({value:this.readControlValue(),locale:this.context().locale,workdate:this.parameters.workdate});
224
+ return rest;
225
+ }
226
+ writeControlValue(value) {
227
+ super.writeControlValue(value);
228
+ if (this.#opened) this.calendarView.configure({value,locale:this.context().locale,workdate:this.parameters.workdate});
229
+ }
230
+ releaseControl() { this.closeCalendar(); super.releaseControl(); }
231
+ context() { return {...super.context(), dtype: 'D', pattern: this.parameters.format ?? 'short'}; }
232
+ checkValue(value) { checkCivilDate(value); }
233
+ editText(value, context) { return this.pageContext.format(value, {...context, pattern: 'short'}); }
234
+ parse(text, context) {
235
+ const now = new Date();
236
+ const workdate = this.parameters.workdate ?? `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`;
237
+ const options = {locale: context.locale, workdate};
238
+ const result = parseDateExpression(text, options);
239
+ if (!result.ok) throw new Error(result.error.message);
240
+ if (result.kind !== 'date') throw new Error('Enter one complete date, not a period.');
241
+ const [y, m, d] = result.date.split('-').map(Number);
242
+ const value = new Date(0); value.setUTCFullYear(y, m - 1, d); return value;
243
+ }
244
+ };
245
+
246
+ export const timeEditor = Base => class extends Base {
247
+ context() { return {...super.context(), dtype: 'H', pattern: this.parameters.format ?? 'short'}; }
248
+ checkValue(value) {
249
+ if (value !== null && (!(value instanceof Date) || !Number.isFinite(value.getTime()) || value.getUTCFullYear() !== 1970 || value.getUTCMonth() !== 0 || value.getUTCDate() !== 1)) throw new TypeError('Expected a civil time on the TYTX epoch date');
250
+ }
251
+ editText(value) {
252
+ return `${pad(value.getUTCHours())}:${pad(value.getUTCMinutes())}:${pad(value.getUTCSeconds())}` +
253
+ (value.getUTCMilliseconds() ? `.${String(value.getUTCMilliseconds()).padStart(3, '0')}` : '');
254
+ }
255
+ parse(text) {
256
+ const match = /^(\d{1,2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/.exec(text.trim());
257
+ if (!match || +match[1] > 23 || +match[2] > 59 || +(match[3] ?? 0) > 59) throw new Error('Enter HH:mm or HH:mm:ss, using the 24-hour clock.');
258
+ return new Date(Date.UTC(1970, 0, 1, +match[1], +match[2], +(match[3] ?? 0), +(match[4] ?? '').padEnd(3, '0')));
259
+ }
260
+ };