import { tr } from '../i18n/index.ts'; import { Editor, Extension, Mark, getMarkRange } from "@tiptap/core"; import { Plugin } from "@tiptap/pm/state"; import { Decoration, DecorationSet } from "@tiptap/pm/view"; import Highlight from "@tiptap/extension-highlight"; import StarterKit from "@tiptap/starter-kit"; import Link from "@tiptap/extension-link"; import Image from "@tiptap/extension-image"; import type { EditorView } from "@codemirror/view"; import { isolateHistory, redo, undo } from "@codemirror/commands"; import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable"; import { tableCellMarkdown } from "./tableCellMarkdown"; import { tableSelectionControls } from "./tableSelectionControls"; import { tableDragControls } from "./tableDragControls"; import type { TableContextActions } from "./tableCellActions"; import { actionIcon } from "../ui/actionIcons"; import { activeTableFormulas } from "../formulas/index.ts"; import { attachTooltip } from "../ui/tooltip"; import { documentLinks } from "./documentLinks"; import { tableLinkLabelPosition } from "./tableLinkSource"; import { renderMarkdownHtml } from "../workspace/noteHtml"; const cellFormats = ["math", "comment"].map(name => Mark.create({ name, parseHTML: () => [{ tag: `span[data-cell-format="${name}"]` }], renderHTML: () => ["span", { "data-cell-format": name, class: `md-inline-${name}` }, 0], })); const CellLink = Link.extend({ addAttributes() { return { ...this.parent?.(), "data-kind": { default: "md" } }; }, }); const CellImage = Image.extend({ addAttributes() { return { ...this.parent?.(), "data-md-src": { default: null }, "data-md-kind": { default: "md" } }; }, parseHTML() { return [...(this.parent?.() || []), { tag: "span.missing-image[data-md-src]" }]; }, renderHTML({ HTMLAttributes }) { return HTMLAttributes.src ? ["img", HTMLAttributes] : ["span", { ...HTMLAttributes, class: "missing-image" }, `Image unavailable: ${HTMLAttributes.alt || HTMLAttributes["data-md-src"] || ""}`]; }, }); export const tableEditors = new WeakMap void; destroy: () => void }>(); export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) { const formulas = activeTableFormulas(); const scroll = root.querySelector(".md-table-scroll"); const table = scroll?.querySelector("table"); if (!scroll || !table || !parseMarkdownTable(initialSource)) return; const wrapper = document.createElement("div"); wrapper.className = "writer-table"; scroll.before(wrapper); wrapper.append(scroll); let editor: Editor | undefined; let active: HTMLTableCellElement | undefined; let sourceEditing = false; let sourceImages = new Map(); let firstEdit = true; let selectionControls: ReturnType | undefined; let dragControls: ReturnType | undefined; const tooltipCleanup: (() => void)[] = []; const controller = { source: initialSource, enter, destroy: () => { tooltipCleanup.forEach(dispose => dispose()); dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } }; tableEditors.set(root, controller); function enter(forward: boolean, x?: number) { const row = table!.rows[forward ? 0 : table!.rows.length - 1]; const cells = [...row.cells]; let cell = cells[forward ? 0 : cells.length - 1]; if (x !== undefined) { const distance = (candidate: HTMLTableCellElement) => { const rect = candidate.getBoundingClientRect(); return Math.max(rect.left - x, x - rect.right, 0); }; cell = cells.reduce((nearest, candidate) => distance(candidate) < distance(nearest) ? candidate : nearest); } activate(cell); const current = editor!; let position = forward ? 1 : current.state.doc.content.size - 1; if (x !== undefined) { const edge = current.view.coordsAtPos(position); position = current.view.posAtCoords({ left: x, top: (edge.top + edge.bottom) / 2 })?.pos ?? position; } current.commands.setTextSelection(position); current.view.focus(); cell.scrollIntoView({ block: "nearest", inline: "nearest" }); } function refreshFormulas() { const parsed = parseMarkdownTable(controller.source); if (!parsed || !formulas) return; const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || "")); const results = formulas.evaluateTableFormulas(grid); for (const row of table!.rows) for (const cell of row.cells) { const result = results[row.rowIndex]?.[cell.cellIndex]; const address = formulas.cellAddress(row.rowIndex, cell.cellIndex); // Only a formula cell has a hover hint. The footer shows the address of each cell, so no hint covers the next cell. if (result?.formula) cell.dataset.cellHint = `${address} · ${result.formula}`; else delete cell.dataset.cellHint; cell.removeAttribute("title"); if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result); if (cell === active) { formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : tr(" · Type = to calculate")}`; formulaHint.textContent = result?.error ? formulas.formulaErrorText(result.error) : ""; formulaHint.hidden = !formulaHint.textContent; } } } function change(insert: string, structural = false) { const source = controller.source; const from = view.posAtDOM(root); if (view.state.doc.sliceString(from, from + source.length) !== source || insert === source) return; // Keep the same DOM/editor on typing, including composition and text selection. if (!structural) controller.source = insert; let start = 0, oldEnd = source.length, newEnd = insert.length; while (start < oldEnd && start < newEnd && source[start] === insert[start]) start++; while (oldEnd > start && newEnd > start && source[oldEnd - 1] === insert[newEnd - 1]) { oldEnd--; newEnd--; } view.dispatch({ changes: { from: from + start, to: from + oldEnd, insert: insert.slice(start, newEnd) }, userEvent: structural ? "input" : editor?.view.composing ? "input.type.compose" : "input.type.table", annotations: structural ? isolateHistory.of("full") : firstEdit ? isolateHistory.of("before") : [], }); firstEdit = false; if (!structural) refreshFormulas(); view.requestMeasure(); } function finish() { if (!editor || !active) return; const cell = active; let html = editor.getHTML(); if (sourceEditing) { const rendered = document.createElement("div"); rendered.innerHTML = renderMarkdownHtml(controller.source, sourceImages); html = rendered.querySelector("table")?.rows[(cell.parentElement as HTMLTableRowElement).rowIndex]?.cells[cell.cellIndex]?.innerHTML ?? html; } sourceEditing = false; editor.destroy(); editor = undefined; active = undefined; cell.innerHTML = html; cell.classList.remove("is-editing", "is-source-editing"); refreshFormulas(); formulaStatus.textContent = tr("Type = in a cell to calculate"); formulaHint.hidden = true; view.requestMeasure(); if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") }); } function leave(after: boolean) { const from = view.posAtDOM(root), to = from + controller.source.length; finish(); let anchor = after ? Math.min(view.state.doc.length, to + 1) : Math.max(0, from - 1); if (after && to + 1 >= view.state.doc.length) { view.dispatch({ changes: { from: view.state.doc.length, insert: to === view.state.doc.length ? "\n\n" : "\n" }, userEvent: "input" }); anchor = to + 2; } else if (after && view.state.doc.sliceString(to, to + 2) === "\n\n") { // Leave the separator blank so typing below cannot become another row. anchor = to + 2; } else if (!after && from === 0) { view.dispatch({ changes: { from: 0, insert: "\n\n" }, userEvent: "input" }); anchor = 0; } view.dispatch({ selection: { anchor }, scrollIntoView: true }); view.focus(); } function activate(cell: HTMLTableCellElement) { if (active === cell) return; finish(); active = cell; firstEdit = true; const row = (cell.parentElement as HTMLTableRowElement).rowIndex; const column = cell.cellIndex; const sourceRow = row === 0 ? 0 : row + 1; const originalCell = parseMarkdownTable(controller.source)?.rows[sourceRow]?.cells[column]; // The nested editor owns browser focus, but the outer editor also needs to // leave its previous active line so its Markdown markers render again. view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" }); let contentFrom = originalCell?.from, contentTo = originalCell?.to; const formula = originalCell && (/^=(?!=)/.test(originalCell.text.trim()) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined; const html = cell.innerHTML; formulaStatus.textContent = formulas ? `${formulas.cellAddress(row, column)}${tr(" · Type = to calculate")}` : ""; cell.innerHTML = ""; cell.classList.add("is-editing"); editor = new Editor({ element: cell, extensions: [ Extension.create({ name: "cellLinkSource", addProseMirrorPlugins: () => [new Plugin({ props: { decorations(state) { if (!sourceEditing) return null; const decorations: Decoration[] = []; state.doc.descendants((node, position) => { if (!node.isTextblock) return; for (const link of documentLinks(node.textBetween(0, node.content.size, "\n", "\n"))) { decorations.push(Decoration.inline(position + link.from + 1, position + link.to + 1, { class: "writer-link-source", "data-href": link.target, "data-kind": link.kind })); if (link.targetTo > link.targetFrom) decorations.push(Decoration.inline(position + link.targetFrom + 1, position + link.targetTo + 1, { class: "writer-link-target" })); } return false; }); return DecorationSet.create(state.doc, decorations); } } })], }), StarterKit.configure({ blockquote: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, codeBlock: false, heading: false, horizontalRule: false, link: false, underline: false, undoRedo: false, trailingNode: false, gapcursor: false, dropcursor: false }), CellLink.configure({ openOnClick: false, autolink: false }), CellImage.configure({ inline: true, allowBase64: true }), Highlight, ...cellFormats, ], content: formula ? { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: formula }] }] } : html, enableInputRules: false, enablePasteRules: false, editorProps: { attributes: { class: "writer-cell-editor", role: "textbox", "aria-label": cell.getAttribute("aria-label")!, "aria-multiline": "true", spellcheck: "true" }, handleKeyDown(_editorView, event) { if (event.isComposing) return false; if (sourceEditing && (event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) { event.preventDefault(); event.stopPropagation(); return true; } if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) { // The nested editor owns cursor movement, including word movement // and selections. Never let an arrow reach the prose editor. event.stopPropagation(); // Native cursor movement can precede ProseMirror's selectionchange // observer (especially during key repeat). Test the visible caret. const native = document.getSelection(); const readNative = (scroll = false) => { if (!native?.anchorNode || !native.focusNode || !_editorView.dom.contains(native.anchorNode) || !_editorView.dom.contains(native.focusNode)) return; const anchor = _editorView.posAtDOM(native.anchorNode, native.anchorOffset); const head = _editorView.posAtDOM(native.focusNode, native.focusOffset); if (anchor === _editorView.state.selection.anchor && head === _editorView.state.selection.head) return; const chain = editor!.chain().setTextSelection({ from: anchor, to: head }); (scroll ? chain.scrollIntoView() : chain).run(); }; readNative(); // ProseMirror reads a native move on the next selectionchange. Its // delayed focus check can run first and restore the old selection, // so the move is lost under load. Move the DOM selection here and // read the result at once. Other shortcuts stay with the browser. const mac = navigator.platform.includes("Mac"); const vertical = event.key === "ArrowUp" || event.key === "ArrowDown"; const word = mac ? event.altKey : event.ctrlKey; const moveNative = () => { if (!native || event.metaKey || (mac ? event.ctrlKey : event.altKey) || (vertical && word)) return false; native.modify( event.shiftKey ? "extend" : "move", vertical ? (event.key === "ArrowUp" ? "backward" : "forward") : event.key === "ArrowLeft" ? "left" : "right", vertical ? "line" : word ? "word" : "character", ); readNative(true); return true; }; if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || !_editorView.state.selection.empty) return moveNative(); const direction = event.key === "ArrowLeft" ? "left" : event.key === "ArrowRight" ? "right" : event.key === "ArrowUp" ? "up" : "down"; const horizontal = direction === "left" || direction === "right"; const backwards = direction === "left" || direction === "up"; const { $head } = _editorView.state.selection; // Pasted rich text can have several paragraphs within one cell. if ($head.depth && (backwards ? $head.before(1) > 0 : $head.after(1) < _editorView.state.doc.content.size)) return moveNative(); if (!_editorView.endOfTextblock(direction)) return moveNative(); event.preventDefault(); const cells = [...table!.querySelectorAll("th, td")]; const next = horizontal ? cells[cells.indexOf(cell) + (backwards ? -1 : 1)] : table!.rows[row + (backwards ? -1 : 1)]?.cells[column]; // Once there are no more cells in this direction, return to prose. if (!next) { leave(!backwards); return true; } const caret = _editorView.coordsAtPos(_editorView.state.selection.head); activate(next); const current = editor!; let position = backwards ? current.state.doc.content.size - 1 : 1; if (!horizontal) { // Enter the closest position on the first/last visual line, even // when either cell wraps or contains a hard break. const edge = current.view.coordsAtPos(position); position = current.view.posAtCoords({ left: caret.left, top: (edge.top + edge.bottom) / 2 })?.pos ?? position; } current.commands.setTextSelection(position); current.view.focus(); next.scrollIntoView({ block: "nearest", inline: "nearest" }); return true; } // Keep formatting shortcuts in the cell. The Writer around the table also binds Ctrl+B. if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) event.stopPropagation(); if ((event.ctrlKey || event.metaKey) && (event.key === "Home" || event.key === "End")) { event.preventDefault(); event.stopPropagation(); const position = event.key === "Home" ? 1 : editor!.state.doc.content.size - 1; editor?.commands.setTextSelection(event.shiftKey ? { from: editor.state.selection.anchor, to: position } : position); return true; } if ((event.ctrlKey || event.metaKey) && ["z", "y"].includes(event.key.toLowerCase())) { event.preventDefault(); event.stopPropagation(); const from = view.posAtDOM(root); (event.key.toLowerCase() === "y" || event.shiftKey ? redo : undo)(view); requestAnimationFrame(() => { const updated = [...view.dom.querySelectorAll(".writer-preview")].find(el => view.posAtDOM(el) === from); (updated?.querySelector("table")?.rows[row]?.cells[column])?.focus(); }); return true; } if (event.key === "Escape" && sourceEditing) { event.preventDefault(); finish(); wrapper.focus(); return true; } if (event.key === "Escape") { event.preventDefault(); leave(true); return true; } if (event.key === "Enter") { event.preventDefault(); if (event.shiftKey) editor?.commands.setHardBreak(); else if (event.ctrlKey || event.metaKey) leave(true); else { const next = table!.rows[row + 1]?.cells[column]; if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); } else add("row", true, column); } return true; } if (event.key === "Tab") { event.preventDefault(); const cells = [...table!.querySelectorAll("th, td")]; const next = cells[cells.indexOf(cell) + (event.shiftKey ? -1 : 1)]; if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); } else if (event.shiftKey) leave(false); else add("row", true); return true; } return false; }, }, onUpdate({ editor: current }) { const text = sourceEditing ? current.getText({ blockSeparator: "
" }).replace(/\r?\n/g, "
").replace(/\|/g, (_pipe, offset, value) => { let slashes = 0; for (let before = offset - 1; before >= 0 && value[before] === "\\"; before--) slashes++; return slashes % 2 ? "|" : "\\|"; }) : tableCellMarkdown(current.getJSON()); const source = controller.source; // Track the full edited range, including typed spaces. Re-parsing the // trimmed cell on each key would gradually turn those spaces into padding. const insert = contentFrom === undefined || contentTo === undefined ? replaceTableCell(source, sourceRow, column, text) : source.slice(0, contentFrom) + text + source.slice(contentTo); contentFrom ??= parseMarkdownTable(insert)?.rows[sourceRow]?.cells[column]?.from; if (contentFrom !== undefined) contentTo = contentFrom + text.length; change(insert); }, onSelectionUpdate({ editor: current }) { // Read the final mouse/keyboard selection after activation sets its // temporary caret. Menus and range selections keep their own focus. requestAnimationFrame(() => { if (current !== editor || current.isDestroyed || sourceEditing || !current.isFocused || current.view.composing) return; const { selection } = current.state; if (!selection.empty) return; const mark = selection.$from.marks().find(mark => mark.type.name === "link"); const range = mark && getMarkRange(selection.$from, mark.type, mark.attrs); if (range) editSource(range, selection.from - range.from); }); }, onBlur() { // A toolbar click, another cell, or the prose editor can now take focus. queueMicrotask(() => { if (active === cell && !cell.contains(document.activeElement) && !selectionControls?.keepEditing()) finish(); }); }, }); editor.commands.setTextSelection(editor.state.doc.content.size - 1); editor.view.focus(); refreshFormulas(); view.requestMeasure(); } function editSource(range: { from: number; to: number }, labelOffset?: number) { if (!editor || !active) return; const row = (active.parentElement as HTMLTableRowElement).rowIndex; const cell = parseMarkdownTable(controller.source)?.rows[row === 0 ? 0 : row + 1]?.cells[active.cellIndex]; if (!cell) return; const preceding = new Set(); editor.state.doc.descendants((node, position) => { const mark = node.marks.find(mark => mark.type.name === "link"); if (mark && position < range.from) { const found = getMarkRange(editor!.state.doc.resolve(position), mark.type, mark.attrs); if (found && found.from < range.from) preceding.add(found.from); } }); const link = documentLinks(cell.text)[preceding.size]; if (!link) return; sourceImages = new Map([...root.querySelectorAll("img[data-md-src]")].map(image => [image.dataset.mdSrc!, image.src])); sourceEditing = true; active.classList.add("is-source-editing"); editor.commands.setContent({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: cell.text }] }] }, { emitUpdate: false }); editor.commands.setTextSelection(labelOffset === undefined ? { from: link.targetFrom + 1, to: link.targetTo + 1 } : tableLinkLabelPosition(cell.text, link, labelOffset) + 1); editor.view.focus(); view.requestMeasure(); } function add(kind: "row" | "column", focusNew = false, column = 0) { const from = view.posAtDOM(root); finish(); const current = controller.source; change(kind === "column" ? appendTableColumn(current) : appendTableRow(current), true); view.focus(); requestAnimationFrame(() => { const updated = [...view.dom.querySelectorAll(".writer-preview")].find(el => view.posAtDOM(el) === from); if (!updated) return; if (focusNew) updated.querySelector("tbody tr:last-child")?.cells[column]?.focus(); if (kind === "column") { const viewport = updated.querySelector(".md-table-scroll")!; viewport.scrollLeft = viewport.scrollWidth; } else updated.querySelector(".table-add-row")?.scrollIntoView({ block: "nearest", inline: "nearest" }); view.requestMeasure(); }); } const help = document.createElement("div"); help.className = "table-edit-help"; help.hidden = true; const footer = document.createElement("div"); footer.className = "table-footer"; const tools = formulas?.createFormulaTools(finish, () => view.requestMeasure()); const formulaStatus = tools?.formulaStatus ?? document.createElement("span"); const formulaHint = tools?.formulaHint ?? document.createElement("div"); footer.append(help); if (tools) footer.append(tools.formulaTools, formulaHint); wrapper.after(footer); for (const kind of ["column", "row"] as const) { const button = document.createElement("button"); const label = kind === "column" ? tr("Add column to the right") : tr("Add row below"); button.type = "button"; button.className = `table-add table-add-${kind}`; tooltipCleanup.push(attachTooltip(button, () => label)); button.setAttribute("aria-label", label); const plus = document.createElement("span"); plus.append(actionIcon("plus")); plus.setAttribute("aria-hidden", "true"); button.append(plus); button.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); }); button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); add(kind); }); button.addEventListener("pointermove", event => { const rect = button.getBoundingClientRect(); button.style.setProperty("--table-add-position", `${kind === "column" ? Math.max(12, Math.min(rect.height - 12, event.clientY - rect.top)) : Math.max(12, Math.min(rect.width - 12, event.clientX - rect.left))}px`); }); wrapper.append(button); } for (const row of table.rows) for (const cell of row.cells) { cell.tabIndex = 0; cell.setAttribute("aria-label", (formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : "") + tr("Row {row}, column {column}", { row: row.rowIndex + 1, column: cell.cellIndex + 1 })); cell.addEventListener("focus", () => activate(cell)); } selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate, editSource }, actions); dragControls = tableDragControls(root, wrapper, table, scroll, view, () => controller.source, selectionControls.select, change); table.addEventListener("mousedown", event => { if (event.button !== 0) return; if (event.ctrlKey || event.metaKey || !(event.target instanceof Element)) return; const cell = event.target.closest("td, th"); if (!cell) return; event.stopPropagation(); if (active !== cell) { event.preventDefault(); activate(cell); const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY }); if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); } } }); refreshFormulas(); for (const row of table.rows) for (const cell of row.cells) { tooltipCleanup.push(attachTooltip(cell, () => cell.dataset.cellHint || "")); } }