Update editor, workspace, Git services, appearance, and project guides
This commit is contained in:
@@ -6,27 +6,32 @@
|
||||
import { editorSession } 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 { TableContextActions } from "./tableCellActions";
|
||||
import { documentLinks, documentLinkAt } from "./documentLinks";
|
||||
|
||||
type Props = {
|
||||
buffer: OpenBuffer;
|
||||
chrome: Chrome;
|
||||
onChange: (value: string, id: string) => void;
|
||||
onInsertImage?: (file: File) => Promise<string | null>;
|
||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||
focusLine?: number | null;
|
||||
onSelectionLine?: (line: number) => void;
|
||||
tableActions?: TableContextActions;
|
||||
shouldFocusOnMount?: () => boolean;
|
||||
};
|
||||
|
||||
let { buffer, chrome, onChange, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
|
||||
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
|
||||
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
|
||||
let ready = $state(0);
|
||||
let applying = false;
|
||||
let loadError = $state<string | null>(null);
|
||||
const documentPath = $derived(buffer.relPath);
|
||||
|
||||
async function takeImages(event: DragEvent | ClipboardEvent, data: DataTransfer | null) {
|
||||
if (!isMarkdownPath(buffer.relPath) || !onInsertImage) {
|
||||
@@ -77,6 +82,8 @@
|
||||
|
||||
$effect(() => {
|
||||
const el = host;
|
||||
// Buffer snapshots change on each edit. Only a path change remounts Monaco.
|
||||
const path = documentPath;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
@@ -88,19 +95,19 @@
|
||||
let releaseDrop: (() => void) | undefined;
|
||||
let releaseCompletion: (() => void) | undefined;
|
||||
const listeners: { dispose(): void }[] = [];
|
||||
void import("./monacoEnv").then(({ monaco }) => {
|
||||
void import("./monacoEnv").then(({ monaco, currentTheme }) => {
|
||||
if (cancelled || !el.isConnected) {
|
||||
return;
|
||||
}
|
||||
session = editorSession(monaco, untrack(() => buffer));
|
||||
const mode = untrack(() => chrome);
|
||||
const model = session.model;
|
||||
const markdown = isMarkdownPath(untrack(() => buffer.relPath));
|
||||
const markdown = isMarkdownPath(path);
|
||||
const view = monaco.editor.create(el, {
|
||||
model,
|
||||
theme: "runestone-dark",
|
||||
theme: currentTheme,
|
||||
automaticLayout: true,
|
||||
fontFamily: "Cascadia Code, JetBrains Mono, Consolas, ui-monospace, monospace",
|
||||
...codeFont(el),
|
||||
scrollBeyondLastLine: false,
|
||||
smoothScrolling: true,
|
||||
cursorBlinking: "smooth",
|
||||
@@ -112,6 +119,37 @@
|
||||
...monacoChrome(mode),
|
||||
});
|
||||
editor = view;
|
||||
const linkPath = `/${encodeURIComponent(untrack(() => buffer.id))}/`;
|
||||
if (markdown) listeners.push(monaco.languages.registerLinkProvider("markdown", {
|
||||
provideLinks(candidate) {
|
||||
if (candidate !== model) return { links: [] };
|
||||
return { links: documentLinks(model.getValue()).map(link => {
|
||||
const from = model.getPositionAt(link.from), to = model.getPositionAt(link.to);
|
||||
return { range: new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column),
|
||||
url: `runestone-link://document${linkPath}${link.kind}?${encodeURIComponent(link.target)}`, tooltip: "Open link" };
|
||||
}) };
|
||||
},
|
||||
}));
|
||||
listeners.push(monaco.editor.registerLinkOpener({ open(resource) {
|
||||
const url = resource.toString(true);
|
||||
if (resource.scheme === "runestone-link" && resource.path.startsWith(linkPath)) {
|
||||
onOpenLink?.(resource.path.slice(linkPath.length) === "wiki" ? "wiki" : "md", decodeURIComponent(resource.query));
|
||||
return true;
|
||||
}
|
||||
if (view.hasTextFocus() && /^(https?:|mailto:)/i.test(url) && onOpenLink) { onOpenLink("md", url); return true; }
|
||||
return false;
|
||||
} }));
|
||||
const openSourceLink = (event: MouseEvent) => {
|
||||
if (!markdown || event.button !== 0 || (!event.ctrlKey && !event.metaKey) || !onOpenLink) return;
|
||||
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
|
||||
const link = position && documentLinkAt(model.getValue(), model.getOffsetAt(position));
|
||||
if (!link) return;
|
||||
event.preventDefault(); event.stopImmediatePropagation();
|
||||
onOpenLink(link.kind, link.target);
|
||||
};
|
||||
el.addEventListener("mousedown", openSourceLink, true);
|
||||
listeners.push({ dispose: () => el.removeEventListener("mousedown", openSourceLink, true) });
|
||||
listeners.push(view.onDidChangeCursorPosition(event => onSelectionLine?.(event.position.lineNumber)));
|
||||
if (markdown) {
|
||||
releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.getTargetAtClientPoint(point.x, point.y)?.position, path); });
|
||||
menu = markdownMenu({
|
||||
@@ -149,6 +187,7 @@
|
||||
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
|
||||
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
|
||||
if (session.view) view.restoreViewState(session.view);
|
||||
onSelectionLine?.(view.getPosition()?.lineNumber ?? 1);
|
||||
ready += 1;
|
||||
contentListener = model.onDidChangeContent(() => {
|
||||
if (applying) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
import { untrack } from "svelte";
|
||||
import { Compartment, EditorState } from "@codemirror/state";
|
||||
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
|
||||
import { EditorView, drawSelection, keymap } from "@codemirror/view";
|
||||
import { defaultKeymap, history, historyField, historyKeymap, indentWithTab, isolateHistory } from "@codemirror/commands";
|
||||
import { defaultKeymap, indentWithTab, isolateHistory } from "@codemirror/commands";
|
||||
import { writerHistory, historyKeymap } from "./writerHistory";
|
||||
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { noteFormats } from "./noteFormats";
|
||||
import { searchKeymap } from "@codemirror/search";
|
||||
@@ -25,6 +27,7 @@
|
||||
import { markdownMenu } from "./markdownMenu";
|
||||
import { tableNavigation } from "./tableNavigation";
|
||||
import { completionExtension } from "$lib/completion/codemirror";
|
||||
import { documentLinkAt } from "./documentLinks";
|
||||
|
||||
type Props = {
|
||||
buffer: OpenBuffer;
|
||||
@@ -33,17 +36,21 @@
|
||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||
onInsertImage?: (file: File) => Promise<string | null>;
|
||||
focusLine?: number | null;
|
||||
onSelectionLine?: (line: number) => void;
|
||||
tableActions?: TableContextActions;
|
||||
shouldFocusOnMount?: () => boolean;
|
||||
focusTitle?: boolean;
|
||||
onTitleFocused?: () => void;
|
||||
};
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor = $state.raw<EditorView>();
|
||||
let error = $state("");
|
||||
let model: import("monaco-editor").editor.ITextModel | undefined;
|
||||
let ModelSelection: typeof import("monaco-editor").Selection;
|
||||
let lastValue = "";
|
||||
let publishing = false;
|
||||
let historySelections: Map<number, EditorSelection> | undefined;
|
||||
let freshState: ((source: string) => EditorState) | undefined;
|
||||
let refreshVersion = 0;
|
||||
let historyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -71,15 +78,32 @@
|
||||
return urls.size !== previousSize;
|
||||
}
|
||||
|
||||
function publish(value: string, id: string) {
|
||||
// CodeMirror stores one character per line break. Serialize only at the model
|
||||
// boundary, so pasted LF and CRLF text both create real editor lines.
|
||||
function modelSource(state: EditorState) {
|
||||
return state.doc.sliceString(0, undefined, model?.getEOL() ?? "\n");
|
||||
}
|
||||
|
||||
function publish(value: string, id: string, startState: EditorState, state: EditorState) {
|
||||
if (!model || value === model.getValue()) return;
|
||||
const before = model.getValue();
|
||||
historySelections?.set(model.getAlternativeVersionId(), startState.selection);
|
||||
const previous = model.getValue();
|
||||
let start = 0;
|
||||
while (start < before.length && start < value.length && before[start] === value[start]) start++;
|
||||
let oldEnd = before.length, newEnd = value.length;
|
||||
while (oldEnd > start && newEnd > start && before[oldEnd - 1] === value[newEnd - 1]) { oldEnd--; newEnd--; }
|
||||
while (start < previous.length && start < value.length && previous[start] === value[start]) start++;
|
||||
let oldEnd = previous.length, newEnd = value.length;
|
||||
while (oldEnd > start && newEnd > start && previous[oldEnd - 1] === value[newEnd - 1]) { oldEnd--; newEnd--; }
|
||||
const from = model.getPositionAt(start), to = model.getPositionAt(oldEnd);
|
||||
model.pushEditOperations(null, [{ range: { startLineNumber: from.lineNumber, startColumn: from.column, endLineNumber: to.lineNumber, endColumn: to.column }, text: value.slice(start, newEnd) }], () => null);
|
||||
const cursorState = (state: EditorState) => state.selection.ranges.map(range => {
|
||||
const anchor = state.doc.lineAt(range.anchor), head = state.doc.lineAt(range.head);
|
||||
return new ModelSelection(anchor.number, range.anchor - anchor.from + 1, head.number, range.head - head.from + 1);
|
||||
});
|
||||
// The model emits changes synchronously. Do not echo this Writer edit back
|
||||
// into CodeMirror while its update listener still runs.
|
||||
publishing = true;
|
||||
try {
|
||||
model.pushEditOperations(cursorState(startState), [{ range: { startLineNumber: from.lineNumber, startColumn: from.column, endLineNumber: to.lineNumber, endColumn: to.column }, text: value.slice(start, newEnd) }], () => cursorState(state));
|
||||
} finally { publishing = false; }
|
||||
historySelections?.set(model.getAlternativeVersionId(), state.selection);
|
||||
clearTimeout(historyTimer);
|
||||
historyTimer = setTimeout(() => model?.pushStackElement(), 500);
|
||||
lastValue = model.getValue();
|
||||
@@ -124,6 +148,7 @@
|
||||
if (!el) return;
|
||||
let cancelled = false;
|
||||
let session: ReturnType<typeof editorSession> | undefined;
|
||||
let contentListener: { dispose(): void } | undefined;
|
||||
let releaseSelection: (() => void) | undefined;
|
||||
let menu: ReturnType<typeof markdownMenu> | undefined;
|
||||
let releaseDrop: (() => void) | undefined;
|
||||
@@ -135,16 +160,29 @@
|
||||
if (cancelled) return;
|
||||
session = editorSession(monaco, untrack(() => buffer));
|
||||
model = session.model;
|
||||
ModelSelection = monaco.Selection;
|
||||
historySelections = session.writerSelections;
|
||||
lastValue = untrack(() => buffer.contents);
|
||||
if (model.getValue() !== lastValue) model.setValue(lastValue);
|
||||
model.pushStackElement();
|
||||
const extensions = [
|
||||
completionExtension(current.id),
|
||||
EditorState.lineSeparator.of(model.getEOL()),
|
||||
markdown({ base: markdownLanguage, extensions: [noteFormats] }),
|
||||
// Rich cell serialization can change delimiters away from the caret.
|
||||
// Keep a burst of typing together even when those source edits aren't adjacent.
|
||||
history({ joinToEvent: (transaction, adjacent) => adjacent || transaction.isUserEvent("input.type.table") }), drawSelection(),
|
||||
writerHistory.of({
|
||||
undo: () => {
|
||||
clearTimeout(historyTimer);
|
||||
model!.pushStackElement();
|
||||
if (!model!.canUndo()) return false;
|
||||
void model!.undo();
|
||||
return true;
|
||||
},
|
||||
redo: () => {
|
||||
clearTimeout(historyTimer);
|
||||
if (!model!.canRedo()) return false;
|
||||
void model!.redo();
|
||||
return true;
|
||||
},
|
||||
}), drawSelection(),
|
||||
EditorView.theme({}, { dark: true }),
|
||||
tableNavigation,
|
||||
writerSearch,
|
||||
@@ -173,18 +211,33 @@
|
||||
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
|
||||
EditorView.contentAttributes.of({ role: "textbox", "aria-label": "Writing editor", "aria-multiline": "true", spellcheck: "true" }),
|
||||
EditorView.updateListener.of(update => {
|
||||
if (update.docChanged || update.selectionSet) menu?.close(false);
|
||||
if (update.docChanged || update.selectionSet) {
|
||||
menu?.close(false);
|
||||
onSelectionLine?.(update.state.doc.lineAt(update.state.selection.main.head).number);
|
||||
}
|
||||
const isolation = update.transactions.map(transaction => transaction.annotation(isolateHistory));
|
||||
const separate = update.transactions.some(transaction => {
|
||||
const event = transaction.annotation(Transaction.userEvent);
|
||||
return transaction.docChanged && event && !/^(input\.type|delete)($|\.)/.test(event);
|
||||
});
|
||||
if (separate || (update.selectionSet && !update.docChanged)) model?.pushStackElement();
|
||||
if (isolation.some(value => value === "before" || value === "full")) model?.pushStackElement();
|
||||
if (update.docChanged) {
|
||||
scroll = scroll?.map(update.changes);
|
||||
publish(update.state.sliceDoc(), current.id);
|
||||
publish(modelSource(update.state), current.id, update.startState, update.state);
|
||||
void loadImages(current.relPath, update.state.sliceDoc()).then(changed => {
|
||||
if (changed && editor === update.view) update.view.dispatch({ effects: refreshImages.of() });
|
||||
});
|
||||
}
|
||||
if (isolation.some(value => value === "after" || value === "full")) {
|
||||
clearTimeout(historyTimer);
|
||||
model?.pushStackElement();
|
||||
}
|
||||
}),
|
||||
EditorView.domEventHandlers({
|
||||
contextmenu(event, view) {
|
||||
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
|
||||
if (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 selection = view.state.selection.main;
|
||||
@@ -200,12 +253,15 @@
|
||||
if (coords) menu?.open(coords.left, coords.bottom);
|
||||
return true;
|
||||
},
|
||||
click(event) {
|
||||
mousedown(event, view) {
|
||||
if (!event.ctrlKey && !event.metaKey) return false;
|
||||
if (event.button !== 0) return false;
|
||||
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
|
||||
if (!link) return false;
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
const sourceLink = position === null ? undefined : documentLinkAt(view.state.doc.toString(), position);
|
||||
if (!link && !sourceLink) return false;
|
||||
event.preventDefault();
|
||||
onOpenLink?.(link.getAttribute("data-kind") === "wiki" ? "wiki" : "md", link.getAttribute("data-href") || link.getAttribute("href") || "");
|
||||
onOpenLink?.(sourceLink?.kind ?? (link?.getAttribute("data-kind") === "wiki" ? "wiki" : "md"), sourceLink?.target ?? link?.getAttribute("data-href") ?? link?.getAttribute("href") ?? "");
|
||||
return true;
|
||||
},
|
||||
paste(event, view) {
|
||||
@@ -217,11 +273,28 @@
|
||||
freshState = source => EditorState.create({ doc: source, extensions });
|
||||
const saved = session.writer;
|
||||
const state = saved?.source === lastValue
|
||||
? EditorState.fromJSON(saved.state, { extensions }, { history: historyField })
|
||||
? EditorState.fromJSON(saved.state, { extensions })
|
||||
: freshState(lastValue);
|
||||
// Restore through CodeMirror's layout pass, once its viewport is measured.
|
||||
const view = new EditorView({ state, parent: el, scrollTo: saved?.source === lastValue ? saved.scroll : undefined });
|
||||
editor = view;
|
||||
onSelectionLine?.(view.state.doc.lineAt(view.state.selection.main.head).number);
|
||||
// Writer and IDE use the same model and undo stack for this document.
|
||||
contentListener = model.onDidChangeContent(event => {
|
||||
if (publishing) return;
|
||||
const value = model!.getValue();
|
||||
if (value === modelSource(view.state)) return;
|
||||
lastValue = value;
|
||||
const changes = event.changes.map(change => ({
|
||||
from: view.state.doc.line(change.range.startLineNumber).from + change.range.startColumn - 1,
|
||||
to: view.state.doc.line(change.range.endLineNumber).from + change.range.endColumn - 1,
|
||||
insert: change.text,
|
||||
}));
|
||||
if (event.isFlush) historySelections?.clear();
|
||||
const selection = event.isUndoing || event.isRedoing ? historySelections?.get(model!.getAlternativeVersionId()) : undefined;
|
||||
view.dispatch({ changes, selection, scrollIntoView: !!selection, annotations: Transaction.addToHistory.of(false) });
|
||||
onChange(value, current.id);
|
||||
});
|
||||
scroll = saved?.source === lastValue ? saved.scroll : view.scrollSnapshot();
|
||||
// Svelte may detach the old tab before effect cleanup runs, at which point
|
||||
// DOM scroll offsets read as zero. Capture while the view is still mounted.
|
||||
@@ -246,10 +319,11 @@
|
||||
refreshVersion++;
|
||||
clearTimeout(historyTimer);
|
||||
model?.pushStackElement();
|
||||
contentListener?.dispose();
|
||||
menu?.destroy();
|
||||
releaseDrop?.();
|
||||
releaseScroll?.();
|
||||
if (session && editor && scroll) session.writer = { source: editor.state.sliceDoc(), state: editor.state.toJSON({ history: historyField }), scroll };
|
||||
if (session && editor && scroll) session.writer = { source: modelSource(editor.state), state: editor.state.toJSON(), scroll };
|
||||
editor?.destroy();
|
||||
releaseSelection?.();
|
||||
editor = undefined;
|
||||
@@ -318,22 +392,28 @@
|
||||
.live-writer { position: absolute; inset: 0; }
|
||||
.live-writer :global(.cm-editor) { height: 100%; color: var(--rs-text); background: transparent; }
|
||||
.live-writer :global(.cm-editor.cm-focused) { outline: none; }
|
||||
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-prose-size)/1.75 var(--rs-font-prose); scrollbar-gutter: stable; }
|
||||
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose); scrollbar-gutter: stable; }
|
||||
.live-writer :global(.cm-content) { max-width: 868px; width: 100%; margin: 0 auto; padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 35vh; caret-color: var(--rs-text-strong); }
|
||||
.live-writer :global(.cm-line) { padding: 0; }
|
||||
.live-writer :global(.cm-line) { padding: 0; position: relative; }
|
||||
.live-writer :global(.cm-line:hover)::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: 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(.writer-heading) { color: var(--rs-text-strong); font-weight: 650; line-height: 1.4; }
|
||||
.live-writer :global(.writer-h1) { font-size: 2.1em; }
|
||||
.live-writer :global(.writer-h2) { font-size: 1.5em; }
|
||||
.live-writer :global(.writer-h3) { font-size: 1.2em; }
|
||||
.live-writer :global(.writer-strong) { font-weight: 650; color: var(--rs-text-strong); }
|
||||
.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-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-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); }
|
||||
@@ -346,10 +426,10 @@
|
||||
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; }
|
||||
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
|
||||
.live-writer :global(.writer-preview img) { max-width: 100%; }
|
||||
.live-writer :global(.writer-table) { position: relative; margin: 1.4em 0 0; padding: 26px; }
|
||||
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 4px; }
|
||||
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
|
||||
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 0; }
|
||||
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
|
||||
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1.75em; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1lh; white-space: pre-wrap; overflow-wrap: break-word; }
|
||||
.live-writer :global(.writer-table p) { margin: 0; }
|
||||
.live-writer :global(.table-add) { position: absolute; display: block; padding: 0; opacity: 0; border: 1px solid var(--rs-border); background: var(--rs-bg-elevated); color: var(--rs-text-dim); cursor: pointer; transition: opacity 100ms; }
|
||||
.live-writer :global(.table-add:hover), .live-writer :global(.table-add:focus-visible) { opacity: 1; color: var(--rs-accent); border-color: var(--rs-accent-deep); outline: none; }
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import ContextMenu from "$lib/layout/ContextMenu.svelte";
|
||||
import type { MenuItem } from "$lib/layout/menuTypes";
|
||||
import { writerContextItems } from "./writerMenu";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
|
||||
type Props = {
|
||||
buffer: OpenBuffer;
|
||||
@@ -132,9 +133,10 @@
|
||||
],
|
||||
content: html,
|
||||
editorProps: {
|
||||
attributes: { class: "reading writer-doc" },
|
||||
attributes: { class: "reading writer-doc", spellcheck: "true" },
|
||||
handleDOMEvents: {
|
||||
contextmenu: (pmView, event) => {
|
||||
if (useSpellingMenu(event, pmView.state.selection.empty)) { menu = null; return false; }
|
||||
event.preventDefault();
|
||||
if (!editor) {
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
export function codeFont(element: HTMLElement) {
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
fontFamily: style.getPropertyValue("--rs-font-mono").trim() || '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace',
|
||||
fontWeight: style.getPropertyValue("--rs-code-font-weight").trim() || "300",
|
||||
fontSize: Number.parseFloat(style.getPropertyValue("--rs-code-font-size")) || 13,
|
||||
lineHeight: Number.parseFloat(style.getPropertyValue("--rs-code-line-height")) || 21,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { markdownLanguage } from "@codemirror/lang-markdown";
|
||||
|
||||
export type DocumentLink = { from: number; to: number; kind: "md" | "wiki"; target: string };
|
||||
|
||||
/** Source ranges survive the change from formatted text to editable Markdown. */
|
||||
export function documentLinks(source: string): DocumentLink[] {
|
||||
const links: DocumentLink[] = [];
|
||||
const literal: { from: number; to: number }[] = [];
|
||||
markdownLanguage.parser.parse(source).iterate({ enter(node) {
|
||||
if (["FencedCode", "CodeBlock", "InlineCode", "Image"].includes(node.name)) {
|
||||
literal.push({ from: node.from, to: node.to });
|
||||
return false;
|
||||
}
|
||||
if (node.name !== "Link" && node.name !== "Autolink") return;
|
||||
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 });
|
||||
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() });
|
||||
}
|
||||
for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) {
|
||||
if (occupied(match.index, match.index + match[0].length)) continue;
|
||||
const target = match[0].replace(/[.,;:!?]+$/, "").replace(/\)+$/, suffix => {
|
||||
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 });
|
||||
}
|
||||
return links.sort((a, b) => a.from - b.from);
|
||||
}
|
||||
|
||||
export function documentLinkAt(source: string, position: number) {
|
||||
return documentLinks(source).find(link => position >= link.from && position < link.to);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type { TableContextActions } from "./tableCellActions";
|
||||
import { imageControls } from "./imageControls";
|
||||
import { ImagePreview, type ImageContext } from "./imagePreview";
|
||||
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
|
||||
@@ -16,6 +17,40 @@ const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||
export const refreshImages = StateEffect.define<void>();
|
||||
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
class CodeCopy extends WidgetType {
|
||||
constructor(readonly code: string) { super(); }
|
||||
eq(other: CodeCopy) { return this.code === other.code; }
|
||||
toDOM() {
|
||||
const button = document.createElement("button");
|
||||
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.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.setAttribute("aria-label", "Code copied");
|
||||
} catch {
|
||||
button.title = "Could not copy code";
|
||||
help.textContent = "Could not copy code";
|
||||
button.setAttribute("aria-label", "Could not copy code");
|
||||
}
|
||||
};
|
||||
return button;
|
||||
}
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
|
||||
class Divider extends WidgetType {
|
||||
eq(other: Divider) { return other instanceof Divider; }
|
||||
toDOM(view: EditorView) {
|
||||
@@ -109,6 +144,9 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
const imageNodes = imageSourceRanges(source);
|
||||
for (const section of renderMarkdownSections(source, urls)) {
|
||||
if (!/(?:<pre|<table|<img|md-properties|md-callout|missing-image)/.test(section.html)) continue;
|
||||
// Code remains a real editor surface. A preview swap loses the first drag
|
||||
// and changes block height when focus or the selection moves elsewhere.
|
||||
if (/^<pre\b/.test(section.html)) continue;
|
||||
// The first rendered section includes leading blank lines. Keep those
|
||||
// editable when the user exits above a table at the start of a note.
|
||||
if (/<table>/.test(section.html)) section.start += /^(?:[ \t]*\r?\n)+/.exec(source.slice(section.start, section.end))?.[0].length ?? 0;
|
||||
@@ -146,6 +184,10 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions, false, height), block: true, atomic: true }).range(section.start, end));
|
||||
}
|
||||
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
|
||||
for (let number = 1; number <= state.doc.lines; number++) {
|
||||
const line = state.doc.line(number);
|
||||
if (!line.text.trim() && !hidden(line.from, line.to)) ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
|
||||
}
|
||||
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
|
||||
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
|
||||
const codeRanges: { from: number; to: number }[] = [];
|
||||
@@ -153,7 +195,15 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
if (hidden(node.from, node.to)) return false;
|
||||
if (node.name === "FencedCode" || node.name === "CodeBlock") {
|
||||
codeRanges.push({ from: node.from, to: node.to });
|
||||
mark(node.from, node.to, "writer-code-source");
|
||||
const first = state.doc.lineAt(node.from), last = state.doc.lineAt(node.to);
|
||||
const fenced = node.name === "FencedCode";
|
||||
const closed = fenced && /^\s*(`{3,}|~{3,})\s*$/.test(last.text) && last.number > first.number;
|
||||
const code = fenced ? source.slice(Math.min(first.to + 1, node.to), closed ? last.from : node.to) : source.slice(node.from, node.to);
|
||||
ranges.push(Decoration.widget({ widget: new CodeCopy(code), side: 1 }).range(first.to));
|
||||
for (let number = first.number; number <= last.number; number++) {
|
||||
const line = state.doc.line(number);
|
||||
ranges.push(Decoration.line({ class: `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const line = state.doc.lineAt(node.from);
|
||||
|
||||
@@ -2,6 +2,10 @@ export type TableCell = { text: string; from: number; to: number };
|
||||
export type TableRow = { from: number; to: number; indent: string; cells: TableCell[] };
|
||||
export type MarkdownTable = { rows: TableRow[]; columns: number; eol: string; end: number };
|
||||
|
||||
export function hasTableDelimiter(line: string): boolean {
|
||||
return /(^|[^\\])(?:\\\\)*\|/.test(line);
|
||||
}
|
||||
|
||||
function row(text: string, from: number): TableRow {
|
||||
const pipes: number[] = [];
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
@@ -30,7 +34,7 @@ export function parseMarkdownTable(source: string): MarkdownTable | null {
|
||||
let offset = 0;
|
||||
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
||||
for (const line of source.split(eol)) {
|
||||
if (!line.trim()) break;
|
||||
if (!line.trim() || (rows.length >= 2 && !hasTableDelimiter(line))) break;
|
||||
rows.push(row(line, offset));
|
||||
offset += line.length + eol.length;
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ export function monacoChrome(mode: Chrome) {
|
||||
wordWrap: "on" as const,
|
||||
lineNumbers: "off" as const,
|
||||
minimap: { enabled: false },
|
||||
fontSize: 16,
|
||||
lineHeight: 26,
|
||||
folding: false,
|
||||
glyphMargin: false,
|
||||
lineDecorationsWidth: 24,
|
||||
@@ -19,8 +17,6 @@ export function monacoChrome(mode: Chrome) {
|
||||
wordWrap: "off" as const,
|
||||
lineNumbers: "on" as const,
|
||||
minimap: { enabled: true, scale: 1 },
|
||||
fontSize: 14,
|
||||
lineHeight: 22,
|
||||
folding: true,
|
||||
glyphMargin: true,
|
||||
lineDecorationsWidth: 10,
|
||||
|
||||
+34
-21
@@ -8,25 +8,38 @@ self.MonacoEnvironment = {
|
||||
},
|
||||
};
|
||||
|
||||
monaco.editor.defineTheme("runestone-dark", {
|
||||
base: "vs-dark",
|
||||
inherit: true,
|
||||
rules: [],
|
||||
colors: {
|
||||
"editor.background": "#141414",
|
||||
"editor.foreground": "#e6e6e6",
|
||||
"editor.lineHighlightBackground": "#ffffff0d",
|
||||
"editor.selectionBackground": "#264f78",
|
||||
"editorCursor.foreground": "#82aaff",
|
||||
"editorLineNumber.foreground": "#5a5a5a",
|
||||
"editorLineNumber.activeForeground": "#c8c8c8",
|
||||
"editorGutter.background": "#141414",
|
||||
"editorWidget.background": "#1c1c1c",
|
||||
"editorWidget.border": "#2e2e2e",
|
||||
"minimap.background": "#1c1c1c",
|
||||
"editorIndentGuide.background1": "#2e2e2e",
|
||||
"editorIndentGuide.activeBackground1": "#3e3e3e",
|
||||
},
|
||||
});
|
||||
|
||||
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';
|
||||
// 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('#', '') },
|
||||
] : [],
|
||||
colors: {
|
||||
'editor.background': color('bg'), 'editor.foreground': color('text'),
|
||||
'editor.lineHighlightBackground': color('bg-active'), 'editor.selectionBackground': color('selection'),
|
||||
'editorCursor.foreground': color('accent'), 'editorLineNumber.foreground': color('text-dim'),
|
||||
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': color('bg'),
|
||||
'editorWidget.background': color('bg-elevated'), 'editorWidget.border': color('border'),
|
||||
'minimap.background': color('bg-elevated'), 'editorIndentGuide.background1': color('border'),
|
||||
'editorIndentGuide.activeBackground1': color('text-dim'),
|
||||
},
|
||||
});
|
||||
monaco.editor.setTheme(currentTheme);
|
||||
}
|
||||
updateTheme();
|
||||
window.addEventListener('runestone-theme-changed', updateTheme);
|
||||
if (import.meta.hot) import.meta.hot.dispose(() => window.removeEventListener('runestone-theme-changed', updateTheme));
|
||||
export { monaco };
|
||||
|
||||
@@ -5,6 +5,7 @@ import { languageFor } from "./languageFor";
|
||||
type Session = {
|
||||
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>();
|
||||
@@ -15,6 +16,7 @@ export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Sessio
|
||||
session = {
|
||||
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
|
||||
view: null,
|
||||
writerSelections: new Map(),
|
||||
};
|
||||
sessions.set(buffer.id, session);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import type { ActionIcon } from "../ui/actionIcons";
|
||||
|
||||
/** WebView2 owns spelling suggestions and applies corrections to the original word. */
|
||||
export function isSpellingTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
if (target instanceof HTMLTextAreaElement || (target instanceof HTMLInputElement && ["text", "search"].includes(target.type))) {
|
||||
return target.spellcheck && !target.disabled && !target.readOnly;
|
||||
}
|
||||
const editable = target.closest<HTMLElement>('[contenteditable="true"][spellcheck="true"]');
|
||||
return !!editable && target.isContentEditable
|
||||
&& !target.closest('a, code, pre, button, [data-href], [spellcheck="false"], .writer-inline-code, .writer-code-source, .writer-code-line');
|
||||
}
|
||||
|
||||
export function useSpellingMenu(event: MouseEvent, selectionEmpty: boolean): boolean {
|
||||
return selectionEmpty && isSpellingTarget(event.target);
|
||||
}
|
||||
|
||||
export type NativeSpellingItem = {
|
||||
id: number; name: string; label: string; shortcut: string; kind: number;
|
||||
enabled: boolean; checked: boolean; children: NativeSpellingItem[];
|
||||
};
|
||||
type NativeMenu = { request: string; items: NativeSpellingItem[] };
|
||||
const icons: Record<string, ActionIcon> = {
|
||||
undo: "undo", redo: "redo",
|
||||
cut: "cut", copy: "copy", paste: "paste", pasteAndMatchStyle: "paste-text",
|
||||
selectAll: "select", addToDictionary: "book", spellCheck: "book", spellingAndGrammar: "book",
|
||||
};
|
||||
|
||||
function nativeLabel(label: string): string {
|
||||
// Windows uses ampersands for access keys and doubles literal ampersands.
|
||||
return label.replace(/&&|&/g, value => value === "&&" ? "&" : "");
|
||||
}
|
||||
|
||||
export function spellingItems(items: NativeSpellingItem[], select: (id: number) => void): ActionMenuItem[] {
|
||||
return items.map(item => item.kind === 3 ? { separator: true } : {
|
||||
label: nativeLabel(item.label), icon: icons[item.name], shortcut: item.shortcut || undefined,
|
||||
disabled: !item.enabled, checked: item.kind === 1 || item.kind === 2 ? item.checked : undefined,
|
||||
radio: item.kind === 2,
|
||||
children: item.kind === 4 ? spellingItems(item.children, select) : undefined,
|
||||
run: () => select(item.id),
|
||||
});
|
||||
}
|
||||
|
||||
/** Mount once per app window. Other platforms keep their native spelling menu. */
|
||||
export function mountSpellingMenu(): () => void {
|
||||
if (!isTauri()) return () => {};
|
||||
let disposed = false, unlisten: (() => void) | undefined;
|
||||
let context: { target: HTMLElement; x: number; y: number } | undefined;
|
||||
let active: { request: string; root: HTMLElement; target: HTMLElement } | undefined;
|
||||
const finish = (command: number | null = null, restoreFocus = false) => {
|
||||
if (!active) return;
|
||||
const { request, root, target } = active;
|
||||
active = undefined;
|
||||
root.remove();
|
||||
if (restoreFocus && target.isConnected) target.focus({ preventScroll: true });
|
||||
void invoke("spelling_menu_select", { request, command }).catch(error => console.error("Cannot close the spelling menu", error));
|
||||
};
|
||||
const remember = (event: MouseEvent) => {
|
||||
finish();
|
||||
if (event.defaultPrevented || !isSpellingTarget(event.target)) { context = undefined; return; }
|
||||
const target = (event.target as HTMLElement).closest<HTMLElement>('[contenteditable="true"], textarea, input')!;
|
||||
const bounds = document.getSelection()?.rangeCount ? document.getSelection()!.getRangeAt(0).getBoundingClientRect() : target.getBoundingClientRect();
|
||||
context = { target, x: event.clientX || bounds.left, y: event.clientY || bounds.bottom };
|
||||
};
|
||||
const outside = (event: PointerEvent) => { if (active && !active.root.contains(event.target as Node)) finish(); };
|
||||
const scroll = (event: Event) => { if (active && !active.root.contains(event.target as Node)) finish(); };
|
||||
const cancel = () => finish();
|
||||
window.addEventListener("contextmenu", remember);
|
||||
window.addEventListener("pointerdown", outside);
|
||||
window.addEventListener("resize", cancel);
|
||||
window.addEventListener("blur", cancel);
|
||||
window.addEventListener("pagehide", cancel);
|
||||
document.addEventListener("scroll", scroll, true);
|
||||
void listen<NativeMenu>("spelling-menu", ({ payload }) => {
|
||||
finish();
|
||||
if (disposed || !context?.target.isConnected) {
|
||||
void invoke("spelling_menu_select", { request: payload.request, command: null, fallback: true });
|
||||
return;
|
||||
}
|
||||
const { target, x, y } = context;
|
||||
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body;
|
||||
const root = actionMenu(x, y, spellingItems(payload.items, id => finish(id, true)), () => finish(null, true), "Spelling actions", parent);
|
||||
active = { request: payload.request, root, target };
|
||||
}).then(async stop => {
|
||||
if (disposed) { stop(); return; }
|
||||
unlisten = stop;
|
||||
await invoke("spelling_menu_install");
|
||||
if (disposed) await invoke("spelling_menu_uninstall");
|
||||
}).catch(error => console.warn("Native spelling menu remains active", error));
|
||||
return () => {
|
||||
disposed = true;
|
||||
finish(); unlisten?.();
|
||||
void invoke("spelling_menu_uninstall").catch(() => {});
|
||||
window.removeEventListener("contextmenu", remember);
|
||||
window.removeEventListener("pointerdown", outside);
|
||||
window.removeEventListener("resize", cancel);
|
||||
window.removeEventListener("blur", cancel);
|
||||
window.removeEventListener("pagehide", cancel);
|
||||
document.removeEventListener("scroll", scroll, true);
|
||||
};
|
||||
}
|
||||
@@ -4,7 +4,8 @@ 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, undo, redo } from "@codemirror/commands";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { undo, redo } from "./writerHistory";
|
||||
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable";
|
||||
import { tableCellMarkdown } from "./tableCellMarkdown";
|
||||
import { tableSelectionControls } from "./tableSelectionControls";
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { undo, redo, isolateHistory } from "@codemirror/commands";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { undo, redo } from "./writerHistory";
|
||||
import type { Editor } from "@tiptap/core";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
|
||||
@@ -138,7 +140,10 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
}
|
||||
table.addEventListener("mousedown", event => {
|
||||
const cell = cellAt(event.target);
|
||||
if (cell && event.button === 2) { event.preventDefault(); return; }
|
||||
if (cell && event.button === 2) {
|
||||
if (!useSpellingMenu(event, !range && !!rich.get()?.state.selection.empty)) event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (!cell || event.button !== 0 || event.ctrlKey || event.metaKey) return;
|
||||
closeMenu(); down = point(cell); dragging = false;
|
||||
if (event.shiftKey) {
|
||||
@@ -163,6 +168,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
table.addEventListener("click", event => { if (dragging) { event.preventDefault(); event.stopPropagation(); dragging = false; } }, { ...options, capture: true });
|
||||
table.addEventListener("contextmenu", event => {
|
||||
const cell = cellAt(event.target); if (!cell) return;
|
||||
if (useSpellingMenu(event, !range && !!rich.get()?.state.selection.empty)) { closeMenu(); return; }
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (cell.classList.contains("is-cell-selected")) showMenu(event.clientX, event.clientY, point(cell));
|
||||
else {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Facet } from "@codemirror/state";
|
||||
import type { Command, KeyBinding } from "@codemirror/view";
|
||||
import { undo as localUndo, redo as localRedo } from "@codemirror/commands";
|
||||
|
||||
export const writerHistory = Facet.define<{ undo: () => boolean; redo: () => boolean }>();
|
||||
|
||||
export const undo: Command = view => {
|
||||
const shared = view.state.facet(writerHistory)[0];
|
||||
return shared ? shared.undo() : localUndo(view);
|
||||
};
|
||||
export const redo: Command = view => {
|
||||
const shared = view.state.facet(writerHistory)[0];
|
||||
return shared ? shared.redo() : localRedo(view);
|
||||
};
|
||||
|
||||
export const historyKeymap: readonly KeyBinding[] = [
|
||||
{ key: "Mod-z", run: undo, preventDefault: true },
|
||||
{ key: "Mod-y", run: redo, preventDefault: true },
|
||||
{ key: "Mod-Shift-z", run: redo, preventDefault: true },
|
||||
];
|
||||
Reference in New Issue
Block a user