272 lines
11 KiB
JavaScript
272 lines
11 KiB
JavaScript
// Chat message editor: one CodeMirror 6 view (vendored core, see scripts/vendor-chat-libs.mjs) that shows
|
|
// either raw source or the hybrid preview, like the official composer (main.js @3520977 createEditorState,
|
|
// @6389722 hybrid/raw switch through compartments with history, keymap and wrapping kept).
|
|
//
|
|
// createChatEditor(host) fills the empty `host` element and returns an adapter with the textarea-like
|
|
// surface the chat composer uses. The editable element is `.cm-content#chat-input`. Contract:
|
|
// - 'input' listeners live on the adapter (it is an EventTarget): fired once per microtask after USER edits
|
|
// (typing, IME commit, paste, cut, drop, undo/redo, Shift+Enter), never synchronously inside a
|
|
// CodeMirror update and never for programmatic value/setRangeText/reset (textarea semantics).
|
|
// - Every other event type is registered on the content element with the given options.
|
|
// - Plain Enter is not bound, so the chat's own keydown listener sends; Shift+Enter inserts a newline.
|
|
// - Settings (preview, disabled, placeholder, attributes) are no-ops when unchanged, keep the document,
|
|
// selection and undo history, and are deferred to a microtask if requested during an update.
|
|
// - Positions are UTF-16 offsets into the exact source text (line breaks normalised to \n, as a textarea).
|
|
import {
|
|
Annotation, Compartment, EditorSelection, EditorState, EditorView, history, historyKeymap, insertNewline,
|
|
keymap, placeholder as placeholderExtension, standardKeymap,
|
|
} from '../vendor/codemirror/codemirror.js';
|
|
import { chatPreview } from './chat-editor-preview.js';
|
|
|
|
const programmatic = Annotation.define();
|
|
|
|
const chatKeymap = [
|
|
{ key: 'Shift-Enter', run: insertNewline },
|
|
...standardKeymap.filter((binding) => binding.key !== 'Enter'),
|
|
...historyKeymap,
|
|
];
|
|
|
|
// Neutralises CodeMirror's default look (monospace, black caret, focus outline, padding) so the
|
|
// composer's stylesheet decides it; selection and caret stay native, as in a textarea.
|
|
const editorTheme = EditorView.theme({
|
|
'&': { color: 'inherit', backgroundColor: 'transparent' },
|
|
'&.cm-focused': { outline: 'none' },
|
|
'.cm-scroller': { fontFamily: 'inherit', lineHeight: 'inherit' },
|
|
'.cm-content': { padding: '0', caretColor: 'currentColor' },
|
|
'.cm-line': { padding: '0' },
|
|
});
|
|
|
|
const disabledExtension = [
|
|
EditorView.editable.of(false),
|
|
EditorState.readOnly.of(true),
|
|
EditorView.contentAttributes.of({ 'aria-disabled': 'true' }),
|
|
EditorView.editorAttributes.of({ class: 'tp-chat-editor-disabled' }),
|
|
];
|
|
|
|
// A dropped file would otherwise be read as text into the draft; files are attached explicitly instead.
|
|
const ignoreFileDrops = EditorView.domEventHandlers({
|
|
drop: (event) => Boolean(event.dataTransfer?.files?.length),
|
|
});
|
|
|
|
const normalize = (text) => String(text ?? '').replace(/\r\n?/g, '\n');
|
|
const clamp = (value, max) => Math.min(Math.max(0, Math.trunc(Number(value)) || 0), max);
|
|
|
|
class ChatEditor extends EventTarget {
|
|
#view;
|
|
#preview = new Compartment();
|
|
#disabled = new Compartment();
|
|
#placeholder = new Compartment();
|
|
#attributes = new Compartment();
|
|
#settings = { preview: true, disabled: false, placeholder: '', attributes: {} };
|
|
#inputQueued = false;
|
|
#destroyed = false;
|
|
|
|
constructor(host) {
|
|
super();
|
|
this.#view = new EditorView({ state: this.#createState('') });
|
|
host.replaceChildren(this.#view.dom);
|
|
}
|
|
|
|
#extensions() {
|
|
const { preview, disabled, placeholder, attributes } = this.#settings;
|
|
return [
|
|
this.#preview.of(preview ? chatPreview() : []),
|
|
this.#disabled.of(disabled ? disabledExtension : []),
|
|
this.#placeholder.of(placeholder ? placeholderExtension(placeholder) : []),
|
|
this.#attributes.of(EditorView.contentAttributes.of({ ...attributes })),
|
|
EditorView.contentAttributes.of({ id: 'chat-input', spellcheck: 'true' }),
|
|
history(),
|
|
keymap.of(chatKeymap),
|
|
EditorView.lineWrapping,
|
|
ignoreFileDrops,
|
|
editorTheme,
|
|
EditorView.updateListener.of((update) => {
|
|
if (update.transactions.some((tr) => tr.docChanged && !tr.annotation(programmatic))) this.#queueInput();
|
|
}),
|
|
];
|
|
}
|
|
|
|
#createState(text) {
|
|
const doc = normalize(text);
|
|
return EditorState.create({ doc, selection: EditorSelection.cursor(doc.length), extensions: this.#extensions() });
|
|
}
|
|
|
|
#queueInput() {
|
|
if (this.#inputQueued) return;
|
|
this.#inputQueued = true;
|
|
queueMicrotask(() => {
|
|
this.#inputQueued = false;
|
|
if (!this.#destroyed) this.dispatchEvent(new Event('input'));
|
|
});
|
|
}
|
|
|
|
/** Runs `fn` now, or right after the update in progress (CodeMirror forbids re-entrant updates). */
|
|
#whenIdle(fn) {
|
|
if (this.#destroyed) return;
|
|
if (this.#view.updateState === 0) fn();
|
|
else queueMicrotask(() => this.#whenIdle(fn));
|
|
}
|
|
|
|
#dispatch(spec) {
|
|
this.#whenIdle(() => this.#view.dispatch({ ...spec, annotations: programmatic.of(true) }));
|
|
}
|
|
|
|
#reconfigure(compartment, extension) {
|
|
this.#dispatch({ effects: compartment.reconfigure(extension) });
|
|
}
|
|
|
|
get dom() { return this.#view.dom; }
|
|
|
|
get contentDOM() { return this.#view.contentDOM; }
|
|
|
|
get value() { return this.#view.state.doc.toString(); }
|
|
|
|
/** Replaces the text as one undoable change (only the differing middle) and puts the caret at the end. */
|
|
set value(text) {
|
|
const next = normalize(text);
|
|
this.#whenIdle(() => {
|
|
const current = this.#view.state.doc.toString();
|
|
if (current === next) return;
|
|
let start = 0;
|
|
const limit = Math.min(current.length, next.length);
|
|
while (start < limit && current.charCodeAt(start) === next.charCodeAt(start)) start += 1;
|
|
let end = 0;
|
|
while (end < limit - start && current.charCodeAt(current.length - 1 - end) === next.charCodeAt(next.length - 1 - end)) end += 1;
|
|
this.#view.dispatch({
|
|
changes: { from: start, to: current.length - end, insert: next.slice(start, next.length - end) },
|
|
selection: EditorSelection.cursor(next.length),
|
|
scrollIntoView: this.#view.hasFocus,
|
|
annotations: programmatic.of(true),
|
|
});
|
|
});
|
|
}
|
|
|
|
get selectionStart() { return this.#view.state.selection.main.from; }
|
|
|
|
get selectionEnd() { return this.#view.state.selection.main.to; }
|
|
|
|
get selectionDirection() {
|
|
const { anchor, head } = this.#view.state.selection.main;
|
|
return head < anchor ? 'backward' : 'forward';
|
|
}
|
|
|
|
setSelectionRange(start, end, direction = 'none') {
|
|
this.#whenIdle(() => {
|
|
const length = this.#view.state.doc.length;
|
|
const to = clamp(end, length);
|
|
const from = Math.min(clamp(start, length), to);
|
|
const selection = direction === 'backward' ? EditorSelection.single(to, from) : EditorSelection.single(from, to);
|
|
this.#view.dispatch({ selection, scrollIntoView: this.#view.hasFocus, annotations: programmatic.of(true) });
|
|
});
|
|
}
|
|
|
|
/** HTMLTextAreaElement.setRangeText: replaces [start, end) (default: the selection). */
|
|
setRangeText(text, start, end, selectionMode = 'preserve') {
|
|
const insert = normalize(text);
|
|
this.#whenIdle(() => {
|
|
const { state } = this.#view;
|
|
const main = state.selection.main;
|
|
const length = state.doc.length;
|
|
const from = start === undefined ? main.from : clamp(start, length);
|
|
const to = end === undefined ? main.to : clamp(end, length);
|
|
if (from > to) throw new DOMException('The start offset is greater than the end offset.', 'IndexSizeError');
|
|
const newEnd = from + insert.length;
|
|
const delta = insert.length - (to - from);
|
|
let selection;
|
|
if (selectionMode === 'select') selection = EditorSelection.single(from, newEnd);
|
|
else if (selectionMode === 'start') selection = EditorSelection.cursor(from);
|
|
else if (selectionMode === 'end') selection = EditorSelection.cursor(newEnd);
|
|
else {
|
|
// Spec "preserve": ends after the range shift, ends inside it snap to its start / new end.
|
|
const selStart = main.from > to ? main.from + delta : main.from > from ? from : main.from;
|
|
const selEnd = main.to > to ? main.to + delta : main.to > from ? newEnd : main.to;
|
|
selection = main.head < main.anchor ? EditorSelection.single(selEnd, selStart) : EditorSelection.single(selStart, selEnd);
|
|
}
|
|
this.#view.dispatch({ changes: { from, to, insert }, selection, scrollIntoView: this.#view.hasFocus, annotations: programmatic.of(true) });
|
|
});
|
|
}
|
|
|
|
get disabled() { return this.#settings.disabled; }
|
|
|
|
set disabled(value) {
|
|
const disabled = Boolean(value);
|
|
if (disabled === this.#settings.disabled) return;
|
|
this.#settings.disabled = disabled;
|
|
this.#reconfigure(this.#disabled, disabled ? disabledExtension : []);
|
|
if (disabled && this.#view.hasFocus) this.#view.contentDOM.blur();
|
|
}
|
|
|
|
get placeholder() { return this.#settings.placeholder; }
|
|
|
|
set placeholder(value) {
|
|
const text = String(value ?? '');
|
|
if (text === this.#settings.placeholder) return;
|
|
this.#settings.placeholder = text;
|
|
this.#reconfigure(this.#placeholder, text ? placeholderExtension(text) : []);
|
|
}
|
|
|
|
get preview() { return this.#settings.preview; }
|
|
|
|
setPreview(enabled) {
|
|
const preview = Boolean(enabled);
|
|
if (preview === this.#settings.preview) return;
|
|
this.#settings.preview = preview;
|
|
this.#reconfigure(this.#preview, preview ? chatPreview() : []);
|
|
}
|
|
|
|
getAttribute(name) { return this.#view.contentDOM.getAttribute(name); }
|
|
|
|
hasAttribute(name) { return this.#view.contentDOM.hasAttribute(name); }
|
|
|
|
/** Content-element attributes go through CodeMirror, which would otherwise drop or overwrite them. */
|
|
setAttribute(name, value) {
|
|
const key = String(name).toLowerCase();
|
|
const text = String(value);
|
|
if (this.#settings.attributes[key] === text) return;
|
|
this.#settings.attributes = { ...this.#settings.attributes, [key]: text };
|
|
this.#reconfigure(this.#attributes, EditorView.contentAttributes.of({ ...this.#settings.attributes }));
|
|
}
|
|
|
|
removeAttribute(name) {
|
|
const key = String(name).toLowerCase();
|
|
if (!Object.hasOwn(this.#settings.attributes, key)) return;
|
|
const { [key]: _removed, ...rest } = this.#settings.attributes;
|
|
this.#settings.attributes = rest;
|
|
this.#reconfigure(this.#attributes, EditorView.contentAttributes.of({ ...rest }));
|
|
}
|
|
|
|
addEventListener(type, listener, options) {
|
|
if (type === 'input') super.addEventListener(type, listener, options);
|
|
else this.#view.contentDOM.addEventListener(type, listener, options);
|
|
}
|
|
|
|
removeEventListener(type, listener, options) {
|
|
if (type === 'input') super.removeEventListener(type, listener, options);
|
|
else this.#view.contentDOM.removeEventListener(type, listener, options);
|
|
}
|
|
|
|
focus() {
|
|
if (!this.#settings.disabled && !this.#destroyed) this.#view.focus();
|
|
}
|
|
|
|
/** New conversation: replaces the document and drops undo history and selection with it. */
|
|
reset(value = '') {
|
|
this.#whenIdle(() => this.#view.setState(this.#createState(value)));
|
|
}
|
|
|
|
resize() {
|
|
if (!this.#destroyed) this.#view.requestMeasure();
|
|
}
|
|
|
|
destroy() {
|
|
if (this.#destroyed) return;
|
|
this.#destroyed = true;
|
|
this.#view.destroy();
|
|
}
|
|
}
|
|
|
|
/** Creates the chat editor inside the empty `host` element (`#chat-editor`). */
|
|
export function createChatEditor(host) {
|
|
return new ChatEditor(host);
|
|
}
|