@gramlot/gramlot 0.3.10 → 0.3.15

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 (91) hide show
  1. package/dist/components/editors/__init__.py +13 -0
  2. package/dist/components/{editors.js → editors/assets/collection.js} +131 -246
  3. package/dist/components/editors/assets/index.js +2 -0
  4. package/dist/components/editors/commands.json +7 -0
  5. package/dist/components/editors/grammar.json +7045 -0
  6. package/dist/components/inputs/__init__.py +13 -0
  7. package/dist/components/{inputs.js → inputs/assets/collection.js} +287 -198
  8. package/dist/components/inputs/assets/index.js +2 -0
  9. package/dist/components/inputs/commands.json +7 -0
  10. package/dist/components/inputs/grammar.json +42881 -0
  11. package/dist/components/layout/__init__.py +13 -0
  12. package/dist/components/layout/assets/collection.js +25737 -0
  13. package/dist/components/layout/assets/index.js +2 -0
  14. package/dist/components/layout/commands.json +7 -0
  15. package/dist/components/layout/grammar.json +1798 -0
  16. package/dist/components/tree/__init__.py +13 -0
  17. package/dist/components/{tree.js → tree/assets/collection.js} +62 -175
  18. package/dist/components/tree/assets/index.js +2 -0
  19. package/dist/components/tree/commands.json +7 -0
  20. package/dist/components/tree/grammar.json +339 -0
  21. package/dist/components/typst/__init__.py +13 -0
  22. package/dist/components/typst/assets/collection.js +4 -0
  23. package/dist/components/typst/assets/index.js +2 -0
  24. package/dist/components/typst/commands.json +7 -0
  25. package/dist/components/typst/grammar.json +81 -0
  26. package/dist/gramlot.js +2491 -902
  27. package/dist/gramlot.min.js +109 -28
  28. package/dist/runtime-notices.json +0 -196
  29. package/package.json +1 -1
  30. package/src/binding/ask-dialog.js +1 -1
  31. package/src/binding/installation.js +5 -6
  32. package/src/binding/runtime.js +4 -2
  33. package/src/bootstrap.d.ts +1 -1
  34. package/src/bootstrap.js +52 -30
  35. package/src/builder/binding.json +25 -0
  36. package/src/builder/gramlot-builder.js +16 -3
  37. package/src/builder/source.js +33 -1
  38. package/src/collection-artifact.d.ts +11 -0
  39. package/src/collection-artifact.js +57 -0
  40. package/src/commands.d.ts +9 -0
  41. package/src/commands.js +36 -0
  42. package/src/components/bases.js +1 -1
  43. package/src/components/border-container.js +26 -1
  44. package/src/components/buttons.js +84 -161
  45. package/src/components/choice-editor.js +31 -10
  46. package/src/components/database-choices.js +110 -0
  47. package/src/components/inputs.js +15 -2
  48. package/src/components/layout.js +5 -3
  49. package/src/components/menus.js +346 -0
  50. package/src/components/popup.js +15 -2
  51. package/src/components/registry.js +18 -3
  52. package/src/components/toolbar-overflow.js +181 -0
  53. package/src/components/tree.js +14 -4
  54. package/src/components/windows.js +284 -0
  55. package/src/gramlot.d.ts +2 -0
  56. package/src/gramlot.js +4 -2
  57. package/src/handlers/rpc-handler.d.ts +6 -1
  58. package/src/handlers/rpc-handler.js +7 -2
  59. package/src/handlers/source-handler.d.ts +2 -1
  60. package/src/handlers/source-handler.js +10 -1
  61. package/src/index-page-styles.js +1 -1
  62. package/src/index-theme.js +1 -1
  63. package/src/index.d.ts +5 -0
  64. package/src/index.js +5 -0
  65. package/src/renderer/gramlot-html-renderer.js +1 -0
  66. package/src/renderer/gramlot-renderer.js +13 -3
  67. package/src/server/gramlot-file-server.d.ts +2 -0
  68. package/src/server/gramlot-file-server.js +45 -1
  69. package/src/server/gramlot-server.d.ts +20 -2
  70. package/src/server/gramlot-server.js +86 -6
  71. package/src/server/page-base.js +1 -0
  72. package/src/server/page.d.ts +3 -0
  73. package/src/view/button.js +47 -3
  74. package/src/view/controls.js +8 -0
  75. package/src/view/html.js +1 -0
  76. package/src/view/menu-command.js +45 -0
  77. package/src/view/menu.js +87 -0
  78. package/themes/gramlot-compact/README.md +19 -0
  79. package/themes/gramlot-compact/theme.css +138 -45
  80. package/themes/joanna/README.md +19 -0
  81. package/themes/joanna/theme.css +134 -78
  82. package/themes/mela/theme.css +184 -0
  83. package/themes/mimi/README.md +19 -0
  84. package/themes/mimi/theme.css +133 -77
  85. package/themes/palettes/README.md +3 -0
  86. package/themes/palettes/compact.css +86 -0
  87. package/themes/palettes/joanna.css +86 -0
  88. package/themes/palettes/mimi.css +86 -0
  89. package/tools/gramlot-tools-inspector.js +3 -3
  90. package/dist/components/layout.js +0 -3385
  91. package/dist/components/typst.js +0 -4
@@ -2,7 +2,7 @@
2
2
  import {defineComponent, defineCollection} from './registry.js';
3
3
  import {controlElement} from './bases.js';
4
4
  import {projectParameters} from './parameters.js';
5
- import {positionPopup} from './popup.js';
5
+ import {MenuContainer, menuLine} from './menus.js';
6
6
 
7
7
  function Command(HTMLElement) {
8
8
  return class extends controlElement(HTMLElement) {
@@ -29,7 +29,7 @@ function Command(HTMLElement) {
29
29
  :host(.button--quiet) button{background:transparent;color:var(--gramlot-action,CanvasText);border-color:transparent}
30
30
  :host(.button--quiet) button:hover:not(:disabled){background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,CanvasText);border-color:transparent}
31
31
  button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:2px}
32
- button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none}
32
+ button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none} .icon img{display:block;width:100%;height:100%;object-fit:contain} .icon:has(img){width:1em;height:1em}
33
33
  .led{display:inline-block;width:.6em;height:.6em;border-radius:50%;background:var(--gramlot-button-led-off,#888)}
34
34
  [aria-pressed=true] .led{background:var(--gramlot-button-led-on,#2b9a46)}
35
35
  .arrow{border-start-start-radius:0;border-end-start-radius:0;border-inline-start:0}
@@ -38,7 +38,7 @@ function Command(HTMLElement) {
38
38
  max-width:var(--gramlot-popup-available-width);max-height:var(--gramlot-popup-available-height);
39
39
  border:1px solid var(--gramlot-border-control,#888);border-radius:var(--gramlot-radius-sm,4px);
40
40
  color:var(--gramlot-ink,CanvasText);background:var(--gramlot-field-background,Canvas);box-shadow:0 3px 12px #0003}
41
- :host([role=menuitem]){display:block} :host([role=menuitem]) button{width:100%;justify-content:start;border:0;background:transparent}
41
+ :host(:is([role=menuitem],[role=menuitemcheckbox])){display:block} :host(:is([role=menuitem],[role=menuitemcheckbox])) button{width:100%;justify-content:start;border:0;background:transparent}
42
42
  :host([role=separator]){display:block;border-top:1px solid var(--gramlot-border-control,#888);margin:.25em}
43
43
  :host([role=separator]) button{display:none}`;
44
44
  this.shadowRoot.append(style);
@@ -49,11 +49,23 @@ function Command(HTMLElement) {
49
49
  const rest = super.projectAttributes(attrs, adapt);
50
50
  this.control.disabled = Boolean(this.parameters.disabled);
51
51
  this.control.readOnly = Boolean(this.parameters.readonly);
52
- this.icon.textContent = this.parameters.icon ?? '';
52
+ this.renderIcon(this.parameters.icon, this.parameters.iconSrc);
53
53
  if (attrs['aria-label'] != null) this.control.setAttribute('aria-label', attrs['aria-label']);
54
54
  else this.control.removeAttribute('aria-label');
55
55
  return rest;
56
56
  }
57
+ renderIcon(icon, iconSrc) {
58
+ if (!iconSrc) { this.icon.textContent = icon ?? ''; return; }
59
+ let image = this.icon.firstElementChild;
60
+ if (!image) {
61
+ image = this.ownerDocument.createElement('img');
62
+ image.alt = ''; image.draggable = false;
63
+ this.icon.replaceChildren(image);
64
+ }
65
+ if (image.getAttribute('src') !== iconSrc) image.setAttribute('src', iconSrc);
66
+ }
67
+ get entryIcon() { return this.parameters.icon; }
68
+ get entryIconSrc() { return this.parameters.iconSrc; }
57
69
  attachCommand() {}
58
70
  releaseCommand() {}
59
71
  commandTarget() { return this; }
@@ -62,7 +74,8 @@ function Command(HTMLElement) {
62
74
  }
63
75
  Command.parameters = {
64
76
  disabled: {dtype: 'B', default: false, binding: 'read'},
65
- icon: {dtype: 'T', default: '', binding: 'read'}
77
+ icon: {dtype: 'T', default: '', binding: 'read'},
78
+ iconSrc: {dtype: 'T', default: '', binding: 'read'}
66
79
  };
67
80
  export const Button = defineComponent({name: 'button', tag: 'gramlot-button', base: Command,
68
81
  command: true, subTags: '*', implementation: Base => class extends Base {}});
@@ -92,166 +105,76 @@ export const ToggleButton = defineComponent({name: 'toggleButton', tag: 'gramlot
92
105
  }
93
106
  }
94
107
  });
95
- function MenuContainer(HTMLElement) {
96
- return class extends HTMLElement {
97
- constructor() {
98
- super();
99
- this.attachShadow({mode: 'open'}).append(this.ownerDocument.createElement('slot'));
100
- }
101
- connectedCallback() { this.slot = 'menu'; this.setAttribute('role', 'menu'); }
102
- projectAttributes(attrs) { return projectParameters(this, attrs); }
103
- };
104
- }
105
- export const Menu = defineComponent({name: 'menu', tag: 'gramlot-menu', base: MenuContainer,
106
- subTags: 'menuline', implementation: Base => class extends Base {}});
107
- export const MenuLine = defineComponent({name: 'menuline', tag: 'gramlot-menu-line', base: Command,
108
- command: true, subTags: '*', parameters: {code: {dtype: 'T', nullable: true}},
109
- implementation: Base => class extends Base {
110
- attachCommand() {
111
- const separator = this.textContent.trim() === '-';
112
- if (!separator && !this.parameters.code) throw new TypeError('menuline requires a stable code');
113
- this.setAttribute('role', separator ? 'separator' : 'menuitem');
114
- this.control.tabIndex = -1;
115
- this.disabled ||= separator;
116
- }
117
- get disabled() {
118
- return super.disabled || Boolean(this.closest('gramlot-drop-down-button')?.parameters.disabled);
119
- }
120
- set disabled(value) { super.disabled = value; }
121
- prepareCommand(event) {
122
- if (!super.prepareCommand(event)) return false;
123
- this.closest('gramlot-drop-down-button').selectCommand(this, event.shiftKey);
124
- return true;
125
- }
108
+
109
+ export const Menu = defineComponent({name:'menu',tag:'gramlot-menu',base:MenuContainer,
110
+ subTags:'menuline,spacer,contentPane',parameters:{
111
+ presentation:{dtype:'T',default:'popup',enum:['popup','bar']},
112
+ orientation:{dtype:'T',default:'horizontal',enum:['horizontal','vertical']},
113
+ modifiers:{dtype:'T',nullable:true},
114
+ labelPosition:{dtype:'T',binding:'read',default:'beside',enum:['beside','below','tooltip']},iconSize:{dtype:'R',binding:'read',default:24},
115
+ resolver:{dtype:'T',nullable:true},cacheTime:{dtype:'R',default:-1},sync:{dtype:'B',default:false}
116
+ },implementation:Base=>class extends Base {}});
117
+ export const MenuLine = defineComponent({name:'menuline',tag:'gramlot-menu-line',base:Command,
118
+ command:true,subTags:'*',parameters:{
119
+ command:{dtype:'T',nullable:true},caption:{dtype:'T',nullable:true},code:{dtype:'T',nullable:true},
120
+ checked:{dtype:'B',nullable:true,binding:'read'},tooltip:{dtype:'T',nullable:true},
121
+ labelPosition:{dtype:'T',binding:'read',nullable:true,enum:['beside','below','tooltip']},iconSize:{dtype:'R',binding:'read',nullable:true},
122
+ group:{dtype:'B',default:false},priority:{dtype:'R',default:0},overflowable:{dtype:'B',default:true},
123
+ parameters:{annotation:{kind:'type',module:'builtins',name:'dict'},nullable:true},favorite:{dtype:'B',default:false}
124
+ },implementation:menuLine});
125
+ export const Spacer = defineComponent({name:'spacer',tag:'gramlot-spacer',base:HTMLElement=>class extends HTMLElement {
126
+ projectAttributes(attrs) {
127
+ const rest=projectParameters(this,attrs),{size,flex}=this.parameters;
128
+ if (size!=null && flex!=null) throw new TypeError('spacer accepts size or flex, not both');
129
+ if (size!=null && (!Number.isFinite(size)||size<0) || flex!=null && (!Number.isFinite(flex)||flex<=0)) throw new TypeError('Invalid spacer size/flex');
130
+ this.style.flex=flex!=null?`${flex} 1 0px`:`0 0 ${size??0}px`;
131
+ this.setAttribute('aria-hidden','true');return rest;
126
132
  }
127
- });
128
- export const DropDownButton = defineComponent({name: 'dropDownButton', tag: 'gramlot-drop-down-button', base: Command,
129
- command: true, subTags: '*', parameters: {persist: {dtype: 'B', default: false}},
130
- implementation: Base => class extends Base {
131
- #selected = null;
132
- #observer = null;
133
- #viewport = null;
134
- #storageKey = null;
135
- #popup;
136
- #arrow;
137
- #chosenCaption;
133
+ },parameters:{size:{dtype:'R',nullable:true},flex:{dtype:'R',nullable:true}},implementation:Base=>class extends Base {}});
134
+ export const DropDownButton = defineComponent({name:'dropDownButton',tag:'gramlot-drop-down-button',base:Command,
135
+ command:true,subTags:'*',parameters:{persist:{dtype:'B',default:false}},
136
+ implementation:Base=>class extends Base {
137
+ #selected=null; #observer; #storageKey=null; #arrow; #chosenCaption;
138
138
  constructor() {
139
- super();
140
- const doc = this.ownerDocument;
139
+ super();const doc=this.ownerDocument;
141
140
  this.control.classList.add('split');
142
- this.#chosenCaption = doc.createElement('span');
143
- this.#chosenCaption.hidden = true;
144
- this.control.append(this.#chosenCaption);
145
- this.#arrow = doc.createElement('button');
146
- this.#arrow.type = 'button'; this.#arrow.className = 'arrow'; this.#arrow.textContent = '▾';
147
- this.#arrow.setAttribute('aria-label', 'Open menu');
148
- this.#arrow.setAttribute('aria-haspopup', 'menu');
149
- this.#arrow.setAttribute('aria-expanded', 'false');
141
+ this.#chosenCaption=doc.createElement('span');this.#chosenCaption.hidden=true;this.control.append(this.#chosenCaption);
142
+ this.#arrow=doc.createElement('button');this.#arrow.type='button';this.#arrow.className='arrow';this.#arrow.textContent='▾';
143
+ this.#arrow.setAttribute('aria-label','Open menu');this.#arrow.setAttribute('aria-haspopup','menu');this.#arrow.setAttribute('aria-expanded','false');
150
144
  this.controlBox.append(this.#arrow);
151
- this.#popup = doc.createElement('div');
152
- this.#popup.className = 'popup'; this.#popup.id = 'menu'; this.#popup.setAttribute('popover', 'auto');
153
- this.#arrow.setAttribute('aria-controls', 'menu');
154
- const slot = doc.createElement('slot'); slot.name = 'menu';
155
- this.#popup.append(slot); this.shadowRoot.append(this.#popup);
156
- this.#arrow.addEventListener('click', event => {
157
- event.stopPropagation();
158
- if (this.#popup.matches(':popover-open')) this.closeMenu(); else this.openMenu();
159
- });
160
- this.#arrow.addEventListener('keydown', event => {
161
- if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
162
- event.preventDefault(); this.openMenu(event.key === 'ArrowUp');
163
- }
164
- });
165
- this.addEventListener('keydown', event => {
166
- if (!this.#popup.matches(':popover-open')) return;
167
- const items = this.menuItems.filter(item => !item.disabled);
168
- const index = items.indexOf(event.composedPath().find(item => items.includes(item)));
169
- let next;
170
- if (event.key === 'ArrowDown') next = (index + 1) % items.length;
171
- if (event.key === 'ArrowUp') next = (index - 1 + items.length) % items.length;
172
- if (event.key === 'Home') next = 0;
173
- if (event.key === 'End') next = items.length - 1;
174
- if (next !== undefined) { event.preventDefault(); items[next]?.focus(); }
175
- if (event.key === 'Escape' || event.key === 'Tab') {
176
- if (event.key === 'Escape') event.preventDefault();
177
- this.closeMenu();
178
- }
179
- });
180
- this.#popup.addEventListener('toggle', () => {
181
- const open = this.#popup.matches(':popover-open');
182
- this.#arrow.setAttribute('aria-expanded', String(open));
183
- if (!open) { this.#viewport?.abort(); this.#viewport = null; }
184
- });
185
- }
186
- get menuItems() { return [...this.querySelectorAll(':scope > gramlot-menu > gramlot-menu-line')]; }
187
- projectAttributes(attrs, adapt) {
188
- const rest = super.projectAttributes(attrs, adapt);
189
- this.#arrow.disabled = this.disabled;
190
- if (this.disabled && this.#popup.matches(':popover-open')) this.closeMenu();
191
- this.#refreshCaption();
192
- return rest;
193
- }
194
- attachCommand() {
195
- if (this.parameters.persist) {
196
- if (!this.id) throw new TypeError('dropDownButton persist requires an explicit id');
197
- this.#storageKey = `gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;
198
- try { this.#selected = this.ownerDocument.defaultView.localStorage.getItem(this.#storageKey); } catch { /* Storage may be disabled. */ }
145
+ const slot=doc.createElement('slot');slot.name='menu';this.shadowRoot.append(slot);
146
+ this.#arrow.addEventListener('click',event=>{event.stopPropagation();if(this.menu.opened)this.closeMenu();else this.openMenu();});
147
+ this.#arrow.addEventListener('keydown',event=>{if(['ArrowDown','ArrowUp'].includes(event.key)){event.preventDefault();this.openMenu(event.key==='ArrowUp');}});
148
+ }
149
+ get menu(){return [...this.children].find(child=>child.localName==='gramlot-menu');}
150
+ get menuItems(){return this.menu?.items??[];}
151
+ projectAttributes(attrs,adapt){const rest=super.projectAttributes(attrs,adapt);this.#arrow.disabled=this.disabled;
152
+ if(this.disabled)this.menu?.close(false);this.#refreshCaption();return rest;}
153
+ attachCommand(){
154
+ if(this.parameters.persist){
155
+ if(!this.id)throw new TypeError('dropDownButton persist requires an explicit id');
156
+ this.#storageKey=`gramlot:command:${this.ownerDocument.location.pathname}${this.ownerDocument.location.search}:${this.id}`;
157
+ try{this.#selected=this.ownerDocument.defaultView.localStorage.getItem(this.#storageKey);}catch{/* storage may be disabled */}
199
158
  }
200
- this.#refreshCaption();
201
- this.#observer = new this.ownerDocument.defaultView.MutationObserver(() => this.#refreshCaption());
202
- this.#observer.observe(this, {childList: true, subtree: true, characterData: true});
203
- }
204
- releaseCommand() {
205
- this.#observer?.disconnect(); this.#observer = null;
206
- this.#viewport?.abort(); this.#viewport = null;
207
- if (this.#popup.matches(':popover-open')) this.#popup.hidePopover();
208
- }
209
- commandTarget(event) {
210
- if (event?.composedPath().includes(this.#popup)) return null;
211
- return this.menuItems.find(item => item.parameters.code === this.#selected) ?? this;
212
- }
213
- selectCommand(item, remember) {
214
- if (remember) {
215
- this.#selected = item.parameters.code;
216
- if (this.#storageKey) {
217
- try { this.ownerDocument.defaultView.localStorage.setItem(this.#storageKey, this.#selected); } catch { /* Keep the in-memory choice. */ }
218
- }
219
- this.#refreshCaption();
220
- }
221
- this.closeMenu();
222
- }
223
- #refreshCaption() {
224
- const codes = this.menuItems.filter(item => item.parameters.code).map(item => item.parameters.code);
225
- if (new Set(codes).size !== codes.length) throw new TypeError('Dropdown menu codes must be unique');
226
- const target = this.commandTarget();
227
- const selected = target !== this;
228
- this.caption.hidden = selected;
229
- this.#chosenCaption.hidden = !selected;
230
- this.#chosenCaption.textContent = selected ? target.textContent : '';
231
- this.icon.textContent = selected ? target.parameters.icon : this.parameters.icon;
232
- }
233
- openMenu(last = false) {
234
- if (this.disabled) return;
235
- const items = this.menuItems.filter(item => !item.disabled);
236
- if (!items.length) return;
237
- this.#popup.showPopover();
238
- this.#arrow.setAttribute('aria-expanded', 'true');
239
- const place = () => positionPopup(this.#popup, this.controlBox);
240
- place();
241
- this.#viewport?.abort();
242
- this.#viewport = new this.ownerDocument.defaultView.AbortController();
243
- const options = {signal: this.#viewport.signal, capture: true};
244
- this.ownerDocument.defaultView.addEventListener('resize', place, options);
245
- this.ownerDocument.addEventListener('scroll', place, options);
246
- items[last ? items.length - 1 : 0].focus();
247
- }
248
- closeMenu() {
249
- if (!this.#popup.matches(':popover-open')) return;
250
- this.#popup.hidePopover();
251
- this.#arrow.setAttribute('aria-expanded', 'false');
252
- this.#viewport?.abort(); this.#viewport = null;
253
- this.#arrow.focus();
254
- }
159
+ this.#refreshCaption();this.#observer=new this.ownerDocument.defaultView.MutationObserver(()=>this.#refreshCaption());
160
+ this.#observer.observe(this,{childList:true,subtree:true,characterData:true});
161
+ }
162
+ releaseCommand(){this.#observer?.disconnect();this.menu?.close(false);}
163
+ commandTarget(event){if(event?.composedPath().includes(this.menu))return null;
164
+ return this.menuItems.find(item=>item.occurrence===this.#selected)??this;}
165
+ selectCommand(item,remember){if(remember){this.#selected=item.occurrence;
166
+ if(this.#storageKey)try{this.ownerDocument.defaultView.localStorage.setItem(this.#storageKey,this.#selected);}catch{/* keep in-memory choice */}
167
+ this.#refreshCaption();}this.closeMenu();}
168
+ #refreshCaption(){
169
+ const codes=this.menuItems.map(item=>item.occurrence).filter(Boolean);
170
+ if(new Set(codes).size!==codes.length)throw new TypeError('Dropdown menu codes must be unique');
171
+ const target=this.commandTarget(),selected=target!==this;
172
+ this.caption.hidden=selected;this.#chosenCaption.hidden=!selected;
173
+ this.#chosenCaption.textContent=selected?target.entryCaption:'';
174
+ this.renderIcon(target.entryIcon, target.entryIconSrc);
175
+ }
176
+ openMenu(last=false){if(!this.disabled)this.menu?.open(this.#arrow,last);}
177
+ closeMenu(){this.menu?.close();}
255
178
  }
256
179
  });
257
- export default defineCollection({name: 'buttons', components: [Button, ToggleButton, DropDownButton, Menu, MenuLine]});
180
+ export default defineCollection({name:'buttons',components:[Button,ToggleButton,DropDownButton,Menu,MenuLine,Spacer]});
@@ -1,7 +1,7 @@
1
- import {Bag} from '@gramlot/gramlot';
2
1
  import {NativeControl} from './bases.js';
3
2
  import {parseChoices} from './choices.js';
4
3
  import {positionPopup} from './popup.js';
4
+ import {Bag} from '@gramlot/gramlot';
5
5
 
6
6
  /** Shared suggestions: constrained controls commit codes; comboBox commits text. */
7
7
  export function ChoiceEditor(HTMLElement) {
@@ -16,6 +16,8 @@ export function ChoiceEditor(HTMLElement) {
16
16
  #source;
17
17
  #separator;
18
18
  #cleanup;
19
+ #requestController;
20
+ #searchTimer;
19
21
  constructor() {
20
22
  super();
21
23
  const doc = this.ownerDocument;
@@ -26,6 +28,7 @@ export function ChoiceEditor(HTMLElement) {
26
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;
27
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)}
28
30
  .choices[hidden]{display:none} .choice{min-height:var(--gramlot-touch-target,0px);display:flex;align-items:center;padding:.25em .5em;cursor:pointer}
31
+ .choice-detail{margin-inline-start:var(--gramlot-space-3,.75rem);color:var(--gramlot-text-secondary,GrayText)}
29
32
  .choice[aria-selected=true]{background:var(--gramlot-selected,Highlight);color:var(--gramlot-ink,HighlightText)}`;
30
33
  this.toggle = doc.createElement('button');
31
34
  this.toggle.className = 'toggle'; this.toggle.type = 'button'; this.toggle.tabIndex = -1;
@@ -44,9 +47,9 @@ export function ChoiceEditor(HTMLElement) {
44
47
  this.choices.addEventListener('mousedown', event => event.preventDefault());
45
48
  this.control.addEventListener('input', event => {
46
49
  this.#dirty = true; this.#picked = null;
47
- if (!event.isComposing) this.search(this.control.value);
50
+ if (!event.isComposing) this.scheduleSearch(this.control.value);
48
51
  });
49
- this.control.addEventListener('compositionend', () => this.search(this.control.value));
52
+ this.control.addEventListener('compositionend', () => this.scheduleSearch(this.control.value));
50
53
  this.control.addEventListener('keydown', event => {
51
54
  if (event.isComposing || this.locked) return;
52
55
  if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
@@ -71,16 +74,28 @@ export function ChoiceEditor(HTMLElement) {
71
74
  input.autocomplete = 'off'; return input;
72
75
  }
73
76
  get constrained() { return true; }
77
+ get choiceSource() { return this.parameters.store ?? this.parameters.callback ?? this.parameters.values; }
78
+ get searchDelay() { return 0; }
79
+ textValue(text) { return text; }
80
+ selectionAccepted(row) {}
81
+ selectionResolved(row) {}
82
+ renderChoice(row, item) { item.textContent = row.caption; }
83
+ scheduleSearch(query) {
84
+ this.closeChoices();
85
+ if (!this.searchDelay) return this.search(query);
86
+ this.#searchTimer = setTimeout(() => { this.#searchTimer = null; this.search(query); }, this.searchDelay);
87
+ }
74
88
  get commitOnChange() { return this.constrained; }
75
89
  get locked() { return this.control.disabled || this.control.readOnly; }
76
90
  get active() { return this.isConnected && this.pageContext?.isActive(); }
77
91
  projectAttributes(attrs, adapt) {
78
92
  const rest = super.projectAttributes(attrs, adapt);
79
- const source = this.parameters.store ?? this.parameters.callback ?? this.parameters.values;
93
+ const source = this.choiceSource;
80
94
  const changed = source !== this.#source || this.parameters.separator !== this.#separator;
81
95
  this.#separator = this.parameters.separator;
82
96
  this.#source = source;
83
97
  this.toggle.disabled = this.locked;
98
+ if (changed) { this.#rows = []; this.#picked = null; }
84
99
  if (changed || this.locked) this.closeChoices();
85
100
  if (changed && this.active && !this.#dirty) this.resolveValue();
86
101
  return rest;
@@ -105,11 +120,12 @@ export function ChoiceEditor(HTMLElement) {
105
120
  if (this.constrained && text !== '' && matches.length !== 1) {
106
121
  this.error('Choose a value from the list.'); return {ok: false};
107
122
  }
108
- const value = this.constrained ? (text === '' ? null : matches[0].id) : text;
123
+ const value = this.constrained ? (text === '' ? null : matches[0].id) : this.textValue(text);
109
124
  return this.validateCandidate(value, accepted => {
110
125
  if (accepted !== value && this.constrained) throw new Error('Validation cannot replace a selected code; update the Data explicitly.');
111
126
  this.#value = accepted; this.#dirty = false; this.#picked = null;
112
127
  if (!this.constrained) this.control.value = accepted ?? '';
128
+ this.selectionAccepted(matches.length === 1 && accepted === value ? matches[0] : null);
113
129
  });
114
130
  }
115
131
  commitDraft() {
@@ -122,30 +138,33 @@ export function ChoiceEditor(HTMLElement) {
122
138
  this.closeChoices(); this.commitDraft();
123
139
  }
124
140
  async request(keywords) {
141
+ this.#requestController?.abort();
142
+ const controller = new AbortController(); this.#requestController = controller;
125
143
  const generation = ++this.#generation;
126
144
  this.control.setAttribute('aria-busy', 'true'); this.error('');
127
145
  try {
128
- const rows = await this.loadChoices(keywords);
146
+ const rows = await this.loadChoices(keywords, controller.signal);
129
147
  if (generation !== this.#generation || !this.active) return null;
130
148
  return rows;
131
149
  } catch (error) {
132
150
  if (generation === this.#generation && this.active) this.error(error.message);
133
151
  return null;
134
152
  } finally {
135
- if (generation === this.#generation) this.control.setAttribute('aria-busy', 'false');
153
+ if (generation === this.#generation) { this.#requestController = null; this.control.setAttribute('aria-busy', 'false'); }
136
154
  }
137
155
  }
138
156
  async resolveValue() {
139
- if (this.#value == null || this.#value === '') { this.control.value = ''; this.error(''); return; }
157
+ if (this.#value == null || this.#value === '') { this.control.value = ''; this.error(''); if (this.active) this.selectionResolved(null); return; }
140
158
  if (!this.active) return;
141
159
  this.control.value = this.#value;
142
- if (!this.constrained) { this.error(''); return; }
160
+ if (!this.constrained) { this.error(''); this.selectionResolved(null); return; }
143
161
  const rows = await this.request({_id: this.#value});
144
162
  if (!rows) return;
145
163
  const row = rows.find(item => item.id === this.#value);
146
164
  this.#rows = rows;
147
165
  this.control.value = row ? row.caption : this.#value;
148
166
  this.error(row ? '' : 'Value is not in the list.');
167
+ this.selectionResolved(row ?? null);
149
168
  }
150
169
  async search(query) {
151
170
  if (this.locked || !this.active) return;
@@ -156,7 +175,7 @@ export function ChoiceEditor(HTMLElement) {
156
175
  const doc = this.ownerDocument;
157
176
  this.choices.replaceChildren(...rows.map((row, index) => {
158
177
  const item = doc.createElement('div'); item.id = `choice-${index}`;
159
- item.className = 'choice'; item.setAttribute('role', 'option'); item.textContent = row.caption;
178
+ item.className = 'choice'; item.setAttribute('role', 'option'); this.renderChoice(row, item);
160
179
  item.addEventListener('click', () => this.choose(row)); return item;
161
180
  }));
162
181
  if (!rows.length) this.choices.textContent = 'No results';
@@ -185,6 +204,8 @@ export function ChoiceEditor(HTMLElement) {
185
204
  else this.control.setAttribute('aria-activedescendant', `choice-${this.#active}`);
186
205
  }
187
206
  closeChoices() {
207
+ clearTimeout(this.#searchTimer); this.#searchTimer = null;
208
+ this.#requestController?.abort(); this.#requestController = null;
188
209
  ++this.#generation; this.#cleanup?.(); this.#cleanup = null;
189
210
  if (this.#opened) this.choices.hidePopover();
190
211
  this.#opened = false; this.choices.hidden = true;
@@ -0,0 +1,110 @@
1
+ /** Database suggestions share the choice editor and the ordinary data RPC. */
2
+ export const databaseParameters = {
3
+ dbtable: {dtype:'T', binding:'read'},
4
+ method: {dtype:'T', default:'dbSelect', binding:'read'},
5
+ columns: {dtype:'T', binding:'read'},
6
+ hiddenColumns: {dtype:'T', binding:'read'},
7
+ order_by: {dtype:'T', binding:'read'},
8
+ limit: {dtype:'L', default:10, binding:'read'},
9
+ searchDelay: {dtype:'L', default:300, binding:'read'},
10
+ ignoreCase: {dtype:'B', default:true, binding:'read'},
11
+ hasDownArrow: {dtype:'B', default:true, binding:'read'},
12
+ emptyLabel: {dtype:'T', default:'', binding:'read'},
13
+ selectedCaption: {dtype:'T'},
14
+ selectedRecord: {dtype:'T'},
15
+ selectedCb: {dtype:'T'}
16
+ };
17
+ const requestParameters = ['dbtable','method','columns','hiddenColumns','order_by','limit','ignoreCase'];
18
+
19
+ export function databaseChoices(Base) {
20
+ return class extends Base {
21
+ #configuration = {};
22
+ #outputs = {};
23
+ #revision = 0;
24
+ #acceptedRow;
25
+ get choiceSource() { return this.#revision; }
26
+ get searchDelay() { return this.parameters.searchDelay; }
27
+ // Database writes wait for a complete choice/free-text edit, even with live=True.
28
+ get commitOnChange() { return true; }
29
+ textValue(text) { return text === '' ? null : text; }
30
+ projectAttributes(attrs, adapt) {
31
+ const configuration = Object.fromEntries(Object.entries(attrs).filter(([key]) =>
32
+ requestParameters.includes(key) || key === 'autoSelect' || key.startsWith('condition_')));
33
+ const keys = new Set([...Object.keys(configuration), ...Object.keys(this.#configuration)]);
34
+ if ([...keys].some(key => !Object.is(configuration[key], this.#configuration[key]))) {
35
+ this.cancelValidation(); this.#acceptedRow = undefined;
36
+ this.#configuration = configuration; this.#revision++;
37
+ }
38
+ this.#outputs = Object.fromEntries(Object.entries(attrs).filter(([key]) => key.startsWith('selected_')));
39
+ const rest = super.projectAttributes(attrs, adapt);
40
+ const {limit, searchDelay, hasDownArrow, emptyLabel} = this.parameters;
41
+ if (!Number.isInteger(limit) || limit < 1) throw new TypeError('limit must be a positive integer.');
42
+ if (!Number.isInteger(searchDelay) || searchDelay < 0) throw new TypeError('searchDelay must be a non-negative integer.');
43
+ this.toggle.hidden = !hasDownArrow;
44
+ this.control.style.paddingRight = hasDownArrow ? '' : 'var(--gramlot-field-padding, .25em)';
45
+ if (!this.parameters.placeholder) this.control.placeholder = emptyLabel;
46
+ for (const key of Object.keys(rest)) if (key.startsWith('condition_') || key.startsWith('selected_')) delete rest[key];
47
+ return rest;
48
+ }
49
+ async loadChoices(keywords, signal) {
50
+ const parameters = Object.fromEntries(requestParameters.filter(key => key !== 'method' && this.parameters[key] != null)
51
+ .map(key => [key, this.parameters[key]]));
52
+ for (const [key, value] of Object.entries(this.#configuration)) {
53
+ if (key.startsWith('condition_')) {
54
+ const name = key.slice(10);
55
+ if (!name || name.startsWith('_') || requestParameters.includes(name)) throw new TypeError('Invalid condition parameter.');
56
+ parameters[name] = value;
57
+ }
58
+ }
59
+ const result = await this.pageContext.remote(this.parameters.method, {...parameters, ...keywords}, signal);
60
+ if (!result || !Array.isArray(result.rows) || typeof result.identifier !== 'string' || typeof result.caption !== 'string') {
61
+ throw new TypeError('Database selectors require {rows, identifier, caption}.');
62
+ }
63
+ const ids = new Set();
64
+ return result.rows.map(record => {
65
+ const id = record[result.identifier], caption = record[result.caption];
66
+ if (!((typeof id === 'string' && id.length) || Number.isSafeInteger(id)) || typeof caption !== 'string' || ids.has(id)) {
67
+ throw new TypeError('Invalid or duplicate database choice identity/caption.');
68
+ }
69
+ ids.add(id); return {id, caption, record, captionField:result.caption};
70
+ });
71
+ }
72
+ selectionAccepted(row) { this.#acceptedRow = row; }
73
+ renderChoice(row, item) {
74
+ super.renderChoice(row, item);
75
+ for (const name of (this.parameters.columns ?? '').split(',').map(name => name.trim()).filter(name => name && name !== row.captionField)) {
76
+ const detail = this.ownerDocument.createElement('span');
77
+ detail.className = 'choice-detail';
78
+ detail.textContent = row.record[name] ?? '';
79
+ item.append(detail);
80
+ }
81
+ }
82
+ selectionResolved(row) { this.#writeOutputs(row); }
83
+ #writeOutputs(row) {
84
+ const {selectedCaption, selectedRecord} = this.parameters;
85
+ this.pageContext.selectionOutputs({selectedCaption, selectedRecord, fields:this.#outputs}, row);
86
+ }
87
+ finishValidation(outcome) {
88
+ if (outcome.ok && this.#acceptedRow !== undefined) {
89
+ const row = this.#acceptedRow; this.#acceptedRow = undefined;
90
+ this.#writeOutputs(row);
91
+ if (this.parameters.selectedCb) {
92
+ const report = error => console.error('Selection notification failed:', error);
93
+ try {
94
+ const result = this.pageContext.callLogic(this.parameters.selectedCb,
95
+ {value:outcome.value, record:row?.record ?? null});
96
+ if (result instanceof Promise) result.catch(report);
97
+ } catch (error) { report(error); }
98
+ }
99
+ }
100
+ super.finishValidation(outcome);
101
+ }
102
+ 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});
106
+ if (rows?.length === 1 && this.readControlValue() == null && !this.locked) this.choose(rows[0]);
107
+ }
108
+ }
109
+ };
110
+ }
@@ -5,6 +5,7 @@ import {TypedEditor, numberEditor, dateEditor, timeEditor} from './typed-editor.
5
5
  import {CalendarControl} from './date-calendar.js';
6
6
  import {FieldState} from './field-state.js';
7
7
  import {ChoiceEditor, localChoices, callbackChoices} from './choice-editor.js';
8
+ import {databaseChoices, databaseParameters} from './database-choices.js';
8
9
 
9
10
  export const Textbox = defineComponent({
10
11
  name: 'textbox', tag: 'gramlot-textbox', base: NativeControl, mixins: [Labelbox, FieldState],
@@ -193,11 +194,23 @@ export const CallbackSelect = defineComponent({
193
194
  });
194
195
  export const ComboBox = defineComponent({
195
196
  name: 'comboBox', tag: 'gramlot-combo-box', base: ChoiceEditor, mixins: [Labelbox, FieldState],
196
- parameters: {values: {dtype: 'T', default: '', binding: 'read'}, separator: {dtype: 'T', default: ',', binding: 'read'}, store: {dtype: 'X', nullable: true, default: null, binding: 'read'}},
197
+ parameters: {values: {dtype: 'T', default: '', binding: 'read'}, separator: {dtype: 'T', default: ',', binding: 'read'},
198
+ store: {dtype: 'X', nullable: true, default: null, binding: 'read'}},
197
199
  implementation: Base => class extends localChoices(Base) {
198
200
  get constrained() { return false; }
199
201
  }
200
202
  });
203
+ export const DbSelect = defineComponent({
204
+ name:'dbSelect', tag:'gramlot-db-select', base:ChoiceEditor, mixins:[Labelbox, FieldState],
205
+ parameters:{...databaseParameters, value:{dtype:['T','L'], nullable:true, binding:'twoWay'},
206
+ autoSelect:{dtype:'B', default:false, binding:'read'}}, implementation:databaseChoices
207
+ });
208
+ export const DbComboBox = defineComponent({
209
+ name:'dbComboBox', tag:'gramlot-db-combo-box', base:ChoiceEditor, mixins:[Labelbox, FieldState],
210
+ parameters:databaseParameters, implementation:Base => class extends databaseChoices(Base) {
211
+ get constrained() { return false; }
212
+ }
213
+ });
201
214
  export const CheckBoxText = defineComponent({
202
215
  name: 'checkBoxText', tag: 'gramlot-check-box-text', base: ChoiceGroup, mixins: [Labelbox, FieldState],
203
216
  parameters: {
@@ -212,4 +225,4 @@ export const CheckBoxText = defineComponent({
212
225
  });
213
226
  export default defineCollection({name: 'inputs', components: [Textbox, Checkbox, RadioButtonText,
214
227
  TextBoxArea, Passwordbox, RadioButton, Colorpicker, HorizontalSlider, VerticalSlider,
215
- NumberTextBox, DateTextBox, TimeTextBox, FilteringSelect, CallbackSelect, ComboBox, CheckBoxText, DateCalendar]});
228
+ NumberTextBox, DateTextBox, TimeTextBox, FilteringSelect, CallbackSelect, ComboBox, DbSelect, DbComboBox, CheckBoxText, DateCalendar]});
@@ -2,12 +2,14 @@
2
2
  import {defineComponent, defineCollection} from './registry.js';
3
3
  import {Labelbox} from './labelbox.js';
4
4
  import {Container} from './container.js';
5
- import {BorderContainer, ContentPane} from './border-container.js';
6
- export {BorderContainer, ContentPane};
5
+ import {BorderContainer, ContentPane, FramePane} from './border-container.js';
6
+ export {BorderContainer, ContentPane, FramePane};
7
7
  import {StackContainer, TabContainer} from './selected-container.js';
8
8
  export {StackContainer, TabContainer};
9
9
  import {positionPopup} from './popup.js';
10
10
  import {FormletLabels} from './formlet-labels.js';
11
+ import {Dialog, FloatingPane} from './windows.js';
12
+ export {Dialog, FloatingPane};
11
13
 
12
14
  const COPY_FEEDBACK_DURATION = 1600;
13
15
 
@@ -170,4 +172,4 @@ export const GroupBox = defineComponent({
170
172
  }
171
173
  }
172
174
  });
173
- export default defineCollection({name: 'layout', components: [Formlet, GroupBox, ContentPane, BorderContainer, StackContainer, TabContainer]});
175
+ export default defineCollection({name: 'layout', components: [Dialog, FloatingPane, FramePane, Formlet, GroupBox, ContentPane, BorderContainer, StackContainer, TabContainer]});