Files
client/app/renderer/js/chat-composer.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

171 lines
11 KiB
JavaScript

// Account-free TS6 formatting snippets (installed editor module, ts6spec-chat.md).
import EMOJI from '../vendor/emoji/shortcodes.js';
import { t, onLanguageChange } from './i18n.js';
import { $, h, icon } from './dom.js';
// Each tuple is prefix, suffix, group, and optional line-prefix mode.
export const SNIPPETS = {
bold: ['**', '**'], italic: ['*', '*'], strike: ['~~', '~~'], underline: ['++', '++'],
link: ['[', '](https://)'], quote: ['> ', '', null, true], codeblock: ['```\n', '\n```'],
h1: ['# ', '', 'heading'], h2: ['## ', '', 'heading'], h3: ['### ', '', 'heading'],
h4: ['#### ', '', 'heading'], h5: ['##### ', '', 'heading'], h6: ['###### ', '', 'heading'], setext: ['', '\n---', 'heading'],
ul: ['- ', '', 'lists', true], ol: ['1. ', '', 'lists', true], task: ['- [ ] ', '', 'lists', true],
spoiler: ['||', '||', 'spoiler'], details: [':::details Summary\n', '\n:::', 'spoiler'],
highlight: ['==', '==', 'others'], sup: ['^', '^', 'others'], sub: ['~', '~', 'others'],
code: ['`', '`', 'others'], math: ['$', '$', 'others'], mathblock: ['$$\n', '\n$$', 'others'],
mermaid: ['```mermaid\n', '\n```', 'others'], indentcode: [' ', '', 'others', true],
table: ['| Column A | Column B |\n| --- | --- |\n| ', ' | |', 'others'], hr: ['---\n', '', 'others'],
left: [':::left\n', '\n:::', 'others'], center: [':::center\n', '\n:::', 'others'],
right: [':::right\n', '\n:::', 'others'], justify: [':::justify\n', '\n:::', 'others'],
fn: ['[^', ']', 'others'], fndef: ['[^id]: ', '', 'others'], reflink: ['[', '][id]', 'others'],
linkdef: ['[id]: https://example.com "Title"\n', '', 'others'], autolink: ['<', '>'],
image: ['![', '](https://example.com/image.png)'], 'image-size': ['![', '](image.png | width=300)'],
callout: ['> [!NOTE]\n> ', ''], escape: ['\\', ''], entity: ['&', ';'], url: ['https://', ''],
};
/** The text change for snippet `id` over [start, end): `insert` replaces [from, to), then [start, end) is selected. */
export function formatSelection(value, start, end, id) {
const snippet = SNIPPETS[id]; if (!snippet) return null;
const [prefix, suffix, , lines] = snippet;
const selected = value.slice(start, end);
if (selected && !lines && value.slice(Math.max(0, start - prefix.length), start) === prefix && value.slice(end, end + suffix.length) === suffix) {
return { from: start - prefix.length, to: end + suffix.length, insert: selected, start: start - prefix.length, end: end - prefix.length };
}
const text = lines ? selected.split('\n').map((line, i) => `${id === 'ol' ? `${i + 1}. ` : prefix}${line}`).join('\n') : prefix + selected + suffix;
return { from: start, to: end, insert: text, start: start + prefix.length, end: start + text.length - suffix.length };
}
/** `editor` is the chat-editor.js adapter; every edit is a text transaction on its single CodeMirror view. */
export function initChatComposer({ editor, onChange, attach }) {
const bar = $('#chat-format-bar');
let menu = null;
let completion = null;
const close = () => {
menu?.remove(); menu = null; completion = null;
for (const button of bar.querySelectorAll('[aria-expanded]')) button.setAttribute('aria-expanded', 'false');
editor.removeAttribute('aria-controls'); editor.removeAttribute('aria-activedescendant');
$('#chat-emoji')?.setAttribute('aria-expanded', 'false');
};
const edit = (change) => {
editor.setRangeText(change.insert, change.from, change.to, 'preserve');
editor.setSelectionRange(change.start, change.end); close(); onChange(); editor.focus();
};
const apply = (id) => {
if (editor.disabled) return;
const change = formatSelection(editor.value, editor.selectionStart, editor.selectionEnd, id);
if (change) edit(change);
};
// A slash command replaces its typed "/name" token with the snippet; the caret lands inside the snippet.
const applySlash = (id, range) => {
if (editor.disabled) return;
const value = editor.value;
const change = formatSelection(value.slice(0, range.start) + value.slice(range.end), range.start, range.start, id);
if (change) edit({ ...change, from: range.start, to: range.end });
};
const more = $('#chat-format-more');
const tools = [...bar.querySelectorAll('button[data-format], button[data-format-group]')];
// Source recomputeInputToolbarLayout: tools that do not fit collapse, in order, behind "More".
const layout = () => {
for (const tool of tools) tool.hidden = false;
more.hidden = false;
const style = getComputedStyle(bar);
const gap = parseFloat(style.columnGap) || 0;
const room = Math.max(0, bar.clientWidth - (parseFloat(style.paddingLeft) || 0) - (parseFloat(style.paddingRight) || 0));
const widths = tools.map((tool) => tool.getBoundingClientRect().width);
const total = widths.reduce((sum, width) => sum + width, 0) + gap * (tools.length - 1);
if (!room || total <= room) { more.hidden = true; return; }
const limit = Math.max(0, room - more.getBoundingClientRect().width);
let used = 0; let shown = 0;
tools.forEach((tool, i) => {
const end = shown ? used + gap + widths[i] : widths[i];
if (shown && end + (tools.length - (shown + 1) > 0 ? gap : 0) > limit) { tool.hidden = true; return; }
shown += 1; used = end;
});
};
const showMenu = (toggle, entries) => {
close(); toggle.setAttribute('aria-expanded', 'true');
menu = h('div', { class: 'composer-tool-menu', role: 'menu' });
for (const { label, glyph, accessory, run } of entries) {
const item = h('button', { class: 'composer-tool-menu-item', role: 'menuitem', type: 'button' }, glyph, h('span', { text: label }), accessory ? icon('chevron-right', 'composer-tool-menu-accessory') : null);
item.addEventListener('click', run); menu.append(item);
}
bar.after(menu); menu.querySelector('button')?.focus();
};
const groupEntries = (group) => Object.entries(SNIPPETS).filter(([, snippet]) => snippet[2] === group)
.map(([id]) => ({ label: t(`chat.snippet.${id}`), run: () => apply(id) }));
const glyphOf = (tool) => tool.querySelector('.icon:not(.composer-tool-expander)')?.cloneNode(true) ?? null;
const overflowEntries = () => tools.filter((tool) => tool.hidden).flatMap((tool) => {
const group = tool.dataset.formatGroup;
if (group === 'others') return groupEntries(group);
const label = tool.getAttribute('aria-label');
if (group) return [{ label, glyph: glyphOf(tool), accessory: true, run: () => showMenu(more, groupEntries(group)) }];
return [{ label, glyph: glyphOf(tool), run: () => apply(tool.dataset.format) }];
});
bar.hidden = false;
new ResizeObserver(layout).observe(bar);
onLanguageChange(layout);
bar.addEventListener('mousedown', (e) => e.preventDefault());
bar.addEventListener('click', (e) => {
const button = e.target.closest('button'); if (!button || button.disabled) return;
if (button === more) return showMenu(more, overflowEntries());
if (button.dataset.format) return apply(button.dataset.format);
if (button.dataset.formatGroup) showMenu(button, groupEntries(button.dataset.formatGroup));
});
// Slash commands insert formatting snippets, never execute native commands or fake Matrix actions.
editor.addEventListener('input', () => {
close();
const before = editor.value.slice(0, editor.selectionStart);
const match = /(?:^|\n)\/([a-z0-9-]*)$/i.exec(before);
if (!match) return;
const ids = Object.keys(SNIPPETS).filter((id) => id.startsWith(match[1])).slice(0, 12);
if (!ids.length) return;
const range = { start: editor.selectionStart - match[1].length - 1, end: editor.selectionStart };
menu = h('div', { class: 'ts-autocomplete-list', role: 'listbox', id: 'chat-slash-completion' });
completion = { ids, range, index: 0 };
ids.forEach((id, i) => {
const button = h('button', { type: 'button', role: 'option', id: `chat-slash-${i}`, 'aria-selected': String(i === 0), text: `/${id} — ${t(`chat.snippet.${id}`)}` });
button.addEventListener('mousedown', (e) => e.preventDefault());
button.addEventListener('click', () => applySlash(id, range)); menu.append(button);
});
bar.before(menu); editor.setAttribute('aria-controls', menu.id); editor.setAttribute('aria-activedescendant', 'chat-slash-0');
});
// Capture phase on the editor's own content element: runs before CodeMirror's keymap and the send listener.
editor.addEventListener('keydown', (e) => {
if (e.key === 'Escape') { close(); return; }
if (!completion || e.isComposing) return;
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
e.preventDefault(); e.stopImmediatePropagation();
completion.index = (completion.index + (e.key === 'ArrowDown' ? 1 : completion.ids.length - 1)) % completion.ids.length;
[...menu.children].forEach((node, i) => node.setAttribute('aria-selected', String(i === completion.index)));
editor.setAttribute('aria-activedescendant', `chat-slash-${completion.index}`);
} else if (e.key === 'Enter' || e.key === 'Tab') {
e.preventDefault(); e.stopImmediatePropagation(); applySlash(completion.ids[completion.index], completion.range);
}
}, true);
$('#chat-attach')?.addEventListener('click', attach);
$('#chat-emoji')?.addEventListener('click', () => {
if (menu?.classList.contains('chat-emoji-picker')) { close(); return; }
close();
const range = { start: editor.selectionStart, end: editor.selectionEnd };
const search = h('input', { type: 'search', 'aria-label': t('chat.emoji.search'), placeholder: t('chat.emoji.search') });
const list = h('div', { class: 'ts-autocomplete-list' });
menu = h('div', { class: 'chat-emoji-picker' }, search, list);
const draw = () => {
const query = search.value.toLowerCase(); list.replaceChildren(); let count = 0;
for (const [name, unicode] of Object.entries(EMOJI)) {
if (!name.includes(query)) continue;
const button = h('button', { type: 'button', text: unicode, title: `:${name}:`, 'aria-label': name });
button.addEventListener('click', () => {
if (editor.disabled) return;
editor.setRangeText(`:${name}:`, range.start, range.end, 'end'); close(); onChange(); editor.focus();
});
list.append(button); if (++count === 80) break;
}
};
search.addEventListener('input', draw); bar.before(menu); draw(); search.focus(); $('#chat-emoji').setAttribute('aria-expanded', 'true');
});
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && menu) { close(); editor.focus(); } });
document.addEventListener('pointerdown', (e) => { if (menu && !menu.contains(e.target) && !e.target.closest('#chat-format-bar, #chat-emoji')) close(); });
return close;
}