Files
client/app/renderer/js/chat-editor-preview.js
T
omar f618d8bce9
ci / linux-arm64-cross (push) Successful in 3m22s
ci / linux-x64 (push) Successful in 3m32s
chat: add safe hybrid Markdown editing with strict CSP
2026-11-02 11:32:31 +03:00

191 lines
7.9 KiB
JavaScript

// Hybrid (rich-text) preview for the chat editor, the account-free counterpart of the official
// `hybridMarkdown({ enablePreview: useRichTextEditing })` CodeMirror extension (main.js @3520977).
// The document is parsed with the same dialect parser as sent messages (markdown/parse.js) and every
// top-level block the selection does not touch is replaced by its message rendering (markdown/render.js);
// the block holding the cursor or any selected text stays raw source. The source text is never rewritten:
// widgets are display-only, so typing, IME, undo and the clipboard always operate on the exact raw text.
// Rendered previews never navigate, load server images or run actions: links lose their href, server
// image buttons are disabled, spoilers are shown revealed and nothing in a widget is focusable.
import { Decoration, EditorSelection, EditorView, StateField, WidgetType, keymap } from '../vendor/codemirror/codemirror.js';
import { parseMarkdown } from './markdown/parse.js';
import { renderMarkdownBlock, renderMarkdownFootnotes } from './markdown/render.js';
// Chat messages are limited to 8 KiB of UTF-8, so a longer draft is never sent as-is; past this many
// UTF-16 units the editor stays raw instead of re-parsing on every keystroke.
export const PREVIEW_MAX_LENGTH = 16384;
const skipLines = (key, value) => (key === 'lines' ? undefined : value);
/**
* Top-level source blocks of `text` as `{ from, to, kind, node, key }` with 0-based document line indexes
* (`to` exclusive), in document order. `key` identifies the rendering, independent of where the block is.
* Lines outside every block (blank lines, link reference definitions) are not listed.
*/
export function previewBlocks(text) {
if (text.length > PREVIEW_MAX_LENGTH) return [];
const doc = parseMarkdown(text);
if (doc.tooComplex) return [];
const blocks = [];
const add = (kind, node) => {
const [from, to] = node.lines;
if (to > from) blocks.push({ from, to, kind, node, key: `${kind}:${to - from}:${JSON.stringify(node, skipLines)}` });
};
for (const node of doc.children) if (node.lines) add('block', node);
for (const note of doc.footnotes) if (note.lines) add('footnote', note);
return blocks.sort((a, b) => a.from - b.from);
}
/** Removes every navigation, network and focus affordance from a rendered message fragment. */
function inert(root) {
for (const a of root.querySelectorAll('a')) {
a.removeAttribute('href');
delete a.dataset.href;
}
for (const spoiler of root.querySelectorAll('.md-spoiler')) {
spoiler.removeAttribute('tabindex');
spoiler.removeAttribute('role');
spoiler.removeAttribute('aria-expanded');
spoiler.classList.add('revealed');
}
for (const button of root.querySelectorAll('.md-ts3image-load')) button.disabled = true;
for (const node of root.querySelectorAll('summary, [tabindex]')) node.tabIndex = -1;
}
class BlockWidget extends WidgetType {
constructor(block) {
super();
this.block = block;
}
eq(other) {
return other.block.key === this.block.key;
}
toDOM(view) {
const wrap = document.createElement('div');
wrap.className = 'tp-chat-editor-block ts-parsed-text-content';
const { kind, node } = this.block;
const rendered = kind === 'footnote' ? renderMarkdownFootnotes([node]) : renderMarkdownBlock(node);
if (rendered) wrap.append(rendered);
inert(wrap);
const lineCount = this.block.to - this.block.from;
wrap.addEventListener('mousedown', (event) => {
// Diagram load/retry buttons render locally in the sandboxed frame; everything else edits.
if (event.button !== 0 || event.target.closest?.('button:not(:disabled)')) return;
event.preventDefault();
if (view.state.readOnly) return;
const rect = wrap.getBoundingClientRect();
const row = rect.height > 0 ? Math.floor(((event.clientY - rect.top) / rect.height) * lineCount) : 0;
const first = view.state.doc.lineAt(view.posAtDOM(wrap)).number;
const line = view.state.doc.line(Math.min(view.state.doc.lines, first + Math.max(0, Math.min(lineCount - 1, row))));
view.dispatch({ selection: EditorSelection.cursor(line.to), scrollIntoView: true, userEvent: 'select.pointer' });
view.focus();
});
// Math and diagrams finish asynchronously; keep CodeMirror's height map in step with them.
const observer = new ResizeObserver(() => view.requestMeasure());
observer.observe(wrap);
wrap.tpObserver = observer;
return wrap;
}
destroy(dom) {
dom.tpObserver?.disconnect();
}
ignoreEvent() {
return true;
}
}
const blocksField = StateField.define({
create: (state) => previewBlocks(state.doc.toString()),
update: (blocks, tr) => (tr.docChanged ? previewBlocks(tr.state.doc.toString()) : blocks),
});
const definitionLine = Decoration.line({ class: 'tp-chat-editor-definition' });
function decorate(state) {
const { doc, selection } = state;
const blocks = state.field(blocksField);
const ranges = [];
let next = 0;
for (const block of blocks) {
// Non-blank lines between blocks are source the message does not show (reference definitions).
for (let i = next; i < block.from; i += 1) {
const line = doc.line(i + 1);
if (line.text.trim()) ranges.push(definitionLine.range(line.from));
}
next = block.to;
const from = doc.line(block.from + 1).from;
const to = doc.line(Math.min(block.to, doc.lines)).to;
if (selection.ranges.some((r) => r.from <= to && r.to >= from)) continue;
ranges.push(Decoration.replace({ widget: new BlockWidget(block), block: true }).range(from, to));
}
for (let i = next; i < doc.lines; i += 1) {
const line = doc.line(i + 1);
if (line.text.trim()) ranges.push(definitionLine.range(line.from));
}
return Decoration.set(ranges, true);
}
const decorationsField = StateField.define({
create: decorate,
update: (decorations, tr) => (tr.docChanged || tr.selection ? decorate(tr.state) : decorations),
provide: (field) => EditorView.decorations.from(field),
});
function rendered(state, pos) {
let found = false;
state.field(decorationsField).between(pos, pos, (from, to, value) => {
if (value.spec.widget) found = true;
return !found;
});
return found;
}
/**
* Up/Down into a rendered block lands on the adjacent source line (same column) so the block opens for
* editing there; CodeMirror's own vertical motion would treat the whole widget as one line.
*/
function vertical(forward, extend) {
return (view) => {
const { state } = view;
const range = state.selection.main;
const line = state.doc.lineAt(range.head);
const target = line.number + (forward ? 1 : -1);
if (target < 1 || target > state.doc.lines) return false;
// Inside a wrapped line the normal visual motion applies.
if (state.doc.lineAt(view.moveVertically(range, forward).head).number === line.number) return false;
const next = state.doc.line(target);
if (!rendered(state, next.from)) return false;
const head = next.from + Math.min(range.head - line.from, next.length);
view.dispatch({
selection: extend ? EditorSelection.range(range.anchor, head) : EditorSelection.cursor(head),
scrollIntoView: true,
userEvent: 'select',
});
return true;
};
}
const previewKeymap = keymap.of([
{ key: 'ArrowDown', run: vertical(true, false), shift: vertical(true, true) },
{ key: 'ArrowUp', run: vertical(false, false), shift: vertical(false, true) },
]);
const previewTheme = EditorView.baseTheme({
// flow-root keeps rendered margins inside the widget, so CodeMirror measures the height it shows.
'.tp-chat-editor-block': { display: 'flow-root', whiteSpace: 'normal', cursor: 'text', userSelect: 'none' },
});
/** The hybrid preview extension; absent, the same editor shows raw source only. */
export function chatPreview() {
return [
blocksField,
decorationsField,
previewKeymap,
previewTheme,
EditorView.editorAttributes.of({ class: 'tp-chat-editor-hybrid' }),
];
}