@gramlot/gramlot 0.3.16 → 0.3.17

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 (96) hide show
  1. package/dist/components/editors/__init__.py +1 -1
  2. package/dist/components/editors/assets/collection.js +16162 -11689
  3. package/dist/components/editors/assets/index.js +1 -1
  4. package/dist/components/editors/grammar.json +3 -0
  5. package/dist/components/inputs/__init__.py +1 -1
  6. package/dist/components/inputs/assets/collection.js +134 -179
  7. package/dist/components/inputs/assets/index.js +1 -1
  8. package/dist/components/inputs/grammar.json +19 -0
  9. package/dist/components/layout/__init__.py +1 -1
  10. package/dist/components/layout/assets/collection.js +4643 -3481
  11. package/dist/components/layout/assets/index.js +1 -1
  12. package/dist/components/layout/grammar.json +509 -1
  13. package/dist/components/tree/__init__.py +1 -1
  14. package/dist/components/tree/assets/collection.js +306 -94
  15. package/dist/components/tree/assets/index.js +1 -1
  16. package/dist/components/tree/grammar.json +16 -0
  17. package/dist/components/typst/__init__.py +1 -1
  18. package/dist/components/typst/assets/collection.js +2 -2
  19. package/dist/components/typst/assets/index.js +1 -1
  20. package/dist/gramlot.js +2124 -506
  21. package/dist/gramlot.min.js +95 -40
  22. package/dist/runtime-notices.json +4 -0
  23. package/package.json +12 -8
  24. package/src/binding/device-resolver.js +27 -0
  25. package/src/binding/error-notifications.js +84 -0
  26. package/src/binding/remote-resolver.d.ts +18 -0
  27. package/src/binding/remote.js +11 -4
  28. package/src/binding/runtime.js +6 -2
  29. package/src/bootstrap.js +4 -4
  30. package/src/components/buttons.js +10 -3
  31. package/src/components/code-mirror-engine.js +14 -4
  32. package/src/components/code-mirror.js +2 -3
  33. package/src/components/container.js +1 -1
  34. package/src/components/date-calendar.js +1 -1
  35. package/src/components/formlet-labels.js +5 -4
  36. package/src/components/html-document.js +4 -2
  37. package/src/components/html-editor.js +2 -2
  38. package/src/components/jodit-engine.js +72 -11
  39. package/src/components/labelbox.js +19 -63
  40. package/src/components/layout.js +31 -19
  41. package/src/components/markdown-document.js +1 -1
  42. package/src/components/markdown-editor.js +2 -2
  43. package/src/components/menus.js +7 -6
  44. package/src/components/prose-mirror-engine.js +14 -1
  45. package/src/components/registry.js +2 -0
  46. package/src/components/selected-container.js +107 -14
  47. package/src/components/toolbar-overflow.js +9 -8
  48. package/src/components/transform-pane.js +140 -0
  49. package/src/components/tray-geometry.js +87 -0
  50. package/src/components/tray-pane.js +435 -0
  51. package/src/components/tray-settings.js +62 -0
  52. package/src/components/tree.js +115 -21
  53. package/src/components/typed-editor.js +1 -1
  54. package/src/components/typst-client.js +14 -13
  55. package/src/components/validation.js +1 -1
  56. package/src/components/window-surface.js +281 -0
  57. package/src/components/windows.js +32 -261
  58. package/src/device-frames.js +195 -0
  59. package/src/filesystem.d.ts +12 -5
  60. package/src/filesystem.js +8 -8
  61. package/src/gramlot.d.ts +3 -1
  62. package/src/gramlot.js +11 -4
  63. package/src/handlers/device-handler.d.ts +75 -0
  64. package/src/handlers/device-handler.js +1037 -0
  65. package/src/handlers/dom-handler.d.ts +2 -0
  66. package/src/handlers/dom-handler.js +9 -0
  67. package/src/handlers/rpc-handler.d.ts +2 -2
  68. package/src/http-transport.d.ts +3 -3
  69. package/src/http-transport.js +17 -11
  70. package/src/ide-documents.js +6 -4
  71. package/src/ide-runtime.d.ts +14 -3
  72. package/src/ide-runtime.js +123 -94
  73. package/src/index-page-runtime.d.ts +2 -2
  74. package/src/index-page-runtime.js +91 -43
  75. package/src/index-page-styles.js +1 -1
  76. package/src/index.d.ts +7 -2
  77. package/src/index.js +5 -1
  78. package/src/inout.d.ts +1 -1
  79. package/src/inout.js +5 -1
  80. package/src/mobile-environment.d.ts +6 -0
  81. package/src/mobile-environment.js +52 -0
  82. package/src/navigation-resolver.d.ts +14 -2
  83. package/src/renderer/attributes.js +5 -2
  84. package/src/renderer/drag-drop.js +5 -4
  85. package/src/renderer/gramlot-renderer.d.ts +13 -2
  86. package/src/renderer/gramlot-renderer.js +49 -13
  87. package/src/server/index-page.js +4 -4
  88. package/src/view/controls.js +48 -23
  89. package/src/view/html.js +85 -4
  90. package/src/view/labelbox.js +95 -0
  91. package/themes/gramlot-base/theme.css +4 -0
  92. package/themes/mela/theme.css +62 -15
  93. package/src/date-parser/civil.js +0 -61
  94. package/src/date-parser/index.d.ts +0 -18
  95. package/src/date-parser/index.js +0 -196
  96. package/src/date-parser/locales.js +0 -257
@@ -17,6 +17,7 @@ export const Tree = defineComponent({
17
17
  getLabelClass: {dtype: 'T', nullable: true, default: null},
18
18
  getIconClass: {dtype: 'T', nullable: true, default: null},
19
19
  selectedLabelClass: {dtype: 'T', default: '', binding: 'read'},
20
+ searchText: {dtype: 'T', default: '', binding: 'read'},
20
21
  autoCollapse: {dtype: 'B', default: false, binding: 'read'},
21
22
  selectedPath: {dtype: 'T', nullable: true, default: null, binding: 'twoWay'}
22
23
  },
@@ -33,6 +34,15 @@ export const Tree = defineComponent({
33
34
  #scheduled = false;
34
35
  #loading = new Set();
35
36
  #errors = new Map();
37
+ #searchInput = '';
38
+ #searchText = '';
39
+ #searchTimer = null;
40
+ #searchVersion = 0;
41
+ #searchOpen = new Set();
42
+ #searchClosed = new WeakSet();
43
+ #searchAttempted = new WeakSet();
44
+ #searching = false;
45
+ #resolutions = new Map();
36
46
 
37
47
  constructor() {
38
48
  super();
@@ -64,6 +74,8 @@ export const Tree = defineComponent({
64
74
  .branch-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${SVG_NS}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 7V4h7l3 3h8v13H3z'/%3E%3C/svg%3E")}
65
75
  .opened-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${SVG_NS}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 19V4h7l3 3h8v3M3 20l3-9h16l-3 9z'/%3E%3C/svg%3E")}
66
76
  .loading>.row{opacity:.65}.error>.row .caption{text-decoration:underline dotted}
77
+ mark{background:#ffe493;color:#302300;font-weight:600;border-radius:2px;padding:0 1px}
78
+ .search-status{padding:4px;color:var(--gramlot-text-secondary,#555);font-size:.9em}
67
79
  [hidden]{display:none}`;
68
80
  this.shadowRoot.append(style);
69
81
  }
@@ -86,6 +98,8 @@ export const Tree = defineComponent({
86
98
  if (!(bag instanceof Bag)) throw new TypeError('tree storepath must resolve to a Bag');
87
99
  if (bag !== this.#store) {
88
100
  this.#store = bag;
101
+ this.#resetSearch();
102
+ this.#searchText = this.#searchInput.toLowerCase();
89
103
  this.#expanded.clear();
90
104
  this.#errors.clear();
91
105
  this.#requestedPath = undefined;
@@ -94,10 +108,65 @@ export const Tree = defineComponent({
94
108
  }
95
109
  projectAttributes(attrs, adapt) {
96
110
  const rest = super.projectAttributes(attrs, adapt);
111
+ const text = this.parameters.searchText.trim();
112
+ if (text !== this.#searchInput) {
113
+ this.#resetSearch();
114
+ this.#searchInput = text;
115
+ if (!text) this.#searchText = '';
116
+ else this.#searchTimer = setTimeout(() => {
117
+ this.#searchTimer = null; this.#searchText = text.toLowerCase(); this.#schedule();
118
+ }, 200);
119
+ }
97
120
  this.#schedule();
98
121
  return rest;
99
122
  }
100
- connectedCallback() { this.#schedule(); }
123
+ connectedCallback() {
124
+ if (this.#searchTimer === null) this.#searchText = this.#searchInput.toLowerCase();
125
+ this.#schedule();
126
+ }
127
+ disconnectedCallback() { this.#resetSearch(); }
128
+ #resetSearch() {
129
+ clearTimeout(this.#searchTimer); this.#searchTimer = null;
130
+ this.#searchVersion++; this.#searching = false;
131
+ this.#searchAttempted = new WeakSet(); this.#searchOpen.clear(); this.#searchClosed = new WeakSet();
132
+ }
133
+ #opened(node) { return this.#searchText ? this.#searchOpen.has(node) : this.#expanded.has(node); }
134
+ async #searchBranches() {
135
+ const version = this.#searchVersion, store = this.#store;
136
+ const current = () => this.isConnected && version === this.#searchVersion && store === this.#store;
137
+ this.#searching = true;
138
+ const visit = async (bag, ancestors = new Set()) => {
139
+ if (!current()) return;
140
+ if (ancestors.has(bag)) throw new TypeError('tree requires an acyclic Bag store');
141
+ const next = new Set(ancestors).add(bag);
142
+ for (const node of bag.getNodes()) {
143
+ if (!current()) return;
144
+ if (node.resolver !== null && node.resolver.expired && !this.#searchAttempted.has(node)) {
145
+ this.#searchAttempted.add(node);
146
+ await this.#resolve(node, true);
147
+ }
148
+ if (!current()) return;
149
+ if (node.staticValue instanceof Bag) await visit(node.staticValue, next);
150
+ }
151
+ };
152
+ try { await visit(store); }
153
+ finally { if (current()) { this.#searching = false; this.#schedule(); } }
154
+ }
155
+ #highlight(caption) {
156
+ const walker = this.ownerDocument.createTreeWalker(caption, 4), texts = [];
157
+ while (walker.nextNode()) texts.push(walker.currentNode);
158
+ for (const text of texts) {
159
+ const value = text.textContent, lower = value.toLowerCase(), fragment = this.ownerDocument.createDocumentFragment();
160
+ let cursor = 0, start = lower.indexOf(this.#searchText);
161
+ if (start < 0) continue;
162
+ while (start >= 0) {
163
+ fragment.append(value.slice(cursor, start));
164
+ const mark = this.ownerDocument.createElement('mark'); mark.textContent = value.slice(start, start + this.#searchText.length);
165
+ fragment.append(mark); cursor = start + this.#searchText.length; start = lower.indexOf(this.#searchText, cursor);
166
+ }
167
+ fragment.append(value.slice(cursor)); text.replaceWith(fragment);
168
+ }
169
+ }
101
170
  #schedule() {
102
171
  if (this.#scheduled) return;
103
172
  this.#scheduled = true;
@@ -121,6 +190,10 @@ export const Tree = defineComponent({
121
190
  seen.delete(bag);
122
191
  };
123
192
  visit(this.#store, '', []);
193
+ if (this.#searchText && this.#searchTimer === null && !this.#searching && [...items.values()].some(({node}) =>
194
+ node.resolver !== null && node.resolver.expired && !this.#searchAttempted.has(node))) {
195
+ void this.#searchBranches();
196
+ }
124
197
  const identities = new Set([...items.values()].map(item => item.node));
125
198
  for (const node of this.#expanded) if (!identities.has(node)) this.#expanded.delete(node);
126
199
  for (const node of this.#errors.keys()) if (!identities.has(node)) this.#errors.delete(node);
@@ -216,13 +289,14 @@ export const Tree = defineComponent({
216
289
  });
217
290
  }
218
291
  const present = () => {
219
- const opened = this.#expanded.has(node), selected = this.#selectedPath === path;
292
+ const opened = this.#opened(node), selected = this.#selectedPath === path;
220
293
  const keywords = {item: node, path, opened, selected};
221
294
  const attribute = this.parameters.labelAttribute;
222
295
  const label = this.parameters.getLabel !== null ? this.#call('getLabel', keywords)
223
296
  : attribute !== null ? (Object.hasOwn(node.attr, attribute) ? node.attr[attribute] : node.label)
224
297
  : this.parameters.labelCb !== null ? this.#call('labelCb', keywords) : node.label;
225
298
  this.#setCaption(caption, label, this.parameters.getLabel !== null || (attribute === null && this.parameters.labelCb !== null));
299
+ if (this.#searchText) this.#highlight(caption);
226
300
  const labelClass = this.parameters.getLabelClass !== null ? this.#call('getLabelClass', keywords)
227
301
  : node.attr[opened ? 'labelClassOpened' : 'labelClassClosed'] || node.attr.labelClass || '';
228
302
  const labelClasses = [...this.#classes(labelClass), ...(selected ? this.#classes(this.parameters.selectedLabelClass) : [])];
@@ -243,7 +317,7 @@ export const Tree = defineComponent({
243
317
  };
244
318
  this.#presentations.set(path, present);
245
319
  const sync = () => {
246
- const opened = this.#expanded.has(node);
320
+ const opened = this.#opened(node);
247
321
  entry.setAttribute('aria-expanded', String(opened));
248
322
  entry.classList.toggle('opened', opened);
249
323
  entry.classList.toggle('closed', !opened);
@@ -253,9 +327,13 @@ export const Tree = defineComponent({
253
327
  present();
254
328
  };
255
329
  const toggle = () => {
256
- if (this.#expanded.has(node)) this.#expanded.delete(node);
330
+ const expanded = this.#searchText ? this.#searchOpen : this.#expanded;
331
+ if (expanded.has(node)) {
332
+ expanded.delete(node);
333
+ if (this.#searchText) this.#searchClosed.add(node);
334
+ }
257
335
  else {
258
- this.#expand(node);
336
+ if (this.#searchText) { this.#searchClosed.delete(node); this.#searchOpen.add(node); } else this.#expand(node);
259
337
  if (node.resolver !== null) this.#resolve(node);
260
338
  }
261
339
  for (const update of branchSync.values()) update();
@@ -272,9 +350,9 @@ export const Tree = defineComponent({
272
350
  else if (event.key === 'Home') target = visible[0];
273
351
  else if (event.key === 'End') target = visible.at(-1);
274
352
  else if (event.key === 'ArrowRight' && branch) {
275
- if (!this.#expanded.has(node)) toggle(); else target = group.firstElementChild;
353
+ if (!this.#opened(node)) toggle(); else target = group.firstElementChild;
276
354
  } else if (event.key === 'ArrowLeft') {
277
- if (branch && this.#expanded.has(node)) toggle(); else target = parent;
355
+ if (branch && this.#opened(node)) toggle(); else target = parent;
278
356
  } else if (event.key === 'Enter' || event.key === ' ') this.#select(path);
279
357
  else return;
280
358
  event.preventDefault(); event.stopPropagation();
@@ -286,6 +364,25 @@ export const Tree = defineComponent({
286
364
  return list;
287
365
  };
288
366
  this.control.replaceChildren(build(this.#store, '', null));
367
+ this.control.setAttribute('aria-busy', String(this.#searching));
368
+ if (this.#searchText) {
369
+ const visible = new Set(), matches = [];
370
+ this.#searchOpen.clear();
371
+ for (const [path, row] of this.#rows) {
372
+ const caption = row.firstElementChild.querySelector('.caption'), item = items.get(path);
373
+ const match = caption.textContent.toLowerCase().includes(this.#searchText);
374
+ if (match) matches.push(caption);
375
+ if (match || this.#errors.has(item.node) || this.#loading.has(item.node)) {
376
+ visible.add(item.node);
377
+ for (const ancestor of item.ancestors) { visible.add(ancestor); if (!this.#searchClosed.has(ancestor)) this.#searchOpen.add(ancestor); }
378
+ }
379
+ }
380
+ for (const [path, row] of this.#rows) row.hidden = !visible.has(items.get(path).node);
381
+ for (const update of branchSync.values()) update();
382
+ const status = this.ownerDocument.createElement('div'); status.className = 'search-status'; status.setAttribute('role', 'status');
383
+ status.textContent = this.#searching ? 'Searching…' : this.#errors.size ? 'Some branches could not be searched. Expand them to retry.' : matches.length ? '' : 'No matches';
384
+ this.control.append(status);
385
+ }
289
386
  this.#tabStop(focused ?? selected);
290
387
  if (focused) this.#rows.get(focused)?.focus();
291
388
  }
@@ -316,6 +413,7 @@ export const Tree = defineComponent({
316
413
  return [...this.control.querySelectorAll('[role=treeitem]')].filter(row => !row.closest('[hidden]'));
317
414
  }
318
415
  #expand(node) {
416
+ if (this.#searchText) { this.#searchOpen.add(node); return; }
319
417
  if (this.parameters.autoCollapse) {
320
418
  for (const sibling of node.parentBag.getNodes()) {
321
419
  if (sibling !== node) this.#expanded.delete(sibling);
@@ -323,20 +421,16 @@ export const Tree = defineComponent({
323
421
  }
324
422
  this.#expanded.add(node);
325
423
  }
326
- async #resolve(node) {
327
- if (this.#loading.has(node)) return;
328
- this.#loading.add(node);
329
- this.#errors.delete(node);
330
- this.#schedule();
331
- try {
332
- await node.getValue();
333
- } catch (error) {
334
- this.#errors.set(node, error);
335
- this.#expanded.delete(node);
336
- } finally {
337
- this.#loading.delete(node);
338
- this.#schedule();
339
- }
424
+ #resolve(node, searching = false) {
425
+ if (this.#resolutions.has(node)) return this.#resolutions.get(node);
426
+ this.#loading.add(node); this.#errors.delete(node); this.#schedule();
427
+ const pending = (async () => {
428
+ try { await Promise.resolve().then(() => node.getValue()); }
429
+ catch (error) { this.#errors.set(node, error); if (!searching) this.#expanded.delete(node); }
430
+ finally { this.#loading.delete(node); this.#resolutions.delete(node); this.#schedule(); }
431
+ })();
432
+ this.#resolutions.set(node, pending);
433
+ return pending;
340
434
  }
341
435
  #tabStop(path) {
342
436
  const visible = this.#visible(), target = typeof path === 'string' || path == null
@@ -1,5 +1,5 @@
1
1
  /** Typed text drafts. Components parse/present; ControlAdapter alone writes Data. */
2
- import {parseDateExpression} from '../date-parser/index.js';
2
+ import {parseDateExpression} from '@genrojs/toolbox';
3
3
  import {CalendarView, checkCivilDate} from './date-calendar.js';
4
4
  import {SVG_NS} from '../renderer/attributes.js';
5
5
  import {NativeControl} from './bases.js';
@@ -1,16 +1,17 @@
1
1
  import source from '../../dist/typst-worker-source.js';
2
2
 
3
- let worker,workerUrl,sequence=0,owners=0,failure;
3
+ let worker,workerUrl,sequence=0,owners=0;
4
4
  const requests=new Map();
5
- function stop(){
6
- worker.terminate();URL.revokeObjectURL(workerUrl);worker=null;
7
- for(const {reject} of requests.values())reject(new Error('Typst preview closed'));
5
+ function stop(error=new Error('Typst preview closed')){
6
+ if(worker){
7
+ worker.onmessage=null;worker.onerror=null;
8
+ worker.terminate();URL.revokeObjectURL(workerUrl);worker=null;
9
+ }
10
+ for(const {reject} of requests.values())reject(error);
8
11
  requests.clear();
9
12
  }
10
- /** Compiler lifetime follows the previews, with serialized jobs in one Worker. */
11
- export function acquireCompiler(){
13
+ function start(){
12
14
  if(!worker){
13
- failure=null;
14
15
  workerUrl=URL.createObjectURL(new Blob([source],{type:'text/javascript'}));
15
16
  worker=new Worker(workerUrl);
16
17
  worker.onmessage=({data})=>{
@@ -18,18 +19,18 @@ export function acquireCompiler(){
18
19
  requests.delete(data.id);
19
20
  if(data.error)request.reject(new Error(data.error));else request.resolve(data);
20
21
  };
21
- worker.onerror=event=>{
22
- failure=new Error(event.message);
23
- for(const {reject} of requests.values())reject(failure);
24
- requests.clear();
25
- };
22
+ worker.onerror=event=>stop(new Error(event.message));
26
23
  }
24
+ }
25
+ /** Compiler lifetime follows the previews; a failed Worker is replaced on the next compile. */
26
+ export function acquireCompiler(){
27
+ start();
27
28
  owners++;
28
29
  let released=false;
29
30
  return {
30
31
  compile(value){
31
32
  if(released)throw new Error('Typst compiler session is closed');
32
- if(failure)return Promise.reject(failure);
33
+ start();
33
34
  const id=++sequence;
34
35
  return new Promise((resolve,reject)=>{requests.set(id,{resolve,reject});worker.postMessage({id,value});});
35
36
  },
@@ -2,7 +2,7 @@ import {Bag} from '@gramlot/gramlot';
2
2
  import {pointerTemplate} from '@genrojs/builders';
3
3
 
4
4
  /** Shared ordered rules. Context supplies activated callbacks/RPC; this module never writes Data. */
5
- export const validationRules = ['select', 'notnull', 'empty', 'case', 'len', 'min', 'max', 'email', 'regex', 'call', 'remote'];
5
+ const validationRules = ['select', 'notnull', 'empty', 'case', 'len', 'min', 'max', 'email', 'regex', 'call', 'remote'];
6
6
  const deferredRules = ['nodup', 'exist', 'gridnodup'];
7
7
  const empty = value => value == null || value === '';
8
8
  const then = (value, next) => value instanceof Promise ? value.then(next) : next(value);
@@ -0,0 +1,281 @@
1
+ import {SVG_NS} from '../renderer/attributes.js';
2
+
3
+ // Shared presentation only; Source ownership remains with the caller.
4
+ const surfaces = new WeakMap();
5
+ export class WindowSurface {
6
+ #context; #observer; #scheduled = false; #live = false;
7
+ #open = false; #collapsed = false; #maximized = false; #pending = null; #generation = 0;
8
+ #geometry = null; #gesture = null; #previousFocus = null;
9
+ #resize = () => { if (this.#open) this.#fit(); };
10
+ constructor(host, root, {modal, validateContent}) {
11
+ this.host = host; this.root = root; this.modal = modal;
12
+ this.validateContent = validateContent;
13
+ const doc = this.ownerDocument;
14
+ const shadow = this.root; shadow.classList.add('window-surface');
15
+ const style = doc.createElement('style');
16
+ style.textContent = `.window-surface{display:contents;font:inherit;color:var(--gramlot-ink,CanvasText)}
17
+ .window-surface *,.window-surface *::before,.window-surface *::after{box-sizing:border-box}
18
+ .window-surface dialog{position:fixed;inset:auto;margin:0;padding:0;border:1px solid var(--gramlot-border,#d5dce5);
19
+ border-radius:var(--gramlot-window-radius,10px);color:inherit;font:inherit;
20
+ background:var(--gramlot-surface,Canvas);box-shadow:0 2px 6px #00000014,0 16px 36px #00000029;overflow:hidden;
21
+ max-width:calc(100vw - 16px);max-height:calc(100dvh - 16px)}
22
+ .window-surface dialog[open]{display:flex;flex-direction:column}
23
+ .window-surface dialog[data-maximized]{max-width:100vw;max-height:100dvh;border-radius:0}
24
+ .window-surface dialog::backdrop{background:var(--gramlot-window-backdrop,#0006)}
25
+ .window-surface .titlebar{display:flex;align-items:center;gap:4px;flex:none;min-height:max(32px,var(--gramlot-tab-height,32px));padding:3px 5px 3px 12px;
26
+ background:color-mix(in srgb,var(--gramlot-surface,Canvas) 60%,var(--gramlot-surface-subtle,#edf1f7));border-bottom:1px solid var(--gramlot-border,#d5dce5)}
27
+ .window-surface .title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;margin:0;font-size:1em;font-weight:600}
28
+ .window-surface .titlebar[data-movable]{cursor:move;touch-action:none;user-select:none}
29
+ .window-surface button{font:inherit;color:inherit;background:transparent;border:0;border-radius:4px;cursor:pointer;min-width:max(24px,var(--gramlot-touch-target,0px));min-height:max(24px,var(--gramlot-touch-target,0px))}
30
+ .window-surface button:hover{background:color-mix(in srgb,currentColor 12%,transparent)}
31
+ .window-surface button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}
32
+ .window-surface .titlebar:focus-visible{outline:none}
33
+ .window-surface .titlebar:focus-visible .title{text-decoration:underline dotted;text-underline-offset:4px;text-decoration-thickness:1px}
34
+ .window-surface .body{flex:1;min-height:0;min-width:0;display:flex;overflow:hidden}
35
+ .window-surface slot{display:contents}
36
+ .window-surface ::slotted(*){flex:1;width:100%;height:100%;min-height:0;min-width:0}
37
+ .window-surface .resize{position:absolute;right:0;bottom:0;width:20px;height:20px;min-width:20px;min-height:20px;
38
+ display:grid;place-items:end;padding:2px;cursor:nwse-resize;touch-action:none;opacity:.65}
39
+ .window-surface .resize:hover,.window-surface .resize:focus-visible{opacity:1}
40
+ .window-surface .resize svg{width:14px;height:14px;pointer-events:none}
41
+ .window-surface [hidden]{display:none!important}
42
+ .window-surface .status{flex:none;font-size:.85em;padding:4px 10px;color:var(--gramlot-error,#b22)}
43
+ .window-surface dialog[data-collapsed] .titlebar{border-bottom:0}`;
44
+ this.shell = doc.createElement('dialog');
45
+ this.titlebar = doc.createElement('header'); this.titlebar.className='titlebar';
46
+ this.heading = doc.createElement('h2'); this.heading.id=''; this.heading.className='title';
47
+ this.collapseButton = this.#button('Collapse window','−');
48
+ this.maximizeButton = this.#button('Maximize window','□');
49
+ this.closeButton = this.#button('Close window','×');
50
+ this.titlebar.append(this.heading,this.collapseButton,this.maximizeButton,this.closeButton);
51
+ this.body = doc.createElement('div');this.body.className='body';this.body.append(doc.createElement('slot'));
52
+ this.resizeButton = this.#button('Resize window','');this.resizeButton.className='resize';
53
+ const resizeIcon=doc.createElementNS(SVG_NS,'svg');
54
+ resizeIcon.setAttribute('viewBox','0 0 16 16');resizeIcon.setAttribute('aria-hidden','true');resizeIcon.setAttribute('focusable','false');
55
+ const resizePath=doc.createElementNS(SVG_NS,'path');
56
+ resizePath.setAttribute('d','M5 13 13 5M9 13l4-4');resizePath.setAttribute('fill','none');
57
+ resizePath.setAttribute('stroke','currentColor');resizePath.setAttribute('stroke-width','1.25');resizePath.setAttribute('stroke-linecap','round');
58
+ resizeIcon.append(resizePath);this.resizeButton.append(resizeIcon);
59
+ this.status = doc.createElement('div');this.status.className='status';this.status.hidden=true;this.status.setAttribute('role','alert');
60
+ this.shell.append(this.titlebar,this.body,this.status,this.resizeButton);shadow.append(style,this.shell);
61
+ this.closeButton.addEventListener('click',()=>this.requestClose('close'));
62
+ this.collapseButton.addEventListener('click',()=>this.#setCollapsed(!this.#collapsed,true));
63
+ this.maximizeButton.addEventListener('click',()=>this.#setMaximized(!this.#maximized,true));
64
+ this.shell.addEventListener('cancel',event=>{event.preventDefault();this.requestClose('escape');});
65
+ this.shell.addEventListener('keydown',event=>{
66
+ if(!this.modal && event.key==='Escape' && !event.defaultPrevented){event.preventDefault();this.requestClose('escape');}
67
+ });
68
+ this.shell.addEventListener('focusin',()=>this.#raise());
69
+ this.shell.addEventListener('pointerdown',()=>this.#raise());
70
+ for (const [handle,kind] of [[this.titlebar,'move'],[this.resizeButton,'resize']]) {
71
+ handle.addEventListener('pointerdown',event=>this.#startGesture(event,kind));
72
+ handle.addEventListener('pointermove',event=>this.#moveGesture(event));
73
+ handle.addEventListener('pointerup',event=>this.#endGesture(event,true));
74
+ handle.addEventListener('pointercancel',event=>this.#endGesture(event,false));
75
+ handle.addEventListener('lostpointercapture',event=>this.#endGesture(event,false));
76
+ handle.addEventListener('keydown',event=>this.#keyGeometry(event,kind));
77
+ }
78
+ this.#observer=new doc.defaultView.MutationObserver(()=>this.#schedule());
79
+ }
80
+ #button(label,text) { const b=this.ownerDocument.createElement('button');b.type='button';b.textContent=text;b.setAttribute('aria-label',label);b.title=label;return b; }
81
+ get ownerDocument() { return this.host.ownerDocument; }
82
+ get opened() { return this.#open; }
83
+ focus() { this.#raise(); this.closeButton.focus(); }
84
+ setSourceContext(context) { this.#context=context; }
85
+ connect() {
86
+ this.#live=true;
87
+ let peers = surfaces.get(this.ownerDocument);
88
+ if (!peers) surfaces.set(this.ownerDocument, peers = new Set());
89
+ peers.add(this);
90
+ this.#observer.observe(this.host,{childList:true});
91
+ this.ownerDocument.defaultView.addEventListener('resize',this.#resize);this.#schedule();
92
+ }
93
+ disconnect() {
94
+ surfaces.get(this.ownerDocument).delete(this);
95
+ this.#live=false;this.#generation++;this.#pending=null;this.#observer.disconnect();
96
+ this.ownerDocument.defaultView.removeEventListener('resize',this.#resize);this.#cancelGesture();
97
+ if(this.shell.open)this.shell.close();this.#open=false;this.#restoreFocus();
98
+ }
99
+ configure(parameters) {
100
+ const previous=this.parameters;
101
+ this.parameters=parameters;
102
+ if(previous) {
103
+ if(['width','height','left','top','minWidth','minHeight'].some(name=>previous[name]!==this.parameters[name])) {
104
+ this.#cancelGesture();this.#geometry=null;this.#collapsed=false;this.#maximized=false;
105
+ }
106
+ if(previous.open!==this.parameters.open) { this.#generation++;this.#pending=null; }
107
+ if(previous.movable!==this.parameters.movable || previous.resizable!==this.parameters.resizable)this.#cancelGesture();
108
+ }
109
+ this.#schedule();
110
+ }
111
+ #schedule() {
112
+ if(this.#scheduled)return;this.#scheduled=true;
113
+ queueMicrotask(()=>{this.#scheduled=false;if(this.#live&&this.host.isConnected&&this.parameters)this.#sync();});
114
+ }
115
+ #sync() {
116
+ this.validateContent();
117
+ const p=this.parameters;
118
+ this.heading.textContent=p.title;this.shell.setAttribute('aria-label',p.title);
119
+ this.closeButton.hidden=!p.closable;this.closeButton.disabled=Boolean(this.#pending);
120
+ this.collapseButton.hidden=!p.collapsible;this.maximizeButton.hidden=!p.maximizable;
121
+ if(!p.open) { this.#close(false);return; }
122
+ if(!this.#open) {
123
+ this.#previousFocus=this.#activeElement();
124
+ this.#collapsed=false;this.#maximized=false;this.body.hidden=false;this.shell.removeAttribute('data-collapsed');
125
+ if(this.modal)this.shell.showModal();else this.shell.show();
126
+ this.#open=true;this.#applySize();this.#fit();this.#raise();
127
+ this.#context.publish('opened',{});
128
+ } else if(!this.#geometry) { this.#applySize();this.#fit(); }
129
+ this.#setMaximized(p.maximizable&&p.maximized,false);
130
+ this.#setCollapsed(p.collapsible&&p.collapsed,false);
131
+ if(!p.maximizable && p.maximized)this.#context.writeParameter('maximized',false);
132
+ if(!p.collapsible && p.collapsed)this.#context.writeParameter('collapsed',false);
133
+ }
134
+ #activeElement() { let active=this.ownerDocument.activeElement;while(active?.shadowRoot?.activeElement)active=active.shadowRoot.activeElement;return active; }
135
+ #restoreFocus() { const previous=this.#previousFocus;this.#previousFocus=null;if(previous?.isConnected)previous.focus({preventScroll:true}); }
136
+ #applySize() {
137
+ const p=this.parameters,s=this.shell.style;
138
+ this.shell.removeAttribute('data-maximized');
139
+ s.width=p.width??'var(--gramlot-window-width,36rem)';s.height=p.height??'var(--gramlot-window-height,24rem)';
140
+ s.minWidth=p.minWidth??'min(220px, calc(100vw - 16px))';s.minHeight=p.minHeight??'min(140px, calc(100dvh - 16px))';
141
+ s.left=p.left??'0px';s.top=p.top??'0px';
142
+ if(this.#geometry){this.#paint(this.#geometry);return;}
143
+ if(!this.#geometry) {
144
+ const r=this.shell.getBoundingClientRect(),w=this.ownerDocument.defaultView;
145
+ if(p.left==null)s.left=`${Math.max(8,(w.document.documentElement.clientWidth-r.width)/2)}px`;
146
+ if(p.top==null)s.top=`${Math.max(8,(w.document.documentElement.clientHeight-r.height)/2)}px`;
147
+ }
148
+ }
149
+ #fit() {
150
+ if(this.#maximized){this.#renderGeometry();return;}
151
+ const r=this.shell.getBoundingClientRect(),w=this.ownerDocument.defaultView;
152
+ const width=Math.min(r.width,Math.max(0,w.document.documentElement.clientWidth-16)),height=Math.min(r.height,Math.max(0,w.document.documentElement.clientHeight-16));
153
+ const rect={left:Math.max(8,Math.min(r.left,w.document.documentElement.clientWidth-width-8)),top:Math.max(8,Math.min(r.top,w.document.documentElement.clientHeight-height-8)),width,height};
154
+ this.#paint(rect);if(!this.#collapsed)this.#geometry=rect;
155
+ else this.#geometry={...this.#geometry,left:rect.left,top:rect.top,width:rect.width};
156
+ }
157
+ #paint(rect) { for(const key of ['left','top','width','height'])this.shell.style[key]=`${rect[key]}px`; }
158
+ #raise() {
159
+ if(this.modal||!this.#open)return;
160
+ // Reserve the page's low stacking levels for layout chrome (splitters/drawers).
161
+ // Modal dialogs and menu popovers remain above these nonmodal windows in the top layer.
162
+ const base=100;
163
+ const peers=[...surfaces.get(this.ownerDocument)].filter(n=>n.opened&&!n.modal&&n!==this);
164
+ peers.sort((a,b)=>Number(a.shell.style.zIndex)-Number(b.shell.style.zIndex)).forEach((n,i)=>n.shell.style.zIndex=String(base+i));
165
+ this.shell.style.zIndex=String(base+peers.length);
166
+ }
167
+ // #geometry always holds the normal expanded rectangle, never viewport size.
168
+ #renderGeometry() {
169
+ const viewport=this.ownerDocument.documentElement;
170
+ const rect=this.#maximized?{left:0,top:0,width:viewport.clientWidth,height:viewport.clientHeight}:{...this.#geometry};
171
+ if(this.#collapsed)rect.height=this.titlebar.getBoundingClientRect().height+2;
172
+ this.shell.toggleAttribute('data-maximized',this.#maximized);
173
+ this.shell.style.minWidth=this.#maximized?'0':this.parameters.minWidth??'min(220px, calc(100vw - 16px))';
174
+ this.shell.style.minHeight=this.#collapsed||this.#maximized?'0':this.parameters.minHeight??'min(140px, calc(100dvh - 16px))';
175
+ this.#paint(rect);
176
+ const movable=this.parameters.movable&&!this.#maximized;
177
+ this.titlebar.toggleAttribute('data-movable',movable);this.titlebar.tabIndex=movable?0:-1;
178
+ this.titlebar.setAttribute('aria-label',movable?'Move window: use arrow keys':this.parameters.title);
179
+ this.resizeButton.hidden=this.#collapsed||this.#maximized||!this.parameters.resizable;
180
+ }
181
+ #setMaximized(value,write) {
182
+ if(!this.#open)return;
183
+ if(value!==this.#maximized){this.#cancelGesture();this.#maximized=value;}
184
+ this.#renderGeometry();
185
+ if(!value)this.#fit();
186
+ this.maximizeButton.textContent=value?'❐':'□';
187
+ this.maximizeButton.setAttribute('aria-label',value?'Restore size':'Maximize window');
188
+ this.maximizeButton.title=value?'Restore size':'Maximize window';
189
+ this.maximizeButton.setAttribute('aria-pressed',String(value));
190
+ if(write){this.parameters.maximized=value;this.#context.writeParameter('maximized',value);}
191
+ }
192
+ #setCollapsed(value,write) {
193
+ if(!this.#open)return;
194
+ if(value!==this.#collapsed) {
195
+ this.#cancelGesture();
196
+ if(value && this.body.contains(this.#activeElement()))this.collapseButton.focus();
197
+ this.#collapsed=value;
198
+ }
199
+ this.body.hidden=value;
200
+ this.shell.toggleAttribute('data-collapsed',value);this.collapseButton.textContent=value?'+':'−';
201
+ this.collapseButton.setAttribute('aria-label',value?'Expand window':'Collapse window');
202
+ this.collapseButton.title=value?'Expand window':'Collapse window';
203
+ this.collapseButton.setAttribute('aria-expanded',String(!value));
204
+ this.#renderGeometry();this.#fit();
205
+ if(write){this.parameters.collapsed=value;this.#context.writeParameter('collapsed',value);}
206
+ }
207
+ async requestClose(reason='application') {
208
+ if(!this.#open || (!this.parameters.closable&&reason!=='application'))return false;
209
+ if(this.#pending)return this.#pending;
210
+ const generation=this.#generation;
211
+ this.status.hidden=true;
212
+ const run=async()=>{
213
+ try {
214
+ const accepted=this.parameters.beforeClose?await this.#context.callLogic(this.parameters.beforeClose,{reason}):true;
215
+ if(typeof accepted!=='boolean')throw new TypeError('beforeClose must return a boolean');
216
+ if(!this.#live||generation!==this.#generation||!this.#open)return false;
217
+ if(accepted)this.#close(true);return accepted;
218
+ } catch(error) {
219
+ if(this.#live&&generation===this.#generation){this.status.textContent='Unable to close: '+error.message;this.status.hidden=false;this.ownerDocument.defaultView.console.error(error);}
220
+ return false;
221
+ } finally {if(generation===this.#generation){this.#pending=null;this.closeButton.disabled=false;this.shell.removeAttribute('aria-busy');}}
222
+ };
223
+ this.closeButton.disabled=true;this.shell.setAttribute('aria-busy','true');
224
+ // Start after assigning the pending request, also for a synchronous guard.
225
+ this.#pending=Promise.resolve().then(run);return this.#pending;
226
+ }
227
+ #close(write) {
228
+ if(!this.#open)return;
229
+ this.#generation++;this.#pending=null;this.#cancelGesture();this.#open=false;
230
+ if(this.shell.open)this.shell.close();this.shell.removeAttribute('aria-busy');this.closeButton.disabled=false;
231
+ this.#restoreFocus();
232
+ if(write){this.parameters.open=false;this.#context.writeParameter('open',false);}
233
+ this.#context.publish('closed',{});
234
+ }
235
+ #startGesture(event,kind) {
236
+ if(event.button!==0||!this.#open||this.#maximized||kind==='move'&&!this.parameters.movable||kind==='resize'&&(!this.parameters.resizable||this.#collapsed))return;
237
+ if(kind==='move'&&event.target.closest('button'))return;
238
+ event.preventDefault();this.#cancelGesture();
239
+ const r=this.shell.getBoundingClientRect();
240
+ this.#gesture={kind,id:event.pointerId,handle:event.currentTarget,x:event.clientX,y:event.clientY,rect:{left:r.left,top:r.top,width:r.width,height:r.height}};
241
+ event.currentTarget.setPointerCapture(event.pointerId);event.currentTarget.focus();
242
+ }
243
+ #moveGesture(event) {
244
+ const g=this.#gesture;if(!g||g.id!==event.pointerId)return;
245
+ this.#adjust(g.rect,event.clientX-g.x,event.clientY-g.y,g.kind);
246
+ }
247
+ #adjust(start,dx,dy,kind) {
248
+ const rect={...start},w=this.ownerDocument.defaultView;
249
+ if(kind==='move'){rect.left+=dx;rect.top+=dy;}
250
+ else {
251
+ const style=w.getComputedStyle(this.shell);
252
+ rect.width=Math.max(parseFloat(style.minWidth)||0,rect.width+dx);
253
+ rect.height=Math.max(parseFloat(style.minHeight)||0,rect.height+dy);
254
+ }
255
+ rect.width=Math.min(rect.width,Math.max(0,w.document.documentElement.clientWidth-16));rect.height=Math.min(rect.height,Math.max(0,w.document.documentElement.clientHeight-16));
256
+ rect.left=Math.max(8,Math.min(rect.left,w.document.documentElement.clientWidth-rect.width-8));rect.top=Math.max(8,Math.min(rect.top,w.document.documentElement.clientHeight-rect.height-8));
257
+ this.#paint(rect);
258
+ if(this.#collapsed){this.#geometry={...this.#geometry,left:rect.left,top:rect.top,width:rect.width};}
259
+ else this.#geometry=rect;
260
+ }
261
+ #endGesture(event,commit) {
262
+ const g=this.#gesture;if(!g||g.id!==event.pointerId)return;
263
+ this.#gesture=null;if(g.handle.hasPointerCapture(g.id))g.handle.releasePointerCapture(g.id);
264
+ if(commit)this.#commitGeometry(g.kind);else {this.#paint(g.rect);if(!this.#collapsed)this.#geometry=g.rect;else this.#geometry={...this.#geometry,left:g.rect.left,top:g.rect.top,width:g.rect.width};}
265
+ }
266
+ #cancelGesture() { if(this.#gesture)this.#endGesture({pointerId:this.#gesture.id},false); }
267
+ #commitGeometry(kind) {
268
+ const r=this.shell.getBoundingClientRect();
269
+ for(const key of kind==='move'?['left','top']:['width','height']) {
270
+ const value=`${r[key]}px`;this.#context.writeParameter(key,value);
271
+ }
272
+ }
273
+ #keyGeometry(event,kind) {
274
+ if(event.target!==event.currentTarget||!['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(event.key))return;
275
+ if(this.#maximized||kind==='move'&&!this.parameters.movable||kind==='resize'&&(!this.parameters.resizable||this.#collapsed))return;
276
+ event.preventDefault();event.stopPropagation();
277
+ const r=this.shell.getBoundingClientRect(),step=event.shiftKey?1:10;
278
+ this.#adjust({left:r.left,top:r.top,width:r.width,height:r.height},event.key==='ArrowLeft'?-step:event.key==='ArrowRight'?step:0,event.key==='ArrowUp'?-step:event.key==='ArrowDown'?step:0,kind);
279
+ this.#commitGeometry(kind);
280
+ }
281
+ }