Improve editor, plugin updates, and window transfers for 0.1.41

This commit is contained in:
Knotty Wyvern
2026-10-21 10:42:44 -07:00
parent 68e86ab6eb
commit 42dd0fa711
56 changed files with 2313 additions and 221 deletions
+38 -6
View File
@@ -1,6 +1,9 @@
<script lang="ts">
import FindPanel from "./FindPanel.svelte";
import { monacoSearch } from "./monacoSearch";
import { SearchQuery } from "@codemirror/search";
import { t } from "$lib/i18n";
import { untrack } from "svelte";
import { tick, 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";
@@ -34,6 +37,24 @@
let host: HTMLDivElement | undefined = $state();
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
export function focus() { editor?.focus(); }
let search = $state.raw<ReturnType<typeof monacoSearch>>();
let findOpen = $state(false);
let findPanel = $state<FindPanel>();
export async function openFind(replace = false) {
if (!search || !editor) return;
const selection = editor.getSelection();
const text = selection && editor.getModel()?.getValueInRange(selection);
if (text && !text.includes("\n") && !text.includes("\r")) {
search.target.setQuery(new SearchQuery({ ...search.target.query, search: text }));
findPanel?.sync(search.target.query);
}
findOpen = true;
search.refresh();
await tick();
findPanel?.focus(replace);
}
export function closeFind() { if (findOpen) search?.target.close(); }
export function nextMatch(backward = false) { if (findOpen) search?.target.next(backward); else void openFind(); }
let ready = $state(0);
let applying = false;
let loadError = $state<string | null>(null);
@@ -125,6 +146,12 @@
...monacoChrome(mode),
});
editor = view;
search = monacoSearch(monaco, view, () => { findOpen = false; });
for (const [id, label, replace] of [["actions.find", "Find", false], ["editor.action.startFindReplaceAction", "Replace", true]] as const) {
listeners.push(view.addAction({ id, label, keybindings: [monaco.KeyMod.CtrlCmd | (replace ? monaco.KeyCode.KeyH : monaco.KeyCode.KeyF)], run: () => openFind(replace) }));
}
listeners.push(view.addAction({ id: "editor.action.nextMatchFindAction", label: "Next match", keybindings: [monaco.KeyCode.F3], run: () => nextMatch() }));
listeners.push(view.addAction({ id: "editor.action.previousMatchFindAction", label: "Previous match", keybindings: [monaco.KeyMod.Shift | monaco.KeyCode.F3], run: () => nextMatch(true) }));
const linkPath = `/${encodeURIComponent(untrack(() => buffer.id))}/`;
if (markdown) listeners.push(monaco.languages.registerLinkProvider("markdown", {
provideLinks(candidate) {
@@ -230,6 +257,9 @@
menu?.destroy();
releaseDrop?.();
listeners.forEach(listener => listener.dispose());
search?.dispose();
search = undefined;
findOpen = false;
view?.dispose();
if (session) releaseEditorSession(session);
editor = undefined;
@@ -273,6 +303,8 @@
});
</script>
<div class="source-editor">
{#if findOpen && search}<FindPanel bind:this={findPanel} target={search.target} />{/if}
<div
class="monaco-host"
role="application"
@@ -291,14 +323,14 @@
void takeImages(event, event.clipboardData);
}}
></div>
</div>
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.monaco-host {
position: absolute;
inset: 0;
overflow: hidden;
}
.source-editor { position: absolute; inset: 0; display: flex; flex-direction: column; min-width: 0; }
.source-editor :global(.rs-find-bar) { flex-shrink: 0; border-bottom: 1px solid var(--rs-border); }
.monaco-host { position: relative; flex: 1; min-height: 0; overflow: hidden; }
.monaco-host :global(.rs-source-search-match) { background: var(--rs-item-selection-bg); outline: 1px solid var(--rs-accent); }
.monaco-host :global(.monaco-editor),
.monaco-host :global(.overflow-guard) {
+25 -17
View File
@@ -1,14 +1,17 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte";
import { runScopeHandlers, type EditorView } from "@codemirror/view";
import { SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, selectMatches, setSearchQuery } from "@codemirror/search";
import { SearchQuery } from "@codemirror/search";
import type { FindTarget } from "./findTarget";
import Icon from "$lib/ui/Icon.svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import "$lib/ui/find.css";
let { view }: { view: EditorView } = $props();
const initialQuery = untrack(() => getSearchQuery(view.state));
let { target }: { target: FindTarget } = $props();
const initialQuery = untrack(() => target.query);
let searchInput: HTMLInputElement;
let replaceInput = $state<HTMLInputElement>();
export function focus(replace = false) { (replace ? replaceInput : searchInput)?.select(); }
let query = $state.raw(initialQuery);
let searchText = $state(initialQuery.search);
let replacement = $state(initialQuery.replace);
@@ -28,18 +31,23 @@
function commit() {
query = new SearchQuery({ search: searchText, replace: replacement, caseSensitive, regexp, wholeWord });
view.dispatch({ effects: setSearchQuery.of(query) });
target.setQuery(query);
}
function keydown(event: KeyboardEvent) {
if (runScopeHandlers(view, event, "search-panel")) {
if (target.keydown?.(event)) {
event.preventDefault();
event.stopPropagation();
} else if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
target.close();
} else if (event.key === "Enter" && event.target instanceof HTMLInputElement && event.target.type === "text") {
event.preventDefault();
event.stopPropagation();
commit();
if (event.target.name === "replace") replaceNext(view);
else (event.shiftKey ? findPrevious : findNext)(view);
if (event.target.name === "replace") target.replace();
else target.next(event.shiftKey);
}
}
</script>
@@ -49,14 +57,14 @@
<div class="rs-find-row">
<div class="rs-find-field">
<Icon icon="search" />
<input type="text" name="search" {...{ "main-field": "true" }} aria-label={$t("Find in document")} placeholder={$t("Find in document")}
<input bind:this={searchInput} type="text" name="search" autocomplete="off" {...{ "main-field": "true" }} aria-label={$t("Find in document")} placeholder={$t("Find in document")}
aria-invalid={searchText !== "" && !query.valid} bind:value={() => searchText, value => { searchText = value; commit(); }} />
</div>
<div class="rs-find-actions">
<IconButton icon="up" label={$t("Previous match (Shift+Enter)")} onclick={() => findPrevious(view)} disabled={!query.valid} />
<IconButton icon="down" label={$t("Next match (Enter)")} onclick={() => findNext(view)} disabled={!query.valid} />
<button class="rs-find-button" type="button" onclick={() => selectMatches(view)} disabled={!query.valid}>{$t("Select all")}</button>
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={() => closeSearchPanel(view)} />
<IconButton icon="up" label={$t("Previous match (Shift+Enter)")} onclick={() => target.next(true)} disabled={!query.valid} />
<IconButton icon="down" label={$t("Next match (Enter)")} onclick={() => target.next()} disabled={!query.valid} />
{#if target.canSelectAll !== false}<button class="rs-find-button" type="button" onclick={() => target.selectAll()} disabled={!query.valid}>{$t("Select all")}</button>{/if}
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={() => target.close()} />
</div>
</div>
<div class="rs-find-options">
@@ -65,14 +73,14 @@
<label><input type="checkbox" bind:checked={() => regexp, value => { regexp = value; commit(); }} />{$t("Regex")}</label>
{#if searchText && !query.valid}<span class="rs-find-error" role="status">{$t("Invalid expression")}</span>{/if}
</div>
{#if !view.state.readOnly}
{#if !target.readOnly}
<div class="rs-find-row">
<div class="rs-find-field">
<input type="text" name="replace" aria-label={$t("Replace with")} placeholder={$t("Replace with")} bind:value={() => replacement, value => { replacement = value; commit(); }} />
<input bind:this={replaceInput} type="text" name="replace" autocomplete="off" aria-label={$t("Replace with")} placeholder={$t("Replace with")} bind:value={() => replacement, value => { replacement = value; commit(); }} />
</div>
<div class="rs-find-actions">
<button class="rs-find-button" type="button" onclick={() => replaceNext(view)} disabled={!query.valid}>{$t("Replace")}</button>
<button class="rs-find-button" type="button" onclick={() => replaceAll(view)} disabled={!query.valid}>{$t("Replace all")}</button>
<button class="rs-find-button" type="button" onclick={() => target.replace()} disabled={!query.valid}>{$t("Replace")}</button>
<button class="rs-find-button" type="button" onclick={() => target.replace(true)} disabled={!query.valid}>{$t("Replace all")}</button>
</div>
</div>
{/if}
+20 -1
View File
@@ -9,7 +9,8 @@
import { writerHistory, historyKeymap } from "./writerHistory";
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
import { noteFormats } from "./noteFormats";
import { searchKeymap } from "@codemirror/search";
import { closeSearchPanel, findNext, findPrevious, openSearchPanel, searchKeymap } from "@codemirror/search";
import { htmlToMarkdown } from "$lib/workspace/htmlToMarkdown";
import { writerSearch } from "./writerSearch";
import type { OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
@@ -52,6 +53,13 @@
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
export function focus() { editor?.focus(); }
export function openFind(replace = false) {
if (!editor) return;
openSearchPanel(editor);
editor.dom.querySelector<HTMLInputElement>(replace ? 'input[name="replace"]' : 'input[name="search"]')?.select();
}
export function closeFind() { if (editor) closeSearchPanel(editor); }
export function nextMatch(backward = false) { if (editor) (backward ? findPrevious : findNext)(editor); }
let error = $state("");
let model: import("monaco-editor").editor.ITextModel | undefined;
let ModelSelection: typeof import("monaco-editor").Selection;
@@ -272,6 +280,17 @@
return true;
},
paste(event, view) {
const html = event.clipboardData?.getData("text/html") || "";
if (/<table[\s>]/i.test(html)) {
const markdown = htmlToMarkdown(html).replace(/\r\n?/g, "\n").trim();
if (markdown) {
event.preventDefault(); event.stopPropagation();
const { from, to } = view.state.selection.main;
const insert = imageInsertion(view.state.doc.toString(), from, to, [markdown]);
view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + insert.length }, userEvent: "input.paste", annotations: isolateHistory.of("full") });
return true;
}
}
if (!onInsertImage || !imageFiles(event.clipboardData).length) return false;
void insertImages(event, view); return true;
},
+42
View File
@@ -0,0 +1,42 @@
import { EditorState } from "@codemirror/state";
import { SearchQuery } from "@codemirror/search";
/** Commands for the shared document search controls. */
export interface FindTarget {
query: SearchQuery;
readOnly: boolean;
canSelectAll?: boolean;
setQuery(query: SearchQuery): void;
next(backward?: boolean): void;
selectAll(): void;
replace(all?: boolean): void;
close(): void;
keydown?(event: KeyboardEvent): boolean;
}
export function documentMatches(source: string, query: SearchQuery) {
const state = EditorState.create({ doc: source });
const matches: { from: number; to: number }[] = [];
if (query.valid) {
const cursor = query.getCursor(state);
for (let match = cursor.next(); !match.done; match = cursor.next()) matches.push(match.value);
}
return { state, matches };
}
export function replacementText(source: string, from: number, query: SearchQuery) {
const replacement = query.literal ? query.replace : query.replace.replace(/\\([nrt\\])/g, (_, char: string) => ({ n: "\n", r: "\r", t: "\t", "\\": "\\" })[char]!);
if (!query.regexp) return replacement;
const expression = new RegExp(query.search, "gmu" + (query.caseSensitive ? "" : "i"));
expression.lastIndex = from;
const match = expression.exec(source);
return replacement.replace(/\$([$&]|\d+)/g, (token, index: string) => {
if (index === "$") return "$";
if (index === "&") return match?.[0] ?? "";
for (let length = index.length; length > 0; length--) {
const number = Number(index.slice(0, length));
if (match && number > 0 && number < match.length) return (match[number] ?? "") + index.slice(length);
}
return token;
});
}
+37 -10
View File
@@ -145,6 +145,24 @@ class Preview extends WidgetType {
}
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
const focusBody = StateEffect.define<boolean>();
const bodyFocused = StateField.define({
create: () => false,
update(value, transaction) {
for (const effect of transaction.effects) if (effect.is(focusBody)) value = effect.value;
return value;
},
});
const syncBodyFocus = ViewPlugin.define(view => {
// A restored editor can already own focus before its focus observer starts.
const sync = () => queueMicrotask(() => {
if (view.dom.isConnected && view.state.field(bodyFocused, false) !== undefined && view.state.field(bodyFocused) !== view.hasFocus) {
view.dispatch({ effects: focusBody.of(view.hasFocus) });
}
});
sync();
return { update: sync };
});
function build(state: EditorState, previous?: DecorationSet): 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 }));
@@ -221,17 +239,32 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
return false;
}
const line = state.doc.lineAt(node.from);
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name)) {
// A list starts with one hyphen. Do not enlarge the preceding paragraph
// while the user enters that marker. Keep the Markdown source unchanged.
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
}
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
if (node.name === "TaskMarker") {
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
if (!match) return;
const markerFrom = line.from + match[1].length;
// ArrowLeft and Home reach the replacement's start, before the list bullet.
// Keep the trailing space outside the edit range so task text stays rendered.
const editingMarker = state.field(bodyFocused) && state.selection.ranges.some(range => range.from <= node.to && range.to >= markerFrom);
if (editingMarker) return;
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x"), atomic: true }).range(markerFrom, line.from + match[0].length));
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
return;
}
if (selected(node.from, node.to)) return;
if (node.name === "HorizontalRule") {
ranges.push(Decoration.line({ class: "writer-divider-line" }).range(line.from));
ranges.push(Decoration.replace({ widget: new Divider(), atomic: true }).range(node.from, node.to));
return false;
}
if (node.name === "HeaderMark") replace(node.from, Math.min(line.to, node.to + 1));
if (node.name === "HeaderMark" && !(source.slice(node.from, node.to) === "-" && node.node.parent?.name === "SetextHeading2")) 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");
@@ -252,12 +285,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
return false;
}
if (node.name === "TaskMarker") {
const match = /^(\s*)([-+*]\s+)\[([ xX])\]\s?/.exec(line.text);
if (!match) return;
ranges.push(Decoration.replace({ widget: new Checkbox(match[3].toLowerCase() === "x"), atomic: true }).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(/\[\^([^\]\s]+)\](:)?/g)) {
const from = match.index, to = from + match[0].length;
@@ -281,12 +308,12 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
}
return Decoration.set(ranges, true);
}
return [imageSource, linkTooltips, StateField.define<DecorationSet>({
return [imageSource, linkTooltips, bodyFocused, syncBodyFocus, EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing)), StateField.define<DecorationSet>({
create: build,
update(value, transaction) {
return transaction.docChanged || transaction.selection
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource) || effect.is(foldEffect) || effect.is(unfoldEffect))
|| transaction.effects.some(effect => effect.is(focusBody) || effect.is(refreshImages) || effect.is(editImageSource) || effect.is(foldEffect) || effect.is(unfoldEffect))
? build(transaction.state, value.map(transaction.changes)) : value;
},
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({
+71
View File
@@ -0,0 +1,71 @@
import type * as Monaco from "monaco-editor";
import { SearchQuery } from "@codemirror/search";
import { documentMatches, replacementText, type FindTarget } from "./findTarget";
export function monacoSearch(monaco: typeof Monaco, view: Monaco.editor.IStandaloneCodeEditor, close: () => void) {
const decorations = view.createDecorationsCollection();
let active = false;
let query = new SearchQuery({ search: "" });
function snapshot() {
const model = view.getModel()!;
const { state, matches } = documentMatches(model.getValue(), query);
function range(match: { from: number; to: number }) {
const from = state.doc.lineAt(match.from), to = state.doc.lineAt(match.to);
return new monaco.Range(from.number, match.from - from.from + 1, to.number, match.to - to.from + 1);
}
return { model, state, matches, range };
}
function refresh() {
active = true;
const { matches, range } = snapshot();
decorations.set(matches.map(match => ({ range: range(match), options: { inlineClassName: "rs-source-search-match" } })));
}
function next(backward = false) {
const { matches, range } = snapshot();
if (!matches.length) return;
const selection = view.getSelection();
const ranges = matches.map(range);
const current = ranges.findIndex(match => selection?.equalsRange(match));
let index: number;
if (current >= 0) index = (current + (backward ? -1 : 1) + ranges.length) % ranges.length;
else if (backward) {
index = ranges.findLastIndex(match => !selection || monaco.Position.compare(match.getEndPosition(), selection.getStartPosition()) <= 0);
if (index < 0) index = ranges.length - 1;
} else {
index = ranges.findIndex(match => !selection || monaco.Position.compare(match.getStartPosition(), selection.getEndPosition()) >= 0);
if (index < 0) index = 0;
}
view.setSelection(ranges[index]);
view.revealRangeInCenterIfOutsideViewport(ranges[index]);
}
const target: FindTarget = {
get query() { return query; }, readOnly: false,
setQuery(value) { query = value; refresh(); },
next,
selectAll() {
const { matches, range } = snapshot();
if (!matches.length) return;
view.setSelections(matches.map(match => { const value = range(match); return new monaco.Selection(value.startLineNumber, value.startColumn, value.endLineNumber, value.endColumn); }));
view.focus();
},
replace(all = false) {
const { state, matches, range } = snapshot();
const selection = view.getSelection();
const selected = all ? matches : matches.filter(match => selection?.equalsRange(range(match))).slice(0, 1);
if (!selected.length) { if (!all) next(); return; }
const edits = selected.map(match => ({ range: range(match), text: replacementText(state.doc.toString(), match.from, query) }));
const last = selected[selected.length - 1];
const inserted = edits[edits.length - 1].text;
const end = state.update({ changes: selected.map((match, index) => ({ ...match, insert: edits[index].text })) }).state;
const offset = all ? 0 : last.from + inserted.length;
const line = end.doc.lineAt(Math.min(offset, end.doc.length));
view.pushUndoStop();
view.executeEdits("document-find", edits, [new monaco.Selection(line.number, offset - line.from + 1, line.number, offset - line.from + 1)]);
view.pushUndoStop();
if (!all) next();
},
close() { active = false; decorations.clear(); close(); view.focus(); },
};
const changed = view.onDidChangeModelContent(() => { if (active) refresh(); });
return { target, refresh, dispose() { changed.dispose(); decorations.clear(); } };
}
+1
View File
@@ -81,6 +81,7 @@ class NoteTitle extends WidgetType {
event.stopPropagation();
if (event.isComposing) return;
if (event.key === "Enter") { event.preventDefault(); void commit(true); }
if (event.key === "Tab" && !event.shiftKey) { event.preventDefault(); void commit(true); }
if (event.key === "Escape" && !pending) { event.preventDefault(); finish(); button.focus(); }
};
return block;
+47
View File
@@ -0,0 +1,47 @@
import { SearchQuery } from "@codemirror/search";
import { documentMatches, type FindTarget } from "./findTarget";
/** Search the visible reading text without changing its Markdown or rendered nodes. */
export function readingSearch(root: HTMLElement, close: () => void, options: { includeButtons?: boolean; focusOnClose?: () => void } = {}): FindTarget {
let query = new SearchQuery({ search: "" });
let current = -1;
function ranges() {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const nodes: { node: Text; from: number; to: number }[] = [];
let source = "", block: Element | null = null;
while (walker.nextNode()) {
const node = walker.currentNode as Text, parent = node.parentElement;
if (!parent || parent.closest(options.includeButtons ? "[hidden], [aria-hidden=true], script, style" : "button, [hidden], script, style") || !parent.getClientRects().length) continue;
const nextBlock = parent.closest("p, h1, h2, h3, h4, h5, h6, li, td, th, pre, button, div, section");
if (nodes.length && nextBlock !== block) source += "\n";
block = nextBlock;
nodes.push({ node, from: source.length, to: source.length + node.length });
source += node.data;
}
return documentMatches(source, query).matches.flatMap(match => {
const start = nodes.find(node => node.to > match.from || node.from === match.from);
const end = nodes.find(node => node.to >= match.to);
if (!start || !end) return [];
const range = document.createRange();
range.setStart(start.node, Math.max(0, match.from - start.from));
range.setEnd(end.node, Math.max(0, match.to - end.from));
return [range];
});
}
function next(backward = false) {
const matches = ranges();
if (!matches.length) { current = -1; return; }
current = current < 0 ? (backward ? matches.length - 1 : 0) : (current + (backward ? -1 : 1) + matches.length) % matches.length;
const range = matches[current];
const selection = window.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
range.startContainer.parentElement?.scrollIntoView({ block: "center" });
}
return {
get query() { return query; }, readOnly: true, canSelectAll: false,
setQuery(value) { if (query.eq(value)) return; query = value; current = -1; window.getSelection()?.removeAllRanges(); },
next, selectAll() {}, replace() {},
close() { close(); if (options.focusOnClose) options.focusOnClose(); else root.focus({ preventScroll: true }); },
};
}
+8 -4
View File
@@ -277,9 +277,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
if (event.key === "Enter") {
event.preventDefault();
if (sourceEditing || /^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
if (event.shiftKey) editor?.commands.setHardBreak();
else if (event.ctrlKey || event.metaKey) leave(true);
else editor?.commands.setHardBreak();
else {
const next = table!.rows[row + 1]?.cells[column];
if (next) { activate(next); editor?.commands.setTextSelection(1); editor?.view.focus(); }
else add("row", true, column);
}
return true;
}
if (event.key === "Tab") {
@@ -360,7 +364,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
view.requestMeasure();
}
function add(kind: "row" | "column", focusNew = false) {
function add(kind: "row" | "column", focusNew = false, column = 0) {
const from = view.posAtDOM(root);
finish();
const current = controller.source;
@@ -369,7 +373,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
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 (focusNew) updated.querySelector<HTMLTableRowElement>("tbody tr:last-child")?.cells[column]?.focus();
if (kind === "column") {
const viewport = updated.querySelector<HTMLElement>(".md-table-scroll")!;
viewport.scrollLeft = viewport.scrollWidth;
+10
View File
@@ -60,6 +60,16 @@ export function copyTableCells(source: string, range: CellRange): string {
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");
}
export function copyTableMarkdown(source: string, range: CellRange): string {
const table = parseMarkdownTable(source);
if (!table) return "";
const { top, bottom, left, right } = bounds(range);
const rows = Array.from({ length: bottom - top + 1 }, (_, r) =>
`| ${Array.from({ length: right - left + 1 }, (_, c) => table.rows[sourceRow(top + r)]?.cells[left + c]?.text || "").join(" | ")} |`);
rows.splice(1, 0, `| ${Array.from({ length: right - left + 1 }, () => "---").join(" | ")} |`);
return rows.join("\n");
}
// Parse quoted spreadsheet TSV, including embedded tabs/newlines, or a Markdown table.
export function clipboardCells(text: string): string[][] {
const table = parseMarkdownTable(text);
+13 -3
View File
@@ -7,7 +7,8 @@ import { useSpellingMenu } from "./spellingMenu";
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
import { alignTableCells, bounds, copyTableCells, copyTableMarkdown, deleteTableCells, formatTableCells, mapTableCells, pasteTableCells, type CellFormat, type CellPoint, type CellRange } from "./tableSelection";
import { renderMarkdownHtml } from "../workspace/noteHtml";
const selections = new WeakMap<Element, (range: CellRange) => void>();
@@ -76,7 +77,12 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
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 (navigator.clipboard.write && typeof ClipboardItem !== "undefined") {
await navigator.clipboard.write([new ClipboardItem({
"text/plain": new Blob([copyTableCells(before, selected)], { type: "text/plain" }),
"text/html": new Blob([renderMarkdownHtml(copyTableMarkdown(before, selected), new Map())], { type: "text/html" }),
})]);
} else await navigator.clipboard.writeText(copyTableMarkdown(before, selected));
if (action === "cut" && root.isConnected && source() === before && range === selected) clearCells();
}
} catch {
@@ -233,7 +239,11 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
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(); }
else {
event.clipboardData.setData("text/plain", copyTableCells(source(), range));
event.clipboardData.setData("text/html", renderMarkdownHtml(copyTableMarkdown(source(), range), new Map()));
if (action === "cut") clearCells();
}
}, { ...options, capture: true });
// Spreadsheet data pasted while editing one cell becomes a grid operation.
wrapper.addEventListener("paste", event => {
+11 -2
View File
@@ -1,5 +1,6 @@
import { flushSync, mount, unmount } from "svelte";
import { getSearchQuery, search, type SearchQuery } from "@codemirror/search";
import { runScopeHandlers } from "@codemirror/view";
import { closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, search, selectMatches, setSearchQuery, type SearchQuery } from "@codemirror/search";
import FindPanel from "./FindPanel.svelte";
export const writerSearch = search({
@@ -12,7 +13,15 @@ export const writerSearch = search({
dom,
top: true,
mount() {
panel = mount(FindPanel, { target: dom, props: { view } });
panel = mount(FindPanel, { target: dom, props: { target: {
query: getSearchQuery(view.state), readOnly: view.state.readOnly,
setQuery(query) { view.dispatch({ effects: setSearchQuery.of(query) }); },
next(backward) { (backward ? findPrevious : findNext)(view); },
selectAll() { selectMatches(view); },
replace(all) { (all ? replaceAll : replaceNext)(view); },
close() { closeSearchPanel(view); view.focus(); },
keydown(event) { return runScopeHandlers(view, event, "search-panel"); },
} } });
flushSync();
dom.querySelector<HTMLInputElement>("[main-field]")?.select();
},
+4
View File
@@ -1,5 +1,9 @@
export type Locale = 'en' | 'fr' | 'ja' | 'zh-CN';
export const messageRows: [string, string, string, string][] = [
["{name}: package applied.", "{name} : paquet appliqué.", "{name}: パッケージを適用しました。", "{name}:已应用软件包。"],
["To update a plugin, select its new ZIP or release link. Its settings and enabled state stay the same.", "Pour mettre à jour un plug-in, sélectionnez son nouveau ZIP ou lien de version. Ses paramètres et son état restent identiques.", "プラグインを更新するには、新しいZIPまたはリリースリンクを選択してください。設定と有効状態は保持されます。", "要更新插件,请选择新的 ZIP 或发行链接。设置和启用状态保持不变。"],
["Update {current} → {next}. Settings and enabled state stay the same.", "Mise à jour {current} → {next}. Les paramètres et l’état restent identiques.", "{current} → {next} に更新します。設定と有効状態は保持されます。", "更新 {current} → {next}。设置和启用状态保持不变。"],
["Apply packages", "Appliquer les paquets", "パッケージを適用", "应用软件包"],
[
"Settings",
"Paramètres",
+32 -1
View File
@@ -2,6 +2,9 @@
import { t } from "$lib/i18n";
import { pluginHost } from "$lib/plugins/registry";
import type { GitLineInfo } from "$lib/git/contracts";
import FindPanel from "$lib/editor/FindPanel.svelte";
import { readingSearch } from "$lib/editor/readingSearch";
import type { FindTarget } from "$lib/editor/findTarget";
import EditorHost from "$lib/editor/EditorHost.svelte";
import LiveWriter from "$lib/editor/LiveWriter.svelte";
import { tick } from "svelte";
@@ -69,6 +72,32 @@
let element: HTMLDivElement | undefined = $state();
let writerEditor: LiveWriter | undefined = $state();
let sourceEditor: EditorHost | undefined = $state();
let readingFind = $state.raw<FindTarget>();
let readingFindPanel = $state<FindPanel>();
$effect(() => { void buffer?.id; void reading; void previewMode; readingFind = undefined; });
async function documentSearch(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest('[role="menu"], dialog, [role="dialog"]')) return;
const key = event.key.toLowerCase();
const open = (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && (key === "f" || key === "h");
const advance = key === "f3" && !event.ctrlKey && !event.metaKey && !event.altKey;
if ((!open && !advance) || buffer?.kind !== "text") return;
event.preventDefault(); event.stopPropagation();
const inReading = reading && (previewMode === "preview" || event.target instanceof Element && (!!event.target.closest(".md-page") || !!readingFind && !!event.target.closest(".rs-find-bar")));
if (inReading) {
const root = element?.querySelector<HTMLElement>(".reading");
if (!root) return;
sourceEditor?.closeFind();
writerEditor?.closeFind();
readingFind ??= readingSearch(root, () => { readingFind = undefined; });
await tick();
if (advance) readingFind.next(event.shiftKey);
else readingFindPanel?.focus();
} else {
readingFind = undefined;
if (writerEditor) { if (advance) writerEditor.nextMatch(event.shiftKey); else writerEditor.openFind(key === "h"); }
else if (sourceEditor) { if (advance) sourceEditor.nextMatch(event.shiftKey); else await sourceEditor.openFind(key === "h"); }
}
}
const shouldFocusOnMount = () => active && !modeControls?.contains(document.activeElement);
export function focusEditor() {
if (reading) element?.querySelector<HTMLElement>(".reading")?.focus({ preventScroll: true });
@@ -145,7 +174,8 @@
</div>
</div>
{:else}
<div class="editor" class:pane-active={active} bind:this={element}>
<!-- svelte-ignore a11y_no_static_element_interactions (Capture document shortcuts before nested editor handlers.) -->
<div class="editor" class:pane-active={active} bind:this={element} onkeydowncapture={documentSearch}>
<div class="chrome-bar">
<span class="breadcrumb" title={buffer.relPath}>{buffer.relPath}</span>
{#if lineInfo}
@@ -179,6 +209,7 @@
/>
</div>
</div>
{#if readingFind}<FindPanel bind:this={readingFindPanel} target={readingFind} />{/if}
<div class="body" class:split={reading && canPreview && previewMode === "split"}>
{#if isImage && buffer.imageUrl}
<ImageViewer src={buffer.imageUrl} name={buffer.name} />
+10 -8
View File
@@ -702,14 +702,16 @@
}
}
async function createTreeNote(parent: string, template?: NoteTemplate) {
try {
const path = await createNote(parent, template);
await load(parent);
onCreated?.({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
} catch (reason) { error = String(reason); }
}
function paneMenuItems(parent: string): MenuItem[] {
const fromTemplate = async (template?: NoteTemplate) => {
try {
const path = await createNote(parent, template);
await load(parent);
onCreated?.({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
} catch (reason) { error = String(reason); }
};
const fromTemplate = (template?: NoteTemplate) => createTreeNote(parent, template);
return [
{
kind: "action",
@@ -881,7 +883,7 @@
<div class="wrap">
<div class="ribbon tree-tools">
<IconButton icon="file-plus" label={$t("New file")} onclick={() => void createIn("", "file")} />
<IconButton icon="file-plus" label={$t("New note")} onclick={() => void createTreeNote("")} />
<IconButton icon="folder-plus" label={$t("New folder")} onclick={() => void createIn("", "folder")} />
<IconButton
icon="sort"
+26 -4
View File
@@ -4,6 +4,13 @@
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { actionIcons } from "$lib/ui/actionIcons";
import TabIcon from "$lib/ui/TabIcon.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
function tabTooltip(node: HTMLElement, label: string) {
let text = label;
const dispose = attachTooltip(node, () => text);
return { update(value: string) { text = value; }, destroy: dispose };
}
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
import type { WorkbenchTab } from "$lib/workspace/workbenchTabs";
@@ -35,6 +42,16 @@
let menuAnchor: HTMLButtonElement | undefined;
let menuPath = $state<string | null>(null);
let receiving = $state(false);
let transferFrame = 0;
let transferX = 0;
function scrollTransfer() {
if (!receiving) { transferFrame = 0; return; }
const bounds = bar.getBoundingClientRect();
const speed = transferX < bounds.left + 28 ? -10 : transferX > bounds.right - 28 ? 10 : 0;
if (speed) { bar.scrollLeft += speed; transferIndex(transferX); }
transferFrame = requestAnimationFrame(scrollTransfer);
}
function startTabTransfer(event: DragEvent, tab: WorkbenchTab) {
const data = tabDragData(tab);
@@ -59,13 +76,18 @@
event.preventDefault();
event.dataTransfer.dropEffect = "move";
receiving = true;
transferX = event.clientX;
if (!transferFrame) transferFrame = requestAnimationFrame(scrollTransfer);
const bounds = bar.getBoundingClientRect();
if (event.clientX < bounds.left + 28) bar.scrollLeft -= 10;
else if (event.clientX > bounds.right - 28) bar.scrollLeft += 10;
transferIndex(event.clientX);
}
function finishTabTransfer() { dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false; }
function finishTabTransfer() {
dragged = dropBefore = dropAfter = null; receiving = false; suppressClick = false;
cancelAnimationFrame(transferFrame); transferFrame = 0;
}
function dropTab(event: DragEvent) {
const data = event.dataTransfer?.getData(transferType);
@@ -237,7 +259,7 @@
window.addEventListener("keydown", onEscape, true);
}
onDestroy(() => { cancelDrag(); closeMenu(); });
onDestroy(() => { cancelDrag(); finishTabTransfer(); closeMenu(); });
function onMiddleDown(event: MouseEvent) {
if (event.button === 1) {
@@ -271,7 +293,7 @@
aria-controls={tab.panelId}
aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
title={`${tab.title}\n${tab.draggable ? $t("Drag to reorder or move to another RuneStone window.") : $t("Drag to reorder.")} ${$t("Right-click for tab actions.")}`}
use:tabTooltip={`${tab.title}\n${tab.draggable ? $t("Drag to reorder or move to another RuneStone window.") : $t("Drag to reorder.")} ${$t("Right-click for tab actions.")}`}
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }}
draggable={!!tab.draggable}
@@ -295,7 +317,7 @@
class="close"
type="button"
aria-label={$t("Close {name}", { name: tab.name })}
title={$t("Close {name}", { name: tab.name })}
use:tabTooltip={$t("Close {name}", { name: tab.name })}
onclick={() => onClose(tab.relPath)}
onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
+47 -10
View File
@@ -4,7 +4,7 @@
import PluginTools from "$lib/plugins/PluginTools.svelte";
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab } from "$lib/plugins/external";
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
import { onMount, onDestroy, tick, untrack } from "svelte";
@@ -146,6 +146,7 @@
let workbenchReady = $state(false);
let documents: Documents | null = null;
let paneComponents = $state<Record<string, EditorPane | undefined>>({});
let pluginPaneComponents = $state<Record<string, PluginEditor | undefined>>({});
function activeEditor() { return paneComponents[documentPanes.active]; }
let fileTree: FileTree | undefined = $state();
let closingTabs = false;
@@ -216,7 +217,7 @@
...tabs.map(tab => ({
id: tab.tabId ?? tab.id, relPath: tab.relPath, name: tab.name,
title: tab.kind === "empty" ? tab.name : tab.relPath,
dirty: tab.contents !== tab.saved, pinned: !!tab.pinned, buffer: tab,
dirty: tab.contents !== tab.saved, pinned: !!tab.pinned, draggable: desktop, buffer: tab,
})),
...$pluginEditors.map(plugin => ({
id: plugin.key, relPath: `plugin:${plugin.key}`, name: plugin.title,
@@ -236,10 +237,35 @@
});
function workingTabDragData(tab: WorkbenchTab) {
const view = $pluginEditors.find(view => view.key === tab.id);
return view ? pluginTabDragData(view) : undefined;
if (view) return pluginTabDragData(view);
const item = workingTabs.find(item => item.id === tab.id);
if (!item || !workspace || !desktop) return;
try { return JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); }
catch (reason) { error = String(reason); return; }
}
async function receiveTab(data: string, index: number) {
try {
const payload = JSON.parse(data);
if (typeof payload?.tabTransfer === "string") {
if (!/^[0-9a-f-]{36}$/i.test(payload.tabTransfer)) throw new Error("Invalid tab transfer.");
const key = `runestone.tab-transfer.${payload.tabTransfer}`;
const raw = localStorage.getItem(key);
if (!raw) throw new Error("This tab transfer expired. Drag the tab again.");
const transfer = JSON.parse(raw);
if (!workspace || switching || !documents || transfer.root !== workspace.root) throw new Error("Move tabs only between windows of the same workspace.");
if (!Number.isFinite(transfer.created) || transfer.created < Date.now() - 120000
|| !transfer.buffer || typeof transfer.buffer.relPath !== "string" || typeof transfer.buffer.contents !== "string"
|| typeof transfer.buffer.saved !== "string") throw new Error("Invalid tab transfer.");
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open.");
selectTab(transfer.buffer.relPath);
setReading(transfer.reading === true);
await tick();
moveWorkingTab(transfer.buffer.relPath, index);
localStorage.setItem(key + ".accepted", "true");
localStorage.removeItem(key);
error = null;
return;
}
await dropPluginTab(data);
if ($pluginView?.placement === "editor") moveWorkingTab(`plugin:${$pluginView.key}`, index);
error = null;
@@ -350,7 +376,9 @@
const transfer = JSON.parse(raw);
if (transfer.root === workspace.root && transfer.created > Date.now() - 120000
&& (transfer.buffer || transfer.plugin)) {
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") documents.importTab(transfer.buffer);
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") {
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window.");
}
else if (transfer.plugin) {
const deadline = Date.now() + 15000;
while (!await restorePluginTab(transfer.plugin)) {
@@ -413,6 +441,13 @@
const action = pluginTabActions(tab.plugin).find(action => "label" in action && /(?:move|open).*new window/i.test(action.label));
if (action && "run" in action && !action.disabled) { action.run?.(); return; }
}
let transfer: ReturnType<typeof prepareTabTransfer> | undefined;
try {
transfer = prepareTabTransfer(tab, keepSource, true);
await workspaceOpenWindow(workspace.root, transfer.token);
} catch (reason) { transfer?.finish(); error = String(reason); }
}
function prepareTabTransfer(tab: EditorTab, keepSource = false, reportTimeout = false) {
const current = documents;
const bufferSnapshot = (buffer?: OpenBuffer) => JSON.stringify(buffer ? { ...buffer, diskError: buffer.diskError ?? null } : undefined);
const snapshot = "buffer" in tab ? bufferSnapshot(tab.buffer) : JSON.stringify(pluginTabState(tab.plugin));
@@ -432,11 +467,11 @@
finish();
};
try {
localStorage.setItem(key, JSON.stringify({ root: workspace.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }));
localStorage.setItem(key, JSON.stringify({ root: workspace!.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }));
window.addEventListener("storage", accepted);
timer = setTimeout(() => { finish(); error = "The new window did not accept the tab. The source tab remains open."; }, 30000);
await workspaceOpenWindow(workspace.root, token);
} catch (reason) { finish(); error = String(reason); }
timer = setTimeout(() => { finish(); if (reportTimeout) error = "The new window did not accept the tab. The source tab remains open."; }, 30000);
return { token, finish };
} catch (reason) { finish(); throw reason; }
}
function pinWorkingTab(path: string) {
const tab = workingTabs.find(tab => tab.relPath === path);
@@ -726,7 +761,9 @@
if (event.defaultPrevented) return;
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f" && editorPluginVisible && $pluginView) {
if (findPluginEditor($pluginView)) { event.preventDefault(); return; }
event.preventDefault();
void pluginPaneComponents[$pluginView.key]?.openFind();
return;
}
const action = pluginHost.get("terminal")?.shortcut(event);
const terminalTarget = event.target instanceof Element && !!event.target.closest(".dock");
@@ -1218,7 +1255,7 @@
onCloseTabs={(path, scope) => void closeTabs(path, scope)} fileActions={workingTabFileActions} tabActions={workingTabActions}
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
{/if}
<PluginEditor view={pane} />
<PluginEditor bind:this={pluginPaneComponents[pane.key]} view={pane} />
</div>
{/each}
</div>
+35 -4
View File
@@ -1,14 +1,44 @@
<script lang="ts">
import { untrack } from "svelte";
import { mountPluginView, type OpenPluginView } from "./external";
import { tick, untrack } from "svelte";
import { findPluginEditor, mountPluginView, type OpenPluginView } from "./external";
import FindPanel from "$lib/editor/FindPanel.svelte";
import { readingSearch } from "$lib/editor/readingSearch";
import type { FindTarget } from "$lib/editor/findTarget";
let { view }: { view: OpenPluginView } = $props();
let host: HTMLDivElement | undefined = $state();
let error = $state("");
let findTarget = $state.raw<FindTarget>();
let findPanel = $state<FindPanel>();
let returnFocus: HTMLElement | null = null;
export async function openFind() {
if (findPluginEditor(view)) return;
if (!view.document || view.icon === "kanban" || !host) return;
if (!findTarget) {
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
findTarget = readingSearch(host, () => { findTarget = undefined; }, {
includeButtons: true,
focusOnClose: () => (returnFocus?.isConnected ? returnFocus : host)?.focus({ preventScroll: true }),
});
}
await tick();
findPanel?.focus();
}
function searchKey(event: KeyboardEvent) {
if (event.target instanceof Element && event.target.closest('dialog, [role="dialog"], [role="menu"]')) return;
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === "f") {
event.preventDefault(); event.stopPropagation(); void openFind();
} else if (findTarget && event.key === "F3" && !event.ctrlKey && !event.metaKey && !event.altKey) {
event.preventDefault(); event.stopPropagation(); findTarget.next(event.shiftKey);
}
}
$effect(() => {
const element = host;
if (!element) return;
error = "";
findTarget = undefined;
let cancelled = false;
let cleanup: (() => void | Promise<void>) | undefined;
void untrack(() => mountPluginView(view.owner, view.id, element, view.document)).then(dispose => {
@@ -23,10 +53,11 @@
</script>
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane"
role="tabpanel" aria-label={view.title} tabindex="-1">
role="tabpanel" aria-label={view.title} tabindex="-1" onkeydowncapture={searchKey}>
{#if error}<p class="error" role="alert">{error}</p>{/if}
{#if findTarget}<FindPanel bind:this={findPanel} target={findTarget} />{/if}
{#key `${view.owner}:${view.id}:${view.document?.path ?? ""}`}
<div class="plugin-editor-content" bind:this={host}></div>
<div class="plugin-editor-content" tabindex="-1" bind:this={host}></div>
{/key}
</div>
+8 -2
View File
@@ -26,6 +26,7 @@
let cancelButton: HTMLButtonElement | undefined = $state();
let previous: HTMLElement | null = null;
const external = $derived($installedPlugins.plugins);
const hasUpdates = $derived(candidates.some(candidate => external.some(plugin => plugin.manifest.id === candidate.manifest?.id)));
$effect(() => {
if (modal && (plan || candidates.length || gitForm)) {
if (!modal.open) { previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; modal.showModal(); }
@@ -55,7 +56,7 @@
async function install(enabled: boolean) {
await run(async () => {
const result = await invoke<{ name: string; error: string | null }[]>("plugins_install", { tokens: selected, enabled });
message = result.filter(item => !item.error).map(item => $t(enabled ? "{name} installed and enabled." : "{name} installed.", { name: item.name })).join(" ");
message = result.filter(item => !item.error).map(item => $t("{name}: package applied.", { name: item.name })).join(" ");
error = result.filter(item => item.error).map(item => `${item.name}: ${item.error}`).join("\n");
await invoke("plugins_cancel", { tokens: candidates.map(item => item.token) });
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
@@ -103,6 +104,7 @@
<h2>{$t("Plug-ins")}</h2>
<p>{$t("Install a plugin ZIP file or get a release from a Git repository link.")}</p>
<p>{$t("To update a plugin, select its new ZIP or release link. Its settings and enabled state stay the same.")}</p>
<div class="toolbar">
<button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />{$t("Install plugin ZIP")}</button>
<button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />{$t("Install from Git link")}</button>
@@ -180,12 +182,15 @@
<div class="candidate">
<label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? $t("Invalid package")}</label>
{#if candidate.manifest}<p>{candidate.manifest.author} · {candidate.manifest.version}</p><p>{candidate.manifest.description}</p><p class="path">{$t("Destination: {path}", { path: `${$installedPlugins.root}\\${candidate.manifest.id}` })}</p>{/if}
{#each external.filter(plugin => plugin.manifest.id === candidate.manifest?.id) as installed}
<p>{$t("Update {current} → {next}. Settings and enabled state stay the same.", { current: installed.manifest.version, next: candidate.manifest!.version })}</p>
{/each}
<p class="path">{$t("Source: {path}", { path: candidate.source })}</p>
{#if candidate.error}<p class="error">{candidate.error}</p>{/if}
</div>
{/each}
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button disabled={busy || !selected.length} onclick={() => install(false)}>{$t("Install")}</button><button disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button></footer>
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button disabled={busy || !selected.length} onclick={() => install(false)}>{$t(hasUpdates ? "Apply packages" : "Install")}</button>{#if !hasUpdates}<button disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button>{/if}</footer>
{/if}
</dialog>
{/if}
@@ -221,6 +226,7 @@
footer { justify-content: flex-end; margin-top: var(--rs-settings-section-gap); }
.candidate { padding: var(--rs-settings-row-padding) 0; border-bottom: 1px solid var(--rs-border); }
.candidate label { display: flex; gap: 8px; }
input[type=checkbox] { accent-color: var(--rs-accent); }
.field { display: flex; flex-direction: column; gap: 6px; margin: 10px 0; }
.field input { min-width: 0; min-height: var(--rs-settings-control-height); padding: 4px 8px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
@media (max-width: 420px) {
+3 -1
View File
@@ -343,7 +343,9 @@ export async function setPluginEnabled(id: string, enabled: boolean, hash?: stri
export async function runPluginCommand(owner: string, id: string) {
try { await sessions.get(owner)?.session.run(id); } catch (error) { report(owner, error); throw error; }
}
export function openPluginView(owner: string, id: string) { show(owner, id); }
export function openPluginView(owner: string, id: string) {
void sessions.get(owner)?.session.launch(id).catch(error => report(owner, error));
}
export async function mountPluginView(owner: string, id: string, element: HTMLElement, document?: PluginDocumentContext, surface: "settings" | "view" = "view"): Promise<Dispose> {
const session = sessions.get(owner)?.session;
if (!session) throw new Error("The plugin is disabled.");
+8 -3
View File
@@ -4,7 +4,6 @@ import { registerCompletionInput } from "../completion/input.ts";
import { showActionMenu } from "../ui/managedActionMenu.ts";
import { backgroundHub } from "./backgrounds.ts";
import type { BackgroundFiles } from "./backgroundContracts.ts";
import { pluginTranslation } from "./translation.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -55,7 +54,6 @@ export class ExternalSession {
};
const api: PluginApi = {
id: this.id, signal: this.controller.signal,
i18n: pluginTranslation(() => this.check(), off => { this.contributions.push(off); }),
...(this.services.backgrounds ? { backgrounds: {
version: 1 as const,
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
@@ -101,7 +99,7 @@ export class ExternalSession {
},
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
registerCommand: item => { if (item.category !== undefined && !["open", "action"].includes(item.category)) throw new Error("Unknown plugin command category."); if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
registerView: item => { if ([item.settings, item.launcher, item.navigation, item.toolbar].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); if (item.placement !== undefined && !["dialog", "editor", "sidebar"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
registerView: item => { if ([item.settings, item.launcher, item.navigation, item.toolbar].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); if (item.placement !== undefined && !["dialog", "editor", "sidebar"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (item.launch !== undefined && typeof item.launch !== "function") throw new Error("A view launch handler must be a function."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
registerTabDrop: receive => { this.check(); if (typeof receive !== "function" || this.receiveTab) throw new Error("Invalid or duplicate tab receiver."); this.receiveTab = receive; },
updateViewTitle: (id, title) => {
this.check(); const view = this.views.get(id);
@@ -171,6 +169,13 @@ export class ExternalSession {
await deadline(this.activation);
}
async run(id: string) { this.check(); const command = this.commands.get(id); if (!command) throw new Error("Unknown plugin command."); await command.run(); }
async launch(id: string) {
this.check();
const view = this.views.get(id);
if (!view) throw new Error("Unknown plugin view.");
if (view.launch) await view.launch();
else this.show(id);
}
private backgroundRequest<T>(request: () => Promise<T>): Promise<T> {
this.check();
return request().then(value => { this.check(); return value; });
+1 -2
View File
@@ -6,7 +6,7 @@ export type { BackgroundFrame, BackgroundApi } from "./backgroundContracts.ts";
/** Package API v1. Compiled plugins export activate(api). */
export type Dispose = () => void | Promise<void>;
export interface PluginCommand { id: string; title: string; icon?: ActionIcon | PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> }
export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise<void>; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; launch?: () => void | Promise<void>; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise<void>; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string }
export interface PluginDocumentContext { id: string; path: string }
export interface PluginDocumentType {
@@ -20,7 +20,6 @@ export interface PluginDocumentType {
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PluginApi {
i18n?: import("./translation.ts").PluginTranslation;
backgrounds?: import("./backgroundContracts.ts").BackgroundApi;
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
git?: import("../git/contracts.ts").GitApi;
-30
View File
@@ -1,30 +0,0 @@
import { get } from 'svelte/store';
import { locale, translate, type Locale } from '../i18n/index.ts';
export type PluginCatalogs = Partial<Record<Locale, Record<string, string>>>;
export interface PluginTranslation {
readonly locale: Locale;
t(message: string, values?: Record<string, string | number>, catalogs?: PluginCatalogs): string;
subscribe(listener: (language: Locale) => void): () => void;
}
/** Translates only explicit interface messages. Document content stays with the plugin. */
export function pluginTranslation(check: () => void, track: (cleanup: () => void) => void): PluginTranslation {
return {
get locale() { check(); return get(locale); },
t(message, values = {}, catalogs = {}) {
check();
const language = get(locale);
const catalog = Object.hasOwn(catalogs, language) ? catalogs[language] : undefined;
if (!catalog || !Object.hasOwn(catalog, message)) return translate(language, message, values);
return catalog[message].replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
},
subscribe(listener) {
check();
if (typeof listener !== 'function') throw new Error('A language listener must be a function.');
const off = locale.subscribe(listener);
track(off);
return off;
},
};
}
+1
View File
@@ -176,6 +176,7 @@
.preview-function{color:var(--rs-syntax-function,var(--rs-accent-2))}
.preview-number{color:var(--rs-syntax-number,var(--rs-special))}
.overlay-controls{display:flex;align-items:center;flex-wrap:wrap;gap:var(--rs-settings-gap);max-width:100%}
.overlay-controls output{width:4ch;flex:0 0 4ch;text-align:right;font-variant-numeric:tabular-nums}
.overlay-controls input[type=range]{width:160px;max-width:100%;min-width:0}
input[type=checkbox]{accent-color:var(--rs-accent)}
.overlay-controls input[type=range]{appearance:none;background:transparent;height:var(--rs-settings-control-height);margin:0;cursor:pointer}
+8 -1
View File
@@ -107,7 +107,7 @@ export function applyTransparency(value: Appearance['transparency'], root: HTMLE
root.style.setProperty('--rs-surface-opacity', `${100 - amount}%`);
root.style.setProperty('--rs-editor-surface-opacity', `${100 - amount * 10 / 18}%`);
root.style.setProperty('--rs-hover-surface-opacity', `${100 - amount * 8 / 18}%`);
root.style.setProperty('--rs-transparent-plugin-bg', amount ? 'transparent' : 'var(--rs-bg)');
root.style.setProperty('--rs-transparent-plugin-bg', 'transparent');
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
@@ -194,6 +194,13 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
for (const [key, color] of Object.entries(characterSyntax(theme))) root.style.setProperty(`--rs-${key}`, color);
root.style.setProperty('--rs-danger', 'var(--rs-error)');
if (custom) for (const [key, color] of Object.entries(custom.colors)) root.style.setProperty(`--rs-${key}`, color);
// Keep the theme hue while exposing the background beneath selected text.
const selection = root.style.getPropertyValue('--rs-selection').trim().slice(1);
const fullSelection = selection.length <= 4 ? [...selection].map(part => part + part).join('') : selection;
if (/^[0-9a-f]{6}([0-9a-f]{2})?$/i.test(fullSelection)) {
const alpha = Math.min(166, fullSelection.length === 8 ? parseInt(fullSelection.slice(6), 16) : 255);
root.style.setProperty('--rs-selection', `#${fullSelection.slice(0, 6)}${alpha.toString(16).padStart(2, '0')}`);
}
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
}
export function saveAppearance(value: Appearance) {
+1 -1
View File
@@ -48,7 +48,7 @@ export class Documents {
importTab(buffer: OpenBuffer) {
if (this.disposed || this.buffers.some(tab => tab.relPath === buffer.relPath)) return false;
this.buffers = this.buffers.filter(tab => tab.kind !== "empty");
this.buffers = this.buffers.filter(tab => tab.kind !== "empty" || tab.pinned || tab.contents !== tab.saved);
this.buffers.push({ ...buffer, id: crypto.randomUUID(), tabId: undefined });
this.select(buffer.relPath);
return true;
+4 -3
View File
@@ -18,7 +18,8 @@ function parseAttrs(raw: string): Record<string, string> {
}
export function htmlToMarkdown(html: string): string {
const tokens = html.match(/<\/?[a-zA-Z][^>]*>|[^<]+/g) ?? [];
// Windows HTML clipboard fragments include comments around the copied content.
const tokens = html.replace(/<!--[\s\S]*?(?:-->|$)/g, "").match(/<\/?[a-zA-Z][^>]*>|[^<]+/g) ?? [];
const out: string[] = [];
const list: string[] = [];
let inPre = false;
@@ -39,7 +40,7 @@ export function htmlToMarkdown(html: string): string {
const spanKind: string[] = [];
function flushInline(): string {
const text = unescapeHtml(inline.replace(/\s+/g, " ").trim());
const text = unescapeHtml(inline.replace(/\s+/g, " ").replace(/\s*<br>\s*/g, "<br>").trim());
inline = "";
return text;
}
@@ -185,7 +186,7 @@ export function htmlToMarkdown(html: string): string {
const tag = (space === -1 ? body : body.slice(0, space)).toLowerCase();
const attrs = space === -1 ? {} : parseAttrs(body.slice(space + 1));
if (tag === "br") {
inline += "\n";
inline += inCell ? "<br>" : "\n";
continue;
}
if (tag === "img") {