@gramlot/gramlot 0.3.7 → 0.3.9

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 (71) hide show
  1. package/dist/components/editors.js +116527 -0
  2. package/dist/components/inputs.js +24507 -0
  3. package/dist/components/layout.js +1402 -0
  4. package/dist/components/tree.js +24538 -0
  5. package/dist/components/typst.js +4 -0
  6. package/dist/gramlot.js +1442 -625
  7. package/dist/gramlot.min.js +27 -405
  8. package/dist/runtime-notices.json +208 -0
  9. package/dist/typst-worker-source.js +4 -0
  10. package/package.json +36 -3
  11. package/src/binding/hooks.js +14 -0
  12. package/src/binding/providers.js +4 -0
  13. package/src/binding/remote-resolver.js +52 -0
  14. package/src/binding/remote.js +2 -0
  15. package/src/binding/router.js +11 -4
  16. package/src/binding/rpc-resolver.js +14 -93
  17. package/src/binding/runtime.js +10 -4
  18. package/src/components/bases.js +1 -0
  19. package/src/components/border-container.js +46 -23
  20. package/src/components/buttons.js +3 -0
  21. package/src/components/choice-editor.js +17 -3
  22. package/src/components/choices.js +3 -2
  23. package/src/components/code-mirror-engine.js +91 -0
  24. package/src/components/code-mirror.js +88 -0
  25. package/src/components/editor-options.d.ts +9 -0
  26. package/src/components/editor-options.js +21 -0
  27. package/src/components/editors.js +10 -0
  28. package/src/components/html-document.js +56 -0
  29. package/src/components/html-editor.js +68 -0
  30. package/src/components/html-preview.js +33 -0
  31. package/src/components/inputs.js +2 -2
  32. package/src/components/jodit-engine.js +89 -0
  33. package/src/components/markdown-codec.js +35 -0
  34. package/src/components/markdown-document.js +14 -0
  35. package/src/components/markdown-editor.js +68 -0
  36. package/src/components/prose-mirror-engine.js +65 -0
  37. package/src/components/registry.js +6 -4
  38. package/src/components/tree.js +350 -0
  39. package/src/components/typst-client.js +38 -0
  40. package/src/components/typst-preview.js +88 -0
  41. package/src/components/typst-worker.js +49 -0
  42. package/src/components/typst.js +4 -0
  43. package/src/filesystem.d.ts +22 -0
  44. package/src/filesystem.js +122 -0
  45. package/src/ide-documents.js +153 -0
  46. package/src/ide-runtime.d.ts +18 -0
  47. package/src/ide-runtime.js +238 -0
  48. package/src/index-page-runtime.d.ts +7 -8
  49. package/src/index-page-runtime.js +100 -396
  50. package/src/index.d.ts +7 -1
  51. package/src/index.js +5 -1
  52. package/src/navigation-resolver.d.ts +6 -0
  53. package/src/navigation-resolver.js +60 -0
  54. package/src/renderer/attributes.js +2 -1
  55. package/src/renderer/drag-drop-policy.js +48 -0
  56. package/src/renderer/drag-drop.js +213 -0
  57. package/src/renderer/drag-preparation.js +33 -0
  58. package/src/renderer/gramlot-renderer.d.ts +18 -0
  59. package/src/renderer/gramlot-renderer.js +41 -2
  60. package/src/server/frame-page.d.ts +12 -0
  61. package/src/server/frame-page.js +23 -0
  62. package/src/server/gramlot-server.js +2 -1
  63. package/src/server/index-page.d.ts +10 -14
  64. package/src/server/index-page.js +26 -95
  65. package/src/server/page.d.ts +7 -0
  66. package/src/server/page.js +5 -0
  67. package/src/view/button.js +2 -1
  68. package/src/view/controls.js +7 -11
  69. package/src/view/events.js +4 -8
  70. package/src/view/html.js +6 -1
  71. package/tools/gramlot-tools-inspector.js +16 -9
@@ -0,0 +1,52 @@
1
+ import {BagResolver} from '@genrojs/bag';
2
+
3
+ /** Shared asynchronous endpoint cache; subclasses own request scheduling and lifetime. */
4
+ export class RemoteResolver extends BagResolver {
5
+ static classKwargs = {...BagResolver.classKwargs, asBag: false};
6
+ constructor({cacheTime, onError}) {
7
+ super({cacheTime: cacheTime ?? -1});
8
+ this.onError = onError;
9
+ this.loading = null;
10
+ this.loaded = false;
11
+ this.writing = false;
12
+ }
13
+ resolve({static: isStatic = false} = {}) {
14
+ if (!isStatic && !this.closed && !this.loading && !this.writing && this.expired) this.refresh();
15
+ return this.cachedValue;
16
+ }
17
+ refresh() {
18
+ if (this.closed) return null;
19
+ const loading = this.startLoad(request => this.#load(request));
20
+ if (loading === null) return null;
21
+ const settle = () => { if (this.loading === loading) this.loading = null; };
22
+ loading.then(settle, settle);
23
+ this.loading = loading;
24
+ loading.catch(error => { if (error?.name !== 'AbortError') this.onError(error); });
25
+ return loading;
26
+ }
27
+ resolveSync(options) { return super.resolve(options); }
28
+ prepareValue(value) { return value; }
29
+ #fingerprint() {
30
+ const kwargs = {...this._kw};
31
+ for (const [name, value] of Object.entries(this.node?.attr ?? {})) {
32
+ if (!this.constructor.internalParams.has(name)) kwargs[name] = value;
33
+ }
34
+ return this._computeEffectiveFingerprint(kwargs);
35
+ }
36
+ async #load(request) {
37
+ if (this.closed) return undefined;
38
+ const fingerprint = this.#fingerprint();
39
+ const received = await this.loadAsync(request);
40
+ if (this.closed || request.ignored) return undefined;
41
+ const value = this.prepareValue(received);
42
+ this._lastUpdate = Date.now();
43
+ this._lastEffectiveFingerprint = fingerprint;
44
+ this.loaded = true;
45
+ this.writing = true;
46
+ try {
47
+ if (this.node) this.node.setValue(value, this.cacheTime !== 0);
48
+ else this.cachedValue = value;
49
+ } finally { this.writing = false; }
50
+ return value;
51
+ }
52
+ }
@@ -1,3 +1,4 @@
1
+ import {invokeHook} from './hooks.js';
1
2
  import {toTytx} from '@genrojs/tytx';
2
3
  import {TriggerTimers} from './providers.js';
3
4
 
@@ -106,6 +107,7 @@ export class RemoteBinding {
106
107
  }
107
108
 
108
109
  #inline(attr, code, source, params) {
110
+ if (attr === '_onRemote') return invokeHook(this.binding.runtime, this.node, attr, code, params);
109
111
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
110
112
  }
111
113
  }
@@ -27,19 +27,23 @@ export class DataRegistration {
27
27
  #recipient;
28
28
  #order;
29
29
  #active = true;
30
+ #subtree;
30
31
 
31
- constructor(router, {path, attr, recipient, order}) {
32
+ constructor(router, {path, attr, recipient, order, subtree = false}) {
32
33
  this.#router = router;
33
34
  this.#path = path;
34
35
  this.#attr = attr;
35
36
  this.#recipient = recipient;
36
37
  this.#order = order;
38
+ this.#subtree = subtree;
37
39
  }
38
40
 
39
41
  get router() { return this.#router; }
40
42
  get path() { return this.#path; }
41
43
  get attr() { return this.#attr; }
42
44
  get recipient() { return this.#recipient; }
45
+ /** Store registration: structural, value and attribute events throughout the subtree. */
46
+ get subtree() { return this.#subtree; }
43
47
  get active() { return this.#active; }
44
48
  /** Registration order, which is also the delivery order of one event. */
45
49
  get order() { return this.#order; }
@@ -82,8 +86,10 @@ export class DataRouter {
82
86
  /** Active registrations. */
83
87
  get size() { return this.#size; }
84
88
 
85
- /** Register `recipient` on the absolute Data `path` (without `_root_`), optionally on its attribute `attr`. */
86
- register({path, attr = null, recipient}) {
89
+ /** Register on an absolute Data path, optionally on an attribute.
90
+ * `subtree` includes descendant attribute events for Bag-backed components.
91
+ */
92
+ register({path, attr = null, recipient, subtree = false}) {
87
93
  if (typeof path !== 'string' || path === '') throw new TypeError(`A Data registration requires a path: ${path}`);
88
94
  let route = this.#root;
89
95
  for (const segment of path.split('.')) {
@@ -95,7 +101,7 @@ export class DataRouter {
95
101
  route = next;
96
102
  }
97
103
  this.#order += 1;
98
- const registration = new DataRegistration(this, {path, attr, recipient, order: this.#order});
104
+ const registration = new DataRegistration(this, {path, attr, recipient, order: this.#order, subtree});
99
105
  route.registrations.add(registration);
100
106
  this.#routes.set(registration, route);
101
107
  this.#size += 1;
@@ -176,6 +182,7 @@ export class DataRouter {
176
182
  */
177
183
  #accepts(registration, level, event) {
178
184
  const {evt} = event;
185
+ if (registration.subtree) return level !== 'container' || evt !== 'upd_attrs';
179
186
  if (registration.attr === null) {
180
187
  if (evt === 'upd_attrs') return false;
181
188
  return !(level === 'child' && event.fired);
@@ -1,4 +1,4 @@
1
- import {BagResolver} from '@genrojs/bag';
1
+ import {RemoteResolver} from './remote-resolver.js';
2
2
 
3
3
  /**
4
4
  * The resolver a `dataRemote` installs on its Data node: the value is the answer of the endpoint
@@ -29,114 +29,35 @@ import {BagResolver} from '@genrojs/bag';
29
29
  * nothing: `loading` rejects with its error and `onError` receives it. A load aborted by the removal of the
30
30
  * node writes nothing, even when its answer had already arrived; a load ignored by `cancel()` writes nothing.
31
31
  */
32
- export class RpcResolver extends BagResolver {
33
- static classKwargs = {...BagResolver.classKwargs, asBag: false};
34
- static internalParams = new Set([...BagResolver.internalParams, 'binding', 'method', 'params', 'onCalling', 'onError',
35
- 'sync']);
36
-
32
+ export class RpcResolver extends RemoteResolver {
33
+ static internalParams = new Set([...RemoteResolver.internalParams, 'binding', 'method', 'params', 'onCalling', 'onError', 'sync']);
37
34
  constructor({binding, method, params, cacheTime, onCalling = null, onError, sync = false}) {
38
- // null: resolve once, as a negative cacheTime.
39
- super({cacheTime: cacheTime ?? -1});
40
- // The NodeBinding of the `dataRemote` node.
35
+ super({cacheTime, onError});
41
36
  this.binding = binding;
42
- // A read waits for the answer of a synchronous call.
43
37
  this.sync = sync;
44
38
  this.method = method;
45
39
  this.params = params;
46
40
  this.onCalling = onCalling;
47
- // Receives the error of a failed load, never an abort.
48
- this.onError = onError;
49
- // The promise of the load in flight or waiting, or null.
50
- this.loading = null;
51
- // A load has written its value; the loaded value is being written.
52
- this.loaded = false;
53
- this.writing = false;
54
41
  }
55
-
56
- /**
57
- * The current value. With `sync` an expired read calls the endpoint and returns its value (BagResolver
58
- * `resolve`, then `load`); without, it starts the load and returns the current value. A static read, or
59
- * a read during a load or its write, returns the current value.
60
- */
42
+ get closed() { return this.binding.closed; }
61
43
  resolve(options = {}) {
62
- const {static: isStatic = false} = options;
63
- if (isStatic || this.loading || this.writing) return this.cachedValue;
64
- if (!this.sync) {
65
- if (this.expired) this.refresh();
66
- return this.cachedValue;
67
- }
44
+ if (!this.sync) return super.resolve(options);
45
+ if (options.static || this.loading || this.writing) return this.cachedValue;
68
46
  if (this.expired && !this.binding.node.requests.calling(this.onCalling)) return this.cachedValue;
69
- return super.resolve(options);
47
+ // A synchronous read uses BagResolver's normal cache and load path.
48
+ return super.resolveSync(options);
70
49
  }
71
-
72
- /** The synchronous call of a `sync` read: BagResolver `resolve` stores the value it returns. */
73
50
  load() {
74
51
  let value;
75
- try {
76
- value = this.binding.callSync('data', this.method, this.params);
77
- } catch (error) {
78
- this.onError(error);
79
- }
52
+ try { value = this.binding.callSync('data', this.method, this.params); }
53
+ catch (error) { this.onError(error); }
80
54
  this.loaded = true;
81
55
  return value;
82
56
  }
83
-
84
- /**
85
- * Start a load and write its value on the node, with the Data event unless `cacheTime` is 0; returns
86
- * `loading`, which settles with the written value, or undefined when nothing was written. A false
87
- * `_onCalling` starts no load and returns null.
88
- */
89
- refresh() {
57
+ startLoad(perform) {
90
58
  const requests = this.binding.node.requests;
91
59
  if (!requests.calling(this.onCalling)) return null;
92
- const loading = requests.submit(this.method, this.params, request => this.#load(request));
93
- const settle = () => {
94
- if (this.loading === loading) this.loading = null;
95
- };
96
- loading.then(settle, settle);
97
- this.loading = loading;
98
- // A load nobody awaits: its failure reaches `onError`, an abort is not a failure.
99
- loading.catch(error => {
100
- if (error?.name !== 'AbortError') this.onError(error);
101
- });
102
- return loading;
103
- }
104
-
105
- /**
106
- * The fingerprint of the parameters of a read without call kwargs, as `BagResolver.resolve` computes it:
107
- * the kwargs of the resolver and the attributes of its node that are not internal.
108
- */
109
- #fingerprint() {
110
- const kwargs = {...this._kw};
111
- for (const [name, value] of Object.entries(this.node?.attr ?? {})) {
112
- if (!this.constructor.internalParams.has(name)) kwargs[name] = value;
113
- }
114
- return this._computeEffectiveFingerprint(kwargs);
115
- }
116
-
117
- /** The asynchronous call of the endpoint with the params given at construction; the read kwargs are not sent. */
118
- async #load(request) {
119
- const binding = this.binding;
120
- // A waiting load of a node that left the Source sends nothing.
121
- if (binding.closed) return undefined;
122
- // The parameters of this load, as `resolve` takes them before a load: the value answers these.
123
- const fingerprint = this.#fingerprint();
124
- const value = await binding.call('data', request);
125
- if (binding.closed || request.ignored) return undefined;
126
- // The cache time and the fingerprint of the parameters of BagResolver: no public member records a load made
127
- // outside `resolve`. A `sync` read loads through `resolve`, which records both and does not write them here;
128
- // this asynchronous load is a debt of the async-resolvers plan. Without the fingerprint, the first explicit
129
- // read after this load finds another one, loads again and sends a call the cache should have answered.
130
- this._lastUpdate = Date.now();
131
- this._lastEffectiveFingerprint = fingerprint;
132
- this.loaded = true;
133
- this.writing = true;
134
- try {
135
- if (this.node) this.node.setValue(value, this.cacheTime !== 0);
136
- else this.cachedValue = value;
137
- } finally {
138
- this.writing = false;
139
- }
140
- return value;
60
+ return requests.submit(this.method, this.params, perform);
141
61
  }
62
+ loadAsync(request) { return this.binding.call('data', request); }
142
63
  }
@@ -3,6 +3,7 @@ import {DataRouter} from './router.js';
3
3
  import {DataInstaller} from './installation.js';
4
4
  import {ControllerProvider, FormulaProvider, RemoteProvider, RpcProvider} from './providers.js';
5
5
  import {InlineCompiler} from './inline.js';
6
+ import {isLogicMethod, callLogic} from './hooks.js';
6
7
  import {RemoteBinding} from './remote.js';
7
8
  import {AskDialog} from './ask-dialog.js';
8
9
  import {randomId} from '../random-id.js';
@@ -412,6 +413,14 @@ export class NodeBinding {
412
413
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
413
414
  if (!dataElement && typeof node.getAttr('remote') === 'string') this.#remote ??= new RemoteBinding(this);
414
415
  const remoteDependencies = new Set();
416
+ if (node._getMeta('gramlot_component')?.bagStore) {
417
+ const storepath = node.getAttr('storepath');
418
+ if (typeof storepath !== 'string' || !storepath || /^[\^=]/.test(storepath) || storepath.includes('?')) {
419
+ throw new TypeError('storepath requires a plain Bag data path');
420
+ }
421
+ const path = node.absDatapath(storepath);
422
+ this.#registrations.push(this.runtime.router.register({path, recipient: this, subtree: true}));
423
+ }
415
424
  const timingDependencies = this.remote ? pointerDependencies(node, node.getAttr('_timing')) : new Set();
416
425
  if (this.remote) for (const [name, raw] of Object.entries(node.getAttr())) {
417
426
  if (name.startsWith('remote_')) for (const dependency of pointerDependencies(node, raw)) remoteDependencies.add(dependency);
@@ -444,10 +453,7 @@ export class NodeBinding {
444
453
  if (typeof handler !== 'string' || !handler) throw new TypeError(`${name} requires a handler`);
445
454
  return payload => {
446
455
  if (this.closed) return;
447
- if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
448
- const {group, method} = this.runtime.logicRegistry.resolve(handler, node);
449
- return method.call(group, node, payload);
450
- }
456
+ if (isLogicMethod(handler)) return callLogic(this.runtime, node, handler, payload);
451
457
  const [, attrs] = node.rootBuilder.runtimeValues(node);
452
458
  const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) =>
453
459
  !key.startsWith('subscribe_') && !key.startsWith('selfsubscribe_')));
@@ -33,6 +33,7 @@ export function controlElement(HTMLElement) {
33
33
  }
34
34
  setPageContext(context) { this.pageContext = context; }
35
35
  releaseControl() {}
36
+ get liveWrites() { return this.control.localName === 'textarea' || ['text', 'password', 'range', 'color'].includes(this.control.type); }
36
37
  validateCandidate(value, accept) {
37
38
  accept(value);
38
39
  return {ok:true, value, isCurrent:() => this.pageContext.isActive()};
@@ -116,6 +116,7 @@ export const BorderContainer = defineComponent({
116
116
  grid-template-columns:var(--left,0px) minmax(0,1fr) var(--right,0px);
117
117
  grid-template-rows:var(--top,0px) minmax(0,1fr) var(--bottom,0px);
118
118
  grid-template-areas:'top top top' 'left center right' 'bottom bottom bottom'}
119
+ .control-box[data-drawer-motion]{transition:grid-template-columns var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out),grid-template-rows var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out)}
119
120
  .control-box[data-design=sidebar]{grid-template-areas:'left top right' 'left center right' 'left bottom right'}
120
121
  .region{position:relative;min-width:0;min-height:0;overflow:visible}
121
122
  .viewport{height:100%;min-width:0;min-height:0;overflow:auto}
@@ -123,7 +124,10 @@ export const BorderContainer = defineComponent({
123
124
  .region[data-side=right]>.viewport{padding-left:var(--region-splitter,0px)}
124
125
  .region[data-side=top]>.viewport{padding-bottom:var(--region-splitter,0px)}
125
126
  .region[data-side=bottom]>.viewport{padding-top:var(--region-splitter,0px)}
126
- .viewport[hidden]{display:none}::slotted(*){min-height:0}
127
+ .viewport[hidden]{display:none}
128
+ .control-box[data-drawer-motion] .viewport{transition:opacity var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out);opacity:1;visibility:visible}
129
+ .control-box[data-drawer-motion] .viewport[hidden]{display:block;opacity:0;visibility:hidden;
130
+ transition:opacity var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out),visibility 0s var(--gramlot-drawer-duration,.24s)}::slotted(*){min-height:0}
127
131
  .separator{position:absolute;z-index:2;touch-action:none;user-select:none;background:var(--gramlot-splitter-background,var(--gramlot-border-control,#aaa))}
128
132
  .separator[data-axis=x]{top:0;bottom:0;width:var(--gramlot-splitter-size,1px);cursor:col-resize}
129
133
  .separator[data-axis=y]{left:0;right:0;height:var(--gramlot-splitter-size,1px);cursor:row-resize}
@@ -140,19 +144,19 @@ export const BorderContainer = defineComponent({
140
144
  .separator:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:1px}
141
145
  .drawer{position:absolute;z-index:3;cursor:pointer;appearance:none;font:inherit;
142
146
  font-size:var(--gramlot-drawer-font-size,11px);line-height:1.2;white-space:nowrap;
143
- --drawer-background:var(--gramlot-drawer-background,#777);
147
+ --drawer-background:var(--gramlot-drawer-background,var(--gramlot-text-secondary,#777));
144
148
  color:var(--gramlot-drawer-color,hsl(from var(--drawer-background) 0 0 clamp(20,calc((60 - l) * 1000),100)));
145
149
  background:var(--drawer-background);outline:none;
146
150
  border:0;border-radius:0;box-shadow:none;
147
151
  min-width:0;min-height:0;padding:0;
148
- opacity:var(--gramlot-drawer-opacity,.45);
149
- transition:opacity var(--gramlot-drawer-duration,.16s) var(--gramlot-drawer-easing,ease-out),
150
- transform var(--gramlot-drawer-duration,.16s) var(--gramlot-drawer-easing,ease-out),
151
- width var(--gramlot-drawer-duration,.16s) var(--gramlot-drawer-easing,ease-out),
152
- height var(--gramlot-drawer-duration,.16s) var(--gramlot-drawer-easing,ease-out),
153
- max-width var(--gramlot-drawer-duration,.16s) var(--gramlot-drawer-easing,ease-out),
154
- max-height var(--gramlot-drawer-duration,.16s) var(--gramlot-drawer-easing,ease-out),
155
- margin var(--gramlot-drawer-duration,.16s) var(--gramlot-drawer-easing,ease-out)}
152
+ opacity:var(--gramlot-drawer-opacity,.20);
153
+ transition:opacity var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out),
154
+ transform var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out),
155
+ width var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out),
156
+ height var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out),
157
+ max-width var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out),
158
+ max-height var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out),
159
+ margin var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out)}
156
160
  .drawer:hover,.drawer:focus-visible{opacity:var(--gramlot-drawer-active-opacity,1)}
157
161
  [data-axis=x]>.drawer[data-resizable]{cursor:col-resize}
158
162
  [data-axis=y]>.drawer[data-resizable]{cursor:row-resize}
@@ -162,18 +166,18 @@ export const BorderContainer = defineComponent({
162
166
  .separator>.drawer:is([data-labelled],[data-icon]):hover{transform:scale(var(--gramlot-drawer-label-hover-scale,1.04))}
163
167
  }
164
168
 
165
- [data-axis=x]>.drawer{--drawer-closed-width:var(--gramlot-drawer-thickness,4px);--drawer-closed-height:var(--gramlot-drawer-length,28px);
166
- top:50%;margin-top:calc(var(--gramlot-drawer-length,28px) / -2);width:var(--drawer-closed-width);height:var(--drawer-closed-height)}
167
- [data-axis=y]>.drawer{--drawer-closed-width:var(--gramlot-drawer-length,28px);--drawer-closed-height:var(--gramlot-drawer-thickness,4px);
168
- left:50%;margin-left:calc(var(--gramlot-drawer-length,28px) / -2);width:var(--drawer-closed-width);height:var(--drawer-closed-height)}
169
+ [data-axis=x]>.drawer{--drawer-closed-width:var(--gramlot-drawer-thickness,6px);--drawer-closed-height:var(--gramlot-drawer-length,40px);
170
+ top:50%;margin-top:calc(var(--gramlot-drawer-length,40px) / -2);width:var(--drawer-closed-width);height:var(--drawer-closed-height)}
171
+ [data-axis=y]>.drawer{--drawer-closed-width:var(--gramlot-drawer-length,40px);--drawer-closed-height:var(--gramlot-drawer-thickness,6px);
172
+ left:50%;margin-left:calc(var(--gramlot-drawer-length,40px) / -2);width:var(--drawer-closed-width);height:var(--drawer-closed-height)}
169
173
  .drawer::after{content:'';position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
170
174
  width:max(100%,var(--gramlot-touch-target,var(--gramlot-drawer-hit-target,12px)));height:max(100%,var(--gramlot-touch-target,var(--gramlot-drawer-hit-target,12px)))}
171
175
  .drawer{--drawer-reveal-width:var(--gramlot-drawer-reveal-width,var(--drawer-content-width,0px));--drawer-reveal-height:var(--gramlot-drawer-reveal-height,var(--drawer-content-height,0px))}
172
176
  .drawer[data-labelled]{opacity:var(--gramlot-drawer-active-opacity,1)}
173
- [data-side=left]>.drawer{transform-origin:left center;left:100%;border-left:0;border-radius:0 var(--gramlot-radius-sm,4px) var(--gramlot-radius-sm,4px) 0}
174
- [data-side=right]>.drawer{transform-origin:right center;right:100%;border-right:0;border-radius:var(--gramlot-radius-sm,4px) 0 0 var(--gramlot-radius-sm,4px)}
175
- [data-side=top]>.drawer{transform-origin:center top;top:100%;border-top:0;border-radius:0 0 var(--gramlot-radius-sm,4px) var(--gramlot-radius-sm,4px)}
176
- [data-side=bottom]>.drawer{transform-origin:center bottom;bottom:100%;border-bottom:0;border-radius:var(--gramlot-radius-sm,4px) var(--gramlot-radius-sm,4px) 0 0}
177
+ [data-side=left]>.drawer{transform-origin:left center;left:100%;border-left:0;border-radius:0 calc(var(--gramlot-radius-sm,4px) * 2) calc(var(--gramlot-radius-sm,4px) * 2) 0}
178
+ [data-side=right]>.drawer{transform-origin:right center;right:100%;border-right:0;border-radius:calc(var(--gramlot-radius-sm,4px) * 2) 0 0 calc(var(--gramlot-radius-sm,4px) * 2)}
179
+ [data-side=top]>.drawer{transform-origin:center top;top:100%;border-top:0;border-radius:0 0 calc(var(--gramlot-radius-sm,4px) * 2) calc(var(--gramlot-radius-sm,4px) * 2)}
180
+ [data-side=bottom]>.drawer{transform-origin:center bottom;bottom:100%;border-bottom:0;border-radius:calc(var(--gramlot-radius-sm,4px) * 2) calc(var(--gramlot-radius-sm,4px) * 2) 0 0}
177
181
  .drawer:is([data-labelled],[data-icon]){width:max-content;height:max-content;padding:0}
178
182
  .drawer-viewport{display:block;overflow:hidden;min-width:0;min-height:0;max-width:inherit;max-height:inherit}
179
183
  .drawer-content{display:flex;width:max-content;height:max-content;align-items:center;gap:var(--gramlot-drawer-content-gap,4px);box-sizing:border-box;
@@ -187,7 +191,7 @@ export const BorderContainer = defineComponent({
187
191
  .separator[data-axis=x]>.drawer.drawer-rotated{margin-top:0;translate:0 -50%}
188
192
  /* Icon and caption reveal as one unit; the resting grip stays thin. */
189
193
  .separator>.drawer.drawer-reveal:is([data-labelled],[data-icon]){--drawer-open:var(--gramlot-drawer-reveal,0);
190
- opacity:calc(var(--gramlot-drawer-opacity,.45) + (var(--gramlot-drawer-active-opacity,1) - var(--gramlot-drawer-opacity,.45)) * var(--drawer-open));
194
+ opacity:calc(var(--gramlot-drawer-opacity,.20) + (var(--gramlot-drawer-active-opacity,1) - var(--gramlot-drawer-opacity,.20)) * var(--drawer-open));
191
195
  display:grid;grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr);
192
196
  min-width:0;min-height:0;
193
197
  max-width:calc(var(--drawer-closed-width) + (var(--drawer-reveal-width) - var(--drawer-closed-width)) * var(--drawer-open));
@@ -195,12 +199,12 @@ export const BorderContainer = defineComponent({
195
199
  .separator[data-axis=x]>.drawer.drawer-reveal{margin-top:0;translate:0 -50%}
196
200
  [data-axis=y]>.drawer:is([data-labelled],[data-icon]){margin-left:0;translate:-50% 0}
197
201
  .drawer-reveal .drawer-content{opacity:var(--drawer-open);
198
- transition:opacity var(--gramlot-drawer-duration,.16s) var(--gramlot-drawer-easing,ease-out)}
202
+ transition:opacity var(--gramlot-drawer-duration,.24s) var(--gramlot-drawer-easing,ease-out)}
199
203
  @media (hover:none),(pointer:coarse){.separator>.drawer.drawer-reveal:is([data-labelled],[data-icon]){--drawer-open:1}}
200
204
  @media (hover:hover){.separator>.drawer.drawer-reveal:is([data-labelled],[data-icon]):hover{--drawer-open:1;transform:scale(var(--gramlot-drawer-label-hover-scale,1.04))}}
201
205
  .separator>.drawer:is([data-labelled],[data-icon]):is(:active,[data-active]){transform:scale(var(--gramlot-drawer-label-hover-scale,1.04))}
202
206
  .separator>.drawer.drawer-reveal:is([data-labelled],[data-icon]):is(:focus-visible,:active,[data-active]){--drawer-open:1;transform:scale(var(--gramlot-drawer-label-hover-scale,1.04))}
203
- @media (prefers-reduced-motion:reduce){.drawer,.drawer-reveal .drawer-content{transition:none}}
207
+ @media (prefers-reduced-motion:reduce){.drawer,.drawer-reveal .drawer-content,.control-box[data-drawer-motion],.control-box[data-drawer-motion] .viewport{transition:none!important}}
204
208
  .drawer[hidden],.separator[hidden]{display:none}
205
209
  .drag-cover{position:absolute;inset:0;z-index:4;display:none}
206
210
  :host{position:relative}.drag-cover[data-active]{display:block}`;
@@ -236,7 +240,7 @@ export const BorderContainer = defineComponent({
236
240
  drawer.addEventListener('click', evt => {
237
241
  evt.stopPropagation();
238
242
  if (state.suppressDrawerClick && evt.detail !== 0) { state.suppressDrawerClick = false; return; }
239
- state.closed = !state.closed; this.#render(side);
243
+ state.closed = !state.closed; this.#render(side, true);
240
244
  state.config.onToggle?.(evt, !state.closed);
241
245
  });
242
246
  }
@@ -245,6 +249,13 @@ export const BorderContainer = defineComponent({
245
249
  }
246
250
  this.cover = doc.createElement('div'); this.cover.className = 'drag-cover';
247
251
  this.shadowRoot.append(style, this.cover);
252
+ this.control.addEventListener('transitionend', event => {
253
+ if (event.target !== this.control) return;
254
+ this.control.removeAttribute('data-drawer-motion');
255
+ for (const [side, state] of this.#regions) {
256
+ state.separator?.setAttribute('aria-valuenow', String(Math.round(this.#extent(side))));
257
+ }
258
+ });
248
259
  this.#observer = new doc.defaultView.MutationObserver(() => this.#sync());
249
260
  }
250
261
  connectedCallback() {
@@ -306,11 +317,22 @@ export const BorderContainer = defineComponent({
306
317
  }
307
318
  this.#render(side);
308
319
  }
309
- #render(side) {
320
+ #render(side, animate = false) {
310
321
  const state = this.#regions.get(side), c = state.config;
311
322
  const visible = !!c && !c.hidden && !state.closed;
312
323
  const previous = state.visibility;
313
324
  state.visibility = c ? {open: visible, drawer: !!c.drawer} : null;
325
+ // Retain the viewport through the closing transition, but disable interaction immediately.
326
+ state.viewport.inert = !visible;
327
+ if (previous && previous.open !== visible) {
328
+ this.control.toggleAttribute('data-drawer-motion', !!c?.drawer && animate && !this.#drag);
329
+ if (this.control.hasAttribute('data-drawer-motion')) {
330
+ const durations = this.ownerDocument.defaultView.getComputedStyle(this.control).transitionDuration;
331
+ if (durations.split(',').every(duration => Number.parseFloat(duration) === 0)) {
332
+ this.control.removeAttribute('data-drawer-motion');
333
+ }
334
+ }
335
+ }
314
336
  state.viewport.hidden = !visible;
315
337
  if (side === 'center') return;
316
338
  this.control.style.setProperty(`--${side}`, visible ? state.size : '0px');
@@ -335,6 +357,7 @@ export const BorderContainer = defineComponent({
335
357
  }
336
358
  #extent(side) { const box = this.#regions.get(side).cell.getBoundingClientRect(); return horizontal(side) ? box.height : box.width; }
337
359
  #resize(side, desired) {
360
+ this.control.removeAttribute('data-drawer-motion');
338
361
  const state = this.#regions.get(side), c = state.config;
339
362
  const opposite = {left:'right',right:'left',top:'bottom',bottom:'top'}[side];
340
363
  const box = this.control.getBoundingClientRect();
@@ -26,6 +26,9 @@ function Command(HTMLElement) {
26
26
  min-height:max(var(--gramlot-field-height,28px),var(--gramlot-touch-target,0px));
27
27
  padding:var(--gramlot-button-padding,.25em .65em);cursor:pointer}
28
28
  button:hover:not(:disabled){background:var(--gramlot-button-hover,var(--gramlot-field-readonly-background,#eee))}
29
+ :host(.button--quiet) button{background:transparent;color:var(--gramlot-action,CanvasText);border-color:transparent}
30
+ :host(.button--quiet) button:hover:not(:disabled){background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,CanvasText);border-color:transparent}
31
+ button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:2px}
29
32
  button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none}
30
33
  .led{display:inline-block;width:.6em;height:.6em;border-radius:50%;background:var(--gramlot-button-led-off,#888)}
31
34
  [aria-pressed=true] .led{background:var(--gramlot-button-led-on,#2b9a46)}
@@ -1,3 +1,4 @@
1
+ import {Bag} from '@genrojs/bag';
1
2
  import {NativeControl} from './bases.js';
2
3
  import {parseChoices} from './choices.js';
3
4
  import {positionPopup} from './popup.js';
@@ -13,6 +14,7 @@ export function ChoiceEditor(HTMLElement) {
13
14
  #dirty = false;
14
15
  #picked = null;
15
16
  #source;
17
+ #separator;
16
18
  #cleanup;
17
19
  constructor() {
18
20
  super();
@@ -74,8 +76,9 @@ export function ChoiceEditor(HTMLElement) {
74
76
  get active() { return this.isConnected && this.pageContext?.isActive(); }
75
77
  projectAttributes(attrs, adapt) {
76
78
  const rest = super.projectAttributes(attrs, adapt);
77
- const source = this.parameters.callback ?? this.parameters.values;
78
- const changed = source !== this.#source;
79
+ const source = this.parameters.store ?? this.parameters.callback ?? this.parameters.values;
80
+ const changed = source !== this.#source || this.parameters.separator !== this.#separator;
81
+ this.#separator = this.parameters.separator;
79
82
  this.#source = source;
80
83
  this.toggle.disabled = this.locked;
81
84
  if (changed || this.locked) this.closeChoices();
@@ -199,7 +202,18 @@ ChoiceEditor.parameters = {...NativeControl.parameters,
199
202
  export function localChoices(Base) {
200
203
  return class extends Base {
201
204
  loadChoices(keywords) {
202
- const rows = parseChoices(this.parameters.values ?? '');
205
+ let rows;
206
+ if (this.parameters.store != null) {
207
+ if (!(this.parameters.store instanceof Bag)) throw new TypeError('store must be a Bag');
208
+ if (this.parameters.values) throw new TypeError('store and values are mutually exclusive');
209
+ const ids = new Set();
210
+ rows = this.parameters.store.getNodes().map(node => {
211
+ const id = node.staticValue, caption = node.attr.caption;
212
+ if (typeof id !== 'string' || !id || typeof caption !== 'string' || ids.has(id)) throw new TypeError('Invalid or duplicate store choice');
213
+ ids.add(id);
214
+ return {id, caption};
215
+ });
216
+ } else rows = parseChoices(this.parameters.values ?? '', this.parameters.separator);
203
217
  return rows.filter(row => Object.hasOwn(keywords, '_id') ? row.id === keywords._id
204
218
  : row.caption.toLocaleLowerCase().includes(keywords._querystring.toLocaleLowerCase()));
205
219
  }
@@ -1,8 +1,9 @@
1
1
  /** Local choices share the same code:caption grammar in editors and groups. */
2
- export function parseChoices(values) {
2
+ export function parseChoices(values, separator = ',') {
3
+ if (typeof separator !== 'string' || !separator) throw new TypeError('separator must be a nonempty string');
3
4
  if (values === '') return [];
4
5
  const ids = new Set();
5
- return values.split(',').map(item => {
6
+ return values.split(separator).map(item => {
6
7
  const colon = item.indexOf(':');
7
8
  const id = colon < 0 ? item : item.slice(0, colon);
8
9
  const caption = colon < 0 ? item : item.slice(colon + 1);
@@ -0,0 +1,91 @@
1
+ /** Optional CodeMirror engine; loaded only when an editor is connected. */
2
+ import {EditorState, Compartment} from '@codemirror/state';
3
+ import {EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter, drawSelection, dropCursor} from '@codemirror/view';
4
+ import {syntaxHighlighting, HighlightStyle, bracketMatching, indentOnInput, indentUnit, foldGutter, foldKeymap} from '@codemirror/language';
5
+ import {defaultKeymap, history, historyKeymap, undo, redo, undoDepth, redoDepth, indentWithTab, insertNewline, insertNewlineAndIndent} from '@codemirror/commands';
6
+ import {search, searchKeymap, highlightSelectionMatches} from '@codemirror/search';
7
+ import {closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap} from '@codemirror/autocomplete';
8
+ import {setDiagnostics} from '@codemirror/lint';
9
+ import {tags} from '@lezer/highlight';
10
+ import {python} from '@codemirror/lang-python';
11
+ import {javascript} from '@codemirror/lang-javascript';
12
+ import {json} from '@codemirror/lang-json';
13
+ import {html} from '@codemirror/lang-html';
14
+ import {css} from '@codemirror/lang-css';
15
+ import {xml} from '@codemirror/lang-xml';
16
+ import {markdown} from '@codemirror/lang-markdown';
17
+ import {typst_lezer} from 'codemirror-lang-typst/lezer';
18
+ import {sql} from '@codemirror/lang-sql';
19
+
20
+ const languages = {text: () => [], python, javascript, typescript: () => javascript({typescript:true}), json, html, css, xml, markdown, sql, typst:typst_lezer};
21
+ const colors = syntaxHighlighting(HighlightStyle.define([
22
+ {tag:[tags.keyword, tags.modifier], color:'var(--gramlot-editor-keyword, #9677d9)'},
23
+ {tag:[tags.string, tags.regexp], color:'var(--gramlot-editor-string, #318f74)'},
24
+ {tag:[tags.number, tags.bool, tags.null], color:'var(--gramlot-editor-number, #c47733)'},
25
+ {tag:tags.comment, color:'var(--gramlot-text-secondary, #78889a)', fontStyle:'italic'},
26
+ {tag:[tags.function(tags.variableName), tags.tagName], color:'var(--gramlot-editor-function, #5499cb)'}
27
+ ]));
28
+ const theme = EditorView.theme({
29
+ '&': {height:'100%', color:'var(--gramlot-ink, CanvasText)', backgroundColor:'var(--gramlot-field-background, Canvas)'},
30
+ '.cm-scroller': {overflow:'auto', fontFamily:'inherit'},
31
+ '.cm-content': {caretColor:'var(--gramlot-ink, CanvasText)'},
32
+ '.cm-cursor, .cm-dropCursor': {borderLeftColor:'var(--gramlot-ink, CanvasText)'},
33
+ '.cm-gutters': {color:'var(--gramlot-text-secondary, GrayText)', backgroundColor:'var(--gramlot-surface-subtle, Canvas)', borderColor:'var(--gramlot-border-control, GrayText)'},
34
+ '.cm-activeLine, .cm-activeLineGutter': {backgroundColor:'color-mix(in srgb, var(--gramlot-brand-blue, Highlight) 10%, transparent)'},
35
+ '&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection': {backgroundColor:'color-mix(in srgb, var(--gramlot-brand-blue, Highlight) 28%, transparent)'},
36
+ '.cm-panels, .cm-tooltip': {color:'var(--gramlot-ink, CanvasText)', backgroundColor:'var(--gramlot-field-background, Canvas)', borderColor:'var(--gramlot-border-control, GrayText)'},
37
+ '.cm-textfield, .cm-button': {color:'inherit', background:'var(--gramlot-field-background, Canvas)', borderColor:'var(--gramlot-border-control, GrayText)'},
38
+ '.cm-search': {fontFamily:'system-ui', fontSize:'13px'}
39
+ });
40
+ function configuration(p) {
41
+ return [languages[p.language](), indentUnit.of(' '.repeat(p.indentUnit)),
42
+ EditorState.tabSize.of(p.indentUnit), EditorState.readOnly.of(Boolean(p.readonly || p.disabled)),
43
+ EditorView.editable.of(!p.disabled), EditorView.contentAttributes.of({'aria-readonly':String(p.readonly), 'aria-disabled':String(p.disabled), tabindex:p.disabled ? '-1' : '0', 'aria-label':p.lbl || 'Code editor'}),
44
+ p.lineNumbers ? lineNumbers() : [], p.lineWrapping ? EditorView.lineWrapping : [],
45
+ p.folding ? foldGutter() : [], p.autoCloseBrackets ? closeBrackets() : [],
46
+ p.autoIndent ? indentOnInput() : [], p.autocompletion ? autocompletion() : [],
47
+ p.highlightActiveLine ? [highlightActiveLine(), highlightActiveLineGutter()] : [],
48
+ p.highlightSelectionMatches ? highlightSelectionMatches() : [], p.bracketMatching ? bracketMatching() : [],
49
+ keymap.of([{key:'Enter', run:p.autoIndent ? insertNewlineAndIndent : insertNewline, shift:p.autoIndent ? insertNewlineAndIndent : insertNewline},
50
+ ...(p.folding ? foldKeymap : []), ...(p.autoCloseBrackets ? closeBracketsKeymap : []), ...(p.autocompletion ? completionKeymap : [])])];
51
+ }
52
+ export function createEditor(host) {
53
+ const options = new Compartment();
54
+ let lastHistory, historyScheduled = false, disposed = false;
55
+ const publishHistory = () => {
56
+ if (historyScheduled) return;
57
+ historyScheduled = true;
58
+ // Subscribers may update bound toolbar Data. Notify after the current
59
+ // editor transaction / external value projection has fully completed.
60
+ queueMicrotask(() => {
61
+ historyScheduled = false;
62
+ if (disposed) return;
63
+ const current = {
64
+ canUndo:!view.state.facet(EditorState.readOnly) && undoDepth(view.state) > 0,
65
+ canRedo:!view.state.facet(EditorState.readOnly) && redoDepth(view.state) > 0
66
+ };
67
+ if (lastHistory && current.canUndo === lastHistory.canUndo && current.canRedo === lastHistory.canRedo) return;
68
+ lastHistory = current;
69
+ host.pageContext.publish('historyChanged',current);
70
+ });
71
+ };
72
+ const extensions = [history(), theme, colors, drawSelection(), dropCursor(),
73
+ search({top:true}), keymap.of([{key:'Mod-s', preventDefault:true, run:() => {host.pageContext.publish('save', {value:host.readControlValue()}); return true;}},
74
+ indentWithTab, ...searchKeymap, ...defaultKeymap, ...historyKeymap]),
75
+ EditorView.updateListener.of(update => {
76
+ if (update.docChanged) host.editorChanged(update.state.doc.toString());
77
+ if (update.docChanged || update.transactions.some(transaction => transaction.reconfigured)) publishHistory();
78
+ })];
79
+ const state = doc => EditorState.create({doc, extensions:[options.of(configuration(host.parameters)), ...extensions]});
80
+ const view = new EditorView({state:state(host.readControlValue()), parent:host.control, root:host.shadowRoot});
81
+ return {view,
82
+ configure() {view.dispatch({effects:options.reconfigure(configuration(host.parameters))});},
83
+ replace(value) {view.setState(state(value)); publishHistory();},
84
+ publishHistory,
85
+ undo() {return !view.state.facet(EditorState.readOnly) && undo(view);},
86
+ redo() {return !view.state.facet(EditorState.readOnly) && redo(view);},
87
+ diagnostics(items) {view.dispatch(setDiagnostics(view.state, items));},
88
+ reveal(position) {view.dispatch({selection:{anchor:position}, effects:EditorView.scrollIntoView(position, {y:'center'})});},
89
+ destroy() {disposed = true; view.destroy();}
90
+ };
91
+ }