From f618d8bce92c0f4c96679426758956934606e5a5 Mon Sep 17 00:00:00 2001 From: omar Date: Mon, 2 Nov 2026 11:32:31 +0300 Subject: [PATCH] chat: add safe hybrid Markdown editing with strict CSP --- CHANGELOG.md | 5 + FEATURE_COMPATIBILITY.md | 1 + app/main/chat-prefs.js | 12 +- app/renderer/index.html | 4 +- app/renderer/js/app.js | 2 +- app/renderer/js/chat-composer.js | 58 +- app/renderer/js/chat-editor-preview.js | 190 + app/renderer/js/chat-editor.js | 271 + app/renderer/js/chat-settings.js | 6 +- app/renderer/js/chat.js | 51 +- app/renderer/js/markdown/parse.js | 316 +- app/renderer/js/markdown/render.js | 15 + app/renderer/shared/en.js | 3 + app/renderer/shared/ru.js | 3 + app/renderer/styles/app.css | 18 +- app/renderer/styles/chat-editor.css | 34 + app/renderer/vendor/DEPENDENCIES.json | 96 + app/renderer/vendor/PROVENANCE.json | 133 + app/renderer/vendor/THIRD_PARTY_NOTICES.txt | 308 +- app/renderer/vendor/codemirror/codemirror.js | 16127 ++++++++++++++++ .../licenses/@codemirror__commands.LICENSE | 21 + .../licenses/@codemirror__language.LICENSE | 21 + .../licenses/@codemirror__state.LICENSE | 21 + .../licenses/@codemirror__view.LICENSE | 21 + .../licenses/@lezer__common.LICENSE | 21 + .../licenses/@lezer__highlight.LICENSE | 21 + .../@marijn__find-cluster-break.LICENSE | 21 + .../codemirror/licenses/style-mod.LICENSE | 19 + .../codemirror/licenses/w3c-keyname.LICENSE | 19 + app/renderer/vendor/codemirror/package.json | 3 + .../official-parity/qa-parity-harness.md | 24 + docs/evidence/official-parity/ts6spec-chat.md | 2 +- .../official-parity/visual-source-map.md | 2 +- scripts/smoke-chat-editor-offscreen.mjs | 306 + scripts/smoke-chat-offscreen.mjs | 4 +- scripts/smoke-i18n.mjs | 2 +- scripts/smoke-stream-view.mjs | 2 +- scripts/smoke-tree-layout.mjs | 3 +- scripts/smoke-ui-shell.mjs | 3 +- scripts/vendor-chat-libs.mjs | 77 +- scripts/vendor-chat-notices.mjs | 4 +- test/chat-editor-preview.test.mjs | 41 + test/chat-prefs.test.js | 9 +- 43 files changed, 18079 insertions(+), 241 deletions(-) create mode 100644 app/renderer/js/chat-editor-preview.js create mode 100644 app/renderer/js/chat-editor.js create mode 100644 app/renderer/styles/chat-editor.css create mode 100644 app/renderer/vendor/codemirror/codemirror.js create mode 100644 app/renderer/vendor/codemirror/licenses/@codemirror__commands.LICENSE create mode 100644 app/renderer/vendor/codemirror/licenses/@codemirror__language.LICENSE create mode 100644 app/renderer/vendor/codemirror/licenses/@codemirror__state.LICENSE create mode 100644 app/renderer/vendor/codemirror/licenses/@codemirror__view.LICENSE create mode 100644 app/renderer/vendor/codemirror/licenses/@lezer__common.LICENSE create mode 100644 app/renderer/vendor/codemirror/licenses/@lezer__highlight.LICENSE create mode 100644 app/renderer/vendor/codemirror/licenses/@marijn__find-cluster-break.LICENSE create mode 100644 app/renderer/vendor/codemirror/licenses/style-mod.LICENSE create mode 100644 app/renderer/vendor/codemirror/licenses/w3c-keyname.LICENSE create mode 100644 app/renderer/vendor/codemirror/package.json create mode 100644 scripts/smoke-chat-editor-offscreen.mjs create mode 100644 test/chat-editor-preview.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b69e76..e48f90b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ to the installed reference. Corrected narrow chat width and input placeholder spacing. All eight main-screen EN/RU, dark/light and wide/narrow fixture comparisons passed; this does not establish whole-client parity or native-platform interoperability. +- Replaced the plain chat textarea with one local CodeMirror editor and the persisted Rich Text Editor + toggle. Hybrid preview uses the existing safe TS Markdown renderer; switching modes retains text, + selection and undo, while switching conversations isolates draft history. Toolbar/slash/emoji edits, + Enter/Shift+Enter, IME and refused-send preservation were exercised in the packaged offscreen app. + Constructed stylesheets keep the application CSP strict; no inline-style exception was added. ## 0.1.6 — 2026-11-02 diff --git a/FEATURE_COMPATIBILITY.md b/FEATURE_COMPATIBILITY.md index aa4b6b9..3b3cc7a 100644 --- a/FEATURE_COMPATIBILITY.md +++ b/FEATURE_COMPATIBILITY.md @@ -17,6 +17,7 @@ the exact build hashes and limits are in `docs/evidence/official-parity/qa-parit | Server icons and snapshot transfer ownership | Main/renderer consumer tests cover session grants, reconnect, partial failure and recycled transfer IDs | No successful live server icon mutation is claimed | | Local contacts and public badges | Model/prefs/catalog tests and actual contact add/alias/restart passed; offline state is retained honestly | Not cloud contacts, badge ownership/redeeming or global presence | | Rich chat | Actual history IPC/restart, scope isolation and local KaTeX/Mermaid hydration passed | Synthetic messages, no server traffic; sandbox permissions tested separately | +| Rich-text composer (post-release development) | Real packaged typing, formatting, emoji/slash completion, raw/hybrid settings, selection/undo, conversation isolation, refused sends and IME passed; hostile preview stayed inert with zero network requests | Windows hidden runtime only; the separate v0.1.6 release does not include this post-cut feature | | Identity related bookmarks | Actual nested/default assignment display and nickname-clearing restart passed without changing UID | The original identity component exposes ordinary nickname, not a separate editable phonetic field | | Whisper manager and history | Actual hidden UI with synthetic events passed overlay switching, preview, session/recycled-ID cleanup and received-history handling | No live whisper delivery proof; two microphone attempts were refused by the test stub | | Changelog and licenses | Actual packaged list/detail navigation and focus restoration passed after fixing stringified DOM arrays | Displays this installation's documents, not TeamSpeak service terms | diff --git a/app/main/chat-prefs.js b/app/main/chat-prefs.js index 5cf97e6..585c325 100644 --- a/app/main/chat-prefs.js +++ b/app/main/chat-prefs.js @@ -5,6 +5,7 @@ * near offset 4873300; defaults from workflowSettings class `Xe` and appearanceSettings class `qe`). * * Official key → TeamsPeach key default + * workflowSettings.useRichTextEditor → chatRichTextEditor true * appearanceSettings.chat_input_toolbar_visibility → chatToolbarVisibility 'always-visible' * appearanceSettings.chat_mermaid_autoload_mode → chatMermaidAutoload 'only-simple' * workflowSettings.openIncomingChats → chatOpenIncoming true @@ -13,10 +14,12 @@ * workflowSettings.autoDownloadImages → autoDownloadImages false * chat-server ignore list (per myTeamSpeak chat connection) → chatIgnoredUsers [] (local, keyed by client UID) * - * Not modelled because TeamsPeach has no backing feature: useRichTextEditor (the composer is a plain - * textarea), autoAcceptIncomingDirectChats (TS6-server decentral chat invitations), useChatsHistory and - * sort_contacts_alphabetically / show_offline_contacts / group_offline_contacts (myTeamSpeak contacts and - * group chats). + * chatRichTextEditor switches the one composer editor between hybrid Markdown preview and raw source + * (main.js@1298380 default true, @3520977 hybridMarkdown enablePreview:useRichTextEditing). + * + * Not modelled because TeamsPeach has no backing feature: autoAcceptIncomingDirectChats (TS6-server + * decentral chat invitations), useChatsHistory and sort_contacts_alphabetically / show_offline_contacts / + * group_offline_contacts (myTeamSpeak contacts and group chats). */ const MAX_IGNORED_USERS = 1000; @@ -48,6 +51,7 @@ function validIgnoredUsers(list) { } const CHAT_SCHEMA = { + chatRichTextEditor: { default: true, check: isBool }, chatToolbarVisibility: { default: 'always-visible', check: (v) => v === 'inactive' || v === 'dynamic' || v === 'always-visible' }, chatMermaidAutoload: { default: 'only-simple', check: (v) => v === 'never' || v === 'only-simple' }, chatOpenIncoming: { default: true, check: isBool }, diff --git a/app/renderer/index.html b/app/renderer/index.html index 70c9796..d65994c 100644 --- a/app/renderer/index.html +++ b/app/renderer/index.html @@ -15,6 +15,7 @@ + @@ -492,7 +493,8 @@
- + +
diff --git a/app/renderer/js/app.js b/app/renderer/js/app.js index 3d0db32..6ab7026 100644 --- a/app/renderer/js/app.js +++ b/app/renderer/js/app.js @@ -927,7 +927,7 @@ async function closeSettings() { S.view = 'main'; renderConnection(); chat.onViewChanged(); - (isConnected() ? $('#chat-input') : $('#connect-address')).focus(); + (isConnected() ? chat.composerEditor() : $('#connect-address')).focus(); } // ---------- diagnostics for automated smoke runs (read-only) ---------- diff --git a/app/renderer/js/chat-composer.js b/app/renderer/js/chat-composer.js index d3ce081..05d1fe0 100644 --- a/app/renderer/js/chat-composer.js +++ b/app/renderer/js/chat-composer.js @@ -23,33 +23,44 @@ export const SNIPPETS = { 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 { value: value.slice(0, start - prefix.length) + selected + value.slice(end + suffix.length), start: start - prefix.length, end: end - prefix.length }; + 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 { value: value.slice(0, start) + text + value.slice(end), start: start + prefix.length, end: start + text.length - suffix.length }; + return { from: start, to: end, insert: text, start: start + prefix.length, end: start + text.length - suffix.length }; } -export function initChatComposer({ onChange, attach }) { - const input = $('#chat-input'); +/** `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'); - input.removeAttribute('aria-controls'); input.removeAttribute('aria-activedescendant'); + editor.removeAttribute('aria-controls'); editor.removeAttribute('aria-activedescendant'); $('#chat-emoji')?.setAttribute('aria-expanded', 'false'); }; - const apply = (id, range) => { - if (input.disabled) return; - const result = formatSelection(input.value, range?.start ?? input.selectionStart, range?.end ?? input.selectionEnd, id); - if (!result) return; - input.value = result.value; input.setSelectionRange(result.start, result.end); close(); onChange(); input.focus(); + 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]')]; @@ -101,40 +112,41 @@ export function initChatComposer({ onChange, attach }) { if (button.dataset.formatGroup) showMenu(button, groupEntries(button.dataset.formatGroup)); }); // Slash commands insert formatting snippets, never execute native commands or fake Matrix actions. - input.addEventListener('input', () => { + editor.addEventListener('input', () => { close(); - const before = input.value.slice(0, input.selectionStart); + 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: input.selectionStart - match[1].length - 1, end: input.selectionStart }; + 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', () => apply(id, range)); menu.append(button); + button.addEventListener('click', () => applySlash(id, range)); menu.append(button); }); - bar.before(menu); input.setAttribute('aria-controls', menu.id); input.setAttribute('aria-activedescendant', 'chat-slash-0'); + bar.before(menu); editor.setAttribute('aria-controls', menu.id); editor.setAttribute('aria-activedescendant', 'chat-slash-0'); }); - input.addEventListener('keydown', (e) => { + // 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.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))); - input.setAttribute('aria-activedescendant', `chat-slash-${completion.index}`); + editor.setAttribute('aria-activedescendant', `chat-slash-${completion.index}`); } else if (e.key === 'Enter' || e.key === 'Tab') { - e.preventDefault(); e.stopImmediatePropagation(); apply(completion.ids[completion.index], completion.range); + 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: input.selectionStart, end: input.selectionEnd }; + 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); @@ -144,15 +156,15 @@ export function initChatComposer({ onChange, attach }) { if (!name.includes(query)) continue; const button = h('button', { type: 'button', text: unicode, title: `:${name}:`, 'aria-label': name }); button.addEventListener('click', () => { - if (input.disabled) return; - input.setRangeText(`:${name}:`, range.start, range.end, 'end'); close(); onChange(); input.focus(); + 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(); input.focus(); } }); + 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; } diff --git a/app/renderer/js/chat-editor-preview.js b/app/renderer/js/chat-editor-preview.js new file mode 100644 index 0000000..c083e9f --- /dev/null +++ b/app/renderer/js/chat-editor-preview.js @@ -0,0 +1,190 @@ +// 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' }), + ]; +} diff --git a/app/renderer/js/chat-editor.js b/app/renderer/js/chat-editor.js new file mode 100644 index 0000000..e0ec919 --- /dev/null +++ b/app/renderer/js/chat-editor.js @@ -0,0 +1,271 @@ +// 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); +} diff --git a/app/renderer/js/chat-settings.js b/app/renderer/js/chat-settings.js index 7140d07..4bd9718 100644 --- a/app/renderer/js/chat-settings.js +++ b/app/renderer/js/chat-settings.js @@ -1,6 +1,6 @@ // Settings > Chats in the official order (client_ui/main.js settings component near 4873300): Text Editing -// (toolbar visibility, diagram auto-load, Markdown Help), Options, Ignored Users. Preference semantics live in -// chat-options.js; schema and defaults in app/main/chat-prefs.js. +// (rich text editor, toolbar visibility, diagram auto-load, Markdown Help), Options, Ignored Users. Preference +// semantics live in chat-options.js; schema and defaults in app/main/chat-prefs.js. import { S } from './state.js'; import { tp } from './core.js'; import { h, icon } from './dom.js'; @@ -93,6 +93,8 @@ export function initChatSettings(changed) { host.replaceChildren( contactSettingsSection(save), section(t('settings.chat.text_edit'), [ + // render@4879468: the subtitle shows the source enabled/disabled strings verbatim. + toggle('chatRichTextEditor', 'settings.chat.text_edit.rich_text', 'settings.chat.text_edit.rich_text.enabled', 'settings.chat.text_edit.rich_text.disabled'), inlineRow(t('settings.chat.toolbar'), t('settings.chat.toolbar.info'), segmented('chatToolbarVisibility', 'settings.chat.toolbar', [['inactive', 'settings.chat.text_edit.toolbar_visibility.inactive'], ['dynamic', 'settings.chat.text_edit.toolbar_visibility.dynamic'], ['always-visible', 'settings.chat.text_edit.toolbar_visibility.always_visible']])), inlineRow(t('settings.chat.diagrams'), t('settings.chat.diagrams.info'), diff --git a/app/renderer/js/chat.js b/app/renderer/js/chat.js index 6666b06..7b1d74a 100644 --- a/app/renderer/js/chat.js +++ b/app/renderer/js/chat.js @@ -9,6 +9,7 @@ import { setMermaidAutoload } from './markdown/mermaid.js'; import { handleMarkdownClick, handleMarkdownKey } from './chat-markdown-help.js'; import { requestServerFileDownload, fetchServerImage, chooseAndUploadChatAttachments, canAttachFiles } from './files.js'; import { initChatComposer } from './chat-composer.js'; +import { createChatEditor } from './chat-editor.js'; import { notify } from './notifications.js'; import { initChatSettings, setIgnoredUser } from './chat-settings.js'; import { formatClock, showsMessage, opensIncoming, isIgnoredText, isIgnoredUid } from './chat-options.js'; @@ -24,6 +25,8 @@ let controls; let privateInfo; let lastBadge = -1; let closeComposer = () => {}; +// The single composer editor (chat-editor.js adapter); its contentDOM is #chat-input. +let editor = null; const imageUrls = new Set(); function stateFor(conn) { @@ -115,9 +118,11 @@ async function restore(state) { export function initChat() { $('#chat-form').addEventListener('submit', (e) => { e.preventDefault(); void send(); }); - const input = $('#chat-input'); - input.addEventListener('input', () => { if (displayed) displayed.draft = input.value; autosize(); updateComposer(); }); - input.addEventListener('keydown', (e) => { + editor = createChatEditor($('#chat-editor')); + editor.setPreview(richTextEditing()); + editor.addEventListener('input', () => { if (displayed) displayed.draft = editor.value; updateComposer(); }); + // Plain Enter is not in CodeMirror's keymap: this listener sends; Shift+Enter stays a newline. + editor.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !e.defaultPrevented) { e.preventDefault(); void send(); } }); $('#chat-tabs')?.addEventListener('keydown', onTabKey); @@ -135,13 +140,13 @@ export function initChat() { $('#chat-log').before(controls); $('#chat-log').addEventListener('click', handleMarkdownClick); $('#chat-log').addEventListener('keydown', handleMarkdownKey); - closeComposer = initChatComposer({ onChange: () => { if (displayed) displayed.draft = input.value; autosize(); updateComposer(); }, attach }); + closeComposer = initChatComposer({ editor, onChange: () => { if (displayed) displayed.draft = editor.value; updateComposer(); }, attach }); $('#chat-form').append(h('div', { id: 'chat-start-prompt', class: 'chat-start-prompt', hidden: true }, icon('mode-chat'), h('span'))); on('appearance-changed', renderLog); on('server_event', onChannelEvent); onLanguageChange(renderLog); initChatSettings(() => { renderLog(); updateComposer(); }); - input.addEventListener('focus', updateComposer); + editor.addEventListener('focus', updateComposer); $('#chat-form').addEventListener('focusout', () => queueMicrotask(updateComposer)); const composer = $('#chat-form'); const log = $('#chat-log'); @@ -171,7 +176,10 @@ export function initChat() { onViewChanged(); } -function autosize() { const input = $('#chat-input'); input.style.height = 'auto'; input.style.height = `${Math.min(input.scrollHeight, 160)}px`; } +/** workflowSettings.useRichTextEditor (default true): hybrid Markdown preview, otherwise raw source. */ +function richTextEditing() { return S.prefs?.chatRichTextEditor !== false; } +/** The composer adapter for callers that move focus into the chat (app.js) or inspect it. */ +export function composerEditor() { return editor; } function partner(chat) { return chat.state.conn.snap?.clients.find((c) => c.uid === chat.scope?.key) ?? null; } function tabTitle(chat) { if (chat.kind === 'channel') return chat.state.conn.snap?.channels.find((c) => String(c.id) === chat.scope?.key)?.name ?? chat.nickname ?? t('ui.channel'); @@ -186,8 +194,7 @@ function canSend(chat) { async function send() { const chat = current(); - const input = $('#chat-input'); - const text = input.value.replace(/\s+$/u, ''); + const text = editor.value.replace(/\s+$/u, ''); if (!text.trim() || !canSend(chat)) return; if (new TextEncoder().encode(text).length > 8192) { toast(() => t('ui.message.exceeds.8.kib'), 'error'); return; } const conn = chat.state.conn; @@ -200,7 +207,7 @@ async function send() { if (!isAlive(conn) || conn.session !== session) return; notify('message_sent', conn); chat.draft = ''; - if (current() === chat && input.value.replace(/\s+$/u, '') === text) { input.value = ''; autosize(); } + if (current() === chat && editor.value.replace(/\s+$/u, '') === text) editor.value = ''; } catch (err) { report(err); } finally { chat.sending = false; if (current() === chat) updateComposer(); } } @@ -313,7 +320,7 @@ function revealChat(chat) { } function select(state, key) { if (!state.chats.has(key)) return; - if (displayed) displayed.draft = $('#chat-input').value; + if (displayed) displayed.draft = editor.value; state.active = key; emit('set-view', 'main'); onViewChanged(); @@ -512,12 +519,13 @@ function rowFor(chat, msg, prev) { li.append(body); return li; } export function updateComposer() { - const input = $('#chat-input'); if (!input) return; + if (!editor) return; const chat = current(); const enabled = canSend(chat); - input.disabled = !enabled; $('#chat-send').disabled = !enabled || !input.value.trim(); + editor.setPreview(richTextEditing()); + editor.disabled = !enabled; $('#chat-send').disabled = !enabled || !editor.value.trim(); const prompt = $('#chat-start-prompt'); if (prompt) { - prompt.hidden = !enabled || Boolean(chat?.messages.length) || Boolean(input.value); + prompt.hidden = !enabled || Boolean(chat?.messages.length) || Boolean(editor.value); prompt.lastElementChild.textContent = t('chat.input.start_conversation'); } for (const button of document.querySelectorAll('#chat-format-bar button, #chat-emoji, #chat-attach')) button.disabled = !enabled; @@ -525,7 +533,8 @@ export function updateComposer() { if (attachment) attachment.hidden = !canAttachFiles(chat?.state.conn); const toolbar = $('#chat-format-bar'); if (toolbar) toolbar.hidden = S.prefs?.chatToolbarVisibility === 'inactive' || (S.prefs?.chatToolbarVisibility === 'dynamic' && !$('#chat-form').contains(document.activeElement)); - input.placeholder = !enabled ? t('ui.not.connected') : t('chat.sendMessage'); + editor.placeholder = !enabled ? t('ui.not.connected') : t('chat.sendMessage'); + editor.setAttribute('aria-label', t('ui.message')); } export function onSnapshot(conn) { const state = stateFor(conn); if (!state) return; @@ -541,10 +550,14 @@ export function onSnapshot(conn) { } } export function onViewChanged() { - if (displayed !== current()) closeComposer(); - if (displayed && $('#chat-input')) displayed.draft = $('#chat-input').value; - displayed = current(); - if ($('#chat-input')) { $('#chat-input').value = displayed?.draft ?? ''; autosize(); } + const next = current(); + if (displayed !== next) closeComposer(); + if (displayed && editor) displayed.draft = editor.value; + // Only a different conversation replaces the document and clears undo/selection; re-rendering the same + // conversation keeps the live editor state. + const changed = displayed !== next; + displayed = next; + if (editor && changed) editor.reset(next?.draft ?? ''); if (displayed && S.view === 'main') displayed.unread = 0; renderTabs(); renderLog(); badge(); if (displayed && !displayed.loaded) void loadPage(displayed); @@ -585,6 +598,6 @@ async function attach() { const query = new URLSearchParams({ port: endpoint.port || '9987', serverUID: serverUid, channel: String(file.channelId), path: file.path, filename: file.name, size: String(file.size), isDir: '0' }); chat.draft += `${chat.draft ? '\n' : ''}ts3file://${endpoint.hostname}?${query}`; } - if (current() === chat) { $('#chat-input').value = chat.draft; autosize(); } + if (current() === chat) { editor.value = chat.draft; updateComposer(); } } catch (err) { report(err); } } diff --git a/app/renderer/js/markdown/parse.js b/app/renderer/js/markdown/parse.js index 0af18c3..aee0db5 100644 --- a/app/renderer/js/markdown/parse.js +++ b/app/renderer/js/markdown/parse.js @@ -156,7 +156,7 @@ class Parser { // all, every definition in document order (the Markdown Help "Footnote Definition" example). for (const label of this.footnoteOrder.length > 0 ? this.footnoteOrder : [...this.footnoteDefs.keys()]) { const def = this.footnoteDefs.get(label); - if (def) notes.push({ label, number: notes.length + 1, children: def.children }); + if (def) notes.push({ label, number: notes.length + 1, children: def.children, lines: def.lines }); } return { type: 'doc', children, footnotes: notes }; } @@ -166,165 +166,169 @@ class Parser { const out = []; let i = 0; while (i < lines.length) { - const line = lines[i]; - this.count(); - if (isBlank(line)) { i += 1; continue; } - - // Fenced code (``` or ~~~); ```mermaid is a diagram. - const fence = FENCE.exec(line); - if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) { - const marker = fence[2]; - const indent = fence[1].length; - const body = []; - let j = i + 1; - for (; j < lines.length; j += 1) { - const close = FENCE.exec(lines[j]); - if (close && close[2][0] === marker[0] && close[2].length >= marker.length && !close[3].trim()) break; - body.push(lines[j].replace(new RegExp(`^[ \\t]{0,${indent}}`), '')); - } - const lang = fence[3].trim().split(/\s+/)[0] ?? ''; - const content = body.join('\n'); - out.push(lang.toLowerCase() === 'mermaid' ? { type: 'mermaid', text: content } : { type: 'code', lang: unescapeText(lang), text: content }); - i = j + 1; - continue; - } - - // $$ math block: needs a closing $$ and some content, otherwise the line is plain text. - if (line.trim() === '$$') { - let j = i + 1; - while (j < lines.length && lines[j].trim() !== '$$') j += 1; - const content = lines.slice(i + 1, j).filter((l) => l.length > 0); - if (j < lines.length && content.length > 0) { - out.push({ type: 'math_block', text: content.join('\n') }); - i = j + 1; - continue; - } - } - - // :::details Title / :::left|center|right|justify … ::: (the close needs the same colon count). - const colon = COLON_FENCE.exec(line); - if (colon) { - const keyword = colon[2].toLowerCase(); - const header = colon[3] ?? ''; - const isDetails = keyword === 'details'; - const isAlign = ['left', 'center', 'right', 'justify'].includes(keyword); - if ((isDetails || (isAlign && !header)) && !header.includes(':::')) { - const count = colon[1].length; - let j = i + 1; - while (j < lines.length && !new RegExp(`^[ \\t]*:{${count}}[ \\t]*$`).test(lines[j])) j += 1; - const inner = this.parseBlocks(lines.slice(i + 1, j), depth + 1); - if (isDetails) out.push({ type: 'details', summary: header ? this.parseInline(header, depth + 1) : [], children: inner }); - else out.push({ type: 'align', align: keyword, children: inner }); - i = j + 1; - continue; - } - } - - // BBCode block mode: an opening tag alone on its line, its closing tag alone on a later line. - const bbOpen = /^[ \t]*\[([a-z]+)(?:[= ]([^\]\n]*))?\][ \t]*$/i.exec(line); - if (bbOpen) { - const tag = bbOpen[1].toLowerCase(); - if (tag === 'hr') { - out.push({ type: 'hr' }); - i += 1; - continue; - } - if (BB_PAIRED.has(tag) && (bbOpen[2] === undefined || BB_PARAM.has(tag))) { - const closeRe = new RegExp(`^[ \\t]*\\[/${tag}\\][ \\t]*$`, 'i'); - let j = i + 1; - while (j < lines.length && !closeRe.test(lines[j])) j += 1; - if (j < lines.length && j > i + 1 && lines.slice(i + 1, j).some((l) => l.trim())) { - out.push(bbBlock(tag, (bbOpen[2] ?? '').trim(), this.parseBlocks(lines.slice(i + 1, j), depth + 1))); - i = j + 1; - continue; - } - } - } - - // Blockquote: every quoted line needs its own `>` (strict, no lazy continuation). - if (/^[ \t]{0,3}>/.test(line)) { - const inner = []; - let j = i; - for (; j < lines.length && /^[ \t]{0,3}>/.test(lines[j]); j += 1) inner.push(lines[j].replace(/^[ \t]{0,3}> ?/, '')); - let callout = null; - const rest = []; - for (const l of inner) { - const marker = /^\s*\[!([A-Za-z]+)\]\s*$/.exec(l); - const type = marker && CALLOUTS.get(marker[1].toUpperCase()); - if (type) { - if (!callout) callout = { type, title: CALLOUT_TITLES[type] }; - continue; - } - rest.push(l); - } - out.push({ type: 'blockquote', callout, children: this.parseBlocks(rest, depth + 1) }); - i = j; - continue; - } - - if (isThematicBreak(line)) { out.push({ type: 'hr' }); i += 1; continue; } - - const atx = ATX.exec(line); - if (atx) { - out.push({ type: 'heading', level: atx[1].length, children: this.parseInline(atx[2] ?? '', depth + 1) }); - i += 1; - continue; - } - - const marker = listMarker(line); - if (marker) { - const { list, next } = this.parseList(lines, i, marker.kind, marker.from, depth); - out.push(list); - i = next; - continue; - } - - const fn = FOOTNOTE_DEF.exec(line); - if (fn) { - const body = [fn[2]]; - let j = i + 1; - while (j < lines.length && !isBlank(lines[j]) && leadingSpaces(lines[j]) > 0) body.push(lines[j].trim()), (j += 1); - if (!this.footnoteDefs.has(fn[1])) this.footnoteDefs.set(fn[1], { children: this.parseInline(body.join(' '), depth + 1) }); - i = j; - continue; - } - - const def = LINK_DEF.exec(line); - if (def && !def[1].startsWith('^')) { i += 1; continue; } - - // GFM table: header row with pipes followed by a delimiter row. - if (line.includes('|') && i + 1 < lines.length && isTableDelimiter(lines[i + 1])) { - const align = splitRow(lines[i + 1]).map((c) => { - const t = c.trim(); - if (t.startsWith(':') && t.endsWith(':')) return 'center'; - if (t.endsWith(':')) return 'right'; - if (t.startsWith(':')) return 'left'; - return null; - }); - const header = splitRow(line).map((c) => this.parseInline(c.trim(), depth + 1)); - const rows = []; - let j = i + 2; - for (; j < lines.length && !isBlank(lines[j]) && lines[j].includes('|'); j += 1) { - rows.push(splitRow(lines[j]).map((c) => this.parseInline(c.trim(), depth + 1))); - } - out.push({ type: 'table', align, header, rows }); - i = j; - continue; - } - - // Setext heading: a text line underlined by === or ---. - if (i + 1 < lines.length && isSetextUnderline(lines[i + 1])) { - out.push({ type: 'heading', level: lines[i + 1].trim()[0] === '=' ? 1 : 2, children: this.parseInline(line.trim(), depth + 1) }); - i += 2; - continue; - } - - out.push({ type: 'paragraph', children: this.parseInline(line.replace(/^[ \t]+/, '').replace(/[ \t]+$/, ''), depth + 1) }); - i += 1; + const before = out.length; + const next = this.parseBlock(lines, i, depth, out); + // Source span [first line, end line) of the block within `lines`; at depth 0 these are document + // lines, which the chat editor's preview uses to map rendered blocks back to their source. + if (out.length > before) out[before].lines = [i, Math.min(next, lines.length)]; + i = next; } return out; } + /** Parses the block that starts at line `i` (pushing at most one node) and returns the next line index. */ + parseBlock(lines, i, depth, out) { + const line = lines[i]; + this.count(); + if (isBlank(line)) return i + 1; + + // Fenced code (``` or ~~~); ```mermaid is a diagram. + const fence = FENCE.exec(line); + if (fence && !(fence[2][0] === '`' && fence[3].includes('`'))) { + const marker = fence[2]; + const indent = fence[1].length; + const body = []; + let j = i + 1; + for (; j < lines.length; j += 1) { + const close = FENCE.exec(lines[j]); + if (close && close[2][0] === marker[0] && close[2].length >= marker.length && !close[3].trim()) break; + body.push(lines[j].replace(new RegExp(`^[ \\t]{0,${indent}}`), '')); + } + const lang = fence[3].trim().split(/\s+/)[0] ?? ''; + const content = body.join('\n'); + out.push(lang.toLowerCase() === 'mermaid' ? { type: 'mermaid', text: content } : { type: 'code', lang: unescapeText(lang), text: content }); + return j + 1; + } + + // $$ math block: needs a closing $$ and some content, otherwise the line is plain text. + if (line.trim() === '$$') { + let j = i + 1; + while (j < lines.length && lines[j].trim() !== '$$') j += 1; + const content = lines.slice(i + 1, j).filter((l) => l.length > 0); + if (j < lines.length && content.length > 0) { + out.push({ type: 'math_block', text: content.join('\n') }); + return j + 1; + } + } + + // :::details Title / :::left|center|right|justify … ::: (the close needs the same colon count). + const colon = COLON_FENCE.exec(line); + if (colon) { + const keyword = colon[2].toLowerCase(); + const header = colon[3] ?? ''; + const isDetails = keyword === 'details'; + const isAlign = ['left', 'center', 'right', 'justify'].includes(keyword); + if ((isDetails || (isAlign && !header)) && !header.includes(':::')) { + const count = colon[1].length; + let j = i + 1; + while (j < lines.length && !new RegExp(`^[ \\t]*:{${count}}[ \\t]*$`).test(lines[j])) j += 1; + const inner = this.parseBlocks(lines.slice(i + 1, j), depth + 1); + if (isDetails) out.push({ type: 'details', summary: header ? this.parseInline(header, depth + 1) : [], children: inner }); + else out.push({ type: 'align', align: keyword, children: inner }); + return j + 1; + } + } + + // BBCode block mode: an opening tag alone on its line, its closing tag alone on a later line. + const bbOpen = /^[ \t]*\[([a-z]+)(?:[= ]([^\]\n]*))?\][ \t]*$/i.exec(line); + if (bbOpen) { + const tag = bbOpen[1].toLowerCase(); + if (tag === 'hr') { + out.push({ type: 'hr' }); + return i + 1; + } + if (BB_PAIRED.has(tag) && (bbOpen[2] === undefined || BB_PARAM.has(tag))) { + const closeRe = new RegExp(`^[ \\t]*\\[/${tag}\\][ \\t]*$`, 'i'); + let j = i + 1; + while (j < lines.length && !closeRe.test(lines[j])) j += 1; + if (j < lines.length && j > i + 1 && lines.slice(i + 1, j).some((l) => l.trim())) { + out.push(bbBlock(tag, (bbOpen[2] ?? '').trim(), this.parseBlocks(lines.slice(i + 1, j), depth + 1))); + return j + 1; + } + } + } + + // Blockquote: every quoted line needs its own `>` (strict, no lazy continuation). + if (/^[ \t]{0,3}>/.test(line)) { + const inner = []; + let j = i; + for (; j < lines.length && /^[ \t]{0,3}>/.test(lines[j]); j += 1) inner.push(lines[j].replace(/^[ \t]{0,3}> ?/, '')); + let callout = null; + const rest = []; + for (const l of inner) { + const marker = /^\s*\[!([A-Za-z]+)\]\s*$/.exec(l); + const type = marker && CALLOUTS.get(marker[1].toUpperCase()); + if (type) { + if (!callout) callout = { type, title: CALLOUT_TITLES[type] }; + continue; + } + rest.push(l); + } + out.push({ type: 'blockquote', callout, children: this.parseBlocks(rest, depth + 1) }); + return j; + } + + if (isThematicBreak(line)) { + out.push({ type: 'hr' }); + return i + 1; + } + + const atx = ATX.exec(line); + if (atx) { + out.push({ type: 'heading', level: atx[1].length, children: this.parseInline(atx[2] ?? '', depth + 1) }); + return i + 1; + } + + const marker = listMarker(line); + if (marker) { + const { list, next } = this.parseList(lines, i, marker.kind, marker.from, depth); + out.push(list); + return next; + } + + const fn = FOOTNOTE_DEF.exec(line); + if (fn) { + const body = [fn[2]]; + let j = i + 1; + while (j < lines.length && !isBlank(lines[j]) && leadingSpaces(lines[j]) > 0) body.push(lines[j].trim()), (j += 1); + if (!this.footnoteDefs.has(fn[1])) { + this.footnoteDefs.set(fn[1], { children: this.parseInline(body.join(' '), depth + 1), lines: depth === 0 ? [i, j] : null }); + } + return j; + } + + const def = LINK_DEF.exec(line); + if (def && !def[1].startsWith('^')) return i + 1; + + // GFM table: header row with pipes followed by a delimiter row. + if (line.includes('|') && i + 1 < lines.length && isTableDelimiter(lines[i + 1])) { + const align = splitRow(lines[i + 1]).map((c) => { + const t = c.trim(); + if (t.startsWith(':') && t.endsWith(':')) return 'center'; + if (t.endsWith(':')) return 'right'; + if (t.startsWith(':')) return 'left'; + return null; + }); + const header = splitRow(line).map((c) => this.parseInline(c.trim(), depth + 1)); + const rows = []; + let j = i + 2; + for (; j < lines.length && !isBlank(lines[j]) && lines[j].includes('|'); j += 1) { + rows.push(splitRow(lines[j]).map((c) => this.parseInline(c.trim(), depth + 1))); + } + out.push({ type: 'table', align, header, rows }); + return j; + } + + // Setext heading: a text line underlined by === or ---. + if (i + 1 < lines.length && isSetextUnderline(lines[i + 1])) { + out.push({ type: 'heading', level: lines[i + 1].trim()[0] === '=' ? 1 : 2, children: this.parseInline(line.trim(), depth + 1) }); + return i + 2; + } + + out.push({ type: 'paragraph', children: this.parseInline(line.replace(/^[ \t]+/, '').replace(/[ \t]+$/, ''), depth + 1) }); + return i + 1; + } + /** Strict single-line list items; deeper markers (≥ marker + 2 columns) open a nested list. */ parseList(lines, i, kind, baseIndent, depth) { const items = []; diff --git a/app/renderer/js/markdown/render.js b/app/renderer/js/markdown/render.js index aa61715..bba0565 100644 --- a/app/renderer/js/markdown/render.js +++ b/app/renderer/js/markdown/render.js @@ -396,3 +396,18 @@ export function renderMarkdownInto(target, source, options = {}) { && doc.children[0].children.every((c) => c.type === 'emoji' || (c.type === 'text' && !c.value.trim())); return { onlyEmoji }; } + +/** + * Renders one top-level block of a `parseMarkdown` tree (chat editor preview). Reference links and + * footnote numbers are resolved document-wide by the parser, so a block looks as it will in the message. + */ +export function renderMarkdownBlock(node, options = {}) { + return new DomRenderer(options).block(node); +} + +/** Renders footnote definitions as the message's footnote section, numbered from the first note. */ +export function renderMarkdownFootnotes(notes, options = {}) { + const section = new DomRenderer(options).footnotes(notes); + if (section && notes[0].number !== 1) section.firstChild.start = notes[0].number; + return section; +} diff --git a/app/renderer/shared/en.js b/app/renderer/shared/en.js index ecba606..f8d579f 100644 --- a/app/renderer/shared/en.js +++ b/app/renderer/shared/en.js @@ -1676,6 +1676,9 @@ "settings.chat.ignored_users": "Ignored Users", "settings.chat.ignored_users.empty": "No ignored users", "settings.chat.ignored_users.empty.info": "You can set other chat users as Ignored, meaning TeamSpeak will ignore any invites and messages from them", + "settings.chat.text_edit.rich_text": "Use Rich Text Editor", + "settings.chat.text_edit.rich_text.disabled": "See and change the style of text as you type.", + "settings.chat.text_edit.rich_text.enabled": "See exactly the text you have typed, including text style marks.", "settings.chat.text_edit.toolbar_visibility.inactive": "Hidden", "settings.chat.text_edit.toolbar_visibility.dynamic": "Dynamic", "settings.chat.text_edit.toolbar_visibility.always_visible": "Always Visible", diff --git a/app/renderer/shared/ru.js b/app/renderer/shared/ru.js index 033999f..49c95ef 100644 --- a/app/renderer/shared/ru.js +++ b/app/renderer/shared/ru.js @@ -1678,6 +1678,9 @@ "settings.chat.ignored_users": "Игнорируемые пользователи", "settings.chat.ignored_users.empty": "Нет игнорируемых пользователей", "settings.chat.ignored_users.empty.info": "Ты можешь установить для других пользователей чата статус \"Игнорируемые\" и TeamSpeak будет игнорировать любые приглашения и сообщения от них", + "settings.chat.text_edit.rich_text": "Использовать редактор форматированного текста", + "settings.chat.text_edit.rich_text.disabled": "Просматривай и меняй стиль текста по мере его ввода.", + "settings.chat.text_edit.rich_text.enabled": "Текст, который ты вводишь, отображается с применением форматирования в реальном времени.", "settings.chat.text_edit.toolbar_visibility.inactive": "Скрыта", "settings.chat.text_edit.toolbar_visibility.dynamic": "Динамически", "settings.chat.text_edit.toolbar_visibility.always_visible": "Всегда видна", diff --git a/app/renderer/styles/app.css b/app/renderer/styles/app.css index 74d8862..65d03fa 100644 --- a/app/renderer/styles/app.css +++ b/app/renderer/styles/app.css @@ -1255,23 +1255,7 @@ html[data-chat-style="compact"] .msg .msg-body::before { display: none; } .composer-tool:hover { background: color-mix(in srgb, var(--tsv-bg) 65%, transparent); border-bottom-color: var(--tsv-tint); color: var(--tsv-tint); --tsv-icon-base: var(--tsv-tint); } .composer-tool:active, .composer-tool[aria-expanded="true"] { background: color-mix(in srgb, var(--tsv-bg) 80%, transparent); } .composer-row { display: flex; align-items: stretch; } -.composer textarea { - flex: 1; - min-height: 34px; - max-height: 250px; - padding: 8px 10px; - border: 0; - border-radius: var(--tsv-border-radius-large); - background: transparent; - color: var(--tsv-font-color); - font-size: var(--tsv-font-size-content); - line-height: var(--tsv-line-height-content); - /* source -.025rem resolves against the source's fixed 15px root (main.css@1034 `body,html{font-size:15px}`) */ - letter-spacing: -0.375px; - resize: none; -} -.composer textarea { font-weight: 400; } -.composer textarea:focus-visible { outline: none; } +/* the input itself (#chat-editor, one CodeMirror view): styles/chat-editor.css */ .composer-actions { flex: none; display: flex; align-items: center; height: var(--tsv-bar-element-height); margin: auto 3px 4px auto; } /* source `.ts-chat-input-container-actions *{margin:auto 3px}`: 24px buttons, glyph inset 3px from the left */ .composer-actions .icon-btn { width: 24px; height: 26px; margin: auto 3px; padding: 0; justify-items: start; color: var(--tsv-tint); } diff --git a/app/renderer/styles/chat-editor.css b/app/renderer/styles/chat-editor.css new file mode 100644 index 0000000..ffd0031 --- /dev/null +++ b/app/renderer/styles/chat-editor.css @@ -0,0 +1,34 @@ +/* Chat composer editor: one CodeMirror view in #chat-editor (chat-editor.js), contentDOM #chat-input. + Source: TSChatInputTextarea `.ts-chat-input` (main.css@212291), its inner editor (@205434) and the + CodeMirror overrides scoped to it (@205985-206823). The engine's JS theme only neutralises CodeMirror + defaults; every visible value here is the source's. */ +.composer-editor { + display: flex; + flex: 1; + flex-direction: column; + min-width: 0; + min-height: 34px; + max-height: 250px; + padding: var(--tsv-padding-v) var(--tsv-padding-h-small); + border: none; + background-color: transparent; + color: var(--tsv-font-color); + font-size: var(--tsv-font-size-content); + font-weight: 400; + line-height: var(--tsv-line-height-content); + /* source -.025rem resolves against the source's fixed 15px root (main.css@1034 `body,html{font-size:15px}`) */ + letter-spacing: -0.375px; + outline: none; +} +#chat-editor .cm-editor { flex-shrink: 1; min-height: 0; background: transparent; color: var(--tsv-font-color); outline: none; } +#chat-editor .cm-editor.cm-focused { outline: none; } +#chat-editor .cm-scroller { font-family: inherit; line-height: inherit; overflow: auto; } +#chat-editor .cm-content { padding: 0; white-space: pre-wrap; caret-color: var(--tsv-font-color); } +#chat-editor .cm-content:focus-visible { outline: none; } +/* `.is-empty:before{content:attr(data-placeholder)}` (main.css@205743): subtitle colour, content size */ +#chat-editor .cm-placeholder { color: var(--tsv-font-subtitle-color); font-size: var(--tsv-font-size-content); pointer-events: none; } +#chat-editor .tp-chat-editor-disabled .cm-content { cursor: default; } +/* Raw `[id]: url` definitions stay editable source; they are not message content. */ +#chat-editor .cm-line.tp-chat-editor-definition { color: var(--tsv-font-subtitle-color); } +/* Rendered inactive blocks reuse the message markdown rules (.ts-parsed-text-content) without extra spacing. */ +#chat-editor .tp-chat-editor-block { margin: 0; } diff --git a/app/renderer/vendor/DEPENDENCIES.json b/app/renderer/vendor/DEPENDENCIES.json index 7d189c4..34a005f 100644 --- a/app/renderer/vendor/DEPENDENCIES.json +++ b/app/renderer/vendor/DEPENDENCIES.json @@ -25,6 +25,46 @@ "integrity": "sha512-U+HFai5+zmJCkK86QsaJtoITlboZHBqrVketcO2ROv865xfCMSFpELQoz1GkX5GzME8pTa+3kbKrZHQtI0gdbw==", "location": "node_modules/@chevrotain/types" }, + { + "name": "@codemirror/commands", + "version": "6.11.1", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz", + "integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==", + "location": "node_modules/@codemirror/commands" + }, + { + "name": "@codemirror/language", + "version": "6.13.1", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz", + "integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==", + "location": "node_modules/@codemirror/language" + }, + { + "name": "@codemirror/state", + "version": "6.7.6", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz", + "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", + "location": "node_modules/@codemirror/state" + }, + { + "name": "@codemirror/streamparser", + "version": "6.0.0", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@codemirror/streamparser/-/streamparser-6.0.0.tgz", + "integrity": "sha512-JTFPF6xrfjt0mnfGPgzcLiMwYmvIyNaoizp8BYzv8FE8KrT6GBGDZ190rtt+O7Wke3gG/MFHyiY9YGNeimof4w==", + "location": "node_modules/@codemirror/streamparser" + }, + { + "name": "@codemirror/view", + "version": "6.43.15", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.15.tgz", + "integrity": "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==", + "location": "node_modules/@codemirror/view" + }, { "name": "@iconify/types", "version": "2.0.0", @@ -41,6 +81,38 @@ "integrity": "sha512-JZHlwdID+dy+lTgbYC8NEC4zeugqeYsc6jewvzb4c58kHauJn+X7rNwQjxz5p2qSjqaEeQoLkCIQ9v/H4PK0/w==", "location": "node_modules/@iconify/utils" }, + { + "name": "@lezer/common", + "version": "1.5.5", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.5.tgz", + "integrity": "sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg==", + "location": "node_modules/@lezer/common" + }, + { + "name": "@lezer/highlight", + "version": "1.2.5", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz", + "integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==", + "location": "node_modules/@lezer/highlight" + }, + { + "name": "@lezer/lr", + "version": "1.4.12", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@lezer/lr/-/lr-1.4.12.tgz", + "integrity": "sha512-On9HU4oMMiHPMkQDgoTnGahjgG5n/MkN38CgG77sMraKLL+3JBbeQNi1FcCXV9QRqwF9/BUXP3caHyJC1fBOTQ==", + "location": "node_modules/@lezer/lr" + }, + { + "name": "@marijn/find-cluster-break", + "version": "1.0.4", + "license": "MIT", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.4.tgz", + "integrity": "sha512-Wy0V7+SGUjnF9/TkiM1hKVDPj7jKXduPNboMVtHTA8dySMURWqfg/JZ9E2Sq8JgSJmkl7k7Qe9FLeMSrSraWmQ==", + "location": "node_modules/@marijn/find-cluster-break" + }, { "name": "@mermaid-js/parser", "version": "1.2.1", @@ -337,6 +409,14 @@ "integrity": "sha512-s9whTXInMSgAp/NVXVNuVxVKzGH2qck3aQlVHxDCdAEPgtMKwc4Wq6/QKhgdEdgbLSi9rBTAcPoRa6JpiG4ksg==", "location": "node_modules/cose-base" }, + { + "name": "crelt", + "version": "1.0.7", + "license": "MIT", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.7.tgz", + "integrity": "sha512-aK6BbWfhf4U/wCcLHKPJl/xa6VkVstRaPywWtMKGwuOLc/wZTyQYuoxgvZnNsBvv7Kg3YTBQYYBCggcviQczuA==", + "location": "node_modules/crelt" + }, { "name": "cytoscape", "version": "3.34.4", @@ -889,6 +969,14 @@ "integrity": "sha512-cEmp9QeXXRmjj/rVp9oyiqcvyocWab/HaoN4+bwFeZ7QzykJD6L3yD4v12K1x0tHpqRqVpJevN3gW7kyM39Bqg==", "location": "node_modules/strictdom" }, + { + "name": "style-mod", + "version": "4.1.4", + "license": "MIT", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.4.tgz", + "integrity": "sha512-XXWIQt633/EpAFx8aZDOTjBzrCaGmhvEQlQo6MVPfa2OzO2cWo+4hV9h+6UkHYlXGfy+ODXKUdP7Pthmcu5ATw==", + "location": "node_modules/style-mod" + }, { "name": "stylis", "version": "4.4.0", @@ -920,6 +1008,14 @@ "resolved": "https://registry.npmjs.org/uuid/-/uuid-14.0.3.tgz", "integrity": "sha512-Sc5u1VVln93y1Xnz4R+CunOZc7R9LUcTmhj7Rc7Eg3HVcf7rVn2FOoa812fe0W8p3jD7xeoGSYbfqCGGH2B6xw==", "location": "node_modules/uuid" + }, + { + "name": "w3c-keyname", + "version": "2.2.8", + "license": "MIT", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "location": "node_modules/w3c-keyname" } ] } diff --git a/app/renderer/vendor/PROVENANCE.json b/app/renderer/vendor/PROVENANCE.json index d4d1a10..0ca47bd 100644 --- a/app/renderer/vendor/PROVENANCE.json +++ b/app/renderer/vendor/PROVENANCE.json @@ -164,6 +164,139 @@ "sha256": "3ca9d4afd21425087cf31893b8f9f63c81b0b8408db5e343ca76e5f8aa26ab9a" } ] + }, + { + "name": "codemirror", + "bundler": "esbuild@0.28.2", + "exports": { + "@codemirror/state": [ + "Annotation", + "Compartment", + "EditorSelection", + "EditorState", + "StateField" + ], + "@codemirror/view": [ + "Decoration", + "EditorView", + "WidgetType", + "keymap", + "placeholder" + ], + "@codemirror/commands": [ + "history", + "historyKeymap", + "insertNewline", + "standardKeymap" + ] + }, + "patches": [ + "style-mod: use constructed stylesheets on Document as well as ShadowRoot; no inline style element under the application CSP" + ], + "bundled": [ + { + "name": "@codemirror/commands", + "version": "6.11.1", + "license": "MIT" + }, + { + "name": "@codemirror/language", + "version": "6.13.1", + "license": "MIT" + }, + { + "name": "@codemirror/state", + "version": "6.7.6", + "license": "MIT" + }, + { + "name": "@codemirror/view", + "version": "6.43.15", + "license": "MIT" + }, + { + "name": "@lezer/common", + "version": "1.5.5", + "license": "MIT" + }, + { + "name": "@lezer/highlight", + "version": "1.2.5", + "license": "MIT" + }, + { + "name": "@marijn/find-cluster-break", + "version": "1.0.4", + "license": "MIT" + }, + { + "name": "style-mod", + "version": "4.1.4", + "license": "MIT" + }, + { + "name": "w3c-keyname", + "version": "2.2.8", + "license": "MIT" + } + ], + "files": [ + { + "path": "codemirror/codemirror.js", + "generated": true, + "sha256": "4d1ae27dba70188a37a581a48d20ff4cfc2c8f81783db1a3157a4d91637381f0" + }, + { + "path": "codemirror/package.json", + "generated": true, + "sha256": "3ca9d4afd21425087cf31893b8f9f63c81b0b8408db5e343ca76e5f8aa26ab9a" + }, + { + "path": "codemirror/licenses/@codemirror__commands.LICENSE", + "from": "@codemirror/commands/LICENSE", + "sha256": "05c6130cda97e7600ca91427a41e8a065efcf82365fc0293e7de80faec494c07" + }, + { + "path": "codemirror/licenses/@codemirror__language.LICENSE", + "from": "@codemirror/language/LICENSE", + "sha256": "05c6130cda97e7600ca91427a41e8a065efcf82365fc0293e7de80faec494c07" + }, + { + "path": "codemirror/licenses/@codemirror__state.LICENSE", + "from": "@codemirror/state/LICENSE", + "sha256": "05c6130cda97e7600ca91427a41e8a065efcf82365fc0293e7de80faec494c07" + }, + { + "path": "codemirror/licenses/@codemirror__view.LICENSE", + "from": "@codemirror/view/LICENSE", + "sha256": "05c6130cda97e7600ca91427a41e8a065efcf82365fc0293e7de80faec494c07" + }, + { + "path": "codemirror/licenses/@lezer__common.LICENSE", + "from": "@lezer/common/LICENSE", + "sha256": "568902fb66eaf1f11750e966b33fd7b5d7c618e65af09f35ef843635bcf5f1ba" + }, + { + "path": "codemirror/licenses/@lezer__highlight.LICENSE", + "from": "@lezer/highlight/LICENSE", + "sha256": "568902fb66eaf1f11750e966b33fd7b5d7c618e65af09f35ef843635bcf5f1ba" + }, + { + "path": "codemirror/licenses/@marijn__find-cluster-break.LICENSE", + "from": "@marijn/find-cluster-break/LICENSE", + "sha256": "9360b00fdd091f05c783b568bdd46c679c41b72415599252de98949462ea1acb" + }, + { + "path": "codemirror/licenses/style-mod.LICENSE", + "from": "style-mod/LICENSE", + "sha256": "cb4474e26547397169061d3586c00022cda5330a1b64fa13e872319f3b63aff1" + }, + { + "path": "codemirror/licenses/w3c-keyname.LICENSE", + "from": "w3c-keyname/LICENSE", + "sha256": "869c30f368eb08735e779027b9f4bc9fea2f39624351856aebe42741f0bc0884" + } + ] } ] } diff --git a/app/renderer/vendor/THIRD_PARTY_NOTICES.txt b/app/renderer/vendor/THIRD_PARTY_NOTICES.txt index cea3d60..30ee49b 100644 --- a/app/renderer/vendor/THIRD_PARTY_NOTICES.txt +++ b/app/renderer/vendor/THIRD_PARTY_NOTICES.txt @@ -1,5 +1,5 @@ Chat renderer dependency notices -The npm workspace inventory below conservatively includes build/type-only dependencies as well as runtime bundled dependencies. +The npm workspace inventory below conservatively includes build/type-only dependencies as well as runtime bundled dependencies; devDependencies (build tools such as esbuild) are not redistributed and are excluded. DOMPurify is redistributed under its Apache-2.0 option. No official TeamSpeak bundle is redistributed. ===== @antfu/install-pkg@2.1.0 (MIT) ===== @@ -261,6 +261,136 @@ SOFTWARE. limitations under the License. +===== @codemirror/commands@6.11.1 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +===== @codemirror/language@6.13.1 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +===== @codemirror/state@6.7.6 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +===== @codemirror/streamparser@6.0.0 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +===== @codemirror/view@6.43.15 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2018-2021 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + ===== @iconify/types@2.0.0 (MIT) ===== --- license.txt --- @@ -311,6 +441,110 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +===== @lezer/common@1.5.5 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2018 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +===== @lezer/highlight@1.2.5 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2018 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +===== @lezer/lr@1.4.12 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2018 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +===== @marijn/find-cluster-break@1.0.4 (MIT) ===== + +--- LICENSE --- +MIT License + +Copyright (C) 2024 by Marijn Haverbeke + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + ===== @mermaid-js/parser@1.2.1 (MIT) ===== --- LICENSE --- @@ -1275,6 +1509,30 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +===== crelt@1.0.7 (MIT) ===== + +--- LICENSE --- +Copyright (C) 2020 by Marijn Haverbeke + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + ===== cytoscape@3.34.4 (MIT) ===== --- LICENSE --- @@ -3904,6 +4162,30 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +===== style-mod@4.1.4 (MIT) ===== + +--- LICENSE --- +Copyright (C) 2018 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + ===== stylis@4.4.0 (MIT) ===== --- LICENSE --- @@ -3995,3 +4277,27 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +===== w3c-keyname@2.2.8 (MIT) ===== + +--- LICENSE --- +Copyright (C) 2016 by Marijn Haverbeke and others + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/app/renderer/vendor/codemirror/codemirror.js b/app/renderer/vendor/codemirror/codemirror.js new file mode 100644 index 0000000..d8d768e --- /dev/null +++ b/app/renderer/vendor/codemirror/codemirror.js @@ -0,0 +1,16127 @@ +// Generated by scripts/vendor-chat-libs.mjs with esbuild 0.28.2. Do not edit. +// Bundles @codemirror/commands@6.11.1 (MIT), @codemirror/language@6.13.1 (MIT), @codemirror/state@6.7.6 (MIT), @codemirror/view@6.43.15 (MIT), @lezer/common@1.5.5 (MIT), @lezer/highlight@1.2.5 (MIT), @marijn/find-cluster-break@1.0.4 (MIT), style-mod@4.1.4 (MIT), w3c-keyname@2.2.8 (MIT). +// License texts: vendor/codemirror/licenses/. +// Local CSP adaptation: constructed stylesheets also on Document. +// node_modules/@marijn/find-cluster-break/src/index.js +var rangeFrom = []; +var rangeTo = []; +(() => { + let numbers = "lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,1n,9,16,o,,x,1i,3,,i,,7,a,2,t,3,1k,,,7,2,2,2,3,9,,a,2,q,,2,3,1k,,,5,4,2,2,3,3,,u,2,3,,b,3,1k,,,8,,3,,3,k,2,m,6,,3,1k,,,7,2,2,2,3,7,3,a,2,u,,1n,5,3,3,,4,9,,14,5,1j,,,7,,3,,4,7,2,b,2,t,3,1k,,,7,,3,,4,7,2,b,2,f,,c,4,1j,2,,7,,3,,4,9,,a,2,t,3,1y,,4,6,,,,8,i,2,1p,,,8,c,8,2q,,,a,b,7,21,2,r,,,,,,4,2,1d,k,,2,5,b,,10,9,,2u,b,,6,n,4,4,3,g,4,d,,,3,6,,f,,jj,3,qa,4,s,3,t,2,u,2,1s,w,9,,19,3,,,39,2,y,,3a,c,4,c,63,5,1l,a,,,,,2,o,2,,1c,1a,2,c,k,5,1b,h,12,9,c,3,u,d,1k,e,1c,k,48,3,,l,4,,6,,2,3,5i,1s,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,n,5,4,,2b,2,1e,i,q,i,d,,12,8,p,d,18,4,1b,e,10,,1v,e,c,,8,2,1a,,1f,,,3,2,2,5,2,,,15,5,5,2,6k,8,,2,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,1t,5,8t,2,25,6,1y,b,1d,4,3e,3,1h,f,15,,2,2,a,4,19,b,7,,1p,3,10,e,g,2,18,,c,3,1c,e,8,4,,2,2k,c,6,,2,,4d,c,l,4,1j,2,,7,2,2,2,3,9,,a,2,2,7,3,5,1v,9,,,2,,,4,,5,,,e,2,2a,i,n,,29,k,6j,7,2,9,r,2,2a,h,2y,d,2t,3,2,a,74,f,6t,6,,2,2,4,,,,2,3x,7,2,7,3,,s,a,14,7,,4,8,,9,b,1a,g,5i,8,5j,8,,8,2a,m,,e,3e,6,3,,,2,,7,,,1u,5,,2,,5,9n,4,9,2,,,1c,7,3,5,n,,44l,,6,f,8ug,i,1xc,5,1n,7,t4,,,1j,7,4,29,,b,2,f57,2,3mp,1a,2,n,f2,5,3,6,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,2s,,4g,7,af,,1p,4,e4,4,72,2,6r,,2,,7,2,5,,d6,7,31,7,240,5".split(",").map((s) => s ? parseInt(s, 36) : 1); + for (let i2 = 0, n = 0; i2 < numbers.length; i2++) + (i2 % 2 ? rangeTo : rangeFrom).push(n = n + numbers[i2]); +})(); +function isExtendingChar(code2) { + if (code2 < 768) return false; + for (let from = 0, to = rangeFrom.length; ; ) { + let mid = from + to >> 1; + if (code2 < rangeFrom[mid]) to = mid; + else if (code2 >= rangeTo[mid]) from = mid + 1; + else return true; + if (from == to) return false; + } +} +function isRegionalIndicator(code2) { + return code2 >= 127462 && code2 <= 127487; +} +var ZWJ = 8205; +function findClusterBreak(str, pos, forward = true, includeExtending = true) { + return (forward ? nextClusterBreak : prevClusterBreak)(str, pos, includeExtending); +} +function nextClusterBreak(str, pos, includeExtending) { + if (pos == str.length) return pos; + if (pos && surrogateLow(str.charCodeAt(pos)) && surrogateHigh(str.charCodeAt(pos - 1))) pos--; + let prev = codePointAt(str, pos); + pos += codePointSize(prev); + while (pos < str.length) { + let next = codePointAt(str, pos); + if (prev == ZWJ || next == ZWJ || includeExtending && isExtendingChar(next)) { + pos += codePointSize(next); + prev = next; + } else if (isRegionalIndicator(next)) { + let countBefore = 0, i2 = pos - 2; + while (i2 >= 0 && isRegionalIndicator(codePointAt(str, i2))) { + countBefore++; + i2 -= 2; + } + if (countBefore % 2 == 0) break; + else pos += 2; + } else { + break; + } + } + return pos; +} +function prevClusterBreak(str, pos, includeExtending) { + while (pos > 1) { + let found = nextClusterBreak(str, pos - 2, includeExtending); + if (found < pos) return found; + pos--; + } + return 0; +} +function codePointAt(str, pos) { + let code0 = str.charCodeAt(pos); + if (!surrogateHigh(code0) || pos + 1 == str.length) return code0; + let code1 = str.charCodeAt(pos + 1); + if (!surrogateLow(code1)) return code0; + return (code0 - 55296 << 10) + (code1 - 56320) + 65536; +} +function surrogateLow(ch) { + return ch >= 56320 && ch < 57344; +} +function surrogateHigh(ch) { + return ch >= 55296 && ch < 56320; +} +function codePointSize(code2) { + return code2 < 65536 ? 1 : 2; +} + +// node_modules/@codemirror/state/dist/index.js +var Text = class _Text { + /** + Get the line description around the given position. + */ + lineAt(pos) { + if (pos < 0 || pos > this.length) + throw new RangeError(`Invalid position ${pos} in document of length ${this.length}`); + return this.lineInner(pos, false, 1, 0); + } + /** + Get the description for the given (1-based) line number. + */ + line(n) { + if (n < 1 || n > this.lines) + throw new RangeError(`Invalid line number ${n} in ${this.lines}-line document`); + return this.lineInner(n, true, 1, 0); + } + /** + Replace a range of the text with the given content. + */ + replace(from, to, text) { + [from, to] = clip(this, from, to); + let parts = []; + this.decompose( + 0, + from, + parts, + 2 + /* Open.To */ + ); + if (text.length) + text.decompose( + 0, + text.length, + parts, + 1 | 2 + /* Open.To */ + ); + this.decompose( + to, + this.length, + parts, + 1 + /* Open.From */ + ); + return TextNode.from(parts, this.length - (to - from) + text.length); + } + /** + Append another document to this one. + */ + append(other) { + return this.replace(this.length, this.length, other); + } + /** + Retrieve the text between the given points. + */ + slice(from, to = this.length) { + [from, to] = clip(this, from, to); + let parts = []; + this.decompose(from, to, parts, 0); + return TextNode.from(parts, to - from); + } + /** + Test whether this text is equal to another instance. + */ + eq(other) { + if (other == this) + return true; + if (other.length != this.length || other.lines != this.lines) + return false; + let start = this.scanIdentical(other, 1), end = this.length - this.scanIdentical(other, -1); + let a = new RawTextCursor(this), b = new RawTextCursor(other); + for (let skip = start, pos = start; ; ) { + a.next(skip); + b.next(skip); + skip = 0; + if (a.lineBreak != b.lineBreak || a.done != b.done || a.value != b.value) + return false; + pos += a.value.length; + if (a.done || pos >= end) + return true; + } + } + /** + Iterate over the text. When `dir` is `-1`, iteration happens + from end to start. This will return lines and the breaks between + them as separate strings. + */ + iter(dir = 1) { + return new RawTextCursor(this, dir); + } + /** + Iterate over a range of the text. When `from` > `to`, the + iterator will run in reverse. + */ + iterRange(from, to = this.length) { + return new PartialTextCursor(this, from, to); + } + /** + Return a cursor that iterates over the given range of lines, + _without_ returning the line breaks between, and yielding empty + strings for empty lines. + + When `from` and `to` are given, they should be 1-based line numbers. + */ + iterLines(from, to) { + let inner; + if (from == null) { + inner = this.iter(); + } else { + if (to == null) + to = this.lines + 1; + let start = this.line(from).from; + inner = this.iterRange(start, Math.max(start, to == this.lines + 1 ? this.length : to <= 1 ? 0 : this.line(to - 1).to)); + } + return new LineCursor(inner); + } + /** + Return the document as a string, using newline characters to + separate lines. + */ + toString() { + return this.sliceString(0); + } + /** + Convert the document to an array of lines (which can be + deserialized again via [`Text.of`](https://codemirror.net/6/docs/ref/#state.Text^of)). + */ + toJSON() { + let lines = []; + this.flatten(lines); + return lines; + } + /** + @internal + */ + constructor() { + } + /** + Create a `Text` instance for the given array of lines. + */ + static of(text) { + if (text.length == 0) + throw new RangeError("A document must have at least one line"); + if (text.length == 1 && !text[0]) + return _Text.empty; + return text.length <= 32 ? new TextLeaf(text) : TextNode.from(TextLeaf.split(text, [])); + } +}; +var TextLeaf = class _TextLeaf extends Text { + constructor(text, length = textLength(text)) { + super(); + this.text = text; + this.length = length; + } + get lines() { + return this.text.length; + } + get children() { + return null; + } + lineInner(target, isLine, line, offset) { + for (let i2 = 0; ; i2++) { + let string2 = this.text[i2], end = offset + string2.length; + if ((isLine ? line : end) >= target) + return new Line(offset, end, line, string2); + offset = end + 1; + line++; + } + } + decompose(from, to, target, open) { + let text = from <= 0 && to >= this.length ? this : new _TextLeaf(sliceText(this.text, from, to), Math.min(to, this.length) - Math.max(0, from)); + if (open & 1) { + let prev = target.pop(); + let joined = appendText(text.text, prev.text.slice(), 0, text.length); + if (joined.length <= 32) { + target.push(new _TextLeaf(joined, prev.length + text.length)); + } else { + let mid = joined.length >> 1; + target.push(new _TextLeaf(joined.slice(0, mid)), new _TextLeaf(joined.slice(mid))); + } + } else { + target.push(text); + } + } + replace(from, to, text) { + if (!(text instanceof _TextLeaf)) + return super.replace(from, to, text); + [from, to] = clip(this, from, to); + let lines = appendText(this.text, appendText(text.text, sliceText(this.text, 0, from)), to); + let newLen = this.length + text.length - (to - from); + if (lines.length <= 32) + return new _TextLeaf(lines, newLen); + return TextNode.from(_TextLeaf.split(lines, []), newLen); + } + sliceString(from, to = this.length, lineSep = "\n") { + [from, to] = clip(this, from, to); + let result = ""; + for (let pos = 0, i2 = 0; pos <= to && i2 < this.text.length; i2++) { + let line = this.text[i2], end = pos + line.length; + if (pos > from && i2) + result += lineSep; + if (from < end && to > pos) + result += line.slice(Math.max(0, from - pos), to - pos); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let line of this.text) + target.push(line); + } + scanIdentical() { + return 0; + } + static split(text, target) { + let part = [], len = -1; + for (let line of text) { + part.push(line); + len += line.length + 1; + if (part.length == 32) { + target.push(new _TextLeaf(part, len)); + part = []; + len = -1; + } + } + if (len > -1) + target.push(new _TextLeaf(part, len)); + return target; + } +}; +var TextNode = class _TextNode extends Text { + constructor(children, length) { + super(); + this.children = children; + this.length = length; + this.lines = 0; + for (let child of children) + this.lines += child.lines; + } + lineInner(target, isLine, line, offset) { + for (let i2 = 0; ; i2++) { + let child = this.children[i2], end = offset + child.length, endLine = line + child.lines - 1; + if ((isLine ? endLine : end) >= target) + return child.lineInner(target, isLine, line, offset); + offset = end + 1; + line = endLine + 1; + } + } + decompose(from, to, target, open) { + for (let i2 = 0, pos = 0; pos <= to && i2 < this.children.length; i2++) { + let child = this.children[i2], end = pos + child.length; + if (from <= end && to >= pos) { + let childOpen = open & ((pos <= from ? 1 : 0) | (end >= to ? 2 : 0)); + if (pos >= from && end <= to && !childOpen) + target.push(child); + else + child.decompose(from - pos, to - pos, target, childOpen); + } + pos = end + 1; + } + } + replace(from, to, text) { + [from, to] = clip(this, from, to); + if (text.lines < this.lines) + for (let i2 = 0, pos = 0; i2 < this.children.length; i2++) { + let child = this.children[i2], end = pos + child.length; + if (from >= pos && to <= end) { + let updated = child.replace(from - pos, to - pos, text); + let totalLines = this.lines - child.lines + updated.lines; + if (updated.lines < totalLines >> 5 - 1 && updated.lines > totalLines >> 5 + 1) { + let copy = this.children.slice(); + copy[i2] = updated; + return new _TextNode(copy, this.length - (to - from) + text.length); + } + return super.replace(pos, end, updated); + } + pos = end + 1; + } + return super.replace(from, to, text); + } + sliceString(from, to = this.length, lineSep = "\n") { + [from, to] = clip(this, from, to); + let result = ""; + for (let i2 = 0, pos = 0; i2 < this.children.length && pos <= to; i2++) { + let child = this.children[i2], end = pos + child.length; + if (pos > from && i2) + result += lineSep; + if (from < end && to > pos) + result += child.sliceString(from - pos, to - pos, lineSep); + pos = end + 1; + } + return result; + } + flatten(target) { + for (let child of this.children) + child.flatten(target); + } + scanIdentical(other, dir) { + if (!(other instanceof _TextNode)) + return 0; + let length = 0; + let [iA, iB, eA, eB] = dir > 0 ? [0, 0, this.children.length, other.children.length] : [this.children.length - 1, other.children.length - 1, -1, -1]; + for (; ; iA += dir, iB += dir) { + if (iA == eA || iB == eB) + return length; + let chA = this.children[iA], chB = other.children[iB]; + if (chA != chB) + return length + chA.scanIdentical(chB, dir); + length += chA.length + 1; + } + } + static from(children, length = children.reduce((l, ch) => l + ch.length + 1, -1)) { + let lines = 0; + for (let ch of children) + lines += ch.lines; + if (lines < 32) { + let flat = []; + for (let ch of children) + ch.flatten(flat); + return new TextLeaf(flat, length); + } + let chunk = Math.max( + 32, + lines >> 5 + /* Tree.BranchShift */ + ), maxChunk = chunk << 1, minChunk = chunk >> 1; + let chunked = [], currentLines = 0, currentLen = -1, currentChunk = []; + function add(child) { + let last2; + if (child.lines > maxChunk && child instanceof _TextNode) { + for (let node of child.children) + add(node); + } else if (child.lines > minChunk && (currentLines > minChunk || !currentLines)) { + flush(); + chunked.push(child); + } else if (child instanceof TextLeaf && currentLines && (last2 = currentChunk[currentChunk.length - 1]) instanceof TextLeaf && child.lines + last2.lines <= 32) { + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk[currentChunk.length - 1] = new TextLeaf(last2.text.concat(child.text), last2.length + 1 + child.length); + } else { + if (currentLines + child.lines > chunk) + flush(); + currentLines += child.lines; + currentLen += child.length + 1; + currentChunk.push(child); + } + } + function flush() { + if (currentLines == 0) + return; + chunked.push(currentChunk.length == 1 ? currentChunk[0] : _TextNode.from(currentChunk, currentLen)); + currentLen = -1; + currentLines = currentChunk.length = 0; + } + for (let child of children) + add(child); + flush(); + return chunked.length == 1 ? chunked[0] : new _TextNode(chunked, length); + } +}; +Text.empty = /* @__PURE__ */ new TextLeaf([""], 0); +function textLength(text) { + let length = -1; + for (let line of text) + length += line.length + 1; + return length; +} +function appendText(text, target, from = 0, to = 1e9) { + for (let pos = 0, i2 = 0, first = true; i2 < text.length && pos <= to; i2++) { + let line = text[i2], end = pos + line.length; + if (end >= from) { + if (end > to) + line = line.slice(0, to - pos); + if (pos < from) + line = line.slice(from - pos); + if (first) { + target[target.length - 1] += line; + first = false; + } else + target.push(line); + } + pos = end + 1; + } + return target; +} +function sliceText(text, from, to) { + return appendText(text, [""], from, to); +} +var RawTextCursor = class { + constructor(text, dir = 1) { + this.dir = dir; + this.done = false; + this.lineBreak = false; + this.value = ""; + this.nodes = [text]; + this.offsets = [dir > 0 ? 1 : (text instanceof TextLeaf ? text.text.length : text.children.length) << 1]; + } + nextInner(skip, dir) { + this.done = this.lineBreak = false; + for (; ; ) { + let last2 = this.nodes.length - 1; + let top2 = this.nodes[last2], offsetValue = this.offsets[last2], offset = offsetValue >> 1; + let size = top2 instanceof TextLeaf ? top2.text.length : top2.children.length; + if (offset == (dir > 0 ? size : 0)) { + if (last2 == 0) { + this.done = true; + this.value = ""; + return this; + } + if (dir > 0) + this.offsets[last2 - 1]++; + this.nodes.pop(); + this.offsets.pop(); + } else if ((offsetValue & 1) == (dir > 0 ? 0 : 1)) { + this.offsets[last2] += dir; + if (skip == 0) { + this.lineBreak = true; + this.value = "\n"; + return this; + } + skip--; + } else if (top2 instanceof TextLeaf) { + let next = top2.text[offset + (dir < 0 ? -1 : 0)]; + this.offsets[last2] += dir; + if (next.length > Math.max(0, skip)) { + this.value = skip == 0 ? next : dir > 0 ? next.slice(skip) : next.slice(0, next.length - skip); + return this; + } + skip -= next.length; + } else { + let next = top2.children[offset + (dir < 0 ? -1 : 0)]; + if (skip > next.length) { + skip -= next.length; + this.offsets[last2] += dir; + } else { + if (dir < 0) + this.offsets[last2]--; + this.nodes.push(next); + this.offsets.push(dir > 0 ? 1 : (next instanceof TextLeaf ? next.text.length : next.children.length) << 1); + } + } + } + } + next(skip = 0) { + if (skip < 0) { + this.nextInner(-skip, -this.dir); + skip = this.value.length; + } + return this.nextInner(skip, this.dir); + } +}; +var PartialTextCursor = class { + constructor(text, start, end) { + this.value = ""; + this.done = false; + this.cursor = new RawTextCursor(text, start > end ? -1 : 1); + this.pos = start > end ? text.length : 0; + this.from = Math.min(start, end); + this.to = Math.max(start, end); + } + nextInner(skip, dir) { + if (dir < 0 ? this.pos <= this.from : this.pos >= this.to) { + this.value = ""; + this.done = true; + return this; + } + skip += Math.max(0, dir < 0 ? this.pos - this.to : this.from - this.pos); + let limit = dir < 0 ? this.pos - this.from : this.to - this.pos; + if (skip > limit) + skip = limit; + limit -= skip; + let { value } = this.cursor.next(skip); + this.pos += (value.length + skip) * dir; + this.value = value.length <= limit ? value : dir < 0 ? value.slice(value.length - limit) : value.slice(0, limit); + this.done = !this.value; + return this; + } + next(skip = 0) { + if (skip < 0) + skip = Math.max(skip, this.from - this.pos); + else if (skip > 0) + skip = Math.min(skip, this.to - this.pos); + return this.nextInner(skip, this.cursor.dir); + } + get lineBreak() { + return this.cursor.lineBreak && this.value != ""; + } +}; +var LineCursor = class { + constructor(inner) { + this.inner = inner; + this.afterBreak = true; + this.value = ""; + this.done = false; + } + next(skip = 0) { + let { done, lineBreak, value } = this.inner.next(skip); + if (done && this.afterBreak) { + this.value = ""; + this.afterBreak = false; + } else if (done) { + this.done = true; + this.value = ""; + } else if (lineBreak) { + if (this.afterBreak) { + this.value = ""; + } else { + this.afterBreak = true; + this.next(); + } + } else { + this.value = value; + this.afterBreak = false; + } + return this; + } + get lineBreak() { + return false; + } +}; +if (typeof Symbol != "undefined") { + Text.prototype[Symbol.iterator] = function() { + return this.iter(); + }; + RawTextCursor.prototype[Symbol.iterator] = PartialTextCursor.prototype[Symbol.iterator] = LineCursor.prototype[Symbol.iterator] = function() { + return this; + }; +} +var Line = class { + /** + @internal + */ + constructor(from, to, number2, text) { + this.from = from; + this.to = to; + this.number = number2; + this.text = text; + } + /** + The length of the line (not including any line break after it). + */ + get length() { + return this.to - this.from; + } +}; +function clip(text, from, to) { + from = Math.max(0, Math.min(text.length, from)); + return [from, Math.max(from, Math.min(text.length, to))]; +} +function findClusterBreak2(str, pos, forward = true, includeExtending = true) { + return findClusterBreak(str, pos, forward, includeExtending); +} +function surrogateLow2(ch) { + return ch >= 56320 && ch < 57344; +} +function surrogateHigh2(ch) { + return ch >= 55296 && ch < 56320; +} +function codePointAt2(str, pos) { + let code0 = str.charCodeAt(pos); + if (!surrogateHigh2(code0) || pos + 1 == str.length) + return code0; + let code1 = str.charCodeAt(pos + 1); + if (!surrogateLow2(code1)) + return code0; + return (code0 - 55296 << 10) + (code1 - 56320) + 65536; +} +function codePointSize2(code2) { + return code2 < 65536 ? 1 : 2; +} +var DefaultSplit = /\r\n?|\n/; +var MapMode = /* @__PURE__ */ (function(MapMode2) { + MapMode2[MapMode2["Simple"] = 0] = "Simple"; + MapMode2[MapMode2["TrackDel"] = 1] = "TrackDel"; + MapMode2[MapMode2["TrackBefore"] = 2] = "TrackBefore"; + MapMode2[MapMode2["TrackAfter"] = 3] = "TrackAfter"; + return MapMode2; +})(MapMode || (MapMode = {})); +var ChangeDesc = class _ChangeDesc { + // Sections are encoded as pairs of integers. The first is the + // length in the current document, and the second is -1 for + // unaffected sections, and the length of the replacement content + // otherwise. So an insertion would be (0, n>0), a deletion (n>0, + // 0), and a replacement two positive numbers. + /** + @internal + */ + constructor(sections) { + this.sections = sections; + } + /** + The length of the document before the change. + */ + get length() { + let result = 0; + for (let i2 = 0; i2 < this.sections.length; i2 += 2) + result += this.sections[i2]; + return result; + } + /** + The length of the document after the change. + */ + get newLength() { + let result = 0; + for (let i2 = 0; i2 < this.sections.length; i2 += 2) { + let ins = this.sections[i2 + 1]; + result += ins < 0 ? this.sections[i2] : ins; + } + return result; + } + /** + False when there are actual changes in this set. + */ + get empty() { + return this.sections.length == 0 || this.sections.length == 2 && this.sections[1] < 0; + } + /** + Iterate over the unchanged parts left by these changes. `posA` + provides the position of the range in the old document, `posB` + the new position in the changed document. + */ + iterGaps(f) { + for (let i2 = 0, posA = 0, posB = 0; i2 < this.sections.length; ) { + let len = this.sections[i2++], ins = this.sections[i2++]; + if (ins < 0) { + f(posA, posB, len); + posB += len; + } else { + posB += ins; + } + posA += len; + } + } + /** + Iterate over the ranges changed by these changes. (See + [`ChangeSet.iterChanges`](https://codemirror.net/6/docs/ref/#state.ChangeSet.iterChanges) for a + variant that also provides you with the inserted text.) + `fromA`/`toA` provides the extent of the change in the starting + document, `fromB`/`toB` the extent of the replacement in the + changed document. + + When `individual` is true, adjacent changes (which are kept + separate for [position mapping](https://codemirror.net/6/docs/ref/#state.ChangeDesc.mapPos)) are + reported separately. + */ + iterChangedRanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a description of the inverted form of these changes. + */ + get invertedDesc() { + let sections = []; + for (let i2 = 0; i2 < this.sections.length; ) { + let len = this.sections[i2++], ins = this.sections[i2++]; + if (ins < 0) + sections.push(len, ins); + else + sections.push(ins, len); + } + return new _ChangeDesc(sections); + } + /** + Compute the combined effect of applying another set of changes + after this one. The length of the document after this set should + match the length before `other`. + */ + composeDesc(other) { + return this.empty ? other : other.empty ? this : composeSets(this, other); + } + /** + Map this description, which should start with the same document + as `other`, over another set of changes, so that it can be + applied after it. When `before` is true, map as if the changes + in `this` happened before the ones in `other`. + */ + mapDesc(other, before = false) { + return other.empty ? this : mapSet(this, other, before); + } + mapPos(pos, assoc = -1, mode = MapMode.Simple) { + let posA = 0, posB = 0; + for (let i2 = 0; i2 < this.sections.length; ) { + let len = this.sections[i2++], ins = this.sections[i2++], endA = posA + len; + if (ins < 0) { + if (endA > pos) + return posB + (pos - posA); + posB += len; + } else { + if (mode != MapMode.Simple && endA >= pos && (mode == MapMode.TrackDel && posA < pos && endA > pos || mode == MapMode.TrackBefore && posA < pos || mode == MapMode.TrackAfter && endA > pos)) + return null; + if (endA > pos || endA == pos && assoc < 0 && !len) + return pos == posA || assoc < 0 ? posB : posB + ins; + posB += ins; + } + posA = endA; + } + if (pos > posA) + throw new RangeError(`Position ${pos} is out of range for changeset of length ${posA}`); + return posB; + } + /** + Check whether these changes touch a given range. When one of the + changes entirely covers the range, the string `"cover"` is + returned. + */ + touchesRange(from, to = from) { + for (let i2 = 0, pos = 0; i2 < this.sections.length && pos <= to; ) { + let len = this.sections[i2++], ins = this.sections[i2++], end = pos + len; + if (ins >= 0 && pos <= to && end >= from) + return pos < from && end > to ? "cover" : true; + pos = end; + } + return false; + } + /** + @internal + */ + toString() { + let result = ""; + for (let i2 = 0; i2 < this.sections.length; ) { + let len = this.sections[i2++], ins = this.sections[i2++]; + result += (result ? " " : "") + len + (ins >= 0 ? ":" + ins : ""); + } + return result; + } + /** + Serialize this change desc to a JSON-representable value. + */ + toJSON() { + return this.sections; + } + /** + Create a change desc from its JSON representation (as produced + by [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeDesc.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json) || json.length % 2 || json.some((a) => typeof a != "number")) + throw new RangeError("Invalid JSON representation of ChangeDesc"); + return new _ChangeDesc(json); + } + /** + @internal + */ + static create(sections) { + return new _ChangeDesc(sections); + } +}; +var ChangeSet = class _ChangeSet extends ChangeDesc { + constructor(sections, inserted) { + super(sections); + this.inserted = inserted; + } + /** + Apply the changes to a document, returning the modified + document. + */ + apply(doc2) { + if (this.length != doc2.length) + throw new RangeError("Applying change set to a document with the wrong length"); + iterChanges(this, (fromA, toA, fromB, _toB, text) => doc2 = doc2.replace(fromB, fromB + (toA - fromA), text), false); + return doc2; + } + mapDesc(other, before = false) { + return mapSet(this, other, before, true); + } + /** + Given the document as it existed _before_ the changes, return a + change set that represents the inverse of this set, which could + be used to go from the document created by the changes back to + the document as it existed before the changes. + */ + invert(doc2) { + let sections = this.sections.slice(), inserted = []; + for (let i2 = 0, pos = 0; i2 < sections.length; i2 += 2) { + let len = sections[i2], ins = sections[i2 + 1]; + if (ins >= 0) { + sections[i2] = ins; + sections[i2 + 1] = len; + let index = i2 >> 1; + while (inserted.length < index) + inserted.push(Text.empty); + inserted.push(len ? doc2.slice(pos, pos + len) : Text.empty); + } + pos += len; + } + return new _ChangeSet(sections, inserted); + } + /** + Combine two subsequent change sets into a single set. `other` + must start in the document produced by `this`. If `this` goes + `docA` → `docB` and `other` represents `docB` → `docC`, the + returned value will represent the change `docA` → `docC`. + */ + compose(other) { + return this.empty ? other : other.empty ? this : composeSets(this, other, true); + } + /** + Given another change set starting in the same document, maps this + change set over the other, producing a new change set that can be + applied to the document produced by applying `other`. When + `before` is `true`, order changes as if `this` comes before + `other`, otherwise (the default) treat `other` as coming first. + + Given two changes `A` and `B`, `A.compose(B.map(A))` and + `B.compose(A.map(B, true))` will produce the same document. This + provides a basic form of [operational + transformation](https://en.wikipedia.org/wiki/Operational_transformation), + and can be used for collaborative editing. + */ + map(other, before = false) { + return other.empty ? this : mapSet(this, other, before, true); + } + /** + Iterate over the changed ranges in the document, calling `f` for + each, with the range in the original document (`fromA`-`toA`) + and the range that replaces it in the new document + (`fromB`-`toB`). + + When `individual` is true, adjacent changes are reported + separately. + */ + iterChanges(f, individual = false) { + iterChanges(this, f, individual); + } + /** + Get a [change description](https://codemirror.net/6/docs/ref/#state.ChangeDesc) for this change + set. + */ + get desc() { + return ChangeDesc.create(this.sections); + } + /** + @internal + */ + filter(ranges) { + let resultSections = [], resultInserted = [], filteredSections = []; + let iter = new SectionIter(this); + done: for (let i2 = 0, pos = 0; ; ) { + let next = i2 == ranges.length ? 1e9 : ranges[i2++]; + while (pos < next || pos == next && iter.len == 0) { + if (iter.done) + break done; + let len = Math.min(iter.len, next - pos); + addSection(filteredSections, len, -1); + let ins = iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0; + addSection(resultSections, len, ins); + if (ins > 0) + addInsert(resultInserted, resultSections, iter.text); + iter.forward(len); + pos += len; + } + let end = ranges[i2++]; + while (pos < end) { + if (iter.done) + break done; + let len = Math.min(iter.len, end - pos); + addSection(resultSections, len, -1); + addSection(filteredSections, len, iter.ins == -1 ? -1 : iter.off == 0 ? iter.ins : 0); + iter.forward(len); + pos += len; + } + } + return { + changes: new _ChangeSet(resultSections, resultInserted), + filtered: ChangeDesc.create(filteredSections) + }; + } + /** + Serialize this change set to a JSON-representable value. + */ + toJSON() { + let parts = []; + for (let i2 = 0; i2 < this.sections.length; i2 += 2) { + let len = this.sections[i2], ins = this.sections[i2 + 1]; + if (ins < 0) + parts.push(len); + else if (ins == 0) + parts.push([len]); + else + parts.push([len].concat(this.inserted[i2 >> 1].toJSON())); + } + return parts; + } + /** + Create a change set for the given changes, for a document of the + given length, using `lineSep` as line separator. + */ + static of(changes, length, lineSep) { + let sections = [], inserted = [], pos = 0; + let total = null; + function flush(force = false) { + if (!force && !sections.length) + return; + if (pos < length) + addSection(sections, length - pos, -1); + let set = new _ChangeSet(sections, inserted); + total = total ? total.compose(set.map(total)) : set; + sections = []; + inserted = []; + pos = 0; + } + function process(spec) { + if (Array.isArray(spec)) { + for (let sub of spec) + process(sub); + } else if (spec instanceof _ChangeSet) { + if (spec.length != length) + throw new RangeError(`Mismatched change set length (got ${spec.length}, expected ${length})`); + flush(); + total = total ? total.compose(spec.map(total)) : spec; + } else { + let { from, to = from, insert: insert2 } = spec; + if (from > to || from < 0 || to > length) + throw new RangeError(`Invalid change range ${from} to ${to} (in doc of length ${length})`); + let insText = !insert2 ? Text.empty : typeof insert2 == "string" ? Text.of(insert2.split(lineSep || DefaultSplit)) : insert2; + let insLen = insText.length; + if (from == to && insLen == 0) + return; + if (from < pos) + flush(); + if (from > pos) + addSection(sections, from - pos, -1); + addSection(sections, to - from, insLen); + addInsert(inserted, sections, insText); + pos = to; + } + } + process(changes); + flush(!total); + return total; + } + /** + Create an empty changeset of the given length. + */ + static empty(length) { + return new _ChangeSet(length ? [length, -1] : [], []); + } + /** + Create a changeset from its JSON representation (as produced by + [`toJSON`](https://codemirror.net/6/docs/ref/#state.ChangeSet.toJSON). + */ + static fromJSON(json) { + if (!Array.isArray(json)) + throw new RangeError("Invalid JSON representation of ChangeSet"); + let sections = [], inserted = []; + for (let i2 = 0; i2 < json.length; i2++) { + let part = json[i2]; + if (typeof part == "number") { + sections.push(part, -1); + } else if (!Array.isArray(part) || typeof part[0] != "number" || part.some((e, i3) => i3 && typeof e != "string")) { + throw new RangeError("Invalid JSON representation of ChangeSet"); + } else if (part.length == 1) { + sections.push(part[0], 0); + } else { + while (inserted.length < i2) + inserted.push(Text.empty); + inserted[i2] = Text.of(part.slice(1)); + sections.push(part[0], inserted[i2].length); + } + } + return new _ChangeSet(sections, inserted); + } + /** + @internal + */ + static createSet(sections, inserted) { + return new _ChangeSet(sections, inserted); + } +}; +function addSection(sections, len, ins, forceJoin = false) { + if (len == 0 && ins <= 0) + return; + let last2 = sections.length - 2; + if (last2 >= 0 && ins <= 0 && ins == sections[last2 + 1]) + sections[last2] += len; + else if (last2 >= 0 && len == 0 && sections[last2] == 0) + sections[last2 + 1] += ins; + else if (forceJoin) { + sections[last2] += len; + sections[last2 + 1] += ins; + } else + sections.push(len, ins); +} +function addInsert(values, sections, value) { + if (value.length == 0) + return; + let index = sections.length - 2 >> 1; + if (index < values.length) { + values[values.length - 1] = values[values.length - 1].append(value); + } else { + while (values.length < index) + values.push(Text.empty); + values.push(value); + } +} +function iterChanges(desc, f, individual) { + let inserted = desc.inserted; + for (let posA = 0, posB = 0, i2 = 0; i2 < desc.sections.length; ) { + let len = desc.sections[i2++], ins = desc.sections[i2++]; + if (ins < 0) { + posA += len; + posB += len; + } else { + let endA = posA, endB = posB, text = Text.empty; + for (; ; ) { + endA += len; + endB += ins; + if (ins && inserted) + text = text.append(inserted[i2 - 2 >> 1]); + if (individual || i2 == desc.sections.length || desc.sections[i2 + 1] < 0) + break; + len = desc.sections[i2++]; + ins = desc.sections[i2++]; + } + f(posA, endA, posB, endB, text); + posA = endA; + posB = endB; + } + } +} +function mapSet(setA, setB, before, mkSet = false) { + let sections = [], insert2 = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + for (let inserted = -1; ; ) { + if (a.done && b.len || b.done && a.len) { + throw new Error("Mismatched change set lengths"); + } else if (a.ins == -1 && b.ins == -1) { + let len = Math.min(a.len, b.len); + addSection(sections, len, -1); + a.forward(len); + b.forward(len); + } else if (b.ins >= 0 && (a.ins < 0 || inserted == a.i || a.off == 0 && (b.len < a.len || b.len == a.len && !before))) { + let len = b.len; + addSection(sections, b.ins, -1); + while (len) { + let piece = Math.min(a.len, len); + if (a.ins >= 0 && inserted < a.i && a.len <= piece) { + addSection(sections, 0, a.ins); + if (insert2) + addInsert(insert2, sections, a.text); + inserted = a.i; + } + a.forward(piece); + len -= piece; + } + b.next(); + } else if (a.ins >= 0) { + let len = 0, left = a.len; + while (left) { + if (b.ins == -1) { + let piece = Math.min(left, b.len); + len += piece; + left -= piece; + b.forward(piece); + } else if (b.ins == 0 && b.len < left) { + left -= b.len; + b.next(); + } else { + break; + } + } + addSection(sections, len, inserted < a.i ? a.ins : 0); + if (insert2 && inserted < a.i) + addInsert(insert2, sections, a.text); + inserted = a.i; + a.forward(a.len - left); + } else if (a.done && b.done) { + return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections); + } else { + throw new Error("Mismatched change set lengths"); + } + } +} +function composeSets(setA, setB, mkSet = false) { + let sections = []; + let insert2 = mkSet ? [] : null; + let a = new SectionIter(setA), b = new SectionIter(setB); + for (let open = false; ; ) { + if (a.done && b.done) { + return insert2 ? ChangeSet.createSet(sections, insert2) : ChangeDesc.create(sections); + } else if (a.ins == 0) { + addSection(sections, a.len, 0, open); + a.next(); + } else if (b.len == 0 && !b.done) { + addSection(sections, 0, b.ins, open); + if (insert2) + addInsert(insert2, sections, b.text); + b.next(); + } else if (a.done || b.done) { + throw new Error("Mismatched change set lengths"); + } else { + let len = Math.min(a.len2, b.len), sectionLen = sections.length; + if (a.ins == -1) { + let insB = b.ins == -1 ? -1 : b.off ? 0 : b.ins; + addSection(sections, len, insB, open); + if (insert2 && insB) + addInsert(insert2, sections, b.text); + } else if (b.ins == -1) { + addSection(sections, a.off ? 0 : a.len, len, open); + if (insert2) + addInsert(insert2, sections, a.textBit(len)); + } else { + addSection(sections, a.off ? 0 : a.len, b.off ? 0 : b.ins, open); + if (insert2 && !b.off) + addInsert(insert2, sections, b.text); + } + open = (a.ins > len || b.ins >= 0 && b.len > len) && (open || sections.length > sectionLen); + a.forward2(len); + b.forward(len); + } + } +} +var SectionIter = class { + constructor(set) { + this.set = set; + this.i = 0; + this.next(); + } + next() { + let { sections } = this.set; + if (this.i < sections.length) { + this.len = sections[this.i++]; + this.ins = sections[this.i++]; + } else { + this.len = 0; + this.ins = -2; + } + this.off = 0; + } + get done() { + return this.ins == -2; + } + get len2() { + return this.ins < 0 ? this.len : this.ins; + } + get text() { + let { inserted } = this.set, index = this.i - 2 >> 1; + return index >= inserted.length ? Text.empty : inserted[index]; + } + textBit(len) { + let { inserted } = this.set, index = this.i - 2 >> 1; + return index >= inserted.length && !len ? Text.empty : inserted[index].slice(this.off, len == null ? void 0 : this.off + len); + } + forward(len) { + if (len == this.len) + this.next(); + else { + this.len -= len; + this.off += len; + } + } + forward2(len) { + if (this.ins == -1) + this.forward(len); + else if (len == this.ins) + this.next(); + else { + this.ins -= len; + this.off += len; + } + } +}; +var SelectionRange = class _SelectionRange { + constructor(from, to, flags, goalColumn) { + this.from = from; + this.to = to; + this.flags = flags; + this.goalColumn = goalColumn; + } + /** + The anchor of the range—the side that doesn't move when you + extend it. + */ + get anchor() { + return this.flags & 32 ? this.to : this.from; + } + /** + The head of the range, which is moved when the range is + [extended](https://codemirror.net/6/docs/ref/#state.SelectionRange.extend). + */ + get head() { + return this.flags & 32 ? this.from : this.to; + } + /** + True when `anchor` and `head` are at the same position. + */ + get empty() { + return this.from == this.to; + } + /** + If this is a cursor that is explicitly associated with the + character on one of its sides, this returns the side. -1 means + the character before its position, 1 the character after, and 0 + means no association. + */ + get assoc() { + return this.flags & 8 ? -1 : this.flags & 16 ? 1 : 0; + } + /** + A flag that, when set, makes some selection-extending commands + treat the range's head and anchor as exchangeable, so that for + example Shift-ArrowUp will make the lower side of the selection + the anchor, even if that was the head before. Used to implement + MacOS-style undirectional selections. + */ + get undirectional() { + return (this.flags & 64) > 0; + } + /** + The bidirectional text level associated with this cursor, if + any. + */ + get bidiLevel() { + let level = this.flags & 7; + return level == 7 ? null : level; + } + /** + Map this range through a change, producing a valid range in the + updated document. + */ + map(change, assoc = -1) { + let from, to; + if (this.empty) { + from = to = change.mapPos(this.from, assoc); + } else { + from = change.mapPos(this.from, 1); + to = change.mapPos(this.to, -1); + } + return from == this.from && to == this.to ? this : new _SelectionRange(from, to, this.flags, this.goalColumn); + } + /** + Extend this range to cover at least `from` to `to`. + */ + extend(from, to = from, assoc = 0) { + if (from <= this.anchor && to >= this.anchor) + return EditorSelection.range(from, to, void 0, void 0, assoc); + let head = Math.abs(from - this.anchor) > Math.abs(to - this.anchor) ? from : to; + return EditorSelection.range(this.anchor, head, void 0, void 0, assoc); + } + /** + Compare this range to another range. + */ + eq(other, includeAssoc = false) { + return this.anchor == other.anchor && this.head == other.head && this.goalColumn == other.goalColumn && (!includeAssoc || !this.empty || this.assoc == other.assoc); + } + /** + Return a JSON-serializable object representing the range. + */ + toJSON() { + return { anchor: this.anchor, head: this.head }; + } + /** + Convert a JSON representation of a range to a `SelectionRange` + instance. + */ + static fromJSON(json) { + if (!json || typeof json.anchor != "number" || typeof json.head != "number") + throw new RangeError("Invalid JSON representation for SelectionRange"); + return EditorSelection.range(json.anchor, json.head); + } + /** + @internal + */ + static create(from, to, flags, goalColumn) { + return new _SelectionRange(from, to, flags, goalColumn); + } +}; +var EditorSelection = class _EditorSelection { + constructor(ranges, mainIndex) { + this.ranges = ranges; + this.mainIndex = mainIndex; + } + /** + Map a selection through a change. Used to adjust the selection + position for changes. + */ + map(change, assoc = -1) { + if (change.empty) + return this; + return _EditorSelection.create(this.ranges.map((r) => r.map(change, assoc)), this.mainIndex); + } + /** + Compare this selection to another selection. By default, ranges + are compared only by position. When `includeAssoc` is true, + cursor ranges must also have the same + [`assoc`](https://codemirror.net/6/docs/ref/#state.SelectionRange.assoc) value. + */ + eq(other, includeAssoc = false) { + if (this.ranges.length != other.ranges.length || this.mainIndex != other.mainIndex) + return false; + for (let i2 = 0; i2 < this.ranges.length; i2++) + if (!this.ranges[i2].eq(other.ranges[i2], includeAssoc)) + return false; + return true; + } + /** + Get the primary selection range. Usually, you should make sure + your code applies to _all_ ranges, by using methods like + [`changeByRange`](https://codemirror.net/6/docs/ref/#state.EditorState.changeByRange). + */ + get main() { + return this.ranges[this.mainIndex]; + } + /** + Make sure the selection only has one range. Returns a selection + holding only the main range from this selection. + */ + asSingle() { + return this.ranges.length == 1 ? this : new _EditorSelection([this.main], 0); + } + /** + Extend this selection with an extra range. + */ + addRange(range, main = true) { + return _EditorSelection.create([range].concat(this.ranges), main ? 0 : this.mainIndex + 1); + } + /** + Replace a given range with another range, and then normalize the + selection to merge and sort ranges if necessary. + */ + replaceRange(range, which = this.mainIndex) { + let ranges = this.ranges.slice(); + ranges[which] = range; + return _EditorSelection.create(ranges, this.mainIndex); + } + /** + Convert this selection to an object that can be serialized to + JSON. + */ + toJSON() { + return { ranges: this.ranges.map((r) => r.toJSON()), main: this.mainIndex }; + } + /** + Create a selection from a JSON representation. + */ + static fromJSON(json) { + if (!json || !Array.isArray(json.ranges) || typeof json.main != "number" || json.main >= json.ranges.length) + throw new RangeError("Invalid JSON representation for EditorSelection"); + return new _EditorSelection(json.ranges.map((r) => SelectionRange.fromJSON(r)), json.main); + } + /** + Create a selection holding a single range. + */ + static single(anchor, head = anchor) { + return new _EditorSelection([_EditorSelection.range(anchor, head)], 0); + } + /** + Sort and merge the given set of ranges, creating a valid + selection. + */ + static create(ranges, mainIndex = 0) { + if (ranges.length == 0) + throw new RangeError("A selection needs at least one range"); + for (let pos = 0, i2 = 0; i2 < ranges.length; i2++) { + let range = ranges[i2]; + if (range.empty ? range.from <= pos : range.from < pos) + return _EditorSelection.normalized(ranges.slice(), mainIndex); + pos = range.to; + } + return new _EditorSelection(ranges, mainIndex); + } + /** + Create a cursor selection range at the given position. You can + safely ignore the optional arguments in most situations. + */ + static cursor(pos, assoc = 0, bidiLevel, goalColumn) { + return SelectionRange.create(pos, pos, (assoc == 0 ? 0 : assoc < 0 ? 8 : 16) | (bidiLevel == null ? 7 : Math.min(6, bidiLevel)), goalColumn); + } + /** + Create a selection range. + */ + static range(anchor, head, goalColumn, bidiLevel, assoc) { + let flags = bidiLevel == null ? 7 : Math.min(6, bidiLevel); + if (!assoc && anchor != head) + assoc = head < anchor ? 1 : -1; + if (assoc) + flags |= assoc < 0 ? 8 : 16; + return head < anchor ? SelectionRange.create(head, anchor, flags | 32, goalColumn) : SelectionRange.create(anchor, head, flags, goalColumn); + } + /** + Create an [undirectional](https://codemirror.net/6/docs/ref/#state.SelectionRange.undirectional) + selection range. + */ + static undirectionalRange(from, to) { + return SelectionRange.create(from, to, 64, void 0); + } + /** + @internal + */ + static normalized(ranges, mainIndex = 0) { + let main = ranges[mainIndex]; + ranges.sort((a, b) => a.from - b.from); + mainIndex = ranges.indexOf(main); + for (let i2 = 1; i2 < ranges.length; i2++) { + let range = ranges[i2], prev = ranges[i2 - 1]; + if (range.empty ? range.from <= prev.to : range.from < prev.to) { + let from = prev.from, to = Math.max(range.to, prev.to); + if (i2 <= mainIndex) + mainIndex--; + ranges.splice(--i2, 2, range.anchor > range.head ? _EditorSelection.range(to, from) : _EditorSelection.range(from, to)); + } + } + return new _EditorSelection(ranges, mainIndex); + } +}; +function checkSelection(selection, docLength) { + for (let range of selection.ranges) + if (range.to > docLength) + throw new RangeError("Selection points outside of document"); +} +var nextID = 0; +var Facet = class _Facet { + constructor(combine, compareInput, compare2, isStatic, enables) { + this.combine = combine; + this.compareInput = compareInput; + this.compare = compare2; + this.isStatic = isStatic; + this.id = nextID++; + this.default = combine([]); + this.extensions = typeof enables == "function" ? enables(this) : enables; + } + /** + Returns a facet reader for this facet, which can be used to + [read](https://codemirror.net/6/docs/ref/#state.EditorState.facet) it but not to define values for it. + */ + get reader() { + return this; + } + /** + Define a new facet. + */ + static define(config = {}) { + return new _Facet(config.combine || ((a) => a), config.compareInput || ((a, b) => a === b), config.compare || (!config.combine ? sameArray : (a, b) => a === b), !!config.static, config.enables); + } + /** + Returns an extension that adds the given value to this facet. + */ + of(value) { + return new FacetProvider([], this, 0, value); + } + /** + Create an extension that computes a value for the facet from a + state. You must take care to declare the parts of the state that + this value depends on, since your function is only called again + for a new state when one of those parts changed. + + In cases where your value depends only on a single field, you'll + want to use the [`from`](https://codemirror.net/6/docs/ref/#state.Facet.from) method instead. + */ + compute(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 1, get); + } + /** + Create an extension that computes zero or more values for this + facet from a state. + */ + computeN(deps, get) { + if (this.isStatic) + throw new Error("Can't compute a static facet"); + return new FacetProvider(deps, this, 2, get); + } + from(field, get) { + if (!get) + get = (x) => x; + return this.compute([field], (state) => get(state.field(field))); + } +}; +function sameArray(a, b) { + return a == b || a.length == b.length && a.every((e, i2) => e === b[i2]); +} +var FacetProvider = class { + constructor(dependencies, facet, type, value) { + this.dependencies = dependencies; + this.facet = facet; + this.type = type; + this.value = value; + this.id = nextID++; + } + dynamicSlot(addresses) { + var _a2; + let getter = this.value; + let compare2 = this.facet.compareInput; + let id = this.id, idx = addresses[id] >> 1, multi = this.type == 2; + let depDoc = false, depSel = false, depAddrs = []; + for (let dep of this.dependencies) { + if (dep == "doc") + depDoc = true; + else if (dep == "selection") + depSel = true; + else if ((((_a2 = addresses[dep.id]) !== null && _a2 !== void 0 ? _a2 : 1) & 1) == 0) + depAddrs.push(addresses[dep.id]); + } + return { + create(state) { + state.values[idx] = getter(state); + return 1; + }, + update(state, tr) { + if (depDoc && tr.docChanged || depSel && (tr.docChanged || tr.selection) || ensureAll(state, depAddrs)) { + let newVal = getter(state); + if (multi ? !compareArray(newVal, state.values[idx], compare2) : !compare2(newVal, state.values[idx])) { + state.values[idx] = newVal; + return 1; + } + } + return 0; + }, + reconfigure: (state, oldState) => { + let newVal, oldAddr = oldState.config.address[id]; + if (oldAddr != null) { + let oldVal = getAddr(oldState, oldAddr); + if (this.dependencies.every((dep) => { + return dep instanceof Facet ? oldState.facet(dep) === state.facet(dep) : dep instanceof StateField ? oldState.field(dep, false) == state.field(dep, false) : true; + }) || (multi ? compareArray(newVal = getter(state), oldVal, compare2) : compare2(newVal = getter(state), oldVal))) { + state.values[idx] = oldVal; + return 0; + } + } else { + newVal = getter(state); + } + state.values[idx] = newVal; + return 1; + } + }; + } + get extension() { + return this; + } +}; +function compareArray(a, b, compare2) { + if (a.length != b.length) + return false; + for (let i2 = 0; i2 < a.length; i2++) + if (!compare2(a[i2], b[i2])) + return false; + return true; +} +function ensureAll(state, addrs) { + let changed = false; + for (let addr of addrs) + if (ensureAddr(state, addr) & 1) + changed = true; + return changed; +} +function dynamicFacetSlot(addresses, facet, providers) { + let providerAddrs = providers.map((p) => addresses[p.id]); + let providerTypes = providers.map((p) => p.type); + let dynamic = providerAddrs.filter((p) => !(p & 1)); + let idx = addresses[facet.id] >> 1; + function get(state) { + let values = []; + for (let i2 = 0; i2 < providerAddrs.length; i2++) { + let value = getAddr(state, providerAddrs[i2]); + if (providerTypes[i2] == 2) + for (let val of value) + values.push(val); + else + values.push(value); + } + return facet.combine(values); + } + return { + create(state) { + for (let addr of providerAddrs) + ensureAddr(state, addr); + state.values[idx] = get(state); + return 1; + }, + update(state, tr) { + if (!ensureAll(state, dynamic)) + return 0; + let value = get(state); + if (facet.compare(value, state.values[idx])) + return 0; + state.values[idx] = value; + return 1; + }, + reconfigure(state, oldState) { + let depChanged = ensureAll(state, providerAddrs); + let oldProviders = oldState.config.facets[facet.id], oldValue = oldState.facet(facet); + if (oldProviders && !depChanged && sameArray(providers, oldProviders)) { + state.values[idx] = oldValue; + return 0; + } + let value = get(state); + if (facet.compare(value, oldValue)) { + state.values[idx] = oldValue; + return 0; + } + state.values[idx] = value; + return 1; + } + }; +} +var initField = /* @__PURE__ */ Facet.define({ static: true }); +var StateField = class _StateField { + constructor(id, createF, updateF, compareF, spec) { + this.id = id; + this.createF = createF; + this.updateF = updateF; + this.compareF = compareF; + this.spec = spec; + this.provides = void 0; + } + /** + Define a state field. + */ + static define(config) { + let field = new _StateField(nextID++, config.create, config.update, config.compare || ((a, b) => a === b), config); + if (config.provide) + field.provides = config.provide(field); + return field; + } + create(state) { + let init = state.facet(initField).find((i2) => i2.field == this); + return ((init === null || init === void 0 ? void 0 : init.create) || this.createF)(state); + } + /** + @internal + */ + slot(addresses) { + let idx = addresses[this.id] >> 1; + return { + create: (state) => { + state.values[idx] = this.create(state); + return 1; + }, + update: (state, tr) => { + let oldVal = state.values[idx]; + let value = this.updateF(oldVal, tr); + if (this.compareF(oldVal, value)) + return 0; + state.values[idx] = value; + return 1; + }, + reconfigure: (state, oldState) => { + let init = state.facet(initField), oldInit = oldState.facet(initField), reInit; + if ((reInit = init.find((i2) => i2.field == this)) && reInit != oldInit.find((i2) => i2.field == this)) { + state.values[idx] = reInit.create(state); + return 1; + } + if (oldState.config.address[this.id] != null) { + state.values[idx] = oldState.field(this); + return 0; + } + state.values[idx] = this.create(state); + return 1; + } + }; + } + /** + Returns an extension that enables this field and overrides the + way it is initialized. Can be useful when you need to provide a + non-default starting value for the field. + */ + init(create) { + return [this, initField.of({ field: this, create })]; + } + /** + State field instances can be used as + [`Extension`](https://codemirror.net/6/docs/ref/#state.Extension) values to enable the field in a + given state. + */ + get extension() { + return this; + } +}; +var Prec_ = { lowest: 4, low: 3, default: 2, high: 1, highest: 0 }; +function prec(value) { + return (ext) => new PrecExtension(ext, value); +} +var Prec = { + /** + The highest precedence level, for extensions that should end up + near the start of the precedence ordering. + */ + highest: /* @__PURE__ */ prec(Prec_.highest), + /** + A higher-than-default precedence, for extensions that should + come before those with default precedence. + */ + high: /* @__PURE__ */ prec(Prec_.high), + /** + The default precedence, which is also used for extensions + without an explicit precedence. + */ + default: /* @__PURE__ */ prec(Prec_.default), + /** + A lower-than-default precedence. + */ + low: /* @__PURE__ */ prec(Prec_.low), + /** + The lowest precedence level. Meant for things that should end up + near the end of the extension order. + */ + lowest: /* @__PURE__ */ prec(Prec_.lowest) +}; +var PrecExtension = class { + constructor(inner, prec2) { + this.inner = inner; + this.prec = prec2; + } + get extension() { + return this; + } +}; +var Compartment = class _Compartment { + /** + Create an instance of this compartment to add to your [state + configuration](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions). + */ + of(ext) { + return new CompartmentInstance(this, ext); + } + /** + Create an [effect](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) that + reconfigures this compartment. + */ + reconfigure(content2) { + return _Compartment.reconfigure.of({ compartment: this, extension: content2 }); + } + /** + Get the current content of the compartment in the state, or + `undefined` if it isn't present. + */ + get(state) { + return state.config.compartments.get(this); + } +}; +var CompartmentInstance = class { + constructor(compartment, inner) { + this.compartment = compartment; + this.inner = inner; + } + get extension() { + return this; + } +}; +var Configuration = class _Configuration { + constructor(base2, compartments, dynamicSlots, address, staticValues, facets) { + this.base = base2; + this.compartments = compartments; + this.dynamicSlots = dynamicSlots; + this.address = address; + this.staticValues = staticValues; + this.facets = facets; + this.statusTemplate = []; + while (this.statusTemplate.length < dynamicSlots.length) + this.statusTemplate.push( + 0 + /* SlotStatus.Unresolved */ + ); + } + staticFacet(facet) { + let addr = this.address[facet.id]; + return addr == null ? facet.default : this.staticValues[addr >> 1]; + } + static resolve(base2, compartments, oldState) { + let fields = []; + let facets = /* @__PURE__ */ Object.create(null); + let newCompartments = /* @__PURE__ */ new Map(); + for (let ext of flatten(base2, compartments, newCompartments)) { + if (ext instanceof StateField) + fields.push(ext); + else + (facets[ext.facet.id] || (facets[ext.facet.id] = [])).push(ext); + } + let address = /* @__PURE__ */ Object.create(null); + let staticValues = []; + let dynamicSlots = []; + for (let field of fields) { + address[field.id] = dynamicSlots.length << 1; + dynamicSlots.push((a) => field.slot(a)); + } + let oldFacets = oldState === null || oldState === void 0 ? void 0 : oldState.config.facets; + for (let id in facets) { + let providers = facets[id], facet = providers[0].facet; + let oldProviders = oldFacets && oldFacets[id] || []; + if (providers.every( + (p) => p.type == 0 + /* Provider.Static */ + )) { + address[facet.id] = staticValues.length << 1 | 1; + if (sameArray(oldProviders, providers)) { + staticValues.push(oldState.facet(facet)); + } else { + let value = facet.combine(providers.map((p) => p.value)); + staticValues.push(oldState && facet.compare(value, oldState.facet(facet)) ? oldState.facet(facet) : value); + } + } else { + for (let p of providers) { + if (p.type == 0) { + address[p.id] = staticValues.length << 1 | 1; + staticValues.push(p.value); + } else { + address[p.id] = dynamicSlots.length << 1; + dynamicSlots.push((a) => p.dynamicSlot(a)); + } + } + address[facet.id] = dynamicSlots.length << 1; + dynamicSlots.push((a) => dynamicFacetSlot(a, facet, providers)); + } + } + let dynamic = dynamicSlots.map((f) => f(address)); + return new _Configuration(base2, newCompartments, dynamic, address, staticValues, facets); + } +}; +function flatten(extension, compartments, newCompartments) { + let result = [[], [], [], [], []]; + let seen = /* @__PURE__ */ new Map(); + function inner(ext, prec2) { + let known = seen.get(ext); + if (known != null) { + if (known <= prec2) + return; + let found = result[known].indexOf(ext); + if (found > -1) + result[known].splice(found, 1); + if (ext instanceof CompartmentInstance) + newCompartments.delete(ext.compartment); + } + seen.set(ext, prec2); + if (Array.isArray(ext)) { + for (let e of ext) + inner(e, prec2); + } else if (ext instanceof CompartmentInstance) { + if (newCompartments.has(ext.compartment)) + throw new RangeError(`Duplicate use of compartment in extensions`); + let content2 = compartments.get(ext.compartment) || ext.inner; + newCompartments.set(ext.compartment, content2); + inner(content2, prec2); + } else if (ext instanceof PrecExtension) { + inner(ext.inner, ext.prec); + } else if (ext instanceof StateField) { + result[prec2].push(ext); + if (ext.provides) + inner(ext.provides, prec2); + } else if (ext instanceof FacetProvider) { + result[prec2].push(ext); + if (ext.facet.extensions) + inner(ext.facet.extensions, Prec_.default); + } else { + let content2 = ext.extension; + if (!content2) + throw new Error(`Unrecognized extension value in extension set (${ext}).`); + if (content2 == ext) + throw new Error(`Unrecognized extension value in extension set (${ext}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`); + inner(content2, prec2); + } + } + inner(extension, Prec_.default); + return result.reduce((a, b) => a.concat(b)); +} +function ensureAddr(state, addr) { + if (addr & 1) + return 2; + let idx = addr >> 1; + let status = state.status[idx]; + if (status == 4) + throw new Error("Cyclic dependency between fields and/or facets"); + if (status & 2) + return status; + state.status[idx] = 4; + let changed = state.computeSlot(state, state.config.dynamicSlots[idx]); + return state.status[idx] = 2 | changed; +} +function getAddr(state, addr) { + return addr & 1 ? state.config.staticValues[addr >> 1] : state.values[addr >> 1]; +} +var languageData = /* @__PURE__ */ Facet.define(); +var allowMultipleSelections = /* @__PURE__ */ Facet.define({ + combine: (values) => values.some((v) => v), + static: true +}); +var lineSeparator = /* @__PURE__ */ Facet.define({ + combine: (values) => values.length ? values[0] : void 0, + static: true +}); +var changeFilter = /* @__PURE__ */ Facet.define(); +var transactionFilter = /* @__PURE__ */ Facet.define(); +var transactionExtender = /* @__PURE__ */ Facet.define(); +var readOnly = /* @__PURE__ */ Facet.define({ + combine: (values) => values.length ? values[0] : false +}); +var Annotation = class { + /** + @internal + */ + constructor(type, value) { + this.type = type; + this.value = value; + } + /** + Define a new type of annotation. + */ + static define() { + return new AnnotationType(); + } +}; +var AnnotationType = class { + /** + Create an instance of this annotation. + */ + of(value) { + return new Annotation(this, value); + } +}; +var StateEffectType = class { + /** + @internal + */ + constructor(map) { + this.map = map; + } + /** + Create a [state effect](https://codemirror.net/6/docs/ref/#state.StateEffect) instance of this + type. + */ + of(value) { + return new StateEffect(this, value); + } +}; +var StateEffect = class _StateEffect { + /** + @internal + */ + constructor(type, value) { + this.type = type; + this.value = value; + } + /** + Map this effect through a position mapping. Will return + `undefined` when that ends up deleting the effect. + */ + map(mapping) { + let mapped = this.type.map(this.value, mapping); + return mapped === void 0 ? void 0 : mapped == this.value ? this : new _StateEffect(this.type, mapped); + } + /** + Tells you whether this effect object is of a given + [type](https://codemirror.net/6/docs/ref/#state.StateEffectType). + */ + is(type) { + return this.type == type; + } + /** + Define a new effect type. The type parameter indicates the type + of values that his effect holds. It should be a type that + doesn't include `undefined`, since that is used in + [mapping](https://codemirror.net/6/docs/ref/#state.StateEffect.map) to indicate that an effect is + removed. + */ + static define(spec = {}) { + return new StateEffectType(spec.map || ((v) => v)); + } + /** + Map an array of effects through a change set. + */ + static mapEffects(effects, mapping) { + if (!effects.length) + return effects; + let result = []; + for (let effect of effects) { + let mapped = effect.map(mapping); + if (mapped) + result.push(mapped); + } + return result; + } +}; +StateEffect.reconfigure = /* @__PURE__ */ StateEffect.define(); +StateEffect.appendConfig = /* @__PURE__ */ StateEffect.define(); +var Transaction = class _Transaction { + constructor(startState, changes, selection, effects, annotations, scrollIntoView2) { + this.startState = startState; + this.changes = changes; + this.selection = selection; + this.effects = effects; + this.annotations = annotations; + this.scrollIntoView = scrollIntoView2; + this._doc = null; + this._state = null; + if (selection) + checkSelection(selection, changes.newLength); + if (!annotations.some((a) => a.type == _Transaction.time)) + this.annotations = annotations.concat(_Transaction.time.of(Date.now())); + } + /** + @internal + */ + static create(startState, changes, selection, effects, annotations, scrollIntoView2) { + return new _Transaction(startState, changes, selection, effects, annotations, scrollIntoView2); + } + /** + The new document produced by the transaction. Contrary to + [`.state`](https://codemirror.net/6/docs/ref/#state.Transaction.state)`.doc`, accessing this won't + force the entire new state to be computed right away, so it is + recommended that [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) use this getter + when they need to look at the new document. + */ + get newDoc() { + return this._doc || (this._doc = this.changes.apply(this.startState.doc)); + } + /** + The new selection produced by the transaction. If + [`this.selection`](https://codemirror.net/6/docs/ref/#state.Transaction.selection) is undefined, + this will [map](https://codemirror.net/6/docs/ref/#state.EditorSelection.map) the start state's + current selection through the changes made by the transaction. + */ + get newSelection() { + return this.selection || this.startState.selection.map(this.changes); + } + /** + The new state created by the transaction. Computed on demand + (but retained for subsequent access), so it is recommended not to + access it in [transaction + filters](https://codemirror.net/6/docs/ref/#state.EditorState^transactionFilter) when possible. + */ + get state() { + if (!this._state) + this.startState.applyTransaction(this); + return this._state; + } + /** + Get the value of the given annotation type, if any. + */ + annotation(type) { + for (let ann of this.annotations) + if (ann.type == type) + return ann.value; + return void 0; + } + /** + Indicates whether the transaction changed the document. + */ + get docChanged() { + return !this.changes.empty; + } + /** + Indicates whether this transaction reconfigures the state + (through a [configuration compartment](https://codemirror.net/6/docs/ref/#state.Compartment) or + with a top-level configuration + [effect](https://codemirror.net/6/docs/ref/#state.StateEffect^reconfigure). + */ + get reconfigured() { + return this.startState.config != this.state.config; + } + /** + Returns true if the transaction has a [user + event](https://codemirror.net/6/docs/ref/#state.Transaction^userEvent) annotation that is equal to + or more specific than `event`. For example, if the transaction + has `"select.pointer"` as user event, `"select"` and + `"select.pointer"` will match it. + */ + isUserEvent(event) { + let e = this.annotation(_Transaction.userEvent); + return !!(e && (e == event || e.length > event.length && e.slice(0, event.length) == event && e[event.length] == ".")); + } +}; +Transaction.time = /* @__PURE__ */ Annotation.define(); +Transaction.userEvent = /* @__PURE__ */ Annotation.define(); +Transaction.addToHistory = /* @__PURE__ */ Annotation.define(); +Transaction.remote = /* @__PURE__ */ Annotation.define(); +function joinRanges(a, b) { + let result = []; + for (let iA = 0, iB = 0; ; ) { + let from, to; + if (iA < a.length && (iB == b.length || b[iB] >= a[iA])) { + from = a[iA++]; + to = a[iA++]; + } else if (iB < b.length) { + from = b[iB++]; + to = b[iB++]; + } else + return result; + if (!result.length || result[result.length - 1] < from) + result.push(from, to); + else if (result[result.length - 1] < to) + result[result.length - 1] = to; + } +} +function mergeTransaction(a, b, sequential) { + var _a2; + let mapForA, mapForB, changes; + if (sequential) { + mapForA = b.changes; + mapForB = ChangeSet.empty(b.changes.length); + changes = a.changes.compose(b.changes); + } else { + mapForA = b.changes.map(a.changes); + mapForB = a.changes.mapDesc(b.changes, true); + changes = a.changes.compose(mapForA); + } + return { + changes, + selection: b.selection ? b.selection.map(mapForB) : (_a2 = a.selection) === null || _a2 === void 0 ? void 0 : _a2.map(mapForA), + effects: StateEffect.mapEffects(a.effects, mapForA).concat(StateEffect.mapEffects(b.effects, mapForB)), + annotations: a.annotations.length ? a.annotations.concat(b.annotations) : b.annotations, + scrollIntoView: a.scrollIntoView || b.scrollIntoView + }; +} +function resolveTransactionInner(state, spec, docSize) { + let sel = spec.selection, annotations = asArray(spec.annotations); + if (spec.userEvent) + annotations = annotations.concat(Transaction.userEvent.of(spec.userEvent)); + return { + changes: spec.changes instanceof ChangeSet ? spec.changes : ChangeSet.of(spec.changes || [], docSize, state.facet(lineSeparator)), + selection: sel && (sel instanceof EditorSelection ? sel : EditorSelection.single(sel.anchor, sel.head)), + effects: asArray(spec.effects), + annotations, + scrollIntoView: !!spec.scrollIntoView + }; +} +function resolveTransaction(state, specs, filter) { + let s = resolveTransactionInner(state, specs.length ? specs[0] : {}, state.doc.length); + if (specs.length && specs[0].filter === false) + filter = false; + for (let i2 = 1; i2 < specs.length; i2++) { + if (specs[i2].filter === false) + filter = false; + let seq = !!specs[i2].sequential; + s = mergeTransaction(s, resolveTransactionInner(state, specs[i2], seq ? s.changes.newLength : state.doc.length), seq); + } + let tr = Transaction.create(state, s.changes, s.selection, s.effects, s.annotations, s.scrollIntoView); + return extendTransaction(filter ? filterTransaction(tr) : tr); +} +function filterTransaction(tr) { + let state = tr.startState; + let result = true; + for (let filter of state.facet(changeFilter)) { + let value = filter(tr); + if (value === false) { + result = false; + break; + } + if (Array.isArray(value)) + result = result === true ? value : joinRanges(result, value); + } + if (result !== true) { + let changes, back; + if (result === false) { + back = tr.changes.invertedDesc; + changes = ChangeSet.empty(state.doc.length); + } else { + let filtered = tr.changes.filter(result); + changes = filtered.changes; + back = filtered.filtered.mapDesc(filtered.changes).invertedDesc; + } + tr = Transaction.create(state, changes, tr.selection && tr.selection.map(back), StateEffect.mapEffects(tr.effects, back), tr.annotations, tr.scrollIntoView); + } + let filters = state.facet(transactionFilter); + for (let i2 = filters.length - 1; i2 >= 0; i2--) { + let filtered = filters[i2](tr); + if (filtered instanceof Transaction) + tr = filtered; + else if (Array.isArray(filtered) && filtered.length == 1 && filtered[0] instanceof Transaction) + tr = filtered[0]; + else + tr = resolveTransaction(state, asArray(filtered), false); + } + return tr; +} +function extendTransaction(tr) { + let state = tr.startState, extenders = state.facet(transactionExtender), spec = tr; + for (let i2 = extenders.length - 1; i2 >= 0; i2--) { + let extension = extenders[i2](tr); + if (extension && Object.keys(extension).length) + spec = mergeTransaction(spec, resolveTransactionInner(state, extension, tr.changes.newLength), true); + } + return spec == tr ? tr : Transaction.create(state, tr.changes, tr.selection, spec.effects, spec.annotations, spec.scrollIntoView); +} +var none = []; +function asArray(value) { + return value == null ? none : Array.isArray(value) ? value : [value]; +} +var CharCategory = /* @__PURE__ */ (function(CharCategory2) { + CharCategory2[CharCategory2["Word"] = 0] = "Word"; + CharCategory2[CharCategory2["Space"] = 1] = "Space"; + CharCategory2[CharCategory2["Other"] = 2] = "Other"; + return CharCategory2; +})(CharCategory || (CharCategory = {})); +var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; +var wordChar; +try { + wordChar = /* @__PURE__ */ new RegExp("[\\p{Alphabetic}\\p{Number}_]", "u"); +} catch (_) { +} +function hasWordChar(str) { + if (wordChar) + return wordChar.test(str); + for (let i2 = 0; i2 < str.length; i2++) { + let ch = str[i2]; + if (/\w/.test(ch) || ch > "€" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))) + return true; + } + return false; +} +function makeCategorizer(wordChars) { + return (char) => { + if (!/\S/.test(char)) + return CharCategory.Space; + if (hasWordChar(char)) + return CharCategory.Word; + for (let i2 = 0; i2 < wordChars.length; i2++) + if (char.indexOf(wordChars[i2]) > -1) + return CharCategory.Word; + return CharCategory.Other; + }; +} +var EditorState = class _EditorState { + constructor(config, doc2, selection, values, computeSlot, tr) { + this.config = config; + this.doc = doc2; + this.selection = selection; + this.values = values; + this.status = config.statusTemplate.slice(); + this.computeSlot = computeSlot; + if (tr) + tr._state = this; + for (let i2 = 0; i2 < this.config.dynamicSlots.length; i2++) + ensureAddr(this, i2 << 1); + this.computeSlot = null; + } + field(field, require2 = true) { + let addr = this.config.address[field.id]; + if (addr == null) { + if (require2) + throw new RangeError("Field is not present in this state"); + return void 0; + } + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Create a [transaction](https://codemirror.net/6/docs/ref/#state.Transaction) that updates this + state. Any number of [transaction specs](https://codemirror.net/6/docs/ref/#state.TransactionSpec) + can be passed. Unless + [`sequential`](https://codemirror.net/6/docs/ref/#state.TransactionSpec.sequential) is set, the + [changes](https://codemirror.net/6/docs/ref/#state.TransactionSpec.changes) (if any) of each spec + are assumed to start in the _current_ document (not the document + produced by previous specs), and its + [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection) and + [effects](https://codemirror.net/6/docs/ref/#state.TransactionSpec.effects) are assumed to refer + to the document created by its _own_ changes. The resulting + transaction contains the combined effect of all the different + specs. For [selection](https://codemirror.net/6/docs/ref/#state.TransactionSpec.selection), later + specs take precedence over earlier ones. + */ + update(...specs) { + return resolveTransaction(this, specs, true); + } + /** + @internal + */ + applyTransaction(tr) { + let conf = this.config, { base: base2, compartments } = conf; + for (let effect of tr.effects) { + if (effect.is(Compartment.reconfigure)) { + if (conf) { + compartments = /* @__PURE__ */ new Map(); + conf.compartments.forEach((val, key) => compartments.set(key, val)); + conf = null; + } + compartments.set(effect.value.compartment, effect.value.extension); + } else if (effect.is(StateEffect.reconfigure)) { + conf = null; + base2 = effect.value; + } else if (effect.is(StateEffect.appendConfig)) { + conf = null; + base2 = asArray(base2).concat(effect.value); + } + } + let startValues; + if (!conf) { + conf = Configuration.resolve(base2, compartments, this); + let intermediateState = new _EditorState(conf, this.doc, this.selection, conf.dynamicSlots.map(() => null), (state, slot) => slot.reconfigure(state, this), null); + startValues = intermediateState.values; + } else { + startValues = tr.startState.values.slice(); + } + let selection = tr.startState.facet(allowMultipleSelections) ? tr.newSelection : tr.newSelection.asSingle(); + new _EditorState(conf, tr.newDoc, selection, startValues, (state, slot) => slot.update(state, tr), tr); + } + /** + Create a [transaction spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec) that + replaces every selection range with the given content. + */ + replaceSelection(text) { + if (typeof text == "string") + text = this.toText(text); + return this.changeByRange((range) => ({ + changes: { from: range.from, to: range.to, insert: text }, + range: EditorSelection.cursor(range.from + text.length, -1) + })); + } + /** + Create a set of changes and a new selection by running the given + function for each range in the active selection. The function + can return an optional set of changes (in the coordinate space + of the start document), plus an updated range (in the coordinate + space of the document produced by the call's own changes). This + method will merge all the changes and ranges into a single + changeset and selection, and return it as a [transaction + spec](https://codemirror.net/6/docs/ref/#state.TransactionSpec), which can be passed to + [`update`](https://codemirror.net/6/docs/ref/#state.EditorState.update). + */ + changeByRange(f) { + let sel = this.selection; + let result1 = f(sel.ranges[0]); + let changes = this.changes(result1.changes), ranges = [result1.range]; + let effects = asArray(result1.effects); + for (let i2 = 1; i2 < sel.ranges.length; i2++) { + let result = f(sel.ranges[i2]); + let newChanges = this.changes(result.changes), newMapped = newChanges.map(changes); + for (let j = 0; j < i2; j++) + ranges[j] = ranges[j].map(newMapped); + let mapBy = changes.mapDesc(newChanges, true); + ranges.push(result.range.map(mapBy)); + changes = changes.compose(newMapped); + effects = StateEffect.mapEffects(effects, newMapped).concat(StateEffect.mapEffects(asArray(result.effects), mapBy)); + } + return { + changes, + selection: EditorSelection.create(ranges, sel.mainIndex), + effects + }; + } + /** + Create a [change set](https://codemirror.net/6/docs/ref/#state.ChangeSet) from the given change + description, taking the state's document length and line + separator into account. + */ + changes(spec = []) { + if (spec instanceof ChangeSet) + return spec; + return ChangeSet.of(spec, this.doc.length, this.facet(_EditorState.lineSeparator)); + } + /** + Using the state's [line + separator](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator), create a + [`Text`](https://codemirror.net/6/docs/ref/#state.Text) instance from the given string. + */ + toText(string2) { + return Text.of(string2.split(this.facet(_EditorState.lineSeparator) || DefaultSplit)); + } + /** + Return the given range of the document as a string. + */ + sliceDoc(from = 0, to = this.doc.length) { + return this.doc.sliceString(from, to, this.lineBreak); + } + /** + Get the value of a state [facet](https://codemirror.net/6/docs/ref/#state.Facet). + */ + facet(facet) { + let addr = this.config.address[facet.id]; + if (addr == null) + return facet.default; + ensureAddr(this, addr); + return getAddr(this, addr); + } + /** + Convert this state to a JSON-serializable object. When custom + fields should be serialized, you can pass them in as an object + mapping property names (in the resulting object, which should + not use `doc` or `selection`) to fields. + */ + toJSON(fields) { + let result = { + doc: this.sliceDoc(), + selection: this.selection.toJSON() + }; + if (fields) + for (let prop in fields) { + let value = fields[prop]; + if (value instanceof StateField && this.config.address[value.id] != null) + result[prop] = value.spec.toJSON(this.field(fields[prop]), this); + } + return result; + } + /** + Deserialize a state from its JSON representation. When custom + fields should be deserialized, pass the same object you passed + to [`toJSON`](https://codemirror.net/6/docs/ref/#state.EditorState.toJSON) when serializing as + third argument. + */ + static fromJSON(json, config = {}, fields) { + if (!json || typeof json.doc != "string") + throw new RangeError("Invalid JSON representation for EditorState"); + let fieldInit = []; + if (fields) + for (let prop in fields) { + if (Object.prototype.hasOwnProperty.call(json, prop)) { + let field = fields[prop], value = json[prop]; + fieldInit.push(field.init((state) => field.spec.fromJSON(value, state))); + } + } + return _EditorState.create({ + doc: json.doc, + selection: EditorSelection.fromJSON(json.selection), + extensions: config.extensions ? fieldInit.concat([config.extensions]) : fieldInit + }); + } + /** + Create a new state. You'll usually only need this when + initializing an editor—updated states are created by applying + transactions. + */ + static create(config = {}) { + let configuration = Configuration.resolve(config.extensions || [], /* @__PURE__ */ new Map()); + let doc2 = config.doc instanceof Text ? config.doc : Text.of((config.doc || "").split(configuration.staticFacet(_EditorState.lineSeparator) || DefaultSplit)); + let selection = !config.selection ? EditorSelection.single(0) : config.selection instanceof EditorSelection ? config.selection : EditorSelection.single(config.selection.anchor, config.selection.head); + checkSelection(selection, doc2.length); + if (!configuration.staticFacet(allowMultipleSelections)) + selection = selection.asSingle(); + return new _EditorState(configuration, doc2, selection, configuration.dynamicSlots.map(() => null), (state, slot) => slot.create(state), null); + } + /** + The size (in columns) of a tab in the document, determined by + the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. + */ + get tabSize() { + return this.facet(_EditorState.tabSize); + } + /** + Get the proper [line-break](https://codemirror.net/6/docs/ref/#state.EditorState^lineSeparator) + string for this state. + */ + get lineBreak() { + return this.facet(_EditorState.lineSeparator) || "\n"; + } + /** + Returns true when the editor is + [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. + */ + get readOnly() { + return this.facet(readOnly); + } + /** + Look up a translation for the given phrase (via the + [`phrases`](https://codemirror.net/6/docs/ref/#state.EditorState^phrases) facet), or return the + original string if no translation is found. + + If additional arguments are passed, they will be inserted in + place of markers like `$1` (for the first value) and `$2`, etc. + A single `$` is equivalent to `$1`, and `$$` will produce a + literal dollar sign. + */ + phrase(phrase, ...insert2) { + for (let map of this.facet(_EditorState.phrases)) + if (Object.prototype.hasOwnProperty.call(map, phrase)) { + phrase = map[phrase]; + break; + } + if (insert2.length) + phrase = phrase.replace(/\$(\$|\d*)/g, (m, i2) => { + if (i2 == "$") + return "$"; + let n = +(i2 || 1); + return !n || n > insert2.length ? m : insert2[n - 1]; + }); + return phrase; + } + /** + Find the values for a given language data field, provided by the + the [`languageData`](https://codemirror.net/6/docs/ref/#state.EditorState^languageData) facet. + + Examples of language data fields are... + + - [`"commentTokens"`](https://codemirror.net/6/docs/ref/#commands.CommentTokens) for specifying + comment syntax. + - [`"autocomplete"`](https://codemirror.net/6/docs/ref/#autocomplete.autocompletion^config.override) + for providing language-specific completion sources. + - [`"wordChars"`](https://codemirror.net/6/docs/ref/#state.EditorState.charCategorizer) for adding + characters that should be considered part of words in this + language. + - [`"closeBrackets"`](https://codemirror.net/6/docs/ref/#autocomplete.CloseBracketConfig) controls + bracket closing behavior. + */ + languageDataAt(name2, pos, side = -1) { + let values = []; + for (let provider of this.facet(languageData)) { + for (let result of provider(this, pos, side)) { + if (Object.prototype.hasOwnProperty.call(result, name2)) + values.push(result[name2]); + } + } + return values; + } + /** + Return a function that can categorize strings (expected to + represent a single [grapheme cluster](https://codemirror.net/6/docs/ref/#state.findClusterBreak)) + into one of: + + - Word (contains an alphanumeric character or a character + explicitly listed in the local language's `"wordChars"` + language data, which should be a string) + - Space (contains only whitespace) + - Other (anything else) + */ + charCategorizer(at) { + let chars = this.languageDataAt("wordChars", at); + return makeCategorizer(chars.length ? chars[0] : ""); + } + /** + Find the word at the given position, meaning the range + containing all [word](https://codemirror.net/6/docs/ref/#state.CharCategory.Word) characters + around it. If no word characters are adjacent to the position, + this returns null. + */ + wordAt(pos) { + let { text, from, length } = this.doc.lineAt(pos); + let cat = this.charCategorizer(pos); + let start = pos - from, end = pos - from; + while (start > 0) { + let prev = findClusterBreak2(text, start, false); + if (cat(text.slice(prev, start)) != CharCategory.Word) + break; + start = prev; + } + while (end < length) { + let next = findClusterBreak2(text, end); + if (cat(text.slice(end, next)) != CharCategory.Word) + break; + end = next; + } + return start == end ? null : EditorSelection.range(start + from, end + from); + } +}; +EditorState.allowMultipleSelections = allowMultipleSelections; +EditorState.tabSize = /* @__PURE__ */ Facet.define({ + combine: (values) => values.length ? values[0] : 4 +}); +EditorState.lineSeparator = lineSeparator; +EditorState.readOnly = readOnly; +EditorState.phrases = /* @__PURE__ */ Facet.define({ + compare(a, b) { + let kA = Object.keys(a), kB = Object.keys(b); + return kA.length == kB.length && kA.every((k) => a[k] == b[k]); + } +}); +EditorState.languageData = languageData; +EditorState.changeFilter = changeFilter; +EditorState.transactionFilter = transactionFilter; +EditorState.transactionExtender = transactionExtender; +Compartment.reconfigure = /* @__PURE__ */ StateEffect.define(); +function combineConfig(configs, defaults, combine = {}) { + let result = {}; + for (let config of configs) + for (let key of Object.keys(config)) { + let value = config[key], current = result[key]; + if (current === void 0) + result[key] = value; + else if (current === value || value === void 0) ; + else if (Object.hasOwnProperty.call(combine, key)) + result[key] = combine[key](current, value); + else + throw new Error("Config merge conflict for field " + key); + } + for (let key in defaults) + if (result[key] === void 0) + result[key] = defaults[key]; + return result; +} +var RangeValue = class { + /** + Compare this value with another value. Used when comparing + rangesets. The default implementation compares by identity. + Unless you are only creating a fixed number of unique instances + of your value type, it is a good idea to implement this + properly. + */ + eq(other) { + return this == other; + } + /** + Create a [range](https://codemirror.net/6/docs/ref/#state.Range) with this value. + */ + range(from, to = from) { + return Range.create(from, to, this); + } +}; +RangeValue.prototype.startSide = RangeValue.prototype.endSide = 0; +RangeValue.prototype.point = false; +RangeValue.prototype.mapMode = MapMode.TrackDel; +function cmpVal(a, b) { + return a == b || a.constructor == b.constructor && a.eq(b); +} +var Range = class _Range { + constructor(from, to, value) { + this.from = from; + this.to = to; + this.value = value; + } + /** + @internal + */ + static create(from, to, value) { + return new _Range(from, to, value); + } +}; +function cmpRange(a, b) { + return a.from - b.from || a.value.startSide - b.value.startSide; +} +var Chunk = class _Chunk { + constructor(from, to, value, maxPoint) { + this.from = from; + this.to = to; + this.value = value; + this.maxPoint = maxPoint; + } + get length() { + return last(this.to); + } + // Find the index of the given position and side. Use the ranges' + // `from` pos when `end == false`, `to` when `end == true`. + findIndex(pos, side, end, startAt = 0) { + let arr = end ? this.to : this.from; + for (let lo = startAt, hi = arr.length; ; ) { + if (lo == hi) + return lo; + let mid = lo + hi >> 1; + let diff = arr[mid] - pos || (end ? this.value[mid].endSide : this.value[mid].startSide) - side; + if (mid == lo) + return diff >= 0 ? lo : hi; + if (diff >= 0) + hi = mid; + else + lo = mid + 1; + } + } + between(offset, from, to, f) { + for (let i2 = this.findIndex(from, -1e9, true), e = this.findIndex(to, 1e9, false, i2); i2 < e; i2++) + if (f(this.from[i2] + offset, this.to[i2] + offset, this.value[i2]) === false) + return false; + } + map(offset, changes, basePos, baseSide, spill) { + let value = [], from = [], to = [], newPos = -1, maxPoint = -1; + iter: for (let i2 = 0; i2 < this.value.length; i2++) { + let val = this.value[i2], curFrom = this.from[i2] + offset, curTo = this.to[i2] + offset, newFrom, newTo; + if (curFrom == curTo) { + let mapped = changes.mapPos(curFrom, val.startSide, val.mapMode); + if (mapped == null) + continue; + newFrom = newTo = mapped; + if (val.startSide != val.endSide) { + newTo = changes.mapPos(curFrom, val.endSide); + if (newTo < newFrom) + continue; + } + } else { + newFrom = changes.mapPos(curFrom, val.startSide); + newTo = changes.mapPos(curTo, val.endSide); + if (newFrom > newTo || newFrom == newTo && val.startSide > 0 && val.endSide <= 0) + continue; + } + if ((newTo - newFrom || val.endSide - val.startSide) < 0) + continue; + if (newPos < 0) + newPos = newFrom; + if (val.point) + maxPoint = Math.max(maxPoint, newTo - newFrom); + if ((newFrom - basePos || val.startSide - baseSide) >= 0) { + value.push(val); + from.push(newFrom - newPos); + to.push(newTo - newPos); + basePos = newTo; + baseSide = val.endSide; + } else { + if (newFrom == newTo) { + for (let i3 = value.length; i3 > 0; i3--) { + if ((newFrom - (to[i3 - 1] + newPos) || val.startSide - value[i3 - 1].endSide) >= 0) { + value.splice(i3, 0, val); + from.splice(i3, 0, newFrom - newPos); + to.splice(i3, 0, newTo - newPos); + continue iter; + } + if ((newFrom - (from[i3 - 1] + newPos) || val.endSide - value[i3 - 1].startSide) > 0) + break; + } + } + spill(newFrom, newTo, val); + } + } + return { mapped: value.length ? new _Chunk(from, to, value, maxPoint) : null, pos: newPos }; + } +}; +var RangeSet = class _RangeSet { + constructor(chunkPos, chunk, nextLayer, maxPoint) { + this.chunkPos = chunkPos; + this.chunk = chunk; + this.nextLayer = nextLayer; + this.maxPoint = maxPoint; + } + /** + @internal + */ + static create(chunkPos, chunk, nextLayer, maxPoint) { + return new _RangeSet(chunkPos, chunk, nextLayer, maxPoint); + } + /** + @internal + */ + get length() { + let last2 = this.chunk.length - 1; + return last2 < 0 ? 0 : Math.max(this.chunkEnd(last2), this.nextLayer.length); + } + /** + The number of ranges in the set. + */ + get size() { + if (this.isEmpty) + return 0; + let size = this.nextLayer.size; + for (let chunk of this.chunk) + size += chunk.value.length; + return size; + } + /** + @internal + */ + chunkEnd(index) { + return this.chunkPos[index] + this.chunk[index].length; + } + /** + Update the range set, optionally adding new ranges or filtering + out existing ones. + + (Note: The type parameter is just there as a kludge to work + around TypeScript variance issues that prevented `RangeSet` + from being a subtype of `RangeSet` when `X` is a subtype of + `Y`.) + */ + update(updateSpec) { + let { add = [], sort = false, filterFrom = 0, filterTo = this.length } = updateSpec; + let filter = updateSpec.filter; + if (add.length == 0 && !filter) + return this; + if (sort) + add = add.slice().sort(cmpRange); + if (this.isEmpty) + return add.length ? _RangeSet.of(add) : this; + let cur = new LayerCursor(this, null, -1).goto(0), i2 = 0, spill = []; + let builder = new RangeSetBuilder(); + while (cur.value || i2 < add.length) { + if (i2 < add.length && (cur.from - add[i2].from || cur.startSide - add[i2].value.startSide) >= 0) { + let range = add[i2++]; + if (!builder.addInner(range.from, range.to, range.value, false)) + spill.push(range); + } else if (cur.rangeIndex == 1 && cur.chunkIndex < this.chunk.length && (i2 == add.length || this.chunkEnd(cur.chunkIndex) < add[i2].from) && (!filter || filterFrom > this.chunkEnd(cur.chunkIndex) || filterTo < this.chunkPos[cur.chunkIndex]) && builder.addChunk(this.chunkPos[cur.chunkIndex], this.chunk[cur.chunkIndex])) { + cur.nextChunk(); + } else { + if (!filter || filterFrom > cur.to || filterTo < cur.from || filter(cur.from, cur.to, cur.value)) { + if (!builder.addInner(cur.from, cur.to, cur.value, false)) + spill.push(Range.create(cur.from, cur.to, cur.value)); + } + cur.next(); + } + } + return builder.finishInner(this.nextLayer.isEmpty && !spill.length ? _RangeSet.empty : this.nextLayer.update({ add: spill, filter, filterFrom, filterTo })); + } + /** + Map this range set through a set of changes, return the new set. + */ + map(changes) { + if (changes.empty || this.isEmpty) + return this; + let chunks = [], chunkPos = [], maxPoint = -1; + let spilled; + let spill = (from, to, value) => { + if (!spilled) + spilled = new RangeSetBuilder(); + spilled.addRange(from, to, value, false); + }; + for (let i2 = 0; i2 < this.chunk.length; i2++) { + let start = this.chunkPos[i2], chunk = this.chunk[i2]; + let touch = changes.touchesRange(start, start + chunk.length); + if (touch === false) { + maxPoint = Math.max(maxPoint, chunk.maxPoint); + chunks.push(chunk); + chunkPos.push(changes.mapPos(start)); + } else if (touch === true) { + let [prevPos, prevSide] = !chunks.length ? [-1, -1] : [last(chunkPos) + last(chunks).length, last(last(chunks).value).endSide]; + let { mapped, pos } = chunk.map(start, changes, prevPos, prevSide, spill); + if (mapped) { + maxPoint = Math.max(maxPoint, mapped.maxPoint); + chunks.push(mapped); + chunkPos.push(pos); + } + } + } + let next = this.nextLayer.map(changes); + if (spilled) + next = spilled.finishInner(next); + return chunks.length == 0 ? next : new _RangeSet(chunkPos, chunks, next || _RangeSet.empty, maxPoint); + } + /** + Iterate over the ranges that touch the region `from` to `to`, + calling `f` for each. There is no guarantee that the ranges will + be reported in any specific order. When the callback returns + `false`, iteration stops. + */ + between(from, to, f) { + if (this.isEmpty) + return; + for (let i2 = 0; i2 < this.chunk.length; i2++) { + let start = this.chunkPos[i2], chunk = this.chunk[i2]; + if (to >= start && from <= start + chunk.length && chunk.between(start, from - start, to - start, f) === false) + return; + } + this.nextLayer.between(from, to, f); + } + /** + Iterate over the ranges in this set, in order, including all + ranges that end at or after `from`. + */ + iter(from = 0) { + return HeapCursor.from([this]).goto(from); + } + /** + @internal + */ + get isEmpty() { + return this.nextLayer == this; + } + /** + Iterate over the ranges in a collection of sets, in order, + starting from `from`. + */ + static iter(sets, from = 0) { + return HeapCursor.from(sets).goto(from); + } + /** + Iterate over two groups of sets, calling methods on `comparator` + to notify it of possible differences. + */ + static compare(oldSets, newSets, textDiff, comparator, minPointSize = -1) { + let a = oldSets.filter((set) => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let b = newSets.filter((set) => set.maxPoint > 0 || !set.isEmpty && set.maxPoint >= minPointSize); + let sharedChunks = findSharedChunks(a, b, textDiff); + let sideA = new SpanCursor(a, sharedChunks, minPointSize); + let sideB = new SpanCursor(b, sharedChunks, minPointSize); + textDiff.iterGaps((fromA, fromB, length) => compare(sideA, fromA, sideB, fromB, length, comparator)); + if (textDiff.empty && textDiff.length == 0) + compare(sideA, 0, sideB, 0, 0, comparator); + } + /** + Compare the contents of two groups of range sets, returning true + if they are equivalent in the given range. + */ + static eq(oldSets, newSets, from = 0, to) { + if (to == null) + to = 1e9 - 1; + let a = oldSets.filter((set) => !set.isEmpty && newSets.indexOf(set) < 0); + let b = newSets.filter((set) => !set.isEmpty && oldSets.indexOf(set) < 0); + if (a.length != b.length) + return false; + if (!a.length) + return true; + let sharedChunks = findSharedChunks(a, b); + let sideA = new SpanCursor(a, sharedChunks, 0).goto(from), sideB = new SpanCursor(b, sharedChunks, 0).goto(from); + for (; ; ) { + if (sideA.to != sideB.to || !sameValues(sideA.active, sideB.active) || sideA.point && (!sideB.point || !cmpVal(sideA.point, sideB.point))) + return false; + if (sideA.to > to) + return true; + sideA.next(); + sideB.next(); + } + } + /** + Iterate over a group of range sets at the same time, notifying + the iterator about the ranges covering every given piece of + content. Returns the open count (see + [`SpanIterator.span`](https://codemirror.net/6/docs/ref/#state.SpanIterator.span)) at the end + of the iteration. + */ + static spans(sets, from, to, iterator, minPointSize = -1) { + let cursor = new SpanCursor(sets, null, minPointSize).goto(from), pos = from; + let openRanges = cursor.openStart; + for (; ; ) { + let curTo = Math.min(cursor.to, to); + if (cursor.point) { + let active = cursor.activeForPoint(cursor.to); + let openCount = cursor.pointFrom < from ? active.length + 1 : cursor.point.startSide < 0 ? active.length : Math.min(active.length, openRanges); + iterator.point(pos, curTo, cursor.point, active, openCount, cursor.pointRank); + openRanges = Math.min(cursor.openEnd(curTo), active.length); + } else if (curTo > pos) { + iterator.span(pos, curTo, cursor.active, openRanges); + openRanges = cursor.openEnd(curTo); + } + if (cursor.to > to) + return openRanges + (cursor.point && cursor.to > to ? 1 : 0); + pos = cursor.to; + cursor.next(); + } + } + /** + Create a range set for the given range or array of ranges. By + default, this expects the ranges to be _sorted_ (by start + position and, if two start at the same position, + `value.startSide`). You can pass `true` as second argument to + cause the method to sort them. + */ + static of(ranges, sort = false) { + let build = new RangeSetBuilder(); + for (let range of ranges instanceof Range ? [ranges] : sort ? lazySort(ranges) : ranges) + build.add(range.from, range.to, range.value); + return build.finish(); + } + /** + Join an array of range sets into a single set. + */ + static join(sets) { + if (!sets.length) + return _RangeSet.empty; + let result = last(sets); + for (let i2 = sets.length - 2; i2 >= 0; i2--) { + for (let layer = sets[i2]; layer != _RangeSet.empty; layer = layer.nextLayer) + result = new _RangeSet(layer.chunkPos, layer.chunk, result, Math.max(layer.maxPoint, result.maxPoint)); + } + return result; + } +}; +RangeSet.empty = /* @__PURE__ */ new RangeSet([], [], null, -1); +function last(arr) { + return arr[arr.length - 1]; +} +function lazySort(ranges) { + if (ranges.length > 1) + for (let prev = ranges[0], i2 = 1; i2 < ranges.length; i2++) { + let cur = ranges[i2]; + if (cmpRange(prev, cur) > 0) + return ranges.slice().sort(cmpRange); + prev = cur; + } + return ranges; +} +RangeSet.empty.nextLayer = RangeSet.empty; +var RangeSetBuilder = class _RangeSetBuilder { + finishChunk(newArrays) { + this.chunks.push(new Chunk(this.from, this.to, this.value, this.maxPoint)); + this.chunkPos.push(this.chunkStart); + this.chunkStart = -1; + this.setMaxPoint = Math.max(this.setMaxPoint, this.maxPoint); + this.maxPoint = -1; + if (newArrays) { + this.from = []; + this.to = []; + this.value = []; + } + } + /** + Create an empty builder. + */ + constructor() { + this.chunks = []; + this.chunkPos = []; + this.chunkStart = -1; + this.last = null; + this.lastFrom = -1e9; + this.lastTo = -1e9; + this.from = []; + this.to = []; + this.value = []; + this.maxPoint = -1; + this.setMaxPoint = -1; + this.nextLayer = null; + } + /** + Add a range. Ranges should be added in sorted (by `from` and + `value.startSide`) order. + */ + add(from, to, value) { + this.addRange(from, to, value, true); + } + /** + @internal + */ + addRange(from, to, value, strict) { + if (!this.addInner(from, to, value, strict)) + (this.nextLayer || (this.nextLayer = new _RangeSetBuilder())).addRange(from, to, value, strict); + } + /** + @internal + */ + addInner(from, to, value, strict) { + let diff = from - this.lastTo || value.startSide - this.last.endSide; + if (strict && diff <= 0 && (from - this.lastFrom || value.startSide - this.last.startSide) < 0) + throw new Error("Ranges must be added sorted by `from` position and `startSide`"); + if (diff < 0) + return false; + if (this.from.length == 250) + this.finishChunk(true); + if (this.chunkStart < 0) + this.chunkStart = from; + this.from.push(from - this.chunkStart); + this.to.push(to - this.chunkStart); + this.last = value; + this.lastFrom = from; + this.lastTo = to; + this.value.push(value); + if (value.point) + this.maxPoint = Math.max(this.maxPoint, to - from); + return true; + } + /** + @internal + */ + addChunk(from, chunk) { + if ((from - this.lastTo || chunk.value[0].startSide - this.last.endSide) < 0) + return false; + if (this.from.length) + this.finishChunk(true); + this.setMaxPoint = Math.max(this.setMaxPoint, chunk.maxPoint); + this.chunks.push(chunk); + this.chunkPos.push(from); + let last2 = chunk.value.length - 1; + this.last = chunk.value[last2]; + this.lastFrom = chunk.from[last2] + from; + this.lastTo = chunk.to[last2] + from; + return true; + } + /** + Finish the range set. Returns the new set. The builder can't be + used anymore after this has been called. + */ + finish() { + return this.finishInner(RangeSet.empty); + } + /** + @internal + */ + finishInner(next) { + if (this.from.length) + this.finishChunk(false); + if (this.chunks.length == 0) + return next; + let result = RangeSet.create(this.chunkPos, this.chunks, this.nextLayer ? this.nextLayer.finishInner(next) : next, this.setMaxPoint); + this.from = null; + return result; + } +}; +function findSharedChunks(a, b, textDiff) { + let inA = /* @__PURE__ */ new Map(); + for (let set of a) + for (let i2 = 0; i2 < set.chunk.length; i2++) + if (set.chunk[i2].maxPoint <= 0) + inA.set(set.chunk[i2], set.chunkPos[i2]); + let shared = /* @__PURE__ */ new Set(); + for (let set of b) + for (let i2 = 0; i2 < set.chunk.length; i2++) { + let known = inA.get(set.chunk[i2]); + if (known != null && (textDiff ? textDiff.mapPos(known) : known) == set.chunkPos[i2] && !(textDiff === null || textDiff === void 0 ? void 0 : textDiff.touchesRange(known, known + set.chunk[i2].length))) + shared.add(set.chunk[i2]); + } + return shared; +} +var LayerCursor = class { + constructor(layer, skip, minPoint, rank = 0) { + this.layer = layer; + this.skip = skip; + this.minPoint = minPoint; + this.rank = rank; + } + get startSide() { + return this.value ? this.value.startSide : 0; + } + get endSide() { + return this.value ? this.value.endSide : 0; + } + goto(pos, side = -1e9) { + this.chunkIndex = this.rangeIndex = 0; + this.gotoInner(pos, side, false); + return this; + } + gotoInner(pos, side, forward) { + while (this.chunkIndex < this.layer.chunk.length) { + let next = this.layer.chunk[this.chunkIndex]; + if (!(this.skip && this.skip.has(next) || this.layer.chunkEnd(this.chunkIndex) < pos || next.maxPoint < this.minPoint)) + break; + this.chunkIndex++; + forward = false; + } + if (this.chunkIndex < this.layer.chunk.length) { + let rangeIndex = this.layer.chunk[this.chunkIndex].findIndex(pos - this.layer.chunkPos[this.chunkIndex], side, true); + if (!forward || this.rangeIndex < rangeIndex) + this.setRangeIndex(rangeIndex); + } + this.next(); + } + forward(pos, side) { + if ((this.to - pos || this.endSide - side) < 0) + this.gotoInner(pos, side, true); + } + next() { + for (; ; ) { + if (this.chunkIndex == this.layer.chunk.length) { + this.from = this.to = 1e9; + this.value = null; + break; + } else { + let chunkPos = this.layer.chunkPos[this.chunkIndex], chunk = this.layer.chunk[this.chunkIndex]; + let from = chunkPos + chunk.from[this.rangeIndex]; + this.from = from; + this.to = chunkPos + chunk.to[this.rangeIndex]; + this.value = chunk.value[this.rangeIndex]; + this.setRangeIndex(this.rangeIndex + 1); + if (this.minPoint < 0 || this.value.point && this.to - this.from >= this.minPoint) + break; + } + } + } + setRangeIndex(index) { + if (index == this.layer.chunk[this.chunkIndex].value.length) { + this.chunkIndex++; + if (this.skip) { + while (this.chunkIndex < this.layer.chunk.length && this.skip.has(this.layer.chunk[this.chunkIndex])) + this.chunkIndex++; + } + this.rangeIndex = 0; + } else { + this.rangeIndex = index; + } + } + nextChunk() { + this.chunkIndex++; + this.rangeIndex = 0; + this.next(); + } + compare(other) { + return this.from - other.from || this.startSide - other.startSide || this.rank - other.rank || this.to - other.to || this.endSide - other.endSide; + } +}; +var HeapCursor = class _HeapCursor { + constructor(heap) { + this.heap = heap; + } + static from(sets, skip = null, minPoint = -1) { + let heap = []; + for (let i2 = 0; i2 < sets.length; i2++) { + for (let cur = sets[i2]; !cur.isEmpty; cur = cur.nextLayer) { + if (cur.maxPoint >= minPoint) + heap.push(new LayerCursor(cur, skip, minPoint, i2)); + } + } + return heap.length == 1 ? heap[0] : new _HeapCursor(heap); + } + get startSide() { + return this.value ? this.value.startSide : 0; + } + goto(pos, side = -1e9) { + for (let cur of this.heap) + cur.goto(pos, side); + for (let i2 = this.heap.length >> 1; i2 >= 0; i2--) + heapBubble(this.heap, i2); + this.next(); + return this; + } + forward(pos, side) { + for (let cur of this.heap) + cur.forward(pos, side); + for (let i2 = this.heap.length >> 1; i2 >= 0; i2--) + heapBubble(this.heap, i2); + if ((this.to - pos || this.value.endSide - side) < 0) + this.next(); + } + next() { + if (this.heap.length == 0) { + this.from = this.to = 1e9; + this.value = null; + this.rank = -1; + } else { + let top2 = this.heap[0]; + this.from = top2.from; + this.to = top2.to; + this.value = top2.value; + this.rank = top2.rank; + if (top2.value) + top2.next(); + heapBubble(this.heap, 0); + } + } +}; +function heapBubble(heap, index) { + for (let cur = heap[index]; ; ) { + let childIndex = (index << 1) + 1; + if (childIndex >= heap.length) + break; + let child = heap[childIndex]; + if (childIndex + 1 < heap.length && child.compare(heap[childIndex + 1]) >= 0) { + child = heap[childIndex + 1]; + childIndex++; + } + if (cur.compare(child) < 0) + break; + heap[childIndex] = cur; + heap[index] = child; + index = childIndex; + } +} +var SpanCursor = class { + constructor(sets, skip, minPoint) { + this.minPoint = minPoint; + this.active = []; + this.activeTo = []; + this.activeRank = []; + this.minActive = -1; + this.point = null; + this.pointFrom = 0; + this.pointRank = 0; + this.to = -1e9; + this.endSide = 0; + this.openStart = -1; + this.cursor = HeapCursor.from(sets, skip, minPoint); + } + goto(pos, side = -1e9) { + this.cursor.goto(pos, side); + this.active.length = this.activeTo.length = this.activeRank.length = 0; + this.minActive = -1; + this.to = pos; + this.endSide = side; + this.openStart = -1; + this.next(); + return this; + } + forward(pos, side) { + while (this.minActive > -1 && (this.activeTo[this.minActive] - pos || this.active[this.minActive].endSide - side) < 0) + this.removeActive(this.minActive); + this.cursor.forward(pos, side); + } + removeActive(index) { + remove(this.active, index); + remove(this.activeTo, index); + remove(this.activeRank, index); + this.minActive = findMinIndex(this.active, this.activeTo); + } + addActive(trackOpen) { + let i2 = 0, { value, to, rank } = this.cursor; + while (i2 < this.activeRank.length && (rank - this.activeRank[i2] || to - this.activeTo[i2]) > 0) + i2++; + insert(this.active, i2, value); + insert(this.activeTo, i2, to); + insert(this.activeRank, i2, rank); + if (trackOpen) + insert(trackOpen, i2, this.cursor.from); + this.minActive = findMinIndex(this.active, this.activeTo); + } + // After calling this, if `this.point` != null, the next range is a + // point. Otherwise, it's a regular range, covered by `this.active`. + next() { + let from = this.to, wasPoint = this.point; + this.point = null; + let trackOpen = this.openStart < 0 ? [] : null; + for (; ; ) { + let a = this.minActive; + if (a > -1 && (this.activeTo[a] - this.cursor.from || this.active[a].endSide - this.cursor.startSide) < 0) { + if (this.activeTo[a] > from) { + this.to = this.activeTo[a]; + this.endSide = this.active[a].endSide; + break; + } + this.removeActive(a); + if (trackOpen) + remove(trackOpen, a); + } else if (!this.cursor.value) { + this.to = this.endSide = 1e9; + break; + } else if (this.cursor.from > from) { + this.to = this.cursor.from; + this.endSide = this.cursor.startSide; + break; + } else { + let nextVal = this.cursor.value; + if (!nextVal.point) { + this.addActive(trackOpen); + this.cursor.next(); + } else if (wasPoint && this.cursor.to == this.to && this.cursor.from < this.cursor.to) { + this.cursor.next(); + } else { + this.point = nextVal; + this.pointFrom = this.cursor.from; + this.pointRank = this.cursor.rank; + this.to = this.cursor.to; + this.endSide = nextVal.endSide; + this.cursor.next(); + this.forward(this.to, this.endSide); + break; + } + } + } + if (trackOpen) { + this.openStart = 0; + for (let i2 = trackOpen.length - 1; i2 >= 0 && trackOpen[i2] < from; i2--) + this.openStart++; + } + } + activeForPoint(to) { + if (!this.active.length) + return this.active; + let active = []; + for (let i2 = this.active.length - 1; i2 >= 0; i2--) { + if (this.activeRank[i2] < this.pointRank) + break; + if (this.activeTo[i2] > to || this.activeTo[i2] == to && this.active[i2].endSide >= this.point.endSide) + active.push(this.active[i2]); + } + return active.reverse(); + } + openEnd(to) { + let open = 0; + for (let i2 = this.activeTo.length - 1; i2 >= 0 && this.activeTo[i2] > to; i2--) + open++; + return open; + } +}; +function compare(a, startA, b, startB, length, comparator) { + a.goto(startA); + b.goto(startB); + let endB = startB + length; + let pos = startB, dPos = startB - startA; + let bounds = !!comparator.boundChange; + for (let boundChange = false; ; ) { + let dEnd = a.to + dPos - b.to, diff = dEnd || a.endSide - b.endSide; + let end = diff < 0 ? a.to + dPos : b.to, clipEnd = Math.min(end, endB); + let point = a.point || b.point; + if (point) { + if (!(a.point && b.point && cmpVal(a.point, b.point) && sameValues(a.activeForPoint(a.to), b.activeForPoint(b.to)))) + comparator.comparePoint(pos, clipEnd, a.point, b.point); + boundChange = false; + } else { + if (boundChange) { + comparator.boundChange(pos); + boundChange = false; + } + if (clipEnd > pos && !sameValues(a.active, b.active)) + comparator.compareRange(pos, clipEnd, a.active, b.active); + if (bounds && clipEnd < endB && (dEnd || a.openEnd(end) != b.openEnd(end))) + boundChange = true; + } + if (end > endB) + break; + pos = end; + if (diff <= 0) + a.next(); + if (diff >= 0) + b.next(); + } +} +function sameValues(a, b) { + if (a.length != b.length) + return false; + for (let i2 = 0; i2 < a.length; i2++) + if (a[i2] != b[i2] && !cmpVal(a[i2], b[i2])) + return false; + return true; +} +function remove(array, index) { + for (let i2 = index, e = array.length - 1; i2 < e; i2++) + array[i2] = array[i2 + 1]; + array.pop(); +} +function insert(array, index, value) { + for (let i2 = array.length - 1; i2 >= index; i2--) + array[i2 + 1] = array[i2]; + array[index] = value; +} +function findMinIndex(value, array) { + let found = -1, foundPos = 1e9; + for (let i2 = 0; i2 < array.length; i2++) + if ((array[i2] - foundPos || value[i2].endSide - value[found].endSide) < 0) { + found = i2; + foundPos = array[i2]; + } + return found; +} +function countColumn(string2, tabSize, to = string2.length) { + let n = 0; + for (let i2 = 0; i2 < to && i2 < string2.length; ) { + if (string2.charCodeAt(i2) == 9) { + n += tabSize - n % tabSize; + i2++; + } else { + n++; + i2 = findClusterBreak2(string2, i2); + } + } + return n; +} +function findColumn(string2, col, tabSize, strict) { + for (let i2 = 0, n = 0; ; ) { + if (n >= col) + return i2; + if (i2 == string2.length) + break; + n += string2.charCodeAt(i2) == 9 ? tabSize - n % tabSize : 1; + i2 = findClusterBreak2(string2, i2); + } + return strict === true ? -1 : string2.length; +} + +// node_modules/style-mod/src/style-mod.js +var C = "ͼ"; +var COUNT = typeof Symbol == "undefined" ? "__" + C : Symbol.for(C); +var SET = typeof Symbol == "undefined" ? "__styleSet" + Math.floor(Math.random() * 1e8) : /* @__PURE__ */ Symbol("styleSet"); +var top = typeof globalThis != "undefined" ? globalThis : typeof window != "undefined" ? window : {}; +var StyleModule = class { + // :: (Object