@gramlot/gramlot 0.3.7 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/components/editors.js +116527 -0
  2. package/dist/components/inputs.js +24507 -0
  3. package/dist/components/layout.js +1402 -0
  4. package/dist/components/tree.js +24538 -0
  5. package/dist/components/typst.js +4 -0
  6. package/dist/gramlot.js +1442 -625
  7. package/dist/gramlot.min.js +27 -405
  8. package/dist/runtime-notices.json +208 -0
  9. package/dist/typst-worker-source.js +4 -0
  10. package/package.json +36 -3
  11. package/src/binding/hooks.js +14 -0
  12. package/src/binding/providers.js +4 -0
  13. package/src/binding/remote-resolver.js +52 -0
  14. package/src/binding/remote.js +2 -0
  15. package/src/binding/router.js +11 -4
  16. package/src/binding/rpc-resolver.js +14 -93
  17. package/src/binding/runtime.js +10 -4
  18. package/src/components/bases.js +1 -0
  19. package/src/components/border-container.js +46 -23
  20. package/src/components/buttons.js +3 -0
  21. package/src/components/choice-editor.js +17 -3
  22. package/src/components/choices.js +3 -2
  23. package/src/components/code-mirror-engine.js +91 -0
  24. package/src/components/code-mirror.js +88 -0
  25. package/src/components/editor-options.d.ts +9 -0
  26. package/src/components/editor-options.js +21 -0
  27. package/src/components/editors.js +10 -0
  28. package/src/components/html-document.js +56 -0
  29. package/src/components/html-editor.js +68 -0
  30. package/src/components/html-preview.js +33 -0
  31. package/src/components/inputs.js +2 -2
  32. package/src/components/jodit-engine.js +89 -0
  33. package/src/components/markdown-codec.js +35 -0
  34. package/src/components/markdown-document.js +14 -0
  35. package/src/components/markdown-editor.js +68 -0
  36. package/src/components/prose-mirror-engine.js +65 -0
  37. package/src/components/registry.js +6 -4
  38. package/src/components/tree.js +350 -0
  39. package/src/components/typst-client.js +38 -0
  40. package/src/components/typst-preview.js +88 -0
  41. package/src/components/typst-worker.js +49 -0
  42. package/src/components/typst.js +4 -0
  43. package/src/filesystem.d.ts +22 -0
  44. package/src/filesystem.js +122 -0
  45. package/src/ide-documents.js +153 -0
  46. package/src/ide-runtime.d.ts +18 -0
  47. package/src/ide-runtime.js +238 -0
  48. package/src/index-page-runtime.d.ts +7 -8
  49. package/src/index-page-runtime.js +100 -396
  50. package/src/index.d.ts +7 -1
  51. package/src/index.js +5 -1
  52. package/src/navigation-resolver.d.ts +6 -0
  53. package/src/navigation-resolver.js +60 -0
  54. package/src/renderer/attributes.js +2 -1
  55. package/src/renderer/drag-drop-policy.js +48 -0
  56. package/src/renderer/drag-drop.js +213 -0
  57. package/src/renderer/drag-preparation.js +33 -0
  58. package/src/renderer/gramlot-renderer.d.ts +18 -0
  59. package/src/renderer/gramlot-renderer.js +41 -2
  60. package/src/server/frame-page.d.ts +12 -0
  61. package/src/server/frame-page.js +23 -0
  62. package/src/server/gramlot-server.js +2 -1
  63. package/src/server/index-page.d.ts +10 -14
  64. package/src/server/index-page.js +26 -95
  65. package/src/server/page.d.ts +7 -0
  66. package/src/server/page.js +5 -0
  67. package/src/view/button.js +2 -1
  68. package/src/view/controls.js +7 -11
  69. package/src/view/events.js +4 -8
  70. package/src/view/html.js +6 -1
  71. package/tools/gramlot-tools-inspector.js +16 -9
@@ -0,0 +1,350 @@
1
+ /** Bag hierarchy, lazy branch expansion, captions and path selection. */
2
+ import {Bag} from '@gramlot/gramlot';
3
+ import createDOMPurify from 'dompurify';
4
+ import {defineComponent, defineCollection} from './registry.js';
5
+ import {Container} from './container.js';
6
+ import {SVG_NS} from '../renderer/attributes.js';
7
+
8
+ export const Tree = defineComponent({
9
+ name: 'tree', tag: 'gramlot-tree', base: Container, sourceContext: true, bagStore: true, dragSource: true,
10
+ parameters: {
11
+ storepath: {dtype: 'T'},
12
+ draggable: {dtype: 'B', default: false, binding: 'read'},
13
+ labelAttribute: {dtype: 'T', nullable: true, default: null, binding: 'read'},
14
+ hideValues: {dtype: 'B', default: false, binding: 'read'},
15
+ labelCb: {dtype: 'T', nullable: true, default: null},
16
+ getLabel: {dtype: 'T', nullable: true, default: null},
17
+ getLabelClass: {dtype: 'T', nullable: true, default: null},
18
+ getIconClass: {dtype: 'T', nullable: true, default: null},
19
+ selectedLabelClass: {dtype: 'T', default: '', binding: 'read'},
20
+ autoCollapse: {dtype: 'B', default: false, binding: 'read'},
21
+ selectedPath: {dtype: 'T', nullable: true, default: null, binding: 'twoWay'}
22
+ },
23
+ implementation: Base => class extends Base {
24
+ #store;
25
+ #sanitizer;
26
+ #context;
27
+ #expanded = new Set();
28
+ #rows = new Map();
29
+ #dragRows = new WeakMap();
30
+ #presentations = new Map();
31
+ #requestedPath;
32
+ #selectedPath = null;
33
+ #scheduled = false;
34
+ #loading = new Set();
35
+ #errors = new Map();
36
+
37
+ constructor() {
38
+ super();
39
+ this.#sanitizer = createDOMPurify(this.ownerDocument.defaultView);
40
+ this.control.replaceChildren();
41
+ this.control.setAttribute('role', 'tree');
42
+ this.control.setAttribute('aria-label', 'Tree');
43
+ this.control.classList.add('tree');
44
+ this.control.setAttribute('part', 'tree');
45
+ const style = this.ownerDocument.createElement('style');
46
+ style.textContent = `
47
+ .control-box{overflow:auto;padding:4px;min-height:32px}
48
+ ul{list-style:none;margin:0;padding:0} ul ul{padding-inline-start:20px}
49
+ .row{display:flex;align-items:center;min-height:var(--gramlot-tree-row-height,28px);gap:4px;border-radius:3px;cursor:default}
50
+ .row:hover{background:var(--gramlot-tree-hover-background,var(--gramlot-field-readonly-background,#f2f4f7))}
51
+ .canBeDropped{outline:2px solid var(--gramlot-brand-blue,#3766b5);outline-offset:-2px}
52
+ .cannotBeDropped{outline:2px dashed currentColor;outline-offset:-2px}.draggedItem{opacity:.75}
53
+ [role=treeitem][aria-selected=true]>.row{background:var(--gramlot-tree-selected-background,#e3edff);
54
+ color:var(--gramlot-tree-selected-color,#214f91)}
55
+ [role=treeitem]:focus{outline:none}
56
+ [role=treeitem]:focus-visible>.row{outline:2px solid var(--gramlot-brand-blue,#3766b5);outline-offset:-2px}
57
+ button{border:0;background:transparent;color:inherit;width:24px;height:24px;padding:0;font:inherit;cursor:pointer}
58
+ .spacer{width:24px;flex:none}.caption{min-width:0;overflow-wrap:anywhere}
59
+ .icon{width:16px;height:16px;flex:none;background:currentColor;opacity:.7;mask:center/contain no-repeat;
60
+ mask-image:url("data:image/svg+xml,%3Csvg xmlns='${SVG_NS}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M5 3h9l5 5v13H5zM14 3v6h5M8 13h8M8 17h8'/%3E%3C/svg%3E")}
61
+ .branch-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${SVG_NS}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 7V4h7l3 3h8v13H3z'/%3E%3C/svg%3E")}
62
+ .opened-icon{mask-image:url("data:image/svg+xml,%3Csvg xmlns='${SVG_NS}' viewBox='0 0 24 24'%3E%3Cpath fill='none' stroke='black' stroke-width='1.7' d='M3 19V4h7l3 3h8v3M3 20l3-9h16l-3 9z'/%3E%3C/svg%3E")}
63
+ .loading>.row{opacity:.65}.error>.row .caption{text-decoration:underline dotted}
64
+ [hidden]{display:none}`;
65
+ this.shadowRoot.append(style);
66
+ }
67
+ setSourceContext(context) { this.#context = context; }
68
+ /** Read only the rendered row and its BagNode; never request a resolver value. */
69
+ getDragContext(event) {
70
+ for (const element of event.composedPath()) {
71
+ const row = this.#dragRows.get(element);
72
+ if (!row) continue;
73
+ const {item, path, caption} = row;
74
+ return {element, item, path, dragValues: {
75
+ 'text/plain': caption.textContent,
76
+ nodeattr: {...item.getAttr()},
77
+ treenode: {fullpath: item.fullpath, relpath: path}
78
+ }};
79
+ }
80
+ return null;
81
+ }
82
+ setStoreBag(bag) {
83
+ if (!(bag instanceof Bag)) throw new TypeError('tree storepath must resolve to a Bag');
84
+ if (bag !== this.#store) {
85
+ this.#store = bag;
86
+ this.#expanded.clear();
87
+ this.#errors.clear();
88
+ this.#requestedPath = undefined;
89
+ }
90
+ this.#schedule();
91
+ }
92
+ projectAttributes(attrs, adapt) {
93
+ const rest = super.projectAttributes(attrs, adapt);
94
+ this.#schedule();
95
+ return rest;
96
+ }
97
+ connectedCallback() { this.#schedule(); }
98
+ #schedule() {
99
+ if (this.#scheduled) return;
100
+ this.#scheduled = true;
101
+ queueMicrotask(() => {
102
+ this.#scheduled = false;
103
+ if (this.isConnected && this.#store) this.#render();
104
+ });
105
+ }
106
+ #render() {
107
+ const focused = this.shadowRoot.activeElement?.closest('[role=treeitem]')?.dataset.path;
108
+ const items = new Map(), seen = new Set();
109
+ const visit = (bag, prefix, ancestors) => {
110
+ if (seen.has(bag)) throw new TypeError('tree requires an acyclic Bag store');
111
+ seen.add(bag);
112
+ for (const node of bag.getNodes()) {
113
+ const path = prefix ? `${prefix}.${node.label}` : node.label;
114
+ const value = node.staticValue; // Rendering never evaluates resolvers.
115
+ items.set(path, {node, ancestors, children: value instanceof Bag ? value : null});
116
+ if (value instanceof Bag) visit(value, path, [...ancestors, node]);
117
+ }
118
+ seen.delete(bag);
119
+ };
120
+ visit(this.#store, '', []);
121
+ const identities = new Set([...items.values()].map(item => item.node));
122
+ for (const node of this.#expanded) if (!identities.has(node)) this.#expanded.delete(node);
123
+ for (const node of this.#errors.keys()) if (!identities.has(node)) this.#errors.delete(node);
124
+ const requested = this.parameters.selectedPath;
125
+ if (requested !== this.#requestedPath) {
126
+ this.#requestedPath = requested;
127
+ this.#selectedPath = requested;
128
+ for (const node of items.get(requested)?.ancestors ?? []) this.#expand(node);
129
+ }
130
+ const selected = this.#selectedPath;
131
+ this.#rows.clear();
132
+ this.#dragRows = new WeakMap();
133
+ this.#presentations.clear();
134
+ const branchSync = new Map();
135
+ const build = (bag, prefix, parent) => {
136
+ const list = this.ownerDocument.createElement('ul');
137
+ list.className = 'group'; list.setAttribute('part', 'group');
138
+ list.setAttribute('role', 'group');
139
+ for (const node of bag.getNodes()) {
140
+ const path = prefix ? `${prefix}.${node.label}` : node.label;
141
+ const {children} = items.get(path);
142
+ const scalar = children === null && !this.parameters.hideValues && (node.resolver === null || !node.resolver.expired);
143
+ const branch = children !== null ? children.length > 0
144
+ : scalar || (node.resolver !== null && node.attr.child_count !== 0);
145
+ const entry = this.ownerDocument.createElement('li');
146
+ entry.className = `node ${branch ? 'branch' : 'leaf'}`;
147
+ entry.setAttribute('part', `node ${branch ? 'branch' : 'leaf'}`);
148
+ entry.classList.toggle('loading', this.#loading.has(node));
149
+ entry.classList.toggle('error', this.#errors.has(node));
150
+ entry.setAttribute('aria-busy', String(this.#loading.has(node)));
151
+ entry.setAttribute('role', 'treeitem');
152
+ entry.setAttribute('aria-selected', String(selected === path));
153
+ entry.classList.toggle('selected', selected === path);
154
+ entry.dataset.path = path;
155
+ entry.tabIndex = -1;
156
+ const row = this.ownerDocument.createElement('div'); row.className = 'row';
157
+ row.draggable = this.parameters.draggable;
158
+ row.setAttribute('part', `row ${branch ? 'branch-row' : 'leaf-row'}${selected === path ? ' selected-row' : ''}`);
159
+ if (this.#errors.has(node)) row.title = String(this.#errors.get(node));
160
+ const expander = this.ownerDocument.createElement(branch ? 'button' : 'span');
161
+ expander.setAttribute('part', branch ? 'expander' : 'spacer');
162
+ if (branch) {
163
+ expander.className = 'expander';
164
+ expander.type = 'button'; expander.tabIndex = -1;
165
+ expander.addEventListener('click', event => {
166
+ event.stopPropagation(); toggle(); entry.focus();
167
+ });
168
+ } else expander.className = 'spacer';
169
+ const caption = this.ownerDocument.createElement('span'); caption.className = 'caption';
170
+ this.#dragRows.set(row, {item: node, path, caption});
171
+ caption.setAttribute('part', 'caption');
172
+ const icon = this.ownerDocument.createElement('span');
173
+ icon.className = `icon ${branch ? 'branch-icon' : 'leaf-icon'}`;
174
+ icon.setAttribute('aria-hidden', 'true');
175
+ icon.setAttribute('part', `icon ${branch ? 'branch-icon' : 'leaf-icon'}`);
176
+
177
+ row.append(expander, icon, caption); entry.append(row);
178
+ const group = branch ? (children ? build(children, path, entry) : this.ownerDocument.createElement('ul')) : null;
179
+ if (group) { group.className = 'group'; group.setAttribute('role', 'group'); group.setAttribute('part', 'group'); }
180
+ if (group) entry.append(group);
181
+ if (scalar) {
182
+ const valueEntry = this.ownerDocument.createElement('li');
183
+ valueEntry.className = 'value-node'; valueEntry.setAttribute('part', 'value-node');
184
+ valueEntry.setAttribute('role', 'treeitem'); valueEntry.setAttribute('aria-selected', 'false');
185
+ valueEntry.tabIndex = -1; valueEntry.dataset.path = path; valueEntry.dataset.valueRow = 'true';
186
+ const valueRow = this.ownerDocument.createElement('div');
187
+ valueRow.className = 'row value-row'; valueRow.setAttribute('part', 'row value-row');
188
+ const spacer = this.ownerDocument.createElement('span'); spacer.className = 'spacer';
189
+ const text = this.ownerDocument.createElement('span');
190
+ text.className = 'value'; text.setAttribute('part', 'value'); text.textContent = String(node.staticValue);
191
+ valueRow.append(spacer, text); valueEntry.append(valueRow); group.append(valueEntry);
192
+ valueRow.addEventListener('click', () => this.#select(path));
193
+ valueEntry.addEventListener('keydown', event => {
194
+ const visible = this.#visible(), index = visible.indexOf(valueEntry);
195
+ let target;
196
+ if (event.key === 'ArrowUp') target = visible[index - 1];
197
+ else if (event.key === 'ArrowDown') target = visible[index + 1];
198
+ else if (event.key === 'Home') target = visible[0];
199
+ else if (event.key === 'End') target = visible.at(-1);
200
+ else if (event.key === 'ArrowLeft') target = entry;
201
+ else if (event.key === 'Enter' || event.key === ' ') this.#select(path);
202
+ else return;
203
+ event.preventDefault(); event.stopPropagation();
204
+ if (target) { this.#tabStop(target); target.focus(); }
205
+ });
206
+ }
207
+ const present = () => {
208
+ const opened = this.#expanded.has(node), selected = this.#selectedPath === path;
209
+ const keywords = {item: node, path, opened, selected};
210
+ const attribute = this.parameters.labelAttribute;
211
+ const label = this.parameters.getLabel !== null ? this.#call('getLabel', keywords)
212
+ : attribute !== null ? (Object.hasOwn(node.attr, attribute) ? node.attr[attribute] : node.label)
213
+ : this.parameters.labelCb !== null ? this.#call('labelCb', keywords) : node.label;
214
+ this.#setCaption(caption, label, this.parameters.getLabel !== null || (attribute === null && this.parameters.labelCb !== null));
215
+ const labelClass = this.parameters.getLabelClass !== null ? this.#call('getLabelClass', keywords)
216
+ : node.attr[opened ? 'labelClassOpened' : 'labelClassClosed'] || node.attr.labelClass || '';
217
+ const labelClasses = [...this.#classes(labelClass), ...(selected ? this.#classes(this.parameters.selectedLabelClass) : [])];
218
+ caption.className = ['caption', ...labelClasses].join(' ');
219
+ caption.setAttribute('part', ['caption', ...labelClasses].join(' '));
220
+ const nodeClasses = this.#classes(node.attr.node_class ?? '');
221
+ entry.className = ['node', branch ? 'branch' : 'leaf', ...nodeClasses,
222
+ ...(selected ? ['selected'] : []), ...(branch ? [opened ? 'opened' : 'closed'] : []),
223
+ ...(this.#loading.has(node) ? ['loading'] : []), ...(this.#errors.has(node) ? ['error'] : [])].join(' ');
224
+ entry.setAttribute('part', ['node', branch ? 'branch' : 'leaf', ...nodeClasses].join(' '));
225
+ const customIcon = this.parameters.getIconClass !== null;
226
+ const iconClasses = customIcon ? this.#classes(this.#call('getIconClass', keywords))
227
+ : [branch ? 'branch-icon' : 'leaf-icon', ...(branch ? [opened ? 'opened-icon' : 'closed-icon'] : [])];
228
+ icon.className = ['icon', ...iconClasses].join(' ');
229
+ icon.setAttribute('part', ['icon', ...iconClasses].join(' '));
230
+ icon.hidden = customIcon && iconClasses.length === 0;
231
+ if (branch) expander.setAttribute('aria-label', `${opened ? 'Collapse' : 'Expand'} ${caption.textContent}`);
232
+ };
233
+ this.#presentations.set(path, present);
234
+ const sync = () => {
235
+ const opened = this.#expanded.has(node);
236
+ entry.setAttribute('aria-expanded', String(opened));
237
+ entry.classList.toggle('opened', opened);
238
+ entry.classList.toggle('closed', !opened);
239
+ icon.classList.toggle('opened-icon', opened);
240
+ icon.setAttribute('part', `icon branch-icon ${opened ? 'opened-icon' : 'closed-icon'}`);
241
+ expander.textContent = opened ? '▾' : '▸';
242
+ group.hidden = !opened;
243
+ present();
244
+ };
245
+ const toggle = () => {
246
+ if (this.#expanded.has(node)) this.#expanded.delete(node);
247
+ else {
248
+ this.#expand(node);
249
+ if (node.resolver !== null) this.#resolve(node);
250
+ }
251
+ for (const update of branchSync.values()) update();
252
+ this.#tabStop(path);
253
+ };
254
+ if (branch) { branchSync.set(node, sync); sync(); } else present();
255
+ row.addEventListener('click', () => this.#select(path));
256
+ entry.addEventListener('keydown', event => {
257
+ if (event.target !== entry) return;
258
+ const visible = this.#visible(), index = visible.indexOf(entry);
259
+ let target;
260
+ if (event.key === 'ArrowDown') target = visible[index + 1];
261
+ else if (event.key === 'ArrowUp') target = visible[index - 1];
262
+ else if (event.key === 'Home') target = visible[0];
263
+ else if (event.key === 'End') target = visible.at(-1);
264
+ else if (event.key === 'ArrowRight' && branch) {
265
+ if (!this.#expanded.has(node)) toggle(); else target = group.firstElementChild;
266
+ } else if (event.key === 'ArrowLeft') {
267
+ if (branch && this.#expanded.has(node)) toggle(); else target = parent;
268
+ } else if (event.key === 'Enter' || event.key === ' ') this.#select(path);
269
+ else return;
270
+ event.preventDefault(); event.stopPropagation();
271
+ if (target) { this.#tabStop(target); target.focus(); }
272
+ });
273
+ this.#rows.set(path, entry);
274
+ list.append(entry);
275
+ }
276
+ return list;
277
+ };
278
+ this.control.replaceChildren(build(this.#store, '', null));
279
+ this.#tabStop(focused ?? selected);
280
+ if (focused) this.#rows.get(focused)?.focus();
281
+ }
282
+ #classes(value) {
283
+ if (typeof value !== 'string') throw new TypeError('Tree classes must be a string');
284
+ return value.split(/\s+/).filter(Boolean);
285
+ }
286
+ #call(name, keywords) {
287
+ const result = this.#context.callLogic(this.parameters[name], keywords);
288
+ if (name === 'labelCb' || name === 'getLabel') {
289
+ if (!result || typeof result !== 'object' || Object.keys(result).length !== 1 ||
290
+ !(Object.hasOwn(result, 'text') && typeof result.text === 'string' ||
291
+ Object.hasOwn(result, 'html') && typeof result.html === 'string')) {
292
+ throw new TypeError(`tree ${name} must return {text: string} or {html: string} synchronously`);
293
+ }
294
+ } else if (typeof result !== 'string') throw new TypeError(`tree ${name} must return a string synchronously`);
295
+ return result;
296
+ }
297
+ #setCaption(caption, label, computed) {
298
+ if (computed && Object.hasOwn(label, 'html')) {
299
+ caption.replaceChildren(this.#sanitizer.sanitize(label.html, {
300
+ USE_PROFILES: {html: true}, FORBID_TAGS: ['style', 'form', 'input', 'button', 'select', 'textarea'],
301
+ RETURN_DOM_FRAGMENT: true
302
+ }));
303
+ } else caption.textContent = computed ? label.text : label;
304
+ }
305
+ #visible() {
306
+ return [...this.control.querySelectorAll('[role=treeitem]')].filter(row => !row.closest('[hidden]'));
307
+ }
308
+ #expand(node) {
309
+ if (this.parameters.autoCollapse) {
310
+ for (const sibling of node.parentBag.getNodes()) {
311
+ if (sibling !== node) this.#expanded.delete(sibling);
312
+ }
313
+ }
314
+ this.#expanded.add(node);
315
+ }
316
+ async #resolve(node) {
317
+ if (this.#loading.has(node)) return;
318
+ this.#loading.add(node);
319
+ this.#errors.delete(node);
320
+ this.#schedule();
321
+ try {
322
+ await node.getValue();
323
+ } catch (error) {
324
+ this.#errors.set(node, error);
325
+ this.#expanded.delete(node);
326
+ } finally {
327
+ this.#loading.delete(node);
328
+ this.#schedule();
329
+ }
330
+ }
331
+ #tabStop(path) {
332
+ const visible = this.#visible(), target = typeof path === 'string' || path == null
333
+ ? visible.find(row => row.dataset.path === path) ?? visible[0] : path;
334
+ for (const row of this.control.querySelectorAll('[role=treeitem]')) row.tabIndex = row === target ? 0 : -1;
335
+ }
336
+ #select(path) {
337
+ this.#selectedPath = path;
338
+ for (const [key, row] of this.#rows) {
339
+ row.setAttribute('aria-selected', String(key === path));
340
+ row.classList.toggle('selected', key === path);
341
+ this.#presentations.get(key)();
342
+ row.firstElementChild.setAttribute('part', `row ${row.classList.contains('branch') ? 'branch-row' : 'leaf-row'}${key === path ? ' selected-row' : ''}`);
343
+ }
344
+ this.#tabStop(path);
345
+ this.#rows.get(path).focus();
346
+ this.#context.writeParameter('selectedPath', path);
347
+ }
348
+ }
349
+ });
350
+ export default defineCollection({name: 'tree', components: [Tree]});
@@ -0,0 +1,38 @@
1
+ import source from '../../dist/typst-worker-source.js';
2
+
3
+ let worker,workerUrl,sequence=0,owners=0,failure;
4
+ const requests=new Map();
5
+ function stop(){
6
+ worker.terminate();URL.revokeObjectURL(workerUrl);worker=null;
7
+ for(const {reject} of requests.values())reject(new Error('Typst preview closed'));
8
+ requests.clear();
9
+ }
10
+ /** Compiler lifetime follows the previews, with serialized jobs in one Worker. */
11
+ export function acquireCompiler(){
12
+ if(!worker){
13
+ failure=null;
14
+ workerUrl=URL.createObjectURL(new Blob([source],{type:'text/javascript'}));
15
+ worker=new Worker(workerUrl);
16
+ worker.onmessage=({data})=>{
17
+ const request=requests.get(data.id);if(!request)return;
18
+ requests.delete(data.id);
19
+ if(data.error)request.reject(new Error(data.error));else request.resolve(data);
20
+ };
21
+ worker.onerror=event=>{
22
+ failure=new Error(event.message);
23
+ for(const {reject} of requests.values())reject(failure);
24
+ requests.clear();
25
+ };
26
+ }
27
+ owners++;
28
+ let released=false;
29
+ return {
30
+ compile(value){
31
+ if(released)throw new Error('Typst compiler session is closed');
32
+ if(failure)return Promise.reject(failure);
33
+ const id=++sequence;
34
+ return new Promise((resolve,reject)=>{requests.set(id,{resolve,reject});worker.postMessage({id,value});});
35
+ },
36
+ release(){if(released)return;released=true;if(--owners===0)stop();}
37
+ };
38
+ }
@@ -0,0 +1,88 @@
1
+ import {defineComponent} from './registry.js';
2
+ import {projectParameters} from './parameters.js';
3
+
4
+ function PreviewElement(HTMLElement){
5
+ return class extends HTMLElement {
6
+ #revision=0;
7
+ #timer;
8
+ #compiler;
9
+ #loading;
10
+ #busy=false;
11
+ #urls=[];
12
+ constructor(){
13
+ super();
14
+ const root=this.attachShadow({mode:'open'}),doc=this.ownerDocument;
15
+ const style=doc.createElement('style');
16
+ style.textContent=`:host{display:block;height:100%;min-height:0;color:var(--gramlot-ink,CanvasText)}
17
+ .preview{display:flex;flex-direction:column;height:100%;background:var(--gramlot-surface-subtle,Canvas)}
18
+ .tools{display:flex;gap:16px;align-items:center;padding:8px 12px;font:inherit}
19
+ a{color:var(--gramlot-brand-blue,LinkText);border-radius:var(--gramlot-radius-sm,4px);padding:4px 8px;text-decoration:none;white-space:nowrap}
20
+ a:hover{background:var(--gramlot-selected-background,Highlight)}
21
+ a:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight)}
22
+ a[aria-disabled=true]{opacity:.45;pointer-events:none}
23
+ .status{white-space:pre-wrap;font-size:.9em;overflow:auto;max-height:8em}
24
+ .pages{flex:1;min-height:0;overflow:auto;padding:16px}
25
+ img{display:block;width:100%;height:auto;background:white;box-shadow:0 2px 10px #0002}
26
+ img[hidden]{display:none}`;
27
+ const pane=doc.createElement('div');pane.className='preview';
28
+ const tools=doc.createElement('div');tools.className='tools';
29
+ this.download=doc.createElement('a');this.download.textContent='Download PDF';
30
+ this.status=doc.createElement('span');this.status.className='status';this.status.setAttribute('role','status');
31
+ const pages=doc.createElement('div');pages.className='pages';
32
+ this.image=doc.createElement('img');this.image.alt='Typst document preview';this.image.hidden=true;
33
+ pages.append(this.image);tools.append(this.download,this.status);pane.append(tools,pages);root.append(style,pane);
34
+ this.#invalidate();
35
+ }
36
+ #invalidate(){
37
+ this.download.removeAttribute('href');this.download.setAttribute('aria-disabled','true');this.download.tabIndex=-1;
38
+ this.image.hidden=true;this.image.removeAttribute('src');
39
+ for(const url of this.#urls)this.ownerDocument.defaultView.URL.revokeObjectURL(url);
40
+ this.#urls=[];
41
+ }
42
+ connectedCallback(){this.#schedule();}
43
+ disconnectedCallback(){
44
+ ++this.#revision;clearTimeout(this.#timer);this.#compiler?.release();this.#compiler=null;
45
+ this.#invalidate();
46
+ }
47
+ projectAttributes(attrs){
48
+ const previous=this.parameters?.value,rest=projectParameters(this,attrs);
49
+ this.download.download=this.parameters.filename;
50
+ if(previous!==this.parameters.value){++this.#revision;this.#invalidate();this.#schedule();}
51
+ return rest;
52
+ }
53
+ #schedule(){
54
+ clearTimeout(this.#timer);
55
+ if(!this.isConnected || !this.parameters)return;
56
+ this.status.textContent='Preparing preview…';
57
+ this.#timer=setTimeout(()=>{this.ready=this.#render();},350);
58
+ }
59
+ async #render(){
60
+ if(this.#busy)return;
61
+ const revision=this.#revision;
62
+ this.#busy=true;
63
+ try{
64
+ this.#loading??=import('./typst-client.js');
65
+ const module=await this.#loading;
66
+ if(!this.isConnected || revision!==this.#revision)return;
67
+ this.#compiler??=module.acquireCompiler();
68
+ this.status.textContent='Compiling…';
69
+ const result=await this.#compiler.compile(this.parameters.value);
70
+ if(!this.isConnected || revision!==this.#revision)return;
71
+ const {URL,Blob}=this.ownerDocument.defaultView;
72
+ const svg=URL.createObjectURL(new Blob([result.svg],{type:'image/svg+xml'}));
73
+ const pdf=URL.createObjectURL(new Blob([result.pdf],{type:'application/pdf'}));
74
+ this.#urls=[svg,pdf];this.image.src=svg;this.image.hidden=false;
75
+ this.download.href=pdf;this.download.setAttribute('aria-disabled','false');this.download.tabIndex=0;
76
+ this.status.textContent=result.diagnostics.length ? result.diagnostics.join('\n') : 'Preview and PDF are up to date';
77
+ }catch(error){
78
+ if(this.isConnected && revision===this.#revision)this.status.textContent=error.message;
79
+ }finally{
80
+ this.#busy=false;
81
+ if(this.isConnected && revision!==this.#revision)this.#schedule();
82
+ }
83
+ }
84
+ };
85
+ }
86
+ export const TypstPreview=defineComponent({name:'typstPreview',tag:'gramlot-typst-preview',base:PreviewElement,
87
+ parameters:{value:{dtype:'T',default:'',binding:'read'},filename:{dtype:'T',default:'document.pdf',binding:'read'}},
88
+ implementation:Base=>class extends Base {}});
@@ -0,0 +1,49 @@
1
+ /** One serial compiler owns a virtual filesystem; no network/file provider. */
2
+ import {createTypstCompiler,createTypstRenderer,loadFonts,MemoryAccessModel,initOptions} from '@myriaddreamin/typst.ts';
3
+ import {TypstSnippet} from '@myriaddreamin/typst.ts/contrib/snippet';
4
+ import compilerWasm from '@myriaddreamin/typst-ts-web-compiler/wasm';
5
+ import rendererWasm from '@myriaddreamin/typst-ts-renderer/wasm';
6
+ import serif from '../../../assets/typst-fonts/LibertinusSerif-Regular.otf';
7
+ import bold from '../../../assets/typst-fonts/LibertinusSerif-Bold.otf';
8
+ import italic from '../../../assets/typst-fonts/LibertinusSerif-Italic.otf';
9
+ import mono from '../../../assets/typst-fonts/DejaVuSansMono.ttf';
10
+ import math from '../../../assets/typst-fonts/NewCMMath-Regular.otf';
11
+
12
+ const typst=new TypstSnippet({
13
+ compiler:async()=>{
14
+ const compiler=createTypstCompiler();
15
+ await compiler.init({getModule:()=>compilerWasm,beforeBuild:[initOptions.withAccessModel(new MemoryAccessModel()),
16
+ initOptions.withPackageRegistry({resolve(){throw new Error('External Typst packages are not included in this offline document');}}),loadFonts([serif,bold,italic,mono,math],{assets:false})]});
17
+ return compiler;
18
+ },
19
+ renderer:async()=>{
20
+ const renderer=createTypstRenderer();
21
+ await renderer.init({getModule:()=>rendererWasm});
22
+ return renderer;
23
+ }
24
+ });
25
+ const pending=new Map();
26
+ let running=false;
27
+ async function drain(){
28
+ if(running)return;
29
+ running=true;
30
+ while(pending.size){
31
+ const [id,value]=pending.entries().next().value;
32
+ pending.delete(id);
33
+ try{
34
+ const compiler=await typst.getCompiler();
35
+ compiler.resetShadow();
36
+ await compiler.reset();
37
+ compiler.addSource('/main.typ',value);
38
+ const options={mainFilePath:'/main.typ',root:'/',inputs:{},diagnostics:'unix'};
39
+ const vector=await compiler.compile(options);
40
+ if(!vector.result)throw new Error(vector.diagnostics?.join('\n') || 'Typst compilation failed');
41
+ const svg=await typst.svg({vectorData:vector.result,data_selection:{body:true,defs:true,css:true,js:false}});
42
+ const pdf=await compiler.compile({...options,format:1});
43
+ if(!pdf.result)throw new Error(pdf.diagnostics?.join('\n') || 'PDF compilation failed');
44
+ self.postMessage({id,svg,pdf:pdf.result,diagnostics:vector.diagnostics || []});
45
+ }catch(error){self.postMessage({id,error:error.message});}
46
+ }
47
+ running=false;
48
+ }
49
+ self.onmessage=({data:{id,value}})=>{pending.set(id,value);void drain();};
@@ -0,0 +1,4 @@
1
+ import {defineCollection} from './registry.js';
2
+ import {TypstPreview} from './typst-preview.js';
3
+ export {TypstPreview} from './typst-preview.js';
4
+ export default defineCollection({name:'typst',components:[TypstPreview]});
@@ -0,0 +1,22 @@
1
+ import type {Bag} from '@genrojs/bag';
2
+ import type {SourceBag, SourceBagNode} from '@genrojs/builders';
3
+ import type {Gramlot} from './gramlot.js';
4
+ export function fileSystemTree(parent: SourceBag | SourceBagNode, options: {datapath: string; [key:string]:unknown}): SourceBagNode;
5
+ export class DirectoryResolver {
6
+ constructor(options: {gramlot:Gramlot; root:string; path?:string; onError:(error:Error)=>void});
7
+ prepareValue(bag:Bag):Bag;
8
+ readonly closed:boolean;
9
+ loading:Promise<Bag>|null;
10
+ resolve():Bag|null;
11
+ refresh():Promise<Bag>|null;
12
+ abort():void;
13
+ }
14
+ export class FileSystemController {
15
+ constructor(gramlot:Gramlot, state:Bag);
16
+ open(root:string):Promise<string|null>;
17
+ dispose():void;
18
+ }
19
+ export class FileSystemLogic {
20
+ fileSystemMount(node:SourceBagNode):void;
21
+ fileSystemOpen(node:SourceBagNode, args:{root:string|null}):Promise<string|null>|undefined;
22
+ }