@gramlot/gramlot 0.3.8 → 0.3.10

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 (55) hide show
  1. package/dist/components/editors.js +116578 -0
  2. package/dist/components/inputs.js +24509 -0
  3. package/dist/components/layout.js +3385 -0
  4. package/dist/components/tree.js +24538 -0
  5. package/dist/components/typst.js +4 -0
  6. package/dist/gramlot.js +791 -37
  7. package/dist/gramlot.min.js +27 -24
  8. package/dist/runtime-notices.json +208 -0
  9. package/dist/typst-worker-source.js +4 -0
  10. package/package.json +34 -3
  11. package/src/binding/hooks.js +14 -0
  12. package/src/binding/providers.js +4 -0
  13. package/src/binding/remote.js +11 -2
  14. package/src/binding/runtime.js +10 -7
  15. package/src/builder/source.js +8 -3
  16. package/src/components/bases.js +1 -0
  17. package/src/components/border-container.js +7 -1
  18. package/src/components/buttons.js +3 -0
  19. package/src/components/choice-editor.js +17 -3
  20. package/src/components/choices.js +3 -2
  21. package/src/components/code-mirror-engine.js +91 -0
  22. package/src/components/code-mirror.js +88 -0
  23. package/src/components/editor-options.d.ts +9 -0
  24. package/src/components/editor-options.js +21 -0
  25. package/src/components/editors.js +10 -0
  26. package/src/components/html-document.js +56 -0
  27. package/src/components/html-editor.js +68 -0
  28. package/src/components/html-preview.js +33 -0
  29. package/src/components/inputs.js +2 -2
  30. package/src/components/jodit-engine.js +89 -0
  31. package/src/components/markdown-codec.js +35 -0
  32. package/src/components/markdown-document.js +14 -0
  33. package/src/components/markdown-editor.js +68 -0
  34. package/src/components/prose-mirror-engine.js +65 -0
  35. package/src/components/typst-client.js +38 -0
  36. package/src/components/typst-preview.js +88 -0
  37. package/src/components/typst-worker.js +49 -0
  38. package/src/components/typst.js +4 -0
  39. package/src/components/validation.js +1 -1
  40. package/src/filesystem.d.ts +22 -0
  41. package/src/filesystem.js +122 -0
  42. package/src/ide-documents.js +153 -0
  43. package/src/ide-runtime.d.ts +18 -0
  44. package/src/ide-runtime.js +238 -0
  45. package/src/index.d.ts +4 -1
  46. package/src/index.js +4 -1
  47. package/src/renderer/attributes.js +11 -2
  48. package/src/renderer/gramlot-renderer.js +3 -2
  49. package/src/server/assets.js +2 -2
  50. package/src/server/page.d.ts +5 -0
  51. package/src/server/page.js +4 -0
  52. package/src/view/button.js +2 -1
  53. package/src/view/controls.js +7 -11
  54. package/src/view/events.js +4 -8
  55. package/src/view/html.js +7 -0
@@ -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
 
@@ -18,6 +19,7 @@ import {TriggerTimers} from './providers.js';
18
19
  export class RemoteBinding {
19
20
  #binding;
20
21
  #timers;
22
+ #closed = false;
21
23
  // The name and TYTX parameters of the fragment mounted last on the node, whoever requested it.
22
24
  #lastName = null;
23
25
  #lastParams = null;
@@ -29,7 +31,13 @@ export class RemoteBinding {
29
31
 
30
32
  get binding() { return this.#binding; }
31
33
  get node() { return this.binding.node; }
32
- get closed() { return this.binding.closed; }
34
+ get closed() { return this.#closed || this.binding.closed; }
35
+
36
+ /** Removing the declaration releases scheduled calls; an in-flight fragment keeps the node request contract. */
37
+ close() {
38
+ this.#closed = true;
39
+ this.#timers.cancel();
40
+ }
33
41
 
34
42
  /** Start `_timing` again from its current value: called at every registration of the node's pointers. */
35
43
  register() {
@@ -80,7 +88,7 @@ export class RemoteBinding {
80
88
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, {cause: error});
81
89
  }
82
90
  const onRemote = node.getAttr('_onRemote');
83
- if (mounted && onRemote) this.#inline('_onRemote', onRemote, onRemote, params);
91
+ if (!this.closed && mounted && onRemote) this.#inline('_onRemote', onRemote, onRemote, params);
84
92
  }
85
93
 
86
94
  /**
@@ -106,6 +114,7 @@ export class RemoteBinding {
106
114
  }
107
115
 
108
116
  #inline(attr, code, source, params) {
117
+ if (attr === '_onRemote') return invokeHook(this.binding.runtime, this.node, attr, code, params);
109
118
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
110
119
  }
111
120
  }
@@ -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';
@@ -217,8 +218,8 @@ export class BindingRuntime {
217
218
  /**
218
219
  * Steps 2-4 of §5.1 on `branch` (a SourceBagNode or a new SourceBag value). The `nodeId` map is
219
220
  * complete, and a duplicate refused, before the first write or registration, so a `#<nodeId>`
220
- * of the branch translates; then the installation (`dataSetter`s and defaults), then one
221
- * NodeBinding per node and the registrations, providers included. On an error the NodeBindings
221
+ * of the branch translates; one NodeBinding per node owns expression cleanup before installation
222
+ * (`dataSetter`s and defaults), followed by registrations, providers included. On an error the NodeBindings
222
223
  * opened here are closed and the map entries they brought are removed; the Data is not rolled
223
224
  * back. Then `_init` (step 5), once per node: its error propagates and the NodeBindings stay
224
225
  * open (P12, no rollback).
@@ -240,8 +241,8 @@ export class BindingRuntime {
240
241
  }
241
242
  for (const [nodeId, node] of entering) this.nodeIds.set(nodeId, node);
242
243
  try {
243
- this.installer.install(branch);
244
244
  for (const node of nodes) this.openBinding(node);
245
+ this.installer.install(branch);
245
246
  for (const node of nodes) this.bindingFor(node).registerPointers();
246
247
  } catch (error) {
247
248
  const errors = [error];
@@ -411,6 +412,10 @@ export class NodeBinding {
411
412
  const dataElement = node._getMeta('data_element');
412
413
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
413
414
  if (!dataElement && typeof node.getAttr('remote') === 'string') this.#remote ??= new RemoteBinding(this);
415
+ else if (this.#remote) {
416
+ this.#remote.close();
417
+ this.#remote = null;
418
+ }
414
419
  const remoteDependencies = new Set();
415
420
  if (node._getMeta('gramlot_component')?.bagStore) {
416
421
  const storepath = node.getAttr('storepath');
@@ -452,10 +457,7 @@ export class NodeBinding {
452
457
  if (typeof handler !== 'string' || !handler) throw new TypeError(`${name} requires a handler`);
453
458
  return payload => {
454
459
  if (this.closed) return;
455
- if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
456
- const {group, method} = this.runtime.logicRegistry.resolve(handler, node);
457
- return method.call(group, node, payload);
458
- }
460
+ if (isLogicMethod(handler)) return callLogic(this.runtime, node, handler, payload);
459
461
  const [, attrs] = node.rootBuilder.runtimeValues(node);
460
462
  const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) =>
461
463
  !key.startsWith('subscribe_') && !key.startsWith('selfsubscribe_')));
@@ -529,6 +531,7 @@ export class NodeBinding {
529
531
  close() {
530
532
  if (this.closed) return;
531
533
  this.#closed = true;
534
+ this.#remote?.close();
532
535
  if (this.node._getMeta('data_element')) this.runtime.renderer.references.remove(this.node);
533
536
  this.#closeRegistrations();
534
537
  const errors = [];
@@ -193,7 +193,8 @@ export class GramlotBuilderBagNode extends SourceBagNode {
193
193
  * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the four providers, the
194
194
  * `_onCalling`/`_onResult`/`_onError` of a dataRpc and the `_onCalling` of a dataRemote, `action` of a
195
195
  * button, `_if`/`_else`/`_onRemote`/`_onCalling` of a node whose `remote` is a string, every `connect_on<event>`,
196
- * every `==` attribute (canonical name) and a `==` node value (`''`).
196
+ * every `==` attribute (canonical name) and a `==` node value (`''`). Script elements also retain
197
+ * their literal executable text and URLs here for the live renderer's activation check.
197
198
  */
198
199
  codeAttributes() {
199
200
  const own = [...(CODE_ATTRIBUTES[this.nodeTag] ?? []),
@@ -214,8 +215,12 @@ export class GramlotBuilderBagNode extends SourceBagNode {
214
215
  }
215
216
  for (const [name, value] of sourceAttributeItems(this.getAttr())) {
216
217
  if (isExpression(value)) items.push([name, value]);
218
+ if (this.nodeTag === 'script' && typeof value === 'string') {
219
+ const prefix = this.builder.constructor.dialectPrefixes.find(prefix => name.startsWith(prefix)) ?? '';
220
+ if (['src', 'href', 'xlink:href', 'xlink_href', '_text'].includes(name.slice(prefix.length).toLowerCase())) items.push([name, value]);
221
+ }
217
222
  }
218
- if (isExpression(this.staticValue)) items.push(['', this.staticValue]);
223
+ if (isExpression(this.staticValue) || this.nodeTag === 'script' && typeof this.staticValue === 'string') items.push(['', this.staticValue]);
219
224
  return items;
220
225
  }
221
226
 
@@ -274,7 +279,7 @@ export class GramlotBuilderBagNode extends SourceBagNode {
274
279
 
275
280
  /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
276
281
  publish(topic, payload = {}) {
277
- return this.builder.binding.subscriptions.publishNode(this, topic, payload);
282
+ return this.rootBuilder.binding.subscriptions.publishNode(this, topic, payload);
278
283
  }
279
284
 
280
285
  /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
@@ -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()};
@@ -1,6 +1,7 @@
1
1
  /** Parent-owned regions. Layout changes never move or recreate slotted content. */
2
2
  import {defineComponent} from './registry.js';
3
3
  import {Container} from './container.js';
4
+ import createDOMPurify from 'dompurify';
4
5
 
5
6
  const SIDES = ['top', 'bottom', 'left', 'right'];
6
7
  const REGIONS = [...SIDES, 'center'];
@@ -99,10 +100,12 @@ export const BorderContainer = defineComponent({
99
100
  #observer;
100
101
  #contentObserver;
101
102
  #drag;
103
+ #sanitizer;
102
104
  constructor() {
103
105
  super();
104
106
  this.control.replaceChildren();
105
107
  const doc = this.ownerDocument;
108
+ this.#sanitizer = createDOMPurify(doc.defaultView);
106
109
  this.#contentObserver = new doc.defaultView.ResizeObserver(entries => {
107
110
  for (const {target} of entries) {
108
111
  const region = target.closest('.region');
@@ -309,7 +312,10 @@ export const BorderContainer = defineComponent({
309
312
  state.separator.classList.add('separator'); state.drawer.classList.add('drawer');
310
313
  state.drawer.classList.toggle('drawer-reveal', config.minimize);
311
314
  state.drawer.classList.toggle('drawer-rotated', !horizontal(side));
312
- state.drawerLabel.innerHTML = config.label ?? '';
315
+ state.drawerLabel.replaceChildren(this.#sanitizer.sanitize(config.label ?? '', {
316
+ USE_PROFILES: {html: true}, FORBID_TAGS: ['style', 'form', 'input', 'button', 'select', 'textarea'],
317
+ RETURN_DOM_FRAGMENT: true,
318
+ }));
313
319
  state.drawerIcon.textContent = config.icon ?? '';
314
320
  state.drawerIcon.hidden = !config.icon;
315
321
  state.drawer.toggleAttribute('data-icon', !!config.icon);
@@ -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 '@gramlot/gramlot';
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
+ }
@@ -0,0 +1,88 @@
1
+ import {controlElement} from './bases.js';
2
+ import {defineComponent} from './registry.js';
3
+ import {Labelbox} from './labelbox.js';
4
+ import {FieldState} from './field-state.js';
5
+
6
+ const languages = ['text', 'python', 'javascript', 'typescript', 'json', 'html', 'css', 'xml', 'markdown', 'sql', 'typst'];
7
+ let engineModule;
8
+ export function EditorControl(HTMLElement) {
9
+ return class extends controlElement(HTMLElement) {
10
+ #value = '';
11
+ #generation = 0;
12
+ constructor() {
13
+ super();
14
+ this.control = this.ownerDocument.createElement('div');
15
+ this.control.id = 'control'; this.control.className = 'editor-control';
16
+ this.controlBox.append(this.control);
17
+ const style = this.ownerDocument.createElement('style');
18
+ style.textContent = `:host{display:block;height:300px;min-height:0;min-width:0}
19
+ .control-box,.labelbox,.editor-control{height:100%;min-height:0;min-width:0}
20
+ .labelbox{grid-template-rows:auto minmax(0,1fr)}
21
+ .editor-control{border:1px solid var(--gramlot-border-control,GrayText);border-radius:var(--gramlot-radius-sm,4px);overflow:hidden}
22
+ :host([data-editor-disabled]) .editor-control{opacity:.6}
23
+ .editor-status{padding:1em;color:var(--gramlot-text-secondary,GrayText)}`;
24
+ this.shadowRoot.append(style);
25
+ // Engine transactions emit one normalized control event. Native contenteditable
26
+ // input events must not produce a second binding write.
27
+ for (const type of ['input','change']) this.control.addEventListener(type, event => {
28
+ if (event.target !== this.control) event.stopImmediatePropagation();
29
+ });
30
+ this.control.addEventListener('focusout', () => this.#emit('change'));
31
+ }
32
+ get liveWrites() { return true; }
33
+ connectedCallback() {
34
+ const generation = ++this.#generation;
35
+ this.control.textContent = 'Loading editor…';
36
+ this.ready = (engineModule ??= import('./code-mirror-engine.js')).then(module => {
37
+ if (generation !== this.#generation || !this.isConnected) return;
38
+ this.control.textContent = '';
39
+ this.editor = module.createEditor(this);
40
+ this.editor.publishHistory();
41
+ }).catch(error => {
42
+ if (generation !== this.#generation) return;
43
+ this.control.textContent = `CodeMirror could not start: ${error.message}`;
44
+ this.control.setAttribute('role','alert');
45
+ throw error;
46
+ });
47
+ // Keep the rejected ready promise inspectable without an unhandled rejection.
48
+ this.ready.catch(error => console.error(error));
49
+ }
50
+ releaseControl() { ++this.#generation; this.editor?.destroy(); this.editor = null; super.releaseControl(); }
51
+ projectAttributes(attrs) {
52
+ const rest = super.projectAttributes(attrs), p = this.parameters;
53
+ if (!languages.includes(p.language)) throw new TypeError(`Unsupported CodeMirror language: ${p.language}`);
54
+ if (!Number.isInteger(p.indentUnit) || p.indentUnit < 1 || p.indentUnit > 16) throw new TypeError('indentUnit must be an integer from 1 to 16');
55
+ if (!Number.isFinite(p.fontSize) || p.fontSize < 8 || p.fontSize > 48) throw new TypeError('fontSize must be from 8 to 48');
56
+ this.control.disabled = p.disabled; this.control.readOnly = p.readonly;
57
+ this.toggleAttribute('data-editor-disabled', p.disabled);
58
+ this.control.style.fontFamily = p.fontFamily; this.control.style.fontSize = `${p.fontSize}px`;
59
+ this.editor?.configure();
60
+ return rest;
61
+ }
62
+ #emit(type) {this.control.dispatchEvent(new this.ownerDocument.defaultView.Event(type, {bubbles:true}));}
63
+ editorChanged(value) {this.#value = value; this.#emit('input');}
64
+ readControlValue() {return this.#value;}
65
+ writeControlValue(value) {
66
+ if (typeof value !== 'string') throw new TypeError('CodeMirror value must be a string');
67
+ if (value === this.#value) return;
68
+ this.#value = value; this.editor?.replace(value);
69
+ }
70
+ focus() {if (!this.parameters.disabled) this.editor?.view.focus();}
71
+ setDiagnostics(items) {this.editor.diagnostics(items);}
72
+ revealPosition(position) {this.editor.reveal(position);}
73
+ undo() {return this.editor ? this.editor.undo() : false;}
74
+ redo() {return this.editor ? this.editor.redo() : false;}
75
+ };
76
+ }
77
+ EditorControl.parameters = {
78
+ disabled:{dtype:'B', default:false, binding:'read'}, readonly:{dtype:'B', default:false, binding:'read'},
79
+ live:{dtype:'B', default:true, binding:'read'}
80
+ };
81
+ const toggle = {dtype:'B', default:true, binding:'read'};
82
+ export const CodeMirror = defineComponent({name:'codeMirror', tag:'gramlot-code-mirror', base:EditorControl, mixins:[Labelbox,FieldState],
83
+ parameters:{value:{dtype:'T', default:'', binding:'twoWay'}, language:{dtype:'T', default:'text', binding:'read', enum:languages},
84
+ lineNumbers:toggle, lineWrapping:toggle, indentUnit:{dtype:'L',default:4,binding:'read'},
85
+ fontSize:{dtype:'L',default:14,binding:'read'}, fontFamily:{dtype:'T',default:'monospace',binding:'read'},
86
+ folding:toggle, bracketMatching:toggle, autoCloseBrackets:toggle, autoIndent:toggle, autocompletion:toggle, highlightActiveLine:toggle, highlightSelectionMatches:toggle},
87
+ implementation:Base => class extends Base {}
88
+ });
@@ -0,0 +1,9 @@
1
+ import type {SourceBag, SourceBagNode} from '@genrojs/builders';
2
+ /** Reusable Source composition; relative value pointers resolve within datapath. */
3
+ export function codeMirrorWithOptions(parent: SourceBag | SourceBagNode, options: {
4
+ datapath: string;
5
+ value: string;
6
+ language?: string;
7
+ height?: string;
8
+ [attribute: string]: unknown;
9
+ }): SourceBagNode;
@@ -0,0 +1,21 @@
1
+ /** Source composition; settings belong to the caller's scoped Data. */
2
+ export function codeMirrorWithOptions(parent, {datapath, value, language = 'text', height = '420px', ...attributes}) {
3
+ if (!datapath) throw new TypeError('codeMirrorWithOptions requires datapath');
4
+ const pane = parent.borderContainer({datapath, height, class:'gramlot-editor-options'});
5
+ const defaults = {language, indentUnit:4, fontSize:14, fontFamily:'monospace', lineNumbers:true, lineWrapping:true,
6
+ folding:true, bracketMatching:true, autoCloseBrackets:true, autoIndent:true, autocompletion:true, highlightActiveLine:true, highlightSelectionMatches:true};
7
+ for (const [name, setting] of Object.entries(defaults)) pane.dataSetter({destination_path:`.settings.${name}`, value:setting});
8
+ const options = pane.contentPane({region:'right', width:'250px', drawer:'close', drawer_label:'Options', drawer_icon:'⚙', drawer_minimize:false,
9
+ padding:'12px', overflow:'auto', class:'gramlot-editor-settings'});
10
+ options.h3('Editor options');
11
+ options.filteringSelect({value:'^.settings.language', lbl:'Language', values:'text:Plain text,python:Python,javascript:JavaScript,typescript:TypeScript,json:JSON,html:HTML,css:CSS,xml:XML,markdown:Markdown,sql:SQL,typst:Typst'});
12
+ options.numberTextBox({value:'^.settings.indentUnit', lbl:'Indent spaces', min:1, max:16, dtype:'L', validate_notnull:true});
13
+ options.numberTextBox({value:'^.settings.fontSize', lbl:'Font size', min:8, max:48, dtype:'L', validate_notnull:true});
14
+ options.textbox({value:'^.settings.fontFamily', lbl:'Font family'});
15
+ const labels = {lineNumbers:'Line numbers', lineWrapping:'Wrap lines', folding:'Code folding', bracketMatching:'Match brackets', autoCloseBrackets:'Close brackets and quotes', autoIndent:'Automatic indentation',
16
+ autocompletion:'Local completion', highlightActiveLine:'Highlight current line', highlightSelectionMatches:'Highlight matching selections'};
17
+ for (const [name, label] of Object.entries(labels)) options.checkbox({value:`^.settings.${name}`, label, display:'block', margin_top:'8px'});
18
+ const center = pane.contentPane({region:'center', min_height:0});
19
+ center.codeMirror({...attributes, value, height:'100%', ...Object.fromEntries(Object.keys(defaults).map(name => [name, `^.settings.${name}`]))});
20
+ return pane;
21
+ }
@@ -0,0 +1,10 @@
1
+ import {defineCollection} from './registry.js';
2
+ import {CodeMirror} from './code-mirror.js';
3
+ import {HtmlEditor} from './html-editor.js';
4
+ import {HtmlPreview,MarkdownPreview} from './html-preview.js';
5
+ import {MarkdownEditor} from './markdown-editor.js';
6
+ export {CodeMirror} from './code-mirror.js';
7
+ export {HtmlEditor} from './html-editor.js';
8
+ export {HtmlPreview,MarkdownPreview} from './html-preview.js';
9
+ export {MarkdownEditor} from './markdown-editor.js';
10
+ export default defineCollection({name:'editors', components:[CodeMirror,HtmlEditor,HtmlPreview,MarkdownEditor,MarkdownPreview]});
@@ -0,0 +1,56 @@
1
+ /** Preserve nonvisual document content while editing the body through Jodit. */
2
+ const protectedSelector = 'script,style,iframe,object,embed,template,svg,math,link,meta,base';
3
+ const unsafeAttribute = (element, name, value) => /^on/i.test(name) || ['autofocus','srcdoc'].includes(name) ||
4
+ (['href','src','action','formaction','xlink:href'].includes(name) && /^(?:javascript|vbscript|data):/i.test(value.trim()) &&
5
+ !(element.tagName === 'IMG' && name === 'src' && /^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(value)));
6
+
7
+ export function prepareHtmlDocument(value, window) {
8
+ const parse = html => new window.DOMParser().parseFromString(html,'text/html');
9
+ const original = parse(value);
10
+ const full = /<(?:html|head|body)[\s>]|<!doctype/i.test(value) || original.head.children.length > 0;
11
+ const display = original.body.cloneNode(true);
12
+ const marker = `data-gramlot-${crypto.randomUUID()}`;
13
+ const nodes = new Map(), attributes = new Map();
14
+ let sequence = 0;
15
+ const comments = [], walker = original.createTreeWalker(display,128);
16
+ while (walker.nextNode()) comments.push(walker.currentNode);
17
+ for (const node of [...display.querySelectorAll(protectedSelector), ...comments]) {
18
+ if (!display.contains(node)) continue;
19
+ const id = String(++sequence), placeholder = original.createElement('span');
20
+ placeholder.setAttribute(marker,id); placeholder.setAttribute('contenteditable','false');
21
+ placeholder.textContent = `[${node.nodeName.toLowerCase()} — edit in Code]`;
22
+ nodes.set(id,node.cloneNode(true)); node.replaceWith(placeholder);
23
+ }
24
+ for (const element of display.querySelectorAll('*')) {
25
+ const removed = [...element.attributes].filter(attr => unsafeAttribute(element,attr.name,attr.value))
26
+ .map(attr => [attr.name,attr.value]);
27
+ if (!removed.length) continue;
28
+ for (const [name] of removed) element.removeAttribute(name);
29
+ const id = String(++sequence); element.setAttribute(`${marker}-attrs`,id); attributes.set(id,removed);
30
+ }
31
+ const unique = (body, attribute, id) => {
32
+ const matches = body.querySelectorAll(`[${attribute}="${id}"]`);
33
+ if (matches.length !== 1) throw new Error('Protected page content changed. Use Code to edit it.');
34
+ return matches[0];
35
+ };
36
+ return {
37
+ html:display.innerHTML,
38
+ styles:[...original.head.querySelectorAll('style')].map(node => node.textContent).join('\n'),
39
+ serialize(html) {
40
+ const edited = parse(html);
41
+ if (edited.body.querySelector(protectedSelector) || [...edited.body.querySelectorAll('*')].some(element =>
42
+ [...element.attributes].some(attr => unsafeAttribute(element,attr.name,attr.value)))) {
43
+ throw new Error('Active or embedded content must be edited in Code.');
44
+ }
45
+ for (const [id,node] of nodes) unique(edited.body,marker,id).replaceWith(node.cloneNode(true));
46
+ for (const [id,removed] of attributes) {
47
+ const element = unique(edited.body,`${marker}-attrs`,id);
48
+ for (const [name,value] of removed) element.setAttribute(name,value);
49
+ element.removeAttribute(`${marker}-attrs`);
50
+ }
51
+ const result = original.cloneNode(true);
52
+ result.body.innerHTML = edited.body.innerHTML;
53
+ return full ? (result.doctype ? new window.XMLSerializer().serializeToString(result.doctype)+'\n' : '') + result.documentElement.outerHTML : result.body.innerHTML;
54
+ }
55
+ };
56
+ }
@@ -0,0 +1,68 @@
1
+ import {controlElement} from './bases.js';
2
+ import {defineComponent} from './registry.js';
3
+ import {Labelbox} from './labelbox.js';
4
+ import {FieldState} from './field-state.js';
5
+
6
+ let engineModule;
7
+ function HtmlControl(HTMLElement) {
8
+ return class extends controlElement(HTMLElement) {
9
+ #value='';
10
+ #generation=0;
11
+ constructor() {
12
+ super();
13
+ this.control=this.ownerDocument.createElement('div');
14
+ this.control.className='html-editor-control';
15
+ this.controlBox.append(this.control);
16
+ const style=this.ownerDocument.createElement('style');
17
+ style.textContent=':host{display:block;height:400px;min-height:0}.control-box,.labelbox,.html-editor-control{height:100%;min-height:0}.labelbox{grid-template-rows:auto minmax(0,1fr)}.html-editor-control{overflow:hidden}.html-editor-status{font:inherit;color:var(--gramlot-text-secondary,GrayText)}.html-editor-status:empty{display:none}';
18
+ this.shadowRoot.append(style);
19
+ for (const type of ['input','change']) this.control.addEventListener(type,event=>{
20
+ if (event.target!==this.control) event.stopImmediatePropagation();
21
+ });
22
+ }
23
+ get liveWrites() {return true;}
24
+ connectedCallback() {this.load();}
25
+ load() {
26
+ const generation=++this.#generation;
27
+ this.engine?.destroy();this.engine=null;
28
+ this.control.textContent='Loading HTML editor…';
29
+ this.ready=(engineModule ??= import('./jodit-engine.js')).then(module=>{
30
+ if (generation!==this.#generation || !this.isConnected) return;
31
+ this.control.textContent='';
32
+ this.engine=module.createHtmlEditor(this);
33
+ }).catch(error=>{
34
+ if (generation!==this.#generation) return;
35
+ this.control.textContent=`HTML editor could not start: ${error.message}`;
36
+ this.control.setAttribute('role','alert');
37
+ throw error;
38
+ });
39
+ this.ready.catch(error=>console.error(error));
40
+ }
41
+ projectAttributes(attrs) {
42
+ const rest=super.projectAttributes(attrs);
43
+ this.control.disabled=this.parameters.disabled;
44
+ this.control.readOnly=this.parameters.readonly;
45
+ this.engine?.configure();
46
+ return rest;
47
+ }
48
+ readControlValue() {return this.#value;}
49
+ writeControlValue(value) {
50
+ if (typeof value!=='string') throw new TypeError('HTML editor value must be a string');
51
+ if (value===this.#value) return;
52
+ this.#value=value;
53
+ if (this.isConnected && this.engine) this.load();
54
+ }
55
+ editorChanged(value) {
56
+ this.#value=value;
57
+ this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('input',{bubbles:true}));
58
+ }
59
+ editorBlurred() {this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('change',{bubbles:true}));}
60
+ undo() {return this.engine ? this.engine.undo() : false;}
61
+ redo() {return this.engine ? this.engine.redo() : false;}
62
+ focus() {if (!this.parameters.disabled) this.engine?.focus();}
63
+ releaseControl() {++this.#generation;this.engine?.destroy();this.engine=null;super.releaseControl();}
64
+ };
65
+ }
66
+ HtmlControl.parameters={disabled:{dtype:'B',default:false,binding:'read'},readonly:{dtype:'B',default:false,binding:'read'},live:{dtype:'B',default:true,binding:'read'}};
67
+ export const HtmlEditor=defineComponent({name:'htmlEditor',tag:'gramlot-html-editor',base:HtmlControl,mixins:[Labelbox,FieldState],
68
+ parameters:{value:{dtype:'T',default:'',binding:'twoWay'}},implementation:Base=>class extends Base {}});
@@ -0,0 +1,33 @@
1
+ import {defineComponent} from './registry.js';
2
+ import {projectParameters} from './parameters.js';
3
+ import {renderMarkdownDocument} from './markdown-document.js';
4
+
5
+ function PreviewElement(HTMLElement) {
6
+ return class extends HTMLElement {
7
+ constructor() {
8
+ super();
9
+ const root=this.attachShadow({mode:'open'});
10
+ const style=this.ownerDocument.createElement('style');
11
+ style.textContent=':host{display:block;height:100%;min-height:0}iframe{display:block;width:100%;height:100%;border:0;background:white}';
12
+ this.frame=this.ownerDocument.createElement('iframe');
13
+ this.frame.setAttribute('sandbox','');
14
+ this.frame.title='HTML preview';
15
+ root.append(style,this.frame);
16
+ }
17
+ renderDocument(value) {return value;}
18
+ projectAttributes(attrs) {
19
+ const rest=projectParameters(this,attrs);
20
+ const html=this.renderDocument(this.parameters.value);
21
+ if (this.frame.srcdoc !== html) this.frame.srcdoc=html;
22
+ return rest;
23
+ }
24
+ };
25
+ }
26
+ export const HtmlPreview=defineComponent({name:'htmlPreview',tag:'gramlot-html-preview',base:PreviewElement,
27
+ parameters:{value:{dtype:'T',default:'',binding:'read'}},implementation:Base=>class extends Base {}});
28
+
29
+ export const MarkdownPreview=defineComponent({name:'markdownPreview',tag:'gramlot-markdown-preview',base:PreviewElement,
30
+ parameters:{value:{dtype:'T',default:'',binding:'read'},allowHtml:{dtype:'B',default:false,binding:'read'}},implementation:Base=>class extends Base {
31
+ constructor(){super();this.frame.title='Markdown preview';}
32
+ renderDocument(value){return renderMarkdownDocument(value,{allowHtml:this.parameters.allowHtml,document:this.ownerDocument});}
33
+ }});