@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
package/dist/gramlot.js CHANGED
@@ -22275,10 +22275,11 @@ function projectParameters(element, attrs) {
22275
22275
  }
22276
22276
 
22277
22277
  // src/components/choices.js
22278
- function parseChoices(values) {
22278
+ function parseChoices(values, separator = ",") {
22279
+ if (typeof separator !== "string" || !separator) throw new TypeError("separator must be a nonempty string");
22279
22280
  if (values === "") return [];
22280
22281
  const ids = /* @__PURE__ */ new Set();
22281
- return values.split(",").map((item) => {
22282
+ return values.split(separator).map((item) => {
22282
22283
  const colon = item.indexOf(":");
22283
22284
  const id = colon < 0 ? item : item.slice(0, colon);
22284
22285
  const caption = colon < 0 ? item : item.slice(colon + 1);
@@ -22323,6 +22324,9 @@ function controlElement(HTMLElement) {
22323
22324
  }
22324
22325
  releaseControl() {
22325
22326
  }
22327
+ get liveWrites() {
22328
+ return this.control.localName === "textarea" || ["text", "password", "range", "color"].includes(this.control.type);
22329
+ }
22326
22330
  validateCandidate(value, accept) {
22327
22331
  accept(value);
22328
22332
  return { ok: true, value, isCurrent: () => this.pageContext.isActive() };
@@ -22529,6 +22533,9 @@ function Command(HTMLElement) {
22529
22533
  min-height:max(var(--gramlot-field-height,28px),var(--gramlot-touch-target,0px));
22530
22534
  padding:var(--gramlot-button-padding,.25em .65em);cursor:pointer}
22531
22535
  button:hover:not(:disabled){background:var(--gramlot-button-hover,var(--gramlot-field-readonly-background,#eee))}
22536
+ :host(.button--quiet) button{background:transparent;color:var(--gramlot-action,CanvasText);border-color:transparent}
22537
+ :host(.button--quiet) button:hover:not(:disabled){background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,CanvasText);border-color:transparent}
22538
+ button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:2px}
22532
22539
  button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none}
22533
22540
  .led{display:inline-block;width:.6em;height:.6em;border-radius:50%;background:var(--gramlot-button-led-off,#888)}
22534
22541
  [aria-pressed=true] .led{background:var(--gramlot-button-led-on,#2b9a46)}
@@ -22988,7 +22995,7 @@ var NATIVE_ATTRIBUTES = {
22988
22995
  canvas: ["width", "height"]
22989
22996
  };
22990
22997
  var DISPLAY_ATTRIBUTES = ["format", "mask", "locale", "timeZone", "places", "dtype"];
22991
- var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "formaction", "xlink:href", "xlink_href"]);
22998
+ var URL_ATTRIBUTES = /* @__PURE__ */ new Set(["href", "src", "action", "formaction", "xlink:href", "xlink_href"]);
22992
22999
  function withoutBindingAttributes(attrs) {
22993
23000
  return Object.fromEntries(Object.entries(attrs).filter(([name, value]) => !(value && typeof value === "object" && Object.hasOwn(value, "$gramlotRef")) && !BINDING_ATTRIBUTES.has(name) && !BINDING_ATTRIBUTE_PREFIXES.some((prefix) => name.startsWith(prefix))));
22994
23001
  }
@@ -23002,6 +23009,14 @@ function requireStyleClassAttributes(node, attrs, prefixes = []) {
23002
23009
  }
23003
23010
  }
23004
23011
  function requireNoScriptAttributes(node, attrs, prefixes = []) {
23012
+ if (node.nodeTag === "script") {
23013
+ const executable = [["", node.staticValue], ...sourceAttributeItems(node.getAttr()).filter(([name]) => ["src", "href", "xlink:href", "xlink_href", "_text"].includes(name.slice((prefixes.find((prefix) => name.startsWith(prefix)) ?? "").length).toLowerCase()))];
23014
+ for (const [name, value] of executable) {
23015
+ if (node.pointerType(value) || isExpression(value)) {
23016
+ throw new Error(`script '${node.label}': '${name}' must be literal Source; script code and URLs cannot come from Data`);
23017
+ }
23018
+ }
23019
+ }
23005
23020
  if (attrs.onClose != null && !node.parentNode?._getMeta("gramlot_component")?.childParameters?.onClose) {
23006
23021
  throw new Error("onClose is only supported on a tab/stack panel");
23007
23022
  }
@@ -23288,7 +23303,8 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
23288
23303
  * `formula` of a dataFormula, `script` of a dataController, `_if`/`_else` of the four providers, the
23289
23304
  * `_onCalling`/`_onResult`/`_onError` of a dataRpc and the `_onCalling` of a dataRemote, `action` of a
23290
23305
  * button, `_if`/`_else`/`_onRemote`/`_onCalling` of a node whose `remote` is a string, every `connect_on<event>`,
23291
- * every `==` attribute (canonical name) and a `==` node value (`''`).
23306
+ * every `==` attribute (canonical name) and a `==` node value (`''`). Script elements also retain
23307
+ * their literal executable text and URLs here for the live renderer's activation check.
23292
23308
  */
23293
23309
  codeAttributes() {
23294
23310
  const own2 = [
@@ -23311,8 +23327,12 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
23311
23327
  }
23312
23328
  for (const [name, value] of sourceAttributeItems(this.getAttr())) {
23313
23329
  if (isExpression2(value)) items.push([name, value]);
23330
+ if (this.nodeTag === "script" && typeof value === "string") {
23331
+ const prefix = this.builder.constructor.dialectPrefixes.find((prefix2) => name.startsWith(prefix2)) ?? "";
23332
+ if (["src", "href", "xlink:href", "xlink_href", "_text"].includes(name.slice(prefix.length).toLowerCase())) items.push([name, value]);
23333
+ }
23314
23334
  }
23315
- if (isExpression2(this.staticValue)) items.push(["", this.staticValue]);
23335
+ if (isExpression2(this.staticValue) || this.nodeTag === "script" && typeof this.staticValue === "string") items.push(["", this.staticValue]);
23316
23336
  return items;
23317
23337
  }
23318
23338
  /**
@@ -23364,7 +23384,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
23364
23384
  }
23365
23385
  /** Publish to this node's selfsubscribe topics, as in the legacy Source API. */
23366
23386
  publish(topic, payload = {}) {
23367
- return this.builder.binding.subscriptions.publishNode(this, topic, payload);
23387
+ return this.rootBuilder.binding.subscriptions.publishNode(this, topic, payload);
23368
23388
  }
23369
23389
  /** Builder's `^` pointers, except the attributes ending in `_path`, which hold a bare path. */
23370
23390
  pointers() {
@@ -24520,6 +24540,19 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
24520
24540
  }
24521
24541
  };
24522
24542
 
24543
+ // src/binding/hooks.js
24544
+ function isLogicMethod(handler) {
24545
+ return typeof handler === "string" && !["null", "true", "false"].includes(handler) && /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(handler);
24546
+ }
24547
+ function callLogic(runtime, node, methodName, context) {
24548
+ const { group, method } = runtime.logicRegistry.resolve(methodName, node);
24549
+ return method.call(group, node, context);
24550
+ }
24551
+ function invokeHook(runtime, node, attribute, handler, context, inlineNames = Object.keys(context)) {
24552
+ if (isLogicMethod(handler)) return callLogic(runtime, node, handler, context);
24553
+ return runtime.inlineCompiler.compile(node, attribute, handler, inlineNames)(context);
24554
+ }
24555
+
24523
24556
  // src/view/controls.js
24524
24557
  var CONTROL_TAGS = /* @__PURE__ */ new Set(["input", "select", "textarea"]);
24525
24558
  var REBUILD_ATTRIBUTES = ["type", "multiple", "group"];
@@ -24727,8 +24760,8 @@ var ComponentControl = class extends ControlAdapter {
24727
24760
  }
24728
24761
  get writeEvent() {
24729
24762
  if (this.element.commitOnChange) return "change";
24730
- const control = this.element.control;
24731
- return this.live && (control.localName === "textarea" || ["text", "password", "range", "color"].includes(control.type)) ? "input" : "change";
24763
+ const live = this.resolved.live ?? this.element.parameters.live;
24764
+ return live && this.element.liveWrites ? "input" : "change";
24732
24765
  }
24733
24766
  read() {
24734
24767
  return this.element.readControlValue();
@@ -25040,16 +25073,13 @@ var INPUT_CONTROLS = {
25040
25073
  function componentContext(adapter) {
25041
25074
  const { binding, node } = adapter, app = binding.runtime.gramlot;
25042
25075
  const invoke = (attribute, code, keywords, expression = false) => {
25043
- if (!expression && /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(code)) {
25044
- const { group, method } = app.src.logicRegistry.resolve(code, node);
25045
- return method.call(group, node, keywords);
25046
- }
25076
+ if (!expression) return invokeHook(binding.runtime, node, attribute, code, keywords);
25047
25077
  return binding.runtime.inlineCompiler.compile(
25048
25078
  node,
25049
25079
  attribute,
25050
25080
  code,
25051
25081
  Object.keys(keywords),
25052
- expression ? `return (${code});` : code
25082
+ `return (${code});`
25053
25083
  )(keywords);
25054
25084
  };
25055
25085
  return {
@@ -25058,11 +25088,9 @@ function componentContext(adapter) {
25058
25088
  createDecimal,
25059
25089
  isDecimal: isDecimal2,
25060
25090
  getDecimalLibrary,
25091
+ publish: (topic, payload) => node.publish(topic, payload),
25061
25092
  isActive: () => !binding.closed,
25062
- callLogic: (name, keywords) => {
25063
- const { group, method } = app.src.logicRegistry.resolve(name, node);
25064
- return method.call(group, node, keywords);
25065
- },
25093
+ callLogic: (name, keywords) => callLogic(binding.runtime, node, name, keywords),
25066
25094
  format: (value, options) => app.format(value, options),
25067
25095
  invoke,
25068
25096
  remote: (method, keywords, signal) => app.rpc.call("data", method, keywords, { signal }),
@@ -25152,9 +25180,9 @@ function domPropertyName(name) {
25152
25180
  return PROPERTY_NAMES.get(camel.toLowerCase()) ?? camel;
25153
25181
  }
25154
25182
  var HtmlElement = class {
25155
- constructor({ metadataAttributes = [], invokeScript = null, callLogic = null } = {}) {
25183
+ constructor({ metadataAttributes = [], invokeScript = null, callLogic: callLogic2 = null } = {}) {
25156
25184
  this.invokeScript = invokeScript;
25157
- this.callLogic = callLogic;
25185
+ this.callLogic = callLogic2;
25158
25186
  this.metadataAttributes = /* @__PURE__ */ new Set([...META_ATTRS, "_text", ...metadataAttributes]);
25159
25187
  }
25160
25188
  definition(node) {
@@ -25240,6 +25268,13 @@ var HtmlElement = class {
25240
25268
  * control belongs to its ControlAdapter: neither the attribute nor the property is written here.
25241
25269
  */
25242
25270
  update(record2, node, attrs = node.attr, textValue2 = DEFAULT_TEXT, visible = null) {
25271
+ if (node.nodeTag === "script") {
25272
+ for (const [name, code] of node.codeAttributes()) {
25273
+ if (node.activatedCode(name) !== code) {
25274
+ throw new Error(`script '${node.label}': '${name}' runs only as received with the Source`);
25275
+ }
25276
+ }
25277
+ }
25243
25278
  const { element, text } = record2;
25244
25279
  const isHtml = element.namespaceURI === XHTML_NS;
25245
25280
  const renderAttributes = this.definition(node).meta.render_attributes ?? {};
@@ -25452,7 +25487,7 @@ var ButtonBinding = class _ButtonBinding {
25452
25487
  if (this.binding.closed || this.element.disabled || result === null) return;
25453
25488
  const values = { ...read(), ...result };
25454
25489
  if (result) values._askResult = result;
25455
- this.binding.runtime.inlineCompiler.compile(node, "action", node.getAttr("action"), Object.keys(values))(values);
25490
+ invokeHook(this.binding.runtime, node, "action", node.getAttr("action"), values);
25456
25491
  };
25457
25492
  const ask = node.getAttr("ask");
25458
25493
  const askDialog = this.binding.runtime.askDialog;
@@ -25483,7 +25518,6 @@ function eventToString(event) {
25483
25518
 
25484
25519
  // src/view/events.js
25485
25520
  var PREFIX = "connect_on";
25486
- var NAMED_LOGIC = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/;
25487
25521
  var NativeEventBinding = class {
25488
25522
  #binding;
25489
25523
  #record;
@@ -25531,11 +25565,7 @@ var NativeEventBinding = class {
25531
25565
  if (this.binding.closed) return;
25532
25566
  const node = this.node;
25533
25567
  const runtime = this.binding.runtime;
25534
- if (NAMED_LOGIC.test(this.handler)) {
25535
- const { group, method } = runtime.logicRegistry.resolve(this.handler, node);
25536
- method.call(group, node, event);
25537
- return;
25538
- }
25568
+ if (isLogicMethod(this.handler)) return callLogic(runtime, node, this.handler, event);
25539
25569
  runtime.inlineCompiler.compile(node, this.attribute, this.handler, ["event"])({ event });
25540
25570
  }
25541
25571
  };
@@ -26338,6 +26368,9 @@ var Provider = class {
26338
26368
  ...CLICK_FIELDS,
26339
26369
  ...Object.keys(authorArguments(kwargs))
26340
26370
  ];
26371
+ if (["_onCalling", "_onResult", "_onError", "_ask_onCancel"].includes(attr)) {
26372
+ return invokeHook(this.binding.runtime, this.node, attr, code, { ...kwargs, _kwargs: kwargs }, names);
26373
+ }
26341
26374
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, names, source)({ ...kwargs, _kwargs: kwargs });
26342
26375
  }
26343
26376
  /**
@@ -26676,6 +26709,7 @@ ${text}`, { cause: error });
26676
26709
  var RemoteBinding = class {
26677
26710
  #binding;
26678
26711
  #timers;
26712
+ #closed = false;
26679
26713
  // The name and TYTX parameters of the fragment mounted last on the node, whoever requested it.
26680
26714
  #lastName = null;
26681
26715
  #lastParams = null;
@@ -26690,7 +26724,12 @@ var RemoteBinding = class {
26690
26724
  return this.binding.node;
26691
26725
  }
26692
26726
  get closed() {
26693
- return this.binding.closed;
26727
+ return this.#closed || this.binding.closed;
26728
+ }
26729
+ /** Removing the declaration releases scheduled calls; an in-flight fragment keeps the node request contract. */
26730
+ close() {
26731
+ this.#closed = true;
26732
+ this.#timers.cancel();
26694
26733
  }
26695
26734
  /** Start `_timing` again from its current value: called at every registration of the node's pointers. */
26696
26735
  register() {
@@ -26739,7 +26778,7 @@ var RemoteBinding = class {
26739
26778
  throw new Error(`${node.nodeTag} '${node.label}': remote '${name}' failed: ${error.message}`, { cause: error });
26740
26779
  }
26741
26780
  const onRemote = node.getAttr("_onRemote");
26742
- if (mounted && onRemote) this.#inline("_onRemote", onRemote, onRemote, params);
26781
+ if (!this.closed && mounted && onRemote) this.#inline("_onRemote", onRemote, onRemote, params);
26743
26782
  }
26744
26783
  /**
26745
26784
  * Record the fragment `remoteSource` mounted on the node, with its method and the TYTX of its parameters:
@@ -26761,6 +26800,7 @@ var RemoteBinding = class {
26761
26800
  return attrs[name] ?? null;
26762
26801
  }
26763
26802
  #inline(attr, code, source, params) {
26803
+ if (attr === "_onRemote") return invokeHook(this.binding.runtime, this.node, attr, code, params);
26764
26804
  return this.binding.runtime.inlineCompiler.compile(this.node, attr, code, Object.keys(params), source)(params);
26765
26805
  }
26766
26806
  };
@@ -27130,8 +27170,8 @@ var BindingRuntime = class {
27130
27170
  /**
27131
27171
  * Steps 2-4 of §5.1 on `branch` (a SourceBagNode or a new SourceBag value). The `nodeId` map is
27132
27172
  * complete, and a duplicate refused, before the first write or registration, so a `#<nodeId>`
27133
- * of the branch translates; then the installation (`dataSetter`s and defaults), then one
27134
- * NodeBinding per node and the registrations, providers included. On an error the NodeBindings
27173
+ * of the branch translates; one NodeBinding per node owns expression cleanup before installation
27174
+ * (`dataSetter`s and defaults), followed by registrations, providers included. On an error the NodeBindings
27135
27175
  * opened here are closed and the map entries they brought are removed; the Data is not rolled
27136
27176
  * back. Then `_init` (step 5), once per node: its error propagates and the NodeBindings stay
27137
27177
  * open (P12, no rollback).
@@ -27151,8 +27191,8 @@ var BindingRuntime = class {
27151
27191
  }
27152
27192
  for (const [nodeId, node] of entering) this.nodeIds.set(nodeId, node);
27153
27193
  try {
27154
- this.installer.install(branch);
27155
27194
  for (const node of nodes) this.openBinding(node);
27195
+ this.installer.install(branch);
27156
27196
  for (const node of nodes) this.bindingFor(node).registerPointers();
27157
27197
  } catch (error) {
27158
27198
  const errors = [error];
@@ -27321,6 +27361,10 @@ var NodeBinding = class {
27321
27361
  const dataElement = node._getMeta("data_element");
27322
27362
  if (dataElement && !PROVIDERS[node.nodeTag]) return;
27323
27363
  if (!dataElement && typeof node.getAttr("remote") === "string") this.#remote ??= new RemoteBinding(this);
27364
+ else if (this.#remote) {
27365
+ this.#remote.close();
27366
+ this.#remote = null;
27367
+ }
27324
27368
  const remoteDependencies = /* @__PURE__ */ new Set();
27325
27369
  if (node._getMeta("gramlot_component")?.bagStore) {
27326
27370
  const storepath = node.getAttr("storepath");
@@ -27361,10 +27405,7 @@ var NodeBinding = class {
27361
27405
  if (typeof handler !== "string" || !handler) throw new TypeError(`${name} requires a handler`);
27362
27406
  return (payload) => {
27363
27407
  if (this.closed) return;
27364
- if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(handler)) {
27365
- const { group, method } = this.runtime.logicRegistry.resolve(handler, node);
27366
- return method.call(group, node, payload);
27367
- }
27408
+ if (isLogicMethod(handler)) return callLogic(this.runtime, node, handler, payload);
27368
27409
  const [, attrs] = node.rootBuilder.runtimeValues(node);
27369
27410
  const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) => !key.startsWith("subscribe_") && !key.startsWith("selfsubscribe_")));
27370
27411
  const values = { ...this.runtime.renderer.references.resolveArguments(authored), p_0: payload };
@@ -27437,6 +27478,7 @@ var NodeBinding = class {
27437
27478
  close() {
27438
27479
  if (this.closed) return;
27439
27480
  this.#closed = true;
27481
+ this.#remote?.close();
27440
27482
  if (this.node._getMeta("data_element")) this.runtime.renderer.references.remove(this.node);
27441
27483
  this.#closeRegistrations();
27442
27484
  const errors = [];
@@ -27799,12 +27841,14 @@ var GramlotRenderer = class extends GramlotHtmlRenderer {
27799
27841
  const { group, method } = binding.gramlot.src.logicRegistry.resolve(name, node);
27800
27842
  return method.call(group, node, keywords);
27801
27843
  },
27802
- invokeScript: (node, name, code, keywords) => this.inlineCompiler.compile(
27844
+ invokeScript: (node, name, code, keywords) => invokeHook(
27845
+ binding,
27803
27846
  node,
27804
27847
  name,
27805
27848
  code,
27849
+ keywords,
27806
27850
  node.parentNode._getMeta("gramlot_component").childParameters[name].inline
27807
- )(keywords)
27851
+ )
27808
27852
  });
27809
27853
  this.records = /* @__PURE__ */ new Map();
27810
27854
  this.references = new References(source);
@@ -29800,6 +29844,710 @@ var IndexLogic = class {
29800
29844
  }
29801
29845
  };
29802
29846
 
29847
+ // src/components/editor-options.js
29848
+ function codeMirrorWithOptions(parent, { datapath, value, language = "text", height = "420px", ...attributes }) {
29849
+ if (!datapath) throw new TypeError("codeMirrorWithOptions requires datapath");
29850
+ const pane = parent.borderContainer({ datapath, height, class: "gramlot-editor-options" });
29851
+ const defaults = {
29852
+ language,
29853
+ indentUnit: 4,
29854
+ fontSize: 14,
29855
+ fontFamily: "monospace",
29856
+ lineNumbers: true,
29857
+ lineWrapping: true,
29858
+ folding: true,
29859
+ bracketMatching: true,
29860
+ autoCloseBrackets: true,
29861
+ autoIndent: true,
29862
+ autocompletion: true,
29863
+ highlightActiveLine: true,
29864
+ highlightSelectionMatches: true
29865
+ };
29866
+ for (const [name, setting] of Object.entries(defaults)) pane.dataSetter({ destination_path: `.settings.${name}`, value: setting });
29867
+ const options = pane.contentPane({
29868
+ region: "right",
29869
+ width: "250px",
29870
+ drawer: "close",
29871
+ drawer_label: "Options",
29872
+ drawer_icon: "\u2699",
29873
+ drawer_minimize: false,
29874
+ padding: "12px",
29875
+ overflow: "auto",
29876
+ class: "gramlot-editor-settings"
29877
+ });
29878
+ options.h3("Editor options");
29879
+ 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" });
29880
+ options.numberTextBox({ value: "^.settings.indentUnit", lbl: "Indent spaces", min: 1, max: 16, dtype: "L", validate_notnull: true });
29881
+ options.numberTextBox({ value: "^.settings.fontSize", lbl: "Font size", min: 8, max: 48, dtype: "L", validate_notnull: true });
29882
+ options.textbox({ value: "^.settings.fontFamily", lbl: "Font family" });
29883
+ const labels = {
29884
+ lineNumbers: "Line numbers",
29885
+ lineWrapping: "Wrap lines",
29886
+ folding: "Code folding",
29887
+ bracketMatching: "Match brackets",
29888
+ autoCloseBrackets: "Close brackets and quotes",
29889
+ autoIndent: "Automatic indentation",
29890
+ autocompletion: "Local completion",
29891
+ highlightActiveLine: "Highlight current line",
29892
+ highlightSelectionMatches: "Highlight matching selections"
29893
+ };
29894
+ for (const [name, label] of Object.entries(labels)) options.checkbox({ value: `^.settings.${name}`, label, display: "block", margin_top: "8px" });
29895
+ const center = pane.contentPane({ region: "center", min_height: 0 });
29896
+ center.codeMirror({ ...attributes, value, height: "100%", ...Object.fromEntries(Object.keys(defaults).map((name) => [name, `^.settings.${name}`])) });
29897
+ return pane;
29898
+ }
29899
+
29900
+ // src/filesystem.js
29901
+ var DirectoryResolver = class _DirectoryResolver extends RemoteResolver {
29902
+ static internalParams = /* @__PURE__ */ new Set([...RemoteResolver.internalParams, "gramlot", "method", "params", "onError"]);
29903
+ #closed = false;
29904
+ #controller = null;
29905
+ constructor({ gramlot, root, path = "", onError }) {
29906
+ super({ cacheTime: -1, onError });
29907
+ this.gramlot = gramlot;
29908
+ this.method = "directory_tree";
29909
+ this.params = { root, path };
29910
+ this.children = /* @__PURE__ */ new Set();
29911
+ }
29912
+ get closed() {
29913
+ return this.#closed;
29914
+ }
29915
+ startLoad(perform) {
29916
+ if (this.loading) return this.loading;
29917
+ const controller = new AbortController();
29918
+ this.#controller = controller;
29919
+ return perform({ controller, method: this.method, params: this.params, ignored: false });
29920
+ }
29921
+ async loadAsync({ controller, method, params }) {
29922
+ const { signal } = controller;
29923
+ let abort;
29924
+ const cancelled = new Promise((_, reject) => {
29925
+ abort = () => reject(signal.reason);
29926
+ signal.addEventListener("abort", abort, { once: true });
29927
+ });
29928
+ try {
29929
+ const value = await Promise.race([this.gramlot.rpc.call("data", method, params, { signal }), cancelled]);
29930
+ if (signal.aborted) throw signal.reason;
29931
+ return value;
29932
+ } finally {
29933
+ signal.removeEventListener("abort", abort);
29934
+ if (this.#controller === controller) this.#controller = null;
29935
+ }
29936
+ }
29937
+ prepareValue(bag) {
29938
+ if (!(bag instanceof Bag)) throw new TypeError("directory_tree must return a Bag");
29939
+ for (const child of this.children) child.abort();
29940
+ this.children.clear();
29941
+ for (const node of bag.getNodes()) {
29942
+ if (node.attr.is_directory) {
29943
+ const resolver = new _DirectoryResolver({
29944
+ gramlot: this.gramlot,
29945
+ root: this.params.root,
29946
+ path: node.attr.path,
29947
+ onError: this.onError
29948
+ });
29949
+ this.children.add(resolver);
29950
+ bag.setResolver(node.label, resolver);
29951
+ }
29952
+ }
29953
+ return bag;
29954
+ }
29955
+ abort() {
29956
+ this.#closed = true;
29957
+ this.#controller?.abort();
29958
+ for (const child of this.children) child.abort();
29959
+ this.children.clear();
29960
+ }
29961
+ };
29962
+ var FileSystemController = class {
29963
+ constructor(gramlot, state) {
29964
+ this.gramlot = gramlot;
29965
+ this.state = state;
29966
+ this.request = null;
29967
+ this.resolver = null;
29968
+ this.disposed = false;
29969
+ }
29970
+ async open(root) {
29971
+ this.request?.abort();
29972
+ const request = this.request = new AbortController();
29973
+ this.state.setItem("status", "Opening directory\u2026");
29974
+ try {
29975
+ const result = await this.gramlot.rpc.call("data", "workspace_open", { root }, { signal: request.signal });
29976
+ if (this.disposed || request.signal.aborted) return null;
29977
+ const resolver = new DirectoryResolver({
29978
+ gramlot: this.gramlot,
29979
+ root: result.root,
29980
+ onError: (error) => this.state.setItem("status", error.message)
29981
+ });
29982
+ const store = resolver.prepareValue(result.entries);
29983
+ this.resolver?.abort();
29984
+ this.resolver = resolver;
29985
+ this.state.setItem("selectedPath", null);
29986
+ this.state.setItem("store", store);
29987
+ this.state.setItem("root", result.root);
29988
+ this.state.setItem("status", "");
29989
+ return result.root;
29990
+ } catch (error) {
29991
+ if (!this.disposed && !request.signal.aborted) this.state.setItem("status", error.message);
29992
+ return null;
29993
+ } finally {
29994
+ if (this.request === request) this.request = null;
29995
+ }
29996
+ }
29997
+ dispose() {
29998
+ this.disposed = true;
29999
+ this.request?.abort();
30000
+ this.resolver?.abort();
30001
+ }
30002
+ };
30003
+ var FileSystemLogic = class {
30004
+ fileSystemMount(node) {
30005
+ this.fileSystems ??= /* @__PURE__ */ new WeakMap();
30006
+ const scope = node.parentNode, state = scope.getRelativeData(".");
30007
+ const controller = new FileSystemController(this.page, state);
30008
+ this.fileSystems.set(state, controller);
30009
+ this.page.src.renderer.onDispose(scope, () => controller.dispose());
30010
+ }
30011
+ fileSystemOpen(node, { root }) {
30012
+ if (root) return this.fileSystems.get(node.getRelativeData(".")).open(root);
30013
+ }
30014
+ };
30015
+ function fileSystemTree(parent, { datapath, ...attributes }) {
30016
+ const pane = parent.div({ datapath, class: "gramlot-filesystem", ...attributes });
30017
+ pane.dataSetter({ destination_path: ".store", value: new Bag() });
30018
+ pane.dataSetter({ destination_path: ".root", value: null });
30019
+ pane.dataSetter({ destination_path: ".requestedRoot", value: null });
30020
+ pane.dataSetter({ destination_path: ".selectedPath", value: null });
30021
+ pane.dataSetter({ destination_path: ".status", value: "" });
30022
+ pane.dataController({ func: "fileSystemMount", _onBuilt: true });
30023
+ pane.dataController({ func: "fileSystemOpen", root: "^.requestedRoot" });
30024
+ pane.tree({
30025
+ storepath: ".store",
30026
+ selectedPath: "^.selectedPath",
30027
+ labelAttribute: "caption",
30028
+ hideValues: true,
30029
+ class: "gramlot-filesystem-tree"
30030
+ });
30031
+ pane.div("^.status", { role: "status", class: "gramlot-filesystem-status" });
30032
+ return pane;
30033
+ }
30034
+
30035
+ // src/ide-documents.js
30036
+ var documentKey = (root, path) => "d_" + [...new TextEncoder().encode(JSON.stringify([root, path]))].map((byte) => byte.toString(16).padStart(2, "0")).join("");
30037
+ var IdeDocuments = class {
30038
+ constructor(gramlot, state) {
30039
+ this.gramlot = gramlot;
30040
+ this.state = state;
30041
+ this.pending = /* @__PURE__ */ new Map();
30042
+ this.disposed = false;
30043
+ }
30044
+ get documents() {
30045
+ return this.state.getItem("documents");
30046
+ }
30047
+ async open(root, path) {
30048
+ const key = documentKey(root, path);
30049
+ const existing = this.documents.getNodes().find((node) => !node.value.getItem("isNew") && node.value.getItem("root") === root && node.value.getItem("path") === path);
30050
+ if (existing) return existing.label;
30051
+ if (this.pending.has(key)) return this.pending.get(key).promise;
30052
+ const request = new AbortController();
30053
+ const promise = this.gramlot.rpc.call("data", "document_read", { root, path }, { signal: request.signal }).then((result) => {
30054
+ if (this.disposed || request.signal.aborted) return null;
30055
+ const document = new Bag();
30056
+ for (const [name, value] of Object.entries({ ...result, root, saved: result.content, busy: false })) document.setItem(name, value);
30057
+ this.documents.setItem(key, document);
30058
+ return key;
30059
+ }).finally(() => this.pending.delete(key));
30060
+ this.pending.set(key, { request, promise });
30061
+ return promise;
30062
+ }
30063
+ newDocument(language, extension, root = "") {
30064
+ const key = `new_${crypto.randomUUID().replaceAll("-", "")}`;
30065
+ const doc = new Bag();
30066
+ for (const [name, value] of Object.entries({
30067
+ language,
30068
+ root,
30069
+ path: `Untitled${extension}`,
30070
+ content: "",
30071
+ saved: "",
30072
+ writable: true,
30073
+ busy: false,
30074
+ isNew: true,
30075
+ createHidden: true,
30076
+ saveRoot: root,
30077
+ savePath: `Untitled${extension}`
30078
+ })) doc.setItem(name, value);
30079
+ this.documents.setItem(key, doc);
30080
+ return key;
30081
+ }
30082
+ async create(key) {
30083
+ const doc = this.documents.getItem(key);
30084
+ if (!doc || !doc.getItem("isNew") || this.pending.has(key)) return false;
30085
+ const root = doc.getItem("saveRoot"), path = doc.getItem("savePath");
30086
+ if (doc.getItem("path").endsWith(".typ.py") !== path.endsWith(".typ.py")) {
30087
+ throw new Error("The .typ.py extension is required for the Typst Python recipe document type.");
30088
+ }
30089
+ const content = doc.getItem("content"), request = new AbortController();
30090
+ doc.setItem("busy", true);
30091
+ const promise = this.gramlot.rpc.call(
30092
+ "data",
30093
+ "document_create",
30094
+ { root, path, content },
30095
+ { signal: request.signal }
30096
+ ).then((result) => {
30097
+ if (this.disposed || request.signal.aborted) return false;
30098
+ doc.setItem("root", result.root);
30099
+ doc.setItem("path", result.path);
30100
+ doc.setItem("revision", result.revision);
30101
+ doc.setItem("saved", content);
30102
+ doc.setItem("isNew", false);
30103
+ doc.setItem("createHidden", true);
30104
+ return true;
30105
+ }).finally(() => {
30106
+ this.pending.delete(key);
30107
+ if (!this.disposed) doc.setItem("busy", false);
30108
+ });
30109
+ this.pending.set(key, { request, promise });
30110
+ return promise;
30111
+ }
30112
+ invalidateRecipe(key) {
30113
+ const doc = this.documents.getItem(key);
30114
+ if (!doc.getItem("path").endsWith(".typ.py")) return;
30115
+ if (doc.getItem("rendering")) this.pending.get(key)?.request.abort();
30116
+ doc.setItem("previewHidden", true);
30117
+ doc.setItem("typstSource", "");
30118
+ doc.setItem("renderStatus", "Generate preview to render the current Python recipe.");
30119
+ }
30120
+ async renderRecipe(key) {
30121
+ const doc = this.documents.getItem(key);
30122
+ if (!doc || !doc.getItem("path").endsWith(".typ.py") || !doc.getItem("writable") || this.pending.has(key)) return false;
30123
+ const content = doc.getItem("content"), request = new AbortController();
30124
+ doc.setItem("busy", true);
30125
+ doc.setItem("rendering", true);
30126
+ doc.setItem("previewHidden", true);
30127
+ doc.setItem("typstSource", "");
30128
+ doc.setItem("renderStatus", "Generating Typst on the server\u2026");
30129
+ const promise = this.gramlot.rpc.call(
30130
+ "data",
30131
+ "document_render_typst",
30132
+ { content },
30133
+ { signal: request.signal }
30134
+ ).then((result) => {
30135
+ if (this.disposed || request.signal.aborted || doc.getItem("content") !== content) return false;
30136
+ doc.setItem("typstSource", result.source);
30137
+ doc.setItem("previewHidden", false);
30138
+ doc.setItem("renderStatus", "Typst generated from the current recipe.");
30139
+ return true;
30140
+ }).catch((error) => {
30141
+ if (!this.disposed && !request.signal.aborted) doc.setItem("renderStatus", error.message);
30142
+ return false;
30143
+ }).finally(() => {
30144
+ this.pending.delete(key);
30145
+ if (!this.disposed) {
30146
+ doc.setItem("rendering", false);
30147
+ doc.setItem("busy", false);
30148
+ }
30149
+ });
30150
+ this.pending.set(key, { request, promise });
30151
+ return promise;
30152
+ }
30153
+ dirty(key) {
30154
+ const doc = this.documents.getItem(key);
30155
+ return doc && doc.getItem("content") !== doc.getItem("saved");
30156
+ }
30157
+ async save(key) {
30158
+ const doc = this.documents.getItem(key);
30159
+ if (!doc || doc.getItem("isNew") || !this.dirty(key) || !doc.getItem("writable") || this.pending.has(key)) return false;
30160
+ const content = doc.getItem("content"), request = new AbortController();
30161
+ doc.setItem("busy", true);
30162
+ const promise = this.gramlot.rpc.call("data", "document_save", {
30163
+ root: doc.getItem("root"),
30164
+ path: doc.getItem("path"),
30165
+ content,
30166
+ revision: doc.getItem("revision")
30167
+ }, { signal: request.signal }).then((result) => {
30168
+ if (this.disposed || request.signal.aborted) return false;
30169
+ doc.setItem("revision", result.revision);
30170
+ doc.setItem("saved", content);
30171
+ return true;
30172
+ }).finally(() => {
30173
+ this.pending.delete(key);
30174
+ if (!this.disposed) doc.setItem("busy", false);
30175
+ });
30176
+ this.pending.set(key, { request, promise });
30177
+ return promise;
30178
+ }
30179
+ revert(key) {
30180
+ const doc = this.documents.getItem(key);
30181
+ if (!doc || !this.dirty(key) || this.pending.has(key)) return false;
30182
+ doc.setItem("content", doc.getItem("saved"));
30183
+ return true;
30184
+ }
30185
+ canClose(key, discard = false) {
30186
+ return !this.pending.has(key) && (discard || !this.dirty(key));
30187
+ }
30188
+ close(key, discard = false) {
30189
+ if (!this.canClose(key, discard)) return false;
30190
+ this.documents.popNode(key);
30191
+ if (this.state.getItem("active") === key) this.state.setItem("active", this.documents.getNodes()[0]?.label ?? null);
30192
+ return true;
30193
+ }
30194
+ dispose() {
30195
+ this.disposed = true;
30196
+ for (const { request } of this.pending.values()) request.abort();
30197
+ }
30198
+ };
30199
+ var RecentWorkspaces = class {
30200
+ constructor(storage) {
30201
+ this.storage = storage;
30202
+ this.key = "gramlot.ide.recentWorkspaces";
30203
+ }
30204
+ read() {
30205
+ const stored = this.storage.getItem(this.key);
30206
+ const roots = stored === null ? [] : JSON.parse(stored);
30207
+ if (!Array.isArray(roots) || roots.some((root) => typeof root !== "string" || !root)) throw new TypeError("Invalid recent workspace preference");
30208
+ return roots.slice(0, 6);
30209
+ }
30210
+ remember(root) {
30211
+ const roots = [root, ...this.read().filter((item) => item !== root)].slice(0, 6);
30212
+ this.storage.setItem(this.key, JSON.stringify(roots));
30213
+ return roots;
30214
+ }
30215
+ choices(roots = this.read()) {
30216
+ const bag = new Bag();
30217
+ roots.forEach((root, index) => bag.setItem(`r${index}`, root, { caption: root }));
30218
+ return bag;
30219
+ }
30220
+ };
30221
+
30222
+ // src/ide-runtime.js
30223
+ var IdeLogic = class {
30224
+ fileSystemMount(node) {
30225
+ return FileSystemLogic.prototype.fileSystemMount.call(this, node);
30226
+ }
30227
+ fileSystemOpen(node, args) {
30228
+ return FileSystemLogic.prototype.fileSystemOpen.call(this, node, args);
30229
+ }
30230
+ ideMount(node) {
30231
+ this.ideRoot = node.parentNode;
30232
+ this.ideState = node.getRelativeData(".");
30233
+ this.ideDocuments = new IdeDocuments(this.page, this.ideState);
30234
+ this.idePanels = /* @__PURE__ */ new Map();
30235
+ this.ideDisposed = false;
30236
+ this.ideRequested = 0;
30237
+ this.ideRecent = new RecentWorkspaces(this.page.src.renderer.destination.ownerDocument.defaultView.sessionStorage);
30238
+ const roots = this.ideRecent.read();
30239
+ this.ideState.setItem("recent", this.ideRecent.choices(roots));
30240
+ this.ideState.setItem("workspace", roots[0] ?? "");
30241
+ const browser = this.ideState.getItem("browser");
30242
+ browser.subscribe("ide-browser", { any: (event) => {
30243
+ if (event.node === browser.getNode("root")) {
30244
+ const root = browser.getItem("root");
30245
+ this.ideState.setItem("workspace", root);
30246
+ this.ideState.setItem("recent", this.ideRecent.choices(this.ideRecent.remember(root)));
30247
+ this.ideState.setItem("status", `Workspace: ${root}`);
30248
+ } else if (event.node === browser.getNode("selectedPath")) {
30249
+ const path = browser.getItem("selectedPath");
30250
+ const item = path === null ? null : browser.getItem("store").getNode(path);
30251
+ if (item && !item.attr.is_directory) void this.ideOpenDocument(browser.getItem("root"), item.attr.path);
30252
+ }
30253
+ } });
30254
+ this.ideDocuments.documents.subscribe("ide-documents", { any: (event) => {
30255
+ if (!["content", "saved", "busy", "writable", "view", "isNew", "path", "root"].includes(event.node.label)) return;
30256
+ for (const [key, pane] of this.idePanels) {
30257
+ const doc = this.ideDocuments.documents.getItem(key);
30258
+ if (doc) {
30259
+ if (event.node === doc.getNode("content")) this.ideDocuments.invalidateRecipe(key);
30260
+ this.ideDocumentState(key);
30261
+ pane.setAttr({ title: `${this.ideDocuments.dirty(key) ? "\u25CF " : ""}${doc.getItem("path")}` });
30262
+ }
30263
+ }
30264
+ } });
30265
+ this.page.src.renderer.onDispose(this.ideRoot, () => {
30266
+ this.ideDisposed = true;
30267
+ browser.unsubscribe("ide-browser", { any: true });
30268
+ this.ideDocuments.documents.unsubscribe("ide-documents", { any: true });
30269
+ this.ideDocuments.dispose();
30270
+ });
30271
+ }
30272
+ ideOpenWorkspace() {
30273
+ const root = this.ideState.getItem("workspace");
30274
+ if (root && root !== this.ideState.getItem("browser.root")) this.ideState.setItem("browser.requestedRoot", root);
30275
+ }
30276
+ ideDocumentState(key) {
30277
+ const doc = this.ideDocuments.documents.getItem(key);
30278
+ const disabled = !this.ideDocuments.dirty(key) && !doc.getItem("isNew") || doc.getItem("busy");
30279
+ doc.setItem("saveDisabled", Boolean(disabled || !doc.getItem("writable")));
30280
+ doc.setItem("revertDisabled", Boolean(!this.ideDocuments.dirty(key) || doc.getItem("busy")));
30281
+ doc.setItem("displayPath", doc.getItem("isNew") ? doc.getItem("path") : `${doc.getItem("root")}/${doc.getItem("path")}`);
30282
+ doc.setItem("pdfFilename", doc.getItem("path").split("/").at(-1).replace(/\.typ(?:\.py)?$/i, ".pdf"));
30283
+ doc.setItem("renderDisabled", Boolean(doc.getItem("busy") || !doc.getItem("writable")));
30284
+ this.ideHistoryState(doc);
30285
+ }
30286
+ async ideOpenDocument(root, path) {
30287
+ const requested = ++this.ideRequested;
30288
+ try {
30289
+ const key = await this.ideDocuments.open(root, path);
30290
+ if (key === null || this.ideDisposed) return;
30291
+ this.ideShowDocument(key);
30292
+ if (requested === this.ideRequested) {
30293
+ this.ideState.setItem("active", key);
30294
+ this.ideState.setItem("status", `${path}${this.ideDocuments.documents.getItem(key).getItem("writable") ? "" : " (read only)"}`);
30295
+ }
30296
+ } catch (error) {
30297
+ if (!this.ideDisposed) this.ideState.setItem("status", error.message);
30298
+ }
30299
+ }
30300
+ ideNew() {
30301
+ const type = this.ideState.getItem("newType");
30302
+ const language = type === "typstRecipe" ? "python" : type;
30303
+ const extensions = {
30304
+ typstRecipe: ".typ.py",
30305
+ typst: ".typ",
30306
+ markdown: ".md",
30307
+ html: ".html",
30308
+ python: ".py",
30309
+ javascript: ".js",
30310
+ typescript: ".ts",
30311
+ json: ".json",
30312
+ css: ".css",
30313
+ sql: ".sql",
30314
+ xml: ".xml",
30315
+ text: ".txt"
30316
+ };
30317
+ const key = this.ideDocuments.newDocument(language, extensions[type], this.ideState.getItem("workspace"));
30318
+ ++this.ideRequested;
30319
+ this.ideShowDocument(key);
30320
+ this.ideState.setItem("active", key);
30321
+ this.ideState.setItem("status", "New document. Choose directory and name when saving.");
30322
+ }
30323
+ ideShowDocument(key) {
30324
+ const document = this.ideDocuments.documents.getItem(key);
30325
+ const path = document.getItem("path");
30326
+ if (!this.idePanels.has(key)) {
30327
+ const doc = this.ideDocuments.documents.getItem(key);
30328
+ const recipe = path.endsWith(".typ.py");
30329
+ if (recipe) this.ideDocuments.invalidateRecipe(key);
30330
+ doc.setItem("readonly", !doc.getItem("writable"));
30331
+ this.ideDocumentState(key);
30332
+ doc.setItem("view", "code");
30333
+ doc.setItem("createHidden", true);
30334
+ doc.setItem("undoDisabled", true);
30335
+ doc.setItem("redoDisabled", true);
30336
+ const tabs = this.ideRoot.value.getNode("frame.center.tabs");
30337
+ const pane = sourceTarget(tabs.builder.wrapSource(tabs).contentPane({
30338
+ node_label: key,
30339
+ title: path,
30340
+ pageName: key,
30341
+ documentKey: key,
30342
+ closable: true,
30343
+ onClose: "ideClose",
30344
+ height: "100%"
30345
+ }));
30346
+ this.idePanels.set(key, pane);
30347
+ const target = pane.builder.wrapSource(pane).div({ display: "flex", flex_direction: "column", height: "100%" });
30348
+ const toolbar = target.div({
30349
+ datapath: `.documents.${key}`,
30350
+ display: "flex",
30351
+ align_items: "center",
30352
+ gap: "6px",
30353
+ padding: "4px 12px",
30354
+ height: "40px",
30355
+ flex_shrink: 0,
30356
+ box_sizing: "border-box",
30357
+ class: "gramlot-ide-document-toolbar",
30358
+ role: "toolbar",
30359
+ "aria-label": `Commands for ${path}`
30360
+ });
30361
+ for (const [name, path2, label, func] of [
30362
+ ["save", "M5 3h12l4 4v14H3V3h2 M7 3v6h10V3 M7 21v-8h10v8", "Save", "ideSave"],
30363
+ ["revert", "M3 10a9 9 0 1 1 2 8 M3 4v6h6 M12 7v5l3 2", "Revert to saved", "ideRevert"],
30364
+ ["undo", "M9 5 3 11l6 6 M3 11h12a6 6 0 0 1 6 6v2", "Undo", "ideUndo"],
30365
+ ["redo", "m15 5 6 6-6 6 M21 11H9a6 6 0 0 0-6 6v2", "Redo", "ideRedo"]
30366
+ ]) {
30367
+ const button = toolbar.button({
30368
+ title: label,
30369
+ "aria-label": label,
30370
+ disabled: `^.${name}Disabled`,
30371
+ class: `button--quiet gramlot-ide-${name}`
30372
+ });
30373
+ button.svg({
30374
+ viewBox: "0 0 24 24",
30375
+ width: 18,
30376
+ height: 18,
30377
+ fill: "none",
30378
+ stroke: "currentColor",
30379
+ stroke_width: 1.7,
30380
+ stroke_linecap: "round",
30381
+ stroke_linejoin: "round",
30382
+ "aria-hidden": "true"
30383
+ }).path({ d: path2 });
30384
+ button.dataController({ func, documentKey: key });
30385
+ }
30386
+ if (recipe) toolbar.button("Generate preview", { disabled: "^.renderDisabled", class: "button--quiet" }).dataController({ func: "ideRenderRecipe", documentKey: key });
30387
+ toolbar.div("^.displayPath", {
30388
+ class: "gramlot-ide-document-path",
30389
+ overflow: "hidden",
30390
+ text_overflow: "ellipsis",
30391
+ white_space: "nowrap",
30392
+ min_width: 0,
30393
+ flex: "1"
30394
+ });
30395
+ const form = target.div({
30396
+ datapath: `.documents.${key}`,
30397
+ hidden: "^.createHidden",
30398
+ padding: "8px 12px",
30399
+ display: "flex",
30400
+ gap: "8px",
30401
+ align_items: "end",
30402
+ flex_shrink: 0
30403
+ });
30404
+ form.textbox({ value: "^.saveRoot", lbl: "Directory", flex: "1", disabled: "^.busy" });
30405
+ form.textbox({ value: "^.savePath", lbl: "File name", flex: "1", disabled: "^.busy" });
30406
+ form.button("Create file", { disabled: "^.busy" }).dataController({ func: "ideCreate", documentKey: key });
30407
+ form.button("Cancel", { disabled: "^.busy", class: "button--quiet" }).dataController({ func: "ideCancelCreate", documentKey: key });
30408
+ const editorArea = target.div({ flex: "1", min_height: 0 });
30409
+ const html = doc.getItem("language") === "html";
30410
+ const markdown = doc.getItem("language") === "markdown";
30411
+ const rich = html || markdown;
30412
+ const typst = doc.getItem("language") === "typst";
30413
+ const preview = rich || typst || recipe;
30414
+ const views = preview ? editorArea.tabContainer({ height: "100%", selectedPage: `^.documents.${key}.view` }) : null;
30415
+ const code = preview ? views.contentPane({ title: "Code", pageName: "code", height: "100%" }) : editorArea;
30416
+ codeMirrorWithOptions(code, {
30417
+ datapath: `.documents.${key}`,
30418
+ value: "^.content",
30419
+ language: doc.getItem("language"),
30420
+ height: "100%",
30421
+ readonly: "^.readonly",
30422
+ nodeId: `editor_${key}`,
30423
+ editorView: "code",
30424
+ selfsubscribe_historyChanged: "ideHistoryChanged"
30425
+ });
30426
+ target.dataController({ func: "ideSave", documentKey: key, [`subscribe_editor_${key}_save`]: true });
30427
+ if (typst) views.contentPane({ title: "Preview", pageName: "preview", height: "100%" }).typstPreview({ value: `^.documents.${key}.content`, filename: `^.documents.${key}.pdfFilename`, height: "100%" });
30428
+ if (recipe) {
30429
+ const output = views.contentPane({ title: "Preview", pageName: "preview", height: "100%", display: "flex", flex_direction: "column" });
30430
+ output.div(`^.documents.${key}.renderStatus`, { role: "status", padding: "8px 12px", white_space: "pre-wrap", overflow: "auto", max_height: "30%" });
30431
+ output.typstPreview({
30432
+ value: `^.documents.${key}.typstSource`,
30433
+ filename: `^.documents.${key}.pdfFilename`,
30434
+ hidden: `^.documents.${key}.previewHidden`,
30435
+ flex: "1",
30436
+ min_height: 0
30437
+ });
30438
+ views.contentPane({ title: "Generated Typst", pageName: "generated", height: "100%" }).codeMirror({ value: `^.documents.${key}.typstSource`, language: "typst", readonly: true, height: "100%" });
30439
+ }
30440
+ if (rich) {
30441
+ const previewPane = views.contentPane({ title: "Preview", pageName: "preview", height: "100%", display: "flex", flex_direction: "column" });
30442
+ if (markdown) {
30443
+ doc.setItem("allowHtml", false);
30444
+ previewPane.checkbox({ value: `^.documents.${key}.allowHtml`, label: "Allow embedded HTML", class: "gramlot-ide-allow-html", padding: "8px 12px", flex_shrink: 0 });
30445
+ }
30446
+ previewPane[html ? "htmlPreview" : "markdownPreview"]({
30447
+ value: `^.documents.${key}.content`,
30448
+ flex: "1",
30449
+ min_height: 0,
30450
+ ...markdown ? { allowHtml: `^.documents.${key}.allowHtml` } : {}
30451
+ });
30452
+ views.contentPane({ title: "Rich text", pageName: "rich", height: "100%" })[html ? "htmlEditor" : "markdownEditor"]({
30453
+ datapath: `.documents.${key}`,
30454
+ value: "^.content",
30455
+ readonly: "^.readonly",
30456
+ height: "100%",
30457
+ nodeId: `rich_editor_${key}`,
30458
+ editorView: "rich",
30459
+ selfsubscribe_historyChanged: "ideHistoryChanged"
30460
+ });
30461
+ target.dataController({ func: "ideSave", documentKey: key, [`subscribe_rich_editor_${key}_save`]: true });
30462
+ }
30463
+ }
30464
+ }
30465
+ async ideRenderRecipe(node, { documentKey: documentKey2 }) {
30466
+ const doc = this.ideDocuments.documents.getItem(documentKey2);
30467
+ doc.setItem("view", "preview");
30468
+ await this.ideDocuments.renderRecipe(documentKey2);
30469
+ }
30470
+ ideCancelCreate(node, { documentKey: documentKey2 }) {
30471
+ this.ideDocuments.documents.getItem(documentKey2).setItem("createHidden", true);
30472
+ }
30473
+ async ideCreate(node, { documentKey: documentKey2 }) {
30474
+ this.ideState.setItem("status", "Creating file\u2026");
30475
+ try {
30476
+ const saved = await this.ideDocuments.create(documentKey2);
30477
+ if (!this.ideDisposed && saved) {
30478
+ this.ideState.setItem("status", "File created.");
30479
+ const browser = this.ideState.getItem("browser");
30480
+ if (browser.getItem("root")) await this.fileSystems.get(browser).open(browser.getItem("root"));
30481
+ }
30482
+ } catch (error) {
30483
+ if (!this.ideDisposed) this.ideState.setItem("status", error.message);
30484
+ }
30485
+ }
30486
+ async ideSave(node, { documentKey: documentKey2 = null } = {}) {
30487
+ const key = documentKey2 ?? this.ideState.getItem("active");
30488
+ if (!key || this.ideDocuments.documents.getItem(key).getItem("saveDisabled")) return;
30489
+ const doc = this.ideDocuments.documents.getItem(key);
30490
+ if (doc.getItem("isNew")) {
30491
+ doc.setItem("createHidden", false);
30492
+ return;
30493
+ }
30494
+ this.ideState.setItem("status", "Saving\u2026");
30495
+ try {
30496
+ const saved = await this.ideDocuments.save(key);
30497
+ if (!this.ideDisposed) this.ideState.setItem("status", saved ? "Saved." : "Document is read only or a request is pending.");
30498
+ } catch (error) {
30499
+ if (!this.ideDisposed) this.ideState.setItem("status", error.message);
30500
+ }
30501
+ }
30502
+ ideRevert(node, { documentKey: documentKey2 }) {
30503
+ if (this.ideDocuments.revert(documentKey2)) this.ideState.setItem("status", "Restored the last saved version.");
30504
+ }
30505
+ ideHistoryChanged(node, { canUndo, canRedo }) {
30506
+ const doc = node.getRelativeData(".");
30507
+ const view = node.getAttr("editorView");
30508
+ doc.setItem(`${view}CanUndo`, canUndo);
30509
+ doc.setItem(`${view}CanRedo`, canRedo);
30510
+ this.ideHistoryState(doc);
30511
+ }
30512
+ ideHistoryState(doc) {
30513
+ const view = doc.getItem("view");
30514
+ doc.setItem("undoDisabled", !doc.getItem(`${view}CanUndo`));
30515
+ doc.setItem("redoDisabled", !doc.getItem(`${view}CanRedo`));
30516
+ }
30517
+ ideEditor(documentKey2) {
30518
+ const rich = this.ideDocuments.documents.getItem(documentKey2).getItem("view") === "rich";
30519
+ const node = this.page.src.binding.nodeIds.get(`${rich ? "rich_" : ""}editor_${documentKey2}`);
30520
+ return this.page.src.renderer.records.get(node).element;
30521
+ }
30522
+ ideUndo(node, { documentKey: documentKey2 }) {
30523
+ this.ideEditor(documentKey2).undo();
30524
+ }
30525
+ ideRedo(node, { documentKey: documentKey2 }) {
30526
+ this.ideEditor(documentKey2).redo();
30527
+ }
30528
+ ideClose(node) {
30529
+ const key = node.getAttr("documentKey");
30530
+ if (!this.ideDocuments.canClose(key)) {
30531
+ this.ideState.setItem("status", "Save or revert your changes before closing. Pending operations must finish first.");
30532
+ return false;
30533
+ }
30534
+ return true;
30535
+ }
30536
+ ideClosed(node, { pageName }) {
30537
+ this.ideForgetDocument(pageName);
30538
+ }
30539
+ ideForgetDocument(key, discard = false) {
30540
+ const document = this.ideDocuments.documents.getItem(key);
30541
+ const browser = this.ideState.getItem("browser"), selectedPath = browser.getItem("selectedPath");
30542
+ const selected = selectedPath === null ? null : browser.getItem("store").getNode(selectedPath);
30543
+ if (document && browser.getItem("root") === document.getItem("root") && selected?.attr.path === document.getItem("path")) {
30544
+ browser.setItem("selectedPath", null);
30545
+ }
30546
+ this.idePanels.delete(key);
30547
+ this.ideDocuments.close(key, discard);
30548
+ }
30549
+ };
30550
+
29803
30551
  // src/navigation-resolver.js
29804
30552
  var NavigationResolver = class _NavigationResolver extends RemoteResolver {
29805
30553
  static internalParams = /* @__PURE__ */ new Set([...RemoteResolver.internalParams, "gramlot", "method", "params", "onError"]);
@@ -30364,8 +31112,11 @@ function parseDateExpression(text, options = {}) {
30364
31112
  export {
30365
31113
  Bag,
30366
31114
  BagNode,
31115
+ DirectoryResolver,
30367
31116
  DomHandler,
30368
31117
  Exposed,
31118
+ FileSystemController,
31119
+ FileSystemLogic,
30369
31120
  FramePage,
30370
31121
  Gramlot,
30371
31122
  GramlotBuilder,
@@ -30374,6 +31125,7 @@ export {
30374
31125
  GramlotSvgRenderer,
30375
31126
  Handler,
30376
31127
  HttpTransport,
31128
+ IdeLogic,
30377
31129
  InOut,
30378
31130
  IndexLogic,
30379
31131
  IndexPage,
@@ -30386,7 +31138,9 @@ export {
30386
31138
  ServerAdapter,
30387
31139
  SourceHandler,
30388
31140
  UtilitiesHandler,
31141
+ codeMirrorWithOptions,
30389
31142
  createDecimal,
31143
+ fileSystemTree,
30390
31144
  mountIndexPage,
30391
31145
  parseDateExpression
30392
31146
  };