Update editor, themes, menus, backgrounds, and release tooling

This commit is contained in:
Knotty Wyvern
2026-10-14 16:19:51 -07:00
parent f6eaa52949
commit edef2520af
113 changed files with 5722 additions and 386 deletions
+31 -9
View File
@@ -4,12 +4,14 @@
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession } from "./sessions";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
import { codeFont } from "./codeFont";
import { connectMonacoCompletion } from "$lib/completion/monaco";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { codeMenu } from "./codeMenu";
import type { TableContextActions } from "./tableCellActions";
import { documentLinks, documentLinkAt } from "./documentLinks";
@@ -22,13 +24,15 @@
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
};
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
export function focus() { editor?.focus(); }
let ready = $state(0);
let applying = false;
let loadError = $state<string | null>(null);
@@ -116,7 +120,7 @@
renderWhitespace: "selection",
bracketPairColorization: { enabled: true },
overviewRulerLanes: 0,
contextmenu: !markdown,
contextmenu: false,
...monacoChrome(mode),
});
editor = view;
@@ -167,13 +171,31 @@
});
view.pushUndoStop();
},
select(from, to) {
const start = model.getPositionAt(from), end = model.getPositionAt(to);
view.setSelection(new monaco.Selection(start.lineNumber, start.column, end.lineNumber, end.column));
view.revealPositionInCenterIfOutsideViewport(end);
},
selectAll() { view.setSelection(model.getFullModelRange()); view.focus(); },
focus() { view.focus(); },
}, untrack(() => tableActions), message => { loadError = message; });
listeners.push(view.onContextMenu(event => {
event.event.preventDefault(); event.event.stopPropagation();
menu?.open(event.event.posx, event.event.posy);
}));
undo() { view.trigger("markdown-menu", "undo", null); },
redo() { view.trigger("markdown-menu", "redo", null); },
canUndo() { return model.canUndo(); },
canRedo() { return model.canRedo(); },
}, untrack(() => tableActions), message => { loadError = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
} else {
menu = codeMenu(view, message => { loadError = message; });
}
const openContextMenu = (event: MouseEvent) => {
event.preventDefault(); event.stopImmediatePropagation();
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
const selection = view.getSelection();
if (position && (!selection || selection.isEmpty() || !selection.containsPosition(position))) view.setPosition(position);
view.focus();
menu?.open(event.clientX, event.clientY, undefined, position ? model.getOffsetAt(position) : undefined);
};
el.addEventListener("contextmenu", openContextMenu, true);
listeners.push({ dispose: () => el.removeEventListener("contextmenu", openContextMenu, true) });
listeners.push(view.onKeyDown(event => {
if (event.browserEvent.key !== "ContextMenu" && !(event.shiftKey && event.browserEvent.key === "F10")) return;
event.preventDefault(); event.stopPropagation();
@@ -183,7 +205,6 @@
}));
listeners.push(view.onDidChangeCursorSelection(() => menu?.close(false)));
listeners.push(model.onDidChangeContent(() => menu?.close(false)));
}
const documentId = untrack(() => buffer.id);
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
@@ -209,6 +230,7 @@
releaseDrop?.();
listeners.forEach(listener => listener.dispose());
view?.dispose();
if (session) releaseEditorSession(session);
editor = undefined;
};
});
+28 -16
View File
@@ -1,7 +1,6 @@
<script lang="ts">
import { pluginHost } from "$lib/plugins/registry";
import { useSpellingMenu } from "./spellingMenu";
import { spellingWord } from "./spellingWord";
import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte";
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
import { EditorView, drawSelection, keymap } from "@codemirror/view";
@@ -15,11 +14,11 @@
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages } from "$lib/workspace/noteHtml";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession } from "./sessions";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
@@ -27,6 +26,7 @@
import { markdownTitle } from "$lib/workspace/media";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
import { documentLinkAt } from "./documentLinks";
@@ -42,13 +42,15 @@
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
focusTitle?: boolean;
onTitleFocused?: () => void;
};
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
export function focus() { editor?.focus(); }
let error = $state("");
let model: import("monaco-editor").editor.ITextModel | undefined;
let ModelSelection: typeof import("monaco-editor").Selection;
@@ -195,7 +197,7 @@
if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, indentWithTab, ...searchKeymap, ...historyKeymap, ...defaultKeymap]), EditorView.lineWrapping,
liveMarkdown(urls, untrack(() => tableActions), {
liveMarkdown(urls, { ...untrack(() => tableActions), linkActions: () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }) }, {
open: image => onOpenLink?.(image.dataset.mdKind === "wiki" ? "wiki" : "md", image.dataset.mdSrc || ""),
reveal: async image => {
for (const path of linkCandidates(current.relPath, image.dataset.mdSrc || "", "md")) {
@@ -242,12 +244,11 @@
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
if (event.target instanceof HTMLElement && spellingWord(event.target.closest<HTMLElement>('[contenteditable="true"]') ?? event.target, event.clientX, event.clientY) && useSpellingMenu(event, view.state.selection.main.empty)) { menu?.close(false); return false; }
event.preventDefault();
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
const position = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
const selection = view.state.selection.main;
if (position !== null && (selection.empty || position < selection.from || position > selection.to)) view.dispatch({ selection: { anchor: position } });
menu?.open(event.clientX, event.clientY);
menu?.open(event.clientX, event.clientY, selection.empty && isSpellingTarget(event.target) ? position ?? undefined : undefined, position ?? undefined);
return true;
},
keydown(event, view) {
@@ -255,7 +256,7 @@
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const coords = view.coordsAtPos(view.state.selection.main.head);
if (coords) menu?.open(coords.left, coords.bottom);
if (coords) menu?.open(coords.left, coords.bottom, view.state.selection.main.empty ? view.state.selection.main.head : undefined);
return true;
},
mousedown(event, view) {
@@ -275,7 +276,12 @@
},
}),
];
freshState = source => EditorState.create({ doc: source, extensions });
// Start in the body so the initial caret does not reveal properties source.
// Saved selections and explicit line navigation still restore their positions.
freshState = source => {
const doc = EditorState.create({ doc: source }).doc;
return EditorState.create({ doc, selection: { anchor: documentBodyStart(doc.toString()) }, extensions });
};
const saved = session.writer;
const state = saved?.source === lastValue
? EditorState.fromJSON(saved.state, { extensions })
@@ -314,9 +320,14 @@
return { source: doc.toString(), selection: selection.main, valid: () => editor === view && view.state.doc === doc && view.state.selection.eq(selection) };
},
apply(edit) { view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head }, userEvent: "input.markdown", annotations: isolateHistory.of("full") }); },
select(from, to) { view.dispatch({ selection: { anchor: from, head: to }, scrollIntoView: true }); },
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
focus() { view.focus(); },
}, untrack(() => tableActions), message => { error = message; });
undo() { clearTimeout(historyTimer); model?.pushStackElement(); void model?.undo(); },
redo() { clearTimeout(historyTimer); void model?.redo(); },
canUndo() { return model?.canUndo() ?? false; },
canRedo() { return model?.canRedo() ?? false; },
}, untrack(() => tableActions), message => { error = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
if (!focusTitle && shouldFocusOnMount()) view.focus();
}).catch(reason => { if (!cancelled) error = String(reason); });
return () => {
@@ -330,6 +341,7 @@
releaseScroll?.();
if (session && editor && scroll) session.writer = { source: modelSource(editor.state), state: editor.state.toJSON(), scroll };
editor?.destroy();
if (session) releaseEditorSession(session);
releaseSelection?.();
editor = undefined;
};
@@ -404,22 +416,22 @@
.live-writer :global(.writer-heading:hover)::before { display: none; }
.live-writer :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
.live-writer :global(.cm-selectionBackground), .live-writer :global(.cm-focused .cm-selectionBackground) { background: var(--rs-bg-active); }
.live-writer :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .live-writer :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground) { background: var(--rs-selection); }
.live-writer :global(.writer-blank) { font-size: .75em; }
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
.live-writer :global(.writer-emphasis) { font-style: italic; }
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
.live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-link-source) { color: var(--rs-accent); }
.live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-bg-elevated); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-code-block-bg); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; }
.live-writer :global(.writer-code-tooltip) { display: none; position: absolute; z-index: 2; top: 100%; right: 0; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: nowrap; pointer-events: none; }
.live-writer :global(.writer-code-copy:focus-visible .writer-code-tooltip) { display: block; }
.live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); }
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
+59
View File
@@ -0,0 +1,59 @@
import type { editor } from "monaco-editor";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
/** Keep Monaco editing commands in the host's shared action menu. */
export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: string) => void) {
let root: HTMLElement | undefined;
function close(focus = true) {
root?.remove(); root = undefined;
if (focus) view.focus();
}
const outside = (event: MouseEvent) => { if (root && !root.contains(event.target as Node)) close(false); };
const scroll = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
document.addEventListener("mousedown", outside, true);
document.addEventListener("scroll", scroll, true);
window.addEventListener("resize", resize);
function open(x: number, y: number) {
close(false);
const model = view.getModel(), selection = view.getSelection();
if (!model || !selection) return;
const version = model.getVersionId();
const valid = () => view.getModel() === model && !model.isDisposed() && model.getVersionId() === version && !!view.getSelection()?.equalsRange(selection);
const selected = model.getValueInRange(selection);
const replace = (text: string) => {
if (!valid()) return;
view.pushUndoStop();
view.executeEdits("code-menu", [{ range: selection, text }]);
view.pushUndoStop(); view.focus();
};
const clipboard = async (kind: "cut" | "copy" | "paste") => {
close();
try {
if (kind === "paste") replace(await navigator.clipboard.readText());
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
};
const run = (id: string) => { close(); void view.getAction(id)?.run(); };
const items: ActionMenuItem[] = [
{ label: "Undo", icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } },
{ label: "Redo", icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } },
{ separator: true },
{ label: "Change all occurrences", icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") },
{ separator: true },
{ label: "Cut", icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
{ label: "Select all", icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } },
{ separator: true },
{ label: "Command palette", icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") },
];
root = actionMenu(x, y, items, close, "Code text actions");
}
return { open, close, destroy() {
close(false);
document.removeEventListener("mousedown", outside, true);
document.removeEventListener("scroll", scroll, true);
window.removeEventListener("resize", resize);
} };
}
+8 -4
View File
@@ -1,6 +1,6 @@
import { markdownLanguage } from "@codemirror/lang-markdown";
export type DocumentLink = { from: number; to: number; kind: "md" | "wiki"; target: string };
export type DocumentLink = { from: number; to: number; targetFrom: number; targetTo: number; kind: "md" | "wiki"; target: string };
/** Source ranges survive the change from formatted text to editable Markdown. */
export function documentLinks(source: string): DocumentLink[] {
@@ -15,13 +15,17 @@ export function documentLinks(source: string): DocumentLink[] {
const url = node.node.getChild("URL");
if (!url) return;
const target = source.slice(url.from, url.to).replace(/^<|>$/g, "").replace(/\\([\\()])/g, "$1");
links.push({ from: node.from, to: node.to, kind: "md", target });
const angled = source[url.from] === "<";
links.push({ from: node.from, to: node.to, targetFrom: url.from + Number(angled), targetTo: url.to - Number(angled), kind: "md", target });
return false;
} });
const occupied = (from: number, to: number) => [...literal, ...links].some(range => from < range.to && to > range.from);
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
if (occupied(match.index, match.index + match[0].length)) continue;
links.push({ from: match.index, to: match.index + match[0].length, kind: "wiki", target: match[1].split("|")[0].trim() });
if (source[match.index - 1] === "!") continue;
const raw = match[1].split(/\\?\|/)[0], target = raw.trim();
const targetFrom = match.index + 2 + raw.length - raw.trimStart().length;
links.push({ from: match.index, to: match.index + match[0].length, targetFrom, targetTo: targetFrom + target.length, kind: "wiki", target });
}
for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) {
if (occupied(match.index, match.index + match[0].length)) continue;
@@ -29,7 +33,7 @@ export function documentLinks(source: string): DocumentLink[] {
const open = (match[0].match(/\(/g) || []).length, close = (match[0].match(/\)/g) || []).length;
return suffix.slice(0, Math.max(0, suffix.length - Math.max(0, close - open)));
});
links.push({ from: match.index, to: match.index + target.length, kind: "md", target });
links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md", target });
}
return links.sort((a, b) => a.from - b.from);
}
-2
View File
@@ -7,8 +7,6 @@
.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 1px; }
.rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); }
.rs-heading-tooltip { display: none; position: absolute; z-index: 5; top: 100%; inset-inline-start: 0; max-width: 240px; width: max-content; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: normal; pointer-events: none; }
.rs-heading-toggle:hover .rs-heading-tooltip, .rs-heading-toggle:focus-visible .rs-heading-tooltip { display: block; }
.rs-heading-collapsed::after { content: " …"; color: var(--rs-text-dim); font-weight: normal; }
.live-writer .cm-foldPlaceholder { border: none; background: transparent; color: var(--rs-text-dim); cursor: pointer; padding: 0 .3em; }
.reading [hidden] { display: none !important; }
+7 -8
View File
@@ -2,6 +2,8 @@ import { StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view";
import { codeFolding, foldEffect, foldKeymap, foldedRanges, foldService, syntaxTree, unfoldEffect } from "@codemirror/language";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
export type HeadingRange = { start: number; from: number; to: number; level: number; label: string };
@@ -29,12 +31,9 @@ export function headingButton(label: string, collapsed: boolean): HTMLButtonElem
button.setAttribute("aria-expanded", String(!collapsed));
const title = `${collapsed ? "Expand" : "Collapse"} ${label || "heading"}`;
button.setAttribute("aria-label", title);
button.title = title;
tooltipCleanups.set(button, attachTooltip(button, () => button.getAttribute("aria-label") || ""));
const icon = actionIcon("chevron");
const tooltip = document.createElement("span");
tooltip.className = "rs-heading-tooltip";
tooltip.textContent = title;
button.append(icon, tooltip);
button.append(icon);
return button;
}
@@ -55,6 +54,7 @@ class HeadingToggle extends WidgetType {
};
return button;
}
destroy(dom: HTMLElement) { tooltipCleanups.get(dom)?.(); }
ignoreEvent() { return true; }
}
@@ -103,8 +103,7 @@ export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>)
const label = `${collapsed.has(item.key) ? "Expand" : "Collapse"} ${item.label}`;
button.setAttribute("aria-expanded", String(!collapsed.has(item.key)));
button.setAttribute("aria-label", label);
button.title = label;
button.querySelector(".rs-heading-tooltip")!.textContent = label;
item.heading.classList.toggle("rs-heading-collapsed", collapsed.has(item.key));
}
if (!collapsed.has(item.key)) return;
@@ -137,7 +136,7 @@ export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>)
},
destroy() {
elements.forEach(element => { element.hidden = false; });
headings.forEach(item => { item.heading.querySelector(".rs-heading-toggle")?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); });
headings.forEach(item => { const button = item.heading.querySelector<HTMLElement>(".rs-heading-toggle"); if (button) tooltipCleanups.get(button)?.(); button?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); });
},
};
}
+5 -2
View File
@@ -1,4 +1,6 @@
import { actionIcon, type ActionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
export type ImageActions = {
@@ -32,7 +34,7 @@ function button(label: string, icon: ActionIcon, action: () => void) {
control.type = "button";
control.className = "image-action";
control.setAttribute("aria-label", label);
control.dataset.tooltip = label;
tooltipCleanups.set(control, attachTooltip(control, () => label));
control.append(actionIcon(icon));
control.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); action(); });
return control;
@@ -73,7 +75,7 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
dialog.append(header, viewport);
dialog.addEventListener("click", event => { if (event.target === dialog || event.target === viewport) dialog.close(); });
// Escape and focus trapping are provided by the native modal dialog.
dialog.addEventListener("close", () => { dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true });
dialog.addEventListener("close", () => { [zoomOut, zoomIn, fit, close].forEach(button => tooltipCleanups.get(button)?.()); dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true });
image.addEventListener("load", () => resize(scale));
document.body.append(dialog);
dialog.showModal();
@@ -103,6 +105,7 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
toolbar.append(zoom);
if (actions.edit) toolbar.append(button(actions.editing ? "Hide image source" : "Edit image source", "code", actions.editing && actions.done ? actions.done : actions.edit));
frame.append(toolbar);
cleanup.push(() => toolbar.querySelectorAll<HTMLButtonElement>("button").forEach(button => tooltipCleanups.get(button)?.()));
let menu: HTMLElement | undefined;
let openingMenu = false;
function closeMenu(focus = true) { menu?.remove(); menu = undefined; if (focus && frame.isConnected) frame.focus({ preventScroll: true }); }
+1 -1
View File
@@ -64,7 +64,7 @@ export class ImagePreview extends WidgetType {
const edit = document.createElement("button");
edit.type = "button"; edit.className = "image-action";
const label = this.editing ? "Hide image source" : "Edit image source";
edit.setAttribute("aria-label", label); edit.dataset.tooltip = label;
edit.setAttribute("aria-label", label); edit.dataset.editorTooltip = label;
edit.append(actionIcon("code"));
edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); });
dom.append(edit);
+30
View File
@@ -0,0 +1,30 @@
import type { ActionMenuItem } from "../ui/actionMenu";
export type MenuLink = { kind: "md" | "wiki"; target: string };
export type DocumentLinkActions = {
open?: (link: MenuLink) => void | Promise<void>;
browser?: (target: string) => void | Promise<void>;
defaultBrowser?: (target: string) => void | Promise<void>;
workspaceItems?: (link: MenuLink) => ActionMenuItem[];
};
export function linkMenuItems(link: MenuLink, actions: DocumentLinkActions, close: () => void, report: (message: string) => void, edit?: () => void): ActionMenuItem[] {
const run = (action: () => void | Promise<void>) => () => {
close();
void Promise.resolve().then(action).catch(error => report(error instanceof Error ? error.message : String(error)));
};
const external = /^(https?:\/\/|mailto:)/i.test(link.target);
const items: ActionMenuItem[] = external ? [
...(actions.browser && /^https?:\/\//i.test(link.target) ? [{ label: "Open link in app browser", icon: "globe" as const, run: run(() => actions.browser!(link.target)) }] : []),
...(actions.defaultBrowser ? [{ label: "Open link in default browser", icon: "external" as const, run: run(() => actions.defaultBrowser!(link.target)) }] : []),
] : [];
if (!items.length && actions.open) items.push({ label: external ? "Open link" : "Open in new tab", icon: external ? "external" : "file-plus", run: run(() => actions.open!(link)) });
if (!external && actions.workspaceItems) {
const wrap = (item: ActionMenuItem): ActionMenuItem => "separator" in item ? item : { ...item, run: item.run ? run(item.run) : undefined, children: item.children?.map(wrap) };
const workspaceItems = actions.workspaceItems(link).filter(item => !edit || "separator" in item || !["Rename…", "Move file to…", "Open in default app"].includes(item.label));
items.push(...workspaceItems.map(wrap));
}
items.push({ label: external ? "Copy URL" : "Copy link target", icon: "link", run: run(() => navigator.clipboard.writeText(link.target)) });
if (edit) items.push({ label: "Edit link", icon: "rename", run: () => { close(); edit(); } });
return items;
}
+29 -14
View File
@@ -1,5 +1,5 @@
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
@@ -10,6 +10,8 @@ import { imageControls } from "./imageControls";
import { ImagePreview, type ImageContext } from "./imagePreview";
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
import { documentLinks } from "./documentLinks";
import { pluginHost } from "../plugins/registry.ts";
@@ -17,6 +19,20 @@ const previewFormulas = new WeakMap<HTMLElement, unknown>();
export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>();
const linkTooltips = ViewPlugin.define(view => {
const attached = new Map<HTMLElement, () => void>();
const refresh = () => {
for (const [node, dispose] of attached) if (!view.dom.contains(node)) { dispose(); attached.delete(node); }
for (const node of view.dom.querySelectorAll<HTMLElement>("[data-editor-tooltip]")) {
if (!attached.has(node)) attached.set(node, attachTooltip(node, () => node.dataset.editorTooltip || ""));
}
};
const observer = new MutationObserver(refresh);
observer.observe(view.dom, { childList: true, subtree: true });
refresh();
return { destroy() { observer.disconnect(); attached.forEach(dispose => dispose()); } };
});
class CodeCopy extends WidgetType {
constructor(readonly code: string) { super(); }
eq(other: CodeCopy) { return this.code === other.code; }
@@ -25,24 +41,18 @@ class CodeCopy extends WidgetType {
button.type = "button";
button.className = "rs-fence-copy writer-code-copy";
button.setAttribute("aria-label", "Copy code");
button.title = "Copy code";
const help = document.createElement("span");
help.className = "writer-code-tooltip";
help.setAttribute("role", "tooltip");
help.textContent = "Copy code";
button.append(actionIcon("copy"), help);
button.dataset.editorTooltip = "Copy code";
button.append(actionIcon("copy"));
button.onmousedown = event => event.preventDefault();
button.onclick = async event => {
event.preventDefault(); event.stopPropagation();
try {
await navigator.clipboard.writeText(this.code);
button.dataset.copied = "true";
button.title = "Copied";
help.textContent = "Copied";
button.dataset.editorTooltip = "Copied";
button.setAttribute("aria-label", "Code copied");
} catch {
button.title = "Could not copy code";
help.textContent = "Could not copy code";
button.dataset.editorTooltip = "Could not copy code";
button.setAttribute("aria-label", "Could not copy code");
}
};
@@ -238,7 +248,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
if (!match) return;
replace(node.from, node.from + 1);
replace(node.from + 1 + match[1].length, node.to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", title: "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
return false;
}
if (node.name === "TaskMarker") {
@@ -261,11 +271,16 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1);
replace(from, labelStart);
replace(to - 2, to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0] } }).range(labelStart, to - 2));
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0], "data-editor-tooltip": "Ctrl+click to open link" } }).range(labelStart, to - 2));
}
for (const link of documentLinks(source)) {
if (!selected(link.from, link.to) || hidden(link.from, link.to)) continue;
mark(link.from, link.to, "writer-link-source");
mark(link.targetFrom, link.targetTo, "writer-link-target");
}
return Decoration.set(ranges, true);
}
return [imageSource, StateField.define<DecorationSet>({
return [imageSource, linkTooltips, StateField.define<DecorationSet>({
create: build,
update(value, transaction) {
return transaction.docChanged || transaction.selection
+39 -2
View File
@@ -1,6 +1,10 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { wordAt } from "./spellingWord";
import { pickLinkDocument } from "./documentPicker";
import { externalLinkText, workspaceLinkText } from "./linkCommands";
import { documentLinkAt } from "./documentLinks";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
import { htmlToMarkdown } from "../workspace/htmlToMarkdown";
import { cellFormats, type TableContextActions } from "./tableCellActions";
import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands";
@@ -10,11 +14,16 @@ export type MarkdownMenuEditor = {
apply: (edit: MarkdownEdit) => void;
selectAll: () => void;
focus: () => void;
select: (from: number, to: number) => void;
undo?: () => void;
redo?: () => void;
canUndo?: () => boolean;
canRedo?: () => boolean;
};
// A shared controller keeps menus, async selection guards, and clipboard behavior
// identical in the writing editor and the source editor.
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void) {
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void, linkActions: () => DocumentLinkActions = () => ({})) {
let root: HTMLElement | undefined, destroyed = false;
const pending = new AbortController();
function close(focus = true) {
@@ -28,10 +37,11 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
document.addEventListener("scroll", scroll, true);
window.addEventListener("resize", resize);
function open(x: number, y: number) {
function open(x: number, y: number, spellingOffset?: number, linkOffset?: number) {
close(false);
const snapshot = editor.snapshot(), { source, selection } = snapshot;
const text = source.slice(selection.from, selection.to);
const selectedLink = documentLinkAt(source, linkOffset ?? selection.from);
const valid = () => !destroyed && snapshot.valid();
function apply(edit: MarkdownEdit) {
if (!valid()) return;
@@ -74,6 +84,15 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) });
const insert = (label: string, kind: InsertBlock, icon: "footnote" | "table" | "quote" | "rule" | "code" | "math"): ActionMenuItem => ({ label, icon, run: () => apply(insertBlock(source, selection, kind)) });
const items: ActionMenuItem[] = [
...(selectedLink ? [...linkMenuItems(selectedLink, linkActions(), () => close(false), report, () => {
if (!valid()) return;
editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus();
}), { separator: true as const }] : []),
...(editor.undo ? [
{ label: "Undo", icon: "undo" as const, shortcut: "Ctrl+Z", disabled: !editor.canUndo?.(), run: () => { close(); editor.undo?.(); } },
{ label: "Redo", icon: "redo" as const, shortcut: "Ctrl+Shift+Z", disabled: !editor.canRedo?.(), run: () => { close(); editor.redo?.(); } },
{ separator: true as const },
] : []),
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
@@ -104,6 +123,24 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
{ label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } },
];
root = actionMenu(x, y, items, close, "Markdown text actions");
const opened = root;
const word = spellingOffset === undefined ? null : wordAt(source, spellingOffset);
if (word && isTauri()) {
const languages = [...new Set([document.documentElement.lang, ...navigator.languages].filter(Boolean))];
void invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }).then(result => {
if (!result.misspelled || root !== opened || !valid()) return;
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => apply(replacement(word, value)) }));
if (!suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true });
suggestions.push({ label: "Add to dictionary", icon: "book", run: () => {
close();
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary."));
} });
const focusedLabel = opened.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
opened.remove();
root = actionMenu(x, y, [...suggestions, { separator: true }, ...items], close, "Markdown text actions");
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
}).catch(() => { /* Editing actions remain available without spelling suggestions. */ });
}
}
return { open, close, destroy() {
destroyed = true; pending.abort(); close(false);
+27 -12
View File
@@ -12,28 +12,43 @@ export let currentTheme = 'runestone-default-dark';
function updateTheme() {
const style = getComputedStyle(document.documentElement);
const color = (name: string) => style.getPropertyValue(`--rs-${name}`).trim();
const sakura = document.documentElement.dataset.palette === 'sakura';
const syntaxColor = (role: string) => {
const value = document.documentElement.style.getPropertyValue(`--rs-syntax-${role}`).trim();
const match = /^#([0-9a-f]{3,8})$/i.exec(value);
if (!match) return undefined;
const hex = match[1];
return hex.length === 3 || hex.length === 4 ? `#${hex.slice(0, 3).split('').map(part => part + part).join('')}`
: hex.length === 6 || hex.length === 8 ? `#${hex.slice(0, 6)}` : undefined;
};
const syntaxRules = [
['keyword', 'keyword'], ['variable.parameter', 'parameter'], ['variable', 'local'],
['variable.predefined', 'global'], ['variable.property', 'instance'], ['variable.static', 'static'],
['identifier', 'local'], ['string', 'string'], ['number', 'number'], ['comment', 'comment'],
['type', 'type'], ['type.identifier', 'type'], ['entity.name.type', 'type'],
['function', 'function'], ['predefined', 'function'], ['delimiter', 'global'],
].flatMap(([token, role]) => {
const foreground = syntaxColor(role);
return foreground ? [{ token, foreground: foreground.slice(1) }] : [];
});
// Monaco permits only letters, digits, and hyphens in registered theme names.
const palette = (document.documentElement.dataset.palette || 'default').replace(/[^a-z0-9-]/gi, '-');
currentTheme = `runestone-${palette}-${document.documentElement.dataset.theme || 'dark'}`;
monaco.editor.defineTheme(currentTheme, {
base: document.documentElement.dataset.theme === 'light' ? 'vs' : 'vs-dark',
inherit: true,
rules: sakura ? [
{ token: 'keyword', foreground: color('syntax-keyword').replace('#', '') },
{ token: 'variable.parameter', foreground: color('syntax-parameter').replace('#', '') },
{ token: 'variable', foreground: color('syntax-local').replace('#', '') },
{ token: 'variable.predefined', foreground: color('syntax-global').replace('#', '') },
{ token: 'variable.property', foreground: color('syntax-instance').replace('#', '') },
{ token: 'variable.static', foreground: color('syntax-static').replace('#', '') },
] : [],
rules: syntaxRules,
colors: {
'editor.background': color('bg'), 'editor.foreground': color('text'),
...Object.fromEntries(['keyword', 'number', 'type', 'string', 'function', 'parameter'].flatMap((role, index) => {
const foreground = syntaxColor(role);
return foreground ? [[`editorBracketHighlight.foreground${index + 1}`, foreground]] : [];
})),
'editor.background': '#00000000', 'editor.foreground': color('text'),
'editor.lineHighlightBackground': color('bg-active'), 'editor.selectionBackground': color('selection'),
'editor.inactiveSelectionBackground': color('selection'), 'editor.selectionForeground': color('selection-text'),
'editorCursor.foreground': color('accent'), 'editorLineNumber.foreground': color('text-dim'),
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': color('bg'),
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': '#00000000',
'editorWidget.background': color('bg-elevated'), 'editorWidget.border': color('border'),
'minimap.background': color('bg-elevated'), 'editorIndentGuide.background1': color('border'),
'minimap.background': '#00000000', 'editorIndentGuide.background1': color('border'),
'editorIndentGuide.activeBackground1': color('text-dim'),
},
});
+1 -5
View File
@@ -21,11 +21,7 @@ class NoteTitle extends WidgetType {
button.className = "note-title-button";
button.setAttribute("aria-label", "Rename note");
button.append(document.createTextNode(this.title), actionIcon("rename"));
const help = document.createElement("span");
help.className = "note-title-help";
help.textContent = "Rename note";
help.setAttribute("role", "tooltip");
button.append(help);
button.dataset.editorTooltip = "Rename note";
heading.replaceChildren(button);
const input = document.createElement("input");
+58
View File
@@ -0,0 +1,58 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
/** Preserve the DOM range while the shared menu owns keyboard focus. */
export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, search: ((text: string) => void) | undefined, report: (message: string) => void) {
let root: HTMLElement | undefined;
let previousFocus: HTMLElement | null = null;
let range: Range | undefined;
function close(restore = true) {
if (!root) return;
root.remove(); root = undefined;
if (restore) {
(previousFocus?.isConnected ? previousFocus : host).focus({ preventScroll: true });
if (range?.startContainer.isConnected && range.endContainer.isConnected) {
const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range);
}
}
}
function open(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || event.target instanceof Element && event.target.closest("input, textarea, [contenteditable=true], .rs-image-frame")) return;
const keyboard = event instanceof KeyboardEvent;
if (keyboard && event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
const selection = window.getSelection();
const selected = selection?.rangeCount ? selection.getRangeAt(0) : undefined;
range = selected && host.contains(selected.startContainer) && host.contains(selected.endContainer) ? selected.cloneRange() : undefined;
const text = range?.toString() ?? "";
const target = event.target instanceof Element ? event.target : null;
const anchor = target?.closest("a") ?? (keyboard && selection?.anchorNode ? (selection.anchorNode.parentElement?.closest("a") ?? null) : null);
if (!text && !anchor) return;
event.preventDefault(); event.stopPropagation(); close(false);
previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host;
const items: ActionMenuItem[] = [];
if (text) items.push(
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", run: () => { close(); void navigator.clipboard.writeText(text).catch(() => report("Clipboard unavailable. Use Ctrl+C to copy.")); } },
{ label: `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”`, icon: "search", disabled: !search, run: () => { close(false); search?.(text); } },
);
if (anchor) {
if (items.length) items.push({ separator: true });
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: "Open link", icon: "link", run: () => { close(false); (anchor as HTMLElement).click(); } });
else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => close(false), report));
}
const rect = keyboard ? (range?.getBoundingClientRect() ?? anchor?.getBoundingClientRect() ?? host.getBoundingClientRect()) : null;
root = actionMenu(rect?.left ?? (event as MouseEvent).clientX, rect?.bottom ?? (event as MouseEvent).clientY, items, close, "Reading actions");
}
const outside = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
host.addEventListener("contextmenu", open);
host.addEventListener("keydown", open);
document.addEventListener("mousedown", outside, true);
document.addEventListener("scroll", outside, true);
window.addEventListener("resize", resize);
return () => {
close(false);
host.removeEventListener("contextmenu", open); host.removeEventListener("keydown", open);
document.removeEventListener("mousedown", outside, true); document.removeEventListener("scroll", outside, true);
window.removeEventListener("resize", resize);
};
}
+4 -5
View File
@@ -1,10 +1,9 @@
// Readers retain editor selection when toolbar buttons take focus.
let current: { id: string; read: () => string } | undefined;
const readers = new Map<string, () => string>();
export function registerSelection(id: string, read: () => string): () => void {
const owner = { id, read };
current = owner;
return () => { if (current === owner) current = undefined; };
readers.set(id, read);
return () => { if (readers.get(id) === read) readers.delete(id); };
}
export function selectedEditorText(id?: string): string {
return current && current.id === id ? current.read() : "";
return id ? readers.get(id)?.() ?? "" : "";
}
+14 -2
View File
@@ -3,17 +3,20 @@ import type { OpenBuffer } from "../workspace/types";
import { languageFor } from "./languageFor";
type Session = {
users: number;
model: Monaco.editor.ITextModel;
view: Monaco.editor.ICodeEditorViewState | null;
writerSelections: Map<number, import("@codemirror/state").EditorSelection>;
writer?: { source: string; state: ReturnType<import("@codemirror/state").EditorState["toJSON"]>; scroll: ReturnType<import("@codemirror/view").EditorView["scrollSnapshot"]> };
};
const sessions = new Map<string, Session>();
let retained = new Set<string>();
export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Session {
let session = sessions.get(buffer.id);
if (!session) {
session = {
users: 0,
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
view: null,
writerSelections: new Map(),
@@ -21,12 +24,21 @@ export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Sessio
sessions.set(buffer.id, session);
}
monaco.editor.setModelLanguage(session.model, languageFor(buffer.relPath));
session.users++;
return session;
}
export function retainEditorSessions(ids: string[]) {
const retained = new Set(ids);
retained = new Set(ids);
for (const [id, session] of sessions) {
if (!retained.has(id)) { session.model.dispose(); sessions.delete(id); }
if (!retained.has(id) && session.users === 0) { session.model.dispose(); sessions.delete(id); }
}
}
export function releaseEditorSession(session: Session) {
session.users = Math.max(0, session.users - 1);
if (session.users) return;
for (const [id, entry] of sessions) {
if (entry === session && !retained.has(id)) { session.model.dispose(); sessions.delete(id); break; }
}
}
+28 -4
View File
@@ -1,9 +1,12 @@
import type { Editor, JSONContent } from "@tiptap/core";
import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
import { requestText } from "../workspace/dialogs.svelte";
import { extractedCellMarkdown } from "./tableCellMarkdown";
import type { ActionMenuItem } from "../ui/actionMenu";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
import { documentLinkAt } from "./documentLinks";
export type TableContextActions = {
linkActions?: () => DocumentLinkActions;
onSearch?: (text: string) => void;
onExtract?: (markdown: string, label: string, valid: () => boolean) => Promise<string | null>;
};
@@ -13,8 +16,9 @@ export const cellFormats = [
["Code", "code"], ["Math", "math"], ["Comment", "comment"], ["Clear formatting", "clear"],
] as const;
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void): ActionMenuItem[] {
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void, editSource: (range: { from: number; to: number }) => void): ActionMenuItem[] {
const selection = editor.state.selection, doc = editor.state.doc;
const sourceEditing = editor.view.dom.parentElement?.classList.contains("is-source-editing");
const text = doc.textBetween(selection.from, selection.to, "\n");
const valid = () => !editor.isDestroyed && editor.state.doc === doc && editor.state.selection.eq(selection);
function run(command: () => void) { if (!valid()) return; close(); transaction(() => { editor.view.focus(); command(); }); }
@@ -41,6 +45,21 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
});
});
}
const at = doc.resolve(selection.from);
const mark = [...at.marks(), ...(at.nodeAfter?.marks || [])].find(mark => mark.type.name === "link");
const linkRange = mark && getMarkRange(doc.resolve(selection.from), mark.type, mark.attrs);
const sourceLink = sourceEditing ? documentLinkAt(doc.textContent, selection.from - 1)
|| documentLinkAt(doc.textContent, selection.from - 2) : undefined;
const selectedLink = sourceLink || (mark && linkRange ? { kind: mark.attrs["data-kind"] === "wiki" ? "wiki" as const : "md" as const, target: String(mark.attrs.href) } : undefined);
function editLink() {
if (!selectedLink) return;
if (!valid()) return;
close();
if (sourceLink) {
editor.commands.setTextSelection({ from: sourceLink.targetFrom + 1, to: sourceLink.targetTo + 1 });
editor.view.focus();
} else if (linkRange) editSource(linkRange);
}
async function clipboard(action: "cut" | "copy" | "paste" | "plain") {
await request(async () => {
try {
@@ -49,7 +68,7 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
if (action === "cut") run(() => { editor.commands.deleteSelection(); });
} else {
let html = "", value = "";
if (action === "paste" && navigator.clipboard.read) {
if (!sourceEditing && action === "paste" && navigator.clipboard.read) {
try {
const data = await navigator.clipboard.read();
const rich = data.find(item => item.types.includes("text/html"));
@@ -72,7 +91,8 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
});
}
return [
const items: ActionMenuItem[] = [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
@@ -95,4 +115,8 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
{ label: "Paste as plain text", icon: "paste-text", run: () => void clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } },
];
return sourceEditing ? [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
...items.slice(items.findIndex(item => "label" in item && item.label === "Cut")),
] : items;
}
+93 -10
View File
@@ -1,4 +1,6 @@
import { Editor, Mark } from "@tiptap/core";
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";
@@ -13,6 +15,10 @@ import { tableDragControls } from "./tableDragControls";
import type { TableContextActions } from "./tableCellActions";
import { actionIcon } from "../ui/actionIcons";
import { pluginHost } from "../plugins/registry.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,
@@ -46,10 +52,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
wrapper.append(scroll);
let editor: Editor | undefined;
let active: HTMLTableCellElement | undefined;
let sourceEditing = false;
let sourceImages = new Map<string, string>();
let firstEdit = true;
let selectionControls: ReturnType<typeof tableSelectionControls> | undefined;
let dragControls: ReturnType<typeof tableDragControls> | undefined;
const controller = { source: initialSource, enter, destroy: () => { dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = 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) {
@@ -83,7 +92,8 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
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);
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
cell.dataset.cellHint = `${address}${result?.formula ? ` · ${result.formula}` : ""}`;
cell.removeAttribute("title");
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
if (cell === active) {
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
@@ -115,10 +125,16 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
function finish() {
if (!editor || !active) return;
const cell = active;
const html = editor.getHTML();
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");
cell.classList.remove("is-editing", "is-source-editing");
refreshFormulas();
formulaStatus.textContent = "Type = in a cell to calculate";
formulaHint.hidden = true;
@@ -165,6 +181,22 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
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 }),
@@ -177,6 +209,9 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
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.
@@ -237,10 +272,11 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
});
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 (/^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
if (sourceEditing || /^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
else if (event.ctrlKey || event.metaKey) leave(true);
else editor?.commands.setHardBreak();
return true;
@@ -258,7 +294,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
},
},
onUpdate({ editor: current }) {
const text = tableCellMarkdown(current.getJSON());
const text = sourceEditing
? current.getText({ blockSeparator: "<br>" }).replace(/\r?\n/g, "<br>").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.
@@ -269,6 +311,18 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
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(); });
@@ -279,6 +333,32 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
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<number>();
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<HTMLImageElement>("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) {
const from = view.posAtDOM(root);
finish();
@@ -299,7 +379,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
const help = document.createElement("div");
help.className = "table-edit-help";
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
help.hidden = true;
const footer = document.createElement("div");
footer.className = "table-footer";
const tools = formulas?.createFormulaTools(finish, () => view.requestMeasure());
@@ -313,7 +393,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
const label = kind === "column" ? "Add column to the right" : "Add row below";
button.type = "button";
button.className = `table-add table-add-${kind}`;
button.title = label;
tooltipCleanup.push(attachTooltip(button, () => label));
button.setAttribute("aria-label", label);
const plus = document.createElement("span");
plus.append(actionIcon("plus"));
@@ -332,7 +412,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
cell.setAttribute("aria-label", `${formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : ""}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 }, actions);
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;
@@ -347,4 +427,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
}
});
refreshFormulas();
for (const row of table.rows) for (const cell of row.cells) {
tooltipCleanup.push(attachTooltip(cell, () => cell.dataset.cellHint || cell.getAttribute("aria-label") || ""));
}
}
+4 -3
View File
@@ -2,12 +2,14 @@ import type { EditorView } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
import { moveTableAxis, type TableAxis } from "./tableStructure";
import type { CellRange } from "./tableSelection";
import { attachTooltip } from "../ui/tooltip";
const controls = new WeakMap<HTMLTableElement, (axis: TableAxis, index: number, keyboard: boolean) => void>();
export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, scroll: HTMLElement, view: EditorView, source: () => string, select: (range: CellRange) => void, change: (text: string, structural: boolean) => void) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
const handles: { axis: TableAxis; index: number; button: HTMLButtonElement }[] = [];
const tooltipCleanup: (() => void)[] = [];
const layer = document.createElement("div");
layer.className = "table-drag-layer";
wrapper.append(layer);
@@ -172,8 +174,7 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
const label = `Move ${axis} ${index + 1}`;
const tooltip = `${label} · Drag to reorder · ${axis === "row" ? "↑/↓" : "←/→"} to move`;
button.setAttribute("aria-label", label);
button.title = tooltip;
button.dataset.tooltip = tooltip;
tooltipCleanup.push(attachTooltip(button, () => drag ? "" : tooltip));
button.append(actionIcon("grip"));
layer.append(button);
handles.push({ axis, index, button });
@@ -222,5 +223,5 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
const observer = new ResizeObserver(scheduleLayout);
observer.observe(table); observer.observe(scroll);
scheduleLayout();
return { destroy() { cancel(); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
return { destroy() { cancel(); tooltipCleanup.forEach(dispose => dispose()); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
}
+45
View File
@@ -0,0 +1,45 @@
import { markdownLanguage } from "@codemirror/lang-markdown";
import type { DocumentLink } from "./documentLinks";
/** Keep the caret on the clicked label character when Markdown becomes visible. */
export function tableLinkLabelPosition(source: string, link: DocumentLink, offset: number): number {
let from = link.targetFrom, to = link.targetTo;
if (link.kind === "wiki") {
const separator = source.indexOf("|", link.from + 2);
from = link.from + 2; to = link.to - 2;
if (separator >= 0 && separator < to) {
if (separator + 1 < to) from = separator + 1;
else to = separator - Number(source[separator - 1] === "\\");
}
} else if (source[link.from] === "[") {
from = link.from + 1;
markdownLanguage.parser.parse(source).iterate({ enter(node) {
if (node.name === "LinkMark" && node.from > from && node.from < link.targetFrom && source[node.from] === "]") to = node.from;
} });
}
const label = source.slice(from, to);
const hidden = new Set<number>();
const entities = new Map<number, { to: number; length: number }>();
if (link.kind === "wiki") {
// Wiki labels are literal text. Table parsing removes escaped pipe marks.
for (let i = 0; i < label.length - 1; i++) if (label[i] === "\\" && label[i + 1] === "|") hidden.add(i);
} else markdownLanguage.parser.parse(label).iterate({ enter(node) {
if (["EmphasisMark", "StrikethroughMark", "CodeMark"].includes(node.name)) {
for (let i = node.from; i < node.to; i++) hidden.add(i);
} else if (node.name === "Escape") hidden.add(node.from);
else if (node.name === "Entity") {
const text = document.createElement("textarea");
text.innerHTML = label.slice(node.from, node.to);
entities.set(node.from, { to: node.to, length: text.value.length });
}
} });
let visible = 0;
for (let i = 0; i < label.length; i++) {
if (hidden.has(i)) continue;
if (visible >= offset) return from + i;
const entity = entities.get(i);
if (entity) { visible += entity.length; i = entity.to - 1; }
else visible++;
}
return to;
}
+4 -4
View File
@@ -10,7 +10,7 @@ import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableC
const selections = new WeakMap<Element, (range: CellRange) => void>();
export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void }, actions: TableContextActions) {
export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void; editSource: (range: { from: number; to: number }) => void }, actions: TableContextActions) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
let range: CellRange | undefined, down: CellPoint | undefined, dragging = false;
let menu: HTMLElement | undefined;
@@ -80,7 +80,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
}
} catch {
const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; }
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; }
}
}
function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) {
@@ -109,11 +109,11 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem));
const report = (message: string) => {
const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; }
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; }
};
const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => {
view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") });
}, value => { pending = value; }, report) : [
}, value => { pending = value; }, report, rich.editSource) : [
...(["cut", "copy", "paste"] as const).map(action => ({ label: action[0].toUpperCase() + action.slice(1), icon: action, run: () => void clipboard(action) })),
sep,
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) },