@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.
- package/dist/components/editors.js +116578 -0
- package/dist/components/inputs.js +24509 -0
- package/dist/components/layout.js +3385 -0
- package/dist/components/tree.js +24538 -0
- package/dist/components/typst.js +4 -0
- package/dist/gramlot.js +791 -37
- package/dist/gramlot.min.js +27 -24
- package/dist/runtime-notices.json +208 -0
- package/dist/typst-worker-source.js +4 -0
- package/package.json +34 -3
- package/src/binding/hooks.js +14 -0
- package/src/binding/providers.js +4 -0
- package/src/binding/remote.js +11 -2
- package/src/binding/runtime.js +10 -7
- package/src/builder/source.js +8 -3
- package/src/components/bases.js +1 -0
- package/src/components/border-container.js +7 -1
- package/src/components/buttons.js +3 -0
- package/src/components/choice-editor.js +17 -3
- package/src/components/choices.js +3 -2
- package/src/components/code-mirror-engine.js +91 -0
- package/src/components/code-mirror.js +88 -0
- package/src/components/editor-options.d.ts +9 -0
- package/src/components/editor-options.js +21 -0
- package/src/components/editors.js +10 -0
- package/src/components/html-document.js +56 -0
- package/src/components/html-editor.js +68 -0
- package/src/components/html-preview.js +33 -0
- package/src/components/inputs.js +2 -2
- package/src/components/jodit-engine.js +89 -0
- package/src/components/markdown-codec.js +35 -0
- package/src/components/markdown-document.js +14 -0
- package/src/components/markdown-editor.js +68 -0
- package/src/components/prose-mirror-engine.js +65 -0
- package/src/components/typst-client.js +38 -0
- package/src/components/typst-preview.js +88 -0
- package/src/components/typst-worker.js +49 -0
- package/src/components/typst.js +4 -0
- package/src/components/validation.js +1 -1
- package/src/filesystem.d.ts +22 -0
- package/src/filesystem.js +122 -0
- package/src/ide-documents.js +153 -0
- package/src/ide-runtime.d.ts +18 -0
- package/src/ide-runtime.js +238 -0
- package/src/index.d.ts +4 -1
- package/src/index.js +4 -1
- package/src/renderer/attributes.js +11 -2
- package/src/renderer/gramlot-renderer.js +3 -2
- package/src/server/assets.js +2 -2
- package/src/server/page.d.ts +5 -0
- package/src/server/page.js +4 -0
- package/src/view/button.js +2 -1
- package/src/view/controls.js +7 -11
- package/src/view/events.js +4 -8
- package/src/view/html.js +7 -0
package/src/components/inputs.js
CHANGED
|
@@ -185,7 +185,7 @@ export const TimeTextBox = defineComponent({
|
|
|
185
185
|
});
|
|
186
186
|
export const FilteringSelect = defineComponent({
|
|
187
187
|
name: 'filteringSelect', tag: 'gramlot-filtering-select', base: ChoiceEditor, mixins: [Labelbox, FieldState],
|
|
188
|
-
parameters: {values: {dtype: 'T', default: '', binding: 'read'}}, implementation: localChoices
|
|
188
|
+
parameters: {values: {dtype: 'T', default: '', binding: 'read'}, separator: {dtype: 'T', default: ',', binding: 'read'}}, implementation: localChoices
|
|
189
189
|
});
|
|
190
190
|
export const CallbackSelect = defineComponent({
|
|
191
191
|
name: 'callbackSelect', tag: 'gramlot-callback-select', base: ChoiceEditor, mixins: [Labelbox, FieldState],
|
|
@@ -193,7 +193,7 @@ export const CallbackSelect = defineComponent({
|
|
|
193
193
|
});
|
|
194
194
|
export const ComboBox = defineComponent({
|
|
195
195
|
name: 'comboBox', tag: 'gramlot-combo-box', base: ChoiceEditor, mixins: [Labelbox, FieldState],
|
|
196
|
-
parameters: {values: {dtype: 'T', default: '', binding: 'read'}},
|
|
196
|
+
parameters: {values: {dtype: 'T', default: '', binding: 'read'}, separator: {dtype: 'T', default: ',', binding: 'read'}, store: {dtype: 'X', nullable: true, default: null, binding: 'read'}},
|
|
197
197
|
implementation: Base => class extends localChoices(Base) {
|
|
198
198
|
get constrained() { return false; }
|
|
199
199
|
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/** Locally bundled optional Jodit engine, initialized only by htmlEditor. */
|
|
2
|
+
import {Jodit} from 'jodit';
|
|
3
|
+
import 'jodit/esm/plugins/clean-html/clean-html.js';
|
|
4
|
+
import 'jodit/esm/plugins/clipboard/clipboard.js';
|
|
5
|
+
import 'jodit/esm/plugins/fullsize/fullsize.js';
|
|
6
|
+
import 'jodit/esm/plugins/hr/hr.js';
|
|
7
|
+
import 'jodit/esm/plugins/indent/indent.js';
|
|
8
|
+
import 'jodit/esm/plugins/search/search.js';
|
|
9
|
+
import 'jodit/esm/plugins/select/select.js';
|
|
10
|
+
import 'jodit/esm/plugins/select-cells/select-cells.js';
|
|
11
|
+
import 'jodit/esm/plugins/resize-cells/resize-cells.js';
|
|
12
|
+
import 'jodit/esm/plugins/table-keyboard-navigation/table-keyboard-navigation.js';
|
|
13
|
+
import css from 'jodit/es2021/jodit.min.css';
|
|
14
|
+
import {prepareHtmlDocument} from './html-document.js';
|
|
15
|
+
|
|
16
|
+
const theme=`.jodit-container,.jodit-popup,.jodit-dialog{--jd-color-background-default:var(--gramlot-surface,white);--jd-color-panel:var(--gramlot-surface-subtle,#eee);--jd-color-text-icons:var(--gramlot-ink,#222);--jd-color-separator:var(--gramlot-border-control,#aaa);--jd-color-button-background-hover:var(--gramlot-selected,#ddd);--jd-color-background-active:var(--gramlot-selected,#ddd);--jd-color-background-gray:var(--gramlot-surface-subtle,#eee);--jd-color-background-light-gray:var(--gramlot-surface-subtle,#eee);--jd-color-background-button-hover:var(--gramlot-selected,#ddd);--jd-color-border:var(--gramlot-border-control,#aaa);--jd-color-text:var(--gramlot-ink,#222);--jd-color-icon:var(--gramlot-ink,#222);--jd-border-radius-default:var(--gramlot-radius-sm,4px)}.jodit-toolbar-button__button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight)}`;
|
|
17
|
+
const styles=new WeakSet();
|
|
18
|
+
export function createHtmlEditor(host) {
|
|
19
|
+
const document=host.ownerDocument, window=document.defaultView;
|
|
20
|
+
if (!styles.has(host.shadowRoot)) {
|
|
21
|
+
const style=document.createElement('style');style.textContent=css+'\n'+theme;host.shadowRoot.append(style);styles.add(host.shadowRoot);
|
|
22
|
+
}
|
|
23
|
+
if (!styles.has(document)) {
|
|
24
|
+
const style=document.createElement('style');style.textContent=css+'\n'+theme;document.head.append(style);styles.add(document);
|
|
25
|
+
}
|
|
26
|
+
const status=document.createElement('div');status.className='html-editor-status';status.setAttribute('role','status');
|
|
27
|
+
const textarea=document.createElement('textarea');textarea.setAttribute('aria-label','HTML content');
|
|
28
|
+
host.control.append(status,textarea);
|
|
29
|
+
const originalValue=host.readControlValue();
|
|
30
|
+
const content=prepareHtmlDocument(originalValue,window);
|
|
31
|
+
const locked=()=>Boolean(host.parameters.readonly||host.parameters.disabled);
|
|
32
|
+
const editor=Jodit.make(textarea,{
|
|
33
|
+
globalFullSize:false,height:'100%',minHeight:200,readonly:locked(),
|
|
34
|
+
iframe:true,iframeSandbox:'allow-same-origin',iframeStyle:'body{font-family:system-ui;padding:16px;background:white;color:#222}',
|
|
35
|
+
toolbarAdaptive:false,toolbarSticky:false,showXPathInStatusbar:false,showCharsCounter:false,showWordsCounter:false,
|
|
36
|
+
sourceEditor:'area',disablePlugins:['mobile'],
|
|
37
|
+
buttons:['undo','redo','|','paragraph','bold','italic','underline','strikethrough','brush','eraser','|','ul','ol','outdent','indent','align','|','link','image','table','hr','|','find','selectall'],
|
|
38
|
+
uploader:{insertImageAsBase64URI:true}
|
|
39
|
+
});
|
|
40
|
+
const frameDoc=editor.editor.ownerDocument;
|
|
41
|
+
const policy=frameDoc.createElement('meta');policy.httpEquiv='Content-Security-Policy';
|
|
42
|
+
policy.content="default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src data:; form-action 'none'";
|
|
43
|
+
frameDoc.head.prepend(policy);
|
|
44
|
+
const pageStyle=frameDoc.createElement('style');pageStyle.textContent=content.styles;frameDoc.head.append(pageStyle);
|
|
45
|
+
const events=new window.AbortController(),options={capture:true,signal:events.signal};
|
|
46
|
+
frameDoc.addEventListener('submit',event=>event.preventDefault(),options);
|
|
47
|
+
frameDoc.addEventListener('click',event=>{if(event.target.closest('a'))event.preventDefault();},options);
|
|
48
|
+
frameDoc.addEventListener('keydown',event=>{
|
|
49
|
+
if ((event.ctrlKey||event.metaKey)&&event.key.toLowerCase()==='s') {event.preventDefault();host.pageContext.publish('save',{value:host.readControlValue()});}
|
|
50
|
+
},options);
|
|
51
|
+
editor.value=content.html;
|
|
52
|
+
editor.history.clear();
|
|
53
|
+
const initialHtml=editor.value;
|
|
54
|
+
let previous=initialHtml,restoring=false,disposed=false,scheduled=false,lastHistory;
|
|
55
|
+
const history=()=>{
|
|
56
|
+
if(scheduled)return;scheduled=true;
|
|
57
|
+
queueMicrotask(()=>{
|
|
58
|
+
scheduled=false;if(disposed)return;
|
|
59
|
+
const current={canUndo:!locked()&&editor.history.canUndo(),canRedo:!locked()&&editor.history.canRedo()};
|
|
60
|
+
if(lastHistory&¤t.canUndo===lastHistory.canUndo&¤t.canRedo===lastHistory.canRedo)return;
|
|
61
|
+
lastHistory=current;host.pageContext.publish('historyChanged',current);
|
|
62
|
+
});
|
|
63
|
+
};
|
|
64
|
+
editor.events.on('change',()=>{
|
|
65
|
+
if(restoring||locked()||disposed)return;
|
|
66
|
+
const html=editor.value;if(html===previous)return;
|
|
67
|
+
try {
|
|
68
|
+
const value=html===initialHtml ? originalValue : content.serialize(html);previous=html;status.textContent='';host.editorChanged(value);
|
|
69
|
+
} catch(error) {
|
|
70
|
+
restoring=true;try{editor.value=previous;}finally{restoring=false;}
|
|
71
|
+
status.textContent=error.message;
|
|
72
|
+
}
|
|
73
|
+
history();
|
|
74
|
+
});
|
|
75
|
+
editor.events.on('blur',()=>host.editorBlurred());
|
|
76
|
+
editor.events.on('changeStack',history);
|
|
77
|
+
const resize=new window.ResizeObserver(entries=>{
|
|
78
|
+
if(!disposed && entries.some(entry=>entry.contentRect.width>0 && entry.contentRect.height>0)) editor.events.fire('resize');
|
|
79
|
+
});
|
|
80
|
+
resize.observe(host.control);
|
|
81
|
+
history();
|
|
82
|
+
return {
|
|
83
|
+
configure(){editor.setReadOnly(locked());history();},
|
|
84
|
+
undo(){if(locked()||!editor.history.canUndo())return false;editor.history.undo();return true;},
|
|
85
|
+
redo(){if(locked()||!editor.history.canRedo())return false;editor.history.redo();return true;},
|
|
86
|
+
focus(){editor.selection.focus();},
|
|
87
|
+
destroy(){disposed=true;resize.disconnect();events.abort();editor.destruct();}
|
|
88
|
+
};
|
|
89
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import {Schema} from 'prosemirror-model';
|
|
2
|
+
import {schema as baseSchema,MarkdownParser,MarkdownSerializer,defaultMarkdownParser,defaultMarkdownSerializer} from 'prosemirror-markdown';
|
|
3
|
+
import {markdownRenderer as md} from './markdown-document.js';
|
|
4
|
+
|
|
5
|
+
/** Opaque source blocks keep syntax outside the rich editor's supported schema. */
|
|
6
|
+
export function createMarkdownCodec(document) {
|
|
7
|
+
const image = {...baseSchema.spec.nodes.get('image'), parseDOM:[{tag:'img[src]', getAttrs:dom=>
|
|
8
|
+
md.validateLink(dom.getAttribute('src')) ? {src:dom.getAttribute('src'),alt:dom.getAttribute('alt'),title:dom.getAttribute('title')} : false}]};
|
|
9
|
+
const link = {...baseSchema.spec.marks.get('link'), parseDOM:[{tag:'a[href]', getAttrs:dom=>
|
|
10
|
+
md.validateLink(dom.getAttribute('href')) ? {href:dom.getAttribute('href'),title:dom.getAttribute('title')} : false}]};
|
|
11
|
+
const schema = new Schema({nodes:baseSchema.spec.nodes.update('image',image).append({source_block:{group:'block',atom:true,
|
|
12
|
+
attrs:{source:{}},toDOM:node=>{
|
|
13
|
+
const element=document.createElement('div');element.className='markdown-source-block';
|
|
14
|
+
element.contentEditable='false';element.title='Preserved Markdown block — edit in Code';
|
|
15
|
+
element.innerHTML=md.render(node.attrs.source);return element;
|
|
16
|
+
}}}),marks:baseSchema.spec.marks.update('link',link)});
|
|
17
|
+
const parser = new MarkdownParser(schema,defaultMarkdownParser.tokenizer,defaultMarkdownParser.tokens);
|
|
18
|
+
const serializer = new MarkdownSerializer({...defaultMarkdownSerializer.nodes,
|
|
19
|
+
source_block:(state,node)=>{state.write(node.attrs.source);state.closeBlock(node);}},defaultMarkdownSerializer.marks);
|
|
20
|
+
function parse(value) {
|
|
21
|
+
if (typeof value !== 'string') throw new TypeError('Markdown editor value must be a string');
|
|
22
|
+
const opaque=source=>schema.nodes.source_block.create({source});
|
|
23
|
+
if (/^ {0,3}\[[^\]]+\]:/m.test(value) || /^---\r?\n/.test(value)) return schema.node('doc',null,[opaque(value)]);
|
|
24
|
+
const lines=value.split('\n'),tokens=md.parse(value,{}),nodes=[];
|
|
25
|
+
for (const token of tokens) {
|
|
26
|
+
if (token.level!==0 || !token.map || token.nesting===-1) continue;
|
|
27
|
+
const source=lines.slice(token.map[0],token.map[1]).join('\n');
|
|
28
|
+
const complex=!['fence','code_block'].includes(token.type) && (md.parse(source,{}).some(item=>item.type==='table_open') || /<\/?[A-Za-z][^>]*>|<!--|~~/.test(source) || /^\s*[-+*]\s+\[[ xX]\]/m.test(source));
|
|
29
|
+
if (complex) nodes.push(opaque(source));
|
|
30
|
+
else parser.parse(source).content.forEach(node=>nodes.push(node));
|
|
31
|
+
}
|
|
32
|
+
return schema.node('doc',null,nodes.length ? nodes : [schema.node('paragraph')]);
|
|
33
|
+
}
|
|
34
|
+
return {schema,parse,serialize:doc=>serializer.serialize(doc)};
|
|
35
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import MarkdownIt from 'markdown-it';
|
|
2
|
+
import createDOMPurify from 'dompurify';
|
|
3
|
+
|
|
4
|
+
// Keep the rich-editor codec and ordinary previews in HTML-as-text mode.
|
|
5
|
+
export const markdownRenderer = new MarkdownIt({html:false});
|
|
6
|
+
const htmlRenderer = new MarkdownIt({html:true});
|
|
7
|
+
export const markdownDocumentStyle = `body{font:16px/1.6 system-ui;color:#243449;background:white;padding:24px;margin:0;overflow-wrap:anywhere}table{border-collapse:collapse}td,th{border:1px solid #ccd3dd;padding:6px 12px}pre{overflow:auto;background:#edf1f7;padding:12px;border-radius:4px}code{font-size:.9em}img{max-width:100%}blockquote{border-left:3px solid #ccd3dd;margin-left:0;padding-left:16px}a{color:#3566aa}`;
|
|
8
|
+
export function renderMarkdownDocument(value, {allowHtml=false, document} = {}) {
|
|
9
|
+
if (typeof value !== 'string') throw new TypeError('Markdown preview value must be a string');
|
|
10
|
+
const rendered = allowHtml ? createDOMPurify(document.defaultView).sanitize(htmlRenderer.render(value), {
|
|
11
|
+
USE_PROFILES:{html:true}, FORBID_TAGS:['style','form','input','button','select','textarea'],
|
|
12
|
+
}) : markdownRenderer.render(value);
|
|
13
|
+
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; form-action 'none'"><style>${markdownDocumentStyle}</style></head><body>${rendered}</body></html>`;
|
|
14
|
+
}
|
|
@@ -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 MarkdownControl(MarkdownElement) {
|
|
8
|
+
return class extends controlElement(MarkdownElement) {
|
|
9
|
+
#value='';
|
|
10
|
+
#generation=0;
|
|
11
|
+
constructor() {
|
|
12
|
+
super();
|
|
13
|
+
this.control=this.ownerDocument.createElement('div');
|
|
14
|
+
this.control.className='markdown-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,.markdown-editor-control{height:100%;min-height:0}.labelbox{grid-template-rows:auto minmax(0,1fr)}.markdown-editor-control{overflow:hidden}.markdown-editor-status{font:inherit;color:var(--gramlot-text-secondary,GrayText)}.markdown-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 Markdown editor…';
|
|
29
|
+
this.ready=(engineModule ??= import('./prose-mirror-engine.js')).then(module=>{
|
|
30
|
+
if (generation!==this.#generation || !this.isConnected) return;
|
|
31
|
+
this.control.textContent='';
|
|
32
|
+
this.engine=module.createMarkdownEditor(this);
|
|
33
|
+
}).catch(error=>{
|
|
34
|
+
if (generation!==this.#generation) return;
|
|
35
|
+
this.control.textContent=`Markdown 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('Markdown 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
|
+
MarkdownControl.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 MarkdownEditor=defineComponent({name:'markdownEditor',tag:'gramlot-markdown-editor',base:MarkdownControl,mixins:[Labelbox,FieldState],
|
|
68
|
+
parameters:{value:{dtype:'T',default:'',binding:'twoWay'}},implementation:Base=>class extends Base {}});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import {EditorState} from 'prosemirror-state';
|
|
2
|
+
import {EditorView} from 'prosemirror-view';
|
|
3
|
+
import {toggleMark,baseKeymap} from 'prosemirror-commands';
|
|
4
|
+
import {keymap} from 'prosemirror-keymap';
|
|
5
|
+
import {history,undo,redo} from 'prosemirror-history';
|
|
6
|
+
import {createMarkdownCodec} from './markdown-codec.js';
|
|
7
|
+
|
|
8
|
+
const styleText=`.markdown-editor-control{display:flex;flex-direction:column;border:1px solid var(--gramlot-border-control,#aaa);border-radius:var(--gramlot-radius-sm,4px);background:var(--gramlot-surface,white);color:var(--gramlot-ink,#243449)}
|
|
9
|
+
.markdown-tools{display:flex;gap:4px;align-items:center;flex-wrap:wrap;padding:5px 8px;border-bottom:1px solid var(--gramlot-border-control,#aaa);background:var(--gramlot-surface-subtle,#edf1f7)}
|
|
10
|
+
.markdown-tools button{border:0;background:transparent;color:inherit;border-radius:var(--gramlot-radius-sm,4px);padding:6px 10px;font:inherit;cursor:pointer}.markdown-tools button:hover:not(:disabled),.markdown-tools button[aria-pressed=true]{background:var(--gramlot-selected,#eaf0fc)}.markdown-tools button:disabled{opacity:.4;cursor:default}
|
|
11
|
+
.markdown-content{flex:1;min-height:0;overflow:auto}.ProseMirror{padding:20px;min-height:100%;outline:0;white-space:pre-wrap;overflow-wrap:break-word;line-height:1.6}.ProseMirror:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:-2px}.ProseMirror pre{white-space:pre-wrap;background:var(--gramlot-surface-subtle,#edf1f7);padding:12px}.ProseMirror li{position:relative}.ProseMirror img{max-width:100%}.ProseMirror a{color:var(--gramlot-action,LinkText)}.ProseMirror blockquote{border-left:3px solid var(--gramlot-border-control,#aaa);padding-left:16px;margin-left:0}.ProseMirror table{border-collapse:collapse}.ProseMirror td,.ProseMirror th{border:1px solid var(--gramlot-border-control,#aaa);padding:6px 12px}.markdown-source-block{border:1px dashed var(--gramlot-border-control,#aaa);padding:10px;margin:12px 0;background:var(--gramlot-surface-subtle,#edf1f7);white-space:normal}.ProseMirror-selectednode{outline:2px solid var(--gramlot-focus-ring,Highlight)}.ProseMirror-hideselection *::selection{background:transparent}.ProseMirror-hideselection{caret-color:transparent}`;
|
|
12
|
+
const styled=new WeakSet();
|
|
13
|
+
export function createMarkdownEditor(host) {
|
|
14
|
+
const document=host.ownerDocument;
|
|
15
|
+
if (!styled.has(host.shadowRoot)) {const style=document.createElement('style');style.textContent=styleText;host.shadowRoot.append(style);styled.add(host.shadowRoot);}
|
|
16
|
+
const toolbar=document.createElement('div');toolbar.className='markdown-tools';toolbar.setAttribute('role','toolbar');toolbar.setAttribute('aria-label','Markdown formatting');
|
|
17
|
+
const content=document.createElement('div');content.className='markdown-content';host.control.append(toolbar,content);
|
|
18
|
+
const original=host.readControlValue(),codec=createMarkdownCodec(document),initialDoc=codec.parse(original);
|
|
19
|
+
const locked=()=>Boolean(host.parameters.readonly||host.parameters.disabled);
|
|
20
|
+
let disposed=false,scheduled=false,lastHistory;
|
|
21
|
+
const buttons=[];
|
|
22
|
+
function refresh() {
|
|
23
|
+
for (const {button,command,mark} of buttons) {
|
|
24
|
+
button.disabled=locked()||!command(view.state);
|
|
25
|
+
if(mark){const {from,to,empty,$from}=view.state.selection;button.setAttribute('aria-pressed',String(empty ? Boolean(mark.isInSet(view.state.storedMarks||$from.marks())) : view.state.doc.rangeHasMark(from,to,mark)));}
|
|
26
|
+
}
|
|
27
|
+
if(scheduled)return;scheduled=true;
|
|
28
|
+
queueMicrotask(()=>{
|
|
29
|
+
scheduled=false;if(disposed)return;
|
|
30
|
+
const current={canUndo:!locked()&&undo(view.state),canRedo:!locked()&&redo(view.state)};
|
|
31
|
+
if(lastHistory&¤t.canUndo===lastHistory.canUndo&¤t.canRedo===lastHistory.canRedo)return;
|
|
32
|
+
lastHistory=current;host.pageContext.publish('historyChanged',current);
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
const save=()=>{if(!locked())host.pageContext.publish('save',{value:host.readControlValue()});return true;};
|
|
36
|
+
const view=new EditorView(content,{
|
|
37
|
+
state:EditorState.create({doc:initialDoc,plugins:[history(),keymap({'Mod-z':undo,'Mod-Shift-z':redo,'Mod-y':redo,'Mod-b':toggleMark(codec.schema.marks.strong),'Mod-i':toggleMark(codec.schema.marks.em),'Mod-`':toggleMark(codec.schema.marks.code),'Mod-s':save}),keymap(baseKeymap)]}),
|
|
38
|
+
editable:()=>!locked(),attributes:()=>({'aria-label':'Markdown editor',role:'textbox','aria-multiline':'true','aria-readonly':String(locked()),tabindex:host.parameters.disabled ? '-1':'0'}),
|
|
39
|
+
handleDOMEvents:{blur:()=>{if(!disposed)host.editorBlurred();return false;},click:(_,event)=>{if(event.target.closest('a')){event.preventDefault();return true;}return false;}},
|
|
40
|
+
dispatchTransaction:transaction=>{
|
|
41
|
+
if(disposed || (transaction.docChanged&&locked()))return;
|
|
42
|
+
view.updateState(view.state.apply(transaction));
|
|
43
|
+
if(transaction.docChanged)host.editorChanged(view.state.doc.eq(initialDoc) ? original : codec.serialize(view.state.doc));
|
|
44
|
+
refresh();
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
for (const [label,command,mark] of [
|
|
48
|
+
['Bold',toggleMark(codec.schema.marks.strong),codec.schema.marks.strong],
|
|
49
|
+
['Italic',toggleMark(codec.schema.marks.em),codec.schema.marks.em],
|
|
50
|
+
['Code',toggleMark(codec.schema.marks.code),codec.schema.marks.code],['Undo',undo],['Redo',redo]]) {
|
|
51
|
+
const button=document.createElement('button');button.type='button';button.textContent=label;button.title=label;
|
|
52
|
+
button.addEventListener('mousedown',event=>event.preventDefault());
|
|
53
|
+
button.addEventListener('click',()=>{if(!locked()){command(view.state,view.dispatch,view);view.focus();}});
|
|
54
|
+
toolbar.append(button);buttons.push({button,command,mark});
|
|
55
|
+
}
|
|
56
|
+
refresh();
|
|
57
|
+
return {
|
|
58
|
+
view,
|
|
59
|
+
configure(){view.setProps({editable:()=>!locked()});refresh();},
|
|
60
|
+
undo(){return !locked()&&undo(view.state,view.dispatch,view);},
|
|
61
|
+
redo(){return !locked()&&redo(view.state,view.dispatch,view);},
|
|
62
|
+
focus(){view.focus();},
|
|
63
|
+
destroy(){disposed=true;view.destroy();}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -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,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
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import {Bag} from '@genrojs/bag';
|
|
2
|
+
import {RemoteResolver} from './binding/remote-resolver.js';
|
|
3
|
+
|
|
4
|
+
/** One directory per request; the host owns filesystem access. */
|
|
5
|
+
export class DirectoryResolver extends RemoteResolver {
|
|
6
|
+
static internalParams = new Set([...RemoteResolver.internalParams, 'gramlot', 'method', 'params', 'onError']);
|
|
7
|
+
#closed = false;
|
|
8
|
+
#controller = null;
|
|
9
|
+
constructor({gramlot, root, path = '', onError}) {
|
|
10
|
+
super({cacheTime: -1, onError});
|
|
11
|
+
this.gramlot = gramlot;
|
|
12
|
+
this.method = 'directory_tree';
|
|
13
|
+
this.params = {root, path};
|
|
14
|
+
this.children = new Set();
|
|
15
|
+
}
|
|
16
|
+
get closed() { return this.#closed; }
|
|
17
|
+
startLoad(perform) {
|
|
18
|
+
if (this.loading) return this.loading;
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
this.#controller = controller;
|
|
21
|
+
return perform({controller, method: this.method, params: this.params, ignored: false});
|
|
22
|
+
}
|
|
23
|
+
async loadAsync({controller, method, params}) {
|
|
24
|
+
const {signal} = controller;
|
|
25
|
+
let abort;
|
|
26
|
+
const cancelled = new Promise((_, reject) => {
|
|
27
|
+
abort = () => reject(signal.reason);
|
|
28
|
+
signal.addEventListener('abort', abort, {once: true});
|
|
29
|
+
});
|
|
30
|
+
try {
|
|
31
|
+
const value = await Promise.race([this.gramlot.rpc.call('data', method, params, {signal}), cancelled]);
|
|
32
|
+
if (signal.aborted) throw signal.reason;
|
|
33
|
+
return value;
|
|
34
|
+
} finally {
|
|
35
|
+
signal.removeEventListener('abort', abort);
|
|
36
|
+
if (this.#controller === controller) this.#controller = null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
prepareValue(bag) {
|
|
40
|
+
if (!(bag instanceof Bag)) throw new TypeError('directory_tree must return a Bag');
|
|
41
|
+
for (const child of this.children) child.abort();
|
|
42
|
+
this.children.clear();
|
|
43
|
+
for (const node of bag.getNodes()) {
|
|
44
|
+
if (node.attr.is_directory) {
|
|
45
|
+
const resolver = new DirectoryResolver({gramlot: this.gramlot, root: this.params.root,
|
|
46
|
+
path: node.attr.path, onError: this.onError});
|
|
47
|
+
this.children.add(resolver);
|
|
48
|
+
bag.setResolver(node.label, resolver);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return bag;
|
|
52
|
+
}
|
|
53
|
+
abort() {
|
|
54
|
+
this.#closed = true;
|
|
55
|
+
this.#controller?.abort();
|
|
56
|
+
for (const child of this.children) child.abort();
|
|
57
|
+
this.children.clear();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Own directory requests; the selection and store remain in the component's Data Bag. */
|
|
62
|
+
export class FileSystemController {
|
|
63
|
+
constructor(gramlot, state) {
|
|
64
|
+
this.gramlot = gramlot;
|
|
65
|
+
this.state = state;
|
|
66
|
+
this.request = null;
|
|
67
|
+
this.resolver = null;
|
|
68
|
+
this.disposed = false;
|
|
69
|
+
}
|
|
70
|
+
async open(root) {
|
|
71
|
+
this.request?.abort();
|
|
72
|
+
const request = this.request = new AbortController();
|
|
73
|
+
this.state.setItem('status', 'Opening directory…');
|
|
74
|
+
try {
|
|
75
|
+
const result = await this.gramlot.rpc.call('data', 'workspace_open', {root}, {signal:request.signal});
|
|
76
|
+
if (this.disposed || request.signal.aborted) return null;
|
|
77
|
+
const resolver = new DirectoryResolver({gramlot:this.gramlot, root:result.root,
|
|
78
|
+
onError:error => this.state.setItem('status', error.message)});
|
|
79
|
+
const store = resolver.prepareValue(result.entries);
|
|
80
|
+
this.resolver?.abort();
|
|
81
|
+
this.resolver = resolver;
|
|
82
|
+
this.state.setItem('selectedPath', null);
|
|
83
|
+
this.state.setItem('store', store);
|
|
84
|
+
this.state.setItem('root', result.root);
|
|
85
|
+
this.state.setItem('status', '');
|
|
86
|
+
return result.root;
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (!this.disposed && !request.signal.aborted) this.state.setItem('status', error.message);
|
|
89
|
+
return null;
|
|
90
|
+
} finally { if (this.request === request) this.request = null; }
|
|
91
|
+
}
|
|
92
|
+
dispose() { this.disposed = true; this.request?.abort(); this.resolver?.abort(); }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Named Logic used by the reusable Source composition; instances are scoped by Data. */
|
|
96
|
+
export class FileSystemLogic {
|
|
97
|
+
fileSystemMount(node) {
|
|
98
|
+
this.fileSystems ??= new WeakMap();
|
|
99
|
+
const scope = node.parentNode, state = scope.getRelativeData('.');
|
|
100
|
+
const controller = new FileSystemController(this.page, state);
|
|
101
|
+
this.fileSystems.set(state, controller);
|
|
102
|
+
this.page.src.renderer.onDispose(scope, () => controller.dispose());
|
|
103
|
+
}
|
|
104
|
+
fileSystemOpen(node, {root}) {
|
|
105
|
+
if (root) return this.fileSystems.get(node.getRelativeData('.')).open(root);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function fileSystemTree(parent, {datapath, ...attributes}) {
|
|
110
|
+
const pane = parent.div({datapath, class:'gramlot-filesystem', ...attributes});
|
|
111
|
+
pane.dataSetter({destination_path:'.store', value:new Bag()});
|
|
112
|
+
pane.dataSetter({destination_path:'.root', value:null});
|
|
113
|
+
pane.dataSetter({destination_path:'.requestedRoot', value:null});
|
|
114
|
+
pane.dataSetter({destination_path:'.selectedPath', value:null});
|
|
115
|
+
pane.dataSetter({destination_path:'.status', value:''});
|
|
116
|
+
pane.dataController({func:'fileSystemMount', _onBuilt:true});
|
|
117
|
+
pane.dataController({func:'fileSystemOpen', root:'^.requestedRoot'});
|
|
118
|
+
pane.tree({storepath:'.store', selectedPath:'^.selectedPath', labelAttribute:'caption', hideValues:true,
|
|
119
|
+
class:'gramlot-filesystem-tree'});
|
|
120
|
+
pane.div('^.status', {role:'status', class:'gramlot-filesystem-status'});
|
|
121
|
+
return pane;
|
|
122
|
+
}
|