@gramlot/gramlot 0.3.8 → 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 +751 -28
- 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 +2 -0
- package/src/binding/runtime.js +2 -4
- package/src/components/bases.js +1 -0
- 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/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/gramlot-renderer.js +3 -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/binding/runtime.js
CHANGED
|
@@ -3,6 +3,7 @@ import {DataRouter} from './router.js';
|
|
|
3
3
|
import {DataInstaller} from './installation.js';
|
|
4
4
|
import {ControllerProvider, FormulaProvider, RemoteProvider, RpcProvider} from './providers.js';
|
|
5
5
|
import {InlineCompiler} from './inline.js';
|
|
6
|
+
import {isLogicMethod, callLogic} from './hooks.js';
|
|
6
7
|
import {RemoteBinding} from './remote.js';
|
|
7
8
|
import {AskDialog} from './ask-dialog.js';
|
|
8
9
|
import {randomId} from '../random-id.js';
|
|
@@ -452,10 +453,7 @@ export class NodeBinding {
|
|
|
452
453
|
if (typeof handler !== 'string' || !handler) throw new TypeError(`${name} requires a handler`);
|
|
453
454
|
return payload => {
|
|
454
455
|
if (this.closed) return;
|
|
455
|
-
if (
|
|
456
|
-
const {group, method} = this.runtime.logicRegistry.resolve(handler, node);
|
|
457
|
-
return method.call(group, node, payload);
|
|
458
|
-
}
|
|
456
|
+
if (isLogicMethod(handler)) return callLogic(this.runtime, node, handler, payload);
|
|
459
457
|
const [, attrs] = node.rootBuilder.runtimeValues(node);
|
|
460
458
|
const authored = Object.fromEntries(Object.entries(attrs).filter(([key]) =>
|
|
461
459
|
!key.startsWith('subscribe_') && !key.startsWith('selfsubscribe_')));
|
package/src/components/bases.js
CHANGED
|
@@ -33,6 +33,7 @@ export function controlElement(HTMLElement) {
|
|
|
33
33
|
}
|
|
34
34
|
setPageContext(context) { this.pageContext = context; }
|
|
35
35
|
releaseControl() {}
|
|
36
|
+
get liveWrites() { return this.control.localName === 'textarea' || ['text', 'password', 'range', 'color'].includes(this.control.type); }
|
|
36
37
|
validateCandidate(value, accept) {
|
|
37
38
|
accept(value);
|
|
38
39
|
return {ok:true, value, isCurrent:() => this.pageContext.isActive()};
|
|
@@ -26,6 +26,9 @@ function Command(HTMLElement) {
|
|
|
26
26
|
min-height:max(var(--gramlot-field-height,28px),var(--gramlot-touch-target,0px));
|
|
27
27
|
padding:var(--gramlot-button-padding,.25em .65em);cursor:pointer}
|
|
28
28
|
button:hover:not(:disabled){background:var(--gramlot-button-hover,var(--gramlot-field-readonly-background,#eee))}
|
|
29
|
+
:host(.button--quiet) button{background:transparent;color:var(--gramlot-action,CanvasText);border-color:transparent}
|
|
30
|
+
:host(.button--quiet) button:hover:not(:disabled){background:var(--gramlot-selected,Highlight);color:var(--gramlot-action-hover,CanvasText);border-color:transparent}
|
|
31
|
+
button:focus-visible{outline:2px solid var(--gramlot-focus-ring,Highlight);outline-offset:2px}
|
|
29
32
|
button:disabled{opacity:.55;cursor:not-allowed} .icon:empty{display:none}
|
|
30
33
|
.led{display:inline-block;width:.6em;height:.6em;border-radius:50%;background:var(--gramlot-button-led-off,#888)}
|
|
31
34
|
[aria-pressed=true] .led{background:var(--gramlot-button-led-on,#2b9a46)}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {Bag} from '@genrojs/bag';
|
|
1
2
|
import {NativeControl} from './bases.js';
|
|
2
3
|
import {parseChoices} from './choices.js';
|
|
3
4
|
import {positionPopup} from './popup.js';
|
|
@@ -13,6 +14,7 @@ export function ChoiceEditor(HTMLElement) {
|
|
|
13
14
|
#dirty = false;
|
|
14
15
|
#picked = null;
|
|
15
16
|
#source;
|
|
17
|
+
#separator;
|
|
16
18
|
#cleanup;
|
|
17
19
|
constructor() {
|
|
18
20
|
super();
|
|
@@ -74,8 +76,9 @@ export function ChoiceEditor(HTMLElement) {
|
|
|
74
76
|
get active() { return this.isConnected && this.pageContext?.isActive(); }
|
|
75
77
|
projectAttributes(attrs, adapt) {
|
|
76
78
|
const rest = super.projectAttributes(attrs, adapt);
|
|
77
|
-
const source = this.parameters.callback ?? this.parameters.values;
|
|
78
|
-
const changed = source !== this.#source;
|
|
79
|
+
const source = this.parameters.store ?? this.parameters.callback ?? this.parameters.values;
|
|
80
|
+
const changed = source !== this.#source || this.parameters.separator !== this.#separator;
|
|
81
|
+
this.#separator = this.parameters.separator;
|
|
79
82
|
this.#source = source;
|
|
80
83
|
this.toggle.disabled = this.locked;
|
|
81
84
|
if (changed || this.locked) this.closeChoices();
|
|
@@ -199,7 +202,18 @@ ChoiceEditor.parameters = {...NativeControl.parameters,
|
|
|
199
202
|
export function localChoices(Base) {
|
|
200
203
|
return class extends Base {
|
|
201
204
|
loadChoices(keywords) {
|
|
202
|
-
|
|
205
|
+
let rows;
|
|
206
|
+
if (this.parameters.store != null) {
|
|
207
|
+
if (!(this.parameters.store instanceof Bag)) throw new TypeError('store must be a Bag');
|
|
208
|
+
if (this.parameters.values) throw new TypeError('store and values are mutually exclusive');
|
|
209
|
+
const ids = new Set();
|
|
210
|
+
rows = this.parameters.store.getNodes().map(node => {
|
|
211
|
+
const id = node.staticValue, caption = node.attr.caption;
|
|
212
|
+
if (typeof id !== 'string' || !id || typeof caption !== 'string' || ids.has(id)) throw new TypeError('Invalid or duplicate store choice');
|
|
213
|
+
ids.add(id);
|
|
214
|
+
return {id, caption};
|
|
215
|
+
});
|
|
216
|
+
} else rows = parseChoices(this.parameters.values ?? '', this.parameters.separator);
|
|
203
217
|
return rows.filter(row => Object.hasOwn(keywords, '_id') ? row.id === keywords._id
|
|
204
218
|
: row.caption.toLocaleLowerCase().includes(keywords._querystring.toLocaleLowerCase()));
|
|
205
219
|
}
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
/** Local choices share the same code:caption grammar in editors and groups. */
|
|
2
|
-
export function parseChoices(values) {
|
|
2
|
+
export function parseChoices(values, separator = ',') {
|
|
3
|
+
if (typeof separator !== 'string' || !separator) throw new TypeError('separator must be a nonempty string');
|
|
3
4
|
if (values === '') return [];
|
|
4
5
|
const ids = new Set();
|
|
5
|
-
return values.split(
|
|
6
|
+
return values.split(separator).map(item => {
|
|
6
7
|
const colon = item.indexOf(':');
|
|
7
8
|
const id = colon < 0 ? item : item.slice(0, colon);
|
|
8
9
|
const caption = colon < 0 ? item : item.slice(colon + 1);
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/** Optional CodeMirror engine; loaded only when an editor is connected. */
|
|
2
|
+
import {EditorState, Compartment} from '@codemirror/state';
|
|
3
|
+
import {EditorView, keymap, lineNumbers, highlightActiveLine, highlightActiveLineGutter, drawSelection, dropCursor} from '@codemirror/view';
|
|
4
|
+
import {syntaxHighlighting, HighlightStyle, bracketMatching, indentOnInput, indentUnit, foldGutter, foldKeymap} from '@codemirror/language';
|
|
5
|
+
import {defaultKeymap, history, historyKeymap, undo, redo, undoDepth, redoDepth, indentWithTab, insertNewline, insertNewlineAndIndent} from '@codemirror/commands';
|
|
6
|
+
import {search, searchKeymap, highlightSelectionMatches} from '@codemirror/search';
|
|
7
|
+
import {closeBrackets, closeBracketsKeymap, autocompletion, completionKeymap} from '@codemirror/autocomplete';
|
|
8
|
+
import {setDiagnostics} from '@codemirror/lint';
|
|
9
|
+
import {tags} from '@lezer/highlight';
|
|
10
|
+
import {python} from '@codemirror/lang-python';
|
|
11
|
+
import {javascript} from '@codemirror/lang-javascript';
|
|
12
|
+
import {json} from '@codemirror/lang-json';
|
|
13
|
+
import {html} from '@codemirror/lang-html';
|
|
14
|
+
import {css} from '@codemirror/lang-css';
|
|
15
|
+
import {xml} from '@codemirror/lang-xml';
|
|
16
|
+
import {markdown} from '@codemirror/lang-markdown';
|
|
17
|
+
import {typst_lezer} from 'codemirror-lang-typst/lezer';
|
|
18
|
+
import {sql} from '@codemirror/lang-sql';
|
|
19
|
+
|
|
20
|
+
const languages = {text: () => [], python, javascript, typescript: () => javascript({typescript:true}), json, html, css, xml, markdown, sql, typst:typst_lezer};
|
|
21
|
+
const colors = syntaxHighlighting(HighlightStyle.define([
|
|
22
|
+
{tag:[tags.keyword, tags.modifier], color:'var(--gramlot-editor-keyword, #9677d9)'},
|
|
23
|
+
{tag:[tags.string, tags.regexp], color:'var(--gramlot-editor-string, #318f74)'},
|
|
24
|
+
{tag:[tags.number, tags.bool, tags.null], color:'var(--gramlot-editor-number, #c47733)'},
|
|
25
|
+
{tag:tags.comment, color:'var(--gramlot-text-secondary, #78889a)', fontStyle:'italic'},
|
|
26
|
+
{tag:[tags.function(tags.variableName), tags.tagName], color:'var(--gramlot-editor-function, #5499cb)'}
|
|
27
|
+
]));
|
|
28
|
+
const theme = EditorView.theme({
|
|
29
|
+
'&': {height:'100%', color:'var(--gramlot-ink, CanvasText)', backgroundColor:'var(--gramlot-field-background, Canvas)'},
|
|
30
|
+
'.cm-scroller': {overflow:'auto', fontFamily:'inherit'},
|
|
31
|
+
'.cm-content': {caretColor:'var(--gramlot-ink, CanvasText)'},
|
|
32
|
+
'.cm-cursor, .cm-dropCursor': {borderLeftColor:'var(--gramlot-ink, CanvasText)'},
|
|
33
|
+
'.cm-gutters': {color:'var(--gramlot-text-secondary, GrayText)', backgroundColor:'var(--gramlot-surface-subtle, Canvas)', borderColor:'var(--gramlot-border-control, GrayText)'},
|
|
34
|
+
'.cm-activeLine, .cm-activeLineGutter': {backgroundColor:'color-mix(in srgb, var(--gramlot-brand-blue, Highlight) 10%, transparent)'},
|
|
35
|
+
'&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection': {backgroundColor:'color-mix(in srgb, var(--gramlot-brand-blue, Highlight) 28%, transparent)'},
|
|
36
|
+
'.cm-panels, .cm-tooltip': {color:'var(--gramlot-ink, CanvasText)', backgroundColor:'var(--gramlot-field-background, Canvas)', borderColor:'var(--gramlot-border-control, GrayText)'},
|
|
37
|
+
'.cm-textfield, .cm-button': {color:'inherit', background:'var(--gramlot-field-background, Canvas)', borderColor:'var(--gramlot-border-control, GrayText)'},
|
|
38
|
+
'.cm-search': {fontFamily:'system-ui', fontSize:'13px'}
|
|
39
|
+
});
|
|
40
|
+
function configuration(p) {
|
|
41
|
+
return [languages[p.language](), indentUnit.of(' '.repeat(p.indentUnit)),
|
|
42
|
+
EditorState.tabSize.of(p.indentUnit), EditorState.readOnly.of(Boolean(p.readonly || p.disabled)),
|
|
43
|
+
EditorView.editable.of(!p.disabled), EditorView.contentAttributes.of({'aria-readonly':String(p.readonly), 'aria-disabled':String(p.disabled), tabindex:p.disabled ? '-1' : '0', 'aria-label':p.lbl || 'Code editor'}),
|
|
44
|
+
p.lineNumbers ? lineNumbers() : [], p.lineWrapping ? EditorView.lineWrapping : [],
|
|
45
|
+
p.folding ? foldGutter() : [], p.autoCloseBrackets ? closeBrackets() : [],
|
|
46
|
+
p.autoIndent ? indentOnInput() : [], p.autocompletion ? autocompletion() : [],
|
|
47
|
+
p.highlightActiveLine ? [highlightActiveLine(), highlightActiveLineGutter()] : [],
|
|
48
|
+
p.highlightSelectionMatches ? highlightSelectionMatches() : [], p.bracketMatching ? bracketMatching() : [],
|
|
49
|
+
keymap.of([{key:'Enter', run:p.autoIndent ? insertNewlineAndIndent : insertNewline, shift:p.autoIndent ? insertNewlineAndIndent : insertNewline},
|
|
50
|
+
...(p.folding ? foldKeymap : []), ...(p.autoCloseBrackets ? closeBracketsKeymap : []), ...(p.autocompletion ? completionKeymap : [])])];
|
|
51
|
+
}
|
|
52
|
+
export function createEditor(host) {
|
|
53
|
+
const options = new Compartment();
|
|
54
|
+
let lastHistory, historyScheduled = false, disposed = false;
|
|
55
|
+
const publishHistory = () => {
|
|
56
|
+
if (historyScheduled) return;
|
|
57
|
+
historyScheduled = true;
|
|
58
|
+
// Subscribers may update bound toolbar Data. Notify after the current
|
|
59
|
+
// editor transaction / external value projection has fully completed.
|
|
60
|
+
queueMicrotask(() => {
|
|
61
|
+
historyScheduled = false;
|
|
62
|
+
if (disposed) return;
|
|
63
|
+
const current = {
|
|
64
|
+
canUndo:!view.state.facet(EditorState.readOnly) && undoDepth(view.state) > 0,
|
|
65
|
+
canRedo:!view.state.facet(EditorState.readOnly) && redoDepth(view.state) > 0
|
|
66
|
+
};
|
|
67
|
+
if (lastHistory && current.canUndo === lastHistory.canUndo && current.canRedo === lastHistory.canRedo) return;
|
|
68
|
+
lastHistory = current;
|
|
69
|
+
host.pageContext.publish('historyChanged',current);
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
const extensions = [history(), theme, colors, drawSelection(), dropCursor(),
|
|
73
|
+
search({top:true}), keymap.of([{key:'Mod-s', preventDefault:true, run:() => {host.pageContext.publish('save', {value:host.readControlValue()}); return true;}},
|
|
74
|
+
indentWithTab, ...searchKeymap, ...defaultKeymap, ...historyKeymap]),
|
|
75
|
+
EditorView.updateListener.of(update => {
|
|
76
|
+
if (update.docChanged) host.editorChanged(update.state.doc.toString());
|
|
77
|
+
if (update.docChanged || update.transactions.some(transaction => transaction.reconfigured)) publishHistory();
|
|
78
|
+
})];
|
|
79
|
+
const state = doc => EditorState.create({doc, extensions:[options.of(configuration(host.parameters)), ...extensions]});
|
|
80
|
+
const view = new EditorView({state:state(host.readControlValue()), parent:host.control, root:host.shadowRoot});
|
|
81
|
+
return {view,
|
|
82
|
+
configure() {view.dispatch({effects:options.reconfigure(configuration(host.parameters))});},
|
|
83
|
+
replace(value) {view.setState(state(value)); publishHistory();},
|
|
84
|
+
publishHistory,
|
|
85
|
+
undo() {return !view.state.facet(EditorState.readOnly) && undo(view);},
|
|
86
|
+
redo() {return !view.state.facet(EditorState.readOnly) && redo(view);},
|
|
87
|
+
diagnostics(items) {view.dispatch(setDiagnostics(view.state, items));},
|
|
88
|
+
reveal(position) {view.dispatch({selection:{anchor:position}, effects:EditorView.scrollIntoView(position, {y:'center'})});},
|
|
89
|
+
destroy() {disposed = true; view.destroy();}
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import {controlElement} from './bases.js';
|
|
2
|
+
import {defineComponent} from './registry.js';
|
|
3
|
+
import {Labelbox} from './labelbox.js';
|
|
4
|
+
import {FieldState} from './field-state.js';
|
|
5
|
+
|
|
6
|
+
const languages = ['text', 'python', 'javascript', 'typescript', 'json', 'html', 'css', 'xml', 'markdown', 'sql', 'typst'];
|
|
7
|
+
let engineModule;
|
|
8
|
+
export function EditorControl(HTMLElement) {
|
|
9
|
+
return class extends controlElement(HTMLElement) {
|
|
10
|
+
#value = '';
|
|
11
|
+
#generation = 0;
|
|
12
|
+
constructor() {
|
|
13
|
+
super();
|
|
14
|
+
this.control = this.ownerDocument.createElement('div');
|
|
15
|
+
this.control.id = 'control'; this.control.className = 'editor-control';
|
|
16
|
+
this.controlBox.append(this.control);
|
|
17
|
+
const style = this.ownerDocument.createElement('style');
|
|
18
|
+
style.textContent = `:host{display:block;height:300px;min-height:0;min-width:0}
|
|
19
|
+
.control-box,.labelbox,.editor-control{height:100%;min-height:0;min-width:0}
|
|
20
|
+
.labelbox{grid-template-rows:auto minmax(0,1fr)}
|
|
21
|
+
.editor-control{border:1px solid var(--gramlot-border-control,GrayText);border-radius:var(--gramlot-radius-sm,4px);overflow:hidden}
|
|
22
|
+
:host([data-editor-disabled]) .editor-control{opacity:.6}
|
|
23
|
+
.editor-status{padding:1em;color:var(--gramlot-text-secondary,GrayText)}`;
|
|
24
|
+
this.shadowRoot.append(style);
|
|
25
|
+
// Engine transactions emit one normalized control event. Native contenteditable
|
|
26
|
+
// input events must not produce a second binding write.
|
|
27
|
+
for (const type of ['input','change']) this.control.addEventListener(type, event => {
|
|
28
|
+
if (event.target !== this.control) event.stopImmediatePropagation();
|
|
29
|
+
});
|
|
30
|
+
this.control.addEventListener('focusout', () => this.#emit('change'));
|
|
31
|
+
}
|
|
32
|
+
get liveWrites() { return true; }
|
|
33
|
+
connectedCallback() {
|
|
34
|
+
const generation = ++this.#generation;
|
|
35
|
+
this.control.textContent = 'Loading editor…';
|
|
36
|
+
this.ready = (engineModule ??= import('./code-mirror-engine.js')).then(module => {
|
|
37
|
+
if (generation !== this.#generation || !this.isConnected) return;
|
|
38
|
+
this.control.textContent = '';
|
|
39
|
+
this.editor = module.createEditor(this);
|
|
40
|
+
this.editor.publishHistory();
|
|
41
|
+
}).catch(error => {
|
|
42
|
+
if (generation !== this.#generation) return;
|
|
43
|
+
this.control.textContent = `CodeMirror could not start: ${error.message}`;
|
|
44
|
+
this.control.setAttribute('role','alert');
|
|
45
|
+
throw error;
|
|
46
|
+
});
|
|
47
|
+
// Keep the rejected ready promise inspectable without an unhandled rejection.
|
|
48
|
+
this.ready.catch(error => console.error(error));
|
|
49
|
+
}
|
|
50
|
+
releaseControl() { ++this.#generation; this.editor?.destroy(); this.editor = null; super.releaseControl(); }
|
|
51
|
+
projectAttributes(attrs) {
|
|
52
|
+
const rest = super.projectAttributes(attrs), p = this.parameters;
|
|
53
|
+
if (!languages.includes(p.language)) throw new TypeError(`Unsupported CodeMirror language: ${p.language}`);
|
|
54
|
+
if (!Number.isInteger(p.indentUnit) || p.indentUnit < 1 || p.indentUnit > 16) throw new TypeError('indentUnit must be an integer from 1 to 16');
|
|
55
|
+
if (!Number.isFinite(p.fontSize) || p.fontSize < 8 || p.fontSize > 48) throw new TypeError('fontSize must be from 8 to 48');
|
|
56
|
+
this.control.disabled = p.disabled; this.control.readOnly = p.readonly;
|
|
57
|
+
this.toggleAttribute('data-editor-disabled', p.disabled);
|
|
58
|
+
this.control.style.fontFamily = p.fontFamily; this.control.style.fontSize = `${p.fontSize}px`;
|
|
59
|
+
this.editor?.configure();
|
|
60
|
+
return rest;
|
|
61
|
+
}
|
|
62
|
+
#emit(type) {this.control.dispatchEvent(new this.ownerDocument.defaultView.Event(type, {bubbles:true}));}
|
|
63
|
+
editorChanged(value) {this.#value = value; this.#emit('input');}
|
|
64
|
+
readControlValue() {return this.#value;}
|
|
65
|
+
writeControlValue(value) {
|
|
66
|
+
if (typeof value !== 'string') throw new TypeError('CodeMirror value must be a string');
|
|
67
|
+
if (value === this.#value) return;
|
|
68
|
+
this.#value = value; this.editor?.replace(value);
|
|
69
|
+
}
|
|
70
|
+
focus() {if (!this.parameters.disabled) this.editor?.view.focus();}
|
|
71
|
+
setDiagnostics(items) {this.editor.diagnostics(items);}
|
|
72
|
+
revealPosition(position) {this.editor.reveal(position);}
|
|
73
|
+
undo() {return this.editor ? this.editor.undo() : false;}
|
|
74
|
+
redo() {return this.editor ? this.editor.redo() : false;}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
EditorControl.parameters = {
|
|
78
|
+
disabled:{dtype:'B', default:false, binding:'read'}, readonly:{dtype:'B', default:false, binding:'read'},
|
|
79
|
+
live:{dtype:'B', default:true, binding:'read'}
|
|
80
|
+
};
|
|
81
|
+
const toggle = {dtype:'B', default:true, binding:'read'};
|
|
82
|
+
export const CodeMirror = defineComponent({name:'codeMirror', tag:'gramlot-code-mirror', base:EditorControl, mixins:[Labelbox,FieldState],
|
|
83
|
+
parameters:{value:{dtype:'T', default:'', binding:'twoWay'}, language:{dtype:'T', default:'text', binding:'read', enum:languages},
|
|
84
|
+
lineNumbers:toggle, lineWrapping:toggle, indentUnit:{dtype:'L',default:4,binding:'read'},
|
|
85
|
+
fontSize:{dtype:'L',default:14,binding:'read'}, fontFamily:{dtype:'T',default:'monospace',binding:'read'},
|
|
86
|
+
folding:toggle, bracketMatching:toggle, autoCloseBrackets:toggle, autoIndent:toggle, autocompletion:toggle, highlightActiveLine:toggle, highlightSelectionMatches:toggle},
|
|
87
|
+
implementation:Base => class extends Base {}
|
|
88
|
+
});
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type {SourceBag, SourceBagNode} from '@genrojs/builders';
|
|
2
|
+
/** Reusable Source composition; relative value pointers resolve within datapath. */
|
|
3
|
+
export function codeMirrorWithOptions(parent: SourceBag | SourceBagNode, options: {
|
|
4
|
+
datapath: string;
|
|
5
|
+
value: string;
|
|
6
|
+
language?: string;
|
|
7
|
+
height?: string;
|
|
8
|
+
[attribute: string]: unknown;
|
|
9
|
+
}): SourceBagNode;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Source composition; settings belong to the caller's scoped Data. */
|
|
2
|
+
export function codeMirrorWithOptions(parent, {datapath, value, language = 'text', height = '420px', ...attributes}) {
|
|
3
|
+
if (!datapath) throw new TypeError('codeMirrorWithOptions requires datapath');
|
|
4
|
+
const pane = parent.borderContainer({datapath, height, class:'gramlot-editor-options'});
|
|
5
|
+
const defaults = {language, indentUnit:4, fontSize:14, fontFamily:'monospace', lineNumbers:true, lineWrapping:true,
|
|
6
|
+
folding:true, bracketMatching:true, autoCloseBrackets:true, autoIndent:true, autocompletion:true, highlightActiveLine:true, highlightSelectionMatches:true};
|
|
7
|
+
for (const [name, setting] of Object.entries(defaults)) pane.dataSetter({destination_path:`.settings.${name}`, value:setting});
|
|
8
|
+
const options = pane.contentPane({region:'right', width:'250px', drawer:'close', drawer_label:'Options', drawer_icon:'⚙', drawer_minimize:false,
|
|
9
|
+
padding:'12px', overflow:'auto', class:'gramlot-editor-settings'});
|
|
10
|
+
options.h3('Editor options');
|
|
11
|
+
options.filteringSelect({value:'^.settings.language', lbl:'Language', values:'text:Plain text,python:Python,javascript:JavaScript,typescript:TypeScript,json:JSON,html:HTML,css:CSS,xml:XML,markdown:Markdown,sql:SQL,typst:Typst'});
|
|
12
|
+
options.numberTextBox({value:'^.settings.indentUnit', lbl:'Indent spaces', min:1, max:16, dtype:'L', validate_notnull:true});
|
|
13
|
+
options.numberTextBox({value:'^.settings.fontSize', lbl:'Font size', min:8, max:48, dtype:'L', validate_notnull:true});
|
|
14
|
+
options.textbox({value:'^.settings.fontFamily', lbl:'Font family'});
|
|
15
|
+
const labels = {lineNumbers:'Line numbers', lineWrapping:'Wrap lines', folding:'Code folding', bracketMatching:'Match brackets', autoCloseBrackets:'Close brackets and quotes', autoIndent:'Automatic indentation',
|
|
16
|
+
autocompletion:'Local completion', highlightActiveLine:'Highlight current line', highlightSelectionMatches:'Highlight matching selections'};
|
|
17
|
+
for (const [name, label] of Object.entries(labels)) options.checkbox({value:`^.settings.${name}`, label, display:'block', margin_top:'8px'});
|
|
18
|
+
const center = pane.contentPane({region:'center', min_height:0});
|
|
19
|
+
center.codeMirror({...attributes, value, height:'100%', ...Object.fromEntries(Object.keys(defaults).map(name => [name, `^.settings.${name}`]))});
|
|
20
|
+
return pane;
|
|
21
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import {defineCollection} from './registry.js';
|
|
2
|
+
import {CodeMirror} from './code-mirror.js';
|
|
3
|
+
import {HtmlEditor} from './html-editor.js';
|
|
4
|
+
import {HtmlPreview,MarkdownPreview} from './html-preview.js';
|
|
5
|
+
import {MarkdownEditor} from './markdown-editor.js';
|
|
6
|
+
export {CodeMirror} from './code-mirror.js';
|
|
7
|
+
export {HtmlEditor} from './html-editor.js';
|
|
8
|
+
export {HtmlPreview,MarkdownPreview} from './html-preview.js';
|
|
9
|
+
export {MarkdownEditor} from './markdown-editor.js';
|
|
10
|
+
export default defineCollection({name:'editors', components:[CodeMirror,HtmlEditor,HtmlPreview,MarkdownEditor,MarkdownPreview]});
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** Preserve nonvisual document content while editing the body through Jodit. */
|
|
2
|
+
const protectedSelector = 'script,style,iframe,object,embed,template,svg,math,link,meta,base';
|
|
3
|
+
const unsafeAttribute = (element, name, value) => /^on/i.test(name) || ['autofocus','srcdoc'].includes(name) ||
|
|
4
|
+
(['href','src','action','formaction','xlink:href'].includes(name) && /^(?:javascript|vbscript|data):/i.test(value.trim()) &&
|
|
5
|
+
!(element.tagName === 'IMG' && name === 'src' && /^data:image\/(?:png|jpeg|gif|webp);base64,/i.test(value)));
|
|
6
|
+
|
|
7
|
+
export function prepareHtmlDocument(value, window) {
|
|
8
|
+
const parse = html => new window.DOMParser().parseFromString(html,'text/html');
|
|
9
|
+
const original = parse(value);
|
|
10
|
+
const full = /<(?:html|head|body)[\s>]|<!doctype/i.test(value) || original.head.children.length > 0;
|
|
11
|
+
const display = original.body.cloneNode(true);
|
|
12
|
+
const marker = `data-gramlot-${crypto.randomUUID()}`;
|
|
13
|
+
const nodes = new Map(), attributes = new Map();
|
|
14
|
+
let sequence = 0;
|
|
15
|
+
const comments = [], walker = original.createTreeWalker(display,128);
|
|
16
|
+
while (walker.nextNode()) comments.push(walker.currentNode);
|
|
17
|
+
for (const node of [...display.querySelectorAll(protectedSelector), ...comments]) {
|
|
18
|
+
if (!display.contains(node)) continue;
|
|
19
|
+
const id = String(++sequence), placeholder = original.createElement('span');
|
|
20
|
+
placeholder.setAttribute(marker,id); placeholder.setAttribute('contenteditable','false');
|
|
21
|
+
placeholder.textContent = `[${node.nodeName.toLowerCase()} — edit in Code]`;
|
|
22
|
+
nodes.set(id,node.cloneNode(true)); node.replaceWith(placeholder);
|
|
23
|
+
}
|
|
24
|
+
for (const element of display.querySelectorAll('*')) {
|
|
25
|
+
const removed = [...element.attributes].filter(attr => unsafeAttribute(element,attr.name,attr.value))
|
|
26
|
+
.map(attr => [attr.name,attr.value]);
|
|
27
|
+
if (!removed.length) continue;
|
|
28
|
+
for (const [name] of removed) element.removeAttribute(name);
|
|
29
|
+
const id = String(++sequence); element.setAttribute(`${marker}-attrs`,id); attributes.set(id,removed);
|
|
30
|
+
}
|
|
31
|
+
const unique = (body, attribute, id) => {
|
|
32
|
+
const matches = body.querySelectorAll(`[${attribute}="${id}"]`);
|
|
33
|
+
if (matches.length !== 1) throw new Error('Protected page content changed. Use Code to edit it.');
|
|
34
|
+
return matches[0];
|
|
35
|
+
};
|
|
36
|
+
return {
|
|
37
|
+
html:display.innerHTML,
|
|
38
|
+
styles:[...original.head.querySelectorAll('style')].map(node => node.textContent).join('\n'),
|
|
39
|
+
serialize(html) {
|
|
40
|
+
const edited = parse(html);
|
|
41
|
+
if (edited.body.querySelector(protectedSelector) || [...edited.body.querySelectorAll('*')].some(element =>
|
|
42
|
+
[...element.attributes].some(attr => unsafeAttribute(element,attr.name,attr.value)))) {
|
|
43
|
+
throw new Error('Active or embedded content must be edited in Code.');
|
|
44
|
+
}
|
|
45
|
+
for (const [id,node] of nodes) unique(edited.body,marker,id).replaceWith(node.cloneNode(true));
|
|
46
|
+
for (const [id,removed] of attributes) {
|
|
47
|
+
const element = unique(edited.body,`${marker}-attrs`,id);
|
|
48
|
+
for (const [name,value] of removed) element.setAttribute(name,value);
|
|
49
|
+
element.removeAttribute(`${marker}-attrs`);
|
|
50
|
+
}
|
|
51
|
+
const result = original.cloneNode(true);
|
|
52
|
+
result.body.innerHTML = edited.body.innerHTML;
|
|
53
|
+
return full ? (result.doctype ? new window.XMLSerializer().serializeToString(result.doctype)+'\n' : '') + result.documentElement.outerHTML : result.body.innerHTML;
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import {controlElement} from './bases.js';
|
|
2
|
+
import {defineComponent} from './registry.js';
|
|
3
|
+
import {Labelbox} from './labelbox.js';
|
|
4
|
+
import {FieldState} from './field-state.js';
|
|
5
|
+
|
|
6
|
+
let engineModule;
|
|
7
|
+
function HtmlControl(HTMLElement) {
|
|
8
|
+
return class extends controlElement(HTMLElement) {
|
|
9
|
+
#value='';
|
|
10
|
+
#generation=0;
|
|
11
|
+
constructor() {
|
|
12
|
+
super();
|
|
13
|
+
this.control=this.ownerDocument.createElement('div');
|
|
14
|
+
this.control.className='html-editor-control';
|
|
15
|
+
this.controlBox.append(this.control);
|
|
16
|
+
const style=this.ownerDocument.createElement('style');
|
|
17
|
+
style.textContent=':host{display:block;height:400px;min-height:0}.control-box,.labelbox,.html-editor-control{height:100%;min-height:0}.labelbox{grid-template-rows:auto minmax(0,1fr)}.html-editor-control{overflow:hidden}.html-editor-status{font:inherit;color:var(--gramlot-text-secondary,GrayText)}.html-editor-status:empty{display:none}';
|
|
18
|
+
this.shadowRoot.append(style);
|
|
19
|
+
for (const type of ['input','change']) this.control.addEventListener(type,event=>{
|
|
20
|
+
if (event.target!==this.control) event.stopImmediatePropagation();
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
get liveWrites() {return true;}
|
|
24
|
+
connectedCallback() {this.load();}
|
|
25
|
+
load() {
|
|
26
|
+
const generation=++this.#generation;
|
|
27
|
+
this.engine?.destroy();this.engine=null;
|
|
28
|
+
this.control.textContent='Loading HTML editor…';
|
|
29
|
+
this.ready=(engineModule ??= import('./jodit-engine.js')).then(module=>{
|
|
30
|
+
if (generation!==this.#generation || !this.isConnected) return;
|
|
31
|
+
this.control.textContent='';
|
|
32
|
+
this.engine=module.createHtmlEditor(this);
|
|
33
|
+
}).catch(error=>{
|
|
34
|
+
if (generation!==this.#generation) return;
|
|
35
|
+
this.control.textContent=`HTML editor could not start: ${error.message}`;
|
|
36
|
+
this.control.setAttribute('role','alert');
|
|
37
|
+
throw error;
|
|
38
|
+
});
|
|
39
|
+
this.ready.catch(error=>console.error(error));
|
|
40
|
+
}
|
|
41
|
+
projectAttributes(attrs) {
|
|
42
|
+
const rest=super.projectAttributes(attrs);
|
|
43
|
+
this.control.disabled=this.parameters.disabled;
|
|
44
|
+
this.control.readOnly=this.parameters.readonly;
|
|
45
|
+
this.engine?.configure();
|
|
46
|
+
return rest;
|
|
47
|
+
}
|
|
48
|
+
readControlValue() {return this.#value;}
|
|
49
|
+
writeControlValue(value) {
|
|
50
|
+
if (typeof value!=='string') throw new TypeError('HTML editor value must be a string');
|
|
51
|
+
if (value===this.#value) return;
|
|
52
|
+
this.#value=value;
|
|
53
|
+
if (this.isConnected && this.engine) this.load();
|
|
54
|
+
}
|
|
55
|
+
editorChanged(value) {
|
|
56
|
+
this.#value=value;
|
|
57
|
+
this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('input',{bubbles:true}));
|
|
58
|
+
}
|
|
59
|
+
editorBlurred() {this.control.dispatchEvent(new this.ownerDocument.defaultView.Event('change',{bubbles:true}));}
|
|
60
|
+
undo() {return this.engine ? this.engine.undo() : false;}
|
|
61
|
+
redo() {return this.engine ? this.engine.redo() : false;}
|
|
62
|
+
focus() {if (!this.parameters.disabled) this.engine?.focus();}
|
|
63
|
+
releaseControl() {++this.#generation;this.engine?.destroy();this.engine=null;super.releaseControl();}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
HtmlControl.parameters={disabled:{dtype:'B',default:false,binding:'read'},readonly:{dtype:'B',default:false,binding:'read'},live:{dtype:'B',default:true,binding:'read'}};
|
|
67
|
+
export const HtmlEditor=defineComponent({name:'htmlEditor',tag:'gramlot-html-editor',base:HtmlControl,mixins:[Labelbox,FieldState],
|
|
68
|
+
parameters:{value:{dtype:'T',default:'',binding:'twoWay'}},implementation:Base=>class extends Base {}});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import {defineComponent} from './registry.js';
|
|
2
|
+
import {projectParameters} from './parameters.js';
|
|
3
|
+
import {renderMarkdownDocument} from './markdown-document.js';
|
|
4
|
+
|
|
5
|
+
function PreviewElement(HTMLElement) {
|
|
6
|
+
return class extends HTMLElement {
|
|
7
|
+
constructor() {
|
|
8
|
+
super();
|
|
9
|
+
const root=this.attachShadow({mode:'open'});
|
|
10
|
+
const style=this.ownerDocument.createElement('style');
|
|
11
|
+
style.textContent=':host{display:block;height:100%;min-height:0}iframe{display:block;width:100%;height:100%;border:0;background:white}';
|
|
12
|
+
this.frame=this.ownerDocument.createElement('iframe');
|
|
13
|
+
this.frame.setAttribute('sandbox','');
|
|
14
|
+
this.frame.title='HTML preview';
|
|
15
|
+
root.append(style,this.frame);
|
|
16
|
+
}
|
|
17
|
+
renderDocument(value) {return value;}
|
|
18
|
+
projectAttributes(attrs) {
|
|
19
|
+
const rest=projectParameters(this,attrs);
|
|
20
|
+
const html=this.renderDocument(this.parameters.value);
|
|
21
|
+
if (this.frame.srcdoc !== html) this.frame.srcdoc=html;
|
|
22
|
+
return rest;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
export const HtmlPreview=defineComponent({name:'htmlPreview',tag:'gramlot-html-preview',base:PreviewElement,
|
|
27
|
+
parameters:{value:{dtype:'T',default:'',binding:'read'}},implementation:Base=>class extends Base {}});
|
|
28
|
+
|
|
29
|
+
export const MarkdownPreview=defineComponent({name:'markdownPreview',tag:'gramlot-markdown-preview',base:PreviewElement,
|
|
30
|
+
parameters:{value:{dtype:'T',default:'',binding:'read'},allowHtml:{dtype:'B',default:false,binding:'read'}},implementation:Base=>class extends Base {
|
|
31
|
+
constructor(){super();this.frame.title='Markdown preview';}
|
|
32
|
+
renderDocument(value){return renderMarkdownDocument(value,{allowHtml:this.parameters.allowHtml,document:this.ownerDocument});}
|
|
33
|
+
}});
|
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
|
+
}
|