@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.
- package/dist/components/editors.js +116527 -0
- package/dist/components/inputs.js +24507 -0
- package/dist/components/layout.js +1402 -0
- package/dist/components/tree.js +24538 -0
- package/dist/components/typst.js +4 -0
- package/dist/gramlot.js +1442 -625
- package/dist/gramlot.min.js +27 -405
- package/dist/runtime-notices.json +208 -0
- package/dist/typst-worker-source.js +4 -0
- package/package.json +36 -3
- package/src/binding/hooks.js +14 -0
- package/src/binding/providers.js +4 -0
- package/src/binding/remote-resolver.js +52 -0
- package/src/binding/remote.js +2 -0
- package/src/binding/router.js +11 -4
- package/src/binding/rpc-resolver.js +14 -93
- package/src/binding/runtime.js +10 -4
- package/src/components/bases.js +1 -0
- package/src/components/border-container.js +46 -23
- 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/registry.js +6 -4
- package/src/components/tree.js +350 -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/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-page-runtime.d.ts +7 -8
- package/src/index-page-runtime.js +100 -396
- package/src/index.d.ts +7 -1
- package/src/index.js +5 -1
- package/src/navigation-resolver.d.ts +6 -0
- package/src/navigation-resolver.js +60 -0
- package/src/renderer/attributes.js +2 -1
- package/src/renderer/drag-drop-policy.js +48 -0
- package/src/renderer/drag-drop.js +213 -0
- package/src/renderer/drag-preparation.js +33 -0
- package/src/renderer/gramlot-renderer.d.ts +18 -0
- package/src/renderer/gramlot-renderer.js +41 -2
- package/src/server/frame-page.d.ts +12 -0
- package/src/server/frame-page.js +23 -0
- package/src/server/gramlot-server.js +2 -1
- package/src/server/index-page.d.ts +10 -14
- package/src/server/index-page.js +26 -95
- package/src/server/page.d.ts +7 -0
- package/src/server/page.js +5 -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 +6 -1
- package/tools/gramlot-tools-inspector.js +16 -9
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import {controlElement} from './bases.js';
|
|
2
|
+
import {defineComponent} from './registry.js';
|
|
3
|
+
import {Labelbox} from './labelbox.js';
|
|
4
|
+
import {FieldState} from './field-state.js';
|
|
5
|
+
|
|
6
|
+
const languages = ['text', 'python', 'javascript', 'typescript', 'json', 'html', 'css', 'xml', 'markdown', 'sql', 'typst'];
|
|
7
|
+
let engineModule;
|
|
8
|
+
export function EditorControl(HTMLElement) {
|
|
9
|
+
return class extends controlElement(HTMLElement) {
|
|
10
|
+
#value = '';
|
|
11
|
+
#generation = 0;
|
|
12
|
+
constructor() {
|
|
13
|
+
super();
|
|
14
|
+
this.control = this.ownerDocument.createElement('div');
|
|
15
|
+
this.control.id = 'control'; this.control.className = 'editor-control';
|
|
16
|
+
this.controlBox.append(this.control);
|
|
17
|
+
const style = this.ownerDocument.createElement('style');
|
|
18
|
+
style.textContent = `:host{display:block;height:300px;min-height:0;min-width:0}
|
|
19
|
+
.control-box,.labelbox,.editor-control{height:100%;min-height:0;min-width:0}
|
|
20
|
+
.labelbox{grid-template-rows:auto minmax(0,1fr)}
|
|
21
|
+
.editor-control{border:1px solid var(--gramlot-border-control,GrayText);border-radius:var(--gramlot-radius-sm,4px);overflow:hidden}
|
|
22
|
+
:host([data-editor-disabled]) .editor-control{opacity:.6}
|
|
23
|
+
.editor-status{padding:1em;color:var(--gramlot-text-secondary,GrayText)}`;
|
|
24
|
+
this.shadowRoot.append(style);
|
|
25
|
+
// Engine transactions emit one normalized control event. Native contenteditable
|
|
26
|
+
// input events must not produce a second binding write.
|
|
27
|
+
for (const type of ['input','change']) this.control.addEventListener(type, event => {
|
|
28
|
+
if (event.target !== this.control) event.stopImmediatePropagation();
|
|
29
|
+
});
|
|
30
|
+
this.control.addEventListener('focusout', () => this.#emit('change'));
|
|
31
|
+
}
|
|
32
|
+
get liveWrites() { return true; }
|
|
33
|
+
connectedCallback() {
|
|
34
|
+
const generation = ++this.#generation;
|
|
35
|
+
this.control.textContent = 'Loading editor…';
|
|
36
|
+
this.ready = (engineModule ??= import('./code-mirror-engine.js')).then(module => {
|
|
37
|
+
if (generation !== this.#generation || !this.isConnected) return;
|
|
38
|
+
this.control.textContent = '';
|
|
39
|
+
this.editor = module.createEditor(this);
|
|
40
|
+
this.editor.publishHistory();
|
|
41
|
+
}).catch(error => {
|
|
42
|
+
if (generation !== this.#generation) return;
|
|
43
|
+
this.control.textContent = `CodeMirror could not start: ${error.message}`;
|
|
44
|
+
this.control.setAttribute('role','alert');
|
|
45
|
+
throw error;
|
|
46
|
+
});
|
|
47
|
+
// Keep the rejected ready promise inspectable without an unhandled rejection.
|
|
48
|
+
this.ready.catch(error => console.error(error));
|
|
49
|
+
}
|
|
50
|
+
releaseControl() { ++this.#generation; this.editor?.destroy(); this.editor = null; super.releaseControl(); }
|
|
51
|
+
projectAttributes(attrs) {
|
|
52
|
+
const rest = super.projectAttributes(attrs), p = this.parameters;
|
|
53
|
+
if (!languages.includes(p.language)) throw new TypeError(`Unsupported CodeMirror language: ${p.language}`);
|
|
54
|
+
if (!Number.isInteger(p.indentUnit) || p.indentUnit < 1 || p.indentUnit > 16) throw new TypeError('indentUnit must be an integer from 1 to 16');
|
|
55
|
+
if (!Number.isFinite(p.fontSize) || p.fontSize < 8 || p.fontSize > 48) throw new TypeError('fontSize must be from 8 to 48');
|
|
56
|
+
this.control.disabled = p.disabled; this.control.readOnly = p.readonly;
|
|
57
|
+
this.toggleAttribute('data-editor-disabled', p.disabled);
|
|
58
|
+
this.control.style.fontFamily = p.fontFamily; this.control.style.fontSize = `${p.fontSize}px`;
|
|
59
|
+
this.editor?.configure();
|
|
60
|
+
return rest;
|
|
61
|
+
}
|
|
62
|
+
#emit(type) {this.control.dispatchEvent(new this.ownerDocument.defaultView.Event(type, {bubbles:true}));}
|
|
63
|
+
editorChanged(value) {this.#value = value; this.#emit('input');}
|
|
64
|
+
readControlValue() {return this.#value;}
|
|
65
|
+
writeControlValue(value) {
|
|
66
|
+
if (typeof value !== 'string') throw new TypeError('CodeMirror value must be a string');
|
|
67
|
+
if (value === this.#value) return;
|
|
68
|
+
this.#value = value; this.editor?.replace(value);
|
|
69
|
+
}
|
|
70
|
+
focus() {if (!this.parameters.disabled) this.editor?.view.focus();}
|
|
71
|
+
setDiagnostics(items) {this.editor.diagnostics(items);}
|
|
72
|
+
revealPosition(position) {this.editor.reveal(position);}
|
|
73
|
+
undo() {return this.editor ? this.editor.undo() : false;}
|
|
74
|
+
redo() {return this.editor ? this.editor.redo() : false;}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
EditorControl.parameters = {
|
|
78
|
+
disabled:{dtype:'B', default:false, binding:'read'}, readonly:{dtype:'B', default:false, binding:'read'},
|
|
79
|
+
live:{dtype:'B', default:true, binding:'read'}
|
|
80
|
+
};
|
|
81
|
+
const toggle = {dtype:'B', default:true, binding:'read'};
|
|
82
|
+
export const CodeMirror = defineComponent({name:'codeMirror', tag:'gramlot-code-mirror', base:EditorControl, mixins:[Labelbox,FieldState],
|
|
83
|
+
parameters:{value:{dtype:'T', default:'', binding:'twoWay'}, language:{dtype:'T', default:'text', binding:'read', enum:languages},
|
|
84
|
+
lineNumbers:toggle, lineWrapping:toggle, indentUnit:{dtype:'L',default:4,binding:'read'},
|
|
85
|
+
fontSize:{dtype:'L',default:14,binding:'read'}, fontFamily:{dtype:'T',default:'monospace',binding:'read'},
|
|
86
|
+
folding:toggle, bracketMatching:toggle, autoCloseBrackets:toggle, autoIndent:toggle, autocompletion:toggle, highlightActiveLine:toggle, highlightSelectionMatches:toggle},
|
|
87
|
+
implementation:Base => class extends Base {}
|
|
88
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type {SourceBag, SourceBagNode} from '@genrojs/builders';
|
|
2
|
+
/** Reusable Source composition; relative value pointers resolve within datapath. */
|
|
3
|
+
export function codeMirrorWithOptions(parent: SourceBag | SourceBagNode, options: {
|
|
4
|
+
datapath: string;
|
|
5
|
+
value: string;
|
|
6
|
+
language?: string;
|
|
7
|
+
height?: string;
|
|
8
|
+
[attribute: string]: unknown;
|
|
9
|
+
}): SourceBagNode;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Source composition; settings belong to the caller's scoped Data. */
|
|
2
|
+
export function codeMirrorWithOptions(parent, {datapath, value, language = 'text', height = '420px', ...attributes}) {
|
|
3
|
+
if (!datapath) throw new TypeError('codeMirrorWithOptions requires datapath');
|
|
4
|
+
const pane = parent.borderContainer({datapath, height, class:'gramlot-editor-options'});
|
|
5
|
+
const defaults = {language, indentUnit:4, fontSize:14, fontFamily:'monospace', lineNumbers:true, lineWrapping:true,
|
|
6
|
+
folding:true, bracketMatching:true, autoCloseBrackets:true, autoIndent:true, autocompletion:true, highlightActiveLine:true, highlightSelectionMatches:true};
|
|
7
|
+
for (const [name, setting] of Object.entries(defaults)) pane.dataSetter({destination_path:`.settings.${name}`, value:setting});
|
|
8
|
+
const options = pane.contentPane({region:'right', width:'250px', drawer:'close', drawer_label:'Options', drawer_icon:'⚙', drawer_minimize:false,
|
|
9
|
+
padding:'12px', overflow:'auto', class:'gramlot-editor-settings'});
|
|
10
|
+
options.h3('Editor options');
|
|
11
|
+
options.filteringSelect({value:'^.settings.language', lbl:'Language', values:'text:Plain text,python:Python,javascript:JavaScript,typescript:TypeScript,json:JSON,html:HTML,css:CSS,xml:XML,markdown:Markdown,sql:SQL,typst:Typst'});
|
|
12
|
+
options.numberTextBox({value:'^.settings.indentUnit', lbl:'Indent spaces', min:1, max:16, dtype:'L', validate_notnull:true});
|
|
13
|
+
options.numberTextBox({value:'^.settings.fontSize', lbl:'Font size', min:8, max:48, dtype:'L', validate_notnull:true});
|
|
14
|
+
options.textbox({value:'^.settings.fontFamily', lbl:'Font family'});
|
|
15
|
+
const labels = {lineNumbers:'Line numbers', lineWrapping:'Wrap lines', folding:'Code folding', bracketMatching:'Match brackets', autoCloseBrackets:'Close brackets and quotes', autoIndent:'Automatic indentation',
|
|
16
|
+
autocompletion:'Local completion', highlightActiveLine:'Highlight current line', highlightSelectionMatches:'Highlight matching selections'};
|
|
17
|
+
for (const [name, label] of Object.entries(labels)) options.checkbox({value:`^.settings.${name}`, label, display:'block', margin_top:'8px'});
|
|
18
|
+
const center = pane.contentPane({region:'center', min_height:0});
|
|
19
|
+
center.codeMirror({...attributes, value, height:'100%', ...Object.fromEntries(Object.keys(defaults).map(name => [name, `^.settings.${name}`]))});
|
|
20
|
+
return pane;
|
|
21
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import {defineCollection} from './registry.js';
|
|
2
|
+
import {CodeMirror} from './code-mirror.js';
|
|
3
|
+
import {HtmlEditor} from './html-editor.js';
|
|
4
|
+
import {HtmlPreview,MarkdownPreview} from './html-preview.js';
|
|
5
|
+
import {MarkdownEditor} from './markdown-editor.js';
|
|
6
|
+
export {CodeMirror} from './code-mirror.js';
|
|
7
|
+
export {HtmlEditor} from './html-editor.js';
|
|
8
|
+
export {HtmlPreview,MarkdownPreview} from './html-preview.js';
|
|
9
|
+
export {MarkdownEditor} from './markdown-editor.js';
|
|
10
|
+
export default defineCollection({name:'editors', components:[CodeMirror,HtmlEditor,HtmlPreview,MarkdownEditor,MarkdownPreview]});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Preserve nonvisual document content while editing the body through Jodit. */
|
|
2
|
+
const protectedSelector = 'script,style,iframe,object,embed,template,svg,math,link,meta,base';
|
|
3
|
+
const unsafeAttribute = (element, name, value) => /^on/i.test(name) || ['autofocus','srcdoc'].includes(name) ||
|
|
4
|
+
(['href','src','action','formaction','xlink:href'].includes(name) && /^(?:javascript|vbscript|data):/i.test(value.trim()) &&
|
|
5
|
+
!(element.tagName === 'IMG' && name === 'src' && /^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(value)));
|
|
6
|
+
|
|
7
|
+
export function prepareHtmlDocument(value, window) {
|
|
8
|
+
const parse = html => new window.DOMParser().parseFromString(html,'text/html');
|
|
9
|
+
const original = parse(value);
|
|
10
|
+
const full = /<(?:html|head|body)[\s>]|<!doctype/i.test(value) || original.head.children.length > 0;
|
|
11
|
+
const display = original.body.cloneNode(true);
|
|
12
|
+
const marker = `data-gramlot-${crypto.randomUUID()}`;
|
|
13
|
+
const nodes = new Map(), attributes = new Map();
|
|
14
|
+
let sequence = 0;
|
|
15
|
+
const comments = [], walker = original.createTreeWalker(display,128);
|
|
16
|
+
while (walker.nextNode()) comments.push(walker.currentNode);
|
|
17
|
+
for (const node of [...display.querySelectorAll(protectedSelector), ...comments]) {
|
|
18
|
+
if (!display.contains(node)) continue;
|
|
19
|
+
const id = String(++sequence), placeholder = original.createElement('span');
|
|
20
|
+
placeholder.setAttribute(marker,id); placeholder.setAttribute('contenteditable','false');
|
|
21
|
+
placeholder.textContent = `[${node.nodeName.toLowerCase()} — edit in Code]`;
|
|
22
|
+
nodes.set(id,node.cloneNode(true)); node.replaceWith(placeholder);
|
|
23
|
+
}
|
|
24
|
+
for (const element of display.querySelectorAll('*')) {
|
|
25
|
+
const removed = [...element.attributes].filter(attr => unsafeAttribute(element,attr.name,attr.value))
|
|
26
|
+
.map(attr => [attr.name,attr.value]);
|
|
27
|
+
if (!removed.length) continue;
|
|
28
|
+
for (const [name] of removed) element.removeAttribute(name);
|
|
29
|
+
const id = String(++sequence); element.setAttribute(`${marker}-attrs`,id); attributes.set(id,removed);
|
|
30
|
+
}
|
|
31
|
+
const unique = (body, attribute, id) => {
|
|
32
|
+
const matches = body.querySelectorAll(`[${attribute}="${id}"]`);
|
|
33
|
+
if (matches.length !== 1) throw new Error('Protected page content changed. Use Code to edit it.');
|
|
34
|
+
return matches[0];
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
html:display.innerHTML,
|
|
38
|
+
styles:[...original.head.querySelectorAll('style')].map(node => node.textContent).join('\n'),
|
|
39
|
+
serialize(html) {
|
|
40
|
+
const edited = parse(html);
|
|
41
|
+
if (edited.body.querySelector(protectedSelector) || [...edited.body.querySelectorAll('*')].some(element =>
|
|
42
|
+
[...element.attributes].some(attr => unsafeAttribute(element,attr.name,attr.value)))) {
|
|
43
|
+
throw new Error('Active or embedded content must be edited in Code.');
|
|
44
|
+
}
|
|
45
|
+
for (const [id,node] of nodes) unique(edited.body,marker,id).replaceWith(node.cloneNode(true));
|
|
46
|
+
for (const [id,removed] of attributes) {
|
|
47
|
+
const element = unique(edited.body,`${marker}-attrs`,id);
|
|
48
|
+
for (const [name,value] of removed) element.setAttribute(name,value);
|
|
49
|
+
element.removeAttribute(`${marker}-attrs`);
|
|
50
|
+
}
|
|
51
|
+
const result = original.cloneNode(true);
|
|
52
|
+
result.body.innerHTML = edited.body.innerHTML;
|
|
53
|
+
return full ? (result.doctype ? new window.XMLSerializer().serializeToString(result.doctype)+'\n' : '') + result.documentElement.outerHTML : result.body.innerHTML;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import {controlElement} from './bases.js';
|
|
2
|
+
import {defineComponent} from './registry.js';
|
|
3
|
+
import {Labelbox} from './labelbox.js';
|
|
4
|
+
import {FieldState} from './field-state.js';
|
|
5
|
+
|
|
6
|
+
let engineModule;
|
|
7
|
+
function HtmlControl(HTMLElement) {
|
|
8
|
+
return class extends controlElement(HTMLElement) {
|
|
9
|
+
#value='';
|
|
10
|
+
#generation=0;
|
|
11
|
+
constructor() {
|
|
12
|
+
super();
|
|
13
|
+
this.control=this.ownerDocument.createElement('div');
|
|
14
|
+
this.control.className='html-editor-control';
|
|
15
|
+
this.controlBox.append(this.control);
|
|
16
|
+
const style=this.ownerDocument.createElement('style');
|
|
17
|
+
style.textContent=':host{display:block;height:400px;min-height:0}.control-box,.labelbox,.html-editor-control{height:100%;min-height:0}.labelbox{grid-template-rows:auto minmax(0,1fr)}.html-editor-control{overflow:hidden}.html-editor-status{font:inherit;color:var(--gramlot-text-secondary,GrayText)}.html-editor-status:empty{display:none}';
|
|
18
|
+
this.shadowRoot.append(style);
|
|
19
|
+
for (const type of ['input','change']) this.control.addEventListener(type,event=>{
|
|
20
|
+
if (event.target!==this.control) event.stopImmediatePropagation();
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
get liveWrites() {return true;}
|
|
24
|
+
connectedCallback() {this.load();}
|
|
25
|
+
load() {
|
|
26
|
+
const generation=++this.#generation;
|
|
27
|
+
this.engine?.destroy();this.engine=null;
|
|
28
|
+
this.control.textContent='Loading HTML editor…';
|
|
29
|
+
this.ready=(engineModule ??= import('./jodit-engine.js')).then(module=>{
|
|
30
|
+
if (generation!==this.#generation || !this.isConnected) return;
|
|
31
|
+
this.control.textContent='';
|
|
32
|
+
this.engine=module.createHtmlEditor(this);
|
|
33
|
+
}).catch(error=>{
|
|
34
|
+
if (generation!==this.#generation) return;
|
|
35
|
+
this.control.textContent=`HTML editor could not start: ${error.message}`;
|
|
36
|
+
this.control.setAttribute('role','alert');
|
|
37
|
+
throw error;
|
|
38
|
+
});
|
|
39
|
+
this.ready.catch(error=>console.error(error));
|
|
40
|
+
}
|
|
41
|
+
projectAttributes(attrs) {
|
|
42
|
+
const rest=super.projectAttributes(attrs);
|
|
43
|
+
this.control.disabled=this.parameters.disabled;
|
|
44
|
+
this.control.readOnly=this.parameters.readonly;
|
|
45
|
+
this.engine?.configure();
|
|
46
|
+
return rest;
|
|
47
|
+
}
|
|
48
|
+
readControlValue() {return this.#value;}
|
|
49
|
+
writeControlValue(value) {
|
|
50
|
+
if (typeof value!=='string') throw new TypeError('HTML editor value must be a string');
|
|
51
|
+
if (value===this.#value) return;
|
|
52
|
+
this.#value=value;
|
|
53
|
+
if (this.isConnected && this.engine) this.load();
|
|
54
|
+
}
|
|
55
|
+
editorChanged(value) {
|
|
56
|
+
this.#value=value;
|
|
57
|
+
this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('input',{bubbles:true}));
|
|
58
|
+
}
|
|
59
|
+
editorBlurred() {this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('change',{bubbles:true}));}
|
|
60
|
+
undo() {return this.engine ? this.engine.undo() : false;}
|
|
61
|
+
redo() {return this.engine ? this.engine.redo() : false;}
|
|
62
|
+
focus() {if (!this.parameters.disabled) this.engine?.focus();}
|
|
63
|
+
releaseControl() {++this.#generation;this.engine?.destroy();this.engine=null;super.releaseControl();}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
HtmlControl.parameters={disabled:{dtype:'B',default:false,binding:'read'},readonly:{dtype:'B',default:false,binding:'read'},live:{dtype:'B',default:true,binding:'read'}};
|
|
67
|
+
export const HtmlEditor=defineComponent({name:'htmlEditor',tag:'gramlot-html-editor',base:HtmlControl,mixins:[Labelbox,FieldState],
|
|
68
|
+
parameters:{value:{dtype:'T',default:'',binding:'twoWay'}},implementation:Base=>class extends Base {}});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {defineComponent} from './registry.js';
|
|
2
|
+
import {projectParameters} from './parameters.js';
|
|
3
|
+
import {renderMarkdownDocument} from './markdown-document.js';
|
|
4
|
+
|
|
5
|
+
function PreviewElement(HTMLElement) {
|
|
6
|
+
return class extends HTMLElement {
|
|
7
|
+
constructor() {
|
|
8
|
+
super();
|
|
9
|
+
const root=this.attachShadow({mode:'open'});
|
|
10
|
+
const style=this.ownerDocument.createElement('style');
|
|
11
|
+
style.textContent=':host{display:block;height:100%;min-height:0}iframe{display:block;width:100%;height:100%;border:0;background:white}';
|
|
12
|
+
this.frame=this.ownerDocument.createElement('iframe');
|
|
13
|
+
this.frame.setAttribute('sandbox','');
|
|
14
|
+
this.frame.title='HTML preview';
|
|
15
|
+
root.append(style,this.frame);
|
|
16
|
+
}
|
|
17
|
+
renderDocument(value) {return value;}
|
|
18
|
+
projectAttributes(attrs) {
|
|
19
|
+
const rest=projectParameters(this,attrs);
|
|
20
|
+
const html=this.renderDocument(this.parameters.value);
|
|
21
|
+
if (this.frame.srcdoc !== html) this.frame.srcdoc=html;
|
|
22
|
+
return rest;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export const HtmlPreview=defineComponent({name:'htmlPreview',tag:'gramlot-html-preview',base:PreviewElement,
|
|
27
|
+
parameters:{value:{dtype:'T',default:'',binding:'read'}},implementation:Base=>class extends Base {}});
|
|
28
|
+
|
|
29
|
+
export const MarkdownPreview=defineComponent({name:'markdownPreview',tag:'gramlot-markdown-preview',base:PreviewElement,
|
|
30
|
+
parameters:{value:{dtype:'T',default:'',binding:'read'},allowHtml:{dtype:'B',default:false,binding:'read'}},implementation:Base=>class extends Base {
|
|
31
|
+
constructor(){super();this.frame.title='Markdown preview';}
|
|
32
|
+
renderDocument(value){return renderMarkdownDocument(value,{allowHtml:this.parameters.allowHtml,document:this.ownerDocument});}
|
|
33
|
+
}});
|
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
|
+
}
|
|
@@ -16,7 +16,7 @@ function annotation(parameter) {
|
|
|
16
16
|
}
|
|
17
17
|
|
|
18
18
|
/** Compose effective metadata without invoking a DOM class factory. */
|
|
19
|
-
export function defineComponent({name, tag, base, mixins = [], parameters = {}, subTags = '', presentationDefaults = [], dataScope = false, command = false, childParameters = {}, sourceContext = false, implementation}) {
|
|
19
|
+
export function defineComponent({name, tag, base, mixins = [], parameters = {}, subTags = '', presentationDefaults = [], dataScope = false, command = false, childParameters = {}, sourceContext = false, bagStore = false, dragSource = false, implementation}) {
|
|
20
20
|
webcomponentCode({code: tag});
|
|
21
21
|
if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(name)) throw new TypeError('Invalid component authoring name');
|
|
22
22
|
const effective = {...base.parameters};
|
|
@@ -28,8 +28,8 @@ export function defineComponent({name, tag, base, mixins = [], parameters = {},
|
|
|
28
28
|
}
|
|
29
29
|
Object.assign(effective, parameters);
|
|
30
30
|
for (const spec of Object.values(effective)) annotation(spec);
|
|
31
|
-
return Object.freeze({name, tag, base, subTags, presentationDefaults: Object.freeze([...presentationDefaults]), dataScope, command, mixins: Object.freeze([...mixins]),
|
|
32
|
-
parameters: freeze(structuredClone(effective)), childParameters: freeze(structuredClone(childParameters)), sourceContext, implementation});
|
|
31
|
+
return Object.freeze({name, tag, base, subTags, presentationDefaults: Object.freeze([...presentationDefaults]), dataScope, command, bagStore, mixins: Object.freeze([...mixins]),
|
|
32
|
+
parameters: freeze(structuredClone(effective)), childParameters: freeze(structuredClone(childParameters)), sourceContext, dragSource, implementation});
|
|
33
33
|
}
|
|
34
34
|
|
|
35
35
|
export class ComponentCollection {
|
|
@@ -62,7 +62,9 @@ export class ComponentCollection {
|
|
|
62
62
|
_meta: {render_tag: component.tag, gramlot_component: {parameters: structuredClone(component.parameters),
|
|
63
63
|
presentationDefaults: [...component.presentationDefaults], dataScope: component.dataScope, command: component.command,
|
|
64
64
|
...(Object.keys(component.childParameters).length ? {childParameters: structuredClone(component.childParameters)} : {}),
|
|
65
|
-
...(component.sourceContext ? {sourceContext: true} : {})
|
|
65
|
+
...(component.sourceContext ? {sourceContext: true} : {}),
|
|
66
|
+
...(component.dragSource ? {dragSource: true} : {}),
|
|
67
|
+
...(component.bagStore ? {bagStore: true} : {})}}
|
|
66
68
|
}]))};
|
|
67
69
|
}
|
|
68
70
|
/** Register once per document realm, only when the collection is activated. */
|