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

This commit is contained in:
Knotty Wyvern
2026-10-14 16:19:51 -07:00
parent f6eaa52949
commit edef2520af
113 changed files with 5722 additions and 386 deletions
+25 -10
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import Icon from '$lib/ui/Icon.svelte';
import { state as browserState, pageErrors, request, frames, pageEvents, type PageMenu, type BrowserFrame } from './client';
import type { ActionMenuItem } from '$lib/ui/actionMenu';
import { showActionMenu } from '$lib/ui/managedActionMenu';
@@ -13,14 +14,24 @@
const tabId = $derived(status.tabId);
const ready = $derived(status.phase === 'ready');
const current = $derived($browserState?.tabs.find(tab => tab.id === tabId));
const blank = $derived(!current?.url || current.url === 'about:blank');
let address = $state(''); let editing = $state(false);
let image = $state(''); let surface: HTMLDivElement; let addressField: HTMLInputElement;
let width = 1000, height = 700, textInput: HTMLTextAreaElement, composing = false;
let inputQueue = Promise.resolve();
const orderedInput = (command: string, args: Record<string, unknown>) => inputQueue = inputQueue.then(() => send(command, args));
function pageFocus(focused: boolean) { void orderedInput('focus', { focused }); }
const wheels = new WheelQueue(input => send('input', { input }));
let displayedFrame: BrowserFrame | undefined;
let closeMenu: (() => void) | undefined;
function chooseProfile(event: MouseEvent) {
closeMenu?.();
const anchor = event.currentTarget as HTMLButtonElement;
const rect = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: 'Browser profile',
items: ($browserState?.profiles || []).map(profile => ({ label: profile.name, radio: true,
checked: profile.id === current?.profileId, run: () => void openTab(profile.id) })) }).close;
}
let opening = $state(false), openingError = $state(''), mounted = $state(false);
let findOpen = $state(false), findText = $state('');
let findField: HTMLInputElement | undefined = $state();
@@ -60,7 +71,9 @@
frames.set(id, frame => {
if (displayedFrame) acknowledgeFrame();
if (frame.width > 0 && frame.height > 0 && ['image/png', 'image/jpeg'].includes(frame.mime)) {
displayedFrame = frame; image = `data:${frame.mime};base64,${frame.data}`;
displayedFrame = frame;
if (blank) { image = ''; acknowledgeFrame(); }
else image = `data:${frame.mime};base64,${frame.data}`;
}
});
pageEvents.set(id, event => {
@@ -199,18 +212,18 @@
if (type === 'keyDown' && [...event.key].length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void orderedInput('insertText', { text: event.key });
}
</script>
<svelte:window onblur={stopScroll} />
<svelte:document onvisibilitychange={() => { if (document.hidden) stopScroll(); }} />
<div class="browser" data-browser-tab={tabId} data-browser-state={status.phase}>
<svelte:window onblur={() => { stopScroll(); pageFocus(false); }} onfocus={() => { if (surface?.contains(document.activeElement)) pageFocus(true); }} />
<svelte:document onvisibilitychange={() => { if (document.hidden) { stopScroll(); pageFocus(false); } else if (surface?.contains(document.activeElement)) pageFocus(true); }} />
<div class="browser" class:blank data-browser-tab={tabId} data-browser-state={status.phase}>
<form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}>
<IconButton icon="arrow-left" label="Back" disabled={!ready || !current?.canBack} onclick={() => void send('back')} />
<IconButton icon="arrow-right" label="Forward" disabled={!ready || !current?.canForward} onclick={() => void send('forward')} />
<IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : 'Reload'} disabled={!ready} onclick={() => void send(current?.loading ? 'stop' : 'reload')} />
<input bind:this={addressField} bind:value={address} disabled={!ready} onfocus={() => editing = true} onblur={() => editing = false} aria-label="Address or search" placeholder="Search or enter an address" spellcheck="false" autocomplete="off">
<IconButton icon="bookmark" label="Bookmark this page" disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} />
<select aria-label="Browser profile" value={current?.profileId} disabled={opening} onchange={event => void openTab(event.currentTarget.value)}>
{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}
</select>
<button type="button" class="profile-choice" aria-label="Browser profile" aria-haspopup="menu" disabled={opening} onclick={chooseProfile}>
{$browserState?.profiles.find(profile => profile.id === current?.profileId)?.name ?? 'Profile'}<Icon icon="chevron-down" />
</button>
</form>
{#if findOpen}
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) -->
@@ -240,13 +253,14 @@
<div class="surface" class:autoscroll={!!scrollAnchor} bind:this={surface} role="application" aria-label="Web page" tabindex="0"
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
onfocusin={() => pageFocus(true)} onfocusout={event => { if (!surface.contains(event.relatedTarget as Node | null)) pageFocus(false); }}
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
<textarea class="text-input" bind:this={textInput} aria-label="Web page text input" autocomplete="off" spellcheck="false"
oncompositionstart={() => composing = true}
oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }}
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
onblur={stopScroll}></textarea>
{#if image && ready}<img src={image} alt="Web page rendered by the browser" draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if image && ready && !blank}<img src={image} alt="Web page rendered by the browser" draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
</div>
</div>
@@ -255,9 +269,10 @@
.browser{display:flex;flex-direction:column;width:100%;height:100%;min-height:200px;background:var(--rs-bg);color:var(--rs-text);font-family:var(--rs-font-ui)}
.toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)}
.toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px}
input,select{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
input{flex:1}select{max-width:160px}input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent)}
input,.profile-choice{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-accent)}
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
.browser.blank,.blank .surface{background:transparent}
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006}
img{display:block;width:100%;height:100%;pointer-events:none;user-select:none}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
+15 -3
View File
@@ -1,5 +1,7 @@
<script lang="ts">
import { onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { request } from './client';
let { profileId }: { profileId: string } = $props();
type Cookie = { id: string; name: string; domain: string; path: string };
@@ -7,6 +9,16 @@
type Data = { profileId: string; cookies: Cookie[]; history: Visit[] };
let data = $state<Data | null>(null), error = $state(''), busy = $state(false), query = $state('');
let kind = $state<'cookies' | 'history'>('cookies');
let closePicker = () => {};
onDestroy(() => closePicker());
function chooseKind(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement, rect = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: 'Web data type',
parent: anchor.closest('dialog') ?? undefined,
items: (['cookies', 'history'] as const).map(value => ({ label: value === 'cookies' ? 'Cookies' : 'History',
radio: true, checked: kind === value, run: () => kind = value })) }).close;
}
let generation = 0;
const cookies = $derived((data?.cookies || []).filter(item => `${item.domain} ${item.name} ${item.path}`.toLowerCase().includes(query.toLowerCase())));
const history = $derived((data?.history || []).filter(item => `${item.title} ${item.url}`.toLowerCase().includes(query.toLowerCase())));
@@ -26,7 +38,7 @@
</script>
<section aria-label="Individual web data">
<div class="toolbar">
<label>Show<select aria-label="Web data type" bind:value={kind}><option value="cookies">Cookies</option><option value="history">History</option></select></label>
<div class="choice"><span>Show</span><button type="button" aria-label="Web data type" aria-haspopup="menu" onclick={chooseKind}>{kind === 'cookies' ? 'Cookies' : 'History'}<Icon icon="chevron-down" /></button></div>
<label class="search">Filter<input type="search" aria-label="Filter web data" bind:value={query} placeholder="Search this profile"></label>
<button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />Refresh</button>
</div>
@@ -45,9 +57,9 @@
</section>
<style>
section{margin-top:var(--rs-settings-section-gap)}.toolbar{display:flex;align-items:end;gap:var(--rs-settings-gap);flex-wrap:wrap}
label{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,select,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
label,.choice{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
button{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;cursor:pointer}button:hover{background:var(--rs-bg-active)}button:disabled{opacity:.6;cursor:wait}
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
button:focus-visible,input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
p,small{font-size:var(--rs-settings-description-size);color:var(--rs-text-dim);line-height:1.5}.entries{max-height:320px;overflow:auto;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);padding:0 var(--rs-settings-row-padding)}
.entry{display:flex;gap:var(--rs-settings-gap);align-items:center;padding:var(--rs-settings-row-padding) 0}.entry+.entry{border-top:1px solid var(--rs-border)}.entry>div{flex:1;min-width:0;overflow-wrap:anywhere}small{display:block}strong{font-weight:500}[role=alert]{color:var(--rs-error)}
@media(max-width:450px){.entry{flex-wrap:wrap}.entry>div{flex-basis:100%}}
+31 -9
View File
@@ -4,12 +4,14 @@
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession } from "./sessions";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
import { codeFont } from "./codeFont";
import { connectMonacoCompletion } from "$lib/completion/monaco";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { codeMenu } from "./codeMenu";
import type { TableContextActions } from "./tableCellActions";
import { documentLinks, documentLinkAt } from "./documentLinks";
@@ -22,13 +24,15 @@
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
};
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
export function focus() { editor?.focus(); }
let ready = $state(0);
let applying = false;
let loadError = $state<string | null>(null);
@@ -116,7 +120,7 @@
renderWhitespace: "selection",
bracketPairColorization: { enabled: true },
overviewRulerLanes: 0,
contextmenu: !markdown,
contextmenu: false,
...monacoChrome(mode),
});
editor = view;
@@ -167,13 +171,31 @@
});
view.pushUndoStop();
},
select(from, to) {
const start = model.getPositionAt(from), end = model.getPositionAt(to);
view.setSelection(new monaco.Selection(start.lineNumber, start.column, end.lineNumber, end.column));
view.revealPositionInCenterIfOutsideViewport(end);
},
selectAll() { view.setSelection(model.getFullModelRange()); view.focus(); },
focus() { view.focus(); },
}, untrack(() => tableActions), message => { loadError = message; });
listeners.push(view.onContextMenu(event => {
event.event.preventDefault(); event.event.stopPropagation();
menu?.open(event.event.posx, event.event.posy);
}));
undo() { view.trigger("markdown-menu", "undo", null); },
redo() { view.trigger("markdown-menu", "redo", null); },
canUndo() { return model.canUndo(); },
canRedo() { return model.canRedo(); },
}, untrack(() => tableActions), message => { loadError = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
} else {
menu = codeMenu(view, message => { loadError = message; });
}
const openContextMenu = (event: MouseEvent) => {
event.preventDefault(); event.stopImmediatePropagation();
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
const selection = view.getSelection();
if (position && (!selection || selection.isEmpty() || !selection.containsPosition(position))) view.setPosition(position);
view.focus();
menu?.open(event.clientX, event.clientY, undefined, position ? model.getOffsetAt(position) : undefined);
};
el.addEventListener("contextmenu", openContextMenu, true);
listeners.push({ dispose: () => el.removeEventListener("contextmenu", openContextMenu, true) });
listeners.push(view.onKeyDown(event => {
if (event.browserEvent.key !== "ContextMenu" && !(event.shiftKey && event.browserEvent.key === "F10")) return;
event.preventDefault(); event.stopPropagation();
@@ -183,7 +205,6 @@
}));
listeners.push(view.onDidChangeCursorSelection(() => menu?.close(false)));
listeners.push(model.onDidChangeContent(() => menu?.close(false)));
}
const documentId = untrack(() => buffer.id);
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
@@ -209,6 +230,7 @@
releaseDrop?.();
listeners.forEach(listener => listener.dispose());
view?.dispose();
if (session) releaseEditorSession(session);
editor = undefined;
};
});
+28 -16
View File
@@ -1,7 +1,6 @@
<script lang="ts">
import { pluginHost } from "$lib/plugins/registry";
import { useSpellingMenu } from "./spellingMenu";
import { spellingWord } from "./spellingWord";
import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte";
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
import { EditorView, drawSelection, keymap } from "@codemirror/view";
@@ -15,11 +14,11 @@
import { workspaceReadDataUrl, workspaceReveal } from "$lib/workspace/api";
import { linkCandidates } from "$lib/workspace/markdownLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages } from "$lib/workspace/noteHtml";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession } from "./sessions";
import { editorSession, releaseEditorSession } from "./sessions";
import { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
import { imageDrops, trackImageDrop, clearImageDrop } from "./imageDrop";
@@ -27,6 +26,7 @@
import { markdownTitle } from "$lib/workspace/media";
import type { TableContextActions } from "./tableCellActions";
import { markdownMenu } from "./markdownMenu";
import type { DocumentLinkActions } from "./linkMenu";
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
import { documentLinkAt } from "./documentLinks";
@@ -42,13 +42,15 @@
focusLine?: number | null;
onSelectionLine?: (line: number) => void;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
shouldFocusOnMount?: () => boolean;
focusTitle?: boolean;
onTitleFocused?: () => void;
};
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, linkActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
let host: HTMLDivElement | undefined = $state();
let editor = $state.raw<EditorView>();
export function focus() { editor?.focus(); }
let error = $state("");
let model: import("monaco-editor").editor.ITextModel | undefined;
let ModelSelection: typeof import("monaco-editor").Selection;
@@ -195,7 +197,7 @@
if (!view.state.field(imageSource)) return false;
view.dispatch({ effects: editImageSource.of(null) }); return true;
} }, indentWithTab, ...searchKeymap, ...historyKeymap, ...defaultKeymap]), EditorView.lineWrapping,
liveMarkdown(urls, untrack(() => tableActions), {
liveMarkdown(urls, { ...untrack(() => tableActions), linkActions: () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }) }, {
open: image => onOpenLink?.(image.dataset.mdKind === "wiki" ? "wiki" : "md", image.dataset.mdSrc || ""),
reveal: async image => {
for (const path of linkCandidates(current.relPath, image.dataset.mdSrc || "", "md")) {
@@ -242,12 +244,11 @@
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
if (event.target instanceof HTMLElement && spellingWord(event.target.closest<HTMLElement>('[contenteditable="true"]') ?? event.target, event.clientX, event.clientY) && useSpellingMenu(event, view.state.selection.main.empty)) { menu?.close(false); return false; }
event.preventDefault();
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
const position = view.posAtCoords({ x: event.clientX, y: event.clientY }, false);
const selection = view.state.selection.main;
if (position !== null && (selection.empty || position < selection.from || position > selection.to)) view.dispatch({ selection: { anchor: position } });
menu?.open(event.clientX, event.clientY);
menu?.open(event.clientX, event.clientY, selection.empty && isSpellingTarget(event.target) ? position ?? undefined : undefined, position ?? undefined);
return true;
},
keydown(event, view) {
@@ -255,7 +256,7 @@
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
event.preventDefault();
const coords = view.coordsAtPos(view.state.selection.main.head);
if (coords) menu?.open(coords.left, coords.bottom);
if (coords) menu?.open(coords.left, coords.bottom, view.state.selection.main.empty ? view.state.selection.main.head : undefined);
return true;
},
mousedown(event, view) {
@@ -275,7 +276,12 @@
},
}),
];
freshState = source => EditorState.create({ doc: source, extensions });
// Start in the body so the initial caret does not reveal properties source.
// Saved selections and explicit line navigation still restore their positions.
freshState = source => {
const doc = EditorState.create({ doc: source }).doc;
return EditorState.create({ doc, selection: { anchor: documentBodyStart(doc.toString()) }, extensions });
};
const saved = session.writer;
const state = saved?.source === lastValue
? EditorState.fromJSON(saved.state, { extensions })
@@ -314,9 +320,14 @@
return { source: doc.toString(), selection: selection.main, valid: () => editor === view && view.state.doc === doc && view.state.selection.eq(selection) };
},
apply(edit) { view.dispatch({ changes: { from: edit.from, to: edit.to, insert: edit.insert }, selection: { anchor: edit.anchor, head: edit.head }, userEvent: "input.markdown", annotations: isolateHistory.of("full") }); },
select(from, to) { view.dispatch({ selection: { anchor: from, head: to }, scrollIntoView: true }); },
selectAll() { view.dispatch({ selection: { anchor: 0, head: view.state.doc.length } }); view.focus(); },
focus() { view.focus(); },
}, untrack(() => tableActions), message => { error = message; });
undo() { clearTimeout(historyTimer); model?.pushStackElement(); void model?.undo(); },
redo() { clearTimeout(historyTimer); void model?.redo(); },
canUndo() { return model?.canUndo() ?? false; },
canRedo() { return model?.canRedo() ?? false; },
}, untrack(() => tableActions), message => { error = message; }, () => ({ ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }));
if (!focusTitle && shouldFocusOnMount()) view.focus();
}).catch(reason => { if (!cancelled) error = String(reason); });
return () => {
@@ -330,6 +341,7 @@
releaseScroll?.();
if (session && editor && scroll) session.writer = { source: modelSource(editor.state), state: editor.state.toJSON(), scroll };
editor?.destroy();
if (session) releaseEditorSession(session);
releaseSelection?.();
editor = undefined;
};
@@ -404,22 +416,22 @@
.live-writer :global(.writer-heading:hover)::before { display: none; }
.live-writer :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
.live-writer :global(.cm-selectionBackground), .live-writer :global(.cm-focused .cm-selectionBackground) { background: var(--rs-bg-active); }
.live-writer :global(.cm-editor .cm-selectionLayer .cm-selectionBackground), .live-writer :global(.cm-editor.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground) { background: var(--rs-selection); }
.live-writer :global(.writer-blank) { font-size: .75em; }
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
.live-writer :global(.writer-emphasis) { font-style: italic; }
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
.live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-link-source) { color: var(--rs-accent); }
.live-writer :global(.writer-link-target) { text-decoration: underline; text-underline-offset: 3px; }
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-bg-elevated); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-code-block-bg); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; }
.live-writer :global(.writer-code-tooltip) { display: none; position: absolute; z-index: 2; top: 100%; right: 0; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: nowrap; pointer-events: none; }
.live-writer :global(.writer-code-copy:focus-visible .writer-code-tooltip) { display: block; }
.live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); }
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
+59
View File
@@ -0,0 +1,59 @@
import type { editor } from "monaco-editor";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
/** Keep Monaco editing commands in the host's shared action menu. */
export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: string) => void) {
let root: HTMLElement | undefined;
function close(focus = true) {
root?.remove(); root = undefined;
if (focus) view.focus();
}
const outside = (event: MouseEvent) => { if (root && !root.contains(event.target as Node)) close(false); };
const scroll = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
document.addEventListener("mousedown", outside, true);
document.addEventListener("scroll", scroll, true);
window.addEventListener("resize", resize);
function open(x: number, y: number) {
close(false);
const model = view.getModel(), selection = view.getSelection();
if (!model || !selection) return;
const version = model.getVersionId();
const valid = () => view.getModel() === model && !model.isDisposed() && model.getVersionId() === version && !!view.getSelection()?.equalsRange(selection);
const selected = model.getValueInRange(selection);
const replace = (text: string) => {
if (!valid()) return;
view.pushUndoStop();
view.executeEdits("code-menu", [{ range: selection, text }]);
view.pushUndoStop(); view.focus();
};
const clipboard = async (kind: "cut" | "copy" | "paste") => {
close();
try {
if (kind === "paste") replace(await navigator.clipboard.readText());
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
};
const run = (id: string) => { close(); void view.getAction(id)?.run(); };
const items: ActionMenuItem[] = [
{ label: "Undo", icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } },
{ label: "Redo", icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } },
{ separator: true },
{ label: "Change all occurrences", icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") },
{ separator: true },
{ label: "Cut", icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
{ label: "Select all", icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } },
{ separator: true },
{ label: "Command palette", icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") },
];
root = actionMenu(x, y, items, close, "Code text actions");
}
return { open, close, destroy() {
close(false);
document.removeEventListener("mousedown", outside, true);
document.removeEventListener("scroll", scroll, true);
window.removeEventListener("resize", resize);
} };
}
+8 -4
View File
@@ -1,6 +1,6 @@
import { markdownLanguage } from "@codemirror/lang-markdown";
export type DocumentLink = { from: number; to: number; kind: "md" | "wiki"; target: string };
export type DocumentLink = { from: number; to: number; targetFrom: number; targetTo: number; kind: "md" | "wiki"; target: string };
/** Source ranges survive the change from formatted text to editable Markdown. */
export function documentLinks(source: string): DocumentLink[] {
@@ -15,13 +15,17 @@ export function documentLinks(source: string): DocumentLink[] {
const url = node.node.getChild("URL");
if (!url) return;
const target = source.slice(url.from, url.to).replace(/^<|>$/g, "").replace(/\\([\\()])/g, "$1");
links.push({ from: node.from, to: node.to, kind: "md", target });
const angled = source[url.from] === "<";
links.push({ from: node.from, to: node.to, targetFrom: url.from + Number(angled), targetTo: url.to - Number(angled), kind: "md", target });
return false;
} });
const occupied = (from: number, to: number) => [...literal, ...links].some(range => from < range.to && to > range.from);
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
if (occupied(match.index, match.index + match[0].length)) continue;
links.push({ from: match.index, to: match.index + match[0].length, kind: "wiki", target: match[1].split("|")[0].trim() });
if (source[match.index - 1] === "!") continue;
const raw = match[1].split(/\\?\|/)[0], target = raw.trim();
const targetFrom = match.index + 2 + raw.length - raw.trimStart().length;
links.push({ from: match.index, to: match.index + match[0].length, targetFrom, targetTo: targetFrom + target.length, kind: "wiki", target });
}
for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) {
if (occupied(match.index, match.index + match[0].length)) continue;
@@ -29,7 +33,7 @@ export function documentLinks(source: string): DocumentLink[] {
const open = (match[0].match(/\(/g) || []).length, close = (match[0].match(/\)/g) || []).length;
return suffix.slice(0, Math.max(0, suffix.length - Math.max(0, close - open)));
});
links.push({ from: match.index, to: match.index + target.length, kind: "md", target });
links.push({ from: match.index, to: match.index + target.length, targetFrom: match.index, targetTo: match.index + target.length, kind: "md", target });
}
return links.sort((a, b) => a.from - b.from);
}
-2
View File
@@ -7,8 +7,6 @@
.rs-heading-toggle:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 1px; }
.rs-heading-toggle svg { width: 14px; height: 14px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.rs-heading-toggle[aria-expanded="true"] svg { transform: rotate(90deg); }
.rs-heading-tooltip { display: none; position: absolute; z-index: 5; top: 100%; inset-inline-start: 0; max-width: 240px; width: max-content; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: normal; pointer-events: none; }
.rs-heading-toggle:hover .rs-heading-tooltip, .rs-heading-toggle:focus-visible .rs-heading-tooltip { display: block; }
.rs-heading-collapsed::after { content: " …"; color: var(--rs-text-dim); font-weight: normal; }
.live-writer .cm-foldPlaceholder { border: none; background: transparent; color: var(--rs-text-dim); cursor: pointer; padding: 0 .3em; }
.reading [hidden] { display: none !important; }
+7 -8
View File
@@ -2,6 +2,8 @@ import { StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view";
import { codeFolding, foldEffect, foldKeymap, foldedRanges, foldService, syntaxTree, unfoldEffect } from "@codemirror/language";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
export type HeadingRange = { start: number; from: number; to: number; level: number; label: string };
@@ -29,12 +31,9 @@ export function headingButton(label: string, collapsed: boolean): HTMLButtonElem
button.setAttribute("aria-expanded", String(!collapsed));
const title = `${collapsed ? "Expand" : "Collapse"} ${label || "heading"}`;
button.setAttribute("aria-label", title);
button.title = title;
tooltipCleanups.set(button, attachTooltip(button, () => button.getAttribute("aria-label") || ""));
const icon = actionIcon("chevron");
const tooltip = document.createElement("span");
tooltip.className = "rs-heading-tooltip";
tooltip.textContent = title;
button.append(icon, tooltip);
button.append(icon);
return button;
}
@@ -55,6 +54,7 @@ class HeadingToggle extends WidgetType {
};
return button;
}
destroy(dom: HTMLElement) { tooltipCleanups.get(dom)?.(); }
ignoreEvent() { return true; }
}
@@ -103,8 +103,7 @@ export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>)
const label = `${collapsed.has(item.key) ? "Expand" : "Collapse"} ${item.label}`;
button.setAttribute("aria-expanded", String(!collapsed.has(item.key)));
button.setAttribute("aria-label", label);
button.title = label;
button.querySelector(".rs-heading-tooltip")!.textContent = label;
item.heading.classList.toggle("rs-heading-collapsed", collapsed.has(item.key));
}
if (!collapsed.has(item.key)) return;
@@ -137,7 +136,7 @@ export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>)
},
destroy() {
elements.forEach(element => { element.hidden = false; });
headings.forEach(item => { item.heading.querySelector(".rs-heading-toggle")?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); });
headings.forEach(item => { const button = item.heading.querySelector<HTMLElement>(".rs-heading-toggle"); if (button) tooltipCleanups.get(button)?.(); button?.remove(); item.heading.classList.remove("rs-foldable-heading", "rs-heading-collapsed"); });
},
};
}
+5 -2
View File
@@ -1,4 +1,6 @@
import { actionIcon, type ActionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
export type ImageActions = {
@@ -32,7 +34,7 @@ function button(label: string, icon: ActionIcon, action: () => void) {
control.type = "button";
control.className = "image-action";
control.setAttribute("aria-label", label);
control.dataset.tooltip = label;
tooltipCleanups.set(control, attachTooltip(control, () => label));
control.append(actionIcon(icon));
control.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); action(); });
return control;
@@ -73,7 +75,7 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
dialog.append(header, viewport);
dialog.addEventListener("click", event => { if (event.target === dialog || event.target === viewport) dialog.close(); });
// Escape and focus trapping are provided by the native modal dialog.
dialog.addEventListener("close", () => { dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true });
dialog.addEventListener("close", () => { [zoomOut, zoomIn, fit, close].forEach(button => tooltipCleanups.get(button)?.()); dialog.remove(); if (trigger.isConnected) trigger.focus(); }, { once: true });
image.addEventListener("load", () => resize(scale));
document.body.append(dialog);
dialog.showModal();
@@ -103,6 +105,7 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
toolbar.append(zoom);
if (actions.edit) toolbar.append(button(actions.editing ? "Hide image source" : "Edit image source", "code", actions.editing && actions.done ? actions.done : actions.edit));
frame.append(toolbar);
cleanup.push(() => toolbar.querySelectorAll<HTMLButtonElement>("button").forEach(button => tooltipCleanups.get(button)?.()));
let menu: HTMLElement | undefined;
let openingMenu = false;
function closeMenu(focus = true) { menu?.remove(); menu = undefined; if (focus && frame.isConnected) frame.focus({ preventScroll: true }); }
+1 -1
View File
@@ -64,7 +64,7 @@ export class ImagePreview extends WidgetType {
const edit = document.createElement("button");
edit.type = "button"; edit.className = "image-action";
const label = this.editing ? "Hide image source" : "Edit image source";
edit.setAttribute("aria-label", label); edit.dataset.tooltip = label;
edit.setAttribute("aria-label", label); edit.dataset.editorTooltip = label;
edit.append(actionIcon("code"));
edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); });
dom.append(edit);
+30
View File
@@ -0,0 +1,30 @@
import type { ActionMenuItem } from "../ui/actionMenu";
export type MenuLink = { kind: "md" | "wiki"; target: string };
export type DocumentLinkActions = {
open?: (link: MenuLink) => void | Promise<void>;
browser?: (target: string) => void | Promise<void>;
defaultBrowser?: (target: string) => void | Promise<void>;
workspaceItems?: (link: MenuLink) => ActionMenuItem[];
};
export function linkMenuItems(link: MenuLink, actions: DocumentLinkActions, close: () => void, report: (message: string) => void, edit?: () => void): ActionMenuItem[] {
const run = (action: () => void | Promise<void>) => () => {
close();
void Promise.resolve().then(action).catch(error => report(error instanceof Error ? error.message : String(error)));
};
const external = /^(https?:\/\/|mailto:)/i.test(link.target);
const items: ActionMenuItem[] = external ? [
...(actions.browser && /^https?:\/\//i.test(link.target) ? [{ label: "Open link in app browser", icon: "globe" as const, run: run(() => actions.browser!(link.target)) }] : []),
...(actions.defaultBrowser ? [{ label: "Open link in default browser", icon: "external" as const, run: run(() => actions.defaultBrowser!(link.target)) }] : []),
] : [];
if (!items.length && actions.open) items.push({ label: external ? "Open link" : "Open in new tab", icon: external ? "external" : "file-plus", run: run(() => actions.open!(link)) });
if (!external && actions.workspaceItems) {
const wrap = (item: ActionMenuItem): ActionMenuItem => "separator" in item ? item : { ...item, run: item.run ? run(item.run) : undefined, children: item.children?.map(wrap) };
const workspaceItems = actions.workspaceItems(link).filter(item => !edit || "separator" in item || !["Rename…", "Move file to…", "Open in default app"].includes(item.label));
items.push(...workspaceItems.map(wrap));
}
items.push({ label: external ? "Copy URL" : "Copy link target", icon: "link", run: run(() => navigator.clipboard.writeText(link.target)) });
if (edit) items.push({ label: "Edit link", icon: "rename", run: () => { close(); edit(); } });
return items;
}
+29 -14
View File
@@ -1,5 +1,5 @@
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
@@ -10,6 +10,8 @@ import { imageControls } from "./imageControls";
import { ImagePreview, type ImageContext } from "./imagePreview";
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
import { actionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
import { documentLinks } from "./documentLinks";
import { pluginHost } from "../plugins/registry.ts";
@@ -17,6 +19,20 @@ const previewFormulas = new WeakMap<HTMLElement, unknown>();
export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>();
const linkTooltips = ViewPlugin.define(view => {
const attached = new Map<HTMLElement, () => void>();
const refresh = () => {
for (const [node, dispose] of attached) if (!view.dom.contains(node)) { dispose(); attached.delete(node); }
for (const node of view.dom.querySelectorAll<HTMLElement>("[data-editor-tooltip]")) {
if (!attached.has(node)) attached.set(node, attachTooltip(node, () => node.dataset.editorTooltip || ""));
}
};
const observer = new MutationObserver(refresh);
observer.observe(view.dom, { childList: true, subtree: true });
refresh();
return { destroy() { observer.disconnect(); attached.forEach(dispose => dispose()); } };
});
class CodeCopy extends WidgetType {
constructor(readonly code: string) { super(); }
eq(other: CodeCopy) { return this.code === other.code; }
@@ -25,24 +41,18 @@ class CodeCopy extends WidgetType {
button.type = "button";
button.className = "rs-fence-copy writer-code-copy";
button.setAttribute("aria-label", "Copy code");
button.title = "Copy code";
const help = document.createElement("span");
help.className = "writer-code-tooltip";
help.setAttribute("role", "tooltip");
help.textContent = "Copy code";
button.append(actionIcon("copy"), help);
button.dataset.editorTooltip = "Copy code";
button.append(actionIcon("copy"));
button.onmousedown = event => event.preventDefault();
button.onclick = async event => {
event.preventDefault(); event.stopPropagation();
try {
await navigator.clipboard.writeText(this.code);
button.dataset.copied = "true";
button.title = "Copied";
help.textContent = "Copied";
button.dataset.editorTooltip = "Copied";
button.setAttribute("aria-label", "Code copied");
} catch {
button.title = "Could not copy code";
help.textContent = "Could not copy code";
button.dataset.editorTooltip = "Could not copy code";
button.setAttribute("aria-label", "Could not copy code");
}
};
@@ -238,7 +248,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
if (!match) return;
replace(node.from, node.from + 1);
replace(node.from + 1 + match[1].length, node.to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", title: "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-href": match[2], "data-kind": "md", "data-editor-tooltip": "Ctrl+click to open link" } }).range(node.from + 1, node.from + 1 + match[1].length));
return false;
}
if (node.name === "TaskMarker") {
@@ -261,11 +271,16 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const labelStart = from + 2 + (separator < 0 ? 0 : separator + 1);
replace(from, labelStart);
replace(to - 2, to);
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0] } }).range(labelStart, to - 2));
ranges.push(Decoration.mark({ class: "writer-link", attributes: { "data-kind": "wiki", "data-href": match[1].split("|")[0], "data-editor-tooltip": "Ctrl+click to open link" } }).range(labelStart, to - 2));
}
for (const link of documentLinks(source)) {
if (!selected(link.from, link.to) || hidden(link.from, link.to)) continue;
mark(link.from, link.to, "writer-link-source");
mark(link.targetFrom, link.targetTo, "writer-link-target");
}
return Decoration.set(ranges, true);
}
return [imageSource, StateField.define<DecorationSet>({
return [imageSource, linkTooltips, StateField.define<DecorationSet>({
create: build,
update(value, transaction) {
return transaction.docChanged || transaction.selection
+39 -2
View File
@@ -1,6 +1,10 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { wordAt } from "./spellingWord";
import { pickLinkDocument } from "./documentPicker";
import { externalLinkText, workspaceLinkText } from "./linkCommands";
import { documentLinkAt } from "./documentLinks";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
import { htmlToMarkdown } from "../workspace/htmlToMarkdown";
import { cellFormats, type TableContextActions } from "./tableCellActions";
import { formatText, insertBlock, paragraphText, replacement, type MarkdownEdit, type TextSelection, type ParagraphStyle, type InsertBlock } from "./markdownCommands";
@@ -10,11 +14,16 @@ export type MarkdownMenuEditor = {
apply: (edit: MarkdownEdit) => void;
selectAll: () => void;
focus: () => void;
select: (from: number, to: number) => void;
undo?: () => void;
redo?: () => void;
canUndo?: () => boolean;
canRedo?: () => boolean;
};
// A shared controller keeps menus, async selection guards, and clipboard behavior
// identical in the writing editor and the source editor.
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void) {
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void, linkActions: () => DocumentLinkActions = () => ({})) {
let root: HTMLElement | undefined, destroyed = false;
const pending = new AbortController();
function close(focus = true) {
@@ -28,10 +37,11 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
document.addEventListener("scroll", scroll, true);
window.addEventListener("resize", resize);
function open(x: number, y: number) {
function open(x: number, y: number, spellingOffset?: number, linkOffset?: number) {
close(false);
const snapshot = editor.snapshot(), { source, selection } = snapshot;
const text = source.slice(selection.from, selection.to);
const selectedLink = documentLinkAt(source, linkOffset ?? selection.from);
const valid = () => !destroyed && snapshot.valid();
function apply(edit: MarkdownEdit) {
if (!valid()) return;
@@ -74,6 +84,15 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) });
const insert = (label: string, kind: InsertBlock, icon: "footnote" | "table" | "quote" | "rule" | "code" | "math"): ActionMenuItem => ({ label, icon, run: () => apply(insertBlock(source, selection, kind)) });
const items: ActionMenuItem[] = [
...(selectedLink ? [...linkMenuItems(selectedLink, linkActions(), () => close(false), report, () => {
if (!valid()) return;
editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus();
}), { separator: true as const }] : []),
...(editor.undo ? [
{ label: "Undo", icon: "undo" as const, shortcut: "Ctrl+Z", disabled: !editor.canUndo?.(), run: () => { close(); editor.undo?.(); } },
{ label: "Redo", icon: "redo" as const, shortcut: "Ctrl+Shift+Z", disabled: !editor.canRedo?.(), run: () => { close(); editor.redo?.(); } },
{ separator: true as const },
] : []),
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
@@ -104,6 +123,24 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
{ label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } },
];
root = actionMenu(x, y, items, close, "Markdown text actions");
const opened = root;
const word = spellingOffset === undefined ? null : wordAt(source, spellingOffset);
if (word && isTauri()) {
const languages = [...new Set([document.documentElement.lang, ...navigator.languages].filter(Boolean))];
void invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }).then(result => {
if (!result.misspelled || root !== opened || !valid()) return;
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => apply(replacement(word, value)) }));
if (!suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true });
suggestions.push({ label: "Add to dictionary", icon: "book", run: () => {
close();
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary."));
} });
const focusedLabel = opened.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
opened.remove();
root = actionMenu(x, y, [...suggestions, { separator: true }, ...items], close, "Markdown text actions");
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
}).catch(() => { /* Editing actions remain available without spelling suggestions. */ });
}
}
return { open, close, destroy() {
destroyed = true; pending.abort(); close(false);
+27 -12
View File
@@ -12,28 +12,43 @@ export let currentTheme = 'runestone-default-dark';
function updateTheme() {
const style = getComputedStyle(document.documentElement);
const color = (name: string) => style.getPropertyValue(`--rs-${name}`).trim();
const sakura = document.documentElement.dataset.palette === 'sakura';
const syntaxColor = (role: string) => {
const value = document.documentElement.style.getPropertyValue(`--rs-syntax-${role}`).trim();
const match = /^#([0-9a-f]{3,8})$/i.exec(value);
if (!match) return undefined;
const hex = match[1];
return hex.length === 3 || hex.length === 4 ? `#${hex.slice(0, 3).split('').map(part => part + part).join('')}`
: hex.length === 6 || hex.length === 8 ? `#${hex.slice(0, 6)}` : undefined;
};
const syntaxRules = [
['keyword', 'keyword'], ['variable.parameter', 'parameter'], ['variable', 'local'],
['variable.predefined', 'global'], ['variable.property', 'instance'], ['variable.static', 'static'],
['identifier', 'local'], ['string', 'string'], ['number', 'number'], ['comment', 'comment'],
['type', 'type'], ['type.identifier', 'type'], ['entity.name.type', 'type'],
['function', 'function'], ['predefined', 'function'], ['delimiter', 'global'],
].flatMap(([token, role]) => {
const foreground = syntaxColor(role);
return foreground ? [{ token, foreground: foreground.slice(1) }] : [];
});
// Monaco permits only letters, digits, and hyphens in registered theme names.
const palette = (document.documentElement.dataset.palette || 'default').replace(/[^a-z0-9-]/gi, '-');
currentTheme = `runestone-${palette}-${document.documentElement.dataset.theme || 'dark'}`;
monaco.editor.defineTheme(currentTheme, {
base: document.documentElement.dataset.theme === 'light' ? 'vs' : 'vs-dark',
inherit: true,
rules: sakura ? [
{ token: 'keyword', foreground: color('syntax-keyword').replace('#', '') },
{ token: 'variable.parameter', foreground: color('syntax-parameter').replace('#', '') },
{ token: 'variable', foreground: color('syntax-local').replace('#', '') },
{ token: 'variable.predefined', foreground: color('syntax-global').replace('#', '') },
{ token: 'variable.property', foreground: color('syntax-instance').replace('#', '') },
{ token: 'variable.static', foreground: color('syntax-static').replace('#', '') },
] : [],
rules: syntaxRules,
colors: {
'editor.background': color('bg'), 'editor.foreground': color('text'),
...Object.fromEntries(['keyword', 'number', 'type', 'string', 'function', 'parameter'].flatMap((role, index) => {
const foreground = syntaxColor(role);
return foreground ? [[`editorBracketHighlight.foreground${index + 1}`, foreground]] : [];
})),
'editor.background': '#00000000', 'editor.foreground': color('text'),
'editor.lineHighlightBackground': color('bg-active'), 'editor.selectionBackground': color('selection'),
'editor.inactiveSelectionBackground': color('selection'), 'editor.selectionForeground': color('selection-text'),
'editorCursor.foreground': color('accent'), 'editorLineNumber.foreground': color('text-dim'),
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': color('bg'),
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': '#00000000',
'editorWidget.background': color('bg-elevated'), 'editorWidget.border': color('border'),
'minimap.background': color('bg-elevated'), 'editorIndentGuide.background1': color('border'),
'minimap.background': '#00000000', 'editorIndentGuide.background1': color('border'),
'editorIndentGuide.activeBackground1': color('text-dim'),
},
});
+1 -5
View File
@@ -21,11 +21,7 @@ class NoteTitle extends WidgetType {
button.className = "note-title-button";
button.setAttribute("aria-label", "Rename note");
button.append(document.createTextNode(this.title), actionIcon("rename"));
const help = document.createElement("span");
help.className = "note-title-help";
help.textContent = "Rename note";
help.setAttribute("role", "tooltip");
button.append(help);
button.dataset.editorTooltip = "Rename note";
heading.replaceChildren(button);
const input = document.createElement("input");
+58
View File
@@ -0,0 +1,58 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
/** Preserve the DOM range while the shared menu owns keyboard focus. */
export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, search: ((text: string) => void) | undefined, report: (message: string) => void) {
let root: HTMLElement | undefined;
let previousFocus: HTMLElement | null = null;
let range: Range | undefined;
function close(restore = true) {
if (!root) return;
root.remove(); root = undefined;
if (restore) {
(previousFocus?.isConnected ? previousFocus : host).focus({ preventScroll: true });
if (range?.startContainer.isConnected && range.endContainer.isConnected) {
const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range);
}
}
}
function open(event: MouseEvent | KeyboardEvent) {
if (event.defaultPrevented || event.target instanceof Element && event.target.closest("input, textarea, [contenteditable=true], .rs-image-frame")) return;
const keyboard = event instanceof KeyboardEvent;
if (keyboard && event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
const selection = window.getSelection();
const selected = selection?.rangeCount ? selection.getRangeAt(0) : undefined;
range = selected && host.contains(selected.startContainer) && host.contains(selected.endContainer) ? selected.cloneRange() : undefined;
const text = range?.toString() ?? "";
const target = event.target instanceof Element ? event.target : null;
const anchor = target?.closest("a") ?? (keyboard && selection?.anchorNode ? (selection.anchorNode.parentElement?.closest("a") ?? null) : null);
if (!text && !anchor) return;
event.preventDefault(); event.stopPropagation(); close(false);
previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host;
const items: ActionMenuItem[] = [];
if (text) items.push(
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", run: () => { close(); void navigator.clipboard.writeText(text).catch(() => report("Clipboard unavailable. Use Ctrl+C to copy.")); } },
{ label: `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”`, icon: "search", disabled: !search, run: () => { close(false); search?.(text); } },
);
if (anchor) {
if (items.length) items.push({ separator: true });
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: "Open link", icon: "link", run: () => { close(false); (anchor as HTMLElement).click(); } });
else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => close(false), report));
}
const rect = keyboard ? (range?.getBoundingClientRect() ?? anchor?.getBoundingClientRect() ?? host.getBoundingClientRect()) : null;
root = actionMenu(rect?.left ?? (event as MouseEvent).clientX, rect?.bottom ?? (event as MouseEvent).clientY, items, close, "Reading actions");
}
const outside = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
host.addEventListener("contextmenu", open);
host.addEventListener("keydown", open);
document.addEventListener("mousedown", outside, true);
document.addEventListener("scroll", outside, true);
window.addEventListener("resize", resize);
return () => {
close(false);
host.removeEventListener("contextmenu", open); host.removeEventListener("keydown", open);
document.removeEventListener("mousedown", outside, true); document.removeEventListener("scroll", outside, true);
window.removeEventListener("resize", resize);
};
}
+4 -5
View File
@@ -1,10 +1,9 @@
// Readers retain editor selection when toolbar buttons take focus.
let current: { id: string; read: () => string } | undefined;
const readers = new Map<string, () => string>();
export function registerSelection(id: string, read: () => string): () => void {
const owner = { id, read };
current = owner;
return () => { if (current === owner) current = undefined; };
readers.set(id, read);
return () => { if (readers.get(id) === read) readers.delete(id); };
}
export function selectedEditorText(id?: string): string {
return current && current.id === id ? current.read() : "";
return id ? readers.get(id)?.() ?? "" : "";
}
+14 -2
View File
@@ -3,17 +3,20 @@ import type { OpenBuffer } from "../workspace/types";
import { languageFor } from "./languageFor";
type Session = {
users: number;
model: Monaco.editor.ITextModel;
view: Monaco.editor.ICodeEditorViewState | null;
writerSelections: Map<number, import("@codemirror/state").EditorSelection>;
writer?: { source: string; state: ReturnType<import("@codemirror/state").EditorState["toJSON"]>; scroll: ReturnType<import("@codemirror/view").EditorView["scrollSnapshot"]> };
};
const sessions = new Map<string, Session>();
let retained = new Set<string>();
export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Session {
let session = sessions.get(buffer.id);
if (!session) {
session = {
users: 0,
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
view: null,
writerSelections: new Map(),
@@ -21,12 +24,21 @@ export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Sessio
sessions.set(buffer.id, session);
}
monaco.editor.setModelLanguage(session.model, languageFor(buffer.relPath));
session.users++;
return session;
}
export function retainEditorSessions(ids: string[]) {
const retained = new Set(ids);
retained = new Set(ids);
for (const [id, session] of sessions) {
if (!retained.has(id)) { session.model.dispose(); sessions.delete(id); }
if (!retained.has(id) && session.users === 0) { session.model.dispose(); sessions.delete(id); }
}
}
export function releaseEditorSession(session: Session) {
session.users = Math.max(0, session.users - 1);
if (session.users) return;
for (const [id, entry] of sessions) {
if (entry === session && !retained.has(id)) { session.model.dispose(); sessions.delete(id); break; }
}
}
+28 -4
View File
@@ -1,9 +1,12 @@
import type { Editor, JSONContent } from "@tiptap/core";
import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
import { requestText } from "../workspace/dialogs.svelte";
import { extractedCellMarkdown } from "./tableCellMarkdown";
import type { ActionMenuItem } from "../ui/actionMenu";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
import { documentLinkAt } from "./documentLinks";
export type TableContextActions = {
linkActions?: () => DocumentLinkActions;
onSearch?: (text: string) => void;
onExtract?: (markdown: string, label: string, valid: () => boolean) => Promise<string | null>;
};
@@ -13,8 +16,9 @@ export const cellFormats = [
["Code", "code"], ["Math", "math"], ["Comment", "comment"], ["Clear formatting", "clear"],
] as const;
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void): ActionMenuItem[] {
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void, editSource: (range: { from: number; to: number }) => void): ActionMenuItem[] {
const selection = editor.state.selection, doc = editor.state.doc;
const sourceEditing = editor.view.dom.parentElement?.classList.contains("is-source-editing");
const text = doc.textBetween(selection.from, selection.to, "\n");
const valid = () => !editor.isDestroyed && editor.state.doc === doc && editor.state.selection.eq(selection);
function run(command: () => void) { if (!valid()) return; close(); transaction(() => { editor.view.focus(); command(); }); }
@@ -41,6 +45,21 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
});
});
}
const at = doc.resolve(selection.from);
const mark = [...at.marks(), ...(at.nodeAfter?.marks || [])].find(mark => mark.type.name === "link");
const linkRange = mark && getMarkRange(doc.resolve(selection.from), mark.type, mark.attrs);
const sourceLink = sourceEditing ? documentLinkAt(doc.textContent, selection.from - 1)
|| documentLinkAt(doc.textContent, selection.from - 2) : undefined;
const selectedLink = sourceLink || (mark && linkRange ? { kind: mark.attrs["data-kind"] === "wiki" ? "wiki" as const : "md" as const, target: String(mark.attrs.href) } : undefined);
function editLink() {
if (!selectedLink) return;
if (!valid()) return;
close();
if (sourceLink) {
editor.commands.setTextSelection({ from: sourceLink.targetFrom + 1, to: sourceLink.targetTo + 1 });
editor.view.focus();
} else if (linkRange) editSource(linkRange);
}
async function clipboard(action: "cut" | "copy" | "paste" | "plain") {
await request(async () => {
try {
@@ -49,7 +68,7 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
if (action === "cut") run(() => { editor.commands.deleteSelection(); });
} else {
let html = "", value = "";
if (action === "paste" && navigator.clipboard.read) {
if (!sourceEditing && action === "paste" && navigator.clipboard.read) {
try {
const data = await navigator.clipboard.read();
const rich = data.find(item => item.types.includes("text/html"));
@@ -72,7 +91,8 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
});
}
return [
const items: ActionMenuItem[] = [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ separator: true },
@@ -95,4 +115,8 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
{ label: "Paste as plain text", icon: "paste-text", run: () => void clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } },
];
return sourceEditing ? [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
...items.slice(items.findIndex(item => "label" in item && item.label === "Cut")),
] : items;
}
+93 -10
View File
@@ -1,4 +1,6 @@
import { Editor, Mark } from "@tiptap/core";
import { Editor, Extension, Mark, getMarkRange } from "@tiptap/core";
import { Plugin } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import Highlight from "@tiptap/extension-highlight";
import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
@@ -13,6 +15,10 @@ import { tableDragControls } from "./tableDragControls";
import type { TableContextActions } from "./tableCellActions";
import { actionIcon } from "../ui/actionIcons";
import { pluginHost } from "../plugins/registry.ts";
import { attachTooltip } from "../ui/tooltip";
import { documentLinks } from "./documentLinks";
import { tableLinkLabelPosition } from "./tableLinkSource";
import { renderMarkdownHtml } from "../workspace/noteHtml";
const cellFormats = ["math", "comment"].map(name => Mark.create({
name,
@@ -46,10 +52,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
wrapper.append(scroll);
let editor: Editor | undefined;
let active: HTMLTableCellElement | undefined;
let sourceEditing = false;
let sourceImages = new Map<string, string>();
let firstEdit = true;
let selectionControls: ReturnType<typeof tableSelectionControls> | undefined;
let dragControls: ReturnType<typeof tableDragControls> | undefined;
const controller = { source: initialSource, enter, destroy: () => { dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } };
const tooltipCleanup: (() => void)[] = [];
const controller = { source: initialSource, enter, destroy: () => { tooltipCleanup.forEach(dispose => dispose()); dragControls?.destroy(); selectionControls?.destroy(); editor?.destroy(); editor = undefined; } };
tableEditors.set(root, controller);
function enter(forward: boolean, x?: number) {
@@ -83,7 +92,8 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
for (const row of table!.rows) for (const cell of row.cells) {
const result = results[row.rowIndex]?.[cell.cellIndex];
const address = formulas.cellAddress(row.rowIndex, cell.cellIndex);
cell.title = `${address} · ${result?.formula || "Click to edit · Type = for a formula"}`;
cell.dataset.cellHint = `${address}${result?.formula ? ` · ${result.formula}` : ""}`;
cell.removeAttribute("title");
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
if (cell === active) {
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
@@ -115,10 +125,16 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
function finish() {
if (!editor || !active) return;
const cell = active;
const html = editor.getHTML();
let html = editor.getHTML();
if (sourceEditing) {
const rendered = document.createElement("div");
rendered.innerHTML = renderMarkdownHtml(controller.source, sourceImages);
html = rendered.querySelector("table")?.rows[(cell.parentElement as HTMLTableRowElement).rowIndex]?.cells[cell.cellIndex]?.innerHTML ?? html;
}
sourceEditing = false;
editor.destroy(); editor = undefined; active = undefined;
cell.innerHTML = html;
cell.classList.remove("is-editing");
cell.classList.remove("is-editing", "is-source-editing");
refreshFormulas();
formulaStatus.textContent = "Type = in a cell to calculate";
formulaHint.hidden = true;
@@ -165,6 +181,22 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
editor = new Editor({
element: cell,
extensions: [
Extension.create({
name: "cellLinkSource",
addProseMirrorPlugins: () => [new Plugin({ props: { decorations(state) {
if (!sourceEditing) return null;
const decorations: Decoration[] = [];
state.doc.descendants((node, position) => {
if (!node.isTextblock) return;
for (const link of documentLinks(node.textBetween(0, node.content.size, "\n", "\n"))) {
decorations.push(Decoration.inline(position + link.from + 1, position + link.to + 1, { class: "writer-link-source", "data-href": link.target, "data-kind": link.kind }));
if (link.targetTo > link.targetFrom) decorations.push(Decoration.inline(position + link.targetFrom + 1, position + link.targetTo + 1, { class: "writer-link-target" }));
}
return false;
});
return DecorationSet.create(state.doc, decorations);
} } })],
}),
StarterKit.configure({ blockquote: false, bulletList: false, orderedList: false, listItem: false, listKeymap: false, codeBlock: false, heading: false, horizontalRule: false, link: false, underline: false, undoRedo: false, trailingNode: false, gapcursor: false, dropcursor: false }),
CellLink.configure({ openOnClick: false, autolink: false }),
CellImage.configure({ inline: true, allowBase64: true }),
@@ -177,6 +209,9 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
attributes: { class: "writer-cell-editor", role: "textbox", "aria-label": cell.getAttribute("aria-label")!, "aria-multiline": "true", spellcheck: "true" },
handleKeyDown(_editorView, event) {
if (event.isComposing) return false;
if (sourceEditing && (event.ctrlKey || event.metaKey) && ["b", "i"].includes(event.key.toLowerCase())) {
event.preventDefault(); event.stopPropagation(); return true;
}
if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key)) {
// The nested editor owns cursor movement, including word movement
// and selections. Never let an arrow reach the prose editor.
@@ -237,10 +272,11 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
});
return true;
}
if (event.key === "Escape" && sourceEditing) { event.preventDefault(); finish(); wrapper.focus(); return true; }
if (event.key === "Escape") { event.preventDefault(); leave(true); return true; }
if (event.key === "Enter") {
event.preventDefault();
if (/^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
if (sourceEditing || /^=(?!=)/.test((editor?.getText() || "").trim())) { finish(); wrapper.focus(); }
else if (event.ctrlKey || event.metaKey) leave(true);
else editor?.commands.setHardBreak();
return true;
@@ -258,7 +294,13 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
},
},
onUpdate({ editor: current }) {
const text = tableCellMarkdown(current.getJSON());
const text = sourceEditing
? current.getText({ blockSeparator: "<br>" }).replace(/\r?\n/g, "<br>").replace(/\|/g, (_pipe, offset, value) => {
let slashes = 0;
for (let before = offset - 1; before >= 0 && value[before] === "\\"; before--) slashes++;
return slashes % 2 ? "|" : "\\|";
})
: tableCellMarkdown(current.getJSON());
const source = controller.source;
// Track the full edited range, including typed spaces. Re-parsing the
// trimmed cell on each key would gradually turn those spaces into padding.
@@ -269,6 +311,18 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
if (contentFrom !== undefined) contentTo = contentFrom + text.length;
change(insert);
},
onSelectionUpdate({ editor: current }) {
// Read the final mouse/keyboard selection after activation sets its
// temporary caret. Menus and range selections keep their own focus.
requestAnimationFrame(() => {
if (current !== editor || current.isDestroyed || sourceEditing || !current.isFocused || current.view.composing) return;
const { selection } = current.state;
if (!selection.empty) return;
const mark = selection.$from.marks().find(mark => mark.type.name === "link");
const range = mark && getMarkRange(selection.$from, mark.type, mark.attrs);
if (range) editSource(range, selection.from - range.from);
});
},
onBlur() {
// A toolbar click, another cell, or the prose editor can now take focus.
queueMicrotask(() => { if (active === cell && !cell.contains(document.activeElement) && !selectionControls?.keepEditing()) finish(); });
@@ -279,6 +333,32 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
view.requestMeasure();
}
function editSource(range: { from: number; to: number }, labelOffset?: number) {
if (!editor || !active) return;
const row = (active.parentElement as HTMLTableRowElement).rowIndex;
const cell = parseMarkdownTable(controller.source)?.rows[row === 0 ? 0 : row + 1]?.cells[active.cellIndex];
if (!cell) return;
const preceding = new Set<number>();
editor.state.doc.descendants((node, position) => {
const mark = node.marks.find(mark => mark.type.name === "link");
if (mark && position < range.from) {
const found = getMarkRange(editor!.state.doc.resolve(position), mark.type, mark.attrs);
if (found && found.from < range.from) preceding.add(found.from);
}
});
const link = documentLinks(cell.text)[preceding.size];
if (!link) return;
sourceImages = new Map([...root.querySelectorAll<HTMLImageElement>("img[data-md-src]")].map(image => [image.dataset.mdSrc!, image.src]));
sourceEditing = true;
active.classList.add("is-source-editing");
editor.commands.setContent({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: cell.text }] }] }, { emitUpdate: false });
editor.commands.setTextSelection(labelOffset === undefined
? { from: link.targetFrom + 1, to: link.targetTo + 1 }
: tableLinkLabelPosition(cell.text, link, labelOffset) + 1);
editor.view.focus();
view.requestMeasure();
}
function add(kind: "row" | "column", focusNew = false) {
const from = view.posAtDOM(root);
finish();
@@ -299,7 +379,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
const help = document.createElement("div");
help.className = "table-edit-help";
help.textContent = "Drag grips: move rows/columns · Drag cells: select · Right-click: actions · Arrows: move through cells · Tab: next cell · Esc: exit table";
help.hidden = true;
const footer = document.createElement("div");
footer.className = "table-footer";
const tools = formulas?.createFormulaTools(finish, () => view.requestMeasure());
@@ -313,7 +393,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
const label = kind === "column" ? "Add column to the right" : "Add row below";
button.type = "button";
button.className = `table-add table-add-${kind}`;
button.title = label;
tooltipCleanup.push(attachTooltip(button, () => label));
button.setAttribute("aria-label", label);
const plus = document.createElement("span");
plus.append(actionIcon("plus"));
@@ -332,7 +412,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
cell.setAttribute("aria-label", `${formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : ""}Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`);
cell.addEventListener("focus", () => activate(cell));
}
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate }, actions);
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate, editSource }, actions);
dragControls = tableDragControls(root, wrapper, table, scroll, view, () => controller.source, selectionControls.select, change);
table.addEventListener("mousedown", event => {
if (event.button !== 0) return;
@@ -347,4 +427,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
}
});
refreshFormulas();
for (const row of table.rows) for (const cell of row.cells) {
tooltipCleanup.push(attachTooltip(cell, () => cell.dataset.cellHint || cell.getAttribute("aria-label") || ""));
}
}
+4 -3
View File
@@ -2,12 +2,14 @@ import type { EditorView } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
import { moveTableAxis, type TableAxis } from "./tableStructure";
import type { CellRange } from "./tableSelection";
import { attachTooltip } from "../ui/tooltip";
const controls = new WeakMap<HTMLTableElement, (axis: TableAxis, index: number, keyboard: boolean) => void>();
export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, scroll: HTMLElement, view: EditorView, source: () => string, select: (range: CellRange) => void, change: (text: string, structural: boolean) => void) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
const handles: { axis: TableAxis; index: number; button: HTMLButtonElement }[] = [];
const tooltipCleanup: (() => void)[] = [];
const layer = document.createElement("div");
layer.className = "table-drag-layer";
wrapper.append(layer);
@@ -172,8 +174,7 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
const label = `Move ${axis} ${index + 1}`;
const tooltip = `${label} · Drag to reorder · ${axis === "row" ? "↑/↓" : "←/→"} to move`;
button.setAttribute("aria-label", label);
button.title = tooltip;
button.dataset.tooltip = tooltip;
tooltipCleanup.push(attachTooltip(button, () => drag ? "" : tooltip));
button.append(actionIcon("grip"));
layer.append(button);
handles.push({ axis, index, button });
@@ -222,5 +223,5 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
const observer = new ResizeObserver(scheduleLayout);
observer.observe(table); observer.observe(scroll);
scheduleLayout();
return { destroy() { cancel(); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
return { destroy() { cancel(); tooltipCleanup.forEach(dispose => dispose()); cancelAnimationFrame(layoutFrame); lifecycle.abort(); observer.disconnect(); controls.delete(table); } };
}
+45
View File
@@ -0,0 +1,45 @@
import { markdownLanguage } from "@codemirror/lang-markdown";
import type { DocumentLink } from "./documentLinks";
/** Keep the caret on the clicked label character when Markdown becomes visible. */
export function tableLinkLabelPosition(source: string, link: DocumentLink, offset: number): number {
let from = link.targetFrom, to = link.targetTo;
if (link.kind === "wiki") {
const separator = source.indexOf("|", link.from + 2);
from = link.from + 2; to = link.to - 2;
if (separator >= 0 && separator < to) {
if (separator + 1 < to) from = separator + 1;
else to = separator - Number(source[separator - 1] === "\\");
}
} else if (source[link.from] === "[") {
from = link.from + 1;
markdownLanguage.parser.parse(source).iterate({ enter(node) {
if (node.name === "LinkMark" && node.from > from && node.from < link.targetFrom && source[node.from] === "]") to = node.from;
} });
}
const label = source.slice(from, to);
const hidden = new Set<number>();
const entities = new Map<number, { to: number; length: number }>();
if (link.kind === "wiki") {
// Wiki labels are literal text. Table parsing removes escaped pipe marks.
for (let i = 0; i < label.length - 1; i++) if (label[i] === "\\" && label[i + 1] === "|") hidden.add(i);
} else markdownLanguage.parser.parse(label).iterate({ enter(node) {
if (["EmphasisMark", "StrikethroughMark", "CodeMark"].includes(node.name)) {
for (let i = node.from; i < node.to; i++) hidden.add(i);
} else if (node.name === "Escape") hidden.add(node.from);
else if (node.name === "Entity") {
const text = document.createElement("textarea");
text.innerHTML = label.slice(node.from, node.to);
entities.set(node.from, { to: node.to, length: text.value.length });
}
} });
let visible = 0;
for (let i = 0; i < label.length; i++) {
if (hidden.has(i)) continue;
if (visible >= offset) return from + i;
const entity = entities.get(i);
if (entity) { visible += entity.length; i = entity.to - 1; }
else visible++;
}
return to;
}
+4 -4
View File
@@ -10,7 +10,7 @@ import { alignTableCells, bounds, copyTableCells, deleteTableCells, formatTableC
const selections = new WeakMap<Element, (range: CellRange) => void>();
export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void }, actions: TableContextActions) {
export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement, table: HTMLTableElement, view: EditorView, source: () => string, finish: () => void, change: (text: string, structural: boolean) => void, rich: { get: () => Editor | undefined; activate: (cell: HTMLTableCellElement) => void; editSource: (range: { from: number; to: number }) => void }, actions: TableContextActions) {
const lifecycle = new AbortController(), options = { signal: lifecycle.signal };
let range: CellRange | undefined, down: CellPoint | undefined, dragging = false;
let menu: HTMLElement | undefined;
@@ -80,7 +80,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
}
} catch {
const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; }
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = `Clipboard unavailable here. Use ${navigator.platform.includes("Mac") ? "⌘" : "Ctrl"}+${action === "paste" ? "V" : action === "cut" ? "X" : "C"}.`; }
}
}
function showMenu(x: number, y: number, at = range?.head, textEditor?: Editor) {
@@ -109,11 +109,11 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem));
const report = (message: string) => {
const status = root.querySelector<HTMLElement>(".table-edit-help");
if (status) { status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; }
if (status) { status.hidden = false; status.setAttribute("role", "status"); status.textContent = message; status.style.visibility = "visible"; }
};
const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => {
view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") });
}, value => { pending = value; }, report) : [
}, value => { pending = value; }, report, rich.editSource) : [
...(["cut", "copy", "paste"] as const).map(action => ({ label: action[0].toUpperCase() + action.slice(1), icon: action, run: () => void clipboard(action) })),
sep,
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) },
+38 -28
View File
@@ -3,8 +3,8 @@
import type { GitLineInfo } from "$lib/git/contracts";
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 { tick } from "svelte";
import IconButton from "$lib/ui/IconButton.svelte";
import ImageViewer from "./ImageViewer.svelte";
import MarkdownView from "./MarkdownView.svelte";
import ModeSwitcher from "$lib/ui/ModeSwitcher.svelte";
@@ -13,6 +13,8 @@
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import type { TableContextActions } from "$lib/editor/tableCellActions";
import type { DocumentLinkActions } from "$lib/editor/linkMenu";
type Props = {
buffer: OpenBuffer | null;
tabs: OpenBuffer[];
@@ -33,9 +35,12 @@
browserOpening?: boolean;
hasWorkspace: boolean;
tableActions?: TableContextActions;
linkActions?: DocumentLinkActions;
active?: boolean;
onCloseSplit?: () => void;
};
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onNewNote, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions }: Props = $props();
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onNewNote, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions, linkActions, active = true, onCloseSplit }: Props = $props();
let selectedLine = $state(1);
let lineInfo = $state<GitLineInfo | null>(null);
const git = $derived.by(() => { void $pluginHost; return pluginHost.get("git"); });
@@ -60,7 +65,15 @@
let previewMode = $state<"split" | "preview">("split");
let modeControls = $state<HTMLDivElement>();
let titleFocusId = $state<string | null>(null);
const shouldFocusOnMount = () => !modeControls?.contains(document.activeElement);
let element: HTMLDivElement | undefined = $state();
let writerEditor: LiveWriter | undefined = $state();
let sourceEditor: EditorHost | undefined = $state();
const shouldFocusOnMount = () => active && !modeControls?.contains(document.activeElement);
export function focusEditor() {
if (reading) element?.querySelector<HTMLElement>(".reading")?.focus({ preventScroll: true });
else if (writerEditor) writerEditor.focus();
else sourceEditor?.focus();
}
export function focusTitle(id: string) {
titleFocusId = id;
}
@@ -70,10 +83,8 @@
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);
@@ -117,21 +128,23 @@
{#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>
{#if onCloseSplit}<IconButton icon="close" label="Close split" onclick={onCloseSplit} />{/if}
<div class="welcome-actions">
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? "Opening browser…" : "Open browser"}</button>{/if}
<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>
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> New note</button>{/if}
<button onclick={onQuickOpen}><Icon icon="search" /> Find a file <kbd>Ctrl P</kbd></button>
<div class="welcome-row">
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button>
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> New note</button>{/if}
<button onclick={onQuickOpen}><Icon icon="search" /> Find file <kbd>Ctrl P</kbd></button>
</div>
{/if}
<div class="welcome-row">
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? "Opening browser…" : "Open browser"}</button>{/if}
</div>
</div>
<p class="hint">Save · Ctrl S &nbsp; Terminal · Ctrl ` &nbsp; Find in file · Ctrl F</p>
</div>
{:else}
<div class="editor">
<div class="editor" class:pane-active={active} bind:this={element}>
<div class="chrome-bar">
<span class="breadcrumb" title={buffer.relPath}>{buffer.relPath}</span>
{#if lineInfo}
@@ -140,6 +153,7 @@
</span>
{/if}
<div class="actions" bind:this={modeControls}>
{#if onCloseSplit}<IconButton icon="close" label="Close split" onclick={onCloseSplit} />{/if}
{#if canPreview}
<ModeSwitcher
label="Document view"
@@ -171,17 +185,17 @@
<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} onSelectionLine={(line) => selectedLine = line}
<LiveWriter bind:this={writerEditor} {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line}
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
{:else}
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line} />
<EditorHost bind:this={sourceEditor} {buffer} {chrome} {onChange} {onInsertImage} {onOpenLink} {linkActions} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line} />
{/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} />
<MarkdownView noteRel={buffer.relPath} contents={buffer.contents} {onOpenLink} {linkActions} onSearch={tableActions?.onSearch} />
</div>
{/key}
{/if}
@@ -195,11 +209,12 @@
.line-history span { overflow: hidden; text-overflow: ellipsis; }
.line-history :global(svg) { width: 14px; height: 14px; flex-shrink: 0; }
.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; }
.welcome-actions { display: flex; flex-direction: column; gap: 12px; max-width: 100%; }
.welcome-row { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; max-width: 100%; }
.welcome-actions button { flex-wrap: wrap; justify-content: center; max-width: 100%; }
.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-image-control-bg); padding: 10px 14px; }
.welcome-actions button:hover { background: var(--rs-image-control-hover-bg); }
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; }
@@ -214,11 +229,6 @@
}
.empty {
background-color: var(--rs-new-tab-bg, var(--rs-bg));
background-image: var(--rs-background-image, var(--rs-new-tab-image, none));
background-size: 100% 100%, var(--rs-background-size, cover);
background-position: center, var(--rs-background-position, center);
background-repeat: no-repeat;
overflow: auto;
box-sizing: border-box;
align-items: center;
@@ -227,7 +237,6 @@
padding: 24px;
text-align: center;
}
.empty h1,.empty>p{background:color-mix(in srgb,var(--rs-bg) 92%,transparent);padding:8px 14px;border-radius:var(--rs-control-radius)}
.chrome-bar {
display: flex;
@@ -251,6 +260,7 @@
}
.body {
background: var(--rs-workarea-editor-bg);
flex: 1;
display: flex;
min-height: 0;
+34 -6
View File
@@ -469,11 +469,16 @@
}
async function createIn(parent: string, kind: "folder" | "note" | "file") {
const operationRoot = workspaceRoot;
let name: string;
if (kind === "note") {
name = "untitled.md";
if (kind === "note" || kind === "folder") {
name = kind === "folder" ? "untitled" : "untitled.md";
if (kind === "folder") {
await load(parent);
if (workspaceRoot !== operationRoot || error) return;
}
} else {
const typed = await requestText(kind === "folder" ? "Folder name" : "File name, including any extension", kind === "folder" ? "folder" : "Untitled");
const typed = await requestText("File name, including any extension", "Untitled");
if (!typed) {
return;
}
@@ -484,21 +489,26 @@
}
name = typed.trim();
}
const finalName = kind === "file" ? name : uniqueName(namesIn(parent), name);
if (workspaceRoot !== operationRoot) return;
const finalName = kind === "file" ? name : uniqueName(kind === "folder" ? namesIn(parent).map(value => value.toLowerCase()) : namesIn(parent), name);
const rel = joinRel(parent, finalName);
try {
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
if (workspaceRoot !== operationRoot) return;
const order = { ...marks.order };
order[parent] = [...(order[parent] ?? []), finalName];
await persistMarks({ ...marks, order });
if (!childrenMap[parent] && parent !== "") {
if (kind === "folder" || (!childrenMap[parent] && parent !== "")) {
const next = new Set(expanded);
next.add(parent);
expanded = next;
}
await load(parent);
if (workspaceRoot !== operationRoot) return;
onStatus?.(`Created ${rel}`);
if (kind !== "folder") {
if (kind === "folder") {
startRename({ name: finalName, rel_path: rel, kind: "folder" });
} else {
onCreated?.({ name: finalName, rel_path: rel, kind: "file" });
}
} catch (err) {
@@ -575,6 +585,24 @@
await focusTreePath(paths.values().next().value);
}
export async function revealPath(path: string) {
const operationRoot = workspaceRoot;
const folders = path.split("/").slice(0, -1);
await load("");
let parent = "";
for (const folder of folders) {
if (workspaceRoot !== operationRoot) return;
parent = parent ? `${parent}/${folder}` : folder;
expanded = new Set([...expanded, parent]);
await load(parent);
}
if (workspaceRoot !== operationRoot) return;
selectOnly(path);
await focusTreePath(path);
const target = [...treeElement.querySelectorAll<HTMLElement>("[data-tree-rel]")].find(node => node.dataset.treeRel === path);
target?.scrollIntoView({ block: "nearest" });
}
async function focusTreePath(path?: string) {
await tick();
const target = [...treeElement.querySelectorAll<HTMLElement>("[data-tree-rel]")].find(node => node.dataset.treeRel === path);
+14 -1
View File
@@ -9,23 +9,34 @@
import { readerHeadingFolding } from "$lib/editor/headingFolding";
import "$lib/editor/headingFolding.css";
import { readingMenu } from "$lib/editor/readingMenu";
import type { DocumentLinkActions } from "$lib/editor/linkMenu";
type Props = {
noteRel: string;
contents: string;
linkActions?: DocumentLinkActions;
onSearch?: (text: string) => void;
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 { noteRel, contents, onOpenLink, linkActions = {}, onSearch, onEditBlock, editing = null, blockEditor }: Props = $props();
let html = $state("");
let menuError = $state("");
let sections = $state<MarkdownSection[]>([]);
let root: HTMLDivElement | undefined = $state();
const collapsedHeadings = new Set<string>();
let foldingNote = "";
let headingControls: ReturnType<typeof readerHeadingFolding> | undefined;
$effect(() => {
if (!root) return;
return readingMenu(root, { ...linkActions, open: link => onOpenLink?.(link.kind, link.target) }, onSearch, message => { menuError = message; });
});
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 => {
@@ -117,6 +128,7 @@
<!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions -->
<div
class="reading"
tabindex="-1"
bind:this={root}
onkeydown={(event) => {
if (event.target instanceof HTMLElement && event.target.classList.contains("md-edit-block") && (event.key === "Enter" || event.key === " ")) {
@@ -165,6 +177,7 @@
}
}}
>
{#if menuError}<p role="alert">{menuError}</p>{/if}
<h1 class="document-title">{markdownTitle(noteRel)}</h1>
{#if onEditBlock}
{#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)}
+10 -9
View File
@@ -10,9 +10,11 @@
let error = $state("");
let dialog: HTMLDialogElement;
let input: HTMLInputElement;
let picked = false;
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(); } }
function pick(entry?: TreeEntry) { if (entry) { picked = true; onOpen(entry); onClose(); } }
onMount(() => {
const origin = document.activeElement instanceof HTMLElement ? document.activeElement : null;
dialog.showModal(); input.focus();
let cancelled = false;
void (async () => {
@@ -27,11 +29,11 @@
} catch (err) { if (!cancelled) error = String(err); }
finally { if (!cancelled) loading = false; }
})();
return () => { cancelled = true; };
return () => { cancelled = true; if (!picked && origin?.isConnected) origin.focus({ preventScroll: true }); };
});
</script>
<dialog bind:this={dialog} aria-label={purpose} onpointerdown={(event) => {
<dialog class="rs-picker" bind:this={dialog} aria-label={purpose} onpointerdown={(event) => {
const bounds = dialog.getBoundingClientRect();
if (event.target === dialog && (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)) onClose();
}} oncancel={onClose}>
@@ -44,7 +46,7 @@
}} />
<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>
<button class="rs-picker-row" data-index={index} aria-current={selected === index ? 'true' : undefined} onclick={() => pick(entry)}><span class="file-detail"><strong>{entry.name}</strong><span class="rs-picker-hint">{entry.rel_path}</span></span></button>
{/each}
{#if !matches.length}<p>{loading ? "Finding files…" : "No matching files."}</p>{/if}
</div>
@@ -52,12 +54,11 @@
</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 { margin-top: 12vh; width: min(640px, 85vw); }
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; }
.results { max-height: 50vh; overflow: auto; }
.file-detail { min-width: 0; overflow-wrap: anywhere; }
footer { color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); }
footer { padding: 10px 14px; display: flex; justify-content: space-between; border-top: 1px solid var(--rs-border); }
</style>
+1 -1
View File
@@ -24,7 +24,7 @@
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
{ id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" },
{ id: "appearance", label: "Appearance", icon: "sun", keywords: "theme colors light dark GPT Claude Terminal Sakura" },
{ id: "appearance", label: "Appearance", icon: "sun", keywords: "theme colors light dark Claude Sakura Harvest Moon Crimson Pilot Silver Serpent" },
{ id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" },
];
let section = $state<Section>(untrack(() => help ? "about" : "general"));
+241 -59
View File
@@ -6,7 +6,12 @@
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, findPluginEditor } 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, tick, untrack } from "svelte";
import { onMount, onDestroy, tick, untrack } from "svelte";
import type { MenuLink } from "$lib/editor/linkMenu";
import { loadMarks, saveMarks } from "$lib/workspace/marks";
import { moveMarks } from "$lib/workspace/treeMoveHistory";
import { retainEditorSessions } from "$lib/editor/sessions";
import { initialDocumentPanes, syncDocumentPanes, splitDocumentPane, closeDocumentPane, selectPane, readDocumentPane } from "$lib/workspace/documentPanes";
import { selectedEditorText } from "$lib/editor/selection";
import { pluginHost } from "$lib/plugins/registry";
import type { Contributions } from "$lib/plugins/contracts";
@@ -41,6 +46,8 @@
import {
onWorkspaceEvent,
workspaceNew,
workspaceList,
workspaceOpenDefault,
workspaceCreate,
workspaceAbsPath,
workspaceLastPath,
@@ -93,7 +100,8 @@
let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen);
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
let terminalOpen = $state(false);
let reading = $state(false);
let documentPanes = $state(initialDocumentPanes());
const reading = $derived(documentPanes.panes.find(pane => pane.id === documentPanes.active)?.reading ?? false);
let quickOpen = $state(false);
let templateManager = $state(false);
let terminalStarted = $state(false);
@@ -136,11 +144,14 @@
let switching = false;
let workbenchReady = $state(false);
let documents: Documents | null = null;
let editorPane: EditorPane | undefined = $state();
let paneComponents = $state<Record<string, EditorPane | undefined>>({});
function activeEditor() { return paneComponents[documentPanes.active]; }
let fileTree: FileTree | undefined = $state();
let closingTabs = false;
const hasDirty = $derived(tabs.some(tab => tab.contents !== tab.saved));
function createDocuments() {
documentPanes = initialDocumentPanes();
const next = new Documents({
read: workspaceRead, write: workspaceWrite, image: workspaceReadDataUrl,
kind: path => isImagePath(path) ? "image" : "text", chrome: detectChrome,
@@ -149,10 +160,50 @@
tabs = next.buffers.map(tab => ({ ...tab }));
activePath = next.activePath;
const selected = next.active;
documentPanes = syncDocumentPanes(documentPanes, next.buffers.map(tab => tab.id), selected?.id ?? null);
if (selected) view = selected.chromeOverride ?? selected.chrome;
});
return next;
}
$effect(() => retainEditorSessions(tabs.map(tab => tab.id)));
onDestroy(() => retainEditorSessions([]));
const documentViews = $derived.by(() => {
const bounds = paneBounds(documentPanes.layout);
return documentPanes.panes.map(pane => ({ ...pane, buffer: tabs.find(tab => tab.id === pane.documentId) ?? null, bounds: bounds[pane.id] }))
.sort((a, b) => a.bounds.left - b.bounds.left);
});
function setReading(next: boolean, paneId = documentPanes.active) {
documentPanes = readDocumentPane(documentPanes, paneId, next);
}
function focusDocumentPane(paneId: string, focusEditor = false) {
const pane = documentPanes.panes.find(pane => pane.id === paneId);
if (!pane) return;
const tab = tabs.find(tab => tab.id === pane.documentId);
documentPanes = selectPane(documentPanes, paneId);
pluginEditorActive.set(false);
if (tab && documents?.active?.id !== tab.id) { focusLine = null; documents?.select(tab.relPath); }
if (focusEditor) void tick().then(() => {
if (documentPanes.active !== paneId) return;
paneComponents[paneId]?.focusEditor();
document.querySelector<HTMLElement>(`[data-document-pane="${paneId}"]`)?.scrollIntoView({ block: "nearest", inline: "nearest" });
});
}
function closeSplit(paneId: string) {
documentPanes = closeDocumentPane(documentPanes, paneId);
focusDocumentPane(documentPanes.active, true);
}
async function openToRight(file: TreeEntry, sourcePane: string) {
const current = documents;
const source = documentPanes.panes.find(pane => pane.id === sourcePane);
if (!current || switching || !source) return;
await current.open(file, "background");
if (documents !== current || switching || documentPanes.active !== sourcePane
|| documentPanes.panes.find(pane => pane.id === sourcePane)?.documentId !== source.documentId) return;
const target = current.buffers.find(tab => tab.relPath === file.rel_path);
if (!target) return;
documentPanes = splitDocumentPane(documentPanes, sourcePane, target.id, crypto.randomUUID());
focusDocumentPane(documentPanes.active, true);
}
let focusLine = $state<number | null>(null);
let dragging = $state<"left" | "right" | "bottom" | null>(null);
let centerStack: HTMLElement | undefined = $state();
@@ -212,7 +263,7 @@
function toggleChrome() {
const next = view === "Writing" ? "Ide" : "Writing";
reading = false;
setReading(false);
applyChrome(next);
documents?.setChrome(next);
}
@@ -306,7 +357,7 @@
await new Promise(resolve => setTimeout(resolve, 100));
}
} else throw new Error("Invalid tab transfer.");
reading = transfer.reading === true;
setReading(transfer.reading === true);
localStorage.setItem(key + ".accepted", "true");
localStorage.removeItem(key);
}
@@ -322,6 +373,7 @@
pluginEditorActive.set(false);
focusLine = null;
documents?.select(relPath);
focusDocumentPane(documentPanes.active, true);
status = documents?.active?.kind === "empty" ? "New tab" : relPath;
}
@@ -353,7 +405,7 @@
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
return tab ? [{ label: "Open in new window", icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
}
async function detachTab(item: WorkbenchTab) {
async function detachTab(item: WorkbenchTab, keepSource = false) {
const tab = workingTabs.find(tab => tab.id === item.id);
if (!tab || !workspace || !desktop) return;
if ("plugin" in tab) {
@@ -373,9 +425,9 @@
};
const accepted = (event: StorageEvent) => {
if (event.key !== key + ".accepted" || event.newValue !== "true") return;
if ("buffer" in tab) {
if (!keepSource && "buffer" in tab) {
if (documents === current && bufferSnapshot(current?.buffers.find(buffer => buffer.id === tab.buffer.id)) === snapshot) current?.close(tab.relPath);
} else if (JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key);
} else if (!keepSource && "plugin" in tab && JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key);
finish();
};
try {
@@ -449,7 +501,7 @@
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
items.push(
{ label: "Save as template", icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => editorPane?.toggleReadingView() },
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => activeEditor()?.toggleReadingView() },
{ label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome },
);
}
@@ -482,7 +534,7 @@
error = null;
focusLine = null;
if (line) {
reading = false;
setReading(false);
queueMicrotask(() => { focusLine = line; });
}
} catch (err) { if (documents === current) error = String(err); }
@@ -492,8 +544,8 @@
const current = documents;
await openFile(entry);
if (documents !== current || current?.active?.relPath !== entry.rel_path || !isMarkdownPath(entry.rel_path)) return;
reading = false;
editorPane?.focusTitle(current.active.id);
setReading(false);
activeEditor()?.focusTitle(current.active.id);
}
function readFileDataUrl(file: File): Promise<string> {
@@ -505,11 +557,11 @@
});
}
async function insertImage(file: File): Promise<string | null> {
if (!buffer || buffer.kind !== "text" || !isMarkdownPath(buffer.relPath)) {
async function insertImage(file: File, note = buffer): Promise<string | null> {
if (!note || note.kind !== "text" || !isMarkdownPath(note.relPath)) {
return null;
}
const noteRel = buffer.relPath;
const noteRel = note.relPath;
const current = documents;
try {
const rel = attachmentRel(file.name);
@@ -538,8 +590,8 @@
searchRequest = { text, id: (searchRequest?.id || 0) + 1 };
}
async function extractSelection(markdown: string, label: string, valid: () => boolean): Promise<string | null> {
const current = documents, note = buffer;
async function extractSelection(markdown: string, label: string, valid: () => boolean, note = buffer): Promise<string | null> {
const current = documents;
if (!workspace || !current || !note) return null;
const folder = note.relPath.slice(0, note.relPath.lastIndexOf("/") + 1);
const suggested = label.replace(/[<>:"/\\|?*\r\n]/g, " ").trim().slice(0, 60) || "Extracted selection";
@@ -587,8 +639,7 @@
} finally { saving = false; }
}
async function saveCopy() {
const tab = buffer;
async function saveCopy(tab = buffer) {
if (!tab || tab.kind !== "text") return;
const name = await requestText("Save a copy as (workspace relative path)", tab.relPath.replace(/(\.[^./]+)?$/, " copy$1"));
if (!name) return;
@@ -789,7 +840,72 @@
}
}
async function openLink(kind: "md" | "wiki", target: string) {
function workspaceLinkItems(link: MenuLink, origin = activePath ?? "", sourcePane = documentPanes.active): ActionMenuItem[] {
const current = documents, currentWorkspace = workspace;
const valid = () => documents === current && workspace === currentWorkspace && !!currentWorkspace;
const entry = async () => {
for (const path of linkCandidates(origin, link.target, link.kind)) {
if (!valid()) throw new Error("The workspace changed. Open the link menu again.");
const parent = path.split("/").slice(0, -1).join("/");
let files: TreeEntry[];
try { files = await workspaceList(parent); } catch { continue; }
const found = files.find(file => file.rel_path === path && file.kind === "file");
if (found) return found;
}
throw new Error(`Could not find ${link.target} in the workspace.`);
};
const run = (action: (file: TreeEntry) => void | Promise<void>) => () => {
void entry().then(file => { if (valid()) return action(file); }).catch(reason => { error = String(reason); });
};
async function rename(file: TreeEntry, move = false) {
const typed = await requestText(move ? "Move file to (workspace path, including filename)" : "New file name", move ? file.rel_path : file.name);
if (!typed || !valid()) return;
let to = typed.trim().replaceAll("\\", "/");
if (move) {
if (!to || to.startsWith("/") || to.split("/").some(part => !part || part === "." || part === "..") || /[<>:"|?*\u0000-\u001f]/.test(to)) throw new Error("Enter a relative workspace path without reserved characters.");
} else {
const plan = planRename(file.rel_path, to);
if (plan.action === "noop") return;
if (plan.action === "error") throw new Error(plan.message);
to = plan.to;
}
if (to === file.rel_path) return;
const marks = await loadMarks();
if (!valid()) return;
await workspaceRename(file.rel_path, to, currentWorkspace!.root);
if (!valid()) return;
applyPathRename(file.rel_path, to);
await saveMarks(moveMarks(marks, file.rel_path, to));
refreshToken++;
status = `Moved to ${to}`;
}
return [
{ label: "Open to the right", icon: "split-right", run: run(file => openToRight(file, sourcePane)) },
{ label: "Open in new window", icon: "external", disabled: !desktop, run: run(async file => {
await openFile(file, undefined, "new");
if (!valid()) return;
const tab = workingTabs.find(tab => tab.relPath === file.rel_path);
if (tab) await detachTab(tab, true);
}) },
{ label: "Copy path", icon: "copy", children: [
{ label: "Workspace path", icon: "copy", run: run(file => copyTabPath(file.rel_path, false)) },
{ label: "System path", icon: "copy", run: run(file => copyTabPath(file.rel_path, true)) },
] },
{ label: "Rename…", icon: "rename", run: run(file => rename(file)) },
{ label: "Move file to…", icon: "folder", run: run(file => rename(file, true)) },
{ label: "Bookmark", icon: "bookmark", run: run(async file => {
const marks = await loadMarks();
if (!valid()) return;
if (!marks.bookmarks.includes(file.rel_path)) await saveMarks({ ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
refreshToken++; status = `Bookmarked ${file.name}`;
}) },
{ label: "Open in default app", icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
{ label: "Show in system explorer", icon: "folder", run: run(file => workspaceReveal(file.rel_path)) },
{ label: "Reveal file in navigation", icon: "folder", run: run(async file => { closePluginSidebar(); leftView = "files"; leftOpen = true; await tick(); await fileTree?.revealPath(file.rel_path); }) },
];
}
async function openLink(kind: "md" | "wiki", target: string, origin = activePath ?? "", paneId = documentPanes.active) {
if (/^(https?:\/\/|mailto:)/i.test(target)) {
try {
if (/^https?:\/\//i.test(target) && await pluginHost.get("browser")?.open(target)) return;
@@ -797,7 +913,8 @@
} catch (err) { error = String(err); }
return;
}
const rels = linkCandidates(activePath ?? "", target, kind);
const rels = linkCandidates(origin, target, kind);
focusDocumentPane(paneId);
for (const rel of rels) {
try {
await documents?.open({ name: rel.split("/").pop() ?? rel, rel_path: rel, kind: "file" });
@@ -952,6 +1069,7 @@
onpointerup={() => (dragging = null)}
onpointerleave={() => (dragging = null)}
>
<div class="workarea-background" aria-hidden="true"></div>
<header class="header" data-tauri-drag-region>
<div class="header-left" data-tauri-drag-region>
{#if !transferredWindow}
@@ -1034,6 +1152,7 @@
<div class="left-stack">
<div class="left-layer" class:shown={leftView === "files"}>
<FileTree
bind:this={fileTree}
workspaceRoot={workspace.root}
showInternal={settings.showInternalFolder}
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
@@ -1103,39 +1222,57 @@
{/each}
</div>
<div class="editor-host" class:plugin-covered={editorPluginVisible}>
{#if buffer?.diskError}
<div class="conflict" role="alert"><span>{buffer.diskError}</span><button onclick={() => void saveCopy()}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
{:else if buffer?.diskContents != null}
<div class="conflict" role="alert">
<span>This file changed on disk. Your edits are preserved. Review both versions before saving.</span>
<button onclick={() => { if (buffer) documents?.resolve(buffer.id, true); }}>Use disk version</button>
<button onclick={() => { if (buffer) documents?.resolve(buffer.id, false); }}>Keep my edits</button>
<button onclick={() => void saveCopy()}>Save a copy</button>
</div>
<details class="disk-review"><summary>View disk version</summary><pre>{buffer.diskContents}</pre></details>
{/if}
<EditorPane
bind:this={editorPane}
{tabs}
hasWorkspace={!!workspace}
onOpenWorkspace={() => void chooseWorkspace()}
onNewFile={() => void newFile()}
onNewNote={(event) => { void newNote(event); }}
onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{browserOpening}
{buffer}
chrome={view}
{reading}
{focusLine}
{onChange}
onInsertImage={insertImage}
onRenameTitle={renameNoteTitle}
tableActions={{ onSearch: searchSelection, onExtract: extractSelection }}
onToggleReading={() => (reading = !reading)}
onToggleChrome={toggleChrome}
onOpenLink={(kind, target) => void openLink(kind, target)}
/>
<div class="document-panes" class:split={documentViews.length > 1}>
{#each documentViews as pane (pane.id)}
<!-- svelte-ignore a11y_no_static_element_interactions (Focus identifies the document for shared commands.) -->
<div class="document-pane" class:focused={documentPanes.active === pane.id}
data-document-pane={pane.id} data-document-path={pane.buffer?.relPath ?? ""}
style:--pane-weight={pane.bounds.width}
onpointerdowncapture={() => focusDocumentPane(pane.id)}
onfocusin={() => focusDocumentPane(pane.id)}>
{#if pane.buffer?.diskError}
<div class="conflict" role="alert"><span>{pane.buffer.diskError}</span><button onclick={() => void saveCopy(pane.buffer)}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
{:else if pane.buffer?.diskContents != null}
<div class="conflict" role="alert">
<span>This file changed on disk. Your edits are preserved. Review both versions before saving.</span>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>Use disk version</button>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>Keep my edits</button>
<button onclick={() => void saveCopy(pane.buffer)}>Save a copy</button>
</div>
<details class="disk-review"><summary>View disk version</summary><pre>{pane.buffer.diskContents}</pre></details>
{/if}
<EditorPane
bind:this={paneComponents[pane.id]}
{tabs}
active={documentPanes.active === pane.id}
onCloseSplit={documentViews.length > 1 ? () => closeSplit(pane.id) : undefined}
hasWorkspace={!!workspace}
onOpenWorkspace={() => void chooseWorkspace()}
onNewFile={() => void newFile()}
onNewNote={(event) => { void newNote(event); }}
onQuickOpen={() => quickOpen = true}
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
{browserOpening}
buffer={pane.buffer}
chrome={pane.buffer?.chromeOverride ?? pane.buffer?.chrome ?? "Writing"}
reading={pane.reading}
focusLine={documentPanes.active === pane.id ? focusLine : null}
{onChange}
onInsertImage={file => insertImage(file, pane.buffer)}
onRenameTitle={renameNoteTitle}
tableActions={{ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) }}
linkActions={{
browser: browserContribution ? async target => { if (!await browserContribution?.open(target)) throw new Error("Could not open the app browser."); } : undefined,
defaultBrowser: target => openUrl(target),
workspaceItems: link => workspaceLinkItems(link, pane.buffer?.relPath ?? "", pane.id),
}}
onToggleReading={() => setReading(!pane.reading, pane.id)}
onToggleChrome={() => { focusDocumentPane(pane.id); toggleChrome(); }}
onOpenLink={(kind, target) => void openLink(kind, target, pane.buffer?.relPath ?? "", pane.id)}
/>
</div>
{/each}
</div>
</div>
</main>
{#if terminalContribution && terminalStarted}
@@ -1170,7 +1307,7 @@
items={outlineItems}
onJump={(line) => {
pluginEditorActive.set(false);
reading = false;
setReading(false);
focusLine = null;
queueMicrotask(() => {
focusLine = line;
@@ -1199,6 +1336,8 @@
.disk-review { padding: 8px 12px; max-height: 35vh; overflow: auto; flex: 0 0 auto; }
.disk-review pre { white-space: pre-wrap; user-select: text; }
.shell {
position: relative;
isolation: isolate;
height: 100vh;
display: grid;
--ribbon-width: 0px;
@@ -1207,6 +1346,39 @@
background: var(--rs-bg);
}
.workarea-background {
position: absolute;
inset: var(--rs-titlebar-height) 0 22px;
z-index: -1;
pointer-events: none;
background-color: var(--rs-new-tab-bg, var(--rs-bg));
background-image: var(--rs-background-image, var(--rs-new-tab-image, none));
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
background-repeat: no-repeat;
}
.workarea-background::before,
.workarea-background::after {
content: '';
position: absolute;
inset: 0;
pointer-events: none;
background-repeat: no-repeat;
}
.workarea-background::before {
background-image: var(--rs-background-previous-image, none);
background-size: var(--rs-background-previous-layer-sizes, 100% 100%, var(--rs-background-previous-size, cover));
background-position: var(--rs-background-previous-layer-positions, center, var(--rs-background-previous-position, center));
}
.workarea-background::after {
background-image: var(--rs-background-transition-image, none);
background-size: var(--rs-background-layer-sizes, 100% 100%, var(--rs-background-size, cover));
background-position: var(--rs-background-layer-positions, center, var(--rs-background-position, center));
}
.shell.left-open {
grid-template-columns: var(--ribbon-width) var(--left) 1px minmax(0, 1fr);
}
@@ -1232,7 +1404,7 @@
min-height: 0;
padding: 6px 5px;
overflow-y: auto;
background: var(--rs-bg-elevated);
background: var(--rs-workarea-sidebar-bg);
border-right: 1px solid var(--rs-border);
}
@@ -1315,7 +1487,7 @@
min-width: 0;
min-height: 0;
overflow: hidden;
background: var(--rs-bg);
background: transparent;
}
.center-stack {
@@ -1337,6 +1509,16 @@
position: relative;
}
.editor-host { container-type: inline-size; }
.document-panes { flex: 1; min-height: 0; display: flex; overflow: hidden; }
.document-pane { flex: var(--pane-weight) 1 0; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; }
.document-pane + .document-pane { border-left: 1px solid var(--rs-border); }
.document-panes.split .document-pane.focused :global(.chrome-bar) { background: var(--rs-bg-active); }
@container (max-width: 640px) {
.document-panes.split { flex-direction: column; overflow-y: auto; }
.document-panes.split .document-pane { flex: 1 0 320px; }
.document-pane + .document-pane { border-left: 0; border-top: 1px solid var(--rs-border); }
}
.editor-host.plugin-covered { display: none; }
.center { position: relative; }
.plugin-panes { position: relative; flex: 1; min-height: 0; min-width: 0; overflow: hidden; }
@@ -1347,7 +1529,7 @@
.left,
.right {
background: var(--rs-bg-elevated);
background: var(--rs-workarea-sidebar-bg);
}
.left {
@@ -1487,7 +1669,7 @@
display: flex;
flex-direction: column;
min-height: 0;
background: var(--rs-bg-elevated);
background: transparent;
}
.bottom > :global(*) {
+13 -13
View File
@@ -82,6 +82,7 @@
finally { busy = false; }
}
function navigate(event: KeyboardEvent) {
if (event.key === "Escape") { event.preventDefault(); close(); return; }
if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
event.preventDefault();
const buttons = [...menu.querySelectorAll<HTMLButtonElement>("button:not(:disabled)")];
@@ -92,14 +93,14 @@
</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}>
<div bind:this={menu} popover="auto" class="workspace-menu rs-picker" 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" />
<button class="workspace-row rs-picker-row" aria-current={path === currentRoot ? "true" : undefined} disabled={busy} onclick={() => open(path)}>
<span class="rs-picker-icon"><Icon icon="folder-open" /></span>
<span class="details"><span>{folderName(path)}</span><small>{path}</small></span>
{#if path === currentRoot}<span class="current-label">Current</span>{/if}
</button>
@@ -107,8 +108,8 @@
</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>
<button class="rs-picker-row" disabled={busy} onclick={newWorkspace}><span class="rs-picker-icon"><Icon icon="folder-plus" /></span> New workspace…</button>
<button class="rs-picker-row" disabled={busy} onclick={browse}><span class="rs-picker-icon"><Icon icon="folder-open" /></span> Open another folder…</button>
</footer>
</div>
@@ -129,17 +130,16 @@
{/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; }
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; width: min(380px, calc(100vw - 16px)); }
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; }
.recent { max-height: min(360px, 45vh); overflow: auto; }
form 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; }
form button:hover { background: var(--rs-bg-active); }
form button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
form 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); }
+24
View File
@@ -0,0 +1,24 @@
export interface BackgroundFrame {
url: string;
blurredUrl?: string;
overlay: number;
position: 'center' | 'top left' | 'top' | 'top right' | 'left' | 'right' | 'bottom left' | 'bottom' | 'bottom right';
size: 'cover' | 'contain' | 'auto';
previous?: Omit<BackgroundFrame, 'previous' | 'transitionMs'>;
transitionMs?: number;
}
export interface BackgroundApi {
readonly version: 1;
chooseFolder(): Promise<string | null>;
defaultFolder?(): Promise<string>;
list(folder: string): Promise<{ name: string }[]>;
read(folder: string, name: string): Promise<Uint8Array>;
readImageSettings?(folder: string): Promise<string | null>;
writeImageSettings?(folder: string, contents: string, expected: string | null): Promise<void>;
set(target: string, frame: BackgroundFrame | null): void;
get(target: string): BackgroundFrame | null;
subscribe(listener: (target: string) => void): () => void;
}
export type BackgroundFiles = Pick<BackgroundApi, 'chooseFolder' | 'defaultFolder' | 'list' | 'read' | 'readImageSettings' | 'writeImageSettings'>;
+125
View File
@@ -0,0 +1,125 @@
import type { BackgroundFrame } from './backgroundContracts.ts';
const positions = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'];
const properties = ['--rs-background-overlay', '--rs-background-image', '--rs-background-position', '--rs-background-size', '--rs-background-layer-sizes', '--rs-background-layer-positions', '--rs-background-previous-layer-sizes', '--rs-background-previous-layer-positions', '--rs-background-previous-image', '--rs-background-previous-position', '--rs-background-previous-size', '--rs-background-transition-image', '--rs-workarea-sidebar-bg', '--rs-workarea-editor-bg', '--rs-workarea-surface-opacity', '--rs-workarea-plugin-bg'] as const;
function validImage(frame: BackgroundFrame) {
return frame && typeof frame.url === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.url)
&& Number.isFinite(frame.overlay) && frame.overlay >= -1 && frame.overlay <= 1
&& (frame.blurredUrl === undefined || (typeof frame.blurredUrl === 'string' && /^blob:[^\s"'\\()]+$/.test(frame.blurredUrl)))
&& positions.includes(frame.position) && ['cover', 'contain', 'auto'].includes(frame.size);
}
function image(frame: BackgroundFrame) {
const shade = frame.overlay < 0 ? '255,255,255' : '0,0,0';
const overlay = `linear-gradient(rgba(${shade},${Math.abs(frame.overlay)}),rgba(${shade},${Math.abs(frame.overlay)}))`;
return { overlay, image: `${overlay}, url("${frame.url}")${frame.blurredUrl ? `, url("${frame.blurredUrl}")` : ''}`,
sizes: `100% 100%, ${frame.size}${frame.blurredUrl ? ', cover' : ''}`,
positions: `center, ${frame.position}${frame.blurredUrl ? ', center' : ''}` };
}
function copy(frame: BackgroundFrame): BackgroundFrame {
return { ...frame, ...(frame.previous ? { previous: { ...frame.previous } } : {}) };
}
function checkTarget(target: string) {
if (target !== 'app' && target !== 'pm-all' && !/^pm-board:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(target)) {
throw new Error('Invalid background target.');
}
}
/** Each window retains temporary frames without changing saved appearance settings. */
export class BackgroundHub {
private frames = new Map<string, Map<symbol, BackgroundFrame>>();
private listeners = new Set<(target: string) => void>();
private restore?: () => void;
private body: () => HTMLElement | undefined;
constructor(body: () => HTMLElement | undefined = () => typeof document === 'undefined' ? undefined : document.body) {
this.body = body;
}
get(target: string): BackgroundFrame | null {
checkTarget(target);
const frame = [...(this.frames.get(target)?.values() ?? [])].at(-1);
return frame ? copy(frame) : null;
}
set(owner: symbol, target: string, frame: BackgroundFrame | null) {
checkTarget(target);
if (frame !== null && (!validImage(frame)
|| (frame.previous !== undefined && (!validImage(frame.previous) || 'previous' in frame.previous || 'transitionMs' in frame.previous))
|| (frame.transitionMs !== undefined && (!Number.isFinite(frame.transitionMs) || frame.transitionMs < 0 || frame.transitionMs > 5000)))) {
throw new Error('Invalid background frame. Use a blob URL and an overlay from -1 to 1.');
}
const owners = this.frames.get(target) ?? new Map<symbol, BackgroundFrame>();
const removed = owners.delete(owner);
if (frame) owners.set(owner, copy(frame));
if (owners.size) this.frames.set(target, owners);
else this.frames.delete(target);
if (frame || removed) this.changed(target);
}
removeOwner(owner: symbol) {
for (const [target, owners] of this.frames) {
if (!owners.delete(owner)) continue;
if (!owners.size) this.frames.delete(target);
this.changed(target);
}
}
subscribe(listener: (target: string) => void): () => void {
this.listeners.add(listener);
return () => { this.listeners.delete(listener); };
}
private changed(target: string) {
if (target === 'app') this.applyApp();
for (const listener of [...this.listeners]) {
try { listener(target); } catch { /* A subscriber must not prevent cleanup or other subscribers. */ }
}
}
private applyApp() {
const frame = this.get('app');
if (!frame) { this.restore?.(); this.restore = undefined; return; }
const body = this.body();
if (!body) return;
if (!this.restore) {
const previous = properties.map(key => [key, body.style.getPropertyValue(key), body.style.getPropertyPriority(key)]);
this.restore = () => {
for (const [key, value, priority] of previous) {
if (value) body.style.setProperty(key, value, priority);
else body.style.removeProperty(key);
}
};
}
const { overlay, image: currentImage, sizes, positions: layerPositions } = image(frame);
body.style.setProperty('--rs-background-overlay', overlay);
body.style.setProperty('--rs-background-image', currentImage);
body.style.setProperty('--rs-background-position', frame.position);
body.style.setProperty('--rs-background-size', frame.size);
body.style.setProperty('--rs-background-layer-sizes', sizes);
body.style.setProperty('--rs-background-layer-positions', layerPositions);
body.style.setProperty('--rs-background-previous-layer-sizes', frame.previous ? image(frame.previous).sizes : sizes);
body.style.setProperty('--rs-background-previous-layer-positions', frame.previous ? image(frame.previous).positions : layerPositions);
body.style.setProperty('--rs-workarea-sidebar-bg', 'var(--rs-image-sidebar-bg)');
body.style.setProperty('--rs-workarea-editor-bg', 'var(--rs-image-editor-bg)');
body.style.setProperty('--rs-workarea-surface-opacity', '82%');
body.style.setProperty('--rs-workarea-plugin-bg', 'transparent');
body.style.setProperty('--rs-background-transition-image', frame.previous ? currentImage : 'none');
body.style.setProperty('--rs-background-previous-image', frame.previous ? image(frame.previous).image : 'none');
body.style.setProperty('--rs-background-previous-position', frame.previous?.position ?? frame.position);
body.style.setProperty('--rs-background-previous-size', frame.previous?.size ?? frame.size);
if (typeof document !== 'undefined') {
for (const element of body.querySelectorAll('.workarea-background')) {
for (const animation of element.getAnimations()) animation.cancel();
if (frame.previous && frame.transitionMs && !window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
element.animate([{ opacity: 0 }, { opacity: 1 }], { duration: frame.transitionMs, easing: 'ease-in-out', pseudoElement: '::after' });
}
}
}
}
}
export const backgroundHub = new BackgroundHub();
+8
View File
@@ -242,6 +242,14 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
const session = new ExternalSession(id, {
completionTransport,
git: gitApi,
backgrounds: {
chooseFolder: () => invoke<string | null>('backgrounds_choose_folder', { id }),
defaultFolder: () => invoke<string>('backgrounds_default_folder', { id }),
list: folder => invoke<{ name: string }[]>('backgrounds_list', { id, folder }),
read: async (folder, name) => Uint8Array.from(atob(await invoke<string>('backgrounds_read', { id, folder, name })), character => character.charCodeAt(0)),
readImageSettings: folder => invoke<string | null>('backgrounds_read_image_settings', { id, folder }),
writeImageSettings: (folder, contents, expected) => invoke<void>('backgrounds_write_image_settings', { id, folder, contents, expected }),
},
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
workspace: {
list: path => workspaceList(path ?? ""), read: workspaceRead,
+31 -2
View File
@@ -2,6 +2,8 @@ import { pluginHost, type ContributionRegistry } from "./registry.ts";
import { completionHub } from "../completion/hub.ts";
import { registerCompletionInput } from "../completion/input.ts";
import { showActionMenu } from "../ui/managedActionMenu.ts";
import { backgroundHub } from "./backgrounds.ts";
import type { BackgroundFiles } from "./backgroundContracts.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -23,8 +25,10 @@ export class ExternalSession {
private mounted = new Set<Dispose>();
private contributions: Dispose[] = [];
private registry: ContributionRegistry;
private backgroundOwner = Symbol('plugin backgrounds');
private backgroundSubscriptions = new Set<() => void>();
readonly id: string;
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
private changed: () => void;
private show: PluginApi["openView"];
private close?: PluginApi["closeView"];
@@ -33,7 +37,7 @@ export class ExternalSession {
private receiveTab?: (data: string) => void | Promise<void>;
private openDocument: (path: string) => Promise<void>;
private renameDocument?: PluginApi["renameDocument"];
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; backgrounds?: BackgroundFiles; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
this.openDocument = openDocument;
this.renameDocument = renameDocument;
this.close = close;
@@ -50,6 +54,25 @@ export class ExternalSession {
};
const api: PluginApi = {
id: this.id, signal: this.controller.signal,
...(this.services.backgrounds ? { backgrounds: {
version: 1 as const,
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
...(this.services.backgrounds.defaultFolder ? { defaultFolder: () => this.backgroundRequest(() => this.services.backgrounds!.defaultFolder!()) } : {}),
list: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.list(folder)),
read: (folder: string, name: string) => this.backgroundRequest(() => this.services.backgrounds!.read(folder, name)),
...(this.services.backgrounds.readImageSettings ? { readImageSettings: (folder: string) => this.backgroundRequest(() => this.services.backgrounds!.readImageSettings!(folder)) } : {}),
...(this.services.backgrounds.writeImageSettings ? { writeImageSettings: (folder: string, contents: string, expected: string | null) => this.backgroundRequest(() => this.services.backgrounds!.writeImageSettings!(folder, contents, expected)) } : {}),
set: (target: string, frame: import('./backgroundContracts.ts').BackgroundFrame | null) => { this.check(); backgroundHub.set(this.backgroundOwner, target, frame); },
get: (target: string) => { this.check(); return backgroundHub.get(target); },
subscribe: (listener: (target: string) => void) => {
this.check();
if (typeof listener !== 'function') throw new Error('A background listener must be a function.');
const off = backgroundHub.subscribe(target => { if (!this.stopped) listener(target); });
const cleanup = () => { off(); this.backgroundSubscriptions.delete(cleanup); };
this.backgroundSubscriptions.add(cleanup);
return cleanup;
},
} } : {}),
ui: { showActionMenu: options => { this.check(); return showActionMenu(options, this.controller.signal); } },
...(this.services.git ? { git: {
status: () => { this.check(); return this.services.git!.status(); },
@@ -145,6 +168,10 @@ 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(); }
private backgroundRequest<T>(request: () => Promise<T>): Promise<T> {
this.check();
return request().then(value => { this.check(); return value; });
}
async dropTab(data: string) {
this.check();
if (!this.receiveTab) throw new Error("This plugin cannot receive tabs.");
@@ -170,6 +197,8 @@ export class ExternalSession {
stop(): Promise<void> {
if (this.stopping) return this.stopping;
this.stopped = true; this.controller.abort(); this.commands.clear(); this.views.clear(); this.documentTypes.clear(); this.receiveTab = undefined; this.changed();
for (const off of this.backgroundSubscriptions) off();
backgroundHub.removeOwner(this.backgroundOwner);
for (const remove of this.contributions.splice(0)) remove();
this.stopping = (async () => {
const errors: unknown[] = [];
+2
View File
@@ -1,6 +1,7 @@
import type { Contributions } from "./contracts.ts";
import type { CompletionApi } from "../completion/contracts.ts";
import type { ActionMenuItem } from "../ui/actionMenu.ts";
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?: PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> }
@@ -18,6 +19,7 @@ export interface PluginDocumentType {
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PluginApi {
backgrounds?: import("./backgroundContracts.ts").BackgroundApi;
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
git?: import("../git/contracts.ts").GitApi;
completion?: CompletionApi;
+29 -10
View File
@@ -6,7 +6,7 @@
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, BACKGROUND_POSITIONS, BACKGROUND_SIZES, parseAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, parseAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
let error = $state('');
let status = $state('');
@@ -16,16 +16,18 @@
let installed = $state<CustomTheme[]>([]);
let themeInput: HTMLInputElement;
let closePicker = () => {};
const themes = $derived([{ id: 'default', name: 'RuneStone' }, { id: 'claude', name: 'Claude' }, { id: 'sakura', name: 'Sakura' }, ...installed.map(theme => ({ id: `custom:${theme.id}`, name: theme.name }))]);
const themes = $derived([...BUILTIN_THEMES, ...installed.map(theme => ({ id: `custom:${theme.id}` as ThemeName, name: theme.name }))].flatMap(theme =>
themeModes(theme.id).map(mode => ({
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? 'Light' : 'Dark'}`,
}))));
onDestroy(() => closePicker());
function picker(event: MouseEvent, mode = false) {
function picker(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const choices = mode ? [{ id: 'light', name: 'Light' }, { id: 'dark', name: 'Dark' }] : themes;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: mode ? 'Appearance' : 'Color theme', parent: anchor.closest('dialog') ?? undefined,
items: choices.map(choice => ({ label: choice.name, radio: true, checked: choice.id === (mode ? appearance.mode : appearance.theme),
run: () => change(mode ? { ...appearance, mode: choice.id as 'light' | 'dark' } : { ...appearance, theme: choice.id as ThemeName }) })) }).close;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: 'Color theme', parent: anchor.closest('dialog') ?? undefined,
items: themes.map(choice => ({ label: choice.name, radio: true, checked: choice.theme === appearance.theme && choice.mode === appearance.mode,
run: () => change({ ...appearance, theme: choice.theme, mode: choice.mode }) })) }).close;
}
const positionLabels = ['Center', 'Top left', 'Top center', 'Top right', 'Center left', 'Center right', 'Bottom left', 'Bottom center', 'Bottom right'];
const sizeLabels = ['Fill', 'Fit', 'Actual size'];
@@ -105,10 +107,13 @@
}
</script>
<h2>Appearance</h2>
<p>Choose a color theme and a light or dark appearance.</p>
<p>Choose a color theme variant.</p>
<div class="card">
<div class="setting-row"><span>Color theme</span><button class="picker" aria-label="Color theme" aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.id === appearance.theme)?.name ?? 'RuneStone'}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Appearance</span><button class="picker" aria-label="Appearance" aria-haspopup="menu" disabled={appearance.theme === 'sakura'} onclick={event => picker(event, true)}>{appearance.mode === 'light' ? 'Light' : 'Dark'}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Color theme</span><button class="picker" aria-label="Color theme" aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div>
</div>
<div class="theme-preview" role="img" aria-label="Color theme preview">
<div class="preview-sidebar" aria-hidden="true"><span></span><span></span><span></span></div>
<div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">A place for your ideas.</span><span class="preview-selection">Selected text</span><span class="preview-link">Link</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></div>
</div>
<div class="theme-actions">
<input bind:this={themeInput} type="file" accept=".json,application/json" aria-label="Theme JSON file" hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} />
@@ -149,6 +154,20 @@
.picker{display:flex;align-items:center;gap:8px;min-height:var(--rs-settings-control-height);max-width:100%;padding:4px 8px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.picker :global(svg){width:14px;height:14px;flex-shrink:0}
.picker:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
.theme-preview{display:flex;gap:var(--rs-settings-gap);margin-top:var(--rs-settings-gap);padding:var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);min-height:100px}
.preview-sidebar{display:flex;flex-direction:column;gap:var(--rs-settings-gap);width:22%;padding:var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
.preview-sidebar span{height:6px;background:var(--rs-text-dim);opacity:.5;border-radius:var(--rs-control-radius)}
.preview-sidebar span:first-child{height:20px;background:var(--rs-bg-active);opacity:1}
.preview-document{display:flex;align-items:flex-start;flex-direction:column;gap:var(--rs-settings-gap);flex:1;min-width:0;padding:4px}
.preview-document strong{color:var(--rs-text-strong);font-family:var(--rs-font-heading)}
.preview-prose{font-family:var(--rs-font-prose);color:var(--rs-text)}
.preview-selection{background:var(--rs-selection);color:var(--rs-text);padding:2px 4px;border-radius:var(--rs-item-selection-radius)}
.preview-link{color:var(--rs-accent);font-size:var(--rs-settings-description-size)}
.preview-code{font-family:var(--rs-font-mono);font-size:var(--rs-settings-description-size);line-height:1.6;overflow-wrap:anywhere;white-space:normal}
.preview-keyword{color:var(--rs-syntax-keyword)}
.preview-string{color:var(--rs-syntax-string,var(--rs-ok))}
.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 input[type=range]{width:160px;max-width:100%;min-width:0}
.overlay-value{padding:0;gap:4px;flex-wrap:nowrap}
+41 -10
View File
@@ -1,15 +1,27 @@
import { customThemes, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts';
export const APPEARANCE_KEY = 'runestone.appearance';
export const THEMES = ['default', 'claude', 'sakura'] as const;
export const THEMES = ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent'] as const;
export const BUILTIN_THEMES = [
{ id: 'default', name: 'RuneStone' }, { id: 'claude', name: 'Claude' }, { id: 'sakura', name: 'Sakura' },
{ id: 'harvest-moon', name: 'Harvest Moon' }, { id: 'crimson-pilot', name: 'Crimson Pilot' }, { id: 'silver-serpent', name: 'Silver Serpent' },
] as const;
// Preserve selections saved before the public palette IDs changed.
const LEGACY_THEME_IDS: Record<string, typeof THEMES[number]> = { holo: 'harvest-moon', asuka: 'crimson-pilot', malfoid: 'silver-serpent' };
export function themeModes(theme: string): readonly ('light' | 'dark')[] {
const character = characterTheme(theme);
return character ? [character.mode] : theme === 'sakura' ? ['light'] : ['light', 'dark'];
}
export type ThemeName = typeof THEMES[number] | `custom:${string}`;
export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'] as const;
export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const;
export type Appearance = { theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } };
export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' };
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown } | null): Appearance {
const theme: ThemeName = typeof value?.theme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(value.theme) || (THEMES as readonly string[]).includes(value.theme)) ? value.theme as ThemeName : 'default';
const result: Appearance = { theme, mode: theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark' };
const savedTheme = typeof value?.theme === 'string' && Object.hasOwn(LEGACY_THEME_IDS, value.theme) ? LEGACY_THEME_IDS[value.theme] : value?.theme;
const theme: ThemeName = typeof savedTheme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(savedTheme) || (THEMES as readonly string[]).includes(savedTheme)) ? savedTheme as ThemeName : 'default';
const result: Appearance = { theme, mode: characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') };
const background = value?.newTabBackground;
if (background && typeof background === 'object') {
const source = background as { image?: unknown; imageId?: unknown; overlay?: unknown; position?: unknown; size?: unknown };
@@ -41,24 +53,38 @@ const palettes = {
sakura: {
light: ['#fefcfc','#fefcfc','#dbeacb','#f8dbe6','#687788','#513346','#321c2a','#98556c','#ffc9dc'],
},
};
function builtinPalette(theme: ThemeName) {
if (theme === 'sakura') return { light: palettes.sakura.light, dark: palettes.sakura.light };
const character = characterTheme(theme);
if (character) return { light: character.surfaces, dark: character.surfaces };
return palettes[theme === 'claude' ? 'claude' : 'default'];
}
export function exportAppearanceTheme(theme: ThemeName): CustomTheme {
const custom = customThemes().find(item => `custom:${item.id}` === theme);
if (custom) return custom;
const palette = theme === 'sakura' ? { light: palettes.sakura.light, dark: palettes.sakura.light }
: palettes[theme === 'claude' ? 'claude' : 'default'];
const palette = builtinPalette(theme);
const syntax = characterSyntax(theme);
const extra = characterTheme(theme) ? { ...syntax, 'accent-2': characterTheme(theme)!.secondary } : {};
return { schema: 1, id: 'my-theme', name: 'My theme',
light: Object.fromEntries(keys.map((key, index) => [key, palette.light[index]])),
dark: Object.fromEntries(keys.map((key, index) => [key, palette.dark[index]])) };
light: { ...Object.fromEntries(keys.map((key, index) => [key, palette.light[index]])), ...extra },
dark: { ...Object.fromEntries(keys.map((key, index) => [key, palette.dark[index]])), ...extra } };
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
function applyBackgroundSurfaces(root: HTMLElement, hasImage: boolean) {
root.style.setProperty('--rs-workarea-sidebar-bg', hasImage ? 'var(--rs-image-sidebar-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-workarea-editor-bg', hasImage ? 'var(--rs-image-editor-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? '82%' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'transparent' : 'var(--rs-bg)');
}
async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) {
const id = background?.imageId;
backgroundRequests.set(root, id);
if (!id) { applyBackgroundImage(root, background?.image); return; }
const previous = backgroundUrls.get(root);
if (previous?.image === id) { root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`); return; }
if (previous?.image === id) { root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`); applyBackgroundSurfaces(root, true); return; }
applyBackgroundImage(root);
try {
const file = await readBackgroundImage(id);
@@ -67,6 +93,7 @@ async function applySavedBackground(root: HTMLElement, background?: Appearance['
const old = backgroundUrls.get(root);
backgroundUrls.set(root, { image: id, url });
root.style.setProperty('--rs-new-tab-image', `url("${url}")`);
applyBackgroundSurfaces(root, true);
if (old) URL.revokeObjectURL(old.url);
} catch { /* Keep the theme usable if image storage is unavailable. */ }
}
@@ -74,6 +101,7 @@ function applyBackgroundImage(root: HTMLElement, image?: string) {
const previous = backgroundUrls.get(root);
if (image && previous?.image === image) {
root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`);
applyBackgroundSurfaces(root, true);
return;
}
let url: string | undefined;
@@ -86,6 +114,7 @@ function applyBackgroundImage(root: HTMLElement, image?: string) {
}
// Large data URLs exceed Chromium's CSS variable limit. Keep only a short blob URL in CSS.
root.style.setProperty('--rs-new-tab-image', url ? `url("${url}")` : 'none');
applyBackgroundSurfaces(root, !!url);
if (image && url) backgroundUrls.set(root, { image, url });
else backgroundUrls.delete(root);
if (previous) URL.revokeObjectURL(previous.url);
@@ -103,9 +132,9 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
root.dataset.theme = mode;
root.dataset.palette = theme;
root.style.colorScheme = mode;
const palette = theme === 'sakura' ? palettes.sakura.light : palettes[theme === 'claude' ? 'claude' : 'default'][mode];
const palette = builtinPalette(theme)[mode];
keys.forEach((key, index) => root.style.setProperty(`--rs-${key}`, palette[index]));
root.style.setProperty('--rs-accent-2', theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : 'var(--rs-accent)');
root.style.setProperty('--rs-accent-2', characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : 'var(--rs-accent)'));
root.style.setProperty('--rs-accent-dim', 'color-mix(in srgb, var(--rs-accent) 80%, var(--rs-bg))');
root.style.setProperty('--rs-accent-deep', 'color-mix(in srgb, var(--rs-accent) 60%, var(--rs-bg))');
const semantic = mode === 'light' ? ['#b42323', '#8a5700', '#806600', '#287b29', '#7740a5']
@@ -113,10 +142,12 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
if (theme === 'claude') { semantic[3] = '#788c5d'; semantic[4] = '#6a9bcc'; }
if (theme === 'sakura') { semantic[3] = '#618c71'; semantic[4] = '#cb6b91'; }
['error', 'warn-hot', 'warn', 'ok', 'special'].forEach((key, index) => root.style.setProperty(`--rs-${key}`, semantic[index]));
SYNTAX_ROLES.forEach(role => root.style.removeProperty(`--rs-syntax-${role}`));
const syntax = theme === 'sakura'
? ['#cb6b91', '#98556c', '#618c71', '#69a2bd', '#607fa9', '#687788']
: ['var(--rs-special)', 'var(--rs-accent)', 'var(--rs-text)', 'var(--rs-accent-2)', 'var(--rs-accent-2)', 'var(--rs-text-dim)'];
['parameter', 'keyword', 'local', 'static', 'instance', 'global'].forEach((key, index) => root.style.setProperty(`--rs-syntax-${key}`, syntax[index]));
for (const [key, color] of Object.entries(characterSyntax(theme))) root.style.setProperty(`--rs-${key}`, color);
root.style.setProperty('--rs-danger', 'var(--rs-error)');
const custom = theme.startsWith('custom:') ? customThemes().find(item => item.id === theme.slice(7)) : undefined;
if (custom) for (const [key, color] of Object.entries(custom[mode])) root.style.setProperty(`--rs-${key}`, color);
+36
View File
@@ -0,0 +1,36 @@
import type { ThemeColors } from './customThemes.ts';
export const SYNTAX_ROLES = ['parameter', 'keyword', 'local', 'static', 'instance', 'global', 'string', 'number', 'comment', 'type', 'function'] as const;
type CharacterTheme = { mode: 'light' | 'dark'; surfaces: string[]; syntax: string[]; secondary: string };
export const CHARACTER_THEMES = {
'harvest-moon': {
mode: 'dark',
// Current Holo fan art: copper hair, brown tail, cream fur, and red eyes/apple.
// Amber carries active and selected states. Green scenery is outside this palette.
surfaces: ['#251b17', '#382820', '#40291c', '#ae744a', '#d3aa8b', '#eee3d1', '#fff4df', '#ffb52e', '#482714'],
secondary: '#ff6740',
syntax: ['#ffcc66', '#ff6740', '#eee3d1', '#ffe7b3', '#e5ae7e', '#ff8d55', '#ffc45b', '#ffffff', '#d3aa8b', '#ffe19a', '#ffb52e'],
},
'crimson-pilot': {
mode: 'dark',
surfaces: ['#210b10', '#341018', '#461620', '#d93840', '#e0b48e', '#f4ece1', '#ffffff', '#ff5b50', '#122b45'],
secondary: '#ff9b18',
syntax: ['#ffad32', '#ff5b50', '#f4ece1', '#b6dfff', '#efb278', '#83dc52', '#ffe066', '#ff8a3d', '#e0b48e', '#64c9ff', '#559fff'],
},
'silver-serpent': {
mode: 'dark',
surfaces: ['#151c1b', '#1d3029', '#223a32', '#528f74', '#bec8ce', '#e3e7eb', '#fff5d5', '#36e395', '#13533a'],
secondary: '#c5d5e2',
syntax: ['#f5d58c', '#36e395', '#e3e7eb', '#b8cbdd', '#f4c6ae', '#edc45f', '#a7e7c4', '#ffb79b', '#bec8ce', '#ffffff', '#61dfbb'],
},
} satisfies Record<string, CharacterTheme>;
export function characterTheme(theme: string): CharacterTheme | undefined {
return CHARACTER_THEMES[theme as keyof typeof CHARACTER_THEMES];
}
export function characterSyntax(theme: string): ThemeColors {
const palette = characterTheme(theme);
return palette ? Object.fromEntries(SYNTAX_ROLES.map((role, index) => [`syntax-${role}`, palette.syntax[index]])) : {};
}
+1 -1
View File
@@ -1,5 +1,5 @@
export const CUSTOM_THEMES_KEY = "runestone.custom-themes";
export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special"] as const;
export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const;
export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>;
export type CustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
+38 -3
View File
@@ -1,5 +1,20 @@
:root {
--rs-selection-text: var(--rs-text);
--rs-tooltip-padding: 6px 10px;
--rs-tooltip-bg: var(--rs-bg-active);
--rs-tooltip-text: var(--rs-text-strong);
--rs-tooltip-shadow: 0 4px 16px #0005;
--rs-tooltip-font-size: 12px;
--rs-control-radius: 5px;
--rs-image-control-bg: color-mix(in srgb, var(--rs-bg) 82%, transparent);
--rs-image-control-hover-bg: color-mix(in srgb, var(--rs-bg-active) 92%, transparent);
--rs-image-sidebar-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-image-editor-bg: color-mix(in srgb, var(--rs-bg) 90%, transparent);
--rs-code-block-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-workarea-sidebar-bg: var(--rs-bg-elevated);
--rs-workarea-editor-bg: var(--rs-bg);
--rs-workarea-surface-opacity: 100%;
--rs-workarea-plugin-bg: var(--rs-bg);
--rs-titlebar-height: 36px;
--rs-settings-row-padding: 10px;
--rs-settings-control-height: 28px;
@@ -9,12 +24,14 @@
--rs-settings-section-gap: 16px;
--rs-menu-width: 248px;
--rs-menu-padding: 5px;
--rs-menu-row-height: 30px;
--rs-menu-row-padding: 4px 10px;
--rs-menu-row-height: 24px;
--rs-menu-row-padding: 2px 10px;
--rs-menu-icon-size: 14px;
--rs-menu-icon-gap: 8px;
--rs-menu-font-size: 13px;
--rs-menu-border: transparent;
--rs-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-menu-active-bg: color-mix(in srgb, var(--rs-bg-active) 82%, transparent);
--rs-menu-shadow: 0 8px 30px #0006;
--rs-item-selection-radius: var(--rs-control-radius);
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent);
@@ -85,6 +102,24 @@
--rs-font-heading: "Poppins", Arial, sans-serif;
}
[data-palette="sakura"] {
[data-palette="sakura"], [data-palette="harvest-moon"], [data-palette="crimson-pilot"], [data-palette="silver-serpent"] {
--rs-item-selection-bg: var(--rs-selection);
}
[data-palette="harvest-moon"] {
--rs-font-ui: Candara, "Trebuchet MS", "Segoe UI", sans-serif;
--rs-font-prose: Constantia, Georgia, "Times New Roman", serif;
--rs-font-heading: var(--rs-font-prose);
}
[data-palette="crimson-pilot"] {
--rs-font-ui: Bahnschrift, "Trebuchet MS", Arial, sans-serif;
--rs-font-prose: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
--rs-font-heading: var(--rs-font-ui);
}
[data-palette="silver-serpent"] {
--rs-font-ui: Corbel, "Segoe UI", "Helvetica Neue", Arial, sans-serif;
--rs-font-prose: "Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif;
--rs-font-heading: var(--rs-font-prose);
}
+6 -6
View File
@@ -143,13 +143,13 @@
max-width: min(280px, calc(100vw - 16px));
white-space: pre-line;
text-align: left;
background: var(--rs-bg-active);
background: var(--rs-tooltip-bg);
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);
border-radius: var(--rs-control-radius);
box-shadow: var(--rs-tooltip-shadow);
color: var(--rs-tooltip-text);
padding: var(--rs-tooltip-padding);
font: var(--rs-tooltip-font-size)/1.5 var(--rs-font-ui);
pointer-events: none;
}
</style>
+6 -6
View File
@@ -156,13 +156,13 @@
position: absolute;
top: calc(100% + 9px);
right: 0;
padding: 6px 10px;
padding: var(--rs-tooltip-padding);
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);
border-radius: var(--rs-control-radius);
background: var(--rs-tooltip-bg);
box-shadow: var(--rs-tooltip-shadow);
color: var(--rs-tooltip-text);
font: var(--rs-tooltip-font-size)/1.5 var(--rs-font-ui);
white-space: nowrap;
pointer-events: none;
visibility: hidden;
+1
View File
@@ -66,6 +66,7 @@ export const actionIcons = {
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"/>',
filter: '<path d="M3 4h18l-7 8v7l-4 2v-9Z"/>',
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"/>',
+12 -4
View File
@@ -7,6 +7,14 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
const opened: { button: HTMLButtonElement; panel: HTMLElement }[] = [];
if (label.startsWith("Terminal")) root.style.width = "min(430px, calc(100vw - 16px))";
const submenus = new Map<HTMLButtonElement, HTMLElement>();
function focusRow(button?: HTMLButtonElement) {
if (!button) return;
button.focus({ preventScroll: true });
const panel = button.parentElement!;
const row = button.getBoundingClientRect(), bounds = panel.getBoundingClientRect();
if (row.top < bounds.top) panel.scrollTop -= bounds.top - row.top;
else if (row.bottom > bounds.bottom) panel.scrollTop += row.bottom - bounds.bottom;
}
function hideSubmenu(parent: HTMLElement = root) {
const keep = parent === root ? 0 : opened.findIndex(entry => entry.panel === parent) + 1;
for (const { button, panel } of opened.splice(keep)) { panel.hidden = true; button.setAttribute("aria-expanded", "false"); }
@@ -20,7 +28,7 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
if (!opened.some(entry => entry.panel === panel)) { hideSubmenu(button.parentElement!); opened.push({ button, panel }); }
panel.hidden = false; button.setAttribute("aria-expanded", "true");
positionSubmenu(button, panel);
if (focus) panel.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus({ preventScroll: true });
if (focus) focusRow(panel.querySelector<HTMLButtonElement>("button:not(:disabled)") ?? undefined);
}
function populate(panel: HTMLElement, entries: ActionMenuItem[]) {
const hasIcons = entries.some(item => !("separator" in item) && (!!item.icon || (item.checked !== undefined && !item.radio)));
@@ -64,17 +72,17 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
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();
event.preventDefault(); focusRow(buttons[event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : (index + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length]);
}
if (event.key === "ArrowRight" && submenus.has(focused)) { event.preventDefault(); reveal(focused, submenus.get(focused)!, true); }
const entry = opened.find(entry => entry.panel === panel);
if (event.key === "ArrowLeft" && entry) { event.preventDefault(); hideSubmenu(entry.button.parentElement!); entry.button.focus(); }
if (event.key === "ArrowLeft" && entry) { event.preventDefault(); hideSubmenu(entry.button.parentElement!); focusRow(entry.button); }
});
root.addEventListener("scroll", () => { for (const { button, panel } of opened) positionSubmenu(button, panel); }, true);
parent.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[role="menuitemradio"][aria-checked="true"]:not(:disabled)')
?? root.querySelector<HTMLButtonElement>(":scope > button:not(:disabled)"))?.focus();
?? root.querySelector<HTMLButtonElement>(":scope > button:not(:disabled)"))?.focus({ preventScroll: true });
return root;
}
+14 -9
View File
@@ -1,5 +1,4 @@
.rs-menu {
position: fixed;
.rs-menu, .rs-picker {
z-index: 1000;
width: var(--rs-menu-width);
max-width: calc(100vw - 16px);
@@ -8,15 +7,18 @@
padding: var(--rs-menu-padding);
border: 1px solid var(--rs-menu-border);
border-radius: var(--rs-control-radius);
background: var(--rs-bg-elevated);
background: var(--rs-menu-bg);
color: var(--rs-text);
box-shadow: var(--rs-menu-shadow);
font: var(--rs-menu-font-size)/1.4 var(--rs-font-ui);
}
.rs-menu { position: fixed; }
.rs-picker { box-sizing: border-box; }
.rs-menu.table-cell-submenu { z-index: 1001; }
.rs-menu > button {
.rs-menu > button, .rs-picker .rs-picker-row {
display: flex;
align-items: center;
gap: var(--rs-menu-icon-gap);
@@ -32,14 +34,17 @@
cursor: pointer;
}
.rs-menu > button:disabled { opacity: .4; cursor: default; }
.rs-menu > button[role="menuitemradio"][aria-checked="true"] { background: var(--rs-bg-active); }
.rs-menu > button:disabled, .rs-picker .rs-picker-row:disabled { opacity: .4; cursor: default; }
.rs-menu > button[role="menuitemradio"][aria-checked="true"] { background: var(--rs-menu-active-bg); }
.rs-menu.rs-menu-text > button > .action-icon { display: none; }
.rs-menu > button:not(:disabled):is(:hover, :focus-visible, [aria-expanded="true"]) {
background: var(--rs-bg-active);
.rs-menu > button:not(:disabled):is(:hover, :focus-visible, [aria-expanded="true"]),
.rs-picker .rs-picker-row:not(:disabled):is(:hover, :focus-visible, :focus-within, [aria-selected="true"], [aria-current="true"]) {
background: var(--rs-menu-active-bg);
outline: none;
}
.rs-menu > hr { margin: 4px 0; border: 0; border-top: 1px solid var(--rs-border); }
.rs-menu > button > .action-icon { width: var(--rs-menu-icon-size); height: var(--rs-menu-icon-size); flex: 0 0 var(--rs-menu-icon-size); }
.rs-menu > button > .action-icon, .rs-picker-icon { width: var(--rs-menu-icon-size); height: var(--rs-menu-icon-size); flex: 0 0 var(--rs-menu-icon-size); }
.rs-picker-hint { display: block; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); }
.rs-picker-icon > svg { width: 100%; height: 100%; }
.rs-menu > button > .action-label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.rs-menu > button > .action-chevron { width: 13px; height: 13px; flex: 0 0 13px; }
+49
View File
@@ -0,0 +1,49 @@
/** A single themed tooltip for DOM controls, with hover and keyboard dismissal. */
export function attachTooltip(target: HTMLElement, label: () => string) {
const tip = document.createElement('span');
tip.className = 'rs-tooltip';
tip.setAttribute('popover', 'manual');
tip.setAttribute('role', 'tooltip');
tip.id = `rs-tooltip-${crypto.randomUUID()}`;
document.body.append(tip);
let timer: ReturnType<typeof setTimeout> | undefined;
const previousDescription = target.getAttribute('aria-describedby');
function hide() {
clearTimeout(timer);
if (tip.matches(':popover-open')) tip.hidePopover();
if (previousDescription) target.setAttribute('aria-describedby', previousDescription);
else target.removeAttribute('aria-describedby');
}
function show() {
clearTimeout(timer);
timer = setTimeout(() => {
if (!target.isConnected || !label()) return;
tip.textContent = label();
tip.showPopover();
const bounds = target.getBoundingClientRect(), size = tip.getBoundingClientRect();
tip.style.left = `${Math.max(8, Math.min(bounds.left, innerWidth - size.width - 8))}px`;
tip.style.top = `${Math.max(8, bounds.bottom + size.height + 8 > innerHeight ? bounds.top - size.height - 8 : bounds.bottom + 8)}px`;
target.setAttribute('aria-describedby', [previousDescription, tip.id].filter(Boolean).join(' '));
}, 300);
}
const escape = (event: KeyboardEvent) => { if (event.key === 'Escape') hide(); };
target.addEventListener('mouseenter', show);
target.addEventListener('mouseleave', hide);
target.addEventListener('focusin', show);
target.addEventListener('focusout', hide);
target.addEventListener('pointerdown', hide);
window.addEventListener('resize', hide);
window.addEventListener('scroll', hide, true);
window.addEventListener('keydown', escape);
return () => {
hide(); tip.remove();
target.removeEventListener('mouseenter', show);
target.removeEventListener('mouseleave', hide);
target.removeEventListener('focusin', show);
target.removeEventListener('focusout', hide);
target.removeEventListener('pointerdown', hide);
window.removeEventListener('resize', hide);
window.removeEventListener('scroll', hide, true);
window.removeEventListener('keydown', escape);
};
}
+58
View File
@@ -0,0 +1,58 @@
import { paneBounds, removePane, splitPane, type SplitLayout } from "./splitLayout.ts";
export type DocumentPane = { id: string; documentId: string | null; reading: boolean };
export type DocumentPanes = { layout: SplitLayout; panes: DocumentPane[]; active: string };
export function initialDocumentPanes(): DocumentPanes {
return { layout: "document-main", panes: [{ id: "document-main", documentId: null, reading: false }], active: "document-main" };
}
export function selectPane(state: DocumentPanes, id: string): DocumentPanes {
return state.active === id || !state.panes.some(pane => pane.id === id) ? state : { ...state, active: id };
}
/** Tabs own documents. Panes keep only a reference and local viewing state. */
export function syncDocumentPanes(state: DocumentPanes, live: readonly string[], selected: string | null): DocumentPanes {
const ids = new Set(live);
let panes = state.panes.map(pane => pane.documentId && !ids.has(pane.documentId) ? { ...pane, documentId: null, reading: false } : pane);
let active = state.active;
if (selected && ids.has(selected)) {
const existing = panes.find(pane => pane.documentId === selected);
if (existing) active = existing.id;
else panes = panes.map(pane => pane.id === active ? { ...pane, documentId: selected } : pane);
}
let layout = state.layout;
for (const pane of panes) {
if (pane.documentId === null && panes.length > 1) {
const next = removePane(layout, pane.id);
if (next !== null) { layout = next; panes = panes.filter(item => item.id !== pane.id); }
}
}
if (!panes.some(pane => pane.id === active)) active = panes[0].id;
if (layout === state.layout && active === state.active && panes.length === state.panes.length && panes.every((pane, i) => pane === state.panes[i])) return state;
return { layout, panes, active };
}
export function splitDocumentPane(state: DocumentPanes, source: string, documentId: string, paneId: string): DocumentPanes {
const existing = state.panes.find(pane => pane.documentId === documentId);
if (existing) return selectPane(state, existing.id);
if (!state.panes.some(pane => pane.id === source) || state.panes.some(pane => pane.id === paneId)) return state;
return {
layout: splitPane(state.layout, source, paneId, "right"),
panes: [...state.panes, { id: paneId, documentId, reading: false }], active: paneId,
};
}
export function closeDocumentPane(state: DocumentPanes, id: string): DocumentPanes {
if (state.panes.length <= 1 || !state.panes.some(pane => pane.id === id)) return state;
const layout = removePane(state.layout, id);
if (layout === null) return state;
const bounds = paneBounds(state.layout);
const panes = state.panes.filter(pane => pane.id !== id);
const neighbor = [...panes].sort((a, b) => Math.abs(bounds[a.id].left - bounds[id].left) - Math.abs(bounds[b.id].left - bounds[id].left))[0];
return { layout, panes, active: state.active === id ? neighbor.id : state.active };
}
export function readDocumentPane(state: DocumentPanes, id: string, reading: boolean): DocumentPanes {
return { ...state, panes: state.panes.map(pane => pane.id === id ? { ...pane, reading } : pane) };
}
+4 -4
View File
@@ -54,9 +54,9 @@ export class Documents {
return true;
}
async open(entry: TreeEntry, target: "current" | "new" = "new") {
const request = ++this.selection;
const previous = target === "current" || this.active?.kind === "empty" ? this.active : undefined;
async open(entry: TreeEntry, target: "current" | "new" | "background" = "new") {
const request = target === "background" ? this.selection : ++this.selection;
const previous = target !== "background" && (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);
@@ -77,7 +77,7 @@ export class Documents {
}
try { await pending; } finally { this.opening.delete(entry.rel_path); }
}
if (!this.disposed && request === this.selection) {
if (target !== "background" && !this.disposed && request === this.selection) {
// Replace only after a successful read, and never discard edits or disk conflicts.
if (!alreadyOpen && previous && !previous.pinned && previous.contents === previous.saved
&& previous.diskContents === undefined && !previous.diskError) {
+4
View File
@@ -175,6 +175,10 @@ function documentParts(contents: string) {
return match ? { body: contents.slice(match[0].length), properties: match[1] } : { body: contents, properties: "" };
}
export function documentBodyStart(contents: string): number {
return contents.length - documentParts(contents).body.length;
}
export function markdownImages(contents: string): string[] {
const paths = new Set<string>();
function visit(tokens: Token[]) {