Initial RuneStone project

This commit is contained in:
Knotty Wyvern
2026-09-26 01:25:42 -07:00
commit bdc15e952d
190 changed files with 25986 additions and 0 deletions
+240
View File
@@ -0,0 +1,240 @@
<script lang="ts">
import { untrack } from "svelte";
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { editorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
import { markdownMenu } from "./markdownMenu";
import type { TableContextActions } from "./tableCellActions";
type Props = {
buffer: OpenBuffer;
chrome: Chrome;
onChange: (value: string, id: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
focusLine?: number | null;
tableActions?: TableContextActions;
shouldFocusOnMount?: () => boolean;
};
let { buffer, chrome, onChange, onInsertImage, focusLine = null, 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);
async function takeImages(event: DragEvent | ClipboardEvent, data: DataTransfer | null) {
if (!isMarkdownPath(buffer.relPath) || !onInsertImage) {
return false;
}
const files = imageFiles(data);
if (files.length === 0) {
return false;
}
event.preventDefault();
event.stopPropagation();
const view = editor, model = view?.getModel();
if (!view || !model) return true;
const position = event instanceof DragEvent ? view.getTargetAtClientPoint(event.clientX, event.clientY)?.position : null;
return importImages(view, files, position);
}
async function importImages(view: import("monaco-editor").editor.IStandaloneCodeEditor, files: File[], position?: import("monaco-editor").Position | null, linkedPath?: string) {
const model = view.getModel();
if (!model) return true;
const range = position ? { startLineNumber: position.lineNumber, startColumn: position.column, endLineNumber: position.lineNumber, endColumn: position.column } : view.getSelection();
if (!range) return true;
const [marker] = model.deltaDecorations([], [{ range, options: { stickiness: 1 } }]);
try {
const snippets: string[] = linkedPath ? [workspaceImageLink(buffer.relPath, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return true;
const snippet = await onInsertImage?.(file);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return true;
const target = model.getDecorationRange(marker);
if (!target) return true;
const from = model.getOffsetAt(target.getStartPosition()), to = model.getOffsetAt(target.getEndPosition());
const text = imageInsertion(model.getValue(), from, to, snippets).replace(/\n/g, model.getEOL());
view.pushUndoStop();
view.executeEdits("insert-images", [{ range: target, text, forceMoveMarkers: true }], () => {
const end = model.getPositionAt(from + text.length);
view.setPosition(end);
return [view.getSelection()!];
});
view.pushUndoStop();
view.focus();
} catch (reason) { if (editor === view) loadError = String(reason); }
finally { if (!model.isDisposed()) model.deltaDecorations([marker], []); }
return true;
}
$effect(() => {
const el = host;
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;
const listeners: { dispose(): void }[] = [];
void import("./monacoEnv").then(({ monaco }) => {
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 view = monaco.editor.create(el, {
model,
theme: "runestone-dark",
automaticLayout: true,
fontFamily: "Cascadia Code, JetBrains Mono, Consolas, ui-monospace, monospace",
scrollBeyondLastLine: false,
smoothScrolling: true,
cursorBlinking: "smooth",
tabSize: 2,
renderWhitespace: "selection",
bracketPairColorization: { enabled: true },
overviewRulerLanes: 0,
contextmenu: !markdown,
...monacoChrome(mode),
});
editor = view;
if (markdown) {
releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.getTargetAtClientPoint(point.x, point.y)?.position, path); });
menu = markdownMenu({
snapshot() {
const selection = view.getSelection()!, version = model.getVersionId();
return { source: model.getValue(), selection: { from: model.getOffsetAt(selection.getStartPosition()), to: model.getOffsetAt(selection.getEndPosition()) }, valid: () => editor === view && model.getVersionId() === version && !!view.getSelection()?.equalsRange(selection) };
},
apply(edit) {
const from = model.getPositionAt(edit.from), to = model.getPositionAt(edit.to);
view.pushUndoStop();
view.executeEdits("markdown-menu", [{ range: new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column), text: edit.insert }], () => {
const anchor = model.getPositionAt(edit.anchor), head = model.getPositionAt(edit.head);
return [new monaco.Selection(anchor.lineNumber, anchor.column, head.lineNumber, head.column)];
});
view.pushUndoStop();
},
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);
}));
listeners.push(view.onKeyDown(event => {
if (event.browserEvent.key !== "ContextMenu" && !(event.shiftKey && event.browserEvent.key === "F10")) return;
event.preventDefault(); event.stopPropagation();
const position = view.getPosition(), rect = el.getBoundingClientRect();
const coords = position && view.getScrolledVisiblePosition(position);
if (coords) menu?.open(rect.left + coords.left, rect.top + coords.top + coords.height);
}));
listeners.push(view.onDidChangeCursorSelection(() => menu?.close(false)));
listeners.push(model.onDidChangeContent(() => menu?.close(false)));
}
const documentId = untrack(() => buffer.id);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
if (session.view) view.restoreViewState(session.view);
ready += 1;
contentListener = model.onDidChangeContent(() => {
if (applying) {
return;
}
onChange(view.getValue(), documentId);
});
if (shouldFocusOnMount()) view.focus();
}).catch((error) => { if (!cancelled) loadError = String(error); });
return () => {
cancelled = true;
const view = editor;
if (view && session) session.view = view.saveViewState();
contentListener?.dispose();
releaseSelection?.();
menu?.destroy();
releaseDrop?.();
listeners.forEach(listener => listener.dispose());
view?.dispose();
editor = undefined;
};
});
$effect(() => {
void ready;
const mode = chrome;
const view = editor;
if (!view) {
return;
}
view.updateOptions(monacoChrome(mode));
});
$effect(() => {
void ready;
const contents = buffer.contents;
const view = editor;
if (!view) {
return;
}
if (contents !== view.getValue()) {
applying = true;
view.setValue(contents ?? "");
applying = false;
}
});
$effect(() => {
void ready;
const line = focusLine;
const view = editor;
if (!view || line == null) {
return;
}
view.revealLineInCenter(line);
view.setPosition({ lineNumber: line, column: 1 });
view.focus();
});
</script>
<div
class="monaco-host"
role="application"
aria-label="Editor"
bind:this={host}
ondragover={(event) => {
if (isMarkdownPath(buffer.relPath) && onInsertImage && hasFileDrag(event.dataTransfer)) {
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
}
}}
ondropcapture={(event) => {
void takeImages(event, event.dataTransfer);
}}
onpastecapture={(event) => {
void takeImages(event, event.clipboardData);
}}
></div>
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>Dismiss</button></p>{/if}
<style>
.monaco-host {
position: absolute;
inset: 0;
overflow: hidden;
}
.monaco-host :global(.monaco-editor),
.monaco-host :global(.overflow-guard) {
height: 100%;
}
</style>
+356
View File
@@ -0,0 +1,356 @@
<script lang="ts">
import { untrack } from "svelte";
import { Compartment, EditorState } from "@codemirror/state";
import { EditorView, drawSelection, keymap } from "@codemirror/view";
import { defaultKeymap, history, historyField, historyKeymap, isolateHistory } from "@codemirror/commands";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { searchKeymap } from "@codemirror/search";
import type { OpenBuffer } from "$lib/workspace/types";
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 { isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { editorSession } from "./sessions";
import { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
import { noteTitle } from "./noteTitle";
import { markdownTitle } from "$lib/workspace/media";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import { tableNavigation } from "./tableNavigation";
type Props = {
buffer: OpenBuffer;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
focusLine?: number | null;
tableActions?: TableContextActions;
shouldFocusOnMount?: () => boolean;
};
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
let error = $state("");
let model: import("monaco-editor").editor.ITextModel | undefined;
let lastValue = "";
let freshState: ((source: string) => EditorState) | undefined;
let refreshVersion = 0;
let historyTimer: ReturnType<typeof setTimeout> | undefined;
const urls = new Map<string, string>();
const loading = new Map<string, Promise<void>>();
const title = new Compartment();
const renameTitle = (name: string) => onRenameTitle!(buffer.id, name);
async function loadImages(path: string, value: string) {
const previousSize = urls.size;
await Promise.all(markdownImages(value).map(async source => {
if (urls.has(source)) return;
if (loading.has(source)) return loading.get(source);
const task = (async () => {
if (isRemoteImage(source)) { urls.set(source, source); return; }
let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
}
})();
loading.set(source, task);
try { await task; } finally { loading.delete(source); }
}));
return urls.size !== previousSize;
}
function publish(value: string, id: string) {
if (!model || value === model.getValue()) return;
const before = 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--; }
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);
clearTimeout(historyTimer);
historyTimer = setTimeout(() => model?.pushStackElement(), 500);
lastValue = model.getValue();
onChange(lastValue, id);
}
async function insertImages(event: ClipboardEvent | DragEvent, view: EditorView) {
const data = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
const files = imageFiles(data);
if (!files.length || !onInsertImage) return;
event.preventDefault();
event.stopPropagation();
const position = event instanceof DragEvent ? view.posAtCoords({ x: event.clientX, y: event.clientY }, false) : null;
await importImages(view, files, position);
}
async function importImages(view: EditorView, files: File[], position: number | null, linkedPath?: string) {
const range = position === null ? view.state.selection.main : { from: position, to: position };
const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
try {
const snippets: string[] = linkedPath ? [workspaceImageLink(path, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return;
const snippet = await onInsertImage?.(file);
if (snippet) snippets.push(snippet);
}
if (editor !== view || !snippets.length) return;
await loadImages(path, snippets.join("\n\n"));
if (editor !== view) return;
const target = view.state.field(imageDrops).get(id);
if (!target) return;
const insert = imageInsertion(view.state.doc.toString(), target.from, target.to, snippets);
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, userEvent: "input.image", annotations: isolateHistory.of("full") });
view.focus();
} catch (reason) { if (editor === view) error = String(reason); }
finally { if (editor === view) view.dispatch({ effects: clearImageDrop.of(id) }); }
}
$effect(() => {
const el = host;
if (!el) return;
let cancelled = false;
let session: ReturnType<typeof editorSession> | undefined;
let releaseSelection: (() => void) | undefined;
let menu: ReturnType<typeof markdownMenu> | undefined;
let releaseDrop: (() => void) | undefined;
let releaseScroll: (() => void) | undefined;
let scroll: ReturnType<EditorView["scrollSnapshot"]> | undefined;
const current = untrack(() => buffer);
void import("./monacoEnv").then(async ({ monaco }) => {
await loadImages(current.relPath, current.contents);
if (cancelled) return;
session = editorSession(monaco, untrack(() => buffer));
model = session.model;
lastValue = untrack(() => buffer.contents);
if (model.getValue() !== lastValue) model.setValue(lastValue);
model.pushStackElement();
const extensions = [
EditorState.lineSeparator.of(model.getEOL()),
markdown({ base: markdownLanguage, extensions: [{
defineNodes: ["NoteHighlight", "NoteMath", "NoteComment", "NoteFormatMark"],
parseInline: [{ name: "NoteFormats", before: "Emphasis", parse(context, next, position) {
const marker = next === 61 ? "==" : next === 37 ? "%%" : next === 36 ? "$" : "";
if (!marker || context.slice(position, position + marker.length) !== marker) return -1;
if (marker === "$" && (context.char(position + 1) === 36 || context.char(position - 1) === 36)) return -1;
let end = position + marker.length;
for (; end < context.end; end++) {
if (context.char(end) === 92) { end++; continue; }
if (context.slice(end, end + marker.length) === marker) break;
}
if (end >= context.end || end === position + marker.length) return -1;
const kind = marker === "==" ? "NoteHighlight" : marker === "$" ? "NoteMath" : "NoteComment";
const children = marker === "==" ? context.parser.parseInline(context.slice(position + marker.length, end), position + marker.length) : [];
return context.addElement(context.elt(kind, position, end + marker.length, [
context.elt("NoteFormatMark", position, position + marker.length), ...children,
context.elt("NoteFormatMark", end, end + marker.length),
]));
} }],
}] }),
// 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(),
EditorView.theme({}, { dark: true }),
tableNavigation,
keymap.of([{ key: "Escape", run: view => {
if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, ...searchKeymap, ...historyKeymap, ...defaultKeymap]), EditorView.lineWrapping,
liveMarkdown(urls, untrack(() => tableActions), {
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")) {
try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Could not find this image in the workspace.");
},
validate: async source => {
if (isRemoteImage(source)) return;
for (const path of linkCandidates(current.relPath, source, "md")) {
try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ }
}
throw new Error("Choose an image that exists in the workspace.");
},
report: message => { error = message; },
}),
imageDrops,
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) {
scroll = scroll?.map(update.changes);
publish(update.state.sliceDoc(), current.id);
void loadImages(current.relPath, update.state.sliceDoc()).then(changed => {
if (changed && editor === update.view) update.view.dispatch({ effects: refreshImages.of() });
});
}
}),
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
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);
return true;
},
keydown(event, view) {
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return false;
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);
return true;
},
click(event) {
if (!event.ctrlKey && !event.metaKey) return false;
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
if (!link) return false;
event.preventDefault();
onOpenLink?.(link.getAttribute("data-kind") === "wiki" ? "wiki" : "md", link.getAttribute("data-href") || link.getAttribute("href") || "");
return true;
},
paste(event, view) {
if (!onInsertImage || !imageFiles(event.clipboardData).length) return false;
void insertImages(event, view); return true;
},
}),
];
freshState = source => EditorState.create({ doc: source, extensions });
const saved = session.writer;
const state = saved?.source === lastValue
? EditorState.fromJSON(saved.state, { extensions }, { history: historyField })
: 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;
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.
const saveScroll = () => { if (view.dom.isConnected) scroll = view.scrollSnapshot(); };
view.scrollDOM.addEventListener("scroll", saveScroll);
releaseScroll = () => view.scrollDOM.removeEventListener("scroll", saveScroll);
releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.posAtCoords(point, false), path); });
releaseSelection = registerSelection(current.id, () => view.state.selection.ranges.map(range => view.state.sliceDoc(range.from, range.to)).join("\n"));
menu = markdownMenu({
snapshot() {
const { doc, selection } = view.state;
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") }); },
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
focus() { view.focus(); },
}, untrack(() => tableActions), message => { error = message; });
if (shouldFocusOnMount()) view.focus();
}).catch(reason => { if (!cancelled) error = String(reason); });
return () => {
cancelled = true;
refreshVersion++;
clearTimeout(historyTimer);
model?.pushStackElement();
menu?.destroy();
releaseDrop?.();
releaseScroll?.();
if (session && editor && scroll) session.writer = { source: editor.state.sliceDoc(), state: editor.state.toJSON({ history: historyField }), scroll };
editor?.destroy();
releaseSelection?.();
editor = undefined;
};
});
$effect(() => {
const name = markdownTitle(buffer.relPath);
const view = editor;
if (view) view.dispatch({ effects: title.reconfigure(noteTitle(name, onRenameTitle ? renameTitle : undefined)) });
});
$effect(() => {
const value = buffer.contents;
const path = buffer.relPath;
const view = editor;
if (!view || value === lastValue) return;
const version = ++refreshVersion;
void loadImages(path, value).then(() => {
if (version !== refreshVersion || editor !== view || buffer.contents !== value || !freshState) return;
lastValue = value;
if (model?.getValue() !== value) model?.setValue(value);
// Reloads start fresh history, so undo cannot revive a discarded disk version.
const anchor = Math.min(view.state.selection.main.head, value.replace(/\r\n/g, "\n").length);
view.setState(freshState(value));
view.dispatch({ selection: { anchor }, effects: title.reconfigure(noteTitle(markdownTitle(buffer.relPath), onRenameTitle ? renameTitle : undefined)) });
});
});
$effect(() => {
const line = focusLine;
const view = editor;
if (!view || line == null) return;
untrack(() => {
const anchor = view.state.doc.line(Math.min(view.state.doc.lines, Math.max(1, line))).from;
view.dispatch({ selection: { anchor }, effects: EditorView.scrollIntoView(anchor, { y: "center" }) });
view.focus();
});
});
</script>
<div class="live-writer" bind:this={host} role="application" aria-label="Markdown writing editor"
ondragovercapture={(event) => {
if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return;
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = "copy";
}}
ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
></div>
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>Dismiss</button></p>{/if}
<style>
.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-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-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-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-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); }
.live-writer :global(.writer-checkbox) { display: inline-block; position: static; width: 15px; height: 15px; margin: 0 .55em 0 0; vertical-align: -.1em; accent-color: var(--rs-accent); cursor: pointer; }
/* Keep child margins inside the measured widget; collapsed margins otherwise
shift mouse hit-testing to the next line after a table or other preview. */
.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 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-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; }
.live-writer :global(.table-add-column) { right: 0; top: 26px; bottom: 26px; width: 26px; border-radius: 0 4px 4px 0; }
.live-writer :global(.table-add-row) { left: 26px; right: 26px; bottom: 0; height: 26px; border-radius: 0 0 4px 4px; }
.live-writer :global(.table-add span) { position: absolute; font: 20px/24px var(--rs-font-ui); width: 24px; height: 24px; text-align: center; pointer-events: none; }
.live-writer :global(.table-add-column span) { left: 0; top: var(--table-add-position, 50%); transform: translateY(-50%); }
.live-writer :global(.table-add-row span) { top: 0; left: var(--table-add-position, 50%); transform: translateX(-50%); }
</style>
+283
View File
@@ -0,0 +1,283 @@
<script lang="ts">
import { untrack } from "svelte";
import type { OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownBlocks } from "$lib/workspace/markdownBlocks";
import { findMarkdownImages, isRemoteImage, resolveImageRel } from "$lib/workspace/media";
import { renderMarkdownHtml } from "$lib/workspace/noteHtml";
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
import ContextMenu from "$lib/layout/ContextMenu.svelte";
import type { MenuItem } from "$lib/layout/menuTypes";
import { writerContextItems } from "./writerMenu";
type Props = {
buffer: OpenBuffer;
onChange: (value: string) => void;
onInsertImage?: (file: File) => Promise<string | null>;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
};
type OpenMenu = { x: number; y: number; items: MenuItem[] } | null;
let { buffer, onChange, onInsertImage, onOpenLink }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor: import("@tiptap/core").Editor | undefined;
let ready = $state(0);
let applying = false;
let skipUpdate = true;
let menu = $state<OpenMenu>(null);
function imageFiles(data: DataTransfer | null): File[] {
if (!data) {
return [];
}
return [...data.files].filter((file) => file.type.startsWith("image/"));
}
async function loadUrls(noteRel: string, contents: string): Promise<Map<string, string>> {
const urls = new Map<string, string>();
for (const block of markdownBlocks(contents)) {
if (block.type !== "text") {
continue;
}
for (const image of findMarkdownImages(block.line)) {
if (urls.has(image.src)) {
continue;
}
if (isRemoteImage(image.src)) {
urls.set(image.src, image.src.trim());
continue;
}
const primary = resolveImageRel(noteRel, image.src);
const base = image.src.replaceAll("\\", "/").split("/").pop() ?? image.src;
try {
urls.set(image.src, await workspaceReadDataUrl(primary));
} catch {
try {
urls.set(image.src, await workspaceReadDataUrl(base));
} catch {
urls.set(image.src, "");
}
}
}
}
return urls;
}
$effect(() => {
const el = host;
if (!el) {
return;
}
let cancelled = false;
void Promise.all([
import("@tiptap/core"),
import("@tiptap/starter-kit"),
import("@tiptap/extension-image"),
import("@tiptap/extension-link"),
import("@tiptap/extension-table"),
import("@tiptap/extension-superscript"),
import("@tiptap/extension-subscript"),
import("@tiptap/extension-task-list"),
import("@tiptap/extension-task-item"),
import("@tiptap/extension-highlight"),
import("./headingMarks"),
import("./writerMarks"),
]).then(async ([core, starter, imageMod, linkMod, tableMod, supMod, subMod, taskListMod, taskItemMod, highlightMod, marks, extra]) => {
if (cancelled || !el.isConnected) {
return;
}
const path = untrack(() => buffer.relPath);
const value = untrack(() => buffer.contents ?? "");
const urls = await loadUrls(path, value);
if (cancelled) {
return;
}
applying = true;
const html = renderMarkdownHtml(value, urls) || "<p></p>";
const Image = imageMod.default.extend({
addAttributes() {
return {
...this.parent?.(),
"data-md-src": { default: null },
"data-md-kind": { default: "md" },
};
},
});
const Link = linkMod.default.extend({
addAttributes() {
return {
...this.parent?.(),
"data-kind": { default: "md" },
class: { default: null },
};
},
});
const view = new core.Editor({
element: el,
extensions: [
starter.default.configure({ heading: { levels: [1, 2, 3, 4, 5, 6] } }),
Image.configure({ inline: false, allowBase64: true }),
Link.configure({ openOnClick: false, autolink: false }),
tableMod.TableKit.configure({ table: { resizable: false } }),
supMod.default,
subMod.default,
taskListMod.default,
taskItemMod.default.configure({ nested: false }),
highlightMod.default.configure({ multicolor: false }),
extra.MathMark,
extra.CommentMark,
marks.HeadingMarks,
],
content: html,
editorProps: {
attributes: { class: "reading writer-doc" },
handleDOMEvents: {
contextmenu: (pmView, event) => {
event.preventDefault();
if (!editor) {
return true;
}
const hit = pmView.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) {
const { from, to } = editor.state.selection;
if (from === to || hit.pos < from || hit.pos > to) {
editor.chain().setTextSelection(hit.pos).run();
}
}
menu = {
x: event.clientX,
y: event.clientY,
items: writerContextItems(editor),
};
return true;
},
},
handleClick: (_view, _pos, event) => {
const node = event.target instanceof Element ? event.target.closest("a") : null;
if (!node) {
return false;
}
const href = node.getAttribute("href") ?? "";
const kind = node.getAttribute("data-kind");
if (kind === "wiki") {
event.preventDefault();
onOpenLink?.("wiki", href);
return true;
}
if (kind === "md" && !/^https?:\/\//i.test(href)) {
event.preventDefault();
onOpenLink?.("md", href);
return true;
}
return false;
},
},
onCreate: () => {
applying = false;
queueMicrotask(() => {
skipUpdate = false;
});
},
onUpdate: ({ editor: current }) => {
if (applying || skipUpdate) {
return;
}
onChange(htmlToMarkdown(current.getHTML()));
},
});
editor = view;
ready += 1;
view.commands.focus("end");
});
return () => {
cancelled = true;
editor?.destroy();
editor = undefined;
};
});
$effect(() => {
void ready;
const contents = buffer.contents;
const view = editor;
if (!view) {
return;
}
if (view.isFocused) {
return;
}
const current = htmlToMarkdown(view.getHTML());
if (contents === current) {
return;
}
applying = true;
void loadUrls(buffer.relPath, contents).then((urls) => {
if (editor !== view) {
return;
}
view.commands.setContent(renderMarkdownHtml(contents, urls) || "<p></p>");
applying = false;
});
});
</script>
<div
class="writer-host"
role="application"
aria-label="Writer"
bind:this={host}
ondragover={(event) => {
if (imageFiles(event.dataTransfer).length > 0) {
event.preventDefault();
}
}}
ondrop={(event) => {
const files = imageFiles(event.dataTransfer);
if (files.length === 0 || !onInsertImage) {
return;
}
event.preventDefault();
void (async () => {
for (const file of files) {
const snippet = await onInsertImage(file);
const rel = snippet ? /\(([^)]+)\)/.exec(snippet)?.[1] : null;
if (!rel || !editor) {
continue;
}
try {
const src = await workspaceReadDataUrl(rel);
editor.commands.insertContent(
`<img src="${src}" alt="${file.name}" data-md-src="${rel}" data-md-kind="md" />`,
);
} catch {
editor.commands.insertContent(snippet);
}
}
})();
}}
></div>
{#if menu}
<ContextMenu
x={menu.x}
y={menu.y}
items={menu.items}
onClose={() => (menu = null)}
/>
{/if}
<style>
.writer-host {
position: absolute;
inset: 0;
overflow: hidden;
}
.writer-host :global(.tiptap),
.writer-host :global(.ProseMirror) {
height: 100%;
overflow: auto;
}
</style>
+90
View File
@@ -0,0 +1,90 @@
import { Extension } from "@tiptap/core";
import type { Node as PmNode } from "@tiptap/pm/model";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
export function headingMarkText(level: number): string {
const n = Math.min(6, Math.max(1, Math.floor(level)));
return "#".repeat(n);
}
export function fenceOpenText(lang: string): string {
const name = lang.trim();
return name ? `\`\`\`${name}` : "```";
}
export function findInlineCodeRange(doc: PmNode, pos: number): { from: number; to: number } | null {
const $pos = doc.resolve(pos);
const type = doc.type.schema.marks.code;
if (!type || !$pos.parent.inlineContent) {
return null;
}
const parentStart = $pos.start();
let runFrom = -1;
let runTo = -1;
let hit: { from: number; to: number } | null = null;
$pos.parent.forEach((child, offset) => {
const from = parentStart + offset;
const to = from + child.nodeSize;
if (type.isInSet(child.marks)) {
if (runFrom === -1) {
runFrom = from;
}
runTo = to;
return;
}
if (runFrom !== -1 && pos >= runFrom && pos <= runTo) {
hit = { from: runFrom, to: runTo };
}
runFrom = -1;
runTo = -1;
});
if (hit) {
return hit;
}
if (runFrom !== -1 && pos >= runFrom && pos <= runTo) {
return { from: runFrom, to: runTo };
}
return null;
}
export const HeadingMarks = Extension.create({
name: "headingMarks",
addProseMirrorPlugins() {
return [
new Plugin({
key: new PluginKey("headingMarks"),
props: {
decorations(state) {
const { $from } = state.selection;
if ($from.parent.type.name === "codeBlock") {
const lang = String($from.parent.attrs.language ?? "");
return DecorationSet.create(state.doc, [
Decoration.node($from.before(), $from.after(), {
class: "is-editing",
"data-fence-open": fenceOpenText(lang),
}),
]);
}
if ($from.parent.type.name === "heading") {
const level = Number($from.parent.attrs.level ?? 1);
return DecorationSet.create(state.doc, [
Decoration.node($from.before(), $from.after(), {
class: "is-editing",
"data-heading-marks": headingMarkText(level),
}),
]);
}
const range = findInlineCodeRange(state.doc, $from.pos);
if (!range) {
return DecorationSet.empty;
}
return DecorationSet.create(state.doc, [
Decoration.inline(range.from, range.to, { class: "is-editing-ticks" }),
]);
},
},
}),
];
},
});
+170
View File
@@ -0,0 +1,170 @@
import { actionIcon, type ActionIcon } from "../ui/actionIcons";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
export type ImageActions = {
edit?: () => void;
done?: () => void;
editing?: boolean;
select?: () => void;
remove?: () => void;
markdown?: () => string;
swap?: (image: HTMLImageElement) => Promise<void>;
open?: (image: HTMLImageElement) => void;
reveal?: (image: HTMLImageElement) => Promise<void>;
report?: (message: string) => void;
};
async function copyImage(image: HTMLImageElement) {
const png = (async () => {
await image.decode();
const canvas = document.createElement("canvas");
canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
const context = canvas.getContext("2d");
if (!context) throw new Error("Image clipboard is unavailable.");
context.drawImage(image, 0, 0);
return await new Promise<Blob>((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not copy image.")), "image/png"));
})();
await navigator.clipboard.write([new ClipboardItem({ "image/png": png })]);
}
function button(label: string, icon: ActionIcon, action: () => void) {
const control = document.createElement("button");
control.type = "button";
control.className = "image-action";
control.setAttribute("aria-label", label);
control.dataset.tooltip = label;
control.append(actionIcon(icon));
control.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); action(); });
return control;
}
function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
const dialog = document.createElement("dialog");
dialog.className = "image-lightbox";
dialog.setAttribute("aria-label", "Image zoom");
const header = document.createElement("div");
header.className = "image-lightbox-toolbar";
const name = document.createElement("span");
name.className = "image-lightbox-name";
name.textContent = original.dataset.mdSrc || original.alt || "Image";
const viewport = document.createElement("div");
viewport.className = "image-lightbox-viewport";
const image = original.cloneNode() as HTMLImageElement;
image.removeAttribute("loading");
image.draggable = false;
let scale = 0;
const status = document.createElement("span");
status.className = "image-lightbox-scale";
status.setAttribute("aria-live", "polite");
function resize(next: number) {
scale = next;
image.style.width = scale ? `${image.naturalWidth * scale}px` : "";
viewport.classList.toggle("is-zoomed", scale > 0);
status.textContent = scale ? `${Math.round(scale * 100)}%` : "Fit";
zoomOut.disabled = scale === 0;
zoomIn.disabled = scale >= 4;
}
const zoomOut = button("Zoom out", "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2));
const zoomIn = button("Zoom in", "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1));
const fit = button("Fit image", "select", () => resize(0));
const close = button("Close image", "close", () => dialog.close());
header.append(name, zoomOut, status, zoomIn, fit, close);
viewport.append(image);
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 });
image.addEventListener("load", () => resize(scale));
document.body.append(dialog);
dialog.showModal();
resize(0);
close.focus();
return () => { if (dialog.isConnected) dialog.close(); };
}
export function imageControls(root: HTMLElement, actions: ImageActions = {}, measure?: () => void): () => void {
const cleanup: (() => void)[] = [];
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
if (image.closest(".md-image-frame")) continue;
const frame = document.createElement("span");
frame.className = "md-image-frame";
frame.contentEditable = "false";
frame.tabIndex = 0;
frame.setAttribute("role", "group");
frame.setAttribute("aria-label", `Image: ${image.alt || image.dataset.mdSrc || "image"}`);
image.replaceWith(frame);
frame.append(image);
image.draggable = false;
const toolbar = document.createElement("span");
toolbar.className = "md-image-actions";
let closeZoom: (() => void) | undefined;
const zoom = button("Zoom in", "zoom-in", () => { closeZoom = zoomImage(image, zoom); });
cleanup.push(() => closeZoom?.());
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);
let menu: HTMLElement | undefined;
let openingMenu = false;
function closeMenu(focus = true) { menu?.remove(); menu = undefined; if (focus && frame.isConnected) frame.focus({ preventScroll: true }); }
async function run(action: () => void | Promise<void>) {
closeMenu(false);
try { await action(); } catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (actions.report) actions.report(message);
else { frame.dataset.error = message; frame.setAttribute("aria-description", message); }
}
}
function select() {
actions.select?.();
frame.classList.add("is-selected");
frame.focus({ preventScroll: true });
}
function openMenu(x: number, y: number) {
closeMenu(false); select();
const items: ActionMenuItem[] = [
{ label: "Copy image", icon: "copy", run: () => void run(() => copyImage(image)) },
...(actions.markdown ? [{ label: "Copy Markdown", icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []),
...(actions.swap ? [{ label: "Swap image…", icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []),
...(actions.remove ? [{ label: "Remove image", icon: "trash" as const, run: () => void run(actions.remove!) }] : []),
{ separator: true },
{ label: "Zoom in", icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } },
...(actions.edit ? [{ label: "Edit image source", icon: "code" as const, run: () => void run(actions.edit!) }] : []),
...(actions.open ? [{ label: "Open in new tab", icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []),
{ label: "Copy path", icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) },
...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: "Show in Explorer", icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []),
];
openingMenu = true;
try { menu = actionMenu(x, y, items, closeMenu, "Image actions"); }
finally { openingMenu = false; }
}
frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } });
frame.addEventListener("contextmenu", event => { event.preventDefault(); event.stopPropagation(); openMenu(event.clientX, event.clientY); });
frame.addEventListener("keydown", event => {
if (event.target !== frame) return;
if (event.key === "ContextMenu" || (event.shiftKey && event.key === "F10")) {
event.preventDefault(); event.stopPropagation(); const rect = frame.getBoundingClientRect(); openMenu(rect.left + 16, rect.top + 16);
} else if ((event.key === "Delete" || event.key === "Backspace") && actions.remove) {
event.preventDefault(); event.stopPropagation(); actions.remove();
} else if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "c") {
event.preventDefault(); event.stopPropagation(); void run(() => copyImage(image));
} else if (event.key === "Enter" || event.key === " ") { event.preventDefault(); select(); }
});
const outside = (event: Event) => {
if (openingMenu) return;
if (event.target instanceof Node && !frame.contains(event.target) && !menu?.contains(event.target)) { closeMenu(false); frame.classList.remove("is-selected"); }
};
const dismiss = () => closeMenu(false);
const scroll = (event: Event) => { if (menu && event.target instanceof Node && !menu.contains(event.target)) closeMenu(false); };
document.addEventListener("mousedown", outside, true);
document.addEventListener("focusin", outside, true);
window.addEventListener("resize", dismiss);
document.addEventListener("scroll", scroll, true);
cleanup.push(() => { closeMenu(false); document.removeEventListener("mousedown", outside, true); document.removeEventListener("focusin", outside, true); window.removeEventListener("resize", dismiss); document.removeEventListener("scroll", scroll, true); });
if (measure) {
image.addEventListener("load", measure);
image.addEventListener("error", measure);
cleanup.push(() => { image.removeEventListener("load", measure); image.removeEventListener("error", measure); });
}
}
return () => cleanup.forEach(dispose => dispose());
}
+18
View File
@@ -0,0 +1,18 @@
import { StateEffect, StateField } from "@codemirror/state";
export const trackImageDrop = StateEffect.define<{ id: symbol; from: number; to: number }>();
export const clearImageDrop = StateEffect.define<symbol>();
export const imageDrops = StateField.define<Map<symbol, { from: number; to: number }>>({
create: () => new Map(),
update(value, transaction) {
const next = new Map([...value].map(([id, range]) => [id, {
from: transaction.changes.mapPos(range.from, 1),
to: transaction.changes.mapPos(range.to, 1),
}]));
for (const effect of transaction.effects) {
if (effect.is(trackImageDrop)) next.set(effect.value.id, effect.value);
if (effect.is(clearImageDrop)) next.delete(effect.value);
}
return next;
},
});
+76
View File
@@ -0,0 +1,76 @@
import { EditorView, WidgetType } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { imageControls, type ImageActions } from "./imageControls";
import { editImageSource } from "./imageSource";
import { requestText } from "../workspace/dialogs.svelte";
import { isRemoteImage } from "../workspace/media";
import { actionIcon } from "../ui/actionIcons";
export type ImageContext = {
open?: (image: HTMLImageElement) => void;
reveal?: (image: HTMLImageElement) => Promise<void>;
validate?: (source: string) => Promise<void>;
report?: (message: string) => void;
};
const cleanups = new WeakMap<HTMLElement, () => void>();
export class ImagePreview extends WidgetType {
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
toDOM(view: EditorView) {
const dom = document.createElement(this.block ? "div" : "span");
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
dom.innerHTML = this.html;
const range = () => {
const position = view.posAtDOM(dom);
const from = this.editing ? position - this.source.length : position;
return { from, to: from + this.source.length };
};
const replace = (insert: string) => {
if (!dom.isConnected) return;
const target = range();
view.dispatch({ changes: { ...target, insert }, selection: { anchor: target.from + insert.length }, effects: editImageSource.of(null), annotations: isolateHistory.of("full"), userEvent: "input.image" });
view.focus();
};
const actions: ImageActions = {
editing: this.editing,
select: () => { const { from, to } = range(); view.dispatch({ selection: { anchor: from, head: to } }); },
edit: () => {
const target = range();
view.dispatch({ effects: [editImageSource.of(target), EditorView.scrollIntoView(target.from, { y: "nearest" })], selection: { anchor: target.from, head: target.to } });
view.focus();
},
done: () => { view.dispatch({ effects: editImageSource.of(null) }); view.focus(); },
remove: () => replace(""),
markdown: () => this.source,
open: this.context.open,
reveal: this.context.reveal,
report: this.context.report,
swap: async image => {
const before = view.state.doc;
const path = (await requestText("Image path relative to this note, or https URL", image.dataset.mdSrc || ""))?.trim();
if (!path || !dom.isConnected || view.state.doc !== before) return;
if (!isRemoteImage(path) && /^[a-z][a-z\d+.-]*:/i.test(path)) throw new Error("Choose a workspace image path or an http/https URL.");
await this.context.validate?.(path);
if (!dom.isConnected || view.state.doc !== before) return;
const target = path.replace(/[<>\s]/g, char => encodeURIComponent(char));
const alt = image.alt.replace(/[\\\[\]]/g, "\\$&");
replace(`![${alt}](<${target}>)`);
},
};
cleanups.set(dom, imageControls(dom, actions, () => { if (dom.isConnected) view.requestMeasure(); }));
// A missing attachment must still offer a way to repair its hidden source.
if (!dom.querySelector("img")) {
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.append(actionIcon("code"));
edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); });
dom.append(edit);
}
return dom;
}
destroy(dom: HTMLElement) { cleanups.get(dom)?.(); }
ignoreEvent() { return true; }
}
+22
View File
@@ -0,0 +1,22 @@
import { StateEffect, StateField } from "@codemirror/state";
import { markdownLanguage } from "@codemirror/lang-markdown";
export type ImageRange = { from: number; to: number };
export function imageSourceRanges(source: string): ImageRange[] {
const ranges: ImageRange[] = [];
// Image controls must also work beyond CodeMirror's partially parsed viewport.
markdownLanguage.parser.parse(source).iterate({ enter(node) {
if (node.name === "Image") { ranges.push({ from: node.from, to: node.to }); return false; }
} });
return ranges;
}
export const editImageSource = StateEffect.define<ImageRange | null>();
export const imageSource = StateField.define<ImageRange | null>({
create: () => null,
update(value, transaction) {
if (value) value = { from: transaction.changes.mapPos(value.from, -1), to: transaction.changes.mapPos(value.to, 1) };
for (const effect of transaction.effects) if (effect.is(editImageSource)) value = effect.value;
if (value && transaction.selection && !transaction.selection.ranges.some(range => range.from <= value.to && range.to >= value.from)) return null;
return value;
},
});
+39
View File
@@ -0,0 +1,39 @@
const LANGUAGES: Record<string, string> = {
md: "markdown",
markdown: "markdown",
mdown: "markdown",
txt: "plaintext",
py: "python",
js: "javascript",
mjs: "javascript",
cjs: "javascript",
ts: "typescript",
tsx: "typescript",
jsx: "javascript",
json: "json",
css: "css",
scss: "scss",
html: "html",
htm: "html",
rs: "rust",
sh: "shell",
bash: "shell",
yml: "yaml",
yaml: "yaml",
toml: "ini",
xml: "xml",
svg: "xml",
};
function fileExt(relPath: string): string {
const base = relPath.split("/").pop() ?? relPath;
const dot = base.lastIndexOf(".");
if (dot <= 0) {
return "";
}
return base.slice(dot + 1).toLowerCase();
}
export function languageFor(relPath: string): string {
return LANGUAGES[fileExt(relPath)] ?? "plaintext";
}
+173
View File
@@ -0,0 +1,173 @@
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
import { tableControls, tableEditors } from "./tableControls";
import { parseMarkdownTable } from "./markdownTable";
import type { TableContextActions } from "./tableCellActions";
import { imageControls } from "./imageControls";
import { ImagePreview, type ImageContext } from "./imagePreview";
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>();
class Checkbox extends WidgetType {
constructor(readonly checked: boolean) { super(); }
eq(other: Checkbox) { return this.checked === other.checked; }
toDOM(view: EditorView) {
const box = document.createElement("input");
box.type = "checkbox";
box.checked = this.checked;
box.className = "writer-checkbox";
box.setAttribute("aria-label", this.checked ? "Mark task incomplete" : "Mark task complete");
box.addEventListener("mousedown", event => event.preventDefault());
box.addEventListener("click", event => {
event.stopPropagation();
const line = view.state.doc.lineAt(view.posAtDOM(box));
const match = /^(\s*[-+*]\s+\[)([ xX])(\])/.exec(line.text);
if (!match) return;
const from = line.from + match[1].length;
view.dispatch({ changes: { from, to: from + 1, insert: this.checked ? " " : "x" }, userEvent: "input" });
});
return box;
}
ignoreEvent() { return true; }
}
class Preview extends WidgetType {
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false) { super(); }
eq(other: Preview) { return other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
updateDOM(dom: HTMLElement) { return tableEditors.get(dom)?.source === this.source; }
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
toDOM(view: EditorView) {
const dom = document.createElement("div");
dom.className = "reading writer-preview";
dom.innerHTML = this.html;
tableControls(dom, view, this.source, this.actions);
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
dom.addEventListener("mousedown", event => {
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
if (event.target instanceof Element && event.target.closest("summary, .md-image-frame")) return;
if (event.ctrlKey || event.metaKey) return;
event.preventDefault();
view.dispatch({ selection: { anchor: view.posAtDOM(dom) }, scrollIntoView: true });
view.focus();
});
requestAnimationFrame(() => {
if (dom.isConnected) {
void renderDiagrams(dom, () => !dom.isConnected).then(() => view.requestMeasure());
view.requestMeasure();
}
});
return dom;
}
ignoreEvent() { return true; }
}
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
function build(state: EditorState): DecorationSet {
const ranges: Range<Decoration>[] = [];
const active = state.selection.ranges.map(range => ({ from: state.doc.lineAt(range.from).from, to: state.doc.lineAt(range.to).to }));
const selected = (from: number, to: number) => active.some(range => range.from <= to && range.to >= from);
const hiddenBlocks: { from: number; to: number }[] = [];
const source = state.doc.toString();
const editing = state.field(imageSource);
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;
// 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;
const end = section.end - (source.slice(section.start, section.end).match(/\n+$/)?.[0].length || 0);
const isTable = /<table>/.test(section.html) && parseMarkdownTable(source.slice(section.start, end));
if (end <= section.start) continue;
const imageHtml = section.html.match(/<img\b[^>]*>|<span class="missing-image"[^>]*>[\s\S]*?<\/span>/g) || [];
const nodes = imageNodes.filter(node => node.from >= section.start && node.to <= end);
if (!isTable && imageHtml.length && imageHtml.length === nodes.length && (!/md-callout/.test(section.html) || selected(section.start, end))) {
nodes.forEach((node, index) => {
const revealed = editing?.from === node.from;
const block = state.doc.lineAt(node.from).from === node.from && state.doc.lineAt(node.to).to === node.to;
const widget = new ImagePreview(imageHtml[index], source.slice(node.from, node.to), images, revealed, revealed || block);
if (revealed) ranges.push(Decoration.widget({ widget, block: true, side: 1 }).range(node.to));
else {
hiddenBlocks.push(node);
ranges.push(Decoration.replace({ widget, block }).range(node.from, node.to));
}
});
continue;
}
if (!isTable && selected(section.start, end)) {
// Keep images below the editable source, without duplicating surrounding prose.
const images = section.html.match(/<img\b[^>]*>|<span class="missing-image"[^>]*>[\s\S]*?<\/span>/g)?.join("");
if (images) ranges.push(Decoration.widget({ widget: new Preview(images, source.slice(section.start, end), actions, true), block: true, side: 1 }).range(end));
continue;
}
hiddenBlocks.push({ from: section.start, to: end });
ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions), block: true }).range(section.start, end));
}
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({}).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 }[] = [];
syntaxTree(state).iterate({ enter(node) {
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");
return false;
}
const line = state.doc.lineAt(node.from);
if (/^ATXHeading[1-6]$/.test(node.name)) {
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
}
if (selected(node.from, node.to)) return;
if (node.name === "HeaderMark") replace(node.from, Math.min(line.to, node.to + 1));
if (node.name === "StrongEmphasis") mark(node.from, node.to, "writer-strong");
if (node.name === "Emphasis") mark(node.from, node.to, "writer-emphasis");
if (node.name === "Strikethrough") mark(node.from, node.to, "writer-strike");
if (node.name === "InlineCode") mark(node.from, node.to, "writer-inline-code");
if (node.name === "NoteHighlight") mark(node.from, node.to, "writer-highlight");
if (node.name === "NoteMath") mark(node.from, node.to, "writer-math");
if (node.name === "NoteComment") mark(node.from, node.to, "writer-comment");
if (["EmphasisMark", "StrikethroughMark", "CodeMark", "NoteFormatMark"].includes(node.name)) replace(node.from, node.to);
if (node.name === "Link") {
// Wiki links are handled separately, because CommonMark sees their inner
// brackets as an incomplete reference link.
if (source[node.from - 1] === "[" && source[node.to] === "]") return false;
const text = source.slice(node.from, node.to);
const match = /^\[([^\]]+)\]\(([^\s)]+)(?:\s+"[^"]*")?\)$/.exec(text);
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));
return false;
}
if (node.name === "TaskMarker") {
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
if (!match) return;
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x") }).range(line.from + match[1].length, line.from + match[0].length));
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
}
} });
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
const from = match.index, to = from + match[0].length;
if (selected(from, to) || hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
const separator = match[1].indexOf("|");
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));
}
return Decoration.set(ranges, true);
}
return [imageSource, StateField.define<DecorationSet>({
create: build,
update(value, transaction) {
return transaction.docChanged || transaction.selection || transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource)) ? build(transaction.state) : value;
},
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field))],
})];
}
+93
View File
@@ -0,0 +1,93 @@
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
export type TextSelection = { from: number; to: number };
export type MarkdownEdit = TextSelection & { insert: string; anchor: number; head: number };
export type InlineFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear";
export type ParagraphStyle = "bullet" | "number" | "task" | "body" | "quote" | 1 | 2 | 3 | 4 | 5 | 6;
export type InsertBlock = "footnote" | "table" | "callout" | "rule" | "code" | "math";
export function replacement(selection: TextSelection, insert: string, start = 0, end = insert.length): MarkdownEdit {
return { ...selection, insert, anchor: selection.from + start, head: selection.from + end };
}
export function formatText(source: string, selection: TextSelection, format: InlineFormat): MarkdownEdit {
let { from, to } = selection;
const selected = source.slice(from, to);
if (format === "clear") {
let marker: string | undefined;
do {
marker = ["**", "__", "~~", "==", "%%", "*", "_", "$", "`"].find(value => source.slice(0, from).endsWith(value) && source.slice(to).startsWith(value));
if (marker) { from -= marker.length; to += marker.length; }
} while (marker);
// The inline serializer uses <br> in tables; retain real newlines in prose.
return replacement({ from, to }, plainInlineMarkdown(source.slice(from, to)).replace(/<br>/g, source.includes("\r\n") ? "\r\n" : "\n"));
}
let marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format];
// Ignore boundary whitespace so emphasis stays valid Markdown.
if (selected.trim()) { from += selected.length - selected.trimStart().length; to -= selected.length - selected.trimEnd().length; }
const text = source.slice(from, to);
if (format === "code") {
const wrapped = /^(`+)([\s\S]+)\1$/.exec(text);
if (wrapped && !wrapped[2].startsWith("`") && !wrapped[2].endsWith("`")) return replacement({ from, to }, wrapped[2].replace(/^ (.*) $/s, "$1"));
const before = /(`+) ?$/.exec(source.slice(0, from)), after = /^ ?(`+)/.exec(source.slice(to));
if (before && after && before[1] === after[1]) return replacement({ from: from - before[0].length, to: to + after[0].length }, text);
}
const isWrapped = text.startsWith(marker) && text.endsWith(marker) && text.length >= marker.length * 2
&& !(format === "italic" && text.startsWith("**") && !text.startsWith("***"));
if (isWrapped) return replacement({ from, to }, text.slice(marker.length, -marker.length));
const before = source.slice(0, from), after = source.slice(to);
const surrounds = before.endsWith(marker) && after.startsWith(marker)
&& !(format === "italic" && before.endsWith("**") && !before.endsWith("***"));
if (surrounds) return replacement({ from: from - marker.length, to: to + marker.length }, text);
if (format === "code") marker = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(match => match[0].length)) + 1);
const padding = format === "code" && /^`|`$/.test(text) ? " " : "";
return replacement({ from, to }, marker + padding + text + padding + marker, marker.length + padding.length, marker.length + padding.length + text.length);
}
export function paragraphText(source: string, selection: TextSelection, style: ParagraphStyle): MarkdownEdit {
const from = selection.from === 0 ? 0 : source.lastIndexOf("\n", selection.from - 1) + 1;
// A selection ending at the start of the next line must not format that line.
const last = selection.to > selection.from && source[selection.to - 1] === "\n" ? selection.to - 1 : selection.to;
const newline = source.indexOf("\n", last);
const to = newline < 0 ? source.length : newline > 0 && source[newline - 1] === "\r" ? newline - 1 : newline;
const eol = source.includes("\r\n") ? "\r\n" : "\n";
let number = 0;
const insert = source.slice(from, to).split(/\r?\n/).map(line => {
if (!line.trim() && from !== to) { number = 0; return line; }
const indent = /^[\t ]*/.exec(line)![0];
const body = line.slice(indent.length).replace(/^(?:#{1,6}\s+|>\s?|(?:[-+*]|\d+[.)])\s+(?:\[[ xX]\]\s+)?)/, "");
const prefix = typeof style === "number" ? "#".repeat(style) + " " : { bullet: "- ", number: `${++number}. `, task: "- [ ] ", quote: "> ", body: "" }[style];
return indent + prefix + body;
}).join(eol);
return replacement({ from, to }, insert, selection.from === selection.to ? insert.length : 0);
}
export function insertBlock(source: string, selection: TextSelection, kind: InsertBlock): MarkdownEdit {
const eol = source.includes("\r\n") ? "\r\n" : "\n";
const text = source.slice(selection.from, selection.to);
if (kind === "footnote") {
let id = 1;
while (source.includes(`[^${id}]`)) id++;
const reference = `[^${id}]`, definition = (text || "Footnote text").replace(/\r?\n/g, eol + " ");
const tail = source.slice(selection.to);
const beforeDefinition = reference + tail;
const gap = beforeDefinition.endsWith(eol + eol) ? "" : beforeDefinition.endsWith(eol) ? eol : eol + eol;
const insert = beforeDefinition + gap + reference + ": " + definition + eol;
const start = beforeDefinition.length + gap.length + reference.length + 2;
return replacement({ from: selection.from, to: source.length }, insert, start, start + definition.length);
}
const fence = "`".repeat(Math.max(2, ...[...text.matchAll(/`+/g)].map(match => match[0].length)) + 1);
const content = text || (kind === "code" ? "Code" : kind === "math" ? "equation" : "Callout text");
let block = kind === "table" ? "| Column 1 | Column 2 |\n| --- | --- |\n| | |"
: kind === "rule" ? "---" : kind === "code" ? `${fence}\n${content}\n${fence}`
: kind === "math" ? `$$\n${content}\n$$` : `> [!note]\n> ${content.replace(/\r?\n/g, "\n> ")}`;
block = block.replace(/\r?\n/g, eol);
// Structural inserts should not delete selected prose.
const at = kind === "table" || kind === "rule" ? { from: selection.to, to: selection.to } : selection;
const before = source.slice(0, at.from), after = source.slice(at.to);
const leading = !before || before.endsWith(eol + eol) ? "" : before.endsWith(eol) ? eol : eol + eol;
const trailing = after.startsWith(eol + eol) ? "" : after.startsWith(eol) ? eol : eol + eol;
const start = kind === "table" ? block.indexOf("Column 1") : kind === "rule" ? block.length : block.indexOf(eol) + eol.length + (kind === "callout" ? 2 : 0);
const length = kind === "table" ? 8 : kind === "rule" ? 0 : content.length;
return replacement(at, leading + block + trailing, leading.length + start, leading.length + start + length);
}
+122
View File
@@ -0,0 +1,122 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { requestText } from "../workspace/dialogs.svelte";
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";
export type MarkdownMenuEditor = {
snapshot: () => { source: string; selection: TextSelection; valid: () => boolean };
apply: (edit: MarkdownEdit) => void;
selectAll: () => void;
focus: () => void;
};
// 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) {
let root: HTMLElement | undefined, destroyed = false;
function close(focus = true) {
root?.remove(); root = undefined;
if (focus && !destroyed) editor.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 snapshot = editor.snapshot(), { source, selection } = snapshot;
const text = source.slice(selection.from, selection.to);
const valid = () => !destroyed && snapshot.valid();
function apply(edit: MarkdownEdit) {
if (!valid()) return;
close(); editor.apply(edit); editor.focus();
}
async function request(run: () => Promise<void>) {
close(false);
try { await run(); } catch (error) { if (!destroyed) report(error instanceof Error ? error.message : String(error)); }
finally { if (valid()) editor.focus(); }
}
function link(external: boolean) {
void request(async () => {
const target = (await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text))?.trim();
if (!target || !valid()) return;
if (external) {
try {
const url = new URL(target);
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error();
} catch { report("Enter a valid http, https, or mailto link."); return; }
const label = (text || target).replace(/[\\[\]]/g, "\\$&").replace(/\r?\n/g, " ");
apply(replacement(selection, `[${label}](${target.replace(/[()<>]/g, char => encodeURIComponent(char).replace("(", "%28").replace(")", "%29"))})`));
} else {
if (/[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; }
const label = text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim();
apply(replacement(selection, `[[${target}${label && label !== target ? "|" + label : ""}]]`));
}
});
}
function clipboard(kind: "cut" | "copy" | "paste" | "plain") {
void request(async () => {
try {
if (kind === "cut" || kind === "copy") {
await navigator.clipboard.writeText(text);
if (kind === "cut") apply(replacement(selection, ""));
} else {
let value = "";
if (kind === "paste" && navigator.clipboard.read) {
try {
const data = await navigator.clipboard.read();
const rich = data.find(item => item.types.includes("text/html"));
if (rich) value = htmlToMarkdown(await (await rich.getType("text/html")).text());
} catch { /* Fall back to the text clipboard on older WebViews. */ }
}
if (!value) value = await navigator.clipboard.readText();
if (value) apply(replacement(selection, value.replace(/\r?\n/g, source.includes("\r\n") ? "\r\n" : "\n")));
}
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
});
}
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[] = [
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const target = await actions.onExtract?.(text, text, valid);
if (target) apply(replacement(selection, `[[${target}|${text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim()}]]`));
}) },
{ label: "Format", icon: "format", children: cellFormats.flatMap(([label, kind]) => [
...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []),
{ label, icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) },
]) },
{ label: "Paragraph", icon: "paragraph", children: [
paragraph("Bullet list", "bullet", "bullet"), paragraph("Numbered list", "number", "number"), paragraph("Task list", "task", "task"),
{ separator: true },
...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(`Heading ${level}`, level, "heading")),
paragraph("Body", "body", "paragraph"), { separator: true }, paragraph("Quote", "quote", "quote"),
] },
{ label: "Insert", icon: "insert", children: [
insert("Footnote", "footnote", "footnote"), insert("Table", "table", "table"), insert("Callout", "callout", "quote"), insert("Horizontal rule", "rule", "rule"),
{ separator: true }, insert("Code block", "code", "code"), insert("Math block", "math", "math"),
] },
{ separator: true },
{ label: "Cut", icon: "cut", disabled: !text, run: () => clipboard("cut") },
{ label: "Copy", icon: "copy", disabled: !text, run: () => clipboard("copy") },
{ label: "Paste", icon: "paste", run: () => clipboard("paste") },
{ label: "Paste as plain text", icon: "paste-text", run: () => clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } },
];
root = actionMenu(x, y, items, close, "Markdown text actions");
}
return { open, close, destroy() {
destroyed = true; close(false);
document.removeEventListener("mousedown", outside, true);
document.removeEventListener("scroll", scroll, true);
window.removeEventListener("resize", resize);
} };
}
+74
View File
@@ -0,0 +1,74 @@
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 };
function row(text: string, from: number): TableRow {
const pipes: number[] = [];
for (let index = 0; index < text.length; index++) {
if (text[index] !== "|") continue;
let slashes = 0;
for (let before = index - 1; before >= 0 && text[before] === "\\"; before--) slashes++;
if (slashes % 2 === 0) pipes.push(index);
}
const start = text.search(/\S/);
const end = text.trimEnd().length;
const left = pipes[0] === start ? pipes.shift()! + 1 : 0;
const right = pipes.at(-1) === end - 1 ? pipes.pop()! : text.length;
const boundaries = [left - 1, ...pipes, right];
const cells = boundaries.slice(0, -1).map((boundary, index) => {
const rawFrom = boundary + 1, rawTo = boundaries[index + 1];
const raw = text.slice(rawFrom, rawTo);
const leading = raw.length - raw.trimStart().length;
const cellFrom = from + rawFrom + leading;
return { text: raw.trim(), from: cellFrom, to: Math.max(cellFrom, from + rawTo - (raw.length - raw.trimEnd().length)) };
});
return { from, to: from + text.length, indent: /^\s*/.exec(text)![0], cells };
}
export function parseMarkdownTable(source: string): MarkdownTable | null {
const rows: TableRow[] = [];
let offset = 0;
const eol = source.includes("\r\n") ? "\r\n" : "\n";
for (const line of source.split(eol)) {
if (!line.trim()) break;
rows.push(row(line, offset));
offset += line.length + eol.length;
}
if (rows.length < 2 || !source.slice(rows[0].from, rows[0].to).includes("|")) return null;
const columns = rows[0].cells.length;
if (rows[1].cells.length !== columns || !rows[1].cells.every(cell => /^:?-+:?$/.test(cell.text))) return null;
return { rows, columns, eol, end: rows.at(-1)!.to };
}
export function appendTableColumn(source: string): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const body = table.rows.map((row, index) => {
const cells = row.cells.map(cell => cell.text);
while (cells.length < table.columns) cells.push("");
cells.splice(table.columns, 0, index === 1 ? "---" : "");
return `${row.indent}| ${cells.join(" | ")} |`;
}).join(table.eol);
return body + source.slice(table.end);
}
export function appendTableRow(source: string): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const row = `${table.rows[0].indent}| ${Array.from({ length: table.columns }, () => "").join(" | ")} |`;
return source.slice(0, table.end) + table.eol + row + source.slice(table.end);
}
// Change only the selected cell: padding, alignment, and every other row stay intact.
export function replaceTableCell(source: string, rowIndex: number, column: number, text: string): string {
const table = parseMarkdownTable(source);
if (!table || rowIndex === 1 || column < 0 || column >= table.columns || /[\r\n]/.test(text)) return source;
const row = table.rows[rowIndex];
if (!row) return source;
const cell = row.cells[column];
if (cell) return source.slice(0, cell.from) + text + source.slice(cell.to);
const cells = row.cells.map(cell => cell.text);
while (cells.length <= column) cells.push("");
cells[column] = text;
return source.slice(0, row.from) + `${row.indent}| ${cells.join(" | ")} |` + source.slice(row.to);
}
+1
View File
@@ -0,0 +1 @@
declare module "monaco-editor-css";
+30
View File
@@ -0,0 +1,30 @@
import type { Chrome } from "../workspace/types";
export function monacoChrome(mode: Chrome) {
if (mode === "Writing") {
return {
wordWrap: "on" as const,
lineNumbers: "off" as const,
minimap: { enabled: false },
fontSize: 16,
lineHeight: 26,
folding: false,
glyphMargin: false,
lineDecorationsWidth: 24,
padding: { top: 16, bottom: 48 },
renderLineHighlight: "none" as const,
};
}
return {
wordWrap: "off" as const,
lineNumbers: "on" as const,
minimap: { enabled: true, scale: 1 },
fontSize: 14,
lineHeight: 22,
folding: true,
glyphMargin: true,
lineDecorationsWidth: 10,
padding: { top: 8, bottom: 24 },
renderLineHighlight: "line" as const,
};
}
+32
View File
@@ -0,0 +1,32 @@
import * as monaco from "monaco-editor";
import "monaco-editor-css";
import editorWorkerUrl from "monaco-editor/editor/editor.worker.js?url";
self.MonacoEnvironment = {
getWorker() {
return new Worker(editorWorkerUrl, { type: "module" });
},
};
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 { monaco };
+99
View File
@@ -0,0 +1,99 @@
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
type RenameTitle = (title: string) => Promise<void>;
class NoteTitle extends WidgetType {
constructor(readonly title: string, readonly rename?: RenameTitle) { super(); }
eq(other: NoteTitle) { return this.title === other.title && this.rename === other.rename; }
toDOM(view: EditorView) {
// Contain heading margins so CodeMirror measures the full block height.
const block = document.createElement("div");
block.style.display = "flow-root";
const heading = document.createElement("h1");
heading.className = "document-title";
heading.textContent = this.title;
block.append(heading);
if (!this.rename) return block;
const button = document.createElement("button");
button.type = "button";
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);
heading.replaceChildren(button);
const input = document.createElement("input");
input.className = "note-title-input";
input.setAttribute("aria-label", "Note filename");
input.autocomplete = "off";
input.spellcheck = false;
input.hidden = true;
heading.append(input);
const message = document.createElement("p");
message.className = "note-title-error";
message.setAttribute("role", "alert");
message.hidden = true;
block.append(message);
let editing = false, pending = false;
const finish = () => {
editing = false;
input.hidden = true;
button.hidden = false;
message.hidden = true;
input.removeAttribute("aria-invalid");
view.requestMeasure();
};
const commit = async (focusEditor: boolean) => {
if (!editing || pending) return;
pending = true;
input.readOnly = true;
input.setAttribute("aria-busy", "true");
try {
await this.rename!(input.value);
finish();
if (focusEditor && view.dom.isConnected && (document.activeElement === input || document.activeElement === document.body)) view.focus();
} catch (reason) {
if (!block.isConnected) return;
input.setAttribute("aria-invalid", "true");
message.textContent = reason instanceof Error ? reason.message : String(reason);
message.hidden = false;
view.requestMeasure();
} finally {
pending = false;
input.readOnly = false;
input.removeAttribute("aria-busy");
}
};
button.onclick = () => {
editing = true;
input.value = this.title;
button.hidden = true;
input.hidden = false;
input.focus();
input.select();
view.requestMeasure();
};
input.onblur = () => { void commit(false); };
input.onkeydown = event => {
event.stopPropagation();
if (event.isComposing) return;
if (event.key === "Enter") { event.preventDefault(); void commit(true); }
if (event.key === "Escape" && !pending) { event.preventDefault(); finish(); button.focus(); }
};
return block;
}
ignoreEvent() { return true; }
}
// Filename editing stays outside the Markdown and its undo history.
export function noteTitle(title: string, rename?: RenameTitle) {
return EditorView.decorations.of(Decoration.set([
Decoration.widget({ widget: new NoteTitle(title, rename), block: true, side: -1 }).range(0),
]));
}
+10
View File
@@ -0,0 +1,10 @@
// Readers retain editor selection when toolbar buttons take focus.
let current: { id: string; read: () => string } | undefined;
export function registerSelection(id: string, read: () => string): () => void {
const owner = { id, read };
current = owner;
return () => { if (current === owner) current = undefined; };
}
export function selectedEditorText(id?: string): string {
return current && current.id === id ? current.read() : "";
}
+30
View File
@@ -0,0 +1,30 @@
import type * as Monaco from "monaco-editor";
import type { OpenBuffer } from "../workspace/types";
import { languageFor } from "./languageFor";
type Session = {
model: Monaco.editor.ITextModel;
view: Monaco.editor.ICodeEditorViewState | null;
writer?: { source: string; state: ReturnType<import("@codemirror/state").EditorState["toJSON"]>; scroll: ReturnType<import("@codemirror/view").EditorView["scrollSnapshot"]> };
};
const sessions = new Map<string, Session>();
export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Session {
let session = sessions.get(buffer.id);
if (!session) {
session = {
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
view: null,
};
sessions.set(buffer.id, session);
}
monaco.editor.setModelLanguage(session.model, languageFor(buffer.relPath));
return session;
}
export function retainEditorSessions(ids: string[]) {
const retained = new Set(ids);
for (const [id, session] of sessions) {
if (!retained.has(id)) { session.model.dispose(); sessions.delete(id); }
}
}
+98
View File
@@ -0,0 +1,98 @@
import type { Editor, JSONContent } from "@tiptap/core";
import { requestText } from "../workspace/dialogs.svelte";
import { extractedCellMarkdown } from "./tableCellMarkdown";
import type { ActionMenuItem } from "../ui/actionMenu";
export type TableContextActions = {
onSearch?: (text: string) => void;
onExtract?: (markdown: string, label: string, valid: () => boolean) => Promise<string | null>;
};
export const cellFormats = [
["Bold", "bold"], ["Italic", "italic"], ["Strikethrough", "strike"], ["Highlight", "highlight"],
["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[] {
const selection = editor.state.selection, doc = editor.state.doc;
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(); }); }
async function request(command: () => Promise<void>) {
pending(true); close();
try { await command(); } catch (error) { report(error instanceof Error ? error.message : String(error)); }
finally { pending(false); if (!editor.isDestroyed) editor.view.focus(); }
}
function link(external: boolean) {
void request(async () => {
const target = await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text);
if (!target || !valid()) return;
if (external) {
try {
const url = new URL(target);
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error("Invalid URL");
} catch { report("Enter a valid http, https, or mailto link."); return; }
}
if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; }
run(() => {
const attrs = { href: target, "data-kind": external ? "md" : "wiki" };
if (selection.empty) editor.commands.insertContent({ type: "text", text: target, marks: [{ type: "link", attrs }] });
else editor.commands.setMark("link", attrs);
});
});
}
async function clipboard(action: "cut" | "copy" | "paste" | "plain") {
await request(async () => {
try {
if (action === "copy" || action === "cut") {
await navigator.clipboard.writeText(text);
if (action === "cut") run(() => { editor.commands.deleteSelection(); });
} else {
let html = "", value = "";
if (action === "paste" && navigator.clipboard.read) {
try {
const data = await navigator.clipboard.read();
const rich = data.find(item => item.types.includes("text/html"));
if (rich) html = await (await rich.getType("text/html")).text();
const plain = data.find(item => item.types.includes("text/plain"));
if (plain) value = await (await plain.getType("text/plain")).text();
} catch { /* Text clipboard is also supported on older WebViews. */ }
}
if (!html && !value) value = await navigator.clipboard.readText();
if (!html && !value) return;
run(() => {
if (html) editor.commands.insertContent(html);
else {
const nodes: JSONContent[] = [];
value.replace(/\r\n?/g, "\n").split("\n").forEach((line, i) => { if (i) nodes.push({ type: "hardBreak" }); if (line) nodes.push({ type: "text", text: line, marks: [] }); });
editor.commands.insertContent(nodes);
}
});
}
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
});
}
return [
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const selected = doc.slice(selection.from, selection.to).content.toJSON() as JSONContent[] | null;
const markdown = extractedCellMarkdown(selected || []);
const target = await actions.onExtract?.(markdown, text, valid);
if (target) run(() => { editor.commands.insertContent({ type: "text", text: text.replace(/\s+/g, " ").trim(), marks: [{ type: "link", attrs: { href: target, "data-kind": "wiki" } }] }); });
}) },
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, disabled: selection.empty, run: () => run(() => {
if (kind === "clear") editor.commands.unsetAllMarks(); else editor.commands.toggleMark(kind);
}) })) },
{ label: "Paragraph", icon: "paragraph", disabled: true, title: "Markdown table cells contain inline text" },
{ label: "Insert", icon: "insert", disabled: true, title: "Use the Row and Column menus to change the table" },
{ separator: true },
{ label: "Cut", icon: "cut", disabled: selection.empty, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", disabled: selection.empty, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", run: () => void clipboard("paste") },
{ 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(); } },
];
}
+63
View File
@@ -0,0 +1,63 @@
import type { JSONContent } from "@tiptap/core";
import { isTableFormula } from "./tableFormulas.ts";
// Extract inline content into a note without confusing literal <br> in code
// with actual cell hard breaks.
export function extractedCellMarkdown(nodes: JSONContent[]): string {
return nodes.map(node => {
if (node.type === "hardBreak") return "\n";
if (node.type === "paragraph") return extractedCellMarkdown(node.content || []);
return tableCellMarkdown(node);
}).join("");
}
function literal(text: string): string {
return text.replace(/&/g, "&amp;").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`).replace(/\r?\n/g, "<br>");
}
function wrap(text: string, marker: string): string {
const [, before, body, after] = /^(\s*)([\s\S]*?)(\s*)$/.exec(text)!;
return body ? `${before}${marker}${body}${marker}${after}` : text;
}
// A cell is inline Markdown. Paragraphs from pasted text become safe table breaks.
export function tableCellMarkdown(node: JSONContent): string {
// Keep plain formula input as readable source. Formatted/code/escaped text
// still follows ordinary Markdown serialization and remains literal.
if (node.type === "doc" && node.content?.length === 1 && node.content[0].type === "paragraph") {
const children = node.content[0].content || [];
const text = children.map(child => child.text || "").join("");
if (children.every(child => child.type === "text" && !child.marks?.length) && (isTableFormula(text) || /^\s*\\=(?!=)/.test(text))) return text.replace(/\|/g, "\\|");
}
if (node.type === "hardBreak") return "<br>";
if (node.type === "image") {
const source = String(node.attrs?.["data-md-src"] || node.attrs?.src || "");
const alt = String(node.attrs?.alt || "");
return node.attrs?.["data-md-kind"] === "wiki"
? `![[${literal(source)}${alt && alt !== source ? `\\|${literal(alt)}` : ""}]]`
: `![${literal(alt)}](<${source.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>)`;
}
let text = node.text === undefined
? (node.content || []).map(tableCellMarkdown).join(node.type === "doc" ? "<br>" : "")
: literal(node.text);
for (const mark of node.marks || []) {
if (mark.type === "code") {
const raw = node.text || "";
const fence = "`".repeat(Math.max(0, ...[...raw.matchAll(/`+/g)].map(match => match[0].length)) + 1);
const padding = /^`|`$|^ .* $/.test(raw) ? " " : "";
text = `${fence}${padding}${raw.replace(/\|/g, "\\|")}${padding}${fence}`;
}
if (mark.type === "bold") text = wrap(text, "**");
if (mark.type === "italic") text = wrap(text, "*");
if (mark.type === "strike") text = wrap(text, "~~");
if (mark.type === "highlight") text = wrap(text, "==");
if (mark.type === "math" || mark.type === "comment") text = wrap((node.text || "").replace(/\|/g, "\\|"), mark.type === "math" ? "$" : "%%");
if (mark.type === "link") {
const href = String(mark.attrs?.href || "");
text = mark.attrs?.["data-kind"] === "wiki"
? `[[${literal(href)}\\|${text}]]`
: `[${text}](<${href.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>${mark.attrs?.title ? ` "${String(mark.attrs.title).replace(/"/g, "&quot;")}"` : ""})`;
}
}
return text;
}
+386
View File
@@ -0,0 +1,386 @@
import { Editor, Mark } from "@tiptap/core";
import Highlight from "@tiptap/extension-highlight";
import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
import Image from "@tiptap/extension-image";
import type { EditorView } from "@codemirror/view";
import { isolateHistory, undo, redo } from "@codemirror/commands";
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable";
import { tableCellMarkdown } from "./tableCellMarkdown";
import { tableSelectionControls } from "./tableSelectionControls";
import { tableDragControls } from "./tableDragControls";
import type { TableContextActions } from "./tableCellActions";
import { actionIcon } from "../ui/actionIcons";
import { cellAddress, evaluateTableFormulas, formulaErrors, isTableFormula } from "./tableFormulas";
import { tableFormulaHtml } from "../workspace/noteHtml";
const cellFormats = ["math", "comment"].map(name => Mark.create({
name,
parseHTML: () => [{ tag: `span[data-cell-format="${name}"]` }],
renderHTML: () => ["span", { "data-cell-format": name, class: `md-inline-${name}` }, 0],
}));
const CellLink = Link.extend({
addAttributes() { return { ...this.parent?.(), "data-kind": { default: "md" } }; },
});
const CellImage = Image.extend({
addAttributes() { return { ...this.parent?.(), "data-md-src": { default: null }, "data-md-kind": { default: "md" } }; },
parseHTML() { return [...(this.parent?.() || []), { tag: "span.missing-image[data-md-src]" }]; },
renderHTML({ HTMLAttributes }) {
return HTMLAttributes.src
? ["img", HTMLAttributes]
: ["span", { ...HTMLAttributes, class: "missing-image" }, `Image unavailable: ${HTMLAttributes.alt || HTMLAttributes["data-md-src"] || ""}`];
},
});
export const tableEditors = new WeakMap<HTMLElement, { source: string; enter: (forward: boolean, x?: number) => void; destroy: () => void }>();
export function tableControls(root: HTMLElement, view: EditorView, initialSource: string, actions: TableContextActions = {}) {
const scroll = root.querySelector<HTMLElement>(".md-table-scroll");
const table = scroll?.querySelector("table");
if (!scroll || !table || !parseMarkdownTable(initialSource)) return;
const wrapper = document.createElement("div");
wrapper.className = "writer-table";
scroll.before(wrapper);
wrapper.append(scroll);
let editor: Editor | undefined;
let active: HTMLTableCellElement | undefined;
let 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; } };
tableEditors.set(root, controller);
function enter(forward: boolean, x?: number) {
const row = table!.rows[forward ? 0 : table!.rows.length - 1];
const cells = [...row.cells];
let cell = cells[forward ? 0 : cells.length - 1];
if (x !== undefined) {
const distance = (candidate: HTMLTableCellElement) => {
const rect = candidate.getBoundingClientRect();
return Math.max(rect.left - x, x - rect.right, 0);
};
cell = cells.reduce((nearest, candidate) => distance(candidate) < distance(nearest) ? candidate : nearest);
}
activate(cell);
const current = editor!;
let position = forward ? 1 : current.state.doc.content.size - 1;
if (x !== undefined) {
const edge = current.view.coordsAtPos(position);
position = current.view.posAtCoords({ left: x, top: (edge.top + edge.bottom) / 2 })?.pos ?? position;
}
current.commands.setTextSelection(position);
current.view.focus();
cell.scrollIntoView({ block: "nearest", inline: "nearest" });
}
function refreshFormulas() {
const parsed = parseMarkdownTable(controller.source);
if (!parsed) return;
const grid = parsed.rows.filter((_, index) => index !== 1).map(row => Array.from({ length: parsed.columns }, (_, c) => row.cells[c]?.text || ""));
const results = evaluateTableFormulas(grid);
for (const row of table!.rows) for (const cell of row.cells) {
const result = results[row.rowIndex]?.[cell.cellIndex];
const address = cellAddress(row.rowIndex, cell.cellIndex);
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
if (result && cell !== active) cell.innerHTML = tableFormulaHtml(result);
if (cell === active) {
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
formulaHint.textContent = result?.error ? formulaErrors[result.error] : "";
formulaHint.hidden = !formulaHint.textContent;
}
}
}
function change(insert: string, structural = false) {
const source = controller.source;
const from = view.posAtDOM(root);
if (view.state.doc.sliceString(from, from + source.length) !== source || insert === source) return;
// Keep the same DOM/editor on typing, including composition and text selection.
if (!structural) controller.source = insert;
let start = 0, oldEnd = source.length, newEnd = insert.length;
while (start < oldEnd && start < newEnd && source[start] === insert[start]) start++;
while (oldEnd > start && newEnd > start && source[oldEnd - 1] === insert[newEnd - 1]) { oldEnd--; newEnd--; }
view.dispatch({
changes: { from: from + start, to: from + oldEnd, insert: insert.slice(start, newEnd) },
userEvent: structural ? "input" : editor?.view.composing ? "input.type.compose" : "input.type.table",
annotations: structural ? isolateHistory.of("full") : firstEdit ? isolateHistory.of("before") : [],
});
firstEdit = false;
if (!structural) refreshFormulas();
view.requestMeasure();
}
function finish() {
if (!editor || !active) return;
const cell = active;
const html = editor.getHTML();
editor.destroy(); editor = undefined; active = undefined;
cell.innerHTML = html;
cell.classList.remove("is-editing");
refreshFormulas();
formulaStatus.textContent = "Type = in a cell to calculate";
formulaHint.hidden = true;
view.requestMeasure();
if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") });
}
function leave(after: boolean) {
const from = view.posAtDOM(root), to = from + controller.source.length;
finish();
let anchor = after ? Math.min(view.state.doc.length, to + 1) : Math.max(0, from - 1);
if (after && to + 1 >= view.state.doc.length) {
view.dispatch({ changes: { from: view.state.doc.length, insert: to === view.state.doc.length ? "\n\n" : "\n" }, userEvent: "input" });
anchor = to + 2;
} else if (after && view.state.doc.sliceString(to, to + 2) === "\n\n") {
// Leave the separator blank so typing below cannot become another row.
anchor = to + 2;
} else if (!after && from === 0) {
view.dispatch({ changes: { from: 0, insert: "\n\n" }, userEvent: "input" });
anchor = 0;
}
view.dispatch({ selection: { anchor }, scrollIntoView: true });
view.focus();
}
function activate(cell: HTMLTableCellElement) {
if (active === cell) return;
finish();
active = cell;
firstEdit = true;
const row = (cell.parentElement as HTMLTableRowElement).rowIndex;
const column = cell.cellIndex;
const sourceRow = row === 0 ? 0 : row + 1;
const originalCell = parseMarkdownTable(controller.source)?.rows[sourceRow]?.cells[column];
// The nested editor owns browser focus, but the outer editor also needs to
// leave its previous active line so its Markdown markers render again.
view.dispatch({ selection: { anchor: view.posAtDOM(root) + (originalCell?.from ?? 0) }, userEvent: "select.table" });
let contentFrom = originalCell?.from, contentTo = originalCell?.to;
const formula = originalCell && (isTableFormula(originalCell.text) || /^\\=(?!=)/.test(originalCell.text)) ? originalCell.text : undefined;
const html = cell.innerHTML;
formulaStatus.textContent = `${cellAddress(row, column)} · Type = to calculate`;
cell.innerHTML = "";
cell.classList.add("is-editing");
editor = new Editor({
element: cell,
extensions: [
StarterKit.configure({ blockquote: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, codeBlock: false, heading: false, horizontalRule: false, link: false, underline: false, undoRedo: false, trailingNode: false, gapcursor: false, dropcursor: false }),
CellLink.configure({ openOnClick: false, autolink: false }),
CellImage.configure({ inline: true, allowBase64: true }),
Highlight, ...cellFormats,
],
content: formula ? { type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: formula }] }] } : html,
enableInputRules: false,
enablePasteRules: false,
editorProps: {
attributes: { class: "writer-cell-editor", role: "textbox", "aria-label": cell.getAttribute("aria-label")!, "aria-multiline": "true", spellcheck: "true" },
handleKeyDown(_editorView, event) {
if (event.isComposing) return false;
if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
// The nested editor owns cursor movement, including word movement
// and selections. Never let an arrow reach the prose editor.
event.stopPropagation();
// Native cursor movement can precede ProseMirror's selectionchange
// observer (especially during key repeat). Test the visible caret.
const native = document.getSelection();
if (native?.anchorNode && native.focusNode && _editorView.dom.contains(native.anchorNode) && _editorView.dom.contains(native.focusNode)) {
const anchor = _editorView.posAtDOM(native.anchorNode, native.anchorOffset);
const head = _editorView.posAtDOM(native.focusNode, native.focusOffset);
if (anchor !== _editorView.state.selection.anchor || head !== _editorView.state.selection.head) editor!.commands.setTextSelection({ from: anchor, to: head });
}
if (event.shiftKey || event.ctrlKey || event.metaKey || event.altKey || !_editorView.state.selection.empty) return false;
const direction = event.key === "ArrowLeft" ? "left" : event.key === "ArrowRight" ? "right" : event.key === "ArrowUp" ? "up" : "down";
const horizontal = direction === "left" || direction === "right";
const backwards = direction === "left" || direction === "up";
const { $head } = _editorView.state.selection;
// Pasted rich text can have several paragraphs within one cell.
if ($head.depth && (backwards ? $head.before(1) > 0 : $head.after(1) < _editorView.state.doc.content.size)) return false;
if (!_editorView.endOfTextblock(direction)) return false;
event.preventDefault();
const cells = [...table!.querySelectorAll<HTMLTableCellElement>("th, td")];
const next = horizontal
? cells[cells.indexOf(cell) + (backwards ? -1 : 1)]
: table!.rows[row + (backwards ? -1 : 1)]?.cells[column];
// Once there are no more cells in this direction, return to prose.
if (!next) { leave(!backwards); return true; }
const caret = _editorView.coordsAtPos(_editorView.state.selection.head);
activate(next);
const current = editor!;
let position = backwards ? current.state.doc.content.size - 1 : 1;
if (!horizontal) {
// Enter the closest position on the first/last visual line, even
// when either cell wraps or contains a hard break.
const edge = current.view.coordsAtPos(position);
position = current.view.posAtCoords({ left: caret.left, top: (edge.top + edge.bottom) / 2 })?.pos ?? position;
}
current.commands.setTextSelection(position);
current.view.focus();
next.scrollIntoView({ block: "nearest", inline: "nearest" });
return true;
}
// Keep formatting shortcuts local; the workbench also binds Ctrl+B.
if ((event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) event.stopPropagation();
if ((event.ctrlKey || event.metaKey) && (event.key === "Home" || event.key === "End")) {
event.preventDefault(); event.stopPropagation();
const position = event.key === "Home" ? 1 : editor!.state.doc.content.size - 1;
editor?.commands.setTextSelection(event.shiftKey ? { from: editor.state.selection.anchor, to: position } : position);
return true;
}
if ((event.ctrlKey || event.metaKey) && ["z", "y"].includes(event.key.toLowerCase())) {
event.preventDefault(); event.stopPropagation();
const from = view.posAtDOM(root);
(event.key.toLowerCase() === "y" || event.shiftKey ? redo : undo)(view);
requestAnimationFrame(() => {
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
(updated?.querySelector("table")?.rows[row]?.cells[column])?.focus();
});
return true;
}
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
if (event.key === "Enter") {
event.preventDefault();
if (isTableFormula(editor?.getText() || "")) { finish(); wrapper.focus(); }
else if (event.ctrlKey || event.metaKey) leave(true);
else editor?.commands.setHardBreak();
return true;
}
if (event.key === "Tab") {
event.preventDefault();
const cells = [...table!.querySelectorAll<HTMLTableCellElement>("th, td")];
const next = cells[cells.indexOf(cell) + (event.shiftKey ? -1 : 1)];
if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); }
else if (event.shiftKey) leave(false);
else add("row", true);
return true;
}
return false;
},
},
onUpdate({ editor: current }) {
const text = tableCellMarkdown(current.getJSON());
const source = controller.source;
// Track the full edited range, including typed spaces. Re-parsing the
// trimmed cell on each key would gradually turn those spaces into padding.
const insert = contentFrom === undefined || contentTo === undefined
? replaceTableCell(source, sourceRow, column, text)
: source.slice(0, contentFrom) + text + source.slice(contentTo);
contentFrom ??= parseMarkdownTable(insert)?.rows[sourceRow]?.cells[column]?.from;
if (contentFrom !== undefined) contentTo = contentFrom + text.length;
change(insert);
},
onBlur() {
// A toolbar click, another cell, or the prose editor can now take focus.
queueMicrotask(() => { if (active === cell && !cell.contains(document.activeElement) && !selectionControls?.keepEditing()) finish(); });
},
});
editor.commands.setTextSelection(editor.state.doc.content.size - 1); editor.view.focus();
refreshFormulas();
view.requestMeasure();
}
function add(kind: "row" | "column", focusNew = false) {
const from = view.posAtDOM(root);
finish();
const current = controller.source;
change(kind === "column" ? appendTableColumn(current) : appendTableRow(current), true);
view.focus();
requestAnimationFrame(() => {
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
if (!updated) return;
if (focusNew) updated.querySelector<HTMLTableCellElement>("tbody tr:last-child td")?.focus();
if (kind === "column") {
const viewport = updated.querySelector<HTMLElement>(".md-table-scroll")!;
viewport.scrollLeft = viewport.scrollWidth;
} else updated.querySelector(".table-add-row")?.scrollIntoView({ block: "nearest", inline: "nearest" });
view.requestMeasure();
});
}
const help = document.createElement("div");
help.className = "table-edit-help";
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
const footer = document.createElement("div");
footer.className = "table-footer";
const formulaTools = document.createElement("div");
formulaTools.className = "table-formula-tools";
const formulaHelp = document.createElement("details");
formulaHelp.className = "table-formula-help";
const summary = document.createElement("summary");
summary.append(actionIcon("math"), document.createTextNode("Formulas"));
summary.title = "How to calculate with table cells";
// Committing a wrapped formula can shrink its row. Keep the click target in
// place until mouseup, then finish editing and give keyboard focus to help.
summary.addEventListener("mousedown", event => { if (event.button === 0) { event.preventDefault(); event.stopPropagation(); } });
summary.addEventListener("click", () => { finish(); summary.focus(); });
const instructions = document.createElement("div");
instructions.className = "table-formula-instructions";
const intro = document.createElement("p");
intro.textContent = "Start a cell with =, then press Enter or Tab. Columns are A, B, C…; the header is row 1 and the first data row is 2.";
const examples = document.createElement("dl");
for (const [formula, description] of [
["=AVERAGE(B2,C2)", "Average two values: 9 and 10 give 9.5."],
["=AVERAGE(B2:C2)", "Average every cell in the range B2 through C2."],
["=SUM(B2:B10)", "Add the values in a range."],
["=(B2+C2)/2", "Add two values and divide by two."],
["=ROUND(B2/3,2)", "Round to two decimal places."],
]) {
const term = document.createElement("dt"), code = document.createElement("code"), descriptionElement = document.createElement("dd");
code.textContent = formula; term.append(code); descriptionElement.textContent = description;
examples.append(term, descriptionElement);
}
const functions = document.createElement("p");
functions.textContent = "Functions: SUM, AVERAGE, MIN, MAX, COUNT, ABS, ROUND. Operators: + − * / ^ and %. Use commas between function arguments; use a colon for a cell range.";
const references = document.createElement("p");
references.textContent = "References stay at their written addresses when copying, inserting, deleting, sorting, or moving cells. Code-formatted expressions are literal text; formulas must start with = outside code formatting.";
instructions.append(intro, examples, functions, references);
formulaHelp.append(summary, instructions);
formulaHelp.addEventListener("toggle", () => view.requestMeasure());
const formulaStatus = document.createElement("span");
formulaStatus.className = "table-formula-status";
formulaStatus.textContent = "Type = in a cell to calculate";
const formulaHint = document.createElement("div");
formulaHint.className = "table-formula-hint";
formulaHint.hidden = true;
formulaTools.append(formulaHelp, formulaStatus);
footer.append(help, formulaTools, formulaHint);
wrapper.after(footer);
for (const kind of ["column", "row"] as const) {
const button = document.createElement("button");
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;
button.setAttribute("aria-label", label);
const plus = document.createElement("span");
plus.append(actionIcon("plus"));
plus.setAttribute("aria-hidden", "true");
button.append(plus);
button.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); });
button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); add(kind); });
button.addEventListener("pointermove", event => {
const rect = button.getBoundingClientRect();
button.style.setProperty("--table-add-position", `${kind === "column" ? Math.max(12, Math.min(rect.height - 12, event.clientY - rect.top)) : Math.max(12, Math.min(rect.width - 12, event.clientX - rect.left))}px`);
});
wrapper.append(button);
}
for (const row of table.rows) for (const cell of row.cells) {
cell.tabIndex = 0;
cell.setAttribute("aria-label", `${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);
dragControls = tableDragControls(root, wrapper, table, scroll, view, () => controller.source, selectionControls.select, change);
table.addEventListener("mousedown", event => {
if (event.button !== 0) return;
if (event.ctrlKey || event.metaKey || !(event.target instanceof Element)) return;
const cell = event.target.closest<HTMLTableCellElement>("td, th");
if (!cell) return;
event.stopPropagation();
if (active !== cell) {
event.preventDefault(); activate(cell);
const hit = editor?.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) { editor?.commands.setTextSelection(hit.pos); editor?.view.focus(); }
}
});
refreshFormulas();
}
+226
View File
@@ -0,0 +1,226 @@
import type { EditorView } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
import { moveTableAxis, type TableAxis } from "./tableStructure";
import type { CellRange } from "./tableSelection";
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 layer = document.createElement("div");
layer.className = "table-drag-layer";
wrapper.append(layer);
const indicator = document.createElement("div");
indicator.className = "table-drop-indicator";
indicator.hidden = true;
layer.append(indicator);
let preview: HTMLElement | undefined, previewLabel: HTMLElement | undefined;
let drag: { axis: TableAxis; index: number; pointer: number; x: number; y: number; startX: number; startY: number; active: boolean; to?: number; before: string } | undefined;
let frame = 0, layoutFrame = 0;
function selectAxis(axis: TableAxis, index: number) {
select(axis === "row"
? { anchor: { row: index, column: 0 }, head: { row: index, column: table.rows[0].cells.length - 1 } }
: { anchor: { row: 0, column: index }, head: { row: table.rows.length - 1, column: index } });
}
function focusAxis(axis: TableAxis, index: number, keyboard = true) {
selectAxis(axis, index);
const button = handles.find(handle => handle.axis === axis && handle.index === index)?.button;
button?.toggleAttribute("data-pointer-focus", !keyboard);
button?.focus({ preventScroll: true });
}
controls.set(table, focusAxis);
function commit(axis: TableAxis, index: number, to: number, keyboard = true) {
const before = source(), after = moveTableAxis(before, axis, index, to);
if (before === after) return;
const from = view.posAtDOM(root), left = scroll.scrollLeft;
change(after, true);
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
const next = updated?.querySelector("table");
const viewport = updated?.querySelector<HTMLElement>(".md-table-scroll");
if (viewport) viewport.scrollLeft = left;
if (next) controls.get(next)?.(axis, to, keyboard);
}
function layout() {
layoutFrame = 0;
const origin = wrapper.getBoundingClientRect(), viewport = scroll.getBoundingClientRect();
for (const { axis, index, button } of handles) {
const rect = (axis === "row" ? table.rows[index] : table.rows[0].cells[index]).getBoundingClientRect();
const left = Math.max(viewport.left, rect.left), right = Math.min(viewport.right, rect.right);
button.hidden = axis === "column" && right <= left;
Object.assign(button.style, axis === "row"
? { left: `${viewport.left - origin.left - 26}px`, top: `${rect.top - origin.top}px`, width: "26px", height: `${rect.height}px` }
: { left: `${left - origin.left}px`, top: `${viewport.top - origin.top - 26}px`, width: `${Math.max(0, right - left)}px`, height: "26px" });
button.style.setProperty("--table-tooltip-left", `${axis === "row" ? 26 : viewport.left - left}px`);
button.style.setProperty("--table-tooltip-width", `${Math.min(260, viewport.width)}px`);
}
}
function scheduleLayout() { if (!layoutFrame) layoutFrame = requestAnimationFrame(layout); }
function createPreview() {
if (!drag) return;
preview = document.createElement("div");
preview.className = `reading table-drag-preview table-drag-preview-${drag.axis}`;
preview.setAttribute("aria-hidden", "true");
preview.inert = true;
previewLabel = document.createElement("div");
previewLabel.className = "table-drag-preview-label";
preview.append(previewLabel);
const content = document.createElement("div");
content.className = "table-drag-preview-content";
const copy = document.createElement("table");
const rows = drag.axis === "row" ? [table.rows[drag.index]] : [...table.rows];
const width = drag.axis === "row" ? table.getBoundingClientRect().width : table.rows[0].cells[drag.index].getBoundingClientRect().width;
preview.style.width = `${Math.min(width, drag.axis === "row" ? 560 : 280, window.innerWidth - 24)}px`;
copy.style.font = getComputedStyle(table).font;
for (const row of rows) {
const clonedRow = document.createElement("tr");
const cells = drag.axis === "row" ? [...row.cells] : [row.cells[drag.index]];
for (const cell of cells) {
const clonedCell = cell.cloneNode(true) as HTMLTableCellElement;
// A visual snapshot must not duplicate focusable controls, document IDs,
// or selection styling from the real cells.
for (const element of [clonedCell, ...clonedCell.querySelectorAll("*")]) {
for (const attribute of ["id", "tabindex", "contenteditable", "aria-selected", "aria-label", "data-selection-edges", "title"]) element.removeAttribute(attribute);
element.classList.remove("is-cell-selected", "is-editing");
}
clonedCell.style.width = `${cell.getBoundingClientRect().width / width * 100}%`;
clonedRow.append(clonedCell);
}
copy.append(clonedRow);
}
content.append(copy); preview.append(content); document.body.append(preview);
updatePreview();
}
function updatePreview() {
if (!preview || !previewLabel || !drag) return;
const valid = drag.to !== undefined;
preview.classList.toggle("is-invalid-drop", !valid);
previewLabel.textContent = `${drag.axis === "row" ? "Row" : "Column"} ${drag.index + 1}${valid ? ` → ${drag.to! + 1}` : " · Release to cancel"}`;
const rect = preview.getBoundingClientRect();
const x = Math.max(8, Math.min(drag.x + 16, window.innerWidth - rect.width - 8));
const y = Math.max(8, Math.min(drag.y + 16, window.innerHeight - rect.height - 8));
preview.style.transform = `translate3d(${x}px, ${y}px, 0)`;
}
function updateTarget() {
if (!drag?.active) return;
const { axis, x, y, index } = drag;
const viewport = scroll.getBoundingClientRect(), origin = wrapper.getBoundingClientRect();
drag.to = undefined;
indicator.hidden = true;
if (x < viewport.left - 32 || x > viewport.right + 32 || y < viewport.top - 32 || y > viewport.bottom + 32) return;
const items = axis === "row" ? [...table.rows].slice(1) : [...table.rows[0].cells];
if (!items.length) return;
const coordinate = axis === "row" ? y : x;
let boundary = items.findIndex(item => {
const rect = item.getBoundingClientRect();
return coordinate < (axis === "row" ? (rect.top + rect.bottom) / 2 : (rect.left + rect.right) / 2);
});
if (boundary < 0) boundary = items.length;
const insertion = boundary + (axis === "row" ? 1 : 0);
drag.to = insertion > index ? insertion - 1 : insertion;
if (drag.to === index) return;
const edge = (items[boundary] || items[items.length - 1]).getBoundingClientRect();
const position = axis === "row" ? (boundary === items.length ? edge.bottom : edge.top) : (boundary === items.length ? edge.right : edge.left);
if (axis === "column" && (position < viewport.left || position > viewport.right)) return;
indicator.hidden = false;
Object.assign(indicator.style, axis === "row"
? { left: `${viewport.left - origin.left}px`, top: `${position - origin.top - 2}px`, width: `${viewport.width}px`, height: "4px" }
: { left: `${position - origin.left - 2}px`, top: `${viewport.top - origin.top}px`, width: "4px", height: `${table.getBoundingClientRect().height}px` });
}
function tick() {
if (!drag?.active) return;
const viewport = scroll.getBoundingClientRect(), editor = view.scrollDOM.getBoundingClientRect();
const speed = (coordinate: number, start: number, end: number) => coordinate < start + 36 ? -Math.min(18, (start + 36 - coordinate) / 3) : coordinate > end - 36 ? Math.min(18, (coordinate - end + 36) / 3) : 0;
if (drag.x >= viewport.left - 32 && drag.x <= viewport.right + 32) {
if (drag.axis === "column") scroll.scrollLeft += speed(drag.x, viewport.left, viewport.right);
// Stop at the table's ends so an edge drag cannot scroll its own drop
// target out from under the pointer after the last row becomes visible.
const vertical = speed(drag.y, editor.top, editor.bottom);
view.scrollDOM.scrollTop += vertical > 0
? Math.min(vertical, Math.max(0, viewport.bottom - editor.bottom + 36))
: Math.max(vertical, Math.min(0, viewport.top - editor.top - 36));
}
layout(); updateTarget(); updatePreview();
frame = requestAnimationFrame(tick);
}
function cancel() {
const previous = drag;
drag = undefined;
cancelAnimationFrame(frame);
indicator.hidden = true;
preview?.remove(); preview = undefined; previewLabel = undefined;
wrapper.classList.remove("is-table-dragging");
if (previous) {
const button = handles.find(handle => handle.axis === previous.axis && handle.index === previous.index)?.button;
if (button?.hasPointerCapture(previous.pointer)) button.releasePointerCapture(previous.pointer);
}
}
for (const axis of ["column", "row"] as const) {
const length = axis === "row" ? table.rows.length : table.rows[0].cells.length;
for (let index = axis === "row" ? 1 : 0; index < length; index++) {
const button = document.createElement("button");
button.type = "button";
button.className = `table-drag-handle table-drag-${axis}`;
button.dataset.index = String(index);
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;
button.append(actionIcon("grip"));
layer.append(button);
handles.push({ axis, index, button });
button.addEventListener("pointerdown", event => {
if (event.button !== 0 || drag) return;
event.preventDefault(); event.stopPropagation();
focusAxis(axis, index, false);
drag = { axis, index, pointer: event.pointerId, x: event.clientX, y: event.clientY, startX: event.clientX, startY: event.clientY, active: false, before: source() };
button.setPointerCapture(event.pointerId);
}, options);
button.addEventListener("lostpointercapture", () => { if (drag) cancel(); }, options);
button.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); }, options);
button.addEventListener("blur", () => button.removeAttribute("data-pointer-focus"), options);
button.addEventListener("keydown", event => {
button.removeAttribute("data-pointer-focus");
const previous = axis === "row" ? "ArrowUp" : "ArrowLeft", next = axis === "row" ? "ArrowDown" : "ArrowRight";
if (![previous, next, " ", "Enter"].includes(event.key)) return;
event.preventDefault(); event.stopPropagation();
if (drag) return;
if (event.key === previous || event.key === next) commit(axis, index, index + (event.key === previous ? -1 : 1));
else focusAxis(axis, index);
}, options);
}
}
document.addEventListener("pointermove", event => {
if (!drag || event.pointerId !== drag.pointer) return;
drag.x = event.clientX; drag.y = event.clientY;
if (!drag.active && Math.hypot(drag.x - drag.startX, drag.y - drag.startY) >= 5) {
drag.active = true; wrapper.classList.add("is-table-dragging"); createPreview(); tick();
}
if (drag.active) { event.preventDefault(); updateTarget(); updatePreview(); }
}, { ...options, passive: false });
document.addEventListener("pointerup", event => {
if (!drag || event.pointerId !== drag.pointer) return;
drag.x = event.clientX; drag.y = event.clientY; updateTarget();
const completed = drag;
cancel();
if (completed.active && completed.to !== undefined && source() === completed.before) commit(completed.axis, completed.index, completed.to, false);
}, options);
document.addEventListener("pointercancel", cancel, options);
document.addEventListener("keydown", event => {
if (drag && event.key === "Escape") { event.preventDefault(); event.stopImmediatePropagation(); cancel(); }
}, { ...options, capture: true });
window.addEventListener("blur", cancel, options);
scroll.addEventListener("scroll", scheduleLayout, options);
const observer = new ResizeObserver(scheduleLayout);
observer.observe(table); observer.observe(scroll);
scheduleLayout();
return { destroy() { cancel(); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
}
+151
View File
@@ -0,0 +1,151 @@
// Formulas are plain Markdown cell text. No JavaScript evaluation or external data.
export const formulaErrors = {
"#ERROR!": "Invalid formula syntax or function arguments",
"#REF!": "Cell reference is outside this table",
"#VALUE!": "Expected a number",
"#NAME?": "Unknown function or cell name",
"#DIV/0!": "Cannot divide by zero or average an empty range",
"#CYCLE!": "Circular cell reference",
"#NUM!": "Result is not a finite number",
"#LIMIT!": "Formula is too complex",
} as const;
type ErrorCode = keyof typeof formulaErrors;
export type FormulaResult = { formula: string; text: string; value?: number; error?: ErrorCode };
class FormulaError extends Error {
code: ErrorCode;
constructor(code: ErrorCode) { super(formulaErrors[code]); this.code = code; }
}
function fail(code: ErrorCode): never { throw new FormulaError(code); }
export const isTableFormula = (text: string) => /^=(?!=)/.test(text.trim());
export function cellAddress(row: number, column: number): string {
let letters = "";
for (let n = column + 1; n > 0; n = Math.floor((n - 1) / 26)) letters = String.fromCharCode(65 + (n - 1) % 26) + letters;
return letters + (row + 1);
}
type Scalar = number | string | null;
type Value = Scalar | Scalar[];
const number = (value: Value): number => typeof value === "number" ? value : value === null ? 0 : fail("#VALUE!");
const finite = (value: number) => Number.isFinite(value) ? value : fail("#NUM!");
const numeric = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
// Header is row 1; the Markdown separator is not a spreadsheet row.
export function evaluateTableFormulas(grid: string[][]): (FormulaResult | null)[][] {
const cache = new Map<string, Scalar | FormulaError>();
const visiting = new Set<string>();
let budget = 50000;
const spend = () => { if (--budget < 0) fail("#LIMIT!"); };
function reference(address: string): [number, number] {
const match = /^\$?([A-Z]+)\$?([1-9]\d*)$/i.exec(address) || fail("#REF!");
let column = 0;
for (const letter of match[1].toUpperCase()) column = column * 26 + letter.charCodeAt(0) - 64;
const row = Number(match[2]);
if (row > grid.length || column > (grid[0]?.length || 0)) fail("#REF!");
return [row - 1, column - 1];
}
function cell(row: number, column: number): Scalar {
spend();
const key = `${row}:${column}`;
if (visiting.has(key)) fail("#CYCLE!");
if (visiting.size >= 128) fail("#LIMIT!");
const cached = cache.get(key);
if (cached instanceof FormulaError) throw cached;
if (cache.has(key)) return cached!;
const source = (grid[row]?.[column] || "").trim();
if (!isTableFormula(source)) return source === "" ? null : numeric.test(source) ? finite(Number(source)) : source;
visiting.add(key);
try {
const value = parse(source.slice(1));
cache.set(key, value);
return value;
} catch (error) {
const problem = error instanceof FormulaError ? error : new FormulaError("#LIMIT!");
cache.set(key, problem);
throw problem;
} finally { visiting.delete(key); }
}
function parse(source: string): number {
if (source.length > 2048) fail("#LIMIT!");
const tokens: string[] = [];
const pattern = /\s*(\$?[A-Za-z]+\$?\d+|[A-Za-z_]+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|[+\-*/^%(),:])/y;
let offset = 0;
while (offset < source.trimEnd().length) {
pattern.lastIndex = offset;
const match = pattern.exec(source) || fail("#ERROR!");
tokens.push(match[1]); offset = pattern.lastIndex;
}
let position = 0, depth = 0;
const peek = () => tokens[position];
const take = () => { spend(); return tokens[position++]; };
const expect = (token: string) => { if (take() !== token) fail("#ERROR!"); };
function expression(min = 0): Value {
if (++depth > 64) fail("#LIMIT!");
let left: Value;
const token = take();
if (token === "+" || token === "-") left = number(expression(3)) * (token === "-" ? -1 : 1);
else if (token === "(") { left = expression(); expect(")"); }
else if (token && numeric.test(token)) left = finite(Number(token));
else if (token && /^\$?[a-z]+\$?\d+$/i.test(token)) {
const [row, column] = reference(token);
if (peek() === ":") {
take(); const [endRow, endColumn] = reference(take() || "");
const values: Scalar[] = [];
for (let r = Math.min(row, endRow); r <= Math.max(row, endRow); r++) {
for (let c = Math.min(column, endColumn); c <= Math.max(column, endColumn); c++) values.push(cell(r, c));
}
left = values;
} else left = cell(row, column);
} else if (token && /^[a-z_]+$/i.test(token)) {
if (peek() !== "(") fail("#NAME?");
take(); const args: Value[] = [];
if (peek() !== ")") {
do { args.push(expression()); if (peek() !== ",") break; take(); } while (true);
}
expect(")");
left = call(token.toUpperCase(), args);
} else fail("#ERROR!");
while (true) {
const op = peek();
if (op === "%") { take(); left = number(left) / 100; continue; }
const precedence = op === "+" || op === "-" ? 1 : op === "*" || op === "/" ? 2 : op === "^" ? 3 : -1;
if (precedence < min) break;
take();
const right = number(expression(precedence + (op === "^" ? 0 : 1))), a = number(left);
left = finite(op === "+" ? a + right : op === "-" ? a - right : op === "*" ? a * right : op === "/" ? (right === 0 ? fail("#DIV/0!") : a / right) : a ** right);
}
depth--;
return left;
}
const result = finite(number(expression()));
if (position !== tokens.length) fail("#ERROR!");
return result;
}
function call(name: string, args: Value[]): number {
if (name === "ABS") return args.length === 1 ? Math.abs(number(args[0])) : fail("#ERROR!");
if (name === "ROUND") {
if (args.length < 1 || args.length > 2) fail("#ERROR!");
const value = number(args[0]), digits = args.length === 2 ? number(args[1]) : 0;
if (!Number.isInteger(digits) || Math.abs(digits) > 100) fail("#NUM!");
const factor = 10 ** digits, scaled = Math.abs(value) * factor;
return finite(Math.sign(value) * Math.round(scaled + Number.EPSILON * scaled) / factor);
}
if (!["SUM", "AVERAGE", "MIN", "MAX", "COUNT"].includes(name)) fail("#NAME?");
const values = args.flat().filter((value): value is number => typeof value === "number");
if (name === "COUNT") return values.length;
if (name === "MIN" || name === "MAX") return values.length ? values.reduce((a, b) => name === "MIN" ? Math.min(a, b) : Math.max(a, b)) : 0;
const sum = finite(values.reduce((a, b) => a + b, 0));
return name === "AVERAGE" ? (values.length ? sum / values.length : fail("#DIV/0!")) : sum;
}
return grid.map((row, r) => row.map((source, c) => {
if (!isTableFormula(source)) return null;
const formula = source.trim();
try {
const value = number(cell(r, c));
return { formula, value, text: String(Number(value.toPrecision(12))) };
} catch (error) {
const code = error instanceof FormulaError ? error.code : "#LIMIT!";
return { formula, text: code, error: code };
}
}));
}
+32
View File
@@ -0,0 +1,32 @@
import { Prec } from "@codemirror/state";
import { keymap } from "@codemirror/view";
import { tableEditors } from "./tableControls";
// Tables are atomic in the prose editor. Intercept a movement that would cross
// one before CodeMirror skips the widget, and hand focus to its cell editor.
export const tableNavigation = Prec.high(keymap.of(["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].map(key => ({
key,
run(view) {
const selection = view.state.selection.main;
if (!view.hasFocus || !selection.empty || view.state.selection.ranges.length !== 1) return false;
const forward = key === "ArrowRight" || key === "ArrowDown";
const vertical = key === "ArrowUp" || key === "ArrowDown";
const next = vertical ? view.moveVertically(selection, forward) : view.moveByChar(selection, forward);
const previews = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")];
if (!forward) previews.reverse();
for (const root of previews) {
const table = tableEditors.get(root);
if (!table) continue;
const from = view.posAtDOM(root), to = from + table.source.length;
const crosses = forward
? selection.head <= from && next.head >= from
: selection.head >= to && next.head <= to;
if (!crosses) continue;
const goal = selection.goalColumn ?? next.goalColumn;
const x = goal === undefined ? view.coordsAtPos(selection.head)?.left : view.contentDOM.getBoundingClientRect().left + goal;
table.enter(forward, vertical ? x : undefined);
return true;
}
return false;
},
}))));
+119
View File
@@ -0,0 +1,119 @@
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable.ts";
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
export type CellPoint = { row: number; column: number };
export type CellRange = { anchor: CellPoint; head: CellPoint };
export type CellFormat = "bold" | "italic" | "strike" | "highlight" | "code" | "math" | "comment" | "clear";
export function bounds(range: CellRange) {
return { top: Math.min(range.anchor.row, range.head.row), bottom: Math.max(range.anchor.row, range.head.row), left: Math.min(range.anchor.column, range.head.column), right: Math.max(range.anchor.column, range.head.column) };
}
const sourceRow = (row: number) => row === 0 ? 0 : row + 1;
export function mapTableCells(source: string, range: CellRange, transform: (text: string) => string): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const { top, bottom, left, right } = bounds(range);
for (let r = Math.max(0, top); r <= Math.min(bottom, table.rows.length - 2); r++) {
for (let c = Math.max(0, left); c <= Math.min(right, table.columns - 1); c++) {
source = replaceTableCell(source, sourceRow(r), c, transform(table.rows[sourceRow(r)].cells[c]?.text || ""));
}
}
return source;
}
export function formatTableCells(source: string, range: CellRange, format: CellFormat): string {
if (format === "clear") return mapTableCells(source, range, plainInlineMarkdown);
const marker = { bold: "**", italic: "*", strike: "~~", highlight: "==", code: "`", math: "$", comment: "%%" }[format];
const wrapped = (text: string) => format === "code" ? /^(`+)(?!`)([\s\S]*[^`])\1(?!`)$/.test(text)
: text.startsWith(marker) && text.endsWith(marker) && text.length > marker.length * 2 && !(format === "italic" && text.startsWith("**") && !text.startsWith("***"));
let allWrapped = true;
mapTableCells(source, range, text => { if (text.trim() && !wrapped(text)) allWrapped = false; return text; });
return mapTableCells(source, range, text => {
if (!text.trim()) return text;
if (wrapped(text)) return allWrapped ? (format === "code" ? plainInlineMarkdown(text) : text.slice(marker.length, -marker.length)) : text;
if (format === "code") {
const fence = "`".repeat(Math.max(0, ...[...text.matchAll(/`+/g)].map(m => m[0].length)) + 1);
return `${fence} ${text} ${fence}`;
}
return marker + text + marker;
});
}
export function alignTableCells(source: string, range: CellRange, alignment: "left" | "center" | "right"): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const { left, right } = bounds(range);
const marker = { left: ":---", center: ":---:", right: "---:" }[alignment];
for (let c = Math.min(right, table.columns - 1); c >= Math.max(0, left); c--) {
const cell = table.rows[1].cells[c];
source = source.slice(0, cell.from) + marker + source.slice(cell.to);
}
return source;
}
export function copyTableCells(source: string, range: CellRange): string {
const table = parseMarkdownTable(source);
if (!table) return "";
const { top, bottom, left, right } = bounds(range);
const quote = (value: string) => /[\t\r\n"]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value;
return Array.from({ length: bottom - top + 1 }, (_, r) => Array.from({ length: right - left + 1 }, (_, c) => quote(table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "")).join("\t")).join("\n");
}
// Parse quoted spreadsheet TSV, including embedded tabs/newlines, or a Markdown table.
export function clipboardCells(text: string): string[][] {
const table = parseMarkdownTable(text);
if (table) return table.rows.filter((_, i) => i !== 1).map(row => row.cells.map(cell => cell.text));
const rows: string[][] = [[]];
let cell = "", quoted = false;
text = text.replace(/\r\n?/g, "\n").replace(/\n$/, "");
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (char === '"' && (quoted || !cell)) {
if (quoted && text[i + 1] === '"') { cell += '"'; i++; }
else quoted = !quoted;
} else if (!quoted && (char === "\t" || char === "\n")) {
rows.at(-1)!.push(cell); cell = "";
if (char === "\n") rows.push([]);
} else cell += char;
}
rows.at(-1)!.push(cell);
return rows.map(row => row.map(value => value.replace(/\n/g, "<br>").replace(/(\\*)\|/g, (match, slashes: string) => slashes.length % 2 ? match : `${slashes}\\|`)));
}
export function pasteTableCells(source: string, range: CellRange, text: string): string {
if (!parseMarkdownTable(source)) return source;
const cells = clipboardCells(text), { top, bottom, left, right } = bounds(range);
if (cells.length === 1 && cells[0].length === 1) return mapTableCells(source, range, () => cells[0][0]);
const gridWidth = Math.max(...cells.map(row => row.length));
const height = Math.max(bottom - top + 1, cells.length), width = Math.max(right - left + 1, gridWidth);
while (parseMarkdownTable(source)!.columns < left + width) source = appendTableColumn(source);
while (parseMarkdownTable(source)!.rows.length - 1 < top + height) source = appendTableRow(source);
for (let r = 0; r < height; r++) for (let c = 0; c < width; c++) {
source = replaceTableCell(source, sourceRow(top + r), left + c, cells[r % cells.length][c % gridWidth] ?? "");
}
return source;
}
// Whole rows/columns are removed structurally; a partial rectangle shifts cells left.
export function deleteTableCells(source: string, range: CellRange): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const { top, bottom, left, right } = bounds(range);
const allRows = top === 0 && bottom >= table.rows.length - 2;
const allColumns = left === 0 && right >= table.columns - 1;
if (allRows && allColumns) return source.slice(table.end);
const rows = table.rows.flatMap((row, i) => {
const r = i === 0 ? 0 : i - 1;
if (allColumns && i !== 1 && r >= top && r <= bottom) return [];
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || "");
if (allRows || (i !== 1 && r >= top && r <= bottom)) {
cells.splice(left, right - left + 1);
if (!allRows) while (cells.length < table.columns) cells.push("");
}
return [{ ...row, cells }];
});
// Deleting the header promotes the first remaining body row.
if (allColumns && top === 0) [rows[0], rows[1]] = [rows[1], rows[0]];
return rows.map(row => `${row.indent}| ${row.cells.join(" | ")} |`).join(table.eol) + source.slice(table.end);
}
+225
View File
@@ -0,0 +1,225 @@
import type { EditorView } from "@codemirror/view";
import { undo, redo, isolateHistory } from "@codemirror/commands";
import type { Editor } from "@tiptap/core";
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
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) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
let range: CellRange | undefined, down: CellPoint | undefined, dragging = false;
let menu: HTMLElement | undefined;
let pending = false;
wrapper.tabIndex = -1;
wrapper.contentEditable = "false";
const point = (cell: HTMLTableCellElement): CellPoint => ({ row: (cell.parentElement as HTMLTableRowElement).rowIndex, column: cell.cellIndex });
function cellAt(target: EventTarget | null) {
const cell = target instanceof Element ? target.closest<HTMLTableCellElement>("td, th") : null;
return cell?.closest("table") === table ? cell : null;
}
function closeMenu() { menu?.remove(); menu = undefined; }
function clear() {
range = undefined; closeMenu();
wrapper.classList.remove("has-cell-selection");
for (const cell of table.querySelectorAll("th, td")) { cell.classList.remove("is-cell-selected"); cell.removeAttribute("aria-selected"); cell.removeAttribute("data-selection-edges"); }
}
function select(next: CellRange) {
finish();
const clamp = (p: CellPoint) => ({ row: Math.max(0, Math.min(table.rows.length - 1, p.row)), column: Math.max(0, Math.min(table.rows[0].cells.length - 1, p.column)) });
range = { anchor: clamp(next.anchor), head: clamp(next.head) };
const { top, bottom, left, right } = bounds(range);
wrapper.classList.add("has-cell-selection");
for (const row of table.rows) for (const cell of row.cells) {
const selected = row.rowIndex >= top && row.rowIndex <= bottom && cell.cellIndex >= left && cell.cellIndex <= right;
cell.classList.toggle("is-cell-selected", selected);
cell.setAttribute("aria-selected", String(selected));
if (selected) cell.setAttribute("data-selection-edges", [
row.rowIndex === top && "top", row.rowIndex === bottom && "bottom",
cell.cellIndex === left && "left", cell.cellIndex === right && "right",
].filter(Boolean).join(" "));
else cell.removeAttribute("data-selection-edges");
}
document.getSelection()?.removeAllRanges();
wrapper.focus({ preventScroll: true });
}
selections.set(table, select);
function apply(transform: (text: string, selected: CellRange) => string, restore?: CellRange) {
if (!range) return;
const selected = range, from = view.posAtDOM(root);
closeMenu(); finish();
change(transform(source(), selected), true);
const updated = [...view.dom.querySelectorAll<HTMLElement>(".writer-preview")].find(el => view.posAtDOM(el) === from);
const nextTable = updated?.querySelector("table");
if (nextTable) selections.get(nextTable)?.(restore || selected);
else view.focus();
}
const clearCells = () => apply((text, selected) => mapTableCells(text, selected, () => ""));
const format = (kind: CellFormat) => apply((text, selected) => formatTableCells(text, selected, kind));
async function clipboard(action: "copy" | "cut" | "paste") {
if (!range) return;
const before = source(), selected = range;
closeMenu(); wrapper.focus({ preventScroll: true });
try {
if (action === "paste") {
const text = await navigator.clipboard.readText();
if (root.isConnected && source() === before && range === selected) apply((value, target) => pasteTableCells(value, target, text));
} else {
await navigator.clipboard.writeText(copyTableCells(before, selected));
if (action === "cut" && root.isConnected && source() === before && range === selected) clearCells();
}
} 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"}.`; }
}
}
function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) {
if (!at) return;
closeMenu();
const cellRange = { anchor: at, head: at };
const returnFocus = () => { closeMenu(); if (textEditor && !textEditor.isDestroyed) textEditor.view.focus(); else wrapper.focus(); };
function structural(axis: TableAxis, operation: TableOperation) {
range ??= cellRange;
const index = axis === "row" ? at!.row : at!.column;
const next = { ...at! };
if (operation === "previous") next[axis]--;
if (operation === "next" || operation === "after" || operation === "duplicate") next[axis]++;
apply(text => changeTableStructure(text, axis, index, operation), { anchor: next, head: next });
}
const row = at.row, column = at.column, lastRow = table.rows.length - 1, lastColumn = table.rows[0].cells.length - 1;
const sep: ActionMenuItem = { separator: true };
const align = (alignment: "left" | "center" | "right") => {
range ??= cellRange;
apply((text, selected) => alignTableCells(text, selected, alignment));
};
const alignmentItems: ActionMenuItem[] = [
{ label: "Align left", icon: "left", run: () => align("left") },
{ label: "Align centre", icon: "center", run: () => align("center") },
{ label: "Align right", icon: "right", run: () => align("right") },
].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"; }
};
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) : [
...(["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) })) },
...alignmentItems,
sep, { label: "Clear cells", icon: "clear", run: clearCells },
{ label: "Delete cells", icon: "trash", run: () => apply(deleteTableCells), title: "Remove selected rows/columns; otherwise shift cells left" },
];
items.push(sep,
{ label: "Row", icon: "row", children: [
{ label: "Add row above", icon: "row-before", disabled: row === 0, title: row === 0 ? "The first row is the Markdown header" : undefined, run: () => structural("row", "before") },
{ label: "Add row below", icon: "row-after", run: () => structural("row", "after") }, sep,
{ label: "Move row up", icon: "up", disabled: row <= 1, run: () => structural("row", "previous") },
{ label: "Move row down", icon: "down", disabled: row === 0 || row === lastRow, run: () => structural("row", "next") }, sep,
{ label: "Duplicate row", icon: "copy", run: () => structural("row", "duplicate") },
{ label: "Delete row", icon: "trash", run: () => structural("row", "delete") },
] },
{ label: "Column", icon: "column", children: [
{ label: "Add column to the left", icon: "column-before", run: () => structural("column", "before") },
{ label: "Add column to the right", icon: "column-after", run: () => structural("column", "after") }, sep,
{ label: "Move column left", icon: "move-left", disabled: column === 0, run: () => structural("column", "previous") },
{ label: "Move column right", icon: "move-right", disabled: column === lastColumn, run: () => structural("column", "next") }, sep,
...alignmentItems, sep,
{ label: "Duplicate column", icon: "copy", run: () => structural("column", "duplicate") },
{ label: "Delete column", icon: "trash", run: () => structural("column", "delete") },
] }, sep,
{ label: "Sort by column (A to Z)", icon: "sort-asc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column)); } },
{ label: "Sort by column (Z to A)", icon: "sort-desc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column, true)); } },
);
menu = actionMenu(x, y, items, returnFocus);
}
table.addEventListener("mousedown", event => {
const cell = cellAt(event.target);
if (cell && event.button === 2) { event.preventDefault(); return; }
if (!cell || event.button !== 0 || event.ctrlKey || event.metaKey) return;
closeMenu(); down = point(cell); dragging = false;
if (event.shiftKey) {
event.preventDefault(); event.stopImmediatePropagation();
const active = table.querySelector<HTMLTableCellElement>(".is-editing");
select({ anchor: range?.anchor || (active ? point(active) : down), head: down }); dragging = true;
} else clear();
}, { ...options, capture: true });
document.addEventListener("mousemove", event => {
if (!down || !(event.buttons & 1)) return;
const cell = cellAt(document.elementFromPoint(event.clientX, event.clientY));
if (!cell) return;
const head = point(cell);
if (dragging || head.row !== down.row || head.column !== down.column) {
event.preventDefault(); dragging = true;
select({ anchor: range?.anchor || down, head });
}
}, options);
document.addEventListener("mouseup", () => { down = undefined; }, options);
table.addEventListener("dragstart", event => event.preventDefault(), options);
table.addEventListener("focus", event => { if (range && cellAt(event.target)) clear(); }, { ...options, capture: true });
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;
event.preventDefault(); event.stopPropagation();
if (cell.classList.contains("is-cell-selected")) showMenu(event.clientX, event.clientY, point(cell));
else {
clear(); rich.activate(cell);
const current = rich.get();
// A context click can arrive before the browser's selectionchange event.
// Read the visible word selection before moving focus into the menu.
const native = document.getSelection();
if (current && native && !native.isCollapsed && native.anchorNode && native.focusNode && current.view.dom.contains(native.anchorNode) && current.view.dom.contains(native.focusNode)) {
current.commands.setTextSelection({ from: current.view.posAtDOM(native.anchorNode, native.anchorOffset), to: current.view.posAtDOM(native.focusNode, native.focusOffset) });
}
if (current?.state.selection.empty) {
const hit = current.view.posAtCoords({ left: event.clientX, top: event.clientY });
if (hit) current.commands.setTextSelection(hit.pos);
}
showMenu(event.clientX, event.clientY, point(cell), current);
}
}, options);
document.addEventListener("mousedown", event => { if (!wrapper.contains(event.target as Node) && !menu?.contains(event.target as Node)) { clear(); if (!pending) finish(); } }, options);
document.addEventListener("scroll", event => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }, { ...options, capture: true });
window.addEventListener("resize", closeMenu, options);
wrapper.addEventListener("keydown", event => {
if (!range) return;
const mod = event.ctrlKey || event.metaKey, key = event.key.toLowerCase();
const handled = ["Escape", "Delete", "Backspace", "Enter", "ContextMenu", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) || (event.shiftKey && event.key === "F10") || (mod && ["b", "i", "z", "y", "a"].includes(key));
if (!handled) return;
event.preventDefault(); event.stopPropagation();
if (mod && ["z", "y"].includes(key)) { closeMenu(); (key === "y" || event.shiftKey ? redo : undo)(view); view.focus(); }
else if (mod && key === "a") select({ anchor: { row: 0, column: 0 }, head: { row: table.rows.length - 1, column: table.rows[0].cells.length - 1 } });
else if (mod && ["b", "i"].includes(key)) format(key === "b" ? "bold" : "italic");
else if (event.key === "Escape") { clear(); view.focus(); }
else if (event.key === "Delete" || event.key === "Backspace") clearCells();
else if (event.key === "Enter") { const target = table.rows[range.head.row].cells[range.head.column]; clear(); target.focus(); }
else if (event.key === "ContextMenu" || event.key === "F10") { const rect = table.rows[range.head.row].cells[range.head.column].getBoundingClientRect(); showMenu(rect.left, rect.bottom); }
else {
const head = { ...range.head };
if (event.key === "ArrowLeft") head.column--; if (event.key === "ArrowRight") head.column++;
if (event.key === "ArrowUp") head.row--; if (event.key === "ArrowDown") head.row++;
select({ anchor: event.shiftKey ? range.anchor : head, head });
table.rows[range!.head.row].cells[range!.head.column].scrollIntoView({ block: "nearest", inline: "nearest" });
}
}, options);
for (const action of ["copy", "cut", "paste"] as const) wrapper.addEventListener(action, event => {
if (!range || !event.clipboardData) return;
if (action === "paste" && !event.clipboardData.types.includes("text/plain")) return;
event.preventDefault(); event.stopPropagation();
if (action === "paste") apply((text, selected) => pasteTableCells(text, selected, event.clipboardData!.getData("text/plain")));
else { event.clipboardData.setData("text/plain", copyTableCells(source(), range)); if (action === "cut") clearCells(); }
}, { ...options, capture: true });
// Spreadsheet data pasted while editing one cell becomes a grid operation.
wrapper.addEventListener("paste", event => {
if (range) return;
const text = event.clipboardData?.getData("text/plain") || "";
const cell = cellAt(event.target);
if (!cell || !text.includes("\t")) return;
event.preventDefault(); event.stopPropagation(); select({ anchor: point(cell), head: point(cell) });
apply((value, selected) => pasteTableCells(value, selected, text));
}, { ...options, capture: true });
return { select, keepEditing: () => !!menu || pending, destroy: () => { lifecycle.abort(); closeMenu(); selections.delete(table); } };
}
+69
View File
@@ -0,0 +1,69 @@
import { parseMarkdownTable } from "./markdownTable.ts";
import { deleteTableCells } from "./tableSelection.ts";
import { plainInlineMarkdown } from "../workspace/noteHtml.ts";
export type TableAxis = "row" | "column";
export type TableOperation = "before" | "after" | "previous" | "next" | "duplicate" | "delete";
// Indices refer to rendered rows (header = 0), or columns. `to` is the
// final position, after removing the source item.
export function moveTableAxis(source: string, axis: TableAxis, from: number, to: number): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const size = axis === "row" ? table.rows.length - 1 : table.columns;
const first = axis === "row" ? 1 : 0;
if (![from, to].every(index => Number.isInteger(index) && index >= first && index < size) || from === to) return source;
function move<T>(items: T[], start: number, end: number) {
items.splice(end, 0, items.splice(start, 1)[0]);
return items;
}
const rows = axis === "row"
? move(table.rows.map(row => source.slice(row.from, row.to)), from + 1, to + 1)
: table.rows.map(row => {
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, i) => row.cells[i]?.text || "");
return `${row.indent}| ${move(cells, from, to).join(" | ")} |`;
});
return rows.join(table.eol) + source.slice(table.end);
}
export function changeTableStructure(source: string, axis: TableAxis, index: number, operation: TableOperation): string {
const table = parseMarkdownTable(source);
if (!table) return source;
const size = axis === "row" ? table.rows.length - 1 : table.columns;
if (index < 0 || index >= size) return source;
if (operation === "delete") return deleteTableCells(source, axis === "row"
? { anchor: { row: index, column: 0 }, head: { row: index, column: table.columns - 1 } }
: { anchor: { row: 0, column: index }, head: { row: table.rows.length - 2, column: index } });
const moving = operation === "previous" || operation === "next";
const other = index + (operation === "previous" ? -1 : 1);
// The Markdown header stays a header; row movement and sorting affect the body.
if (moving && (other < (axis === "row" ? 1 : 0) || other >= size || (axis === "row" && index === 0))) return source;
if (axis === "row") {
if (index === 0 && operation === "before") return source;
const rows = table.rows.map(row => source.slice(row.from, row.to));
const at = index === 0 ? 0 : index + 1;
if (moving) [rows[at], rows[other + 1]] = [rows[other + 1], rows[at]];
else {
const value = operation === "duplicate" ? rows[at] : `${table.rows[0].indent}| ${Array(table.columns).fill("").join(" | ")} |`;
rows.splice(index === 0 ? 2 : at + (operation === "before" ? 0 : 1), 0, value);
}
return rows.join(table.eol) + source.slice(table.end);
}
const rows = table.rows.map((row, r) => {
const cells = Array.from({ length: Math.max(table.columns, row.cells.length) }, (_, c) => row.cells[c]?.text || "");
if (moving) [cells[index], cells[other]] = [cells[other], cells[index]];
else cells.splice(index + (operation === "before" ? 0 : 1), 0, operation === "duplicate" ? cells[index] : r === 1 ? "---" : "");
return `${row.indent}| ${cells.join(" | ")} |`;
});
return rows.join(table.eol) + source.slice(table.end);
}
export function sortTableColumn(source: string, column: number, descending = false): string {
const table = parseMarkdownTable(source);
if (!table || column < 0 || column >= table.columns) return source;
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
const key = (text: string) => plainInlineMarkdown(text).replace(/<br>/g, " ").replace(/\\([\\`*_[\]~<>!|=$%])/g, "$1").trim();
const rows = table.rows.slice(2).map(row => ({ row, key: key(row.cells[column]?.text || "") }));
rows.sort((a, b) => !a.key ? (b.key ? 1 : 0) : !b.key ? -1 : collator.compare(a.key, b.key) * (descending ? -1 : 1));
return [...table.rows.slice(0, 2), ...rows.map(item => item.row)].map(row => source.slice(row.from, row.to)).join(table.eol) + source.slice(table.end);
}
+26
View File
@@ -0,0 +1,26 @@
import { isImagePath } from "../workspace/media";
type Point = { x: number; y: number };
const targets = new Map<HTMLElement, (path: string, point: Point) => void>();
let highlighted: HTMLElement | undefined;
export function registerImageDropTarget(element: HTMLElement, drop: (path: string, point: Point) => void) {
targets.set(element, drop);
return () => { targets.delete(element); element.classList.remove("image-drop-target"); };
}
function targetAt(path: string, point: Point) {
if (!isImagePath(path)) return;
const hit = document.elementFromPoint(point.x, point.y);
return [...targets].find(([element]) => element.isConnected && hit && element.contains(hit));
}
export function highlightImageDrop(path?: string, point?: Point): boolean {
highlighted?.classList.remove("image-drop-target");
highlighted = path && point ? targetAt(path, point)?.[0] : undefined;
highlighted?.classList.add("image-drop-target");
return !!highlighted;
}
export function dropWorkspaceImage(path: string, point: Point): boolean {
const target = targetAt(path, point);
highlightImageDrop();
target?.[1](path, point);
return !!target;
}
+21
View File
@@ -0,0 +1,21 @@
import { Mark } from "@tiptap/core";
export const MathMark = Mark.create({
name: "math",
parseHTML() {
return [{ tag: "span[data-math]" }];
},
renderHTML() {
return ["span", { "data-math": "1", class: "md-math" }, 0];
},
});
export const CommentMark = Mark.create({
name: "comment",
parseHTML() {
return [{ tag: "span[data-comment]" }];
},
renderHTML() {
return ["span", { "data-comment": "1", class: "md-comment" }, 0];
},
});
+143
View File
@@ -0,0 +1,143 @@
import type { Editor } from "@tiptap/core";
import type { MenuItem } from "../layout/menuTypes";
function selectedText(editor: Editor): string {
const { from, to } = editor.state.selection;
return editor.state.doc.textBetween(from, to, "\n");
}
async function writeClipboard(text: string): Promise<boolean> {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
return false;
}
}
export async function cutSelection(editor: Editor): Promise<void> {
const text = selectedText(editor);
if (text && !(await writeClipboard(text))) {
return;
}
editor.chain().focus().deleteSelection().run();
}
export async function copySelection(editor: Editor): Promise<void> {
const text = selectedText(editor);
if (text) {
await writeClipboard(text);
}
}
export async function pasteClipboard(editor: Editor): Promise<void> {
let text = "";
try {
text = await navigator.clipboard.readText();
} catch {
return;
}
if (!text) {
return;
}
editor.chain().focus().run();
editor.view.dispatch(editor.state.tr.insertText(text));
}
export function writerContextItems(editor: Editor): MenuItem[] {
const inTable = editor.isActive("table");
return [
{ kind: "action", label: "Cut", run: () => void cutSelection(editor) },
{ kind: "action", label: "Copy", run: () => void copySelection(editor) },
{ kind: "action", label: "Paste", run: () => void pasteClipboard(editor) },
{ kind: "sep" },
{
kind: "group",
label: "Style",
items: [
{ kind: "action", label: "Heading 1", run: () => editor.chain().focus().toggleHeading({ level: 1 }).run() },
{ kind: "action", label: "Heading 2", run: () => editor.chain().focus().toggleHeading({ level: 2 }).run() },
{ kind: "action", label: "Heading 3", run: () => editor.chain().focus().toggleHeading({ level: 3 }).run() },
{ kind: "action", label: "Heading 4", run: () => editor.chain().focus().toggleHeading({ level: 4 }).run() },
{ kind: "action", label: "Heading 5", run: () => editor.chain().focus().toggleHeading({ level: 5 }).run() },
{ kind: "action", label: "Heading 6", run: () => editor.chain().focus().toggleHeading({ level: 6 }).run() },
{ kind: "action", label: "Body", run: () => editor.chain().focus().setParagraph().run() },
{ kind: "action", label: "Quote", run: () => editor.chain().focus().toggleBlockquote().run() },
{ kind: "sep" },
{ kind: "action", label: "Bullet list", run: () => editor.chain().focus().toggleBulletList().run() },
{ kind: "action", label: "Numbered list", run: () => editor.chain().focus().toggleOrderedList().run() },
{ kind: "action", label: "Task list", run: () => editor.chain().focus().toggleTaskList().run() },
],
},
{
kind: "group",
label: "Format",
items: [
{ kind: "action", label: "Bold", run: () => editor.chain().focus().toggleBold().run() },
{ kind: "action", label: "Italic", run: () => editor.chain().focus().toggleItalic().run() },
{ kind: "action", label: "Strikethrough", run: () => editor.chain().focus().toggleStrike().run() },
{ kind: "action", label: "Highlight", run: () => editor.chain().focus().toggleHighlight().run() },
{ kind: "action", label: "Code", run: () => editor.chain().focus().toggleCode().run() },
{ kind: "action", label: "Math", run: () => editor.chain().focus().toggleMark("math").run() },
{ kind: "action", label: "Comment", run: () => editor.chain().focus().toggleMark("comment").run() },
{ kind: "sep" },
{ kind: "action", label: "Clear formatting", run: () => editor.chain().focus().unsetAllMarks().run() },
],
},
{
kind: "group",
label: "Table",
items: [
{
kind: "action",
label: "Insert table",
run: () => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
},
{ kind: "sep" },
{
kind: "action",
label: "Add row above",
disabled: !inTable,
run: () => editor.chain().focus().addRowBefore().run(),
},
{
kind: "action",
label: "Add row below",
disabled: !inTable,
run: () => editor.chain().focus().addRowAfter().run(),
},
{
kind: "action",
label: "Delete row",
disabled: !inTable,
run: () => editor.chain().focus().deleteRow().run(),
},
{ kind: "sep" },
{
kind: "action",
label: "Add column left",
disabled: !inTable,
run: () => editor.chain().focus().addColumnBefore().run(),
},
{
kind: "action",
label: "Add column right",
disabled: !inTable,
run: () => editor.chain().focus().addColumnAfter().run(),
},
{
kind: "action",
label: "Delete column",
disabled: !inTable,
run: () => editor.chain().focus().deleteColumn().run(),
},
{
kind: "action",
label: "Delete table",
disabled: !inTable,
run: () => editor.chain().focus().deleteTable().run(),
},
],
},
];
}
+90
View File
@@ -0,0 +1,90 @@
<script lang="ts">
import { loadMarks } from "$lib/workspace/marks";
import type { TreeEntry } from "$lib/workspace/types";
type Props = {
refreshToken: number;
onOpen: (entry: TreeEntry) => void;
};
let { refreshToken, onOpen }: Props = $props();
let bookmarks = $state<string[]>([]);
$effect(() => {
void refreshToken;
void loadMarks().then((marks) => {
bookmarks = marks.bookmarks;
});
});
</script>
<div class="pane">
<div class="pane-label">Bookmarks</div>
{#if bookmarks.length === 0}
<p class="placeholder">Right-click a file and choose Bookmark.</p>
{:else}
<ul>
{#each bookmarks as rel (rel)}
<li>
<button
type="button"
onclick={() =>
onOpen({
name: rel.split("/").pop() ?? rel,
rel_path: rel,
kind: "file",
})}
>
{rel}
</button>
</li>
{/each}
</ul>
{/if}
</div>
<style>
.pane {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.pane-label {
padding: 6px 10px;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--rs-text-dim);
border-bottom: 1px solid var(--rs-border);
text-align: center;
}
.placeholder {
margin: 12px;
color: var(--rs-text-dim);
}
ul {
list-style: none;
margin: 0;
padding: 6px 0;
overflow: auto;
}
button {
width: 100%;
border-radius: var(--rs-control-radius);
border: 0;
background: transparent;
color: var(--rs-text);
text-align: left;
padding: 6px 10px;
}
button:hover {
background: var(--rs-bg-active);
color: var(--rs-text-strong);
}
</style>
+167
View File
@@ -0,0 +1,167 @@
<script lang="ts">
import type { MenuAction, MenuItem } from "./menuTypes";
type Props = {
x: number;
y: number;
items: MenuItem[];
onClose: () => void;
};
let { x, y, items, onClose }: Props = $props();
let root: HTMLElement | undefined = $state();
let left = $state(0);
let top = $state(0);
$effect(() => {
left = x;
top = y;
void items;
queueMicrotask(() => {
if (!root) {
return;
}
const rect = root.getBoundingClientRect();
left = Math.min(x, window.innerWidth - rect.width - 8);
top = Math.min(y, window.innerHeight - rect.height - 8);
});
});
function onWindowDown(event: MouseEvent) {
if (root && !root.contains(event.target as Node)) {
onClose();
}
}
function onKey(event: KeyboardEvent) {
if (event.key === "Escape") {
onClose();
}
}
function runAction(item: MenuAction) {
if (item.disabled) {
return;
}
item.run();
onClose();
}
</script>
<svelte:window onmousedown={onWindowDown} onkeydown={onKey} />
<div
bind:this={root}
class="menu"
style:left="{left}px"
style:top="{top}px"
role="menu"
>
{#each items as item, i (i)}
{#if item.kind === "sep"}
<div class="sep"></div>
{:else if item.kind === "group"}
<div class="group">
<div class="group-label" role="none">{item.label}</div>
<div class="flyout" role="menu">
{#each item.items as sub, j (`${i}-${j}`)}
{#if sub.kind === "sep"}
<div class="sep"></div>
{:else if sub.kind === "action"}
<button
type="button"
role="menuitem"
disabled={sub.disabled}
onclick={() => runAction(sub)}
>
{sub.label}
</button>
{/if}
{/each}
</div>
</div>
{:else}
<button
type="button"
role="menuitem"
disabled={item.disabled}
onclick={() => runAction(item)}
>
{item.label}
</button>
{/if}
{/each}
</div>
<style>
.menu,
.flyout {
min-width: 200px;
padding: 4px 0;
background: var(--rs-bg-elevated);
border: 1px solid var(--rs-border);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
}
.menu {
position: fixed;
z-index: 40;
}
.group {
position: relative;
}
.group-label {
padding: 6px 12px;
color: var(--rs-text);
cursor: default;
}
.group-label::after {
content: "▸";
float: right;
color: var(--rs-text-dim);
}
.flyout {
display: none;
position: absolute;
left: 100%;
top: 0;
z-index: 41;
}
.group:hover > .flyout,
.group:focus-within > .flyout {
display: block;
}
button {
display: block;
width: 100%;
border: 0;
background: transparent;
color: var(--rs-text-strong);
text-align: left;
padding: 6px 12px;
}
button:hover,
button:focus-visible {
background: var(--rs-bg-active);
outline: none;
}
button:disabled {
color: var(--rs-text-dim);
opacity: 0.55;
}
.sep {
height: 1px;
margin: 4px 0;
background: var(--rs-border);
}
</style>
+228
View File
@@ -0,0 +1,228 @@
<script lang="ts">
import EditorHost from "$lib/editor/EditorHost.svelte";
import LiveWriter from "$lib/editor/LiveWriter.svelte";
import { onDestroy, tick } from "svelte";
import { retainEditorSessions } from "$lib/editor/sessions";
import ImageViewer from "./ImageViewer.svelte";
import MarkdownView from "./MarkdownView.svelte";
import ModeSwitcher from "$lib/ui/ModeSwitcher.svelte";
import Icon from "$lib/ui/Icon.svelte";
import { isMarkdownPath } from "$lib/workspace/media";
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import type { TableContextActions } from "$lib/editor/tableCellActions";
type Props = {
buffer: OpenBuffer | null;
tabs: OpenBuffer[];
chrome: Chrome;
reading: boolean;
focusLine: number | null;
onChange: (value: string, id: string) => void;
onRenameTitle?: (id: string, title: string) => Promise<void>;
onInsertImage?: (file: File) => Promise<string | null>;
onToggleReading?: () => void;
onToggleChrome?: () => void;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onOpenWorkspace: () => void;
onNewFile: () => void;
onQuickOpen: () => void;
hasWorkspace: boolean;
tableActions?: TableContextActions;
};
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, hasWorkspace, tableActions }: Props = $props();
let previewMode = $state<"split" | "preview">("split");
let modeControls = $state<HTMLDivElement>();
const shouldFocusOnMount = () => !modeControls?.contains(document.activeElement);
const previewScroll = new Map<string, { top: number; left: number }>();
$effect(() => {
const ids = tabs.map(tab => tab.id);
retainEditorSessions(ids);
for (const id of previewScroll.keys()) if (!ids.includes(id)) previewScroll.delete(id);
});
onDestroy(() => retainEditorSessions([]));
function rememberPreviewScroll(node: HTMLDivElement, id: string) {
const saved = previewScroll.get(id);
let cancelled = false;
let restoring = true;
let frame = 0;
const save = () => {
if (!restoring) previewScroll.set(id, { top: node.scrollTop, left: node.scrollLeft });
};
node.addEventListener("scroll", save);
// Markdown renders in an effect; wait for its DOM before restoring offsets.
void tick().then(() => {
if (cancelled) return;
frame = requestAnimationFrame(() => {
node.scrollTop = saved?.top ?? 0;
node.scrollLeft = saved?.left ?? 0;
restoring = false;
});
});
return { destroy() {
cancelled = true;
cancelAnimationFrame(frame);
node.removeEventListener("scroll", save);
} };
}
const isIde = $derived(chrome === "Ide");
const isImage = $derived(buffer?.kind === "image");
const canPreview = $derived(buffer !== null && buffer.kind === "text" && isMarkdownPath(buffer.relPath));
const documentMode = $derived(!reading ? "edit" : previewMode === "preview" ? "read" : "split");
function setDocumentMode(mode: string) {
if (mode !== "edit") previewMode = mode === "read" ? "preview" : "split";
if (reading !== (mode !== "edit")) onToggleReading?.();
}
</script>
{#if !buffer || buffer.kind === "empty"}
<div class="empty">
<h1>{buffer?.kind === "empty" ? "New tab" : "One project. Notes, code, terminal."}</h1>
<p>{hasWorkspace ? "Open a file to get started, or create a note or script." : "Open a folder to work with your own files."}</p>
<div class="welcome-actions">
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
{#if hasWorkspace}
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button>
<button onclick={onQuickOpen}><Icon icon="search" /> Find a file <kbd>Ctrl P</kbd></button>
{/if}
</div>
<p class="hint">Save · Ctrl S &nbsp; Terminal · Ctrl ` &nbsp; Find in file · Ctrl F</p>
</div>
{:else}
<div class="editor">
<div class="chrome-bar">
<span class="breadcrumb" title={buffer.relPath}>{buffer.relPath}</span>
<div class="actions" bind:this={modeControls}>
{#if canPreview}
<ModeSwitcher
label="Document view"
value={documentMode}
options={[
{ value: "edit", label: "Edit", icon: "pen" },
{ value: "read", label: "Read", icon: "book-open" },
{ value: "split", label: "Split", icon: "split" },
]}
onchange={setDocumentMode}
/>
{/if}
<ModeSwitcher
label="Editor layout"
value={chrome}
options={[
{ value: "Ide", label: "IDE", icon: "code" },
{ value: "Writing", label: "Writer", icon: "text" },
]}
shortcut=" (Ctrl E)"
onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }}
/>
</div>
</div>
<div class="body" class:split={reading && canPreview && previewMode === "split"}>
{#if isImage && buffer.imageUrl}
<ImageViewer src={buffer.imageUrl} name={buffer.name} />
{:else}
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
{#key buffer.id}
{#if !isIde && canPreview && !reading}
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} />
{:else}
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {focusLine} {tableActions} {shouldFocusOnMount} />
{/if}
{/key}
</div>
{#if reading && canPreview}
{#key buffer.id}
<div class="md-page" use:rememberPreviewScroll={buffer.id}>
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {onOpenLink} />
</div>
{/key}
{/if}
{/if}
</div>
</div>
{/if}
<style>
.breadcrumb { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-right: auto; }
.welcome-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; }
.welcome-actions button { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); padding: 10px 14px; }
kbd { margin-left: 12px; color: var(--rs-text-dim); font-size: 11px; }
h1 { color: var(--rs-text-strong); font-size: 24px; font-weight: 500; }
.hint { margin-top: 32px; font-size: 12px; }
.hidden { display: none; }
.split .md-page { border-left: 1px solid var(--rs-border); }
.editor { container-type: inline-size; }
.empty,
.editor {
height: 100%;
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
flex: 1;
}
.empty {
align-items: center;
justify-content: center;
color: var(--rs-text-dim);
padding: 24px;
text-align: center;
}
.chrome-bar {
display: flex;
align-items: center;
justify-content: flex-end;
gap: 8px;
height: 42px;
padding: 0 10px;
background: var(--rs-bg-elevated);
border-bottom: 1px solid var(--rs-border);
color: var(--rs-text-dim);
flex: 0 0 auto;
}
.actions {
display: flex;
align-items: center;
gap: 8px;
flex: 0 0 auto;
}
.body {
flex: 1;
display: flex;
min-height: 0;
min-width: 0;
}
.body > :global(*) {
flex: 1;
min-width: 0;
}
.md-page {
flex: 1;
min-height: 0;
overflow: auto;
padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 96px;
scrollbar-gutter: stable;
}
.editor-wrap {
flex: 1;
min-width: 0;
min-height: 0;
position: relative;
}
@container (max-width: 680px) {
.body.split { flex-direction: column; }
.md-page { padding: 28px 24px 64px; }
.split .md-page { border-left: 0; border-top: 1px solid var(--rs-border); }
}
</style>
+748
View File
@@ -0,0 +1,748 @@
<script lang="ts">
import { untrack } from "svelte";
import { confirm } from "@tauri-apps/plugin-dialog";
import { requestText } from "$lib/workspace/dialogs.svelte";
import type { TreeEntry } from "$lib/workspace/types";
import {
workspaceAbsPath,
workspaceCopy,
workspaceCreate,
workspaceDelete,
workspaceList,
workspaceRename,
workspaceReveal,
} from "$lib/workspace/api";
import { loadMarks, saveMarks, togglePath, type Marks } from "$lib/workspace/marks";
import {
dropHint,
dropPlaceAt,
joinRel,
parentRel,
planDrop,
uniqueName,
type DropPlace,
type DropTarget,
} from "$lib/workspace/treeDrop";
import { planRename } from "$lib/workspace/renamePath";
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type SelectionModifiers, type TreeSelection } from "$lib/workspace/treeSelection";
import ContextMenu from "./ContextMenu.svelte";
import type { MenuItem } from "./menuTypes";
import TreeNode from "./TreeNode.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { dropWorkspaceImage, highlightImageDrop } from "$lib/editor/workspaceImageDrop";
type Props = {
workspaceRoot: string;
activePath: string | null;
onOpenFile: (entry: TreeEntry, newTab?: boolean) => void;
refreshToken: number;
onStatus?: (message: string) => void;
onEntryGone?: (rel: string) => void;
onEntryRenamed?: (from: string, to: string) => void;
onCreated?: (entry: TreeEntry) => void;
keysActive?: boolean;
};
let {
workspaceRoot,
activePath,
onOpenFile,
refreshToken,
onStatus,
onEntryGone,
onEntryRenamed,
onCreated,
keysActive = true,
}: Props = $props();
let expanded = $state<Set<string>>(new Set([""]));
let childrenMap = $state<Record<string, TreeEntry[]>>({});
let loading = $state(false);
let error = $state<string | null>(null);
let marks = $state<Marks>({ pins: [], bookmarks: [], order: {} });
let menu = $state<{ x: number; y: number; entry: TreeEntry | null } | null>(null);
let sortMode = $state<"custom" | "name" | "name-desc">("custom");
let dragRel = $state<string | null>(null);
let dropTarget = $state<DropTarget | null>(null);
let dragPoint = $state<{ x: number; y: number } | null>(null);
let selection = $state<TreeSelection>({ paths: new Set(), anchor: null });
const visiblePaths = $derived(visibleTreePaths(childrenMap, expanded));
const selectionEdges = $derived(treeSelectionEdges(visiblePaths, selection.paths));
let renameRel = $state<string | null>(null);
let renameDraft = $state("");
let skipClick = false;
let imageLanding = $state(false);
let cancelDrag: (() => void) | undefined;
$effect(() => () => cancelDrag?.());
const pins = $derived(new Set(marks.pins));
const bookmarks = $derived(new Set(marks.bookmarks));
function sortEntries(parent: string, entries: TreeEntry[]): TreeEntry[] {
const pinSet = new Set(marks.pins);
const custom = marks.order[parent] ?? [];
return [...entries].sort((a, b) => {
const ap = pinSet.has(a.rel_path) ? 0 : 1;
const bp = pinSet.has(b.rel_path) ? 0 : 1;
if (ap !== bp) {
return ap - bp;
}
if (sortMode === "custom") {
const ai = custom.indexOf(a.name);
const bi = custom.indexOf(b.name);
if (ai !== -1 || bi !== -1) {
if (ai === -1) {
return 1;
}
if (bi === -1) {
return -1;
}
if (ai !== bi) {
return ai - bi;
}
}
}
if (a.kind !== b.kind) {
return a.kind === "folder" ? -1 : 1;
}
const byName = a.name.localeCompare(b.name, undefined, { sensitivity: "base" });
return sortMode === "name-desc" ? -byName : byName;
});
}
async function load(rel: string) {
loading = true;
try {
const entries = await workspaceList(rel);
childrenMap = { ...childrenMap, [rel]: sortEntries(rel, entries) };
error = null;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
} finally {
loading = false;
}
}
$effect(() => {
void workspaceRoot;
expanded = new Set([""]);
selection = { paths: new Set(), anchor: null };
childrenMap = {};
marks = { pins: [], bookmarks: [], order: {} };
void loadMarks().then((next) => {
marks = next;
});
void load("");
});
$effect(() => {
void refreshToken;
const keys = untrack(() => Object.keys(childrenMap));
for (const key of keys) {
void load(key);
}
});
$effect(() => {
void marks;
const current = untrack(() => childrenMap);
const next: Record<string, TreeEntry[]> = {};
for (const [key, list] of Object.entries(current)) {
next[key] = sortEntries(key, list);
}
childrenMap = next;
});
function toggleFolder(entry: TreeEntry) {
const next = new Set(expanded);
if (next.has(entry.rel_path)) {
next.delete(entry.rel_path);
} else {
next.add(entry.rel_path);
if (!childrenMap[entry.rel_path]) {
void load(entry.rel_path);
}
}
expanded = next;
}
// Drop selections that are no longer visible after collapsing, deleting or refreshing.
$effect(() => {
const visible = new Set(visiblePaths);
const current = untrack(() => selection);
const paths = new Set([...current.paths].filter((path) => visible.has(path)));
const anchor = current.anchor && visible.has(current.anchor) ? current.anchor : null;
if (paths.size !== current.paths.size || anchor !== current.anchor) selection = { paths, anchor };
});
function selectOnly(rel: string) {
selection = { paths: new Set([rel]), anchor: rel };
}
function onRowClick(entry: TreeEntry, modifiers: SelectionModifiers = {}, newTab = false) {
if (skipClick) {
skipClick = false;
return;
}
selection = selectTreePath(selection, entry.rel_path, visiblePaths, modifiers);
if (renameRel && renameRel !== entry.rel_path) {
void commitRename();
}
if (modifiers.ctrlKey || modifiers.metaKey || modifiers.shiftKey) return;
if (entry.kind === "folder") {
toggleFolder(entry);
return;
}
onOpenFile(entry, newTab);
}
function findEntry(rel: string): TreeEntry | null {
for (const list of Object.values(childrenMap)) {
const found = list.find((item) => item.rel_path === rel);
if (found) {
return found;
}
}
return null;
}
function readDropAt(clientX: number, clientY: number): DropTarget | null {
const hit = document.elementFromPoint(clientX, clientY)?.closest("[data-tree-rel]");
if (!(hit instanceof HTMLElement)) {
return null;
}
const rel = hit.dataset.treeRel;
if (!rel || rel === dragRel) {
return null;
}
const kind = hit.dataset.treeKind === "folder" ? "folder" : "file";
const rect = hit.getBoundingClientRect();
const yRatio = rect.height ? (clientY - rect.top) / rect.height : 0.5;
return { rel, place: dropPlaceAt(kind, yRatio) };
}
function onDragPointerDown(entry: TreeEntry, event: PointerEvent) {
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || renameRel === entry.rel_path) {
return;
}
const startX = event.clientX;
const startY = event.clientY;
let started = false;
cancelDrag?.();
const onMove = (moveEvent: PointerEvent) => {
if (!started) {
if (Math.hypot(moveEvent.clientX - startX, moveEvent.clientY - startY) <= 8) {
return;
}
started = true;
selectOnly(entry.rel_path);
dragRel = entry.rel_path;
}
dragPoint = { x: moveEvent.clientX, y: moveEvent.clientY };
imageLanding = entry.kind === "file" && highlightImageDrop(entry.rel_path, dragPoint);
dropTarget = readDropAt(moveEvent.clientX, moveEvent.clientY);
};
const clean = () => {
window.removeEventListener("pointermove", onMove);
window.removeEventListener("pointerup", onUp);
window.removeEventListener("pointercancel", clean);
window.removeEventListener("keydown", onKey, true);
highlightImageDrop();
dragRel = null; dropTarget = null; dragPoint = null; imageLanding = false;
cancelDrag = undefined;
};
const onKey = (key: KeyboardEvent) => { if (key.key === "Escape") { key.preventDefault(); clean(); } };
const onUp = (up: PointerEvent) => {
if (started) {
skipClick = true;
setTimeout(() => { skipClick = false; }, 0);
}
if (started && entry.kind === "file" && dropWorkspaceImage(entry.rel_path, { x: up.clientX, y: up.clientY })) { clean(); return; }
if (started && dragRel && dropTarget) {
const target = findEntry(dropTarget.rel);
if (target) {
skipClick = true;
void handleDrop(target, dragRel, dropTarget.place);
}
}
clean();
};
cancelDrag = clean;
window.addEventListener("pointermove", onMove);
window.addEventListener("pointerup", onUp);
window.addEventListener("pointercancel", clean);
window.addEventListener("keydown", onKey, true);
}
function cycleSort() {
sortMode = sortMode === "custom" ? "name" : sortMode === "name" ? "name-desc" : "custom";
const current = untrack(() => childrenMap);
const next: Record<string, TreeEntry[]> = {};
for (const [key, list] of Object.entries(current)) {
next[key] = sortEntries(key, list);
}
childrenMap = next;
}
const folderPaths = $derived(
Object.values(childrenMap)
.flat()
.filter((item) => item.kind === "folder")
.map((item) => item.rel_path),
);
const allCollapsed = $derived(folderPaths.every((path) => !expanded.has(path)));
function collapseAll() {
expanded = new Set([""]);
}
async function expandAll() {
const folders = new Set<string>([""]);
const walk = async (parent: string) => {
if (!childrenMap[parent]) {
await load(parent);
}
for (const child of childrenMap[parent] ?? []) {
if (child.kind === "folder") {
folders.add(child.rel_path);
await walk(child.rel_path);
}
}
};
await walk("");
expanded = folders;
}
async function copyText(text: string, label: string) {
try {
await navigator.clipboard.writeText(text);
} catch {
const area = document.createElement("textarea");
area.value = text;
document.body.appendChild(area);
area.select();
document.execCommand("copy");
area.remove();
}
onStatus?.(`Copied ${label}`);
}
async function persistMarks(next: Marks) {
marks = next;
try {
await saveMarks(next);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
}
function namesIn(parent: string): string[] {
return (childrenMap[parent] ?? []).map((item) => item.name);
}
function startRename(entry: TreeEntry) {
selectOnly(entry.rel_path);
renameRel = entry.rel_path;
renameDraft = entry.name;
}
function cancelRename() {
renameRel = null;
renameDraft = "";
}
async function commitRename() {
const from = renameRel;
if (!from) {
return;
}
const plan = planRename(from, renameDraft);
cancelRename();
if (plan.action === "noop") {
return;
}
if (plan.action === "error") {
error = plan.message;
return;
}
try {
await workspaceRename(from, plan.to);
await load(parentRel(from));
selectOnly(plan.to);
onEntryRenamed?.(from, plan.to);
onStatus?.(`Renamed to ${plan.to}`);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
}
function onWindowKey(event: KeyboardEvent) {
if (!keysActive) {
return;
}
if (event.key !== "F2" || event.ctrlKey || event.metaKey || event.altKey) {
return;
}
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
return;
}
if (selection.paths.size > 1) return;
const rel = selection.paths.values().next().value ?? activePath;
if (!rel) {
return;
}
const entry = findEntry(rel);
if (!entry) {
return;
}
event.preventDefault();
startRename(entry);
}
async function createIn(parent: string, kind: "folder" | "note") {
let name: string;
if (kind === "note") {
name = "untitled.md";
} else {
const typed = await requestText("Folder name", "folder");
if (!typed) {
return;
}
if (typed.includes("/") || typed.includes("\\")) {
error = "Name cannot contain a path separator";
return;
}
name = typed;
}
const finalName = uniqueName(namesIn(parent), name);
const rel = joinRel(parent, finalName);
try {
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
const order = { ...marks.order };
order[parent] = [...(order[parent] ?? []), finalName];
await persistMarks({ ...marks, order });
if (!childrenMap[parent] && parent !== "") {
const next = new Set(expanded);
next.add(parent);
expanded = next;
}
await load(parent);
onStatus?.(`Created ${rel}`);
if (kind === "note") {
onCreated?.({ name: finalName, rel_path: rel, kind: "file" });
}
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
}
async function handleDrop(target: TreeEntry, draggedRel: string, place: DropPlace) {
const plan = planDrop(draggedRel, target, place, namesIn);
if (plan.action === "noop") {
return;
}
try {
if (plan.action === "reorder") {
const order = { ...marks.order };
order[plan.parent] = plan.names;
await persistMarks({ ...marks, order });
await load(plan.parent);
onStatus?.(`Moved ${draggedRel}`);
return;
}
await workspaceRename(plan.from, plan.to);
const order = { ...marks.order };
order[plan.fromParent] = plan.orderFrom;
order[plan.toParent] = plan.orderTo;
await persistMarks({ ...marks, order });
await load(plan.fromParent);
if (plan.toParent !== plan.fromParent) {
await load(plan.toParent);
}
selectOnly(plan.to);
onEntryRenamed?.(plan.from, plan.to);
onStatus?.(`Moved to ${plan.to}`);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
}
function paneMenuItems(parent: string): MenuItem[] {
return [
{
kind: "action",
label: "Create folder",
run: () => {
void createIn(parent, "folder");
},
},
{
kind: "action",
label: "Create new note",
run: () => {
void createIn(parent, "note");
},
},
];
}
function menuItems(entry: TreeEntry | null): MenuItem[] {
if (!entry) {
return paneMenuItems("");
}
const pinned = pins.has(entry.rel_path);
const bookmarked = bookmarks.has(entry.rel_path);
const createItems =
entry.kind === "folder"
? [...paneMenuItems(entry.rel_path), { kind: "sep" as const }]
: [];
return [
...createItems,
{
kind: "action",
label: "Make a copy",
run: () => {
void (async () => {
try {
const copy = await workspaceCopy(entry.rel_path);
await load(parentRel(entry.rel_path));
onStatus?.(`Copied to ${copy.rel_path}`);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
})();
},
},
{
kind: "action",
label: bookmarked ? "Remove bookmark" : "Bookmark",
run: () => {
void persistMarks({
...marks,
bookmarks: togglePath(marks.bookmarks, entry.rel_path),
});
},
},
{ kind: "sep" },
{
kind: "action",
label: "Copy workspace path",
run: () => {
void copyText(entry.rel_path, "workspace path");
},
},
{
kind: "action",
label: "Copy system path",
run: () => {
void (async () => {
try {
const abs = await workspaceAbsPath(entry.rel_path);
await copyText(abs, "system path");
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
})();
},
},
{
kind: "action",
label: "Show in Explorer",
run: () => {
void (async () => {
try {
await workspaceReveal(entry.rel_path);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
})();
},
},
{ kind: "sep" },
{
kind: "action",
label: pinned ? "Unpin" : "Pin",
run: () => {
void persistMarks({
...marks,
pins: togglePath(marks.pins, entry.rel_path),
});
},
},
{
kind: "action",
label: "Rename",
run: () => {
startRename(entry);
},
},
{
kind: "action",
label: "Delete",
run: () => {
void (async () => {
try {
if (!await confirm(`Permanently delete ${entry.name}${entry.kind === "folder" ? " and everything inside it" : ""}?`, { title: "Delete from disk", kind: "warning" })) return;
await workspaceDelete(entry.rel_path);
await load(parentRel(entry.rel_path));
onEntryGone?.(entry.rel_path);
onStatus?.(`Deleted ${entry.rel_path}`);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
})();
},
},
];
}
</script>
<svelte:window onkeydown={onWindowKey} />
<div class="wrap">
<div class="ribbon tree-tools">
<IconButton icon="file-plus" label="New file" onclick={() => void createIn("", "note")} />
<IconButton icon="folder-plus" label="New folder" onclick={() => void createIn("", "folder")} />
<IconButton
icon="sort"
label={sortMode === "custom" ? "Sort: custom" : sortMode === "name" ? "Sort: name" : "Sort: name Z-A"}
onclick={cycleSort}
/>
<IconButton
icon={allCollapsed ? "unfold" : "fold"}
label={allCollapsed ? "Expand all" : "Collapse all"}
onclick={() => {
if (allCollapsed) {
void expandAll();
} else {
collapseAll();
}
}}
/>
</div>
<div
class="tree"
role="navigation"
aria-label="Workspace files"
oncontextmenu={(event) => {
event.preventDefault();
menu = { x: event.clientX, y: event.clientY, entry: null };
}}
>
{#if error}
<p class="error">{error}</p>
{/if}
{#if loading && !childrenMap[""]}
<p class="muted">Loading…</p>
{/if}
{#if childrenMap[""]}
<ul role="tree" aria-label="Workspace files" aria-multiselectable="true">
{#each childrenMap[""] as entry (entry.rel_path)}
<TreeNode
{entry}
{childrenMap}
{expanded}
{activePath}
{pins}
{bookmarks}
{onRowClick}
onContextMenu={(target, x, y) => {
menu = { x, y, entry: target };
selectOnly(target.rel_path);
}}
{dropTarget}
{dragRel}
selectedPaths={selection.paths}
{selectionEdges}
{renameRel}
{renameDraft}
onRenameDraft={(value) => (renameDraft = value)}
onRenameCommit={() => void commitRename()}
onRenameCancel={cancelRename}
{onDragPointerDown}
/>
{/each}
</ul>
{/if}
</div>
</div>
{#if dragRel && dragPoint}
{@const landing = dropTarget ? findEntry(dropTarget.rel) : null}
<div class="drag-ghost" style:left="{dragPoint.x + 12}px" style:top="{dragPoint.y + 12}px">
<span>{dragRel.split("/").pop()}</span>
{#if imageLanding}
<span class="hint">Insert image</span>
{:else if landing && dropTarget}
<span class="hint">{dropHint(landing.name, dropTarget.place)}</span>
{/if}
</div>
{/if}
{#if menu}
<ContextMenu
x={menu.x}
y={menu.y}
items={menuItems(menu.entry)}
onClose={() => (menu = null)}
/>
{/if}
<style>
.wrap {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.ribbon.tree-tools {
display: flex;
align-items: center;
justify-content: center;
gap: 2px;
padding: 4px 6px;
border-bottom: 1px solid var(--rs-border);
}
.drag-ghost {
position: fixed;
z-index: 40;
pointer-events: none;
display: flex;
flex-direction: column;
gap: 2px;
padding: 4px 8px;
background: var(--rs-bg-elevated);
border: 1px solid var(--rs-accent);
color: var(--rs-text-strong);
font-size: 12px;
}
.drag-ghost .hint {
color: var(--rs-accent);
}
.tree {
flex: 1;
overflow: auto;
padding: 6px 0 12px;
min-height: 0;
}
ul {
list-style: none;
margin: 0;
padding: 0 0 0 4px;
}
.muted,
.error {
margin: 8px 12px;
color: var(--rs-text-dim);
}
.error {
color: var(--rs-error);
}
</style>
+32
View File
@@ -0,0 +1,32 @@
<script lang="ts">
type Props = {
src: string;
name: string;
};
let { src, name }: Props = $props();
</script>
<div class="viewer">
<img {src} alt={name} />
</div>
<style>
.viewer {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
padding: 16px;
background: var(--rs-bg);
}
img {
max-width: 100%;
max-height: 100%;
object-fit: contain;
border: 1px solid var(--rs-border);
background: var(--rs-bg-elevated);
}
</style>
+161
View File
@@ -0,0 +1,161 @@
<script lang="ts">
import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
import { renderDiagrams } from "$lib/workspace/diagrams";
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls";
type Props = {
noteRel: string;
contents: string;
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
onEditBlock?: (start: number, end: number) => void;
editing?: { start: number; end: number } | null;
blockEditor?: Snippet;
};
let { noteRel, contents, onOpenLink, onEditBlock, editing = null, blockEditor }: Props = $props();
let html = $state("");
let sections = $state<MarkdownSection[]>([]);
let root: HTMLDivElement | undefined = $state();
async function loadUrls(noteRel: string, contents: string): Promise<Map<string, string>> {
const urls = new Map<string, string>();
await Promise.all(markdownImages(contents).map(async source => {
if (isRemoteImage(source)) {
urls.set(source, source.trim());
return;
}
let path = source;
try { path = decodeURIComponent(source); } catch { /* Keep literal malformed escapes. */ }
const primary = resolveImageRel(noteRel, path);
const normalized = path.replaceAll("\\", "/").replace(/^\/+/, "");
const base = normalized.split("/").pop() ?? path;
for (const candidate of new Set([primary, normalized, base])) {
try {
urls.set(source, await workspaceReadDataUrl(candidate));
return;
} catch { /* Try the workspace-relative attachment next. */ }
}
urls.set(source, "");
}));
return urls;
}
$effect(() => {
const path = noteRel;
const text = contents;
let cancelled = false;
html = renderMarkdownHtml(text, new Map());
sections = renderMarkdownSections(text, new Map());
void loadUrls(path, text).then(urls => {
if (!cancelled) {
html = renderMarkdownHtml(text, urls);
sections = renderMarkdownSections(text, urls);
}
});
return () => { cancelled = true; };
});
$effect(() => {
void html;
void sections;
void editing;
const el = root;
let cancelled = false;
let releaseImages: (() => void) | undefined;
if (el) void tick().then(() => {
if (cancelled) return;
releaseImages = imageControls(el);
return renderDiagrams(el, () => cancelled);
});
return () => { cancelled = true; releaseImages?.(); };
});
async function copyFence(button: HTMLButtonElement, body: string) {
try {
await navigator.clipboard.writeText(body);
} catch {
const ta = document.createElement("textarea");
ta.value = body;
ta.setAttribute("readonly", "");
ta.style.position = "fixed";
ta.style.left = "-9999px";
document.body.appendChild(ta);
ta.select();
try {
document.execCommand("copy");
} finally {
ta.remove();
}
}
button.dataset.copied = "true";
button.setAttribute("aria-label", "Copied");
button.title = "Copied";
window.setTimeout(() => {
if (button.isConnected) {
delete button.dataset.copied;
button.setAttribute("aria-label", "Copy code");
button.title = "Copy code";
}
}, 1200);
}
</script>
<!-- Events are delegated from generated native links and buttons, which support keyboard activation. -->
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
<div
class="reading"
bind:this={root}
onkeydown={(event) => {
if (event.target instanceof HTMLElement && event.target.classList.contains("md-edit-block") && (event.key === "Enter" || event.key === " ")) {
event.preventDefault();
onEditBlock?.(Number(event.target.dataset.start), Number(event.target.dataset.end));
}
}}
onclick={(event) => {
const copy = event.target instanceof Element ? event.target.closest("button.rs-fence-copy") : null;
if (copy instanceof HTMLButtonElement) {
event.preventDefault();
const pre = copy.closest("pre.md-code") ?? copy.closest("pre");
const body = pre?.querySelector("code")?.textContent ?? "";
void copyFence(copy, body);
return;
}
const node = event.target instanceof Element ? event.target.closest("a") : null;
if (!node) {
const target = event.target instanceof Element ? event.target : null;
if (target?.closest("textarea, button, summary")) return;
const block = target?.closest<HTMLElement>(".md-edit-block");
if (block) onEditBlock?.(Number(block.dataset.start), Number(block.dataset.end));
return;
}
const href = node.getAttribute("href") ?? "";
const kind = node.getAttribute("data-kind");
if (kind === "wiki") {
event.preventDefault();
onOpenLink?.("wiki", href);
return;
}
if (kind === "md") {
event.preventDefault();
onOpenLink?.("md", href);
}
}}
>
<h1 class="document-title">{markdownTitle(noteRel)}</h1>
{#if onEditBlock}
{#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label="Edit document block" data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each}
{#if editing && blockEditor}
{@render blockEditor()}
{#each sections.filter(section => section.start >= editing.end && section.end > editing.end) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label="Edit document block" data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each}
{/if}
{:else}
{@html html}
{/if}
</div>
+74
View File
@@ -0,0 +1,74 @@
<script lang="ts">
import type { OutlineItem } from "$lib/workspace/outline";
type Props = {
items: OutlineItem[];
onJump: (line: number) => void;
};
let { items, onJump }: Props = $props();
</script>
<div class="outline">
<div class="pane-label">Outline</div>
{#if items.length === 0}
<p class="placeholder">No headings or symbols in this file.</p>
{:else}
<ul>
{#each items as item (item.line + item.text)}
<li style:padding-left="{8 + (item.level - 1) * 12}px">
<button type="button" onclick={() => onJump(item.line)}>{item.text}</button>
</li>
{/each}
</ul>
{/if}
</div>
<style>
.outline {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.pane-label {
padding: 6px 10px;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--rs-text-dim);
border-bottom: 1px solid var(--rs-border);
text-align: center;
}
.placeholder {
margin: 12px;
color: var(--rs-text-dim);
}
ul {
list-style: none;
margin: 0;
padding: 6px 0;
overflow: auto;
}
button {
width: 100%;
border-radius: var(--rs-control-radius);
border: 0;
background: transparent;
color: var(--rs-text);
text-align: left;
padding: 3px 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
button:hover {
background: var(--rs-bg-active);
color: var(--rs-text-strong);
}
</style>
+60
View File
@@ -0,0 +1,60 @@
<script lang="ts">
import { workspaceList } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types";
import { onMount } from "svelte";
let { onOpen, onClose }: { onOpen: (entry: TreeEntry) => void; onClose: () => void } = $props();
let query = $state("");
let files = $state<TreeEntry[]>([]);
let selected = $state(0);
let loading = $state(true);
let error = $state("");
let dialog: HTMLDialogElement;
let input: HTMLInputElement;
const matches = $derived(files.filter(file => query.toLowerCase().split(/\s+/).every(part => file.rel_path.toLowerCase().includes(part))).slice(0, 80));
function pick(entry?: TreeEntry) { if (entry) { onOpen(entry); onClose(); } }
onMount(() => {
dialog.showModal(); input.focus();
let cancelled = false;
void (async () => {
const queue = [""];
try {
while (queue.length && !cancelled) {
const entries = await workspaceList(queue.shift()!);
if (cancelled) return;
files = [...files, ...entries.filter(e => e.kind === "file")];
queue.push(...entries.filter(e => e.kind === "folder").map(e => e.rel_path));
}
} catch (err) { if (!cancelled) error = String(err); }
finally { if (!cancelled) loading = false; }
})();
return () => { cancelled = true; };
});
</script>
<dialog bind:this={dialog} oncancel={onClose}>
<input bind:this={input} bind:value={query} oninput={() => selected = 0} aria-label="Find a file" placeholder="Find a note or code file…" onkeydown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
}
if (event.key === "Enter") { event.preventDefault(); pick(matches[selected]); }
}} />
<div class="results">
{#each matches as entry, index (entry.rel_path)}
<button data-index={index} class:selected={selected === index} onclick={() => pick(entry)}><strong>{entry.name}</strong><span>{entry.rel_path}</span></button>
{/each}
{#if !matches.length}<p>{loading ? "Finding files…" : "No matching files."}</p>{/if}
</div>
<footer>{error || `${files.length} files${loading ? " · indexing…" : ""}`} <span>↑ ↓ select · Enter open · Esc close</span></footer>
</dialog>
<style>
dialog { margin-top: 12vh; padding: 0; width: min(640px, 85vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); }
dialog::backdrop { background: #0008; }
input { width: 100%; padding: 16px; border: 0; background: var(--rs-bg); color: var(--rs-text-strong); }
.results { max-height: 50vh; overflow: auto; padding: 6px; }
button { width: 100%; display: flex; flex-direction: column; align-items: flex-start; gap: 3px; padding: 8px 10px; border: 0; background: transparent; text-align: left; }
button.selected, button:hover { background: var(--rs-bg-active); }
button span, footer { color: var(--rs-text-dim); font-size: 12px; }
footer { padding: 10px 14px; display: flex; justify-content: space-between; border-top: 1px solid var(--rs-border); }
</style>
+147
View File
@@ -0,0 +1,147 @@
<script lang="ts">
import IconButton from "$lib/ui/IconButton.svelte";
import { workspaceSearch, type SearchHit } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types";
type Props = {
onOpen: (entry: TreeEntry, line: number) => void;
searchRequest?: { text: string; id: number } | null;
};
let { onOpen, searchRequest }: Props = $props();
let query = $state("");
let hits = $state<SearchHit[]>([]);
let error = $state<string | null>(null);
let generation = 0;
$effect(() => { if (searchRequest) { query = searchRequest.text; void run(searchRequest.text); } });
async function run(value = query) {
const version = ++generation;
const q = value.trim();
if (!q) {
hits = [];
return;
}
try {
const results = await workspaceSearch(q);
if (version !== generation) return;
hits = results;
error = null;
} catch (err) {
if (version !== generation) return;
error = err instanceof Error ? err.message : String(err);
}
}
</script>
<div class="pane">
<div class="pane-label">Search</div>
<form
class="bar"
onsubmit={(event) => {
event.preventDefault();
void run();
}}
>
<input bind:value={query} placeholder="Search files and notes" />
<IconButton icon="search" label="Search workspace" type="submit" />
</form>
{#if error}
<p class="error">{error}</p>
{/if}
<ul>
{#each hits as hit (hit.rel_path + hit.line + hit.text)}
<li>
<button
type="button"
onclick={() =>
onOpen(
{
name: hit.rel_path.split("/").pop() ?? hit.rel_path,
rel_path: hit.rel_path,
kind: "file",
},
hit.line,
)}
>
<span class="path">{hit.rel_path}:{hit.line}</span>
<span class="text">{hit.text}</span>
</button>
</li>
{/each}
</ul>
</div>
<style>
.pane {
height: 100%;
display: flex;
flex-direction: column;
min-height: 0;
}
.pane-label {
padding: 6px 10px;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--rs-text-dim);
border-bottom: 1px solid var(--rs-border);
text-align: center;
}
.bar {
display: flex;
gap: 6px;
padding: 8px;
}
input {
flex: 1;
min-width: 0;
border-radius: 5px;
border: 1px solid var(--rs-border);
background: var(--rs-bg);
padding: 4px 8px;
}
ul {
list-style: none;
margin: 0;
padding: 0 0 12px;
overflow: auto;
}
button {
width: 100%;
border-radius: var(--rs-control-radius);
border: 0;
background: transparent;
text-align: left;
padding: 6px 10px;
}
button:hover {
background: var(--rs-bg-active);
}
.path {
display: block;
color: var(--rs-accent);
font-size: 12px;
}
.text {
display: block;
color: var(--rs-text-dim);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.error {
margin: 8px 10px;
color: var(--rs-error);
}
</style>
+114
View File
@@ -0,0 +1,114 @@
<script lang="ts">
import type { OpenBuffer } from "$lib/workspace/types";
type Props = {
tabs: OpenBuffer[];
activePath: string | null;
onSelect: (relPath: string) => void;
onClose: (relPath: string) => void;
};
let { tabs, activePath, onSelect, onClose }: Props = $props();
function onMiddleDown(event: MouseEvent) {
if (event.button === 1) {
event.preventDefault();
}
}
function onMiddleUp(event: MouseEvent, relPath: string) {
if (event.button === 1) {
event.preventDefault();
event.stopPropagation();
onClose(relPath);
}
}
</script>
<div class="tabs" role="tablist" aria-label="Open files">
{#each tabs as tab (tab.relPath)}
<div class="tab" class:active={tab.relPath === activePath}>
<button
type="button"
role="tab"
aria-selected={tab.relPath === activePath}
title={tab.kind === "empty" ? tab.name : tab.relPath}
onclick={() => onSelect(tab.relPath)}
onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
>
{tab.name}{tab.contents !== tab.saved ? " •" : ""}
</button>
<button
class="close"
type="button"
aria-label="Close {tab.name}"
title="Close {tab.name}"
onclick={() => onClose(tab.relPath)}
onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
>
×
</button>
</div>
{/each}
</div>
<style>
.tabs {
display: flex;
min-height: 32px;
overflow-x: auto;
background: var(--rs-bg-elevated);
border-bottom: 1px solid var(--rs-border);
}
.tab {
display: flex;
align-items: center;
max-width: 220px;
flex-shrink: 0;
border-radius: var(--rs-item-selection-radius) var(--rs-item-selection-radius) 0 0;
border-right: 1px solid var(--rs-border);
background: var(--rs-bg);
}
.tab.active {
background: var(--rs-bg-active);
box-shadow: inset 0 2px var(--rs-accent);
}
.tab > button:first-child {
flex: 1;
min-width: 0;
border: 0;
background: transparent;
color: var(--rs-text-dim);
text-align: left;
padding: 0 8px 0 12px;
height: 32px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.tab.active > button:first-child {
color: var(--rs-text-strong);
}
.close {
border: 0;
border-radius: var(--rs-control-radius);
background: transparent;
color: var(--rs-text-dim);
width: 22px;
height: 22px;
margin-right: 4px;
flex: 0 0 22px;
}
.close:hover {
color: var(--rs-text-strong);
background: var(--rs-bg);
}
</style>
+260
View File
@@ -0,0 +1,260 @@
<script lang="ts">
import { onMount, tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { ptyProfiles, ptyNewWindow, ptyDictation, workspaceRead } from "$lib/workspace/api";
import { directoryCommand, fileCommand, parseTasks, readSettings, remember, type ShellProfile, type TerminalControl, type TerminalSettings as Settings } from "$lib/terminal/model";
import TerminalPicker from "$lib/terminal/TerminalPicker.svelte";
import TerminalSettings from "$lib/terminal/TerminalSettings.svelte";
import TerminalPane from "./TerminalPane.svelte";
type Session = { id: string; group: string; title: string; state: string; profile: ShellProfile; directory: string; weight: number; command?: string };
type Picker = { title: string; items: { label: string; detail?: string; value: string }[]; onPick: (value: string) => void; empty?: string };
let { cwd, visible, maximized = false, standalone = false, onClose, onMaximize = () => {}, activeFile = false, onRunFile, getSelection = () => "", onConfigureTasks }: {
cwd: string; visible: boolean; maximized?: boolean; standalone?: boolean; onClose: () => void; onMaximize?: () => void;
activeFile?: boolean; onRunFile?: () => Promise<string | null>; getSelection?: () => string; onConfigureTasks?: () => Promise<void>;
} = $props();
let sessions = $state<Session[]>([]);
let profiles = $state<ShellProfile[]>([]);
let settings = $state(readSettings());
let activeId = $state("");
let loading = $state(true);
let error = $state("");
let railWidth = $state(205);
let picker = $state<Picker | null>(null);
let showSettings = $state(false);
let recentCommands = $state<string[]>([]);
let recentDirectories = $state<string[]>([]);
let menu: HTMLElement | undefined;
let menuAnchor: HTMLElement | undefined;
let profileAnchor: HTMLDivElement;
let moreAnchor: HTMLDivElement;
let panes: HTMLDivElement;
let sequence = 0;
let stopResize: (() => void) | undefined;
let ready: Promise<void> = Promise.resolve();
const controls = new Map<string, TerminalControl>();
const active = $derived(sessions.find(session => session.id === activeId));
const group = $derived(sessions.filter(session => session.group === active?.group));
const totalWeight = $derived(group.reduce((sum, session) => sum + session.weight, 0));
function report(reason: unknown) { error = String(reason); }
function persist(next: Settings) {
settings = { ...next };
try { localStorage.setItem("runestone.terminal", JSON.stringify(settings)); } catch (reason) { report(reason); }
}
function defaultProfile() { return profiles.find(profile => profile.id === settings.defaultProfile) || profiles.find(profile => profile.kind !== "node") || profiles[0]; }
export function addSession(profile = defaultProfile(), split = false, command?: string, title?: string) {
if (!profile) return;
const id = crypto.randomUUID();
const next = { id, group: split && active ? active.group : id, title: title || `${profile.title} ${++sequence}`, state: "Starting", profile,
directory: split && active ? active.directory : cwd, weight: 1, command };
if (split) for (const member of group) member.weight = 1;
sessions = [...sessions, next]; activeId = id;
recentDirectories = remember(recentDirectories, next.directory);
}
function killSession(id: string) {
const previous = sessions.findIndex(session => session.id === id);
const sibling = sessions.find(session => session.group === sessions[previous]?.group && session.id !== id);
sessions = sessions.filter(session => session.id !== id);
if (activeId === id) activeId = sibling?.id || sessions[Math.max(0, previous - 1)]?.id || "";
void tick().then(() => controls.get(activeId)?.focus());
}
function select(id: string) { activeId = id; }
function closeMenu(focus = false) { menu?.remove(); menu = undefined; if (focus) menuAnchor?.querySelector<HTMLButtonElement>("button")?.focus(); }
function showMenu(anchor: HTMLElement, items: ActionMenuItem[], name: string) {
const same = menu && menuAnchor === anchor; closeMenu(); if (same) return;
menuAnchor = anchor;
const wrap = (entries: ActionMenuItem[]): ActionMenuItem[] => entries.map(item => "separator" in item ? item : { ...item,
children: item.children ? wrap(item.children) : undefined,
run: item.run ? () => { closeMenu(); item.run?.(); } : undefined });
const bounds = anchor.getBoundingClientRect();
menu = actionMenu(bounds.right - 430, bounds.bottom + 4, wrap(items), () => closeMenu(true), name);
}
function profileMenu() {
showMenu(profileAnchor, [
{ label: "New Terminal", icon: "plus", shortcut: "Ctrl+Shift+`", run: () => addSession() },
{ label: "New Terminal Window", icon: "external", shortcut: "Ctrl+Shift+Alt+`", run: () => void ptyNewWindow().catch(report) },
{ label: "Split Terminal", icon: "column", shortcut: "Ctrl+Shift+5", disabled: !active, run: () => addSession(active?.profile, true) },
{ separator: true },
...profiles.map(profile => ({ label: profile.title, icon: "code" as const, title: profile.kind === "node" ? "Node.js REPL with a local inspector. Attach using an external debugger." : undefined, run: () => addSession(profile) })),
{ label: "Split Terminal with Profile", icon: "column", disabled: !active, children: profiles.map(profile => ({ label: profile.title, icon: "code", run: () => addSession(profile, true) })) },
{ separator: true },
{ label: "Configure Terminal Settings", icon: "format", run: () => showSettings = true },
{ label: "Select Default Profile", icon: "select", run: () => picker = { title: "Select default terminal profile", items: profiles.filter(profile => profile.kind !== "node").map(profile => ({ label: profile.title, value: profile.id, detail: profile.id === settings.defaultProfile ? "Default" : undefined })), onPick: value => persist({ ...settings, defaultProfile: value }) } },
{ separator: true },
{ label: "Run Task…", icon: "task", run: () => void runTask() },
{ label: "Configure Tasks…", icon: "code", disabled: !onConfigureTasks, run: () => void onConfigureTasks?.().catch(report) },
], "Terminal profiles");
}
async function runFile() {
const target = active;
if (!target || !onRunFile) return;
try { const path = await onRunFile(); if (path) controls.get(target.id)?.send(fileCommand(path, target.profile.kind)); } catch (reason) { report(reason); }
}
function runSelection() {
const text = getSelection();
if (!text) { error = "Select text in the editor first."; return; }
controls.get(activeId)?.send(text);
}
function historyPicker(kind: "commands" | "directories") {
const target = active;
if (!target) return;
picker = { title: kind === "commands" ? "Run recent command" : "Go to recent directory",
items: (kind === "commands" ? recentCommands : recentDirectories).map(value => ({ label: value, value })),
empty: kind === "commands" ? "No commands yet. Shell commands appear after the next prompt." : "No directories yet.",
onPick: value => { try { controls.get(target.id)?.send(kind === "commands" ? value : directoryCommand(value, target.profile.kind)); } catch (reason) { report(reason); } } };
}
async function runTask() {
try {
const tasks = parseTasks(await workspaceRead(".runestone/tasks.json"));
picker = { title: "Run task", items: tasks.map((task, index) => ({ label: task.label, detail: task.command, value: String(index) })), empty: "No tasks configured. Choose Configure Tasks… to add one.", onPick: index => {
const task = tasks[Number(index)];
const profile = task.profile ? profiles.find(profile => profile.id === task.profile) : defaultProfile();
if (!profile) { error = `Task profile is unavailable: ${task.profile}`; return; }
addSession(profile, false, task.command, task.label);
} };
} catch (reason) { error = `Cannot load .runestone/tasks.json. Use Configure Tasks… to create or edit it. ${String(reason)}`; }
}
function moreMenu() {
showMenu(moreAnchor, [
{ label: "Scroll to Previous Command", icon: "up", shortcut: "Ctrl+UpArrow", disabled: !active, run: () => controls.get(activeId)?.scrollCommand(-1) },
{ label: "Scroll to Next Command", icon: "down", shortcut: "Ctrl+DownArrow", disabled: !active, run: () => controls.get(activeId)?.scrollCommand(1) },
{ label: "Clear Terminal", icon: "clear", disabled: !active, run: () => controls.get(activeId)?.clear() },
{ label: "Run Active File", icon: "code", disabled: !active || !activeFile, run: () => void runFile() },
{ label: "Run Selected Text", icon: "select", disabled: !active || !activeFile, run: runSelection },
{ label: "Start Dictation", icon: "comment", disabled: !active, title: "Start Windows voice typing in the focused terminal", run: () => { controls.get(activeId)?.focus(); void ptyDictation().catch(report); } },
{ separator: true },
{ label: "Go to Recent Directory…", icon: "external", shortcut: "Ctrl+G", disabled: !active, run: () => historyPicker("directories") },
{ label: "Run Recent Command…", icon: "task", shortcut: "Ctrl+Alt+R", disabled: !active, run: () => historyPicker("commands") },
], "Terminal actions");
}
export async function command(action: "new" | "split" | "window" | "previous" | "next" | "commands" | "directories") {
await ready;
if (action === "new") addSession();
else if (action === "split") addSession(active?.profile || defaultProfile(), !!active);
else if (action === "window") void ptyNewWindow().catch(report);
else if (action === "previous" || action === "next") controls.get(activeId)?.scrollCommand(action === "previous" ? -1 : 1);
else historyPicker(action);
}
function beginResize(event: PointerEvent, update: (x: number) => void) {
if (event.button !== 0) return;
event.preventDefault(); stopResize?.();
const move = (event: PointerEvent) => update(event.clientX);
stopResize = () => { window.removeEventListener("pointermove", move); window.removeEventListener("pointerup", stop); window.removeEventListener("pointercancel", stop); stopResize = undefined; };
const stop = () => stopResize?.();
window.addEventListener("pointermove", move); window.addEventListener("pointerup", stop); window.addEventListener("pointercancel", stop);
}
function resizeRail(event: PointerEvent) { const x = event.clientX, width = railWidth; beginResize(event, next => railWidth = Math.min(340, Math.max(140, width + x - next))); }
function resizeSplit(event: PointerEvent, session: Session) {
const index = group.indexOf(session), previous = group[index - 1];
if (!previous) return;
const x = event.clientX, before = previous.weight, after = session.weight, width = panes.clientWidth, total = totalWeight;
beginResize(event, next => { const change = (next - x) / width * total; previous.weight = Math.min(before + after - .15, Math.max(.15, before + change)); session.weight = before + after - previous.weight; });
}
function paneLeft(session: Session) { return group.slice(0, group.indexOf(session)).reduce((sum, item) => sum + item.weight, 0) / totalWeight * 100; }
onMount(() => {
let disposed = false;
ready = ptyProfiles().then(found => {
if (disposed) return;
profiles = found;
if (!profiles.some(profile => profile.id === settings.defaultProfile)) settings.defaultProfile = defaultProfile()?.id || "";
if (profiles.length) addSession(); else error = "No supported shells were found on PATH.";
}).catch(report).finally(() => loading = false);
const outside = (event: PointerEvent) => { if (menu && !menu.contains(event.target as Node) && !menuAnchor?.contains(event.target as Node)) closeMenu(); };
const resize = () => closeMenu();
window.addEventListener("pointerdown", outside); window.addEventListener("resize", resize);
return () => { disposed = true; closeMenu(); stopResize?.(); window.removeEventListener("pointerdown", outside); window.removeEventListener("resize", resize); };
});
$effect(() => { if (!visible) { closeMenu(); picker = null; showSettings = false; } });
</script>
<div class="dock" style:--rail="{railWidth}px">
<header class="ribbon">
<span class="label" title={cwd}>Terminal</span><span class="directory" title={active?.directory || cwd}>{active?.directory || cwd}</span>
<div class="actions">
{#if sessions.length === 1}<span class="single-session" title={`${active?.title} · ${active?.state}`}>{active?.profile.title}</span>{/if}
<IconButton icon="plus" label="New terminal" disabled={loading || !profiles.length} onclick={() => addSession()} />
<div bind:this={profileAnchor}><IconButton icon="chevron-down" label="Terminal profiles and tasks" disabled={loading} onclick={profileMenu} /></div>
<IconButton icon="split" label="Split terminal (Ctrl+Shift+5)" disabled={!active} onclick={() => addSession(active?.profile, true)} />
<div bind:this={moreAnchor}><IconButton icon="more" label="More terminal actions" onclick={moreMenu} /></div>
<IconButton icon="trash" label="Kill terminal" disabled={!active} onclick={() => killSession(activeId)} />
{#if !standalone}<IconButton icon={maximized ? "restore" : "maximize"} label={maximized ? "Restore panel" : "Maximize panel"} onclick={onMaximize} />{/if}
<IconButton icon="close" label={standalone ? "Close terminal window" : "Hide terminal (sessions keep running)"} onclick={onClose} />
</div>
</header>
{#if error}<div class="error" role="alert"><span>{error}</span><button aria-label="Dismiss terminal error" onclick={() => error = ""}>×</button></div>{/if}
<div class="body">
<div class="panes" bind:this={panes}>
{#each sessions as session (session.id)}
<div class="pane" class:shown={session.group === active?.group} class:focused={session.id === activeId}
style:left="{session.group === active?.group ? paneLeft(session) : 0}%" style:width="{session.group === active?.group ? session.weight / totalWeight * 100 : 100}%">
{#if group.length > 1 && session.group === active?.group}<div class="pane-label">{session.title}</div>{/if}
<TerminalPane id={session.id} {cwd} directory={session.directory} profile={session.profile} {settings}
active={visible && session.group === active?.group} focused={session.id === activeId} onFocus={() => activeId = session.id}
onState={state => { session.state = state; if (state === "Running" && session.command) { controls.get(session.id)?.send(session.command); session.command = undefined; } }}
onControl={control => { if (control) controls.set(session.id, control); else controls.delete(session.id); }}
onCommand={command => recentCommands = remember(recentCommands, command)}
onDirectory={directory => { session.directory = directory; recentDirectories = remember(recentDirectories, directory); }} />
{#if session.group === active?.group && group.indexOf(session) > 0}
<div class="split-gutter" role="separator" aria-label="Resize split terminals" aria-orientation="vertical" onpointerdown={event => resizeSplit(event, session)}></div>
{/if}
</div>
{/each}
{#if !sessions.length}<div class="empty"><p>{loading ? "Detecting terminal profiles…" : "No terminal sessions."}</p><button disabled={loading || !profiles.length} onclick={() => addSession()}>Start a terminal</button></div>{/if}
</div>
{#if sessions.length > 1}
<div class="gutter" role="separator" aria-orientation="vertical" aria-label="Resize terminal list" onpointerdown={resizeRail}></div>
<nav class="rail" aria-label="Terminal list">
{#each sessions as session (session.id)}
<div class="item" data-session={session.id} class:active={session.id === activeId} class:grouped={sessions.filter(item => item.group === session.group).length > 1}>
<button class="pick" aria-pressed={session.id === activeId} title={`${session.title} · ${session.state} · ${session.directory}`} onclick={() => select(session.id)}
onkeydown={event => {
if (event.key === "Delete") { event.preventDefault(); killSession(session.id); }
if (event.key === "ArrowDown" || event.key === "ArrowUp") { event.preventDefault(); const next = sessions[(sessions.indexOf(session) + (event.key === "ArrowDown" ? 1 : sessions.length - 1)) % sessions.length]; activeId = next.id; (event.currentTarget.closest("nav")?.querySelector(`[data-session="${next.id}"] .pick`) as HTMLButtonElement)?.focus(); }
}}><span class="shell-icon" aria-hidden="true">›_</span><span class="session-name">{session.title}<small>{session.state}</small></span></button>
<div class="row-actions">
<IconButton icon="split" label={`Split ${session.title}`} onclick={() => { activeId = session.id; addSession(session.profile, true); }} />
<IconButton icon="trash" label={`Kill ${session.title} (Del)`} onclick={() => killSession(session.id)} />
</div>
</div>
{/each}
</nav>
{/if}
</div>
</div>
{#if picker}<TerminalPicker {...picker} onClose={() => picker = null} />{/if}
{#if showSettings}<TerminalSettings {settings} {profiles} onSave={persist} onClose={() => showSettings = false} />{/if}
<style>
.dock { display: flex; flex-direction: column; height: 100%; min-height: 0; }
.ribbon { display: flex; align-items: center; gap: 10px; flex: 0 0 36px; padding: 0 8px; background: var(--rs-bg-elevated); }
.label { font-size: 13px; color: var(--rs-text-strong); }
.directory { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rs-text-dim); font-size: 12px; }
.actions, .row-actions { display: flex; align-items: center; flex-shrink: 0; }
.single-session { max-width: 130px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--rs-text-dim); margin-right: 6px; }
.body { display: flex; flex: 1; min-height: 0; }
.panes { flex: 1; position: relative; min-width: 0; min-height: 0; }
.pane { display: flex; flex-direction: column; position: absolute; top: 0; bottom: 0; visibility: hidden; min-width: 0; overflow: hidden; }
.pane.shown { visibility: visible; }
.pane :global(.term) { flex: 1; min-height: 0; height: auto; }
.pane-label { flex: 0 0 23px; padding: 3px 10px; font-size: 11px; color: var(--rs-text-dim); border-top: 1px solid transparent; }
.focused .pane-label { color: var(--rs-text-strong); border-top-color: var(--rs-accent); }
.split-gutter { position: absolute; top: 0; bottom: 0; left: 0; width: 4px; cursor: col-resize; background: var(--rs-border); }
.gutter { flex: 0 0 4px; cursor: col-resize; }
.gutter:hover, .split-gutter:hover { background: var(--rs-accent); }
.rail { flex: 0 0 var(--rail); width: var(--rail); overflow: auto; padding: 4px; border-left: 1px solid var(--rs-border); }
.item { display: flex; align-items: center; min-width: 0; border-left: 2px solid transparent; }
.item.grouped { border-left-color: var(--rs-border); }
.item.active { background: var(--rs-bg-active); border-left-color: var(--rs-accent); }
.pick { display: flex; align-items: center; gap: 7px; flex: 1; min-width: 0; border: 0; background: transparent; text-align: left; padding: 5px; }
.shell-icon { color: var(--rs-text-dim); }
.session-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
small { display: block; font-size: 10px; color: var(--rs-text-dim); }
.row-actions { visibility: hidden; }
.item:hover .row-actions, .item:focus-within .row-actions, .item.active .row-actions { visibility: visible; }
.error { padding: 7px 12px; display: flex; align-items: center; gap: 8px; color: var(--rs-error); font-size: 12px; border-bottom: 1px solid var(--rs-border); }
.error span { flex: 1; }
.error button, .empty button { background: var(--rs-bg-active); border: 1px solid var(--rs-border); padding: 4px 8px; }
.empty { padding: 20px; color: var(--rs-text-dim); }
@media (max-width: 700px) { .rail { flex-basis: 150px; width: 150px; } .row-actions { display: none; } .directory, .single-session { display: none; } .label { flex: 1; } }
</style>
+218
View File
@@ -0,0 +1,218 @@
<script lang="ts">
import { listen } from "@tauri-apps/api/event";
import { FitAddon } from "@xterm/addon-fit";
import { Terminal } from "@xterm/xterm";
import { onMount } from "svelte";
import { ptyClose, ptyOpen, ptyResize, ptyWrite } from "$lib/workspace/api";
import { terminalShortcut, type ShellProfile, type TerminalControl, type TerminalSettings } from "$lib/terminal/model";
import "@xterm/xterm/css/xterm.css";
type Props = {
id: string;
cwd: string;
active: boolean;
focused: boolean;
profile: ShellProfile;
directory: string;
settings: TerminalSettings;
onFocus: () => void;
onControl: (control: TerminalControl | null) => void;
onCommand: (command: string) => void;
onDirectory: (directory: string) => void;
onState: (state: string) => void;
};
let { id, cwd, active, focused, profile, directory, settings, onFocus, onControl, onCommand, onDirectory, onState }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let focusTerminal: (() => void) | undefined = $state();
let instance = $state.raw<Terminal>();
let resizeTerminal: (() => void) | undefined;
$effect(() => { if (active && focused && !document.activeElement?.closest(".rail")) focusTerminal?.(); });
$effect(() => {
if (instance) {
instance.options.fontSize = settings.fontSize;
instance.options.scrollback = settings.scrollback;
instance.options.cursorBlink = settings.cursorBlink;
requestAnimationFrame(() => resizeTerminal?.());
}
});
onMount(() => {
if (!host) {
return;
}
const term = new Terminal({
scrollback: settings.scrollback,
fontFamily: "Cascadia Code, Cascadia Mono, Consolas, monospace",
fontSize: settings.fontSize,
cursorBlink: settings.cursorBlink,
allowProposedApi: true,
theme: {
background: "#141414",
foreground: "#e6e6e6",
cursor: "#82aaff",
selectionBackground: "#264f78",
black: "#3b4252",
red: "#bf616a",
green: "#a3be8c",
yellow: "#ebcb8b",
blue: "#81a1c1",
magenta: "#b48ead",
cyan: "#88c0d0",
white: "#e5e9f0",
},
});
const fit = new FitAddon();
term.loadAddon(fit);
term.open(host);
instance = term;
term.attachCustomKeyEventHandler(event => !terminalShortcut(event));
let disposed = false;
let opened = false;
let exited = false;
const pendingInput: string[] = [];
let writes = Promise.resolve();
const unlisteners: (() => void)[] = [];
const fail = (err: unknown) => {
if (!disposed) term.writeln(`\r\n${String(err)}`);
};
const resize = () => {
if (disposed || !host?.clientWidth || !host?.clientHeight) return;
fit.fit();
if (opened && !exited) void ptyResize(id, term.cols, term.rows).catch(fail);
};
resizeTerminal = resize;
focusTerminal = () => { resize(); term.focus(); };
const send = (data: string) => {
if (exited || disposed) return;
if (!opened) { pendingInput.push(data); return; }
writes = writes.then(() => ptyWrite(id, data)).catch(fail);
};
const onData = term.onData(send);
let markers: import("@xterm/xterm").IMarker[] = [];
let prompt: { marker: import("@xterm/xterm").IMarker; column: number } | undefined;
const promptParser = term.parser.registerOscHandler(133, data => {
if (data === "A") {
const marker = term.registerMarker(0);
if (marker) markers = [...markers.filter(item => !item.isDisposed), marker].slice(-1000);
}
if (data === "B") {
prompt?.marker.dispose();
const marker = term.registerMarker(0);
prompt = marker ? { marker, column: term.buffer.active.cursorX } : undefined;
}
return true;
});
const integration = term.parser.registerOscHandler(633, data => {
const separator = data.indexOf(";");
const type = data.slice(0, separator), value = data.slice(separator + 1);
try {
if (type === "Cwd") onDirectory(value);
if (type === "RSCwd" || type === "RSCommand") {
const decoded = new TextDecoder().decode(Uint8Array.from(atob(value), char => char.charCodeAt(0)));
if (type === "RSCwd") onDirectory(decoded); else onCommand(decoded);
}
} catch { /* Ignore malformed shell integration output. */ }
return true;
});
const keys = term.onKey(({ domEvent }) => {
if (profile.kind !== "cmd" || domEvent.key !== "Enter" || !prompt || prompt.marker.isDisposed) return;
const buffer = term.buffer.active;
let command = "";
for (let line = prompt.marker.line; line <= buffer.baseY + buffer.cursorY; line++) {
command += buffer.getLine(line)?.translateToString(true, line === prompt.marker.line ? prompt.column : 0) || "";
}
if (command.trim()) onCommand(command);
prompt.marker.dispose(); prompt = undefined;
});
onControl({
focus: () => { resize(); term.focus(); },
clear: () => { markers.forEach(marker => marker.dispose()); markers = []; term.clear(); term.focus(); },
scrollCommand: direction => {
const lines = markers.filter(marker => !marker.isDisposed).map(marker => marker.line);
const current = term.buffer.active.viewportY;
const target = direction < 0 ? lines.reverse().find(line => line < current) : lines.find(line => line > current);
if (target !== undefined) term.scrollToLine(target); else if (direction > 0) term.scrollToBottom();
},
send: (text, execute = true) => {
if (exited) return;
term.paste(text.replace(/\r?\n/g, "\r"));
if (execute) send("\r");
term.focus();
},
});
const start = async () => {
try {
// Subscribe before spawning: shells and agents can print immediately.
const offData = await listen<{ id: string; data: number[] }>("pty-data", (event) => {
if (!disposed && event.payload.id === id) term.write(new Uint8Array(event.payload.data));
});
unlisteners.push(offData);
if (disposed) return;
const offExit = await listen<{ id: string; code: number | null }>("pty-exit", (event) => {
if (!disposed && event.payload.id === id) {
exited = true;
onState(`Exited${event.payload.code === null ? "" : ` (${event.payload.code})`}`);
term.writeln(`\r\n[Process exited${event.payload.code === null ? "" : ` with code ${event.payload.code}`} ]`);
}
});
unlisteners.push(offExit);
if (disposed) return;
resize();
await ptyOpen(id, term.cols, term.rows, cwd, profile.id, directory);
opened = true;
if (disposed) { await ptyClose(id); return; }
// Includes xterm's replies to startup cursor-position queries.
for (const data of pendingInput.splice(0)) {
writes = writes.then(() => ptyWrite(id, data)).catch(fail);
}
if (!exited) onState("Running");
resize();
if (active && focused) term.focus();
} catch (err) {
fail(err);
if (!disposed) onState("Failed");
} finally {
if (disposed) unlisteners.splice(0).forEach((off) => off());
}
};
void start();
const observer = new ResizeObserver(resize);
observer.observe(host);
return () => {
disposed = true;
focusTerminal = undefined;
instance = undefined;
resizeTerminal = undefined;
onControl(null);
observer.disconnect();
onData.dispose();
promptParser.dispose(); integration.dispose(); keys.dispose();
unlisteners.splice(0).forEach((off) => off());
if (opened) void ptyClose(id).catch(() => {});
term.dispose();
};
});
</script>
<div class="term" data-cwd={directory} bind:this={host} onfocusin={onFocus}></div>
<style>
.term {
height: 100%;
min-height: 0;
padding: 4px;
background: #141414;
}
.term :global(.xterm),
.term :global(.xterm-viewport) {
height: 100%;
}
.term :global(.xterm-viewport) {
/* Whole terminal rows can leave a gap above the bottom edge. */
background-color: transparent;
}
</style>
+29
View File
@@ -0,0 +1,29 @@
<script lang="ts">
import { dialogs, finishText } from "$lib/workspace/dialogs.svelte";
let element: HTMLDialogElement | undefined = $state();
let input: HTMLInputElement | undefined = $state();
$effect(() => {
if (dialogs.text && element && input) {
element.showModal(); input.focus(); input.select();
}
});
</script>
{#if dialogs.text}
<dialog bind:this={element} oncancel={(event) => { event.preventDefault(); finishText(null); }}>
<form onsubmit={(event) => { event.preventDefault(); finishText(dialogs.text?.value.trim() || null); }}>
<label for="text-request">{dialogs.text.title}</label>
<input id="text-request" bind:this={input} bind:value={dialogs.text.value} autocomplete="off" />
<div><button type="button" onclick={() => finishText(null)}>Cancel</button><button type="submit" disabled={!dialogs.text.value.trim()}>Continue</button></div>
</form>
</dialog>
{/if}
<style>
dialog { width: min(480px, 90vw); padding: 22px; background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); }
dialog::backdrop { background: #0008; }
form { display: flex; flex-direction: column; gap: 16px; }
input { width: 100%; background: var(--rs-bg); color: var(--rs-text-strong); border: 1px solid var(--rs-border); padding: 9px; }
form div { display: flex; justify-content: flex-end; gap: 8px; }
button { padding: 6px 12px; background: var(--rs-bg-active); border: 1px solid var(--rs-border); }
</style>
+345
View File
@@ -0,0 +1,345 @@
<script lang="ts">
import type { TreeEntry } from "$lib/workspace/types";
import type { DropTarget } from "$lib/workspace/treeDrop";
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
import { treeFileParts } from "$lib/workspace/chrome";
import TreeNode from "./TreeNode.svelte";
type Props = {
entry: TreeEntry;
childrenMap: Record<string, TreeEntry[]>;
expanded: Set<string>;
activePath: string | null;
selectedPaths: Set<string>;
selectionEdges: ReadonlyMap<string, TreeSelectionEdges>;
renameRel: string | null;
renameDraft: string;
onRenameDraft: (value: string) => void;
onRenameCommit: () => void;
onRenameCancel: () => void;
pins: Set<string>;
bookmarks: Set<string>;
onRowClick: (entry: TreeEntry, modifiers?: SelectionModifiers, newTab?: boolean) => void;
onContextMenu: (entry: TreeEntry, x: number, y: number) => void;
dropTarget: DropTarget | null;
dragRel: string | null;
onDragPointerDown: (entry: TreeEntry, event: PointerEvent) => void;
};
let {
entry,
childrenMap,
expanded,
activePath,
selectedPaths,
selectionEdges,
renameRel,
renameDraft,
onRenameDraft,
onRenameCommit,
onRenameCancel,
pins,
bookmarks,
onRowClick,
onContextMenu,
dropTarget,
dragRel,
onDragPointerDown,
}: Props = $props();
let isOpen = $derived(expanded.has(entry.rel_path));
let isActive = $derived(activePath === entry.rel_path);
let isSelected = $derived(selectedPaths.has(entry.rel_path));
let edges = $derived(selectionEdges.get(entry.rel_path));
let isRenaming = $derived(renameRel === entry.rel_path);
let isDragging = $derived(dragRel === entry.rel_path);
let dropOn = $derived(dropTarget?.rel === entry.rel_path ? dropTarget.place : null);
let nested = $derived(childrenMap[entry.rel_path] ?? []);
let parts = $derived(entry.kind === "file" ? treeFileParts(entry.name) : { label: entry.name, ext: "" });
let ext = $derived(parts.ext);
let label = $derived(parts.label);
function focusSelect(node: HTMLInputElement) {
node.focus();
node.select();
}
function edgeWidth(steps: number | null | undefined) {
if (steps == null) return "100%";
return steps === 0 ? "0px" : `calc(${steps} * var(--tree-indent) + var(--rs-item-selection-width))`;
}
</script>
<li role="none" style:--tree-indent="12px">
<div
class="row"
class:active={isActive}
class:selected={isSelected}
style:--selection-top-width={edgeWidth(edges?.top)}
style:--selection-bottom-width={edgeWidth(edges?.bottom)}
style:--selection-top-left-radius={edges?.top === 0 ? "0px" : "var(--rs-item-selection-radius)"}
style:--selection-top-right-radius={edges?.top == null ? "var(--rs-item-selection-radius)" : "0px"}
style:--selection-bottom-left-radius={edges?.bottom === 0 ? "0px" : "var(--rs-item-selection-radius)"}
style:--selection-bottom-right-radius={edges?.bottom == null ? "var(--rs-item-selection-radius)" : "0px"}
class:folder={entry.kind === "folder"}
class:dragging={isDragging}
class:drop-before={dropOn === "before"}
class:drop-after={dropOn === "after"}
class:drop-inside={dropOn === "inside"}
data-tree-rel={entry.rel_path}
data-tree-kind={entry.kind}
role="treeitem"
tabindex="0"
aria-selected={isSelected}
aria-expanded={entry.kind === "folder" ? isOpen : undefined}
aria-level={entry.rel_path.split("/").length}
onpointerdown={(event) => {
if (event.button === 1) event.preventDefault();
onDragPointerDown(entry, event);
}}
onclick={(event) => onRowClick(entry, event)}
onauxclick={(event) => {
if (event.button !== 1) return;
event.preventDefault();
if (!isRenaming && entry.kind === "file") onRowClick(entry, {}, true);
}}
onkeydown={(event) => {
if (isRenaming) {
return;
}
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
onRowClick(entry, event);
}
}}
oncontextmenu={(event) => {
event.preventDefault();
event.stopPropagation();
onContextMenu(entry, event.clientX, event.clientY);
}}
>
{#if isSelected}
<span class="selection-outline" class:full-top={edges?.top == null} class:full-bottom={edges?.bottom == null} aria-hidden="true">
{#if edges?.top != null && edges.top > 0}<span class="selection-step top"></span>{/if}
{#if edges?.bottom != null && edges.bottom > 0}<span class="selection-step bottom"></span>{/if}
</span>
{/if}
<span class="twist" class:open={isOpen} class:folder={entry.kind === "folder"}></span>
{#if isRenaming}
<input
class="rename"
value={renameDraft}
use:focusSelect
onclick={(event) => event.stopPropagation()}
onpointerdown={(event) => event.stopPropagation()}
oninput={(event) => onRenameDraft(event.currentTarget.value)}
onkeydown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
event.stopPropagation();
onRenameCommit();
}
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
onRenameCancel();
}
}}
onblur={() => onRenameCommit()}
/>
{:else}
<span class="name">{label}</span>
{/if}
{#if ext}
<span class="mark ext">{ext}</span>
{/if}
</div>
{#if entry.kind === "folder" && isOpen}
<ul role="group">
{#each nested as child (child.rel_path)}
<TreeNode
entry={child}
{childrenMap}
{expanded}
{activePath}
{selectedPaths}
{selectionEdges}
{renameRel}
{renameDraft}
{onRenameDraft}
{onRenameCommit}
{onRenameCancel}
{pins}
{bookmarks}
{onRowClick}
{onContextMenu}
{dropTarget}
{dragRel}
{onDragPointerDown}
/>
{/each}
</ul>
{/if}
</li>
<style>
li {
list-style: none;
}
ul {
list-style: none;
margin: 0;
padding: 0 0 0 var(--tree-indent);
}
.row {
position: relative;
display: flex;
align-items: center;
gap: 4px;
width: 100%;
border: 0;
border-radius: var(--rs-control-radius);
background: transparent;
color: var(--rs-text);
text-align: left;
padding: 3px 8px;
cursor: grab;
user-select: none;
}
.row:hover {
background: var(--rs-bg-active);
}
.row.active {
background: var(--rs-bg-active);
color: var(--rs-text-strong);
}
.row.selected {
background-color: var(--rs-item-selection-bg);
border-radius: var(--selection-top-left-radius) var(--selection-top-right-radius)
var(--selection-bottom-right-radius) var(--selection-bottom-left-radius);
color: var(--rs-text-strong);
outline: none;
}
.selection-outline {
position: absolute;
inset: 0;
pointer-events: none;
border: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
border-top: 0;
border-bottom: 0;
border-radius: inherit;
}
.selection-outline.full-top { border-top: var(--rs-item-selection-width) solid var(--rs-item-selection-border); }
.selection-outline.full-bottom { border-bottom: var(--rs-item-selection-width) solid var(--rs-item-selection-border); }
/* Round exposed indentation steps without drawing across shared row edges. */
.selection-step {
position: absolute;
left: calc(-1 * var(--rs-item-selection-width));
height: var(--rs-item-selection-radius);
border-left: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
}
.selection-step.top {
top: 0;
width: var(--selection-top-width);
border-top: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
border-top-left-radius: var(--rs-item-selection-radius);
}
.selection-step.bottom {
bottom: 0;
width: var(--selection-bottom-width);
border-bottom: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
border-bottom-left-radius: var(--rs-item-selection-radius);
}
.row.dragging {
opacity: 0.4;
}
.row.drop-before::before,
.row.drop-after::after {
content: "";
position: absolute;
left: 16px;
right: 8px;
height: 2px;
background: var(--rs-accent);
}
.row.drop-before::before {
top: 0;
}
.row.drop-after::after {
bottom: 0;
}
.row.drop-inside {
outline: 1px solid var(--rs-accent);
background: var(--rs-bg-active);
}
.twist {
width: 14px;
height: 14px;
flex: 0 0 14px;
color: var(--rs-text-strong);
display: inline-flex;
align-items: center;
justify-content: center;
}
.twist.folder::before {
content: "";
width: 0;
height: 0;
border-style: solid;
border-width: 5px 0 5px 8px;
border-color: transparent transparent transparent currentColor;
transform: rotate(0deg);
}
.twist.folder.open::before {
transform: rotate(90deg);
}
.name {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.rename {
flex: 1;
min-width: 0;
height: 20px;
padding: 0 4px;
border: 1px solid var(--rs-accent);
background: var(--rs-bg);
color: var(--rs-text-strong);
}
.folder .name {
color: var(--rs-text-strong);
}
.mark {
margin-left: auto;
font-size: 10px;
letter-spacing: 0.06em;
padding: 1px 5px;
text-transform: uppercase;
color: var(--rs-accent);
background: var(--rs-bg-active);
flex: 0 0 auto;
}
</style>
File diff suppressed because it is too large Load Diff
+158
View File
@@ -0,0 +1,158 @@
<script lang="ts">
import { tick } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import { pickWorkspaceFolder, workspaceRecent } from "$lib/workspace/api";
let { currentRoot, anchor, onOpen }: {
currentRoot?: string; anchor?: HTMLElement;
onOpen: (path: string, name?: string) => Promise<boolean>;
} = $props();
let menu: HTMLDivElement;
let dialog: HTMLDialogElement | undefined = $state();
let input: HTMLInputElement | undefined = $state();
let recent = $state<string[]>([]);
let loading = $state(false);
let busy = $state(false);
let error = $state("");
let creating = $state(false);
let name = $state("");
let parent = $state("");
let returnFocus: HTMLElement | null = null;
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : "Choose where to create your workspace.");
export async function show() {
if (busy || creating) return;
if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
error = ""; loading = true;
menu.showPopover();
position();
menu.querySelector<HTMLButtonElement>("button")?.focus();
try { recent = await workspaceRecent(); }
catch (err) { error = `Could not load recent workspaces: ${String(err)}`; }
finally { loading = false; }
await tick();
if (menu.matches(":popover-open")) { position(); menu.querySelector<HTMLButtonElement>("button")?.focus(); }
}
function position() {
const rect = anchor?.getBoundingClientRect();
menu.style.left = `${Math.max(8, Math.min(rect?.left ?? (innerWidth - menu.offsetWidth) / 2, innerWidth - menu.offsetWidth - 8))}px`;
menu.style.top = `${Math.max(8, (rect?.top ?? (innerHeight + menu.offsetHeight) / 2) - menu.offsetHeight - 8)}px`;
}
function close() { menu.hidePopover(); returnFocus?.focus(); }
async function open(path: string) {
if (busy) return;
if (path === currentRoot) { close(); return; }
busy = true; error = "";
try { if (await onOpen(path)) close(); }
catch (err) { error = `Could not open workspace: ${String(err)}`; }
finally { busy = false; }
}
async function browse() {
if (busy) return;
busy = true; error = "";
try {
const path = await pickWorkspaceFolder();
if (path && await onOpen(path)) close();
} catch (err) { error = String(err); }
finally { busy = false; }
}
async function newWorkspace() {
menu.hidePopover(); error = ""; name = ""; parent = ""; creating = true;
await tick(); dialog?.showModal(); input?.focus();
}
function cancel() { if (!busy) { creating = false; returnFocus?.focus(); } }
async function chooseLocation() {
busy = true; error = "";
try { const path = await pickWorkspaceFolder("Choose a location for the new workspace"); if (path) parent = path; }
catch (err) { error = String(err); }
finally { busy = false; }
}
async function create() {
if (busy || !name.trim() || !parent) return;
busy = true; error = "";
try { if (await onOpen(parent, name.trim())) { creating = false; returnFocus?.focus(); } }
catch (err) { error = String(err); }
finally { busy = false; }
}
function navigate(event: KeyboardEvent) {
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const buttons = [...menu.querySelectorAll<HTMLButtonElement>("button:not(:disabled)")];
const index = buttons.indexOf(document.activeElement as HTMLButtonElement);
const next = event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : (index + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length;
buttons[next]?.focus();
}
</script>
<svelte:window onresize={() => { if (menu?.matches(":popover-open")) position(); }} />
<div bind:this={menu} popover="auto" class="workspace-menu" role="dialog" aria-label="Workspaces" tabindex="-1" onkeydown={navigate}>
<h2>Recent workspaces</h2>
<div class="recent" aria-busy={loading || busy}>
{#if loading}<p>Loading workspaces…</p>
{:else if !recent.length}<p>No recent workspaces yet.</p>{/if}
{#each recent as path}
<button class="workspace-row" class:current={path === currentRoot} aria-current={path === currentRoot ? "true" : undefined} disabled={busy} onclick={() => open(path)}>
<Icon icon="folder-open" />
<span class="details"><span>{folderName(path)}</span><small>{path}</small></span>
{#if path === currentRoot}<span class="current-label">Current</span>{/if}
</button>
{/each}
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer>
<button disabled={busy} onclick={newWorkspace}><Icon icon="folder-plus" /> New workspace…</button>
<button disabled={busy} onclick={browse}><Icon icon="folder-open" /> Open another folder…</button>
</footer>
</div>
{#if creating}
<dialog bind:this={dialog} aria-labelledby="new-workspace-title" oncancel={(event) => { event.preventDefault(); cancel(); }}>
<form onsubmit={(event) => { event.preventDefault(); void create(); }}>
<h2 id="new-workspace-title"><Icon icon="folder-plus" /> New workspace</h2>
<p>Create a folder for your notes and files, then open it in a new window.</p>
<label for="workspace-name">Workspace name</label>
<input id="workspace-name" bind:this={input} bind:value={name} oninput={() => error = ""} placeholder="My workspace" autocomplete="off" required disabled={busy} />
<div class="location-label"><label for="workspace-location">Location</label><button type="button" disabled={busy} onclick={chooseLocation}><Icon icon="folder-open" /> Browse…</button></div>
<input id="workspace-location" value={parent} readonly placeholder="Choose a parent folder" />
<small class="destination">{parent ? "Will create: " : ""}{destination}</small>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="actions"><button type="button" disabled={busy} onclick={cancel}>Cancel</button><button class="primary" type="submit" disabled={busy || !name.trim() || !parent}>{busy ? "Please wait…" : "Create workspace"}</button></div>
</form>
</dialog>
{/if}
<style>
.workspace-menu, dialog { background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); box-shadow: 0 12px 36px #0006; }
.workspace-menu { position: fixed; inset: auto; margin: 0; padding: 6px; width: min(380px, calc(100vw - 16px)); max-height: calc(100vh - 16px); overflow: auto; }
h2 { font-size: 14px; font-weight: 600; margin: 0; padding: 9px 10px; display: flex; align-items: center; gap: 8px; }
p { font-size: 13px; color: var(--rs-text-dim); margin: 8px 10px; }
.recent { max-height: min(360px, 45vh); overflow: auto; padding: 2px; }
button { display: flex; align-items: center; gap: 10px; background: transparent; border: 1px solid transparent; border-radius: var(--rs-control-radius); padding: 9px 10px; color: var(--rs-text); text-align: left; }
button:hover { background: var(--rs-bg-active); }
button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
button:disabled { opacity: .5; }
.workspace-row, footer button { width: 100%; }
.workspace-row.current { background: var(--rs-item-selection-bg); box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); border-radius: var(--rs-item-selection-radius); }
.details { min-width: 0; display: flex; flex: 1; flex-direction: column; gap: 3px; }
small { font-size: 11px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.current-label { font-size: 11px; color: var(--rs-accent); }
footer { border-top: 1px solid var(--rs-border); margin-top: 6px; padding-top: 6px; }
dialog { width: min(480px, calc(100vw - 32px)); padding: 22px; }
dialog::backdrop { background: #0008; }
form { display: flex; flex-direction: column; gap: 12px; }
form h2, form p { padding: 0; margin: 0; }
form label { font-size: 13px; }
input { width: 100%; background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 10px; }
.location-label, .actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
form button { border-color: var(--rs-border); background: var(--rs-bg-active); }
.actions { justify-content: flex-end; margin-top: 8px; }
.primary { border-color: var(--rs-accent); }
.error { color: var(--rs-error); overflow-wrap: anywhere; }
</style>
+16
View File
@@ -0,0 +1,16 @@
export type MenuAction = {
kind: "action";
label: string;
run: () => void;
disabled?: boolean;
};
export type MenuSep = { kind: "sep" };
export type MenuGroup = {
kind: "group";
label: string;
items: MenuItem[];
};
export type MenuItem = MenuAction | MenuSep | MenuGroup;
+43
View File
@@ -0,0 +1,43 @@
<script lang="ts">
import { onMount, tick } from "svelte";
let { title, items, onPick, onClose, empty = "No entries yet." }: {
title: string; items: { label: string; detail?: string; value: string }[];
onPick: (value: string) => void; onClose: () => void; empty?: string;
} = $props();
let query = $state("");
let selected = $state(0);
let dialog: HTMLDialogElement;
let input: HTMLInputElement;
const matches = $derived(items.filter(item => `${item.label} ${item.detail || ""}`.toLowerCase().includes(query.toLowerCase())));
async function pick(value?: string) { if (value !== undefined) { const choose = onPick; onClose(); await tick(); choose(value); } }
onMount(() => { dialog.showModal(); input.focus(); });
</script>
<dialog bind:this={dialog} oncancel={onClose} aria-label={title}>
<header>{title}<button aria-label="Close picker" onclick={onClose}>×</button></header>
<input bind:this={input} bind:value={query} aria-label={title} placeholder="Type to filter…" oninput={() => selected = 0} onkeydown={event => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
}
if (event.key === "Enter") { event.preventDefault(); pick(matches[selected]?.value); }
}} />
<div class="results">
{#each matches as item, index}
<button data-index={index} class:selected={index === selected} onclick={() => pick(item.value)}><span>{item.label}</span>{#if item.detail}<small>{item.detail}</small>{/if}</button>
{/each}
{#if !matches.length}<p>{query ? "No matching entries." : empty}</p>{/if}
</div>
<footer>↑ ↓ select · Enter choose · Esc close</footer>
</dialog>
<style>
dialog { margin-top: 12vh; padding: 0; width: min(640px, 85vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 8px; }
dialog::backdrop { background: #0008; }
header { display: flex; align-items: center; justify-content: space-between; padding: 8px 16px; }
input { width: 100%; padding: 14px; background: var(--rs-bg); color: var(--rs-text-strong); border: 0; }
.results { max-height: 50vh; overflow: auto; padding: 6px; }
button { background: transparent; border: 0; padding: 8px; }
.results button { display: flex; flex-direction: column; width: 100%; text-align: left; gap: 4px; overflow-wrap: anywhere; white-space: pre-wrap; }
button.selected, button:hover { background: var(--rs-bg-active); }
small, footer, p { color: var(--rs-text-dim); }
footer { padding: 10px 14px; border-top: 1px solid var(--rs-border); font-size: 12px; }
</style>
+30
View File
@@ -0,0 +1,30 @@
<script lang="ts">
import { onMount, untrack } from "svelte";
import type { TerminalSettings, ShellProfile } from "./model";
let { settings, profiles, onSave, onClose }: { settings: TerminalSettings; profiles: ShellProfile[]; onSave: (settings: TerminalSettings) => void; onClose: () => void } = $props();
let value = $state(untrack(() => ({ ...settings })));
let dialog: HTMLDialogElement;
onMount(() => dialog.showModal());
</script>
<dialog bind:this={dialog} oncancel={onClose} aria-label="Terminal settings">
<form onsubmit={event => { event.preventDefault(); onSave(value); onClose(); }}>
<h2>Terminal settings</h2>
<label>Default profile<select aria-label="Default profile" bind:value={value.defaultProfile}>{#each profiles.filter(p => p.kind !== "node") as profile}<option value={profile.id}>{profile.title}</option>{/each}</select></label>
<label>Font size<input type="number" min="9" max="28" required bind:value={value.fontSize} /></label>
<label>Scrollback lines<input type="number" min="100" max="100000" step="100" required bind:value={value.scrollback} /></label>
<label class="check"><input type="checkbox" bind:checked={value.cursorBlink} />Blink cursor</label>
<p>Appearance applies to open sessions. The default profile applies to new terminals.</p>
<footer><button type="button" onclick={onClose}>Cancel</button><button type="submit">Save settings</button></footer>
</form>
</dialog>
<style>
dialog { width: min(450px, 90vw); background: var(--rs-bg-elevated); color: var(--rs-text); border: 1px solid var(--rs-border); border-radius: 8px; padding: 24px; }
dialog::backdrop { background: #0008; }
h2 { font-size: 18px; margin: 0 0 8px; }
form { display: flex; flex-direction: column; gap: 16px; }
label { display: flex; flex-direction: column; gap: 6px; }
label.check { flex-direction: row; }
input, select, button { background: var(--rs-bg); color: var(--rs-text); border: 1px solid var(--rs-border); padding: 7px; }
p { color: var(--rs-text-dim); font-size: 12px; margin: 0; }
footer { display: flex; justify-content: flex-end; gap: 8px; }
</style>
+19
View File
@@ -0,0 +1,19 @@
<script lang="ts">
import { getCurrentWindow } from "@tauri-apps/api/window";
import TerminalDock from "$lib/layout/TerminalDock.svelte";
import { terminalShortcut } from "./model";
let { cwd }: { cwd: string } = $props();
let dock: TerminalDock;
let error = $state("");
function keydown(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest("dialog, [role=menu]")) return;
const action = terminalShortcut(event);
if (action && action !== "toggle") { event.preventDefault(); void dock.command(action); }
}
</script>
<svelte:window onkeydown={keydown} />
<div class="window">
{#if error}<p role="alert">{error}</p>{/if}
<TerminalDock bind:this={dock} {cwd} visible standalone onClose={() => void getCurrentWindow().destroy().catch(reason => error = String(reason))} />
</div>
<style>.window { height: 100vh; display: flex; flex-direction: column; }</style>
+70
View File
@@ -0,0 +1,70 @@
export type ShellProfile = { id: string; title: string; kind: "powershell" | "bash" | "cmd" | "node" };
export type TerminalSettings = { defaultProfile: string; fontSize: number; scrollback: number; cursorBlink: boolean };
export type TerminalControl = { focus(): void; clear(): void; scrollCommand(direction: -1 | 1): void; send(text: string, execute?: boolean): void };
export type TerminalTask = { label: string; command: string; profile?: string };
export const defaultSettings: TerminalSettings = { defaultProfile: "", fontSize: 13, scrollback: 10000, cursorBlink: true };
export function readSettings(): TerminalSettings {
try {
const value = JSON.parse(localStorage.getItem("runestone.terminal") || "{}");
return { defaultProfile: typeof value.defaultProfile === "string" ? value.defaultProfile : "",
fontSize: Number.isFinite(value.fontSize) ? Math.min(28, Math.max(9, value.fontSize)) : 13,
scrollback: Number.isFinite(value.scrollback) ? Math.min(100000, Math.max(100, value.scrollback)) : 10000,
cursorBlink: typeof value.cursorBlink === "boolean" ? value.cursorBlink : true };
} catch { return { ...defaultSettings }; }
}
export function quoteShell(value: string, kind: ShellProfile["kind"]): string {
if (/[\r\n\0]/.test(value)) throw new Error("Paths cannot contain line breaks or null characters.");
if (kind === "cmd") {
// Expansion happens even inside cmd quotes. Reject rather than execute a different path.
if (/["%!]/.test(value)) throw new Error("Use PowerShell for paths containing quotes, % or !.");
return `"${value}"`;
}
if (kind === "bash") return `'${value.replaceAll("'", "'\\''")}'`;
return `'${value.replaceAll("'", "''")}'`;
}
export function directoryCommand(path: string, kind: ShellProfile["kind"]): string {
if (kind === "node") return `process.chdir(${JSON.stringify(path)})`;
const normalized = kind === "bash" ? path.replaceAll("\\", "/") : path;
return `${kind === "powershell" ? "Set-Location -LiteralPath" : kind === "cmd" ? "cd /d" : "cd --"} ${quoteShell(normalized, kind)}`;
}
export function fileCommand(path: string, kind: ShellProfile["kind"]): string {
if (kind === "node") throw new Error("Choose a shell terminal to run files. The debug terminal is a Node.js REPL.");
const ext = path.split(".").pop()?.toLowerCase();
const quoted = quoteShell(kind === "bash" ? path.replaceAll("\\", "/") : path, kind);
const runner = ext === "py" ? "python" : ["js", "mjs", "cjs"].includes(ext || "") ? "node"
: ext === "ps1" ? "powershell -NoLogo -File" : ext === "sh" ? "bash" : ext === "rb" ? "ruby"
: ext === "bat" || ext === "cmd" ? "cmd /c" : ext === "exe" ? "" : null;
if (runner === null) throw new Error("No runner for this file type. Use Run Selected Text or configure a task.");
return `${runner || (kind === "powershell" ? "&" : "")}${runner || kind === "powershell" ? " " : ""}${quoted}`;
}
export function parseTasks(text: string): TerminalTask[] {
const value = JSON.parse(text);
if (!Array.isArray(value.tasks)) throw new Error('Tasks must contain a "tasks" array.');
return value.tasks.map((task: unknown) => {
if (!task || typeof task !== "object" || !("label" in task) || typeof task.label !== "string" || !task.label.trim()
|| !("command" in task) || typeof task.command !== "string" || !task.command.trim()
|| ("profile" in task && typeof task.profile !== "string")) throw new Error("Each task needs a label, command, and optional profile ID.");
return task as TerminalTask;
});
}
export function remember(items: string[], value: string): string[] {
return value.trim() ? [value, ...items.filter(item => item !== value)].slice(0, 100) : items;
}
export function terminalShortcut(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "code" | "key">): "toggle" | "new" | "window" | "split" | "previous" | "next" | "commands" | "directories" | null {
if (!event.ctrlKey && !event.metaKey) return null;
if (event.code === "Backquote" || event.key === "`") return event.shiftKey ? event.altKey ? "window" : "new" : "toggle";
if (event.shiftKey && event.code === "Digit5" && !event.altKey) return "split";
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "j") return "toggle";
if (!event.shiftKey && !event.altKey && event.key === "ArrowUp") return "previous";
if (!event.shiftKey && !event.altKey && event.key === "ArrowDown") return "next";
if (!event.shiftKey && event.altKey && event.key.toLowerCase() === "r") return "commands";
if (!event.shiftKey && !event.altKey && event.key.toLowerCase() === "g") return "directories";
return null;
}
+56
View File
@@ -0,0 +1,56 @@
:root {
--rs-control-radius: 5px;
--rs-item-selection-radius: var(--rs-control-radius);
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent);
--rs-item-selection-border: var(--rs-accent);
--rs-item-selection-width: 2px;
--rs-bg: #141414;
--rs-bg-elevated: #1c1c1c;
--rs-bg-active: #2a2a2a;
--rs-border: #2e2e2e;
--rs-text-dim: #9a9a9a;
--rs-text: #e6e6e6;
--rs-text-strong: #f3f3f3;
--rs-accent-2: #89ddff;
--rs-accent: #82aaff;
--rs-accent-dim: #6b8cce;
--rs-accent-deep: #4d6aa8;
--rs-error: #f44747;
--rs-warn-hot: #d68a00;
--rs-warn: #cca700;
--rs-ok: #89d185;
--rs-special: #c792ea;
--rs-font-ui: "Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif;
--rs-font-prose: "Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif;
--rs-font-mono: "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace;
--rs-prose-size: 16px;
--rs-prose-line: 1.65;
--rs-code-size: 13px;
--rs-h1-size: 1.6em;
--rs-h2-size: 1.4em;
--rs-h3-size: 1.25em;
--rs-h4-size: 1.15em;
--rs-h5-size: 1.08em;
--rs-h6-size: 1em;
--rs-selection: #264f78;
--rs-line-highlight: #ffffff0d;
--rs-h1: var(--rs-text-strong);
--rs-h2: var(--rs-text-strong);
--rs-h3: var(--rs-text);
--rs-h4: var(--rs-text);
--rs-h5: var(--rs-text-dim);
--rs-h6: var(--rs-text-dim);
}
[data-theme="light"] {
--rs-bg: #f3f3f3;
--rs-bg-elevated: #ffffff;
--rs-bg-active: #e8e8e8;
--rs-border: #d4d4d4;
--rs-text-dim: #6b6b6b;
--rs-text: #1e1e1e;
--rs-text-strong: #111111;
--rs-selection: #add6ff;
--rs-line-highlight: #0000000d;
}
+121
View File
@@ -0,0 +1,121 @@
<script lang="ts">
import type { IconName } from "./IconButton.svelte";
let { icon }: { icon: IconName } = $props();
</script>
<svg viewBox="0 0 24 24" aria-hidden="true">
{#if icon === "more"}
<circle cx="5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="19" cy="12" r="1" />
{:else if icon === "chevron-down"}
<path d="m6 9 6 6 6-6" />
{:else if icon === "maximize"}
<path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5" />
{:else if icon === "minimize"}
<path d="M5 12h14" />
{:else if icon === "window-maximize"}
<rect x="5" y="5" width="14" height="14" />
{:else if icon === "window-restore"}
<path d="M9 8V4h11v11h-4" /><rect x="4" y="9" width="11" height="11" />
{:else if icon === "restore"}
<path d="M3 8h5V3M21 8h-5V3M16 21v-5h5M3 16h5v5" />
{:else if icon === "split"}
<rect x="3" y="4" width="18" height="16" rx="2" />
<path d="M12 4v16M6 8h3M6 12h3M15 8h3M15 12h3M15 16h3" />
{:else if icon === "text"}
<path d="M4 6h16M4 10h16M4 14h10M4 18h13" />
{:else if icon === "folder-open"}
<path d="M6 14l1.5-2.9A2 2 0 0 1 9.2 10H20a2 2 0 0 1 1.8 2.8l-1.5 3.2A2 2 0 0 1 18.5 17H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h3.7a2 2 0 0 1 1.4.6L10 6h8a2 2 0 0 1 2 2" />
{:else if icon === "file-plus"}
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
<path d="M14 2v6h6" />
<path d="M12 18v-6" />
<path d="M9 15h6" />
{:else if icon === "folder-plus"}
<path d="M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9L9.2 3.9A2 2 0 0 0 7.5 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2z" />
<path d="M12 10v6" />
<path d="M9 13h6" />
{:else if icon === "save"}
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
<path d="M17 21v-8H7v8" />
<path d="M7 3v5h8" />
{:else if icon === "pen"}
<path d="M12 20h9" />
<path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" />
{:else if icon === "code"}
<path d="m16 18 6-6-6-6" />
<path d="m8 6-6 6 6 6" />
{:else if icon === "terminal"}
<path d="M4 5h16v14H4z" />
<path d="m8 9 3 3-3 3" />
<path d="M13 15h4" />
{:else if icon === "eye"}
<path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7Z" />
<circle cx="12" cy="12" r="3" />
{:else if icon === "panel-left"}
<path d="M4 5h16v14H4z" />
<path d="M9 5v14" />
{:else if icon === "panel-right"}
<path d="M4 5h16v14H4z" />
<path d="M15 5v14" />
{:else if icon === "spark"}
<path d="M12 3v4" />
<path d="M12 17v4" />
<path d="M5 12H3" />
<path d="M21 12h-2" />
<path d="m7 7 2 2" />
<path d="m15 15 2 2" />
<path d="m17 7-2 2" />
<path d="m9 15-2 2" />
{:else if icon === "list"}
<path d="M8 6h13" />
<path d="M8 12h13" />
<path d="M8 18h13" />
<path d="M3 6h.01" />
<path d="M3 12h.01" />
<path d="M3 18h.01" />
{:else if icon === "search"}
<circle cx="11" cy="11" r="7" />
<path d="m20 20-3-3" />
{:else if icon === "bookmark"}
<path d="M6 4h12v16l-6-3-6 3z" />
{:else if icon === "files"}
<path d="M4 6h9v14H4z" />
<path d="M8 6V4h9v14h-2" />
{:else if icon === "sort"}
<path d="m3 8 4-4 4 4" />
<path d="M7 4v16" />
<path d="m21 16-4 4-4-4" />
<path d="M17 20V4" />
{:else if icon === "fold"}
<path d="m7 11 5-5 5 5" />
<path d="m7 20 5-5 5 5" />
{:else if icon === "unfold"}
<path d="m7 4 5 5 5-5" />
<path d="m7 13 5 5 5-5" />
{:else if icon === "book-open"}
<path d="M12 7v13" />
<path d="M4 19a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h6a3 3 0 0 1 3 3" />
<path d="M12 7a3 3 0 0 1 3-3h6a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3" />
{:else if icon === "close"}
<path d="M6 6l12 12" />
<path d="M18 6l-12 12" />
{:else if icon === "trash"}
<path d="M4 7h16" />
<path d="M9 7V5h6v2" />
<path d="M6 7l1 13h10l1-13" />
{:else if icon === "plus"}
<path d="M12 5v14" />
<path d="M5 12h14" />
{/if}
</svg>
<style>
svg {
width: 16px;
height: 16px;
flex: 0 0 16px;
fill: none;
stroke: currentColor;
stroke-width: 1.6;
stroke-linecap: round;
stroke-linejoin: round;
}
</style>
+140
View File
@@ -0,0 +1,140 @@
<script lang="ts">
import { onDestroy } from "svelte";
import Icon from "./Icon.svelte";
export type IconName =
| "split"
| "more"
| "chevron-down"
| "maximize"
| "minimize"
| "window-maximize"
| "window-restore"
| "restore"
| "text"
| "folder-open"
| "file-plus"
| "folder-plus"
| "save"
| "pen"
| "code"
| "terminal"
| "eye"
| "panel-left"
| "panel-right"
| "spark"
| "list"
| "search"
| "bookmark"
| "files"
| "sort"
| "fold"
| "unfold"
| "book-open"
| "close"
| "trash"
| "plus";
type Props = {
icon: IconName;
label: string;
active?: boolean;
disabled?: boolean;
onclick?: () => void;
side?: "bottom" | "right";
type?: "button" | "submit";
};
let { icon, label, active, disabled = false, onclick, side = "bottom", type = "button" }: Props = $props();
const tooltipId = $props.id();
let button: HTMLButtonElement;
let tooltip: HTMLSpanElement;
let showTip = $state(false);
let timer: ReturnType<typeof setTimeout> | undefined;
function onLeave() {
clearTimeout(timer);
showTip = false;
if (tooltip?.matches(":popover-open")) tooltip.hidePopover();
}
function onEnter() {
clearTimeout(timer);
timer = setTimeout(() => {
if (!button?.isConnected || disabled) return;
const bounds = button.getBoundingClientRect();
tooltip.showPopover();
const tip = tooltip.getBoundingClientRect();
let left = side === "right" ? bounds.right + 8 : bounds.left + (bounds.width - tip.width) / 2;
let top = side === "right" ? bounds.top + (bounds.height - tip.height) / 2 : bounds.bottom + 8;
if (top + tip.height > innerHeight - 8) top = bounds.top - tip.height - 8;
left = Math.max(8, Math.min(left, innerWidth - tip.width - 8));
tooltip.style.left = `${left}px`;
tooltip.style.top = `${Math.max(8, top)}px`;
showTip = true;
}, 300);
}
onDestroy(() => clearTimeout(timer));
</script>
<svelte:window onresize={onLeave} onkeydown={(event) => { if (event.key === "Escape") onLeave(); }} />
<button
bind:this={button}
class="icon-btn"
class:active
{type}
{disabled}
aria-label={label}
aria-pressed={active}
aria-describedby={showTip ? tooltipId : undefined}
onclick={() => { onLeave(); onclick?.(); }}
onmouseenter={onEnter}
onmouseleave={onLeave}
onfocus={onEnter}
onblur={onLeave}
>
<Icon {icon} />
</button>
<span bind:this={tooltip} id={tooltipId} class="tip" popover="manual" role="tooltip">{label}</span>
<style>
.icon-btn {
position: relative;
width: 28px;
flex: 0 0 28px;
border-radius: var(--rs-control-radius);
height: 28px;
padding: 0;
border: 1px solid transparent;
background: transparent;
color: var(--rs-text-dim);
display: inline-flex;
align-items: center;
justify-content: center;
}
.icon-btn:hover,
.icon-btn.active {
background: var(--rs-bg-active);
border-color: var(--rs-border);
color: var(--rs-accent);
}
.tip {
position: fixed;
inset: auto;
margin: 0;
max-width: min(280px, calc(100vw - 16px));
white-space: pre-line;
text-align: left;
background: var(--rs-bg-active);
border: 1px solid var(--rs-border);
border-radius: 6px;
box-shadow: 0 4px 16px #0005;
color: var(--rs-text-strong);
padding: 6px 10px;
font: 12px/1.5 var(--rs-font-ui);
pointer-events: none;
}
</style>
+190
View File
@@ -0,0 +1,190 @@
<script lang="ts">
import { onDestroy, tick } from "svelte";
import Icon from "./Icon.svelte";
import type { IconName } from "./IconButton.svelte";
type Option = { value: string; label: string; icon: IconName };
let { label, options, value, onchange, shortcut = "" }: {
label: string;
options: Option[];
value: string;
onchange: (value: string) => void;
shortcut?: string;
} = $props();
let expanded = $state(false);
let tooltipDismissed = $state(false);
let hovered = false;
let keyboardFocus = false;
let group: HTMLDivElement;
let timer: ReturnType<typeof setTimeout> | undefined;
const expansionDelay = 1500;
const selected = $derived(Math.max(0, options.findIndex(option => option.value === value)));
function scheduleExpansion() {
clearTimeout(timer);
if (!expanded && (hovered || keyboardFocus)) {
timer = setTimeout(() => { expanded = true; }, expansionDelay);
}
}
function collapse() {
clearTimeout(timer);
expanded = false;
}
function leave() {
hovered = false;
if (!keyboardFocus) collapse();
}
async function choose(index: number) {
// Cycling should leave a full pause before the targets start moving.
scheduleExpansion();
const hadFocus = group.contains(document.activeElement);
onchange(options[index].value);
await tick();
// A compact click changes which button is visible; carry focus with it.
if (hadFocus) group.querySelector<HTMLButtonElement>(`[data-value="${options[index].value}"]`)?.focus({ preventScroll: true });
}
function keydown(event: KeyboardEvent) {
keyboardFocus = true;
if (event.key === "Enter" || event.key === " ") clearTimeout(timer);
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
tooltipDismissed = true;
collapse();
group.querySelector<HTMLButtonElement>(`[data-value="${value}"]`)?.focus();
} else if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) {
event.preventDefault();
clearTimeout(timer);
expanded = true;
const index = event.key === "Home" ? 0 : event.key === "End" ? options.length - 1
: (selected + (event.key === "ArrowRight" ? 1 : -1) + options.length) % options.length;
void choose(index);
}
}
onDestroy(() => clearTimeout(timer));
</script>
<div
bind:this={group}
class="mode-switcher"
class:expanded
class:tooltip-dismissed={tooltipDismissed}
role="group"
aria-label={label}
style:--count={expanded ? options.length : 1}
style:--selected={expanded ? selected : 0}
onmouseenter={() => { hovered = true; scheduleExpansion(); }}
onmouseleave={leave}
onfocusin={(event) => {
if ((event.target as HTMLElement).matches(":focus-visible") && !group.contains(event.relatedTarget as Node)) {
keyboardFocus = true;
scheduleExpansion();
}
}}
onfocusout={(event) => {
if (!group.contains(event.relatedTarget as Node)) {
keyboardFocus = false;
if (!hovered) collapse();
}
}}
>
<span class="selection" aria-hidden="true"></span>
{#each options as option, index (option.value)}
<button
type="button"
class:current={option.value === value}
class:concealed={!expanded && option.value !== value}
style:--index={expanded ? index : 0}
data-value={option.value}
aria-label={option.label}
aria-pressed={option.value === value}
tabindex={expanded || option.value === value ? 0 : -1}
onmouseenter={() => { tooltipDismissed = false; }}
onfocus={() => { tooltipDismissed = false; }}
onpointerdown={() => { keyboardFocus = false; clearTimeout(timer); }}
onpointerup={scheduleExpansion}
onpointercancel={scheduleExpansion}
onkeydown={keydown}
onkeyup={(event) => { if (event.key === "Enter" || event.key === " ") scheduleExpansion(); }}
onclick={() => void choose(expanded ? index : (selected + 1) % options.length)}
>
<Icon icon={option.icon} />
<span class="tooltip" role="tooltip" aria-hidden="true">{option.label}{shortcut}</span>
</button>
{/each}
</div>
<style>
.mode-switcher {
--segment: 32px;
position: relative;
flex: 0 0 auto;
width: calc(var(--segment) * var(--count) + 6px);
height: 34px;
border: 1px solid var(--rs-border);
border-radius: 8px;
transition: width 180ms ease;
}
.selection {
position: absolute;
inset: 2px auto 2px 2px;
width: var(--segment);
border-radius: 5px;
background: var(--rs-bg-active);
transform: translateX(calc(var(--selected) * var(--segment)));
transition: transform 180ms ease;
pointer-events: none;
}
button {
position: absolute;
top: 2px;
left: 2px;
width: var(--segment);
height: 28px;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
border: 0;
border-radius: 5px;
background: transparent;
color: var(--rs-text-dim);
font-size: 12px;
transform: translateX(calc(var(--index) * var(--segment)));
transition: transform 180ms ease, opacity 120ms ease;
}
button.current { color: var(--rs-accent); }
button:hover { color: var(--rs-text-strong); }
button.concealed { visibility: hidden; opacity: 0; pointer-events: none; }
button:hover, button:focus-visible { z-index: 1; }
.tooltip {
position: absolute;
top: calc(100% + 9px);
right: 0;
padding: 6px 10px;
border: 1px solid var(--rs-border);
border-radius: 6px;
background: var(--rs-bg-active);
box-shadow: 0 4px 16px #0005;
color: var(--rs-text-strong);
font: 12px/1.5 var(--rs-font-ui);
white-space: nowrap;
pointer-events: none;
visibility: hidden;
opacity: 0;
}
.mode-switcher:not(.tooltip-dismissed) button:not(.concealed):is(:hover, :focus-visible) .tooltip {
visibility: visible;
opacity: 1;
transition: opacity 120ms ease 200ms, visibility 0s linear 200ms;
}
@media (prefers-reduced-motion: reduce) {
.mode-switcher, .selection, button { transition: none; }
}
</style>
+61
View File
@@ -0,0 +1,61 @@
<script lang="ts">
import { onMount } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window";
import IconButton from "./IconButton.svelte";
let { onError }: { onError: (message: string) => void } = $props();
let maximized = $state(false);
const appWindow = getCurrentWindow();
async function syncMaximized() {
maximized = await appWindow.isMaximized();
}
async function run(action: "minimize" | "toggleMaximize" | "close") {
try {
// close() emits the close request handled by the workbench's unsaved-edits guard.
await appWindow[action]();
if (action === "toggleMaximize") await syncMaximized();
} catch (error) { onError(String(error)); }
}
onMount(() => {
let disposed = false;
let unlisten: (() => void) | undefined;
void syncMaximized().catch(error => onError(String(error)));
void appWindow.onResized(() => {
void syncMaximized().catch(error => onError(String(error)));
}).then(off => {
if (disposed) off(); else unlisten = off;
}).catch(error => onError(String(error)));
return () => { disposed = true; unlisten?.(); };
});
</script>
<div class="window-controls" role="group" aria-label="Window controls">
<IconButton icon="minimize" label="Minimize window" onclick={() => void run("minimize")} />
<IconButton icon={maximized ? "window-restore" : "window-maximize"}
label={maximized ? "Restore window" : "Maximize window"} onclick={() => void run("toggleMaximize")} />
<div class="window-close">
<IconButton icon="close" label="Close window" onclick={() => void run("close")} />
</div>
</div>
<style>
.window-controls {
display: flex;
align-self: stretch;
flex-shrink: 0;
margin-left: 8px;
border-left: 1px solid var(--rs-border);
}
.window-close { display: flex; }
.window-controls :global(.icon-btn) {
width: 40px;
flex-basis: 40px;
height: 100%;
border: 0;
border-radius: 0;
}
.window-close :global(.icon-btn:hover) { background: #c42b1c; color: white; }
</style>
+63
View File
@@ -0,0 +1,63 @@
// Stroke icons share the same 24px grid and weight as IconButton.
export const actionIcons = {
rename: '<path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z"/>',
'zoom-in': '<circle cx="10" cy="10" r="7"/><path d="m15 15 6 6M7 10h6M10 7v6"/>',
'zoom-out': '<circle cx="10" cy="10" r="7"/><path d="m15 15 6 6M7 10h6"/>',
close: '<path d="m6 6 12 12M6 18 18 6"/>',
swap: '<path d="M3 7h18m-4-4 4 4-4 4M21 17H3m4-4-4 4 4 4"/>',
bullet: '<path d="M9 5h12M9 12h12M9 19h12"/><circle cx="3" cy="5" r="1"/><circle cx="3" cy="12" r="1"/><circle cx="3" cy="19" r="1"/>',
number: '<path d="M10 5h11M10 12h11M10 19h11M3 3h2v6M3 9h4M3 14c4-3 5 1 2 3l-2 3h4"/>',
task: '<path d="M20 12v8H4V4h10M9 10l4 4 8-11"/>',
heading: '<path d="M5 4v16M19 4v16M5 12h14"/>',
quote: '<path d="M3 4h7v9c0 4-2 6-6 7v-3c2-1 3-2 3-4H3ZM14 4h7v9c0 4-2 6-6 7v-3c2-1 3-2 3-4h-4Z"/>',
table: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18M15 3v18"/>',
rule: '<path d="M4 12h16"/>',
footnote: '<path d="M4 4h9v16H4ZM7 8h3M7 12h3M16 4l2-1v6M16 9h4"/>',
cut: '<circle cx="6" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="m8 8 12 12M8 16 20 4"/>',
copy: '<rect x="8" y="8" width="12" height="13" rx="2"/><path d="M16 8V3H3v13h5"/>',
paste: '<rect x="5" y="5" width="14" height="16" rx="2"/><rect x="9" y="2" width="6" height="5" rx="1"/><path d="m9 14 2 2 4-4"/>',
'paste-text': '<rect x="5" y="5" width="14" height="16" rx="2"/><path d="M9 5V2h6v3M8 11h8M12 11v7"/>',
format: '<path d="m14 3 7 7-10 10H4v-7ZM11 6l7 7M3 21h18"/>',
bold: '<path d="M6 4h7a4 4 0 0 1 0 8H6zm0 8h8a4 4 0 0 1 0 8H6z"/>',
italic: '<path d="M10 4h10M4 20h10M15 4 9 20"/>',
strike: '<path d="M17 5c-2-3-10-3-10 2 0 2 2 3 5 4M7 19c3 3 10 2 10-2 0-2-2-3-5-4M3 12h18"/>',
highlight: '<path d="m15 3 6 6-9 9-6-6ZM6 12l-3 6 3 3 6-3M3 21h12"/>',
code: '<path d="m7 6-5 6 5 6m10-12 5 6-5 6M14 3l-4 18"/>',
math: '<path d="M19 4H5l7 8-7 8h14"/>',
comment: '<circle cx="6" cy="6" r="3"/><circle cx="18" cy="18" r="3"/><path d="M4 20 20 4"/>',
clear: '<path d="m14 3 7 7-11 11H6l-5-5ZM7 10l7 7M13 21h9"/>',
left: '<path d="M3 5h18M3 10h12M3 15h18M3 20h12"/>',
center: '<path d="M3 5h18M6 10h12M3 15h18M6 20h12"/>',
right: '<path d="M3 5h18M9 10h12M3 15h18M9 20h12"/>',
row: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18M15 3v18"/><path d="M4 10h16v4H4Z" fill="currentColor" opacity=".25"/>',
column: '<rect x="3" y="3" width="18" height="18" rx="2"/><path d="M3 9h18M3 15h18M9 3v18M15 3v18"/><path d="M10 4h4v16h-4Z" fill="currentColor" opacity=".25"/>',
'row-before': '<rect x="3" y="10" width="18" height="11" rx="2"/><path d="M3 15h18M12 2v6M9 5h6"/>',
'row-after': '<rect x="3" y="3" width="18" height="11" rx="2"/><path d="M3 8h18M12 16v6M9 19h6"/>',
'column-before': '<rect x="10" y="3" width="11" height="18" rx="2"/><path d="M15 3v18M2 12h6M5 9v6"/>',
'column-after': '<rect x="3" y="3" width="11" height="18" rx="2"/><path d="M8 3v18M16 12h6M19 9v6"/>',
up: '<path d="M12 21V3m-7 7 7-7 7 7"/>',
down: '<path d="M12 3v18m-7-7 7 7 7-7"/>',
'move-left': '<path d="M21 12H3m7-7-7 7 7 7"/>',
'move-right': '<path d="M3 12h18m-7-7 7 7-7 7"/>',
trash: '<path d="M3 6h18M9 6V3h6v3M5 6l1 15h12l1-15M10 10v7M14 10v7"/>',
'sort-asc': '<path d="M5 3v18m-3-3 3 3 3-3M12 4h4M12 9h6M12 14h8M12 19h10"/>',
'sort-desc': '<path d="M5 3v18m-3-3 3 3 3-3M12 4h10M12 9h8M12 14h6M12 19h4"/>',
link: '<path d="m10 13 4-4M8 16l-2 2a4 4 0 0 1-6-6l5-5a4 4 0 0 1 6 0m2 1 2-2a4 4 0 0 1 6 6l-5 5a4 4 0 0 1-6 0" transform="translate(1 0)"/>',
external: '<path d="M14 3h7v7M10 14 21 3M10 5H4v16h16v-7"/>',
search: '<circle cx="10" cy="10" r="7"/><path d="m15 15 6 6"/>',
extract: '<path d="M11 4H4v16h16v-7M14 3h7v7M11 13 21 3"/><path d="M7 8h2M7 12h2M7 16h7"/>',
select: '<path d="M8 3H3v5M16 3h5v5M21 16v5h-5M8 21H3v-5M3 11v2M21 11v2M11 3h2M11 21h2"/>',
paragraph: '<path d="M13 21V3h-3a5 5 0 0 0 0 10h3M18 3v18M10 3h12"/>',
insert: '<path d="M3 5h18M3 11h8M3 17h8M17 11v10M12 16h10"/>',
chevron: '<path d="m9 5 7 7-7 7"/>',
plus: '<path d="M12 5v14M5 12h14"/>',
grip: '<circle cx="8" cy="5" r="1"/><circle cx="16" cy="5" r="1"/><circle cx="8" cy="12" r="1"/><circle cx="16" cy="12" r="1"/><circle cx="8" cy="19" r="1"/><circle cx="16" cy="19" r="1"/>',
} as const;
export type ActionIcon = keyof typeof actionIcons;
export function actionIcon(name: ActionIcon): SVGSVGElement {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("aria-hidden", "true");
svg.classList.add("action-icon"); svg.innerHTML = actionIcons[name];
return svg;
}
+66
View File
@@ -0,0 +1,66 @@
import { actionIcon, type ActionIcon } from "./actionIcons";
export type ActionMenuItem = { label: string; icon: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; title?: string } | { separator: true };
export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClose: () => void, label = "Table actions") {
const root = document.createElement("div"); root.className = "table-cell-menu"; root.setAttribute("role", "menu"); root.setAttribute("aria-label", label);
let opened: HTMLElement | undefined, owner: HTMLButtonElement | undefined;
if (label.startsWith("Terminal")) root.style.width = "min(430px, calc(100vw - 16px))";
const submenus = new Map<HTMLButtonElement, HTMLElement>();
function hideSubmenu() { if (opened) opened.hidden = true; owner?.setAttribute("aria-expanded", "false"); opened = undefined; owner = undefined; }
function positionSubmenu(button: HTMLButtonElement, panel: HTMLElement) {
const rect = button.getBoundingClientRect(), size = panel.getBoundingClientRect(), main = root.getBoundingClientRect();
panel.style.left = `${Math.max(8, main.right + size.width < innerWidth - 8 ? main.right - 2 : main.left - size.width + 2)}px`;
panel.style.top = `${Math.max(8, Math.min(rect.top - 5, innerHeight - size.height - 8))}px`;
}
function reveal(button: HTMLButtonElement, panel: HTMLElement, focus = false) {
if (opened !== panel) hideSubmenu();
opened = panel; owner = button; panel.hidden = false; button.setAttribute("aria-expanded", "true");
positionSubmenu(button, panel);
if (focus) panel.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus({ preventScroll: true });
}
function populate(panel: HTMLElement, entries: ActionMenuItem[]) {
for (const item of entries) {
if ("separator" in item) { const hr = document.createElement("hr"); hr.setAttribute("role", "separator"); panel.append(hr); continue; }
const button = document.createElement("button"); button.type = "button"; button.setAttribute("role", "menuitem"); button.disabled = !!item.disabled;
if (item.title) button.title = item.title;
const label = document.createElement("span"); label.className = "action-label"; label.textContent = item.label;
button.append(actionIcon(item.icon), label); panel.append(button);
if (item.shortcut) { const shortcut = document.createElement("span"); shortcut.textContent = item.shortcut; shortcut.style.cssText = "margin-left:auto;color:var(--rs-text-dim);font-size:12px;white-space:nowrap"; button.append(shortcut); }
if (item.children) {
button.setAttribute("aria-haspopup", "menu"); button.setAttribute("aria-expanded", "false");
const arrow = actionIcon("chevron"); arrow.classList.add("action-chevron"); button.append(arrow);
const submenu = document.createElement("div"); submenu.className = "table-cell-submenu"; submenu.setAttribute("role", "menu"); submenu.setAttribute("aria-label", item.label); submenu.hidden = true;
populate(submenu, item.children); root.append(submenu); submenus.set(button, submenu);
button.addEventListener("mousemove", () => { if (!button.disabled) reveal(button, submenu); });
button.addEventListener("click", () => reveal(button, submenu, true));
} else {
if (panel === root) button.addEventListener("mousemove", hideSubmenu);
button.addEventListener("click", event => { event.stopPropagation(); item.run?.(); });
}
}
}
populate(root, items);
root.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); });
root.addEventListener("focusin", event => {
const button = event.target as HTMLElement;
if (button.parentElement === root && button !== owner) hideSubmenu();
});
root.addEventListener("keydown", event => {
event.stopPropagation();
if (event.key === "Escape" || event.key === "Tab") { event.preventDefault(); onClose(); return; }
const focused = document.activeElement as HTMLButtonElement, panel = focused.parentElement || root;
const buttons = [...panel.querySelectorAll<HTMLButtonElement>(":scope > button:not(:disabled)")], index = buttons.indexOf(focused);
if (["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) {
event.preventDefault(); buttons[event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : (index + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length]?.focus();
}
if (event.key === "ArrowRight" && submenus.has(focused)) { event.preventDefault(); reveal(focused, submenus.get(focused)!, true); }
if (event.key === "ArrowLeft" && opened?.contains(focused)) { event.preventDefault(); const previous = owner; hideSubmenu(); previous?.focus(); }
});
root.addEventListener("scroll", event => { if (event.target === root && opened && owner) positionSubmenu(owner, opened); });
document.body.append(root);
root.style.left = `${Math.max(8, Math.min(x, innerWidth - root.offsetWidth - 8))}px`;
root.style.top = `${Math.max(8, Math.min(y, innerHeight - root.offsetHeight - 8))}px`;
root.querySelector<HTMLButtonElement>(":scope > button:not(:disabled)")?.focus();
return root;
}
+128
View File
@@ -0,0 +1,128 @@
import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { open as openDialog } from "@tauri-apps/plugin-dialog";
import type { TreeEntry, WorkspaceEvent, WorkspaceInfo } from "./types";
export async function pickWorkspaceFolder(title = "Open workspace"): Promise<string | null> {
const selected = await openDialog({
directory: true,
multiple: false,
title,
});
if (selected === null || Array.isArray(selected)) {
return null;
}
return selected;
}
export function workspaceOpen(path: string): Promise<WorkspaceInfo> {
return invoke("workspace_open", { path });
}
export function workspaceOpenWindow(path: string): Promise<void> {
return invoke("workspace_open_window", { path });
}
export function workspaceLastPath(): Promise<string | null> {
return invoke("workspace_last_path");
}
export function workspaceRecent(): Promise<string[]> {
return invoke("workspace_recent");
}
export function workspaceNew(parent: string, name: string): Promise<void> {
return invoke("workspace_new", { parent, name });
}
export function workspaceList(rel: string): Promise<TreeEntry[]> {
return invoke("workspace_list", { rel });
}
export function workspaceRead(rel: string): Promise<string> {
return invoke("workspace_read", { rel });
}
export function workspaceWrite(rel: string, contents: string, expected?: string): Promise<void> {
return invoke("workspace_write", { rel, contents, expected });
}
export function workspaceCreate(rel: string, kind: "file" | "folder"): Promise<void> {
return invoke("workspace_create", { rel, kind });
}
export function workspaceRename(from: string, to: string): Promise<void> {
return invoke("workspace_rename", { from, to });
}
export function workspaceDelete(rel: string): Promise<void> {
return invoke("workspace_delete", { rel });
}
export function workspaceReadDataUrl(rel: string): Promise<string> {
return invoke("workspace_read_data_url", { rel });
}
export function workspaceWriteBytes(rel: string, base64: string): Promise<void> {
return invoke("workspace_write_bytes", { rel, base64 });
}
export type CopyResult = {
name: string;
rel_path: string;
kind: "file" | "folder";
};
export function workspaceCopy(rel: string): Promise<CopyResult> {
return invoke("workspace_copy", { rel });
}
export function workspaceAbsPath(rel: string): Promise<string> {
return invoke("workspace_abs_path", { rel });
}
export function workspaceReveal(rel: string): Promise<void> {
return invoke("workspace_reveal", { rel });
}
export type SearchHit = {
rel_path: string;
line: number;
text: string;
};
export function workspaceSearch(query: string): Promise<SearchHit[]> {
return invoke("workspace_search", { query });
}
export function ptyOpen(id: string, cols: number, rows: number, cwd: string, profile?: string, directory?: string): Promise<void> {
return invoke("pty_open", { id, cols, rows, cwd, profile, directory });
}
export function ptyProfiles(): Promise<import("$lib/terminal/model").ShellProfile[]> {
return invoke("pty_profiles");
}
export function ptyNewWindow(): Promise<void> {
return invoke("pty_new_window", { id: crypto.randomUUID() });
}
export function ptyDictation(): Promise<void> { return invoke("pty_dictation"); }
export function ptyWrite(id: string, data: string): Promise<void> {
return invoke("pty_write", { id, data });
}
export function ptyResize(id: string, cols: number, rows: number): Promise<void> {
return invoke("pty_resize", { id, cols, rows });
}
export function ptyClose(id: string): Promise<void> {
return invoke("pty_close", { id });
}
export function onWorkspaceEvent(
handler: (event: WorkspaceEvent) => void,
): Promise<UnlistenFn> {
return listen<WorkspaceEvent>("workspace-event", (event) => {
handler(event.payload);
});
}
+27
View File
@@ -0,0 +1,27 @@
import type { Chrome } from "./types";
const WRITING_EXT = new Set(["md", "markdown", "mdown", "txt"]);
export function extensionOf(relPath: string): string {
const base = relPath.split("/").pop() ?? relPath;
const dot = base.lastIndexOf(".");
if (dot <= 0) {
return "";
}
return base.slice(dot + 1).toLowerCase();
}
export function treeFileParts(name: string): { label: string; ext: string } {
const ext = extensionOf(name);
if (!ext || !name.toLowerCase().endsWith(`.${ext}`)) {
return { label: name, ext: "" };
}
return { label: name.slice(0, name.length - ext.length - 1), ext };
}
export function detectChrome(relPath: string): Chrome {
if (WRITING_EXT.has(extensionOf(relPath))) {
return "Writing";
}
return "Ide";
}
+34
View File
@@ -0,0 +1,34 @@
let engine: Promise<typeof import("mermaid").default> | undefined;
let sequence = 0;
function loadMermaid() {
return engine ??= import("mermaid").then(({ default: mermaid }) => {
mermaid.initialize({ startOnLoad: false, securityLevel: "strict", theme: "dark", suppressErrorRendering: true });
return mermaid;
}).catch(error => { engine = undefined; throw error; });
}
export async function renderDiagrams(root: HTMLElement, cancelled: () => boolean) {
if (cancelled()) return;
const diagrams = [...root.querySelectorAll<HTMLElement>(".md-mermaid")];
if (!diagrams.length) return;
for (const block of diagrams) {
const target = block.querySelector<HTMLElement>(".md-diagram");
const source = block.querySelector("code")?.textContent ?? "";
if (!target || target.dataset.rendered) continue;
target.dataset.rendered = "pending";
try {
const mermaid = await loadMermaid();
if (!block.isConnected) continue;
const { svg } = await mermaid.render(`rs-diagram-${++sequence}`, source);
if (!block.isConnected) continue;
target.innerHTML = svg;
target.dataset.rendered = "true";
} catch {
if (!block.isConnected) continue;
target.textContent = "Diagram could not render. Check the Mermaid source below.";
target.setAttribute("role", "status");
block.querySelector("details")?.setAttribute("open", "");
}
}
}
+13
View File
@@ -0,0 +1,13 @@
type TextRequest = { title: string; value: string; resolve: (value: string | null) => void };
export const dialogs = $state<{ text: TextRequest | null }>({ text: null });
export function requestText(title: string, value = ""): Promise<string | null> {
dialogs.text?.resolve(null);
return new Promise(resolve => { dialogs.text = { title, value, resolve }; });
}
export function finishText(value: string | null) {
const request = dialogs.text;
dialogs.text = null;
request?.resolve(value);
}
+191
View File
@@ -0,0 +1,191 @@
import type { OpenBuffer, TreeEntry } from "./types";
export type DocumentIO = {
read: (path: string) => Promise<string>;
write: (path: string, contents: string, expected: string) => Promise<void>;
image: (path: string) => Promise<string>;
kind: (path: string) => "image" | "text";
chrome: (path: string) => OpenBuffer["chrome"];
};
/** One workspace's documents. UI components never own the saved baseline. */
export class Documents {
buffers: OpenBuffer[] = [];
activePath: string | null = null;
private opening = new Map<string, Promise<void>>();
private saving = new Map<string, Promise<void>>();
private selection = 0;
private refreshVersion = 0;
private disposed = false;
private io: DocumentIO;
private changed: () => void;
constructor(io: DocumentIO, changed: () => void) { this.io = io; this.changed = changed; }
dispose() { this.disposed = true; this.selection++; this.refreshVersion++; }
get dirty() { return this.buffers.some(b => b.contents !== b.saved); }
get active() { return this.buffers.find(b => b.relPath === this.activePath); }
private emit() { if (!this.disposed) this.changed(); }
select(path: string) {
this.selection++;
if (this.buffers.some(b => b.relPath === path)) { this.activePath = path; this.emit(); }
}
newTab() {
if (this.disposed) return;
this.selection++;
const id = crypto.randomUUID();
// Empty tabs have an identity but no corresponding workspace file.
const relPath = `empty:${id}`;
this.buffers.push({
id, relPath, name: "New tab", kind: "empty", imageUrl: null,
contents: "", saved: "", chrome: "Writing", chromeOverride: null,
});
this.activePath = relPath;
this.emit();
}
async open(entry: TreeEntry, target: "current" | "new" = "new") {
const request = ++this.selection;
const previous = target === "current" || this.active?.kind === "empty" ? this.active : undefined;
const alreadyOpen = this.buffers.some(b => b.relPath === entry.rel_path);
if (!this.buffers.some(b => b.relPath === entry.rel_path)) {
let pending = this.opening.get(entry.rel_path);
if (!pending) {
pending = (async () => {
const kind = this.io.kind(entry.rel_path);
const value = await (kind === "image" ? this.io.image(entry.rel_path) : this.io.read(entry.rel_path));
if (this.disposed) return;
this.buffers.push({
id: crypto.randomUUID(), relPath: entry.rel_path, name: entry.name,
kind, imageUrl: kind === "image" ? value : null,
contents: kind === "text" ? value : "", saved: kind === "text" ? value : "",
chrome: this.io.chrome(entry.rel_path), chromeOverride: null,
});
this.emit();
})();
this.opening.set(entry.rel_path, pending);
}
try { await pending; } finally { this.opening.delete(entry.rel_path); }
}
if (!this.disposed && request === this.selection) {
// Replace only after a successful read, and never discard edits or disk conflicts.
if (!alreadyOpen && previous && previous.contents === previous.saved
&& previous.diskContents === undefined && !previous.diskError) {
const index = this.buffers.indexOf(previous);
const opened = this.buffers.find(b => b.relPath === entry.rel_path);
if (index !== -1 && opened) {
this.buffers = this.buffers.filter(b => b !== opened);
this.buffers.splice(this.buffers.indexOf(previous), 1, opened);
}
}
this.activePath = entry.rel_path;
this.emit();
}
}
edit(id: string, contents: string) {
const buffer = this.buffers.find(b => b.id === id);
if (buffer?.kind === "text") { buffer.contents = contents; this.emit(); }
}
setChrome(chrome: OpenBuffer["chrome"]) {
if (this.active) { this.active.chromeOverride = chrome; this.emit(); }
}
close(path: string) {
this.selection++;
const index = this.buffers.findIndex(b => b.relPath === path);
this.buffers = this.buffers.filter(b => b.relPath !== path);
if (this.activePath === path) this.activePath = (this.buffers[index] ?? this.buffers[index - 1])?.relPath ?? null;
this.emit();
}
rename(from: string, to: string) {
for (const b of this.buffers) {
if (b.kind === "empty") continue;
if (b.relPath === from || b.relPath.startsWith(`${from}/`)) {
const next = to + b.relPath.slice(from.length);
if (this.activePath === b.relPath) this.activePath = next;
b.relPath = next;
b.name = next.split("/").pop()!;
b.chrome = this.io.chrome(next);
}
}
this.emit();
}
save(id: string): Promise<void> {
const prior = this.saving.get(id) ?? Promise.resolve();
const pending = prior.then(() => this.write(id));
this.saving.set(id, pending);
return pending.finally(() => { if (this.saving.get(id) === pending) this.saving.delete(id); });
}
async autosave() {
const saved: string[] = [];
const failed: { path: string; error: unknown }[] = [];
if (this.disposed) return { saved, failed };
await Promise.all(this.buffers.map(async b => {
if (b.kind !== "text" || b.contents === b.saved || this.saving.has(b.id)
|| b.diskContents !== undefined || b.diskError) return;
const path = b.relPath;
try { await this.save(b.id); saved.push(path); }
catch (error) { failed.push({ path, error }); }
}));
return { saved, failed };
}
private async write(id: string) {
// Serialize saves of a document, and capture the exact text being written.
// Typing while disk I/O is pending must still leave the document dirty.
if (this.disposed) return;
const b = this.buffers.find(b => b.id === id);
if (!b || b.kind !== "text") return;
if (b.diskContents !== undefined || b.diskError) throw new Error("Resolve the disk changes before saving.");
if (b.contents === b.saved) return;
const contents = b.contents;
const path = b.relPath;
await this.io.write(path, contents, b.saved).then(() => {
b.saved = contents;
if (b.diskContents === contents) b.diskContents = undefined;
this.emit();
});
}
async refresh() {
const version = ++this.refreshVersion;
await Promise.all(this.buffers.map(async b => {
if (b.kind === "empty" || this.saving.has(b.id)) return;
const baseline = b.saved;
const path = b.relPath;
try {
const disk = await (b.kind === "image" ? this.io.image(path) : this.io.read(path));
if (this.disposed || version !== this.refreshVersion || !this.buffers.includes(b) || b.relPath !== path || this.saving.has(b.id) || b.saved !== baseline) return;
b.diskError = null;
if (b.kind === "image") { b.imageUrl = disk; return; }
if (disk === b.saved) { b.diskContents = undefined; return; }
if (b.contents === b.saved || b.contents === disk) {
b.contents = disk; b.saved = disk; b.diskContents = undefined;
} else {
b.diskContents = disk;
}
} catch (error) {
if (!this.disposed && version === this.refreshVersion && this.buffers.includes(b) && b.relPath === path && b.saved === baseline && !this.saving.has(b.id)) {
b.diskError = `File unavailable on disk. Your buffer is preserved. ${String(error)}`;
}
}
}));
this.emit();
}
resolve(id: string, useDisk: boolean) {
const b = this.buffers.find(b => b.id === id);
if (!b || b.diskContents == null) return;
if (useDisk) b.contents = b.diskContents;
b.saved = b.diskContents;
b.diskContents = undefined;
this.emit();
}
}
+331
View File
@@ -0,0 +1,331 @@
export function unescapeHtml(text: string): string {
return text
.replaceAll("&quot;", '"')
.replaceAll("&gt;", ">")
.replaceAll("&lt;", "<")
.replaceAll("&amp;", "&");
}
function parseAttrs(raw: string): Record<string, string> {
const attrs: Record<string, string> = {};
const re = /([:\w-]+)(?:=(?:"([^"]*)"|'([^']*)'))?/g;
let match: RegExpExecArray | null = re.exec(raw);
while (match) {
attrs[match[1]] = match[2] ?? match[3] ?? "";
match = re.exec(raw);
}
return attrs;
}
export function htmlToMarkdown(html: string): string {
const tokens = html.match(/<\/?[a-zA-Z][^>]*>|[^<]+/g) ?? [];
const out: string[] = [];
const list: string[] = [];
let inPre = false;
let preLang = "";
let preBody = "";
let inline = "";
let heading = 0;
let inLi = false;
let liTask: boolean | null = null;
let liChecked = false;
let skipButton = false;
let inCell = false;
let tableRows: string[][] | null = null;
let tableRow: string[] | null = null;
let inQuote = false;
let inOl = false;
let olN = 1;
const spanKind: string[] = [];
function flushInline(): string {
const text = unescapeHtml(inline.replace(/\s+/g, " ").trim());
inline = "";
return text;
}
for (const token of tokens) {
if (token.startsWith("</")) {
const tag = token.slice(2, -1).trim().toLowerCase();
if (tag === "pre") {
inPre = false;
const body = unescapeHtml(preBody.replace(/\n$/, ""));
out.push(preLang ? `\`\`\`${preLang}\n${body}\n\`\`\`` : `\`\`\`\n${body}\n\`\`\``);
preBody = "";
preLang = "";
continue;
}
if (tag === "h1" || tag === "h2" || tag === "h3" || tag === "h4" || tag === "h5" || tag === "h6") {
const text = flushInline();
if (text) {
out.push(`${"#".repeat(heading)} ${text}`);
}
heading = 0;
continue;
}
if (tag === "p") {
if (inCell) {
continue;
}
const text = flushInline();
if (inLi) {
list.push(text);
} else if (inQuote) {
out.push(`> ${text}`);
} else if (text) {
out.push(text);
}
continue;
}
if (tag === "blockquote") {
inQuote = false;
continue;
}
if (tag === "ol") {
inOl = false;
continue;
}
if (tag === "span") {
const kind = spanKind.pop();
if (kind === "math") {
inline += "$";
}
if (kind === "comment") {
inline += "%%";
}
continue;
}
if (tag === "mark") {
inline += "==";
continue;
}
if (tag === "em" || tag === "i") {
inline += "*";
continue;
}
if (tag === "td" || tag === "th") {
if (tableRow) {
tableRow.push(flushInline());
}
inCell = false;
continue;
}
if (tag === "tr") {
if (tableRows && tableRow) {
tableRows.push(tableRow);
}
tableRow = null;
continue;
}
if (tag === "table") {
if (tableRows && tableRows.length > 0) {
const width = Math.max(...tableRows.map((row) => row.length));
const pad = (row: string[]) => {
const cells = [...row];
while (cells.length < width) {
cells.push("");
}
return `| ${cells.join(" | ")} |`;
};
const sep = `| ${Array.from({ length: width }, () => "---").join(" | ")} |`;
out.push(pad(tableRows[0]));
out.push(sep);
for (const row of tableRows.slice(1)) {
out.push(pad(row));
}
}
tableRows = null;
continue;
}
if (tag === "li") {
const text = flushInline();
const item = text || list.pop() || "";
if (liTask !== null) {
out.push(`- [${liChecked ? "x" : " "}] ${item}`);
} else if (inOl) {
out.push(`${olN}. ${item}`);
olN += 1;
} else {
out.push(`- ${item}`);
}
inLi = false;
liTask = null;
continue;
}
if (tag === "button") {
skipButton = false;
continue;
}
if (tag === "strong" || tag === "b") {
inline += "**";
continue;
}
if (tag === "s" || tag === "del" || tag === "strike") {
inline += "~~";
continue;
}
if (tag === "sup") {
inline += "^";
continue;
}
if (tag === "sub") {
inline += "~";
continue;
}
if (tag === "code" && !inPre) {
inline += "`";
continue;
}
continue;
}
if (token.startsWith("<")) {
const selfClose = token.endsWith("/>");
const body = token.slice(1, token.length - (selfClose ? 2 : 1)).trim();
const space = body.indexOf(" ");
const tag = (space === -1 ? body : body.slice(0, space)).toLowerCase();
const attrs = space === -1 ? {} : parseAttrs(body.slice(space + 1));
if (tag === "br") {
inline += "\n";
continue;
}
if (tag === "img") {
const src = attrs["data-md-src"] ?? "";
const alt = attrs.alt ?? "";
const kind = attrs["data-md-kind"] ?? "md";
if (kind === "wiki") {
inline += alt && alt !== src ? `![[${src}|${alt}]]` : `![[${src}]]`;
} else {
inline += `![${alt}](${src})`;
}
continue;
}
if (tag === "input") {
liTask = true;
liChecked = Object.prototype.hasOwnProperty.call(attrs, "checked");
continue;
}
if (tag === "button") {
skipButton = true;
continue;
}
if (tag === "pre") {
inPre = true;
preLang = attrs["data-lang"] ?? "";
preBody = "";
continue;
}
if (tag === "code") {
const langClass = (attrs.class ?? "").split(/\s+/).find((c) => c.startsWith("language-"));
if (inPre) {
if (langClass) {
preLang = langClass.slice("language-".length);
}
continue;
}
inline += "`";
continue;
}
if (tag === "h1" || tag === "h2" || tag === "h3" || tag === "h4" || tag === "h5" || tag === "h6") {
heading = Number(tag.slice(1));
continue;
}
if (tag === "blockquote") {
inQuote = true;
continue;
}
if (tag === "ol") {
inOl = true;
olN = 1;
continue;
}
if (tag === "span") {
if ("data-math" in attrs || /data-math/.test(token)) {
inline += "$";
spanKind.push("math");
} else if ("data-comment" in attrs || /data-comment/.test(token)) {
inline += "%%";
spanKind.push("comment");
} else {
spanKind.push("");
}
continue;
}
if (tag === "mark") {
inline += "==";
continue;
}
if (tag === "em" || tag === "i") {
inline += "*";
continue;
}
if (tag === "table") {
tableRows = [];
continue;
}
if (tag === "tr") {
tableRow = [];
continue;
}
if (tag === "td" || tag === "th") {
inCell = true;
continue;
}
if (tag === "li") {
inLi = true;
const taskItem = attrs["data-type"] === "taskItem" || attrs["data-task"] === "1" || "data-checked" in attrs;
liTask = taskItem ? true : null;
liChecked = attrs["data-checked"] === "true";
continue;
}
if (tag === "strong" || tag === "b") {
inline += "**";
continue;
}
if (tag === "s" || tag === "del" || tag === "strike") {
inline += "~~";
continue;
}
if (tag === "sup") {
inline += "^";
continue;
}
if (tag === "sub") {
inline += "~";
continue;
}
if (tag === "a") {
const href = attrs.href ?? "";
const kind = /wiki/.test(token) ? "wiki" : "md";
inline += `<<LINK|${kind}|${href}>>`;
continue;
}
continue;
}
if (skipButton) {
continue;
}
if (inPre) {
preBody += unescapeHtml(token);
continue;
}
const linkMark = inline.match(/<<LINK\|(wiki|md)\|([^>]*)>>$/);
if (linkMark) {
const kind = linkMark[1];
const href = linkMark[2];
const label = unescapeHtml(token).trim();
inline = inline.slice(0, -linkMark[0].length);
if (kind === "wiki") {
inline += label && label !== href ? `[[${href}|${label}]]` : `[[${href}]]`;
} else {
inline += `[${label}](${href})`;
}
continue;
}
inline += token;
}
const trailing = flushInline();
if (trailing) {
out.push(trailing);
}
return out.join("\n");
}
+70
View File
@@ -0,0 +1,70 @@
export type MdBlock =
| { type: "fence"; lang: string; body: string }
| { type: "text"; line: string };
export type MdFence = {
lang: string;
body: string;
openLine: number;
closeLine: number;
};
type Scan = {
blocks: MdBlock[];
fences: MdFence[];
};
function scanMarkdown(contents: string): Scan {
const lines = contents.split(/\r?\n/);
const blocks: MdBlock[] = [];
const fences: MdFence[] = [];
let fence: { lang: string; body: string[]; openLine: number } | null = null;
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
const lineNo = i + 1;
if (line.startsWith("```")) {
const rest = line.slice(3);
if (!fence) {
const closeAt = rest.indexOf("```");
if (closeAt >= 0) {
const body = rest.slice(0, closeAt);
blocks.push({ type: "fence", lang: "", body });
fences.push({ lang: "", body, openLine: lineNo, closeLine: lineNo });
continue;
}
fence = { lang: rest.trim(), body: [], openLine: lineNo };
} else {
const body = fence.body.join("\n");
blocks.push({ type: "fence", lang: fence.lang, body });
fences.push({
lang: fence.lang,
body,
openLine: fence.openLine,
closeLine: lineNo,
});
fence = null;
}
continue;
}
if (fence) {
fence.body.push(line);
continue;
}
blocks.push({ type: "text", line });
}
if (fence) {
blocks.push({ type: "text", line: `\`\`\`${fence.lang}` });
for (const line of fence.body) {
blocks.push({ type: "text", line });
}
}
return { blocks, fences };
}
export function markdownBlocks(contents: string): MdBlock[] {
return scanMarkdown(contents).blocks;
}
export function markdownFences(contents: string): MdFence[] {
return scanMarkdown(contents).fences;
}
+74
View File
@@ -0,0 +1,74 @@
export type MdLink = {
kind: "md" | "wiki";
from: number;
to: number;
label: string;
target: string;
};
export function findMarkdownLinks(line: string): MdLink[] {
const found: MdLink[] = [];
const md = /(!?)\[([^\]]+)\]\(([^)]+)\)/g;
let match: RegExpExecArray | null = md.exec(line);
while (match) {
if (match[1] !== "!") {
found.push({
kind: "md",
from: match.index,
to: match.index + match[0].length,
label: match[2],
target: match[3].trim(),
});
}
match = md.exec(line);
}
const wiki = /(!?)\[\[([^\]|#]+)(?:\|([^\]]+))?\]\]/g;
match = wiki.exec(line);
while (match) {
if (match[1] !== "!") {
found.push({
kind: "wiki",
from: match.index,
to: match.index + match[0].length,
label: match[3] ?? match[2],
target: match[2].trim(),
});
}
match = wiki.exec(line);
}
found.sort((a, b) => a.from - b.from);
return found;
}
export function wikiCandidates(target: string): string[] {
const trimmed = target.replaceAll("\\", "/").replace(/^\/+/, "");
if (trimmed.includes(".") || trimmed.includes("/")) {
return [trimmed, `${trimmed}.md`];
}
return [`${trimmed}.md`, `notes/${trimmed}.md`, trimmed];
}
export function linkCandidates(notePath: string, target: string, kind: "md" | "wiki"): string[] {
let path = target.split("#")[0];
try { path = decodeURIComponent(path); } catch { /* Literal percent in a file name. */ }
path = path.replaceAll("\\", "/");
if (!path) return [notePath];
if (/^[a-z][a-z\d+.-]*:/i.test(path)) return [];
const folder = notePath.split("/").slice(0, -1).join("/");
const normalize = (value: string) => {
const parts: string[] = [];
for (const part of value.split("/")) {
if (!part || part === ".") continue;
if (part === "..") { if (!parts.length) return null; parts.pop(); }
else parts.push(part);
}
return parts.join("/");
};
const bases = path.startsWith("/") ? [path.slice(1)] : [`${folder}/${path}`, path];
const candidates = bases.flatMap(base => {
const normalized = normalize(base);
if (normalized === null) return [];
return kind === "wiki" && !/\.[^/]+$/.test(normalized) ? [`${normalized}.md`, normalized] : [normalized];
});
return [...new Set(candidates)];
}
+39
View File
@@ -0,0 +1,39 @@
import { workspaceRead, workspaceWrite } from "./api";
const MARKS_PATH = ".runestone/marks.json";
export type Marks = {
pins: string[];
bookmarks: string[];
order: Record<string, string[]>;
};
const EMPTY: Marks = { pins: [], bookmarks: [], order: {} };
export async function loadMarks(): Promise<Marks> {
try {
const raw = await workspaceRead(MARKS_PATH);
const parsed = JSON.parse(raw) as Partial<Marks>;
return {
pins: Array.isArray(parsed.pins) ? parsed.pins : [],
bookmarks: Array.isArray(parsed.bookmarks) ? parsed.bookmarks : [],
order:
parsed.order && typeof parsed.order === "object" && !Array.isArray(parsed.order)
? parsed.order
: {},
};
} catch {
return { pins: [], bookmarks: [], order: {} };
}
}
export async function saveMarks(marks: Marks): Promise<void> {
await workspaceWrite(MARKS_PATH, `${JSON.stringify(marks, null, 2)}\n`);
}
export function togglePath(list: string[], rel: string): string[] {
if (list.includes(rel)) {
return list.filter((item) => item !== rel);
}
return [...list, rel];
}
+121
View File
@@ -0,0 +1,121 @@
export const IMAGE_EXT = new Set([
"png",
"jpg",
"jpeg",
"gif",
"webp",
"svg",
"bmp",
"ico",
"avif",
]);
function fileExt(relPath: string): string {
const base = relPath.split("/").pop() ?? relPath;
const dot = base.lastIndexOf(".");
if (dot <= 0) {
return "";
}
return base.slice(dot + 1).toLowerCase();
}
export function isImagePath(relPath: string): boolean {
return IMAGE_EXT.has(fileExt(relPath));
}
export function isMarkdownPath(relPath: string): boolean {
const ext = fileExt(relPath);
return ext === "md" || ext === "markdown" || ext === "mdown";
}
export function markdownTitle(relPath: string): string {
return (relPath.replaceAll("\\", "/").split("/").pop() || "Untitled").replace(/\.(?:md|markdown|mdown)$/i, "");
}
export function dirnameOf(relPath: string): string {
const idx = relPath.replaceAll("\\", "/").lastIndexOf("/");
if (idx <= 0) {
return "";
}
return relPath.slice(0, idx);
}
export function resolveImageRel(noteRel: string, raw: string): string {
let path = raw.trim().replaceAll("\\", "/").replace(/^<|>$/g, "");
path = path.replace(/^\.\//, "");
if (path.startsWith("/")) {
return path.replace(/^\/+/, "");
}
const noteDir = dirnameOf(noteRel.replaceAll("\\", "/"));
if (path.startsWith("../")) {
const parts = [...noteDir.split("/").filter(Boolean), ...path.split("/")];
const out: string[] = [];
for (const part of parts) {
if (part === "..") {
out.pop();
} else if (part !== "." && part) {
out.push(part);
}
}
return out.join("/");
}
if (noteDir) {
return `${noteDir}/${path}`;
}
return path;
}
export function isRemoteImage(raw: string): boolean {
return /^https?:\/\//i.test(raw.trim());
}
export type MarkdownImage = {
alt: string;
src: string;
kind: "md" | "wiki";
};
export function findMarkdownImages(line: string): MarkdownImage[] {
const found: MarkdownImage[] = [];
const md = /!\[([^\]]*)\]\(([^)]+)\)/g;
const wiki = /!\[\[([^\]|#]+)(?:\|([^\]]+))?\]\]/g;
let match: RegExpExecArray | null;
while ((match = md.exec(line))) {
found.push({ alt: match[1], src: match[2].trim(), kind: "md" });
}
while ((match = wiki.exec(line))) {
found.push({ alt: match[2] ?? match[1], src: match[1].trim(), kind: "wiki" });
}
return found;
}
export function attachmentRel(fileName: string): string {
const raw = fileName || "image.png";
const safe = raw.replace(/[^\w.\-]+/g, "-");
const stamp = new Date().toISOString().replace(/[:.]/g, "").replace("T", "-").slice(0, 15);
return `attachments/${stamp}-${crypto.randomUUID()}-${safe}`;
}
export function imageFiles(data: DataTransfer | null): File[] {
return [...(data?.files ?? [])].filter(file => isImagePath(file.name));
}
// File contents and names are protected during dragover; files is usually empty.
export function hasFileDrag(data: DataTransfer | null): boolean {
return !!data && [...data.types].includes("Files");
}
export function imageInsertion(source: string, from: number, to: number, snippets: string[]): string {
const before = source.slice(0, from), after = source.slice(to);
const prefix = !before || /(?:\r?\n){2}$/.test(before) ? "" : before.endsWith("\n") ? "\n" : "\n\n";
const suffix = /^(?:\r?\n){2}/.test(after) ? "" : /^\r?\n/.test(after) ? "\n" : "\n\n";
return prefix + snippets.join("\n\n") + suffix;
}
export function workspaceImageLink(notePath: string, imagePath: string): string {
const from = notePath.replaceAll("\\", "/").split("/").slice(0, -1);
const to = imagePath.replaceAll("\\", "/").split("/");
while (from.length && to.length && from[0] === to[0]) { from.shift(); to.shift(); }
const relative = [...from.map(() => ".."), ...to].map(part => encodeURIComponent(part).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`)).join("/");
return `![](${relative})`;
}
+231
View File
@@ -0,0 +1,231 @@
import MarkdownIt from "markdown-it";
import type { Token } from "markdown-it";
import { evaluateTableFormulas, formulaErrors, type FormulaResult } from "../editor/tableFormulas.ts";
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
export const escapeHtml = markdown.utils.escapeHtml;
// Inline note formats also round-trip through the table cell editor.
markdown.inline.ruler.before("emphasis", "note_formats", (state, silent) => {
const marker = ["==", "%%", "$"].find(value => state.src.startsWith(value, state.pos));
if (!marker || (marker === "$" && state.src.startsWith("$$", state.pos))) return false;
let end = state.pos + marker.length;
for (; end < state.posMax; end++) {
if (state.src[end] === "\\") { end++; continue; }
if (state.src.startsWith(marker, end)) break;
}
if (end >= state.posMax || end === state.pos + marker.length) return false;
if (!silent) {
const kind = marker === "==" ? "highlight" : marker === "$" ? "math" : "comment";
const token = state.push(`note_${kind}`, "", 0);
token.content = state.src.slice(state.pos + marker.length, end);
}
state.pos = end + marker.length;
return true;
});
for (const kind of ["highlight", "math", "comment"]) {
markdown.renderer.rules[`note_${kind}`] = (tokens, index, _options, env) => {
const content = tokens[index].content;
return kind === "highlight" ? `<mark>${markdown.renderInline(content, env)}</mark>` : `<span data-cell-format="${kind}" class="md-inline-${kind}">${escapeHtml(content)}</span>`;
};
}
export function plainInlineMarkdown(source: string): string {
const literal = (text: string) => text.replace(/&/g, "&amp;").replace(/[\\`*_[\]~<>!|=$%]/g, char => `\\${char}`);
function plain(tokens: Token[]): string {
return tokens.map(token => {
if (token.type === "note_highlight") return plain(markdown.parseInline(token.content, {}));
if (token.type === "hardbreak" || token.type === "softbreak") return "<br>";
if (token.type === "image") {
const target = String(token.attrGet("src") || "");
const label = plain(token.children || []);
return token.attrGet("data-md-kind") === "wiki" ? `![[${literal(target)}\\|${label}]]` : `![${label}](<${target.replace(/\|/g, "%7C").replace(/>/g, "%3E")}>)`;
}
if (token.children) return plain(token.children);
return token.nesting === 0 ? literal(token.content) : "";
}).join("");
}
return plain(markdown.parseInline(source, {}));
}
// Obsidian-style table cells use <br> for line breaks. Recognize only this
// attribute-free tag; arbitrary HTML remains escaped, including inside cells.
markdown.inline.ruler.before("html_inline", "note_line_break", (state, silent) => {
const match = /^<br\s*\/?>/i.exec(state.src.slice(state.pos));
if (!match) return false;
if (!silent) state.push("hardbreak", "br", 0);
state.pos += match[0].length;
return true;
});
const copyIcon = '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V4a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h4"/></svg>';
// Parse wiki links as inline tokens, so code spans and fenced code stay literal.
markdown.inline.ruler.before("link", "wiki_link", (state, silent) => {
const match = /^(!?)\[\[([^\]\n]+)\]\]/.exec(state.src.slice(state.pos));
if (!match) return false;
const [target, ...alias] = match[2].split("|");
const label = alias.join("|") || target;
if (!target.trim() || !markdown.validateLink(target)) return false;
if (!silent) {
if (match[1]) {
const image = state.push("image", "img", 0);
image.attrs = [["src", target.trim()], ["alt", label], ["data-md-kind", "wiki"]];
image.content = label;
const text = new MarkdownIt.Token("text", "", 0);
text.content = label;
image.children = [text];
} else {
const open = state.push("link_open", "a", 1);
open.attrs = [["href", target.trim()], ["data-kind", "wiki"], ["class", "wiki"]];
state.push("text", "", 0).content = label;
state.push("link_close", "a", -1);
}
}
state.pos += match[0].length;
return true;
});
markdown.core.ruler.after("inline", "note_blocks", state => {
for (let i = 0; i < state.tokens.length; i++) {
const token = state.tokens[i];
if (token.type !== "inline" || !token.children?.length) continue;
const first = token.children[0];
if (first.type !== "text") continue;
const item = state.tokens[i - 2];
const task = /^\[([ xX])\]\s+/.exec(first.content);
if (task && item?.type === "list_item_open") {
const checked = task[1].toLowerCase() === "x";
item.attrJoin("class", `task-list-item${checked ? " is-checked" : ""}`);
first.content = first.content.slice(task[0].length);
const checkbox = new MarkdownIt.Token("html_inline", "", 0);
checkbox.content = `<input type="checkbox" disabled aria-label="${checked ? "Completed task" : "Incomplete task"}"${checked ? " checked" : ""}> `;
token.children.unshift(checkbox);
for (let parent = i - 3; parent >= 0; parent--) {
const ancestor = state.tokens[parent];
if ((ancestor.type === "bullet_list_open" || ancestor.type === "ordered_list_open") && ancestor.level < item.level) {
ancestor.attrJoin("class", "contains-task-list");
break;
}
}
}
const callout = /^\[!(note|tip|info|warning|danger|important|success|question)\][+-]?(?:[ \t]+([^\n]*))?(?:\n|$)/i.exec(first.content);
if (callout && item?.type === "blockquote_open") {
item.attrJoin("class", "md-callout");
item.attrSet("data-callout", callout[1].toLowerCase());
const title = callout[2] || callout[1].charAt(0).toUpperCase() + callout[1].slice(1).toLowerCase();
first.content = first.content.slice(callout[0].length);
if (!first.content && token.children[1]?.type === "softbreak") token.children.splice(1, 1);
const heading = new MarkdownIt.Token("html_inline", "", 0);
heading.content = `<strong class="md-callout-title">${escapeHtml(title)}</strong>`;
token.children.unshift(heading);
}
}
});
markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) => {
if (!tokens[index].attrGet("data-kind")) tokens[index].attrSet("data-kind", "md");
return renderer.renderToken(tokens, index, options);
};
markdown.renderer.rules.fence = (tokens, index) => {
const token = tokens[index];
const language = token.info.trim().split(/\s+/)[0];
const code = `<pre class="md-code" data-lang="${escapeHtml(language || "code")}"><button type="button" class="rs-fence-copy" aria-label="Copy code" title="Copy code">${copyIcon}</button><code${language ? ` class="language-${escapeHtml(language)}"` : ""}>${escapeHtml(token.content)}</code></pre>\n`;
return language.toLowerCase() === "mermaid"
? `<div class="md-mermaid"><div class="md-diagram" aria-label="Mermaid diagram"></div><details class="md-diagram-source"><summary>Diagram source</summary>${code}</details></div>\n`
: code;
};
markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => {
const token = tokens[index];
const original = String(token.attrGet("src") || "");
const urls = env?.urls as Map<string, string> | undefined;
const resolved = urls?.get(original) || (/^https?:\/\//i.test(original) ? original : "");
const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env);
// Only app-resolved image data or HTTP(S) URLs become image sources.
if (!/^(?:https?:\/\/|data:image\/)/i.test(resolved)) return `<span class="missing-image" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" alt="${escapeHtml(alt)}">Image unavailable: ${escapeHtml(alt || original)}</span>`;
return `<img src="${escapeHtml(resolved)}" alt="${escapeHtml(alt)}" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" loading="lazy">`;
};
markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n';
markdown.renderer.rules.table_close = () => '</table></div>\n';
export function tableFormulaHtml(result: FormulaResult): string {
const label = `${result.formula} → ${result.error ? formulaErrors[result.error] : result.text}`;
return `<span class="md-table-formula${result.error ? " is-error" : ""}" title="${escapeHtml(label)}" aria-label="${escapeHtml(label)}">${escapeHtml(result.text)}</span>`;
}
// Work from raw inline content, before Markdown formatting can interpret * or $.
// Each table gets its own reference scope, including in nested lists/callouts.
markdown.core.ruler.after("inline", "table_formulas", state => {
let rows: Token[][] | undefined;
for (const token of state.tokens) {
if (token.type === "table_open") rows = [];
else if (rows && token.type === "tr_open") rows.push([]);
else if (rows && token.type === "inline") rows.at(-1)?.push(token);
else if (rows && token.type === "table_close") {
const results = evaluateTableFormulas(rows.map(row => row.map(cell => cell.content)));
rows.forEach((row, r) => row.forEach((cell, c) => {
const result = results[r][c];
if (!result) return;
const output = new MarkdownIt.Token("html_inline", "", 0);
output.content = tableFormulaHtml(result);
cell.children = [output];
}));
rows = undefined;
}
}
});
function documentParts(contents: string) {
const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n(?:---|\.\.\.)[ \t]*(?:\r?\n|$)/.exec(contents);
return match ? { body: contents.slice(match[0].length), properties: match[1] } : { body: contents, properties: "" };
}
export function markdownImages(contents: string): string[] {
const paths = new Set<string>();
function visit(tokens: Token[]) {
for (const token of tokens) {
if (token.type === "image") paths.add(String(token.attrGet("src") || ""));
if (token.children) visit(token.children);
}
}
visit(markdown.parse(documentParts(contents).body, {}));
return [...paths];
}
export function renderMarkdownHtml(contents: string, urls: Map<string, string>): string {
const { body, properties } = documentParts(contents);
const metadata = properties ? `<details class="md-properties"><summary>Properties</summary><pre>${escapeHtml(properties)}</pre></details>\n` : "";
return metadata + markdown.render(body, { urls });
}
export type MarkdownSection = { start: number; end: number; html: string };
// Render with the entire document's reference environment, retaining exact source
// offsets so editing one block never serializes the rest of the document.
export function renderMarkdownSections(contents: string, urls: Map<string, string>): MarkdownSection[] {
const { body, properties } = documentParts(contents);
const offset = contents.length - body.length;
const lines = [offset];
for (const match of body.matchAll(/\n/g)) lines.push(offset + match.index + 1);
const env = { urls };
const tokens = markdown.parse(body, env);
const sections: MarkdownSection[] = [];
if (offset) sections.push({ start: 0, end: offset, html: `<details class="md-properties"><summary>Properties</summary><pre>${escapeHtml(properties)}</pre></details>` });
for (let i = 0; i < tokens.length;) {
const token = tokens[i];
const start = token.map ? (lines[token.map[0]] ?? contents.length) : offset;
let end = i + 1;
if (token.nesting === 1) {
let depth = 1;
while (end < tokens.length && depth) depth += tokens[end++].nesting;
}
sections.push({ start, end: contents.length, html: markdown.renderer.render(tokens.slice(i, end), markdown.options, env) });
i = end;
}
if (!sections.length) sections.push({ start: 0, end: contents.length, html: "" });
sections[0].start = 0;
for (let i = 0; i < sections.length - 1; i++) sections[i].end = sections[i + 1].start;
return sections;
}
+31
View File
@@ -0,0 +1,31 @@
import { isMarkdownPath } from "./media";
export type OutlineItem = {
level: number;
text: string;
line: number;
};
export function buildOutline(relPath: string, contents: string): OutlineItem[] {
const lines = contents.split(/\r?\n/);
const items: OutlineItem[] = [];
const markdown = isMarkdownPath(relPath);
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
if (markdown) {
const heading = /^(#{1,6})\s+(.+)\s*$/.exec(line);
if (heading) {
items.push({ level: heading[1].length, text: heading[2].trim(), line: i + 1 });
}
continue;
}
const code =
/^(?:export\s+)?(?:async\s+)?(?:pub\s+)?(?:def|function|class|fn|struct|impl|interface|enum)\s+([A-Za-z0-9_]+)/.exec(
line.trim(),
);
if (code) {
items.push({ level: 1, text: code[1], line: i + 1 });
}
}
return items;
}
+53
View File
@@ -0,0 +1,53 @@
export type RenamePlan =
| { action: "noop" }
| { action: "error"; message: string }
| { action: "rename"; to: string };
function parentOf(rel: string): string {
const idx = rel.lastIndexOf("/");
if (idx <= 0) {
return "";
}
return rel.slice(0, idx);
}
export function planRename(fromRel: string, typed: string): RenamePlan {
const name = typed.trim();
if (!name) {
return { action: "error", message: "Name is empty" };
}
if (name.includes("/") || name.includes("\\")) {
return { action: "error", message: "Name cannot contain a path separator" };
}
const current = fromRel.split("/").pop() ?? fromRel;
if (name === current) {
return { action: "noop" };
}
const parent = parentOf(fromRel);
return { action: "rename", to: parent ? `${parent}/${name}` : name };
}
export function planTitleRename(fromRel: string, title: string): RenamePlan {
const trimmed = title.trim();
if (!trimmed) {
return { action: "error", message: "Name is empty" };
}
const current = fromRel.split("/").pop() ?? fromRel;
const currentDot = current.lastIndexOf(".");
const typedDot = trimmed.lastIndexOf(".");
const nextName =
currentDot > 0 && typedDot <= 0 ? `${trimmed}${current.slice(currentDot)}` : trimmed;
return planRename(fromRel, nextName);
}
/** The writing title edits the basename, keeping the note's Markdown format. */
export function planMarkdownTitleRename(fromRel: string, title: string): RenamePlan {
const extension = fromRel.match(/\.(?:md|markdown|mdown)$/i)?.[0] ?? ".md";
const name = title.trim();
const current = fromRel.split("/").pop() ?? fromRel;
if (name === current.slice(0, -extension.length)) return { action: "noop" };
const stem = name.toLowerCase().endsWith(extension.toLowerCase())
? name.slice(0, -extension.length).trim() : name;
if (!stem) return { action: "error", message: "Name is empty" };
return planRename(fromRel, stem + extension);
}
+151
View File
@@ -0,0 +1,151 @@
import type { TreeEntry, TreeKind } from "./types";
export type DropPlace = "before" | "after" | "inside";
export type DropTarget = {
rel: string;
place: DropPlace;
};
export type DropPlan =
| { action: "noop" }
| { action: "reorder"; parent: string; names: string[] }
| {
action: "move";
from: string;
to: string;
fromParent: string;
toParent: string;
destName: string;
orderFrom: string[];
orderTo: string[];
};
export function parentRel(rel: string): string {
const idx = rel.lastIndexOf("/");
if (idx <= 0) {
return "";
}
return rel.slice(0, idx);
}
export function joinRel(parent: string, name: string): string {
return parent ? `${parent}/${name}` : name;
}
export function uniqueName(existing: Iterable<string>, wanted: string): string {
const names = new Set(existing);
if (!names.has(wanted)) {
return wanted;
}
const dot = wanted.lastIndexOf(".");
const stem = dot > 0 ? wanted.slice(0, dot) : wanted;
const ext = dot > 0 ? wanted.slice(dot) : "";
let n = 2;
while (names.has(`${stem} ${n}${ext}`)) {
n += 1;
}
return `${stem} ${n}${ext}`;
}
function isInside(parent: string, child: string): boolean {
return child === parent || child.startsWith(`${parent}/`);
}
export function dropPlaceAt(kind: TreeKind, yRatio: number): DropPlace {
if (kind === "folder") {
if (yRatio < 0.25) {
return "before";
}
if (yRatio > 0.75) {
return "after";
}
return "inside";
}
return yRatio < 0.5 ? "before" : "after";
}
export function dropHint(name: string, place: DropPlace): string {
if (place === "inside") {
return `Into ${name}`;
}
if (place === "before") {
return `Before ${name}`;
}
return `After ${name}`;
}
function insertAt(names: string[], targetName: string, item: string, place: DropPlace): string[] {
const next = [...names];
let idx = next.indexOf(targetName);
if (idx < 0) {
idx = next.length;
} else if (place === "after") {
idx += 1;
}
next.splice(idx, 0, item);
return next;
}
export function planDrop(
draggedRel: string,
target: TreeEntry,
place: DropPlace,
childrenOf: (parent: string) => string[],
): DropPlan {
if (draggedRel === target.rel_path) {
return { action: "noop" };
}
const fromParent = parentRel(draggedRel);
const draggedName = draggedRel.split("/").pop() ?? draggedRel;
if (place === "inside") {
if (target.kind !== "folder") {
return { action: "noop" };
}
if (isInside(draggedRel, target.rel_path)) {
return { action: "noop" };
}
if (fromParent === target.rel_path) {
return { action: "noop" };
}
const destName = uniqueName(childrenOf(target.rel_path), draggedName);
return {
action: "move",
from: draggedRel,
to: joinRel(target.rel_path, destName),
fromParent,
toParent: target.rel_path,
destName,
orderFrom: childrenOf(fromParent).filter((name) => name !== draggedName),
orderTo: [...childrenOf(target.rel_path), destName],
};
}
if (target.kind === "folder" && isInside(draggedRel, target.rel_path)) {
return { action: "noop" };
}
const toParent = parentRel(target.rel_path);
if (fromParent === toParent) {
const names = childrenOf(toParent).filter((name) => name !== draggedName);
return {
action: "reorder",
parent: toParent,
names: insertAt(names, target.name, draggedName, place),
};
}
const destName = uniqueName(childrenOf(toParent), draggedName);
const names = childrenOf(toParent).filter((name) => name !== draggedName);
return {
action: "move",
from: draggedRel,
to: joinRel(toParent, destName),
fromParent,
toParent,
destName,
orderFrom: childrenOf(fromParent).filter((name) => name !== draggedName),
orderTo: insertAt(names, target.name, destName, place),
};
}
+61
View File
@@ -0,0 +1,61 @@
import type { TreeEntry } from "./types";
export type SelectionModifiers = {
ctrlKey?: boolean;
metaKey?: boolean;
shiftKey?: boolean;
};
export type TreeSelection = {
paths: Set<string>;
anchor: string | null;
};
// null means the full edge; a number is the exposed width in tree indentation steps.
export type TreeSelectionEdges = { top: number | null; bottom: number | null };
export function treeSelectionEdges(visible: readonly string[], selected: ReadonlySet<string>): Map<string, TreeSelectionEdges> {
const edges = new Map<string, TreeSelectionEdges>();
for (let index = 0; index < visible.length; index++) {
const path = visible[index];
if (!selected.has(path)) continue;
const depth = path.split("/").length;
const exposed = (neighbor: string | undefined) => neighbor !== undefined && selected.has(neighbor)
? Math.max(0, neighbor.split("/").length - depth)
: null;
edges.set(path, { top: exposed(visible[index - 1]), bottom: exposed(visible[index + 1]) });
}
return edges;
}
/** Match the rendered tree order, excluding children of collapsed folders. */
export function visibleTreePaths(childrenMap: Record<string, TreeEntry[]>, expanded: ReadonlySet<string>): string[] {
const paths: string[] = [];
function visit(parent: string) {
for (const entry of childrenMap[parent] ?? []) {
paths.push(entry.rel_path);
if (entry.kind === "folder" && expanded.has(entry.rel_path)) visit(entry.rel_path);
}
}
visit("");
return paths;
}
export function selectTreePath(
current: TreeSelection,
path: string,
visible: readonly string[],
modifiers: SelectionModifiers = {},
): TreeSelection {
const additive = modifiers.ctrlKey || modifiers.metaKey;
const anchorIndex = current.anchor === null ? -1 : visible.indexOf(current.anchor);
const targetIndex = visible.indexOf(path);
if (modifiers.shiftKey && anchorIndex !== -1 && targetIndex !== -1) {
const range = visible.slice(Math.min(anchorIndex, targetIndex), Math.max(anchorIndex, targetIndex) + 1);
return { paths: new Set(additive ? [...current.paths, ...range] : range), anchor: current.anchor };
}
const paths = new Set(additive ? current.paths : []);
if (additive && !modifiers.shiftKey && paths.has(path)) paths.delete(path);
else paths.add(path);
return { paths, anchor: path };
}
+35
View File
@@ -0,0 +1,35 @@
export type Chrome = "Writing" | "Ide";
export type TreeKind = "file" | "folder";
export type TreeEntry = {
name: string;
rel_path: string;
kind: TreeKind;
};
export type WorkspaceInfo = {
root: string;
name: string;
watch_mode: string;
};
export type WorkspaceEvent = {
root: string;
kind: string;
paths: string[];
};
export type OpenBuffer = {
id: string;
relPath: string;
name: string;
contents: string;
saved: string;
chrome: Chrome;
chromeOverride: Chrome | null;
kind: "text" | "image" | "empty";
imageUrl: string | null;
diskContents?: string | null;
diskError?: string | null;
};