Update the browser, editor, settings, and installer

This commit is contained in:
Knotty Wyvern
2026-10-12 14:46:21 -07:00
parent 909894b9c8
commit f6eaa52949
163 changed files with 146260 additions and 534 deletions
+84 -21
View File
@@ -1,10 +1,13 @@
<script lang="ts">
import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import { state as browserState, pageErrors, request, frames } from './client';
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';
import { WheelQueue } from './inputQueue';
import { TabSession, type TabStatus } from './tabSession';
import { AutoScroll } from './autoScroll';
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string) => Promise<void> } = $props();
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: 'Opening browser…' });
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
const tabId = $derived(status.tabId);
@@ -12,14 +15,19 @@
const current = $derived($browserState?.tabs.find(tab => tab.id === tabId));
let address = $state(''); let editing = $state(false);
let image = $state(''); let surface: HTMLDivElement; let addressField: HTMLInputElement;
let width = 1000, height = 700;
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));
const wheels = new WheelQueue(input => send('input', { input }));
let displayedFrame: BrowserFrame | undefined;
let closeMenu: (() => void) | undefined;
let opening = $state(false), openingError = $state(''), mounted = $state(false);
let findOpen = $state(false), findText = $state('');
let findField: HTMLInputElement | undefined = $state();
let findTimer: ReturnType<typeof setTimeout> | undefined;
const autoScroll = new AutoScroll();
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
let scrollFrame = 0, moveFrame = 0, wheelPending = false, movePending = false;
let scrollFrame = 0, moveFrame = 0, movePending = false;
let pendingMove: Record<string, unknown> | undefined;
let suppressedRelease = -1;
const result = $derived(current?.find?.text === findText ? current.find : null);
@@ -50,10 +58,53 @@
image = '';
if (!id) return;
frames.set(id, frame => {
if (frame.width > 0 && frame.height > 0 && frame.png.startsWith('iVBORw0KGgo')) image = `data:image/png;base64,${frame.png}`;
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}`;
}
});
return () => { frames.delete(id); };
pageEvents.set(id, event => {
if (event.event === 'context-menu') showPageMenu(event);
else if (event.event === 'open-link' && event.url) void newTab(current?.profileId || 'user', event.url);
});
return () => { acknowledgeFrame(); frames.delete(id); pageEvents.delete(id); closeMenu?.(); };
});
function acknowledgeFrame() {
const frame = displayedFrame; displayedFrame = undefined;
if (frame) void request('frameAck', { tabId: frame.tabId, frameId: frame.frameId }).catch(() => {});
}
function showPageMenu(context: PageMenu) {
stopScroll(); closeMenu?.();
const action = (name: string) => () => { void send('contextAction', { token: context.token, action: name }); };
const edit = (name: string) => () => { void orderedInput('edit', { action: name }); };
const items: ActionMenuItem[] = [];
if (context.linkURL) items.push(
{ label: 'Open link in new tab', icon: 'file-plus', run: () => void newTab(current?.profileId || 'user', context.linkURL) },
{ label: 'Open link in default browser', icon: 'external', run: action('openExternal') },
{ label: 'Copy link address', icon: 'copy', run: action('copyLink') },
{ label: 'Save link as…', icon: 'save', run: action('saveLink') }, { separator: true });
if (context.hasImageContents) items.push(
{ label: 'Save image as…', icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
{ label: 'Copy image', icon: 'copy', run: action('copyImage') },
{ label: 'Copy image address', icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push(
{ label: 'Undo', icon: 'undo', shortcut: 'Ctrl+Z', disabled: !context.editFlags.canUndo, run: edit('undo') },
{ label: 'Redo', icon: 'redo', shortcut: 'Ctrl+Shift+Z', disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true },
{ label: 'Cut', icon: 'cut', shortcut: 'Ctrl+X', disabled: !context.editFlags.canCut, run: edit('cut') });
if (context.isEditable || context.selectionText) items.push({ label: 'Copy', icon: 'copy', shortcut: 'Ctrl+C', disabled: !context.editFlags.canCopy, run: edit('copy') });
if (context.isEditable) items.push(
{ label: 'Paste', icon: 'paste', shortcut: 'Ctrl+V', disabled: !context.editFlags.canPaste, run: edit('paste') },
{ label: 'Paste as plain text', icon: 'paste-text', shortcut: 'Ctrl+Shift+V', disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') },
{ label: 'Select all', icon: 'task', shortcut: 'Ctrl+A', run: edit('selectAll') }, { separator: true });
items.push({ label: 'Back', icon: 'arrow-left', disabled: !current?.canBack, run: () => void send('back') },
{ label: 'Forward', icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') },
{ label: 'Reload', icon: 'refresh', run: () => void send('reload') },
{ label: 'Find in page', icon: 'search', shortcut: 'Ctrl+F', run: () => void find() });
const rect = surface.getBoundingClientRect();
const menu = showActionMenu({ x: rect.left + context.x * rect.width / width, y: rect.top + context.y * rect.height / height,
items, label: 'Browser page actions' });
closeMenu = menu.close;
}
$effect(() => { if (mounted && ready && tabId) untrack(syncSize); });
async function send(command: string, args = {}) {
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
@@ -75,26 +126,25 @@
timer = setTimeout(syncSize, 100);
});
resize.observe(surface);
return () => { mounted = false; stopScroll(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
return () => { mounted = false; stopScroll(); wheels.close(); closeMenu?.(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
});
function syncSize() {
const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { stopScroll(); void send('visible', { visible: false }); return; }
width = Math.max(100, Math.min(2560, Math.round(rect.width)));
height = Math.max(100, Math.min(1600, Math.round(rect.height)));
void send('resize', { width, height }); void send('visible', { visible: true });
width = Math.max(100, Math.min(5120, Math.round(rect.width)));
height = Math.max(100, Math.min(3200, Math.round(rect.height)));
void send('resize', { width, height, scale: Math.max(1, Math.min(3, devicePixelRatio || 1)) }); void send('visible', { visible: true });
}
const modifiers = (event: MouseEvent | KeyboardEvent) => [event.shiftKey && 'shift', event.ctrlKey && 'control', event.altKey && 'alt', event.metaKey && 'meta'].filter(Boolean);
function stopScroll() { autoScroll.stop(); scrollAnchor = null; cancelAnimationFrame(scrollFrame); }
function stopScroll() { autoScroll.stop(); wheels.clear(); scrollAnchor = null; cancelAnimationFrame(scrollFrame); }
function scrollStep(time: number) {
if (!autoScroll.anchor || !ready) { stopScroll(); return; }
const delta = autoScroll.delta(time);
if (delta && !wheelPending && (delta.x || delta.y)) {
wheelPending = true;
if (delta && (delta.x || delta.y)) {
const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { wheelPending = false; stopScroll(); return; }
if (!rect.width || !rect.height) { stopScroll(); return; }
const anchor = autoScroll.anchor;
void send('input', { input: { type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x * width / rect.width)), y: Math.min(height - 1, Math.round(anchor.y * height / rect.height)), deltaX: -delta.x, deltaY: -delta.y } }).finally(() => wheelPending = false);
wheels.push({ type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x * width / rect.width)), y: Math.min(height - 1, Math.round(anchor.y * height / rect.height)), deltaX: -delta.x, deltaY: -delta.y });
}
scrollFrame = requestAnimationFrame(scrollStep);
}
@@ -108,7 +158,7 @@
});
}
function pointer(event: MouseEvent | WheelEvent, type: string) {
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') surface.focus();
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
const rect = surface.getBoundingClientRect();
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
@@ -124,22 +174,29 @@
}
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x * width / rect.width))), y: Math.max(0, Math.min(height - 1, Math.round(point.y * height / rect.height))),
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
...('deltaY' in event ? { deltaY: -event.deltaY, deltaX: -event.deltaX } : {}) };
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
if (type === 'mouseMove') {
pendingMove = input;
if (!moveFrame && !movePending) moveFrame = requestAnimationFrame(flushMove);
} else { pendingMove = undefined; void send('input', { input }); }
} else { pendingMove = undefined; void orderedInput('input', { input }); }
}
function key(event: KeyboardEvent, type: string) {
if (event.isComposing || composing || event.key === 'Process' || event.key === 'Dead') return;
if (autoScroll.anchor) { stopScroll(); if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); return; } }
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'f') { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') void find(); return; }
if (event.key === 'Escape' && findOpen) { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') closeFind(); return; }
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'l') { event.preventDefault(); addressField.focus(); addressField.select(); return; }
if ((event.ctrlKey || event.metaKey) && [',', 'w', 't'].includes(event.key.toLowerCase())) return;
event.preventDefault(); event.stopPropagation();
const editActions: Record<string, string> = { a: 'selectAll', c: 'copy', x: 'cut', v: event.shiftKey ? 'pasteAndMatchStyle' : 'paste', z: event.shiftKey ? 'redo' : 'undo', y: 'redo' };
if ((event.ctrlKey || event.metaKey) && editActions[event.key.toLowerCase()]) {
if (type === 'keyDown') void orderedInput('edit', { action: editActions[event.key.toLowerCase()] });
return;
}
const names: Record<string, string> = { ArrowLeft: 'LEFT', ArrowRight: 'RIGHT', ArrowUp: 'UP', ArrowDown: 'DOWN', Enter: 'ENTER', Backspace: 'BACKSPACE', Escape: 'ESCAPE', Delete: 'DELETE', Tab: 'TAB', Home: 'HOME', End: 'END', PageUp: 'PAGEUP', PageDown: 'PAGEDOWN', ' ': 'SPACE' };
void send('input', { input: { type, keyCode: names[event.key] || event.key, modifiers: modifiers(event) } });
if (type === 'keyDown' && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void send('input', { input: { type: 'char', keyCode: event.key } });
void orderedInput('input', { input: { type, keyCode: names[event.key] || event.key, modifiers: modifiers(event) } });
if (type === 'keyDown' && [...event.key].length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void orderedInput('insertText', { text: event.key });
}
</script>
<svelte:window onblur={stopScroll} />
@@ -184,11 +241,17 @@
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
{#if image && ready}<img src={image} alt="Web page rendered by the browser" draggable="false">{/if}
<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 scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
</div>
</div>
<style>
.text-input{position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;padding:0;border:0;}
.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}
+22 -7
View File
@@ -1,11 +1,25 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import WebData from './WebData.svelte';
import { state as browserState, request } from './client';
let selected = $state('user'), name = $state(''), message = $state('');
let search = $state('duckduckgo'), adblock = $state(true), internalLinks = $state(true), rules = $state('');
let homepage = $state(''), filterLists = $state(''), ready = $state(false), busy = $state(false);
const engines = [{ id: 'duckduckgo', name: 'DuckDuckGo' }, { id: 'google', name: 'Google' }, { id: 'bing', name: 'Bing' }];
let closePicker = () => {};
onDestroy(() => closePicker());
function picker(event: MouseEvent, profile = false) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: profile ? 'Profile' : 'Search engine',
parent: anchor.closest('dialog') ?? undefined,
items: (profile ? $browserState?.profiles || [] : engines).map(choice => ({ label: choice.name,
radio: true, checked: choice.id === (profile ? selected : search),
run: () => { if (profile) selected = choice.id; else search = choice.id; } })) }).close;
}
onMount(() => { void request('state').then(value => {
selected = value.profiles[0].id; search = value.settings.search; adblock = value.settings.adblock;
internalLinks = value.settings.linkDestination === 'internal'; rules = value.settings.personalRules;
@@ -35,17 +49,17 @@
<div class="card">
<label class="row"><span>Open web links in RuneStone<small>Turn this off to use your system browser.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Open web links in RuneStone" bind:checked={internalLinks}></label>
<label class="row"><span>Homepage<small>The page to open in each new browser tab. Leave blank for an empty page.</small></span><input class="address" type="url" aria-label="Homepage" placeholder="https://example.com" maxlength="8192" bind:value={homepage}></label>
<label class="row"><span>Search engine</span><select bind:value={search}><option value="duckduckgo">DuckDuckGo</option><option value="google">Google</option><option value="bing">Bing</option></select></label>
<div class="row"><span>Search engine</span><button type="button" class="picker" aria-label="Search engine" aria-haspopup="menu" onclick={event => picker(event)}>{engines.find(engine => engine.id === search)?.name ?? 'DuckDuckGo'}<Icon icon="chevron-down" /></button></div>
<label class="row"><span>Block ads and trackers<small>Apply the filter lists and personal rules to all browser tabs.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Block ads and trackers" bind:checked={adblock}></label>
<label class="row list-row"><span>Ad blocking lists<small>One HTTPS filter list URL per line, up to eight lists. New lists download when you save.</small></span><textarea aria-label="Ad blocking lists" rows="4" maxlength="66000" placeholder="https://easylist.to/easylist/easylist.txt" bind:value={filterLists}></textarea></label>
</div>
<label class="rules">Personal filter rules<small>Optional rules to add to the selected lists.</small><textarea rows="4" maxlength="100000" bind:value={rules}></textarea></label>
<label class="rules">Personal filter rules<small>Use one rule per line. Block a domain with ||ads.example.com^, allow it with @@||ads.example.com^, or hide an element with example.com##.advertisement. Save to apply the rules.</small><textarea rows="4" maxlength="100000" placeholder={'! Block an advertising domain\n||ads.example.com^\n! Hide an element on one site\nexample.com##.advertisement'} bind:value={rules}></textarea></label>
<button type="submit"><Icon icon="save" />{busy ? 'Saving…' : 'Save browser settings'}</button>
</fieldset>
</form>
<h3>Profiles</h3><p>New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.</p>
<div class="card profiles">
<label>Profile<select aria-label="Profile" bind:value={selected}>{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}</select></label>
<div class="profile-choice"><span>Profile</span><button type="button" class="picker" aria-label="Profile" aria-haspopup="menu" disabled={!ready} onclick={event => picker(event, true)}>{$browserState?.profiles.find(profile => profile.id === selected)?.name ?? 'Profile'}<Icon icon="chevron-down" /></button></div>
<label>New profile name<input bind:value={name} maxlength="60" placeholder="Profile name"></label>
<div class="actions"><button onclick={() => void create(false)}><Icon icon="plus" />New blank profile</button><button onclick={() => void create(true)}><Icon icon="copy" />Duplicate profile</button></div>
<p class="note">Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.</p>
@@ -59,9 +73,10 @@
.settings{color:var(--rs-text);font-family:var(--rs-font-ui)}h2{margin:0;font-size:var(--rs-settings-heading-size);font-weight:500;color:var(--rs-text-strong)}h3{margin:var(--rs-settings-section-gap) 0 var(--rs-settings-gap);font-size:14px;font-weight:500}
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.6}.card{padding:0 var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.row{display:flex;justify-content:space-between;align-items:center;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}.row+.row{border-top:1px solid var(--rs-border)}
input,select,textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px}
button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
.rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
input,textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px}
button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
.picker{justify-content:space-between;min-width:140px;max-width:100%;overflow-wrap:anywhere;text-align:left}
.rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label,.profile-choice{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
.actions{display:flex;flex-wrap:wrap;gap:8px}.note{margin-bottom:0}
fieldset{border:0;margin:0;padding:0;min-width:0}small{display:block;color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5;margin-top:5px}
.row>span{flex:1}.address,.list-row textarea{width:260px;max-width:48%;box-sizing:border-box}.list-row{align-items:flex-start}textarea{resize:vertical}
+1 -1
View File
@@ -17,7 +17,7 @@ export class AutoScroll {
const elapsed = this.previous ? Math.min(50, time - this.previous) : 0;
this.previous = time;
if (!this.anchor) return null;
const speed = (distance: number) => Math.sign(distance) * Math.min(1800, Math.max(0, Math.abs(distance) - 12) * 8);
const speed = (distance: number) => Math.sign(distance) * Math.min(3000, Math.max(0, Math.abs(distance) - 12) * 18);
return { x: speed(this.point.x - this.anchor.x) * elapsed / 1000, y: speed(this.point.y - this.anchor.y) * elapsed / 1000 };
}
}
+9 -4
View File
@@ -13,7 +13,10 @@ export type Snapshot = {
};
export const state = writable<Snapshot | null>(null);
export const pageErrors = writable<Record<string, string>>({});
export const frames = new Map<string, (frame: { png: string; width: number; height: number }) => void>();
export type BrowserFrame = { tabId: string; frameId: number; mime: 'image/png' | 'image/jpeg'; data: string; width: number; height: number };
export type PageMenu = { event: string; tabId: string; token: string; x: number; y: number; linkURL: string; srcURL: string; hasImageContents: boolean; isEditable: boolean; selectionText: string; editFlags: Record<string, boolean>; url?: string };
export const frames = new Map<string, (frame: BrowserFrame) => void>();
export const pageEvents = new Map<string, (event: PageMenu) => void>();
let snapshots = new SnapshotOrder();
let session: string | undefined;
function isSnapshot(value: unknown): value is Snapshot {
@@ -29,15 +32,17 @@ export async function request<T = Snapshot>(command: string, args: Record<string
export async function connect(signal: AbortSignal) {
session = await invoke<string>('browser_connect');
const window = getCurrentWebviewWindow();
const offState = await window.listen<{ event: string; state?: Snapshot; message?: string; tabId?: string }>('browser-state', ({ payload }) => {
const offState = await window.listen<PageMenu & { state?: Snapshot; message?: string }>('browser-state', ({ payload }) => {
if (signal.aborted) return;
if (isSnapshot(payload.state) && snapshots.accept(payload.state)) state.set(payload.state);
if (payload.message && payload.tabId) pageErrors.update(errors => ({ ...errors, [payload.tabId!]: payload.message! }));
if (payload.tabId) pageEvents.get(payload.tabId)?.(payload);
});
const offFrame = await window.listen<{ tabId: string; png: string; width: number; height: number }>('browser-frame', ({ payload }) => {
const offFrame = await window.listen<BrowserFrame>('browser-frame', ({ payload }) => {
if (!signal.aborted) frames.get(payload.tabId)?.(payload);
if (!frames.has(payload.tabId)) void request('frameAck', { tabId: payload.tabId, frameId: payload.frameId }).catch(() => {});
});
const stop = async () => { offState(); offFrame(); frames.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
const stop = async () => { offState(); offFrame(); frames.clear(); pageEvents.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
if (signal.aborted) await stop();
return stop;
}
+1 -1
View File
@@ -84,7 +84,7 @@ export async function activate(api: PluginApi) {
if (value.profileId) saved.profileId = value.profileId;
if (value.url) saved.url = value.url;
},
newTab: (profile: string) => open(profile),
newTab: (profile: string, url?: string) => open(profile, url),
} });
tabId = undefined;
saved.control = instance;
+32
View File
@@ -0,0 +1,32 @@
type Wheel = { type: 'mouseWheel'; x: number; y: number; deltaX: number; deltaY: number; modifiers?: unknown[] };
/** Keep one pending wheel event while the transport processes the current event. */
export class WheelQueue {
private pending?: Wheel;
private running = false;
private closed = false;
private send: (input: Wheel) => Promise<unknown>;
constructor(send: (input: Wheel) => Promise<unknown>) { this.send = send; }
push(input: Wheel) {
if (this.closed) return;
const previous = this.pending;
// A direction change replaces stale motion instead of replaying it later.
const add = (old: number, next: number) => Math.sign(old) === Math.sign(next) || !next ? old + next : next;
this.pending = { ...input,
deltaX: Math.max(-2000, Math.min(2000, previous ? add(previous.deltaX, input.deltaX) : input.deltaX)),
deltaY: Math.max(-2000, Math.min(2000, previous ? add(previous.deltaY, input.deltaY) : input.deltaY)) };
void this.flush();
}
clear() { this.pending = undefined; }
close() { this.closed = true; this.clear(); }
private async flush() {
if (this.running) return;
this.running = true;
try {
while (this.pending && !this.closed) {
const input = this.pending; this.pending = undefined;
await this.send(input);
}
} finally { this.running = false; }
}
}
+2 -1
View File
@@ -3,6 +3,7 @@
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
import { editorSession } from "./sessions";
import { registerSelection } from "./selection";
import { monacoChrome } from "./monacoChrome";
@@ -56,7 +57,7 @@
if (!range) return true;
const [marker] = model.deltaDecorations([], [{ range, options: { stickiness: 1 } }]);
try {
const snippets: string[] = linkedPath ? [workspaceImageLink(buffer.relPath, linkedPath)] : [];
const snippets: string[] = linkedPath ? [workspaceFileLink(buffer.relPath, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return true;
const snippet = await onInsertImage?.(file);
+9 -3
View File
@@ -1,6 +1,7 @@
<script lang="ts">
import { pluginHost } from "$lib/plugins/registry";
import { useSpellingMenu } from "./spellingMenu";
import { spellingWord } from "./spellingWord";
import { untrack } from "svelte";
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
import { EditorView, drawSelection, keymap } from "@codemirror/view";
@@ -17,6 +18,7 @@
import { markdownImages } 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 { registerSelection } from "./selection";
import { liveMarkdown, refreshImages } from "./liveMarkdown";
@@ -28,6 +30,8 @@
import { tableNavigation } from "./tableNavigation";
import { completionExtension } from "$lib/completion/codemirror";
import { documentLinkAt } from "./documentLinks";
import { headingFolding } from "./headingFolding";
import "./headingFolding.css";
type Props = {
buffer: OpenBuffer;
@@ -125,7 +129,7 @@
const id = Symbol(), path = buffer.relPath;
view.dispatch({ effects: trackImageDrop.of({ id, from: range.from, to: range.to }) });
try {
const snippets: string[] = linkedPath ? [workspaceImageLink(path, linkedPath)] : [];
const snippets: string[] = linkedPath ? [workspaceFileLink(path, linkedPath)] : [];
for (const file of files) {
if (editor !== view) return;
const snippet = await onInsertImage?.(file);
@@ -168,6 +172,7 @@
const extensions = [
completionExtension(current.id),
markdown({ base: markdownLanguage, extensions: [noteFormats] }),
headingFolding,
writerHistory.of({
undo: () => {
clearTimeout(historyTimer);
@@ -237,7 +242,7 @@
EditorView.domEventHandlers({
contextmenu(event, view) {
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
if (useSpellingMenu(event, view.state.selection.main.empty)) { menu?.close(false); return false; }
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 selection = view.state.selection.main;
@@ -394,8 +399,9 @@
.live-writer :global(.cm-editor.cm-focused) { outline: none; }
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose); scrollbar-gutter: stable; }
.live-writer :global(.cm-content) { max-width: 868px; width: 100%; margin: 0 auto; padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 35vh; caret-color: var(--rs-text-strong); }
.live-writer :global(.cm-line) { padding: 0; position: relative; }
.live-writer :global(.cm-line) { padding-inline: 0; position: relative; }
.live-writer :global(.cm-line:hover)::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: none; }
.live-writer :global(.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); }
+31
View File
@@ -0,0 +1,31 @@
import { mount, unmount } from "svelte";
import QuickOpen from "../layout/QuickOpen.svelte";
/** Use the workspace file picker without opening or switching the active note. */
export function pickLinkDocument(signal: AbortSignal): Promise<string | null> {
if (signal.aborted) return Promise.resolve(null);
return new Promise(resolve => {
const target = document.createElement("div");
document.body.append(target);
let component: ReturnType<typeof mount> | undefined;
let finished = false;
const finish = (path: string | null) => {
if (finished) return;
finished = true;
signal.removeEventListener("abort", cancel);
if (component) void unmount(component).finally(() => target.remove());
else target.remove();
resolve(path);
};
const cancel = () => finish(null);
try {
component = mount(QuickOpen, { target, props: {
onOpen: entry => finish(entry.rel_path),
onClose: cancel,
purpose: "Add workspace link",
actionLabel: "insert link",
} });
} catch (error) { target.remove(); throw error; }
signal.addEventListener("abort", cancel, { once: true });
});
}
+74
View File
@@ -0,0 +1,74 @@
import type MarkdownIt from "markdown-it";
import type { Token } from "markdown-it";
type MarkdownParser = InstanceType<typeof MarkdownIt>;
type Footnote = { label: string; tokens: Token[]; number: number; references: number };
export type FootnoteEnvironment = { noteFootnotes?: Map<string, Footnote>; urls?: Map<string, string> };
export function footnotes(markdown: MarkdownParser) {
markdown.block.ruler.before("reference", "note_footnote_definition", (state, start, end, silent) => {
if (state.sCount[start] - state.blkIndent >= 4) return false;
const line = state.src.slice(state.bMarks[start] + state.tShift[start], state.eMarks[start]);
const match = /^\[\^([^\]\s]+)\]:[ \t]*(.*)$/.exec(line);
if (!match) return false;
if (silent) return true;
let next = start + 1;
let body = match[2];
while (next < end) {
const text = state.src.slice(state.bMarks[next], state.eMarks[next]);
if (/^(?: {4}|\t)/.test(text)) { body += "\n" + text.replace(/^(?: {4}|\t)/, ""); next++; }
else if (!text.trim() && next + 1 < end && /^(?: {4}|\t)/.test(state.src.slice(state.bMarks[next + 1], state.eMarks[next + 1]))) { body += "\n"; next++; }
else break;
}
const env = state.env as FootnoteEnvironment;
const definitions = env.noteFootnotes ??= new Map();
const tokens: Token[] = [];
// Definitions are blocks. Their inline content is parsed after all labels exist.
markdown.block.parse(body, markdown, state.env, tokens);
if (!definitions.has(match[1])) definitions.set(match[1], { label: match[1], tokens, number: 0, references: 0 });
const token = state.push("note_footnote_definition", "", 0);
token.map = [start, next];
state.line = next;
return true;
}, { alt: ["paragraph", "reference"] });
markdown.inline.ruler.before("image", "note_footnote_reference", (state, silent) => {
if (state.linkLevel > 0) return false;
const match = /^\[\^([^\]\s]+)\]/.exec(state.src.slice(state.pos));
const definitions = (state.env as FootnoteEnvironment).noteFootnotes;
const note = match && definitions?.get(match[1]);
if (!match || !note) return false;
if (!silent) {
if (!note.number) note.number = Math.max(0, ...[...definitions!.values()].map(value => value.number)) + 1;
const token = state.push("note_footnote_reference", "", 0);
token.content = match[1];
token.meta = { number: note.number, reference: ++note.references };
}
state.pos += match[0].length;
return true;
});
markdown.core.ruler.after("inline", "note_footnote_content", state => {
for (const note of (state.env as FootnoteEnvironment).noteFootnotes?.values() ?? []) {
for (const token of note.tokens) {
if (token.type === "inline") {
token.children = [];
markdown.inline.parse(token.content, markdown, state.env, token.children);
}
}
}
});
markdown.renderer.rules.note_footnote_definition = () => "";
markdown.renderer.rules.note_footnote_reference = (tokens, index) => {
const { number, reference } = tokens[index].meta as { number: number; reference: number };
return `<sup class="md-footnote-ref"><a href="#rs-fn-${number}" id="rs-fnref-${number}-${reference}" data-footnote-link aria-label="Footnote ${number}">${number}</a></sup>`;
};
}
export function renderFootnotes(markdown: MarkdownParser, env: FootnoteEnvironment): string {
const notes = [...env.noteFootnotes?.values() ?? []].filter(note => note.number).sort((a, b) => a.number - b.number);
if (!notes.length) return "";
return '<section class="md-footnotes" aria-label="Footnotes"><ol>' + notes.map(note => {
const backlinks = Array.from({ length: note.references }, (_, index) => `<a href="#rs-fnref-${note.number}-${index + 1}" class="md-footnote-back" data-footnote-link aria-label="Back to reference ${note.number}${index ? `, occurrence ${index + 1}` : ""}" title="Back to reference">↩</a>`).join(" ");
return `<li id="rs-fn-${note.number}" tabindex="-1">${markdown.renderer.render(note.tokens, markdown.options, env)} ${backlinks}</li>`;
}).join("") + "</ol></section>";
}
+21
View File
@@ -0,0 +1,21 @@
.rs-foldable-heading { position: relative; }
.reading .rs-foldable-heading { padding-inline-start: 4px; }
.reading .rs-heading-toggle { inset-inline-start: -24px; }
.live-writer .rs-heading-toggle { top: .7em; }
.rs-heading-toggle { position: absolute; inset-inline-start: -30px; top: 0; width: 28px; height: 28px; padding: 6px; border: 0; border-radius: var(--rs-control-radius); color: var(--rs-text-dim); background: transparent; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; vertical-align: middle; }
.rs-heading-toggle:hover, .rs-heading-toggle:focus-visible { color: var(--rs-text); background: var(--rs-bg-active); }
.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; }
.reading .md-footnote-ref, .live-writer .writer-footnote-ref { font-size: .75em; vertical-align: super; line-height: 0; }
.live-writer .writer-footnote-definition { color: var(--rs-text-dim); font-size: .85em; }
.reading .md-footnotes { margin-top: 2em; padding-top: 1em; border-top: 1px solid var(--rs-border); font-size: .9em; }
.reading .md-footnotes li { padding-inline-start: .3em; }
.reading .md-footnotes li > p:last-of-type { display: inline; }
.reading .md-footnote-back { margin-inline-start: .4em; }
.reading .md-footnote-ref a:focus-visible, .reading .md-footnote-back:focus-visible { outline: 1px solid var(--rs-accent); outline-offset: 3px; border-radius: var(--rs-control-radius); }
+143
View File
@@ -0,0 +1,143 @@
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";
export type HeadingRange = { start: number; from: number; to: number; level: number; label: string };
export function headingRanges(state: EditorState): HeadingRange[] {
const headings: HeadingRange[] = [];
syntaxTree(state).iterate({ enter(node) {
if (/^(?:FencedCode|CodeBlock|Blockquote|ListItem)$/.test(node.name)) return false;
const match = /^(?:ATX|Setext)Heading([1-6])$/.exec(node.name);
if (!match) return;
const line = state.doc.lineAt(node.from);
headings.push({ start: line.from, from: node.to, to: state.doc.length, level: Number(match[1]), label: line.text.replace(/^\s*#+\s*/, "").replace(/\s+#+\s*$/, "") });
return false;
} });
headings.forEach((heading, index) => {
const next = headings.slice(index + 1).find(other => other.level <= heading.level);
heading.to = next ? Math.max(heading.from, next.start - 1) : state.doc.length;
});
return headings.filter(heading => state.sliceDoc(heading.from, heading.to).trim().length > 0);
}
export function headingButton(label: string, collapsed: boolean): HTMLButtonElement {
const button = document.createElement("button");
button.type = "button";
button.className = "rs-heading-toggle";
button.setAttribute("aria-expanded", String(!collapsed));
const title = `${collapsed ? "Expand" : "Collapse"} ${label || "heading"}`;
button.setAttribute("aria-label", title);
button.title = title;
const icon = actionIcon("chevron");
const tooltip = document.createElement("span");
tooltip.className = "rs-heading-tooltip";
tooltip.textContent = title;
button.append(icon, tooltip);
return button;
}
class HeadingToggle extends WidgetType {
constructor(readonly heading: HeadingRange, readonly collapsed: boolean) { super(); }
eq(other: HeadingToggle) { return this.heading.from === other.heading.from && this.heading.to === other.heading.to && this.heading.label === other.heading.label && this.collapsed === other.collapsed; }
toDOM(view: EditorView) {
const button = headingButton(this.heading.label, this.collapsed);
button.dataset.headingStart = String(this.heading.start);
button.onmousedown = event => event.preventDefault();
button.onclick = event => {
event.preventDefault(); event.stopPropagation();
const restoreFocus = document.activeElement === button;
const { from, to } = this.heading;
const selection = !this.collapsed && view.state.selection.ranges.some(range => range.to > from && range.from <= to) ? { anchor: from } : undefined;
view.dispatch({ effects: (this.collapsed ? unfoldEffect : foldEffect).of({ from, to }), selection });
if (restoreFocus) view.dom.querySelector<HTMLButtonElement>(`[data-heading-start="${this.heading.start}"]`)?.focus({ preventScroll: true });
};
return button;
}
ignoreEvent() { return true; }
}
export const headingFolding = [
codeFolding({ placeholderText: "…" }),
keymap.of(foldKeymap),
foldService.of((state, start) => {
const heading = headingRanges(state).find(heading => heading.start === start);
return heading ? { from: heading.from, to: heading.to } : null;
}),
StateField.define({
create: decorations,
update(value, transaction) {
return transaction.docChanged || transaction.effects.some(effect => effect.is(foldEffect) || effect.is(unfoldEffect)) || syntaxTree(transaction.state) !== syntaxTree(transaction.startState)
? decorations(transaction.state) : value;
},
provide: field => EditorView.decorations.from(field),
}),
];
function decorations(state: EditorState) {
const ranges: Range<Decoration>[] = [];
const folds = foldedRanges(state);
for (const heading of headingRanges(state)) {
let collapsed = false, hidden = false;
folds.between(0, state.doc.length, (from, to) => {
if (from === heading.from) collapsed = true;
if (from < heading.start && to >= heading.start) hidden = true;
});
if (!hidden) ranges.push(Decoration.widget({ widget: new HeadingToggle(heading, collapsed), side: -1 }).range(heading.start));
}
return Decoration.set(ranges, true);
}
export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>) {
const elements = [...root.children].filter(element => !element.classList.contains("document-title")) as HTMLElement[];
const headings = elements.flatMap((element, index) => {
const heading = /^H[1-6]$/.test(element.tagName) ? element : element.querySelector<HTMLElement>(":scope > h1, :scope > h2, :scope > h3, :scope > h4, :scope > h5, :scope > h6");
return heading ? [{ element, heading, index, level: Number(heading.tagName.slice(1)), label: heading.textContent || "heading", key: `${index}:${heading.textContent}` }] : [];
});
function apply() {
elements.forEach(element => { element.hidden = false; });
headings.forEach(item => {
const button = item.heading.querySelector<HTMLButtonElement>(".rs-heading-toggle");
if (button) {
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;
const next = headings.find(other => other.index > item.index && other.level <= item.level);
for (let index = item.index + 1; index < (next?.index ?? elements.length); index++) elements[index].hidden = true;
});
}
for (const item of headings) {
const next = headings.find(other => other.index > item.index && other.level <= item.level);
if ((next?.index ?? elements.length) <= item.index + 1) continue;
const button = headingButton(item.label, collapsed.has(item.key));
button.onclick = event => {
event.stopPropagation();
if (collapsed.has(item.key)) collapsed.delete(item.key); else collapsed.add(item.key);
apply();
};
item.heading.classList.add("rs-foldable-heading");
item.heading.prepend(button);
}
apply();
return {
reveal(target: HTMLElement) {
const index = elements.findIndex(element => element === target || element.contains(target));
if (index < 0) return;
for (const item of headings) {
const next = headings.find(other => other.index > item.index && other.level <= item.level);
if (item.index < index && (next?.index ?? elements.length) > index) collapsed.delete(item.key);
}
apply();
},
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"); });
},
};
}
+15
View File
@@ -0,0 +1,15 @@
import { replacement, type TextSelection } from "./markdownCommands.ts";
export function externalLinkText(source: string, selection: TextSelection) {
const label = source.slice(selection.from, selection.to).replace(/[\\[\]]/g, "\\$&").replace(/\r?\n/g, " ");
// Select the empty URL when a label exists. Otherwise start in the label.
const cursor = label ? label.length + 3 : 1;
return replacement(selection, `[${label}]()`, cursor, cursor);
}
export function workspaceLinkText(source: string, selection: TextSelection, path: string) {
const label = source.slice(selection.from, selection.to).replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim();
// Root paths avoid a same-name note in the current folder. Encode syntax characters.
const target = "/" + path.replaceAll("\\", "/").replace(/^\/+/, "").split("/").map(encodeURIComponent).join("/");
return replacement(selection, `[[${target}${label ? "|" + label : ""}]]`);
}
+15 -5
View File
@@ -1,6 +1,6 @@
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree } from "@codemirror/language";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
import { tableControls, tableEditors } from "./tableControls";
@@ -139,10 +139,12 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const active = state.selection.ranges.map(range => ({ from: state.doc.lineAt(range.from).from, to: state.doc.lineAt(range.to).to }));
const selected = (from: number, to: number) => active.some(range => range.from <= to && range.to >= from);
const hiddenBlocks: { from: number; to: number }[] = [];
foldedRanges(state).between(0, state.doc.length, (from, to) => { hiddenBlocks.push({ from, to }); });
const source = state.doc.toString();
const editing = state.field(imageSource);
const imageNodes = imageSourceRanges(source);
for (const section of renderMarkdownSections(source, urls)) {
if (hiddenBlocks.some(block => block.from <= section.start && block.to >= section.end - 1)) continue;
if (!/(?:<pre|<table|<img|md-properties|md-callout|missing-image)/.test(section.html)) continue;
// Code remains a real editor surface. A preview swap loses the first drag
// and changes block height when focus or the selection moves elsewhere.
@@ -199,17 +201,19 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const fenced = node.name === "FencedCode";
const closed = fenced && /^\s*(`{3,}|~{3,})\s*$/.test(last.text) && last.number > first.number;
const code = fenced ? source.slice(Math.min(first.to + 1, node.to), closed ? last.from : node.to) : source.slice(node.from, node.to);
ranges.push(Decoration.widget({ widget: new CodeCopy(code), side: 1 }).range(first.to));
const editingCode = selected(node.from, node.to);
if (!editingCode) ranges.push(Decoration.widget({ widget: new CodeCopy(code), side: 1 }).range(first.to));
for (let number = first.number; number <= last.number; number++) {
const line = state.doc.line(number);
ranges.push(Decoration.line({ class: `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
}
return false;
}
const line = state.doc.lineAt(node.from);
if (/^ATXHeading[1-6]$/.test(node.name)) {
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name)) {
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
}
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
if (selected(node.from, node.to)) return;
if (node.name === "HorizontalRule") {
ranges.push(Decoration.line({ class: "writer-divider-line" }).range(line.from));
@@ -244,6 +248,12 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
if (match[3].toLowerCase() === "x") mark(line.from + match[0].length, line.to, "writer-completed");
}
} });
for (const match of source.matchAll(/\[\^([^\]\s]+)\](:)?/g)) {
const from = match.index, to = from + match[0].length;
if (hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
if (source[from - 1] === "\\") continue;
mark(from, to, match[2] && state.doc.lineAt(from).from === from ? "writer-footnote-definition" : "writer-footnote-ref");
}
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
const from = match.index, to = from + match[0].length;
if (selected(from, to) || hidden(from, to) || codeRanges.some(code => from >= code.from && to <= code.to)) continue;
@@ -260,7 +270,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
update(value, transaction) {
return transaction.docChanged || transaction.selection
|| syntaxTree(transaction.startState) !== syntaxTree(transaction.state)
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource))
|| transaction.effects.some(effect => effect.is(refreshImages) || effect.is(editImageSource) || effect.is(foldEffect) || effect.is(unfoldEffect))
? build(transaction.state, value.map(transaction.changes)) : value;
},
provide: field => [EditorView.decorations.from(field), EditorView.atomicRanges.of(view => view.state.field(field).update({
+7 -15
View File
@@ -1,5 +1,6 @@
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { requestText } from "../workspace/dialogs.svelte";
import { pickLinkDocument } from "./documentPicker";
import { externalLinkText, workspaceLinkText } from "./linkCommands";
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";
@@ -15,6 +16,7 @@ export type MarkdownMenuEditor = {
// identical in the writing editor and the source editor.
export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextActions, report: (message: string) => void) {
let root: HTMLElement | undefined, destroyed = false;
const pending = new AbortController();
function close(focus = true) {
root?.remove(); root = undefined;
if (focus && !destroyed) editor.focus();
@@ -41,21 +43,11 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
finally { if (valid()) editor.focus(); }
}
function link(external: boolean) {
if (external) { apply(externalLinkText(source, selection)); return; }
void request(async () => {
const target = (await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text))?.trim();
const target = await pickLinkDocument(pending.signal);
if (!target || !valid()) return;
if (external) {
try {
const url = new URL(target);
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error();
} catch { report("Enter a valid http, https, or mailto link."); return; }
const label = (text || target).replace(/[\\[\]]/g, "\\$&").replace(/\r?\n/g, " ");
apply(replacement(selection, `[${label}](${target.replace(/[()<>]/g, char => encodeURIComponent(char).replace("(", "%28").replace(")", "%29"))})`));
} else {
if (/[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; }
const label = text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim();
apply(replacement(selection, `[[${target}${label && label !== target ? "|" + label : ""}]]`));
}
apply(workspaceLinkText(source, selection, target));
});
}
function clipboard(kind: "cut" | "copy" | "paste" | "plain") {
@@ -114,7 +106,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
root = actionMenu(x, y, items, close, "Markdown text actions");
}
return { open, close, destroy() {
destroyed = true; close(false);
destroyed = true; pending.abort(); close(false);
document.removeEventListener("mousedown", outside, true);
document.removeEventListener("scroll", scroll, true);
window.removeEventListener("resize", resize);
+39 -9
View File
@@ -2,6 +2,7 @@ import { invoke, isTauri } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import type { ActionIcon } from "../ui/actionIcons";
import { spellingWord } from "./spellingWord";
/** WebView2 owns spelling suggestions and applies corrections to the original word. */
export function isSpellingTarget(target: EventTarget | null): boolean {
@@ -22,7 +23,7 @@ export type NativeSpellingItem = {
id: number; name: string; label: string; shortcut: string; kind: number;
enabled: boolean; checked: boolean; children: NativeSpellingItem[];
};
type NativeMenu = { request: string; items: NativeSpellingItem[] };
type NativeMenu = { request: string; items: NativeSpellingItem[]; fallback_spelling?: boolean };
const icons: Record<string, ActionIcon> = {
undo: "undo", redo: "redo",
cut: "cut", copy: "copy", paste: "paste", pasteAndMatchStyle: "paste-text",
@@ -48,7 +49,8 @@ export function spellingItems(items: NativeSpellingItem[], select: (id: number)
export function mountSpellingMenu(): () => void {
if (!isTauri()) return () => {};
let disposed = false, unlisten: (() => void) | undefined;
let context: { target: HTMLElement; x: number; y: number } | undefined;
let context: { target: HTMLElement; x: number; y: number; word: ReturnType<typeof spellingWord> } | undefined;
let revision = 0;
let active: { request: string; root: HTMLElement; target: HTMLElement } | undefined;
const finish = (command: number | null = null, restoreFocus = false) => {
if (!active) return;
@@ -59,30 +61,57 @@ export function mountSpellingMenu(): () => void {
void invoke("spelling_menu_select", { request, command }).catch(error => console.error("Cannot close the spelling menu", error));
};
const remember = (event: MouseEvent) => {
revision++;
finish();
if (event.defaultPrevented || !isSpellingTarget(event.target)) { context = undefined; return; }
const target = (event.target as HTMLElement).closest<HTMLElement>('[contenteditable="true"], textarea, input')!;
const bounds = document.getSelection()?.rangeCount ? document.getSelection()!.getRangeAt(0).getBoundingClientRect() : target.getBoundingClientRect();
context = { target, x: event.clientX || bounds.left, y: event.clientY || bounds.bottom };
context = { target, x: event.clientX || bounds.left, y: event.clientY || bounds.bottom, word: spellingWord(target, event.clientX, event.clientY) };
};
const outside = (event: PointerEvent) => { if (active && !active.root.contains(event.target as Node)) finish(); };
const scroll = (event: Event) => { if (active && !active.root.contains(event.target as Node)) finish(); };
const cancel = () => finish();
const outside = (event: PointerEvent) => { if (!active?.root.contains(event.target as Node)) { revision++; finish(); } };
const scroll = (event: Event) => { if (!active?.root.contains(event.target as Node)) { revision++; finish(); } };
const cancel = () => { revision++; finish(); };
window.addEventListener("contextmenu", remember);
window.addEventListener("pointerdown", outside);
window.addEventListener("resize", cancel);
window.addEventListener("blur", cancel);
window.addEventListener("pagehide", cancel);
document.addEventListener("scroll", scroll, true);
void listen<NativeMenu>("spelling-menu", ({ payload }) => {
document.addEventListener("input", cancel, true);
void listen<NativeMenu>("spelling-menu", async ({ payload }) => {
finish();
if (disposed || !context?.target.isConnected) {
void invoke("spelling_menu_select", { request: payload.request, command: null, fallback: true });
return;
}
const { target, x, y } = context;
const { target, x, y, word } = context;
const requestRevision = ++revision;
let items = spellingItems(payload.items, id => finish(id, true));
if (payload.fallback_spelling) {
const readable = (entries: NativeSpellingItem[]): NativeSpellingItem[] => entries.filter(item => item.kind === 3 || item.label.trim()).map(item => ({ ...item, children: readable(item.children) }));
items = spellingItems(readable(payload.items), id => finish(id, true));
if (word) {
const languages = [...new Set([target.lang, document.documentElement.lang, ...navigator.languages].filter(Boolean))];
try {
const result = await invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages });
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => { finish(); word.replace(value); } }));
if (result.misspelled && !suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true });
if (result.misspelled) suggestions.push({ label: "Add to dictionary", icon: "book", run: () => {
finish(null, true);
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(error => console.error("Could not add the word", error));
} }, { separator: true });
items = [...suggestions, ...items];
} catch {
items = [{ label: "Spelling suggestions unavailable", disabled: true }, { separator: true }, ...items];
}
}
}
if (disposed || requestRevision !== revision || !target.isConnected || (payload.fallback_spelling && word && !word.valid())) {
void invoke("spelling_menu_select", { request: payload.request, command: null });
return;
}
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body;
const root = actionMenu(x, y, spellingItems(payload.items, id => finish(id, true)), () => finish(null, true), "Spelling actions", parent);
const root = actionMenu(x, y, items, () => finish(null, true), "Spelling actions", parent);
active = { request: payload.request, root, target };
}).then(async stop => {
if (disposed) { stop(); return; }
@@ -100,5 +129,6 @@ export function mountSpellingMenu(): () => void {
window.removeEventListener("blur", cancel);
window.removeEventListener("pagehide", cancel);
document.removeEventListener("scroll", scroll, true);
document.removeEventListener("input", cancel, true);
};
}
+55
View File
@@ -0,0 +1,55 @@
export function wordAt(text: string, offset: number) {
for (const match of text.matchAll(/[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*/gu)) {
if (match.index <= offset && match.index + match[0].length >= offset) {
return { word: match[0], from: match.index, to: match.index + match[0].length };
}
}
return null;
}
type WordTarget = { word: string; replace(value: string): void; valid(): boolean };
export function spellingWord(target: HTMLElement, x: number, y: number): WordTarget | null {
const control = target instanceof HTMLTextAreaElement || target instanceof HTMLInputElement;
if (control) {
const original = target.value;
let offset = target.selectionStart ?? 0;
// A transparent mirror resolves the pointer position in wrapped and scrolled inputs.
if (x || y) {
const box = target.getBoundingClientRect(), css = getComputedStyle(target);
const mirror = document.createElement("div");
for (const key of Array.from(css)) mirror.style.setProperty(key, css.getPropertyValue(key));
Object.assign(mirror.style, { position: "fixed", left: `${box.left}px`, top: `${box.top}px`, width: `${box.width}px`, height: `${box.height}px`, margin: "0", opacity: "0", zIndex: "2147483647", pointerEvents: "auto", overflow: "hidden", whiteSpace: target instanceof HTMLInputElement ? "pre" : "pre-wrap", overflowWrap: "break-word" });
mirror.textContent = original || " ";
(target.closest("dialog[open]") ?? document.body).append(mirror);
mirror.scrollTop = target.scrollTop; mirror.scrollLeft = target.scrollLeft;
const hit = document.caretRangeFromPoint(x, y);
if (hit?.startContainer === mirror.firstChild) offset = hit.startOffset;
mirror.remove();
}
const found = wordAt(original, offset);
if (!found) return null;
const valid = () => target.isConnected && target.value === original && !target.disabled && !target.readOnly;
return { word: found.word, valid, replace(value) {
if (!valid()) return;
target.focus({ preventScroll: true }); target.setSelectionRange(found.from, found.to);
if (!document.execCommand("insertText", false, value)) {
target.setRangeText(value, found.from, found.to, "end");
target.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertReplacementText", data: value }));
}
} };
}
const range = x || y ? document.caretRangeFromPoint(x, y) : document.getSelection()?.rangeCount ? document.getSelection()!.getRangeAt(0).cloneRange() : null;
if (!range || range.startContainer.nodeType !== Node.TEXT_NODE || !target.contains(range.startContainer)) return null;
const node = range.startContainer, original = node.textContent ?? "";
const found = wordAt(original, range.startOffset);
if (!found) return null;
range.setStart(node, found.from); range.setEnd(node, found.to);
const valid = () => node.isConnected && target.isConnected && node.textContent === original;
return { word: found.word, valid, replace(value) {
if (!valid()) return;
target.focus({ preventScroll: true });
document.getSelection()?.removeAllRanges(); document.getSelection()?.addRange(range);
document.execCommand("insertText", false, value);
} };
}
+20 -4
View File
@@ -59,6 +59,12 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
else view.focus();
}
const clearCells = () => apply((text, selected) => mapTableCells(text, selected, () => ""));
const deleteCells = () => {
if (!range) return;
const { top, left } = bounds(range);
const next = { row: top, column: left };
apply(deleteTableCells, { anchor: next, head: next });
};
const format = (kind: CellFormat) => apply((text, selected) => formatTableCells(text, selected, kind));
async function clipboard(action: "copy" | "cut" | "paste") {
if (!range) return;
@@ -112,9 +118,10 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
sep,
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) },
...alignmentItems,
sep, { label: "Clear cells", icon: "clear", run: clearCells },
{ label: "Delete cells", icon: "trash", run: () => apply(deleteTableCells), title: "Remove selected rows/columns; otherwise shift cells left" },
sep, { label: "Clear cells", icon: "clear", run: clearCells, title: "Clear selected values and keep the cells." },
{ label: "Delete cells", icon: "trash", run: deleteCells, title: "Delete or Backspace removes full rows or columns. Other selections shift cells left." },
];
if (textEditor) items.push(sep, { label: "Select cell", icon: "select", title: "Select this cell, then use Shift+arrow keys to extend the selection", run: () => { closeMenu(); select(cellRange); } });
items.push(sep,
{ label: "Row", icon: "row", children: [
{ label: "Add row above", icon: "row-before", disabled: row === 0, title: row === 0 ? "The first row is the Markdown header" : undefined, run: () => structural("row", "before") },
@@ -191,7 +198,16 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
document.addEventListener("scroll", event => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }, { ...options, capture: true });
window.addEventListener("resize", closeMenu, options);
wrapper.addEventListener("keydown", event => {
if (!range) return;
if (event.isComposing) return;
if (!range) {
if (event.key !== "ContextMenu" && !(event.shiftKey && event.key === "F10")) return;
const cell = cellAt(event.target);
if (!cell) return;
event.preventDefault(); event.stopPropagation();
const rect = cell.getBoundingClientRect();
showMenu(rect.left, rect.bottom, point(cell), rich.get());
return;
}
const mod = event.ctrlKey || event.metaKey, key = event.key.toLowerCase();
const handled = ["Escape", "Delete", "Backspace", "Enter", "ContextMenu", "ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.key) || (event.shiftKey && event.key === "F10") || (mod && ["b", "i", "z", "y", "a"].includes(key));
if (!handled) return;
@@ -200,7 +216,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
else if (mod && key === "a") select({ anchor: { row: 0, column: 0 }, head: { row: table.rows.length - 1, column: table.rows[0].cells.length - 1 } });
else if (mod && ["b", "i"].includes(key)) format(key === "b" ? "bold" : "italic");
else if (event.key === "Escape") { clear(); view.focus(); }
else if (event.key === "Delete" || event.key === "Backspace") clearCells();
else if (event.key === "Delete" || event.key === "Backspace") deleteCells();
else if (event.key === "Enter") { const target = table.rows[range.head.row].cells[range.head.column]; clear(); target.focus(); }
else if (event.key === "ContextMenu" || event.key === "F10") { const rect = table.rows[range.head.row].cells[range.head.column].getBoundingClientRect(); showMenu(rect.left, rect.bottom); }
else {
+8
View File
@@ -0,0 +1,8 @@
import { isImagePath, workspaceImageLink } from "../workspace/media.ts";
export function workspaceFileLink(notePath: string, filePath: string): string {
const image = workspaceImageLink(notePath, filePath);
if (isImagePath(filePath)) return image;
const label = (filePath.replaceAll("\\", "/").split("/").pop() || filePath).replace(/[\\[\]]/g, "\\$&");
return `[${label}]${image.slice(3)}`;
}
+1 -3
View File
@@ -1,5 +1,3 @@
import { isImagePath } from "../workspace/media";
type Point = { x: number; y: number };
const targets = new Map<HTMLElement, (path: string, point: Point) => void>();
let highlighted: HTMLElement | undefined;
@@ -8,7 +6,7 @@ export function registerImageDropTarget(element: HTMLElement, drop: (path: strin
return () => { targets.delete(element); element.classList.remove("image-drop-target"); };
}
function targetAt(path: string, point: Point) {
if (!isImagePath(path)) return;
if (!path || path.endsWith("/")) return;
const hit = document.elementFromPoint(point.x, point.y);
return [...targets].find(([element]) => element.isConnected && hit && element.contains(hit));
}
+2 -1
View File
@@ -24,7 +24,8 @@
function convert(entries: MenuItem[]): ActionMenuItem[] {
return entries.map(item => {
if (item.kind === "sep") return { separator: true };
if (item.kind === "group") return { label: item.label, icon: item.icon, children: convert(item.items) };
if (item.kind === "group") return { label: item.label, icon: item.icon, children: convert(item.items),
...(item.run ? { run: () => { close(true); item.run?.(); } } : {}) };
return { label: item.label, icon: item.icon, disabled: item.disabled, run: () => {
close(true);
item.run();
+8
View File
@@ -214,12 +214,20 @@
}
.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;
justify-content: center;
color: var(--rs-text-dim);
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;
+43 -13
View File
@@ -29,6 +29,7 @@
type DropTarget,
} from "$lib/workspace/treeDrop";
import { planRename } from "$lib/workspace/renamePath";
import { isImagePath } from "$lib/workspace/media";
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type SelectionModifiers, type TreeSelection } from "$lib/workspace/treeSelection";
import ContextMenu from "./ContextMenu.svelte";
import type { MenuItem } from "./menuTypes";
@@ -49,6 +50,7 @@
keysActive?: boolean;
showInternal?: boolean;
onSaveTemplate?: (entry: TreeEntry) => void;
onManageTemplates?: () => void;
};
let {
@@ -63,6 +65,7 @@
keysActive = true,
showInternal = false,
onSaveTemplate,
onManageTemplates,
}: Props = $props();
let expanded = $state<Set<string>>(new Set([""]));
@@ -86,11 +89,17 @@
let cancelDrag: (() => void) | undefined;
let treeElement: HTMLDivElement;
let clipboard = $state<{ root: string; paths: string[]; cut: boolean } | null>(null);
type MoveBatch = { moves: { from: string; to: string }[]; before: Marks; after: Marks };
type MoveBatch = { action?: "rename"; moves: { from: string; to: string }[]; before: Marks; after: Marks };
let undoMoves = $state<MoveBatch[]>([]);
let redoMoves = $state<MoveBatch[]>([]);
let moving = $state(false);
let templates = $state<NoteTemplate[]>([]);
$effect(() => {
void workspaceRoot; void refreshToken;
let cancelled = false;
void noteTemplates().then(value => { if (!cancelled) templates = value; });
return () => { cancelled = true; };
});
onMount(() => {
const read = () => { void noteTemplates().then(value => templates = value); };
read(); window.addEventListener("runestone-templates-changed", read);
@@ -383,7 +392,7 @@
async function commitRename() {
const from = renameRel;
if (!from) {
if (!from || moving) {
return;
}
const plan = planRename(from, renameDraft);
@@ -395,15 +404,25 @@
error = plan.message;
return;
}
const operationRoot = workspaceRoot;
const before = structuredClone($state.snapshot(marks));
moving = true;
try {
await workspaceRename(from, plan.to);
await workspaceRename(from, plan.to, operationRoot);
if (workspaceRoot !== operationRoot) return;
const after = moveMarks(marks, from, plan.to);
undoMoves = [...undoMoves, { action: "rename", moves: [{ from, to: plan.to }], before, after: structuredClone(after) }];
redoMoves = [];
renameTreePaths(from, plan.to);
onEntryRenamed?.(from, plan.to);
await persistMarks(after);
await load(parentRel(from));
selectOnly(plan.to);
onEntryRenamed?.(from, plan.to);
await focusTreePath(plan.to);
onStatus?.(`Renamed to ${plan.to}`);
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
} finally { moving = false; }
}
function onWindowKey(event: KeyboardEvent) {
@@ -492,6 +511,16 @@
expanded = new Set([...expanded].filter(path => path !== rel && !path.startsWith(`${rel}/`)));
}
function renameTreePaths(from: string, to: string) {
const rename = (path: string) => path === from || path.startsWith(`${from}/`) ? to + path.slice(from.length) : path;
expanded = new Set([...expanded].map(rename));
childrenMap = Object.fromEntries(Object.entries(childrenMap).map(([parent, entries]) => [rename(parent), entries.map(entry => {
const rel_path = rename(entry.rel_path);
return rel_path === entry.rel_path ? entry : { ...entry, rel_path, name: rel_path.split("/").pop()! };
})]));
selection = { paths: new Set([...selection.paths].map(rename)), anchor: selection.anchor === null ? null : rename(selection.anchor) };
}
async function handleDrop(target: TreeEntry, entries: TreeEntry[], place: DropPlace) {
if (moving) return;
const operationRoot = workspaceRoot;
@@ -573,11 +602,12 @@
await persistMarks(replayMoveMarks(marks, batch.before, batch.after, batch.moves, redo));
if (redo) { redoMoves = redoMoves.slice(0, -1); undoMoves = [...undoMoves, batch]; }
else { undoMoves = undoMoves.slice(0, -1); redoMoves = [...redoMoves, batch]; }
childrenMap = {}; expanded = new Set([""]);
await load("");
for (const move of applied) renameTreePaths(move.from, move.to);
const folders = new Set([...Object.keys(childrenMap), ...applied.flatMap(move => [parentRel(move.from), parentRel(move.to)])]);
for (const folder of folders) await load(folder);
selection = { paths: new Set(applied.map(move => move.to)), anchor: applied.at(-1)?.to ?? null };
await focusTreePath(applied.at(-1)?.to);
onStatus?.(redo ? "File move restored." : "File move undone.");
onStatus?.(redo ? "File change restored." : "File change undone.");
} catch (reason) {
const rollbackErrors: string[] = [];
for (const move of applied.reverse()) {
@@ -659,9 +689,10 @@
icon: "file-plus",
run: () => { void createIn(parent, "file"); },
},
...(templates.length ? [{ kind: "group" as const, label: "New note", icon: "file-plus" as const, items: [
...(templates.length || onManageTemplates ? [{ kind: "group" as const, label: "New note", icon: "file-plus" as const, run: () => { void fromTemplate(); }, items: [
{ kind: "action" as const, label: "Blank note", icon: "file-plus" as const, run: () => { void fromTemplate(); } },
...templates.map(template => ({ kind: "action" as const, label: template.name, icon: "file-plus" as const, run: () => { void fromTemplate(template); } })),
...(onManageTemplates ? [{ kind: "sep" as const }, { kind: "action" as const, label: "Manage templates…", icon: "copy" as const, run: onManageTemplates }] : []),
] }] : [{ kind: "action" as const, label: "New note", icon: "file-plus" as const, run: () => { void fromTemplate(); } }]),
{ kind: "action", label: "New folder", icon: "folder-plus", run: () => { void createIn(parent, "folder"); } },
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
@@ -689,10 +720,9 @@
return [
{ kind: "action", label: "Open in terminal", icon: "terminal", run: () => { void workspaceOpenTerminal(parent).catch(reason => error = String(reason)); } },
{ kind: "action", label: "Paste", icon: "paste", disabled: !clipboard || clipboard.root !== workspaceRoot || moving, run: () => { void pasteEntries(parent); } },
{ kind: "action", label: "Copy path", icon: "copy", run: () => { void workspaceAbsPath(parent).then(path => copyText(path, "path")).catch(reason => error = String(reason)); } },
{ kind: "sep" },
{ kind: "action", label: "Undo file move", icon: "undo", disabled: !undoMoves.length || moving, run: () => { void replayMoves(); } },
{ kind: "action", label: "Redo file move", icon: "redo", disabled: !redoMoves.length || moving, run: () => { void replayMoves(true); } },
{ kind: "action", label: undoMoves.at(-1)?.action === "rename" ? "Undo rename" : "Undo file move", icon: "undo", disabled: !undoMoves.length || moving, run: () => { void replayMoves(); } },
{ kind: "action", label: redoMoves.at(-1)?.action === "rename" ? "Redo rename" : "Redo file move", icon: "redo", disabled: !redoMoves.length || moving, run: () => { void replayMoves(true); } },
];
}
@@ -896,7 +926,7 @@
<div class="drag-ghost" style:left="{dragPoint.x + 12}px" style:top="{dragPoint.y + 12}px">
<span>{dragEntries.length > 1 ? `${dragEntries.length} items` : dragRel.split("/").pop()}</span>
{#if imageLanding}
<span class="hint">Insert image</span>
<span class="hint">{isImagePath(dragRel ?? "") ? "Insert image" : "Insert link"}</span>
{:else if landing && dropTarget}
<span class="hint">{dropHint(landing.name, dropTarget.place)}</span>
{/if}
+20 -1
View File
@@ -6,6 +6,8 @@
import { renderDiagrams } from "$lib/workspace/diagrams";
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls";
import { readerHeadingFolding } from "$lib/editor/headingFolding";
import "$lib/editor/headingFolding.css";
type Props = {
noteRel: string;
@@ -20,6 +22,9 @@
let html = $state("");
let sections = $state<MarkdownSection[]>([]);
let root: HTMLDivElement | undefined = $state();
const collapsedHeadings = new Set<string>();
let foldingNote = "";
let headingControls: ReturnType<typeof readerHeadingFolding> | undefined;
async function loadUrls(noteRel: string, contents: string): Promise<Map<string, string>> {
const urls = new Map<string, string>();
@@ -47,6 +52,7 @@
$effect(() => {
void $pluginHost;
const path = noteRel;
if (foldingNote !== path) { collapsedHeadings.clear(); foldingNote = path; }
const text = contents;
let cancelled = false;
html = renderMarkdownHtml(text, new Map());
@@ -67,12 +73,14 @@
const el = root;
let cancelled = false;
let releaseImages: (() => void) | undefined;
let currentHeadings: ReturnType<typeof readerHeadingFolding> | undefined;
if (el) void tick().then(() => {
if (cancelled) return;
releaseImages = imageControls(el);
headingControls = currentHeadings = readerHeadingFolding(el, collapsedHeadings);
return renderDiagrams(el, () => cancelled);
});
return () => { cancelled = true; releaseImages?.(); };
return () => { cancelled = true; releaseImages?.(); currentHeadings?.destroy(); };
});
async function copyFence(button: HTMLButtonElement, body: string) {
@@ -134,6 +142,17 @@
return;
}
const href = node.getAttribute("href") ?? "";
if (node.hasAttribute("data-footnote-link")) {
event.preventDefault();
const target = root?.querySelector<HTMLElement>(`[id="${href.slice(1)}"]`);
if (target) {
// A footnote can sit in a folded section. Reveal it before navigation.
headingControls?.reveal(target);
target.scrollIntoView({ block: "center" });
target.focus({ preventScroll: true });
}
return;
}
const kind = node.getAttribute("data-kind");
if (kind === "wiki") {
event.preventDefault();
+6 -3
View File
@@ -2,7 +2,7 @@
import { workspaceList } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types";
import { onMount } from "svelte";
let { onOpen, onClose }: { onOpen: (entry: TreeEntry) => void; onClose: () => void } = $props();
let { onOpen, onClose, purpose = "Find a file", actionLabel = "open" }: { onOpen: (entry: TreeEntry) => void; onClose: () => void; purpose?: string; actionLabel?: string } = $props();
let query = $state("");
let files = $state<TreeEntry[]>([]);
let selected = $state(0);
@@ -31,7 +31,10 @@
});
</script>
<dialog bind:this={dialog} oncancel={onClose}>
<dialog 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}>
<input bind:this={input} bind:value={query} oninput={() => selected = 0} aria-label="Find a file" placeholder="Find a note or code file…" onkeydown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
@@ -45,7 +48,7 @@
{/each}
{#if !matches.length}<p>{loading ? "Finding files…" : "No matching files."}</p>{/if}
</div>
<footer>{error || `${files.length} files${loading ? " · indexing…" : ""}`} <span>↑ ↓ select · Enter open · Esc close</span></footer>
<footer>{error || `${files.length} files${loading ? " · indexing…" : ""}`} <span>↑ ↓ select · Enter {actionLabel} · Esc close</span></footer>
</dialog>
<style>
+1 -1
View File
@@ -139,7 +139,7 @@
{:else}
<div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>Version {version}</p></div>
<div class="card help-card">
<details open><summary><Icon icon="book-open" /> Get started</summary><div class="help-copy"><p>Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.</p><p>Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.</p><p>Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.</p></div></details>
<details><summary><Icon icon="book-open" /> Get started</summary><div class="help-copy"><p>Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.</p><p>Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.</p><p>Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.</p></div></details>
<details><summary><Icon icon="save" /> Save your work</summary><div class="help-copy"><p>Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.</p><p>If another app changes a file, RuneStone keeps your edits and offers both versions for review.</p></div></details>
<details><summary><Icon icon="code" /> Keyboard shortcuts</summary><dl><div><dt>Open a workspace</dt><dd><kbd>Ctrl+O</kbd></dd></div><div><dt>Find a file</dt><dd><kbd>Ctrl+P</kbd></dd></div><div><dt>Save the active file</dt><dd><kbd>Ctrl+S</kbd></dd></div><div><dt>Search the workspace</dt><dd><kbd>Ctrl+Shift+F</kbd></dd></div><div><dt>Open settings</dt><dd><kbd>Ctrl+,</kbd></dd></div><div><dt>Help and about</dt><dd><kbd>F1</kbd></dd></div></dl></details>
</div>
+77
View File
@@ -0,0 +1,77 @@
<script lang="ts">
import { onMount } from "svelte";
import { confirm } from "@tauri-apps/plugin-dialog";
import { isTauri } from "@tauri-apps/api/core";
import IconButton from "$lib/ui/IconButton.svelte";
import Icon from "$lib/ui/Icon.svelte";
import { requestText } from "$lib/workspace/dialogs.svelte";
import { noteTemplates, saveNoteTemplate, TEMPLATE_FOLDER, type NoteTemplate } from "$lib/workspace/templates";
import { workspaceDelete, workspaceRename } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types";
let { onClose, onEdit, onRenamed, onDeleted }: { onClose: () => void; onEdit: (entry: TreeEntry) => void;
onRenamed: (from: string, to: string) => void; onDeleted: (path: string) => void } = $props();
let dialog: HTMLDialogElement;
let templates = $state<NoteTemplate[]>([]);
let error = $state("");
let busy = $state(false);
const edit = (template: NoteTemplate) => onEdit({ rel_path: template.path, name: template.name + ".md", kind: "file" });
async function refresh() { templates = await noteTemplates(); window.dispatchEvent(new Event("runestone-templates-changed")); }
onMount(() => { dialog.showModal(); void refresh(); });
async function create() {
const name = await requestText("Template name", "New template");
if (!name) return;
busy = true; error = "";
try { const path = await saveNoteTemplate(name, ""); await refresh(); edit({ path, name: path.split("/").at(-1)!.replace(/\.md$/i, "") }); }
catch (reason) { error = String(reason); }
finally { busy = false; }
}
async function rename(template: NoteTemplate) {
const name = await requestText("Template name", template.name);
if (!name) return;
const title = name.trim().replace(/\.md$/i, "");
if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) { error = "Enter a valid template name."; return; }
const path = `${TEMPLATE_FOLDER}/${title}.md`;
if (path === template.path) return;
busy = true; error = "";
try { await workspaceRename(template.path, path); onRenamed(template.path, path); await refresh(); }
catch (reason) { error = String(reason); }
finally { busy = false; }
}
async function remove(template: NoteTemplate) {
const message = `Delete the template “${template.name}”? Existing notes stay unchanged.`;
const accepted = isTauri() ? await confirm(message, { title: "Delete template", kind: "warning" }) : window.confirm(message);
if (!accepted) return;
busy = true; error = "";
try { await workspaceDelete(template.path); onDeleted(template.path); await refresh(); }
catch (reason) { error = String(reason); }
finally { busy = false; }
}
</script>
<dialog bind:this={dialog} aria-labelledby="templates-title" oncancel={event => { event.preventDefault(); if (!busy) onClose(); }}>
<header><h2 id="templates-title">Document templates</h2><IconButton icon="close" label="Close templates" disabled={busy} onclick={onClose} /></header>
<p>Templates belong to this workspace. Edit a template to change future notes.</p>
<button class="new" disabled={busy} onclick={() => void create()}><Icon icon="file-plus" /> New template</button>
<div class="list">
{#each templates as template (template.path)}
<div class="row"><span title={template.name}>{template.name}</span><div class="actions">
<IconButton icon="pen" label={`Edit ${template.name}`} disabled={busy} onclick={() => edit(template)} />
<button class="rename" aria-label={`Rename ${template.name}`} title={`Rename ${template.name}`} disabled={busy} onclick={() => void rename(template)}><Icon icon="text" /> Rename</button>
<IconButton icon="trash" label={`Delete ${template.name}`} disabled={busy} onclick={() => void remove(template)} />
</div></div>
{:else}<p>No templates yet. Create one or use Save as template on a note.</p>{/each}
</div>
{#if error}<p role="alert">{error}</p>{/if}
</dialog>
<style>
dialog{width:min(600px,90vw);max-height:80vh;padding:var(--rs-settings-section-gap);background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
dialog::backdrop{background:#0008}
header,.row,.actions,.new{display:flex;align-items:center;gap:var(--rs-settings-gap)}
header{justify-content:space-between}h2{margin:0;font-size:var(--rs-settings-heading-size)}
p{font-size:var(--rs-settings-description-size);color:var(--rs-text-dim);line-height:1.5}
.list{margin-top:var(--rs-settings-gap);max-height:50vh;overflow:auto}.row{padding:var(--rs-settings-row-padding);border-bottom:1px solid var(--rs-border);flex-wrap:wrap}.row>span{flex:1;min-width:100px;overflow-wrap:anywhere}
.new{min-height:var(--rs-settings-control-height);padding:4px 8px;background:var(--rs-bg-elevated);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.new :global(svg){width:16px;height:16px}[role=alert]{color:var(--rs-error)}
.rename{display:flex;align-items:center;gap:4px;min-height:28px;padding:4px 8px;background:transparent;border:0;border-radius:var(--rs-control-radius)}.rename:hover{background:var(--rs-bg-active)}.rename:focus-visible{outline:2px solid var(--rs-accent)}.rename :global(svg){width:16px;height:16px}
</style>
+4 -1
View File
@@ -10,7 +10,10 @@
</script>
{#if dialogs.text}
<dialog bind:this={element} oncancel={(event) => { event.preventDefault(); finishText(null); }}>
<dialog bind:this={element} onpointerdown={(event) => {
const bounds = element!.getBoundingClientRect();
if (event.target === element && (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)) finishText(null);
}} oncancel={(event) => { event.preventDefault(); finishText(null); }}>
<form onsubmit={(event) => { event.preventDefault(); finishText(dialogs.text?.value.trim() || null); }}>
<label for="text-request">{dialogs.text.title}</label>
<input id="text-request" bind:this={input} bind:value={dialogs.text.value} autocomplete="off" />
+36 -25
View File
@@ -22,6 +22,7 @@
import { requestText } from "$lib/workspace/dialogs.svelte";
import TextDialog from "./TextDialog.svelte";
import QuickOpen from "./QuickOpen.svelte";
import TemplateManager from "./TemplateManager.svelte";
import WorkspacePicker from "./WorkspacePicker.svelte";
import SettingsDialog from "./SettingsDialog.svelte";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
@@ -74,6 +75,7 @@
let settingsReady = $state(false);
let workspaceAnchor: HTMLDivElement | undefined = $state();
const desktop = isTauri();
const transferredWindow = /^[0-9a-f-]{36}$/i.test(new URLSearchParams(location.search).get("tabTransfer") ?? "");
let tabs = $state<OpenBuffer[]>([]);
let activePath = $state<string | null>(null);
const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null);
@@ -87,18 +89,19 @@
let bottomHeight = $state(180);
let leftView = $state<WorkbenchLayout["leftView"]>(DEFAULT_WORKBENCH_LAYOUT.leftView);
let searchRequest = $state<{ text: string; id: number } | null>(null);
let leftOpen = $state(DEFAULT_WORKBENCH_LAYOUT.leftOpen);
let rightOpen = $state(DEFAULT_WORKBENCH_LAYOUT.rightOpen);
$effect(() => { if ($pluginSidebar) leftOpen = true; });
let leftOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.leftOpen);
let rightOpen = $state(!transferredWindow && DEFAULT_WORKBENCH_LAYOUT.rightOpen);
$effect(() => { if ($pluginSidebar && !transferredWindow) leftOpen = true; });
let terminalOpen = $state(false);
let reading = $state(false);
let quickOpen = $state(false);
let templateManager = $state(false);
let terminalStarted = $state(false);
let terminalMaximized = $state(false);
let terminalDock: TerminalSlot | undefined = $state();
const terminalContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("terminal"); });
const terminalEnabled = $derived(!!terminalContribution);
const sidebarNavigation = $derived($pluginNavigation.filter(item => item.placement === "sidebar" && !item.toolbar));
const sidebarNavigation = $derived($pluginNavigation.filter(item => item.placement === "sidebar"));
const ribbonNavigation = $derived($pluginNavigation.filter(item => item.placement !== "sidebar" && !item.toolbar));
const browserContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); });
let browserOpening = $state(false);
@@ -255,6 +258,7 @@
}
function selectLeft(next: "files" | "search" | "bookmarks") {
if (transferredWindow) return;
const hadSidebar = !!$pluginSidebar;
closePluginSidebar();
if (!hadSidebar && leftOpen && leftView === next) {
@@ -357,7 +361,8 @@
if (action && "run" in action && !action.disabled) { action.run?.(); return; }
}
const current = documents;
const snapshot = JSON.stringify("buffer" in tab ? tab.buffer : pluginTabState(tab.plugin));
const bufferSnapshot = (buffer?: OpenBuffer) => JSON.stringify(buffer ? { ...buffer, diskError: buffer.diskError ?? null } : undefined);
const snapshot = "buffer" in tab ? bufferSnapshot(tab.buffer) : JSON.stringify(pluginTabState(tab.plugin));
const token = crypto.randomUUID(), key = `runestone.tab-transfer.${token}`;
let timer: ReturnType<typeof setTimeout>;
const finish = () => {
@@ -369,7 +374,7 @@
const accepted = (event: StorageEvent) => {
if (event.key !== key + ".accepted" || event.newValue !== "true") return;
if ("buffer" in tab) {
if (documents === current && JSON.stringify(current?.buffers.find(buffer => buffer.id === tab.buffer.id)) === snapshot) current?.close(tab.relPath);
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);
finish();
};
@@ -688,7 +693,7 @@
event.preventDefault(); newTab(); return;
}
if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key.toLowerCase() === "f") {
event.preventDefault(); leftOpen = true; leftView = "search"; return;
event.preventDefault(); if (!transferredWindow) { leftOpen = true; leftView = "search"; } return;
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "s") {
event.preventDefault();
@@ -720,7 +725,7 @@
}
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === "b") {
event.preventDefault();
leftOpen = !leftOpen;
if (!transferredWindow) leftOpen = !leftOpen;
}
if (event.key === "F2" && !event.ctrlKey && !event.metaKey && !event.altKey) {
if (event.target instanceof HTMLInputElement || event.target instanceof HTMLTextAreaElement) {
@@ -830,12 +835,13 @@
try {
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
if (transferredWindow) { leftOpen = false; rightOpen = false; }
layoutReady = true;
} catch { error = "Could not read your layout. Default layout applies for this window."; }
});
$effect(() => {
if (!layoutReady) return;
if (!layoutReady || transferredWindow) return;
try { saveWorkbenchLayout(localStorage, { leftOpen, rightOpen, leftWidth, rightWidth, leftView }); }
catch { error = "Could not save your layout. Layout changes apply for this window only."; }
});
@@ -926,12 +932,17 @@
<WorkspacePicker bind:this={workspacePicker} currentRoot={workspace?.root} anchor={workspaceAnchor} onOpen={openPath} />
{#if preferences}<SettingsDialog {settings} help={preferences === "help"} onSave={updateSettings} onClose={() => preferences = null} />{/if}
{#if quickOpen && workspace}<QuickOpen onOpen={(entry) => void openFile(entry)} onClose={() => quickOpen = false} />{/if}
{#if templateManager && workspace}<TemplateManager onClose={() => templateManager = false}
onEdit={(entry) => { templateManager = false; void openFile(entry, undefined, "new"); }}
onRenamed={(from, to) => { applyPathRename(from, to); refreshToken++; }}
onDeleted={(path) => { removePluginDocuments(path); void documents?.refresh(); refreshToken++; }} />{/if}
<div
class="shell"
class:has-ribbon={ribbonNavigation.length > 0}
class:left-open={leftOpen}
class:right-open={rightOpen}
class:detached={transferredWindow}
class:has-ribbon={!transferredWindow && ribbonNavigation.length > 0}
class:left-open={!transferredWindow && leftOpen}
class:right-open={!transferredWindow && rightOpen}
role="application"
aria-label="RuneStone workbench"
style:--left="{leftWidth}px"
@@ -943,6 +954,7 @@
>
<header class="header" data-tauri-drag-region>
<div class="header-left" data-tauri-drag-region>
{#if !transferredWindow}
<IconButton
icon="files"
label="Files"
@@ -969,6 +981,7 @@
onclick={() => openPluginView(item.owner, item.id)}
/>
{/each}
{/if}
</div>
<div class="header-center" data-tauri-drag-region>
<TabBar tabs={workingTabs} activePath={activeTabPath} onSelect={selectWorkingTab} onClose={closeTab}
@@ -977,30 +990,26 @@
onDetach={(tab) => { void detachTab(tab); }}
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
<PluginAccessMenu surface="open" compact />
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
</div>
<div class="header-right" data-tauri-drag-region>
{#each $pluginNavigation.filter(item => item.toolbar) as item (item.owner + ":" + item.id)}
<IconButton icon={item.icon ?? "puzzle"} label={item.title}
active={$pluginView?.owner === item.owner && $pluginView?.id === item.id && $pluginEditorActive}
onclick={() => openPluginView(item.owner, item.id)} />
{/each}
{#if browserContribution?.newTab}<IconButton icon="globe" label="New browser tab" disabled={browserOpening} onclick={() => void openBrowser()} />{/if}
<PluginAccessMenu surface="open" compact />
<PluginTools />
<PluginAccessMenu surface="commands" compact />
<IconButton icon="save" label="Save" disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} />
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if}
<IconButton
{#if !transferredWindow}<IconButton
icon="panel-right"
label={rightOpen ? "Hide outline" : "Show outline"}
active={rightOpen}
onclick={() => (rightOpen = !rightOpen)}
/>
/>{/if}
{#if desktop}<WindowControls onError={(message) => error = message} />{/if}
</div>
</header>
<nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={ribbonNavigation.length === 0}>
{#if !transferredWindow}<nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={ribbonNavigation.length === 0}>
{#each ribbonNavigation as item (`${item.owner}:${item.id}`)}
<IconButton
icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" || item.icon === "git" ? item.icon : "puzzle"}
@@ -1010,9 +1019,9 @@
onclick={() => openPluginView(item.owner, item.id)}
/>
{/each}
</nav>
</nav>{/if}
{#if leftOpen}
{#if leftOpen && !transferredWindow}
<aside class="left">
<div class="left-body">
{#if $pluginSidebar}
@@ -1028,6 +1037,7 @@
workspaceRoot={workspace.root}
showInternal={settings.showInternalFolder}
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
onManageTemplates={() => templateManager = true}
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
{refreshToken}
@@ -1137,7 +1147,7 @@
<section class="bottom" class:terminal-hidden={!terminalOpen}>
{#if workspace}
{#key workspace.root}
<TerminalSlot contribution={terminalContribution} bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={toggleTerminal}
<TerminalSlot contribution={terminalContribution} bind:this={terminalDock} cwd={workspace.root} visible={terminalOpen} onClose={() => { terminalOpen = false; terminalStarted = false; terminalMaximized = false; }}
maximized={terminalMaximized} onMaximize={() => terminalMaximized = !terminalMaximized}
activeFile={buffer?.kind === "text" && !reading} onRunFile={terminalFile}
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
@@ -1149,7 +1159,7 @@
{/if}
</div>
{#if rightOpen}
{#if rightOpen && !transferredWindow}
<div
class="gutter gutter-v"
role="separator"
@@ -1210,6 +1220,7 @@
}
.shell.has-ribbon { --ribbon-width: 44px; }
.shell.detached { grid-template-columns: minmax(0, 1fr); }
.plugin-ribbon {
grid-column: 1;
+1
View File
@@ -13,6 +13,7 @@ export type MenuSep = { kind: "sep" };
export type MenuGroup = {
kind: "group";
label: string;
run?: () => void;
icon?: ActionIcon;
items: MenuItem[];
};
+6 -4
View File
@@ -3,14 +3,16 @@
import Icon from "$lib/ui/Icon.svelte";
import ContextMenu from "$lib/layout/ContextMenu.svelte";
import type { MenuItem } from "$lib/layout/menuTypes";
import { installedPlugins, pluginTools, openPluginView, runPluginCommand } from "./external";
import { installedPlugins, pluginTools, pluginNavigation, openPluginView, runPluginCommand } from "./external";
let { surface, compact = false }: { surface: "commands" | "open"; compact?: boolean } = $props();
let anchor = $state<HTMLButtonElement>();
let position = $state<{ x: number; y: number } | null>(null);
let error = $state("");
let pointerWasOpen = false;
const label = $derived(surface === "open" ? "Open tab or view" : "Commands");
const tools = $derived($pluginTools.filter(tool => tool.surface === surface));
const label = $derived(surface === "open" ? "Plug-in views" : "Commands");
const tools = $derived($pluginTools.filter(tool => tool.surface === surface
&& tool.owner !== "runestone.browser"
&& !(surface === "open" && tool.kind === "view" && $pluginNavigation.some(item => item.owner === tool.owner && item.id === tool.id && item.placement === "sidebar"))));
const signature = $derived(JSON.stringify([tools, $installedPlugins.plugins.map(row => [row.manifest.id, row.manifest.name])]));
const items: MenuItem[] = $derived.by(() => { void signature; return untrack(() => tools.map(tool => ({
kind: "action" as const,
@@ -28,7 +30,7 @@
<button class="access-button" class:compact bind:this={anchor} aria-label={label} aria-haspopup="menu" aria-expanded={position !== null} title={label}
onpointerdown={() => pointerWasOpen = position !== null}
onclick={event => { const close = event.detail > 0 ? pointerWasOpen : position !== null; const bounds = anchor!.getBoundingClientRect(); position = close ? null : { x: bounds.left, y: bounds.bottom + 4 }; }}>
<Icon icon={surface === "open" ? "chevron-down" : "code"} />{#if !compact}<span>{label}</span>{/if}
<Icon icon={surface === "open" ? "puzzle" : "code"} />{#if !compact}<span>{label}</span>{/if}
{#if compact}<span class="access-tooltip" role="tooltip">{label}</span>{/if}
</button>
{/if}
+1 -1
View File
@@ -10,7 +10,7 @@ export function pluginAccess(owner: string, commands: Iterable<PluginCommand>, v
const result: PluginTool[] = [];
for (const command of commands) {
const legacyOpen = owner === "runestone.browser" && command.id === "new-tab";
result.push({ owner, id: command.id, title: command.title, kind: "command", surface: command.category === "open" || (command.category === undefined && legacyOpen) ? "open" : "commands" });
result.push({ owner, id: command.id, title: command.title, kind: "command", surface: command.category === "open" || (command.category === undefined && legacyOpen) ? "open" : "commands", icon: command.icon });
}
for (const view of views) {
const settings = view.settings ?? (owner === "runestone.local-autocomplete" && view.id === "settings");
+2
View File
@@ -1,6 +1,7 @@
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 type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -49,6 +50,7 @@ export class ExternalSession {
};
const api: PluginApi = {
id: this.id, signal: this.controller.signal,
ui: { showActionMenu: options => { this.check(); return showActionMenu(options, this.controller.signal); } },
...(this.services.git ? { git: {
status: () => { this.check(); return this.services.git!.status(); },
diff: (path: string, staged: boolean) => { this.check(); return this.services.git!.diff(path, staged); },
+2 -1
View File
@@ -3,7 +3,7 @@ import type { CompletionApi } from "../completion/contracts.ts";
import type { ActionMenuItem } from "../ui/actionMenu.ts";
/** Package API v1. Compiled plugins export activate(api). */
export type Dispose = () => void | Promise<void>;
export interface PluginCommand { id: string; title: string; category?: "open" | "action"; run: () => void | Promise<void> }
export interface PluginCommand { id: string; title: string; icon?: PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> }
export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise<void>; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string }
export interface PluginDocumentContext { id: string; path: string }
@@ -18,6 +18,7 @@ export interface PluginDocumentType {
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PluginApi {
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
git?: import("../git/contracts.ts").GitApi;
completion?: CompletionApi;
readonly id: string;
+112 -23
View File
@@ -1,20 +1,64 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, onDestroy } from 'svelte';
import { invoke, isTauri } from '@tauri-apps/api/core';
import { customThemes, installTheme, parseCustomTheme, removeTheme, type CustomTheme } from './customThemes';
import IconButton from '$lib/ui/IconButton.svelte';
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, parseAppearance, normalizeAppearance, saveAppearance, type Appearance, type ThemeName } from './appearance';
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';
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
let error = $state('');
let status = $state('');
let exporting = $state(false);
let backgroundInput: HTMLInputElement;
let backgroundRevision = 0;
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 }))]);
onDestroy(() => closePicker());
function picker(event: MouseEvent, mode = false) {
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;
}
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'];
function backgroundPicker(event: MouseEvent, field: 'position' | 'size') {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const values = field === 'position' ? BACKGROUND_POSITIONS : BACKGROUND_SIZES;
const labels = field === 'position' ? positionLabels : sizeLabels;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? 'Image position' : 'Image size', parent: anchor.closest('dialog') ?? undefined,
items: values.map((value, index) => ({ label: labels[index], radio: true, checked: value === appearance.newTabBackground?.[field],
run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close;
}
onMount(() => {
const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = 'Could not read appearance settings.'; } };
read(); window.addEventListener('storage', read); window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', read); window.removeEventListener('focus', read); };
});
function change(next: Appearance) {
try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; }
catch { error = 'Could not save appearance settings.'; }
try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; return true; }
catch { error = 'Could not save appearance settings.'; return false; }
}
function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber;
if (!Number.isFinite(percent)) return;
change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 } });
}
async function removeBackground() {
backgroundRevision++;
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: undefined }) && old) {
try { await removeBackgroundImage(old); } catch { error = 'Could not remove the saved image from storage.'; }
}
}
async function importTheme(file?: File) {
if (!file) return;
@@ -26,30 +70,50 @@
} catch (reason) { error = String(reason); }
finally { themeInput.value = ''; }
}
function exportTemplate() {
const palette = (mode: 'light' | 'dark') => ({ bg: mode === 'dark' ? '#141414' : '#ffffff', text: mode === 'dark' ? '#e6e6e6' : '#202020', accent: mode === 'dark' ? '#82aaff' : '#315fb3' });
const selected = installed.find(item => `custom:${item.id}` === appearance.theme);
const source = selected ?? { schema: 1, id: 'my-theme', name: 'My theme', light: palette('light'), dark: palette('dark') };
const url = URL.createObjectURL(new Blob([JSON.stringify(source, null, 2) + '\n'], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = source.id + '.json'; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
async function importBackground(file?: File) {
if (!file) return;
const revision = ++backgroundRevision;
try {
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error('Choose a PNG, JPEG, WebP, or GIF image.');
const imageId = await saveBackgroundImage(file);
if (revision !== backgroundRevision) { await removeBackgroundImage(imageId); return; }
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
if (old) await removeBackgroundImage(old);
} else await removeBackgroundImage(imageId);
} catch (reason) { if (revision === backgroundRevision) error = String(reason); }
finally { if (revision === backgroundRevision) backgroundInput.value = ''; }
}
async function exportTemplate() {
if (exporting) return;
exporting = true; error = ''; status = '';
try {
const source = exportAppearanceTheme(appearance.theme);
const contents = JSON.stringify(source, null, 2) + '\n';
if (isTauri()) {
const path = await invoke<string | null>('theme_export', { contents, defaultName: source.id + '.json' });
status = path ? `Theme saved to ${path}` : 'Export canceled.';
} else {
const url = URL.createObjectURL(new Blob([contents], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = source.id + '.json';
document.body.append(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
status = 'Theme download started.';
}
} catch (reason) { error = `Could not export the theme: ${String(reason)}`; }
finally { exporting = false; }
}
</script>
<h2>Appearance</h2>
<p>Choose a color theme and a light or dark appearance.</p>
<div class="card">
<label><span>Color theme</span><select aria-label="Color theme" value={appearance.theme} onchange={event => change({ ...appearance, theme: event.currentTarget.value as ThemeName })}>
<option value="default">RuneStone</option><option value="claude">Claude</option><option value="sakura">Sakura</option>
{#each installed as theme}<option value={`custom:${theme.id}`}>{theme.name}</option>{/each}
</select></label>
<label><span>Appearance</span><select aria-label="Appearance" disabled={appearance.theme === 'sakura'} value={appearance.mode} onchange={event => change({ ...appearance, mode: event.currentTarget.value as 'light' | 'dark' })}>
<option value="light">Light</option><option value="dark">Dark</option>
</select></label>
<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>
<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]); }} />
<button onclick={() => themeInput.click()}>Install theme</button>
<button onclick={exportTemplate}>Export theme template</button>
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? 'Exporting…' : 'Export theme template'}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label="Remove custom theme" onclick={() => {
try { removeTheme(appearance.theme.slice(7)); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
catch { error = 'Could not remove this theme.'; }
@@ -57,17 +121,42 @@
</div>
<p>Edit the exported JSON colors, then choose Install theme. Each theme has light and dark colors.</p>
{#if appearance.theme === 'sakura'}<p>Sakura uses a light appearance.</p>{/if}
<h3>Background image</h3>
<div class="background-preview" aria-label="Background image preview"><span>Background</span></div>
{#if appearance.newTabBackground}
<div class="card">
<div class="setting-row"><span>Image position</span><button class="picker" aria-label="Image position" aria-haspopup="menu" onclick={event => backgroundPicker(event, 'position')}>{positionLabels[BACKGROUND_POSITIONS.indexOf(appearance.newTabBackground.position ?? 'center')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Image size</span><button class="picker" aria-label="Image size" aria-haspopup="menu" onclick={event => backgroundPicker(event, 'size')}>{sizeLabels[BACKGROUND_SIZES.indexOf(appearance.newTabBackground.size ?? 'cover')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Image overlay</span><div class="overlay-controls"><input type="range" aria-label="Image overlay" min="-100" max="100" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} /><label class="overlay-value"><input type="number" aria-label="Image overlay percentage" min="-100" max="100" step="1" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((appearance.newTabBackground?.overlay ?? 0) * 100)); }} /><span>%</span></label></div></div>
</div>
<p>Move left to lighten the image or right to darken it.</p>
{/if}
<div class="theme-actions">
<input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label="Background image file" hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} />
<button onclick={() => backgroundInput.click()}>Choose image…</button>
{#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>Remove image</button>{/if}
<button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>Reset background</button>
</div>
<p>PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.</p>
{#if status}<p role="status">{status}</p>{/if}
{#if error}<p role="alert">{error}</p>{/if}
<style>
h2{margin:0;font-size:var(--rs-settings-heading-size);color:var(--rs-text-strong)}
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5}
.card{padding:0 var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated)}
label{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}
label+label{border-top:1px solid var(--rs-border)}
select{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)}
select:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
label,.setting-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}
.setting-row+.setting-row{border-top:1px solid var(--rs-border)}
.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}
.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}
.overlay-value input{width:64px;min-height:var(--rs-settings-control-height);box-sizing:border-box;padding:4px 6px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);font:inherit}
.overlay-value input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
[role=alert]{color:var(--rs-error)}
.theme-actions{display:flex;gap:var(--rs-settings-gap);flex-wrap:wrap;margin-top:var(--rs-settings-gap)}
.theme-actions 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);padding:4px 8px}
h3{margin-top:var(--rs-settings-section-gap);font-size:14px}.background-preview{height:120px;background-color:var(--rs-bg);background-image:var(--rs-background-image,none);background-size:100% 100%,var(--rs-background-size,cover);background-position:center,var(--rs-background-position,center);background-repeat:no-repeat;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);display:grid;place-items:center;margin-bottom:var(--rs-settings-gap)}.background-preview span{padding:8px 14px;background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
</style>
+75 -5
View File
@@ -1,12 +1,26 @@
import { customThemes } from './customThemes.ts';
import { customThemes, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
export const APPEARANCE_KEY = 'runestone.appearance';
export const THEMES = ['default', 'claude', 'sakura'] as const;
export type ThemeName = typeof THEMES[number] | `custom:${string}`;
export type Appearance = { theme: ThemeName; mode: 'light' | 'dark' };
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 } | null): Appearance {
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';
return { theme, mode: theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark' };
const result: Appearance = { 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 };
const image = typeof source.image === 'string' && source.image.length <= 3_000_000 && /^data:image\/(?:png|jpeg|webp|gif);base64,[a-z0-9+/=]+$/i.test(source.image) ? source.image : undefined;
const imageId = typeof source.imageId === 'string' && /^[0-9a-f-]{36}$/i.test(source.imageId) ? source.imageId : undefined;
const overlay = typeof source.overlay === 'number' && Number.isFinite(source.overlay) ? Math.max(-1, Math.min(1, source.overlay)) : 0;
const position = BACKGROUND_POSITIONS.includes(source.position as typeof BACKGROUND_POSITIONS[number]) ? source.position as typeof BACKGROUND_POSITIONS[number] : 'center';
const size = BACKGROUND_SIZES.includes(source.size as typeof BACKGROUND_SIZES[number]) ? source.size as typeof BACKGROUND_SIZES[number] : 'cover';
if (image || imageId) result.newTabBackground = { ...(image ? { image } : {}), ...(imageId ? { imageId } : {}), overlay, position, size };
}
return result;
}
export function parseAppearance(raw: string | null): Appearance {
try { return normalizeAppearance(JSON.parse(raw || 'null')); }
@@ -28,8 +42,64 @@ const palettes = {
light: ['#fefcfc','#fefcfc','#dbeacb','#f8dbe6','#687788','#513346','#321c2a','#98556c','#ffc9dc'],
},
};
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'];
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]])) };
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
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; }
applyBackgroundImage(root);
try {
const file = await readBackgroundImage(id);
if (!file || backgroundRequests.get(root) !== id) return;
const url = URL.createObjectURL(file);
const old = backgroundUrls.get(root);
backgroundUrls.set(root, { image: id, url });
root.style.setProperty('--rs-new-tab-image', `url("${url}")`);
if (old) URL.revokeObjectURL(old.url);
} catch { /* Keep the theme usable if image storage is unavailable. */ }
}
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}")`);
return;
}
let url: string | undefined;
if (image) {
try {
const [header, data] = image.split(',');
const bytes = Uint8Array.from(atob(data), character => character.charCodeAt(0));
url = URL.createObjectURL(new Blob([bytes], { type: header.slice(5, header.indexOf(';')) }));
} catch { /* Invalid saved image data must not stop the theme update. */ }
}
// 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');
if (image && url) backgroundUrls.set(root, { image, url });
else backgroundUrls.delete(root);
if (previous) URL.revokeObjectURL(previous.url);
}
export function applyAppearance(value: Appearance, root = document.documentElement) {
const { theme, mode } = normalizeAppearance(value);
const { theme, mode, newTabBackground } = normalizeAppearance(value);
root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)');
const overlay = newTabBackground?.overlay ?? 0;
const shade = overlay < 0 ? '255,255,255' : '0,0,0';
root.style.setProperty('--rs-background-overlay', `linear-gradient(rgba(${shade},${Math.abs(overlay)}),rgba(${shade},${Math.abs(overlay)}))`);
root.style.setProperty('--rs-background-image', newTabBackground ? 'var(--rs-background-overlay), var(--rs-new-tab-image, none)' : 'none');
root.style.setProperty('--rs-background-position', newTabBackground?.position ?? 'center');
root.style.setProperty('--rs-background-size', newTabBackground?.size ?? 'cover');
void applySavedBackground(root, newTabBackground);
root.dataset.theme = mode;
root.dataset.palette = theme;
root.style.colorScheme = mode;
+46
View File
@@ -0,0 +1,46 @@
export const BACKGROUND_IMAGE_LIMIT = 50 * 1024 * 1024;
function database(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open('runestone-appearance', 1);
request.onupgradeneeded = () => request.result.createObjectStore('images');
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function saveBackgroundImage(file: Blob): Promise<string> {
if (file.size > BACKGROUND_IMAGE_LIMIT) throw new Error('Choose an image of 50 MiB or less.');
const db = await database();
const id = crypto.randomUUID();
try {
await new Promise<void>((resolve, reject) => {
const transaction = db.transaction('images', 'readwrite');
transaction.objectStore('images').put(file, id);
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
transaction.onabort = () => reject(transaction.error);
});
return id;
} finally { db.close(); }
}
export async function readBackgroundImage(id: string): Promise<Blob | undefined> {
const db = await database();
try {
return await new Promise<Blob | undefined>((resolve, reject) => {
const request = db.transaction('images').objectStore('images').get(id);
request.onsuccess = () => resolve(request.result instanceof Blob ? request.result : undefined);
request.onerror = () => reject(request.error);
});
} finally { db.close(); }
}
export async function removeBackgroundImage(id: string): Promise<void> {
const db = await database();
try {
await new Promise<void>((resolve, reject) => {
const transaction = db.transaction('images', 'readwrite');
transaction.objectStore('images').delete(id);
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
transaction.onabort = () => reject(transaction.error);
});
} finally { db.close(); }
}
+4 -3
View File
@@ -9,11 +9,12 @@
--rs-settings-section-gap: 16px;
--rs-menu-width: 248px;
--rs-menu-padding: 5px;
--rs-menu-row-height: 26px;
--rs-menu-row-padding: 3px 8px;
--rs-menu-row-height: 30px;
--rs-menu-row-padding: 4px 10px;
--rs-menu-icon-size: 14px;
--rs-menu-icon-gap: 8px;
--rs-menu-font-size: 12px;
--rs-menu-font-size: 13px;
--rs-menu-border: 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);
+5
View File
@@ -1,5 +1,10 @@
// Stroke icons share the same 24px grid and weight as IconButton.
export const actionIcons = {
archive: '<path d="M4 8v12h16V8M3 3h18v5H3zM9 12h6"/>',
save: '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/>',
refresh: '<path d="M20 7v5h-5M4 17v-5h5M6 7a7 7 0 0 1 12-1l2 3M4 15l2 3a7 7 0 0 0 12-1"/>',
'arrow-left': '<path d="M20 12H4m6-6-6 6 6 6"/>',
'arrow-right': '<path d="M4 12h16m-6-6 6 6-6 6"/>',
terminal: '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="m6 8 4 4-4 4m6 0h6"/>',
undo: '<path d="M3 10h11a7 7 0 0 1 0 14" transform="translate(0 -4)"/><path d="m7 2-4 4 4 4"/>',
redo: '<path d="M21 6H10a7 7 0 0 0 0 14"/><path d="m17 2 4 4-4 4"/>',
+11 -4
View File
@@ -1,4 +1,4 @@
import { actionIcon, type ActionIcon } from "./actionIcons";
import { actionIcon, type ActionIcon } from "./actionIcons.ts";
export type ActionMenuItem = { label: string; icon?: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; checked?: boolean; radio?: boolean; title?: string } | { separator: true };
@@ -23,13 +23,15 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
if (focus) panel.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus({ preventScroll: true });
}
function populate(panel: HTMLElement, entries: ActionMenuItem[]) {
const hasIcons = entries.some(item => !("separator" in item) && (!!item.icon || (item.checked !== undefined && !item.radio)));
panel.classList.toggle("rs-menu-text", !hasIcons);
for (const item of entries) {
if ("separator" in item) { const hr = document.createElement("hr"); hr.setAttribute("role", "separator"); panel.append(hr); continue; }
const button = document.createElement("button"); button.type = "button"; button.setAttribute("role", "menuitem"); button.disabled = !!item.disabled;
if (item.checked !== undefined) { button.setAttribute("role", item.radio ? "menuitemradio" : "menuitemcheckbox"); button.setAttribute("aria-checked", String(item.checked)); }
if (item.title) button.title = item.title;
const label = document.createElement("span"); label.className = "action-label"; label.textContent = item.label;
const icon = item.checked ? actionIcon("task") : item.icon ? actionIcon(item.icon) : document.createElement("span");
const icon = item.checked && !item.radio ? actionIcon("task") : item.icon ? actionIcon(item.icon) : document.createElement("span");
icon.classList.add("action-icon"); icon.setAttribute("aria-hidden", "true");
button.append(icon, label); panel.append(button);
if (item.shortcut) { const shortcut = document.createElement("span"); shortcut.textContent = item.shortcut; shortcut.style.cssText = "margin-left:auto;color:var(--rs-text-dim);font-size:12px;white-space:nowrap"; button.append(shortcut); }
@@ -39,7 +41,11 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
const submenu = document.createElement("div"); submenu.className = "rs-menu table-cell-submenu"; submenu.setAttribute("role", "menu"); submenu.setAttribute("aria-label", item.label); submenu.hidden = true;
populate(submenu, item.children); root.append(submenu); submenus.set(button, submenu);
button.addEventListener("mousemove", () => { if (!button.disabled) reveal(button, submenu); });
button.addEventListener("click", () => reveal(button, submenu, true));
button.addEventListener("click", event => {
event.stopPropagation();
if (item.run && !(event.target instanceof Node && arrow.contains(event.target))) item.run();
else reveal(button, submenu, true);
});
} else {
button.addEventListener("mousemove", () => hideSubmenu(panel));
button.addEventListener("click", event => { event.stopPropagation(); item.run?.(); });
@@ -68,6 +74,7 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
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:not(:disabled)")?.focus();
(root.querySelector<HTMLButtonElement>(':scope > button[role="menuitemradio"][aria-checked="true"]:not(:disabled)')
?? root.querySelector<HTMLButtonElement>(":scope > button:not(:disabled)"))?.focus();
return root;
}
+45
View File
@@ -0,0 +1,45 @@
import { actionMenu, type ActionMenuItem } from "./actionMenu.ts";
export type MenuOptions = { x: number; y: number; items: ActionMenuItem[]; label?: string; parent?: HTMLElement };
export function showActionMenu(options: MenuOptions, signal?: AbortSignal): { close(): void } {
const origin = document.activeElement instanceof HTMLElement ? document.activeElement : null;
// Focus can scroll a trigger before its queued scroll event reaches this menu.
const scrollPositions = new Map<EventTarget, [number, number]>();
for (let node: HTMLElement | null = origin; node; node = node.parentElement) {
scrollPositions.set(node, [node.scrollLeft, node.scrollTop]);
}
scrollPositions.set(document, [window.scrollX, window.scrollY]);
let root: HTMLElement | undefined;
const close = (restore = false) => {
root?.remove();
window.removeEventListener("pointerdown", outside, true);
window.removeEventListener("resize", dismiss);
window.removeEventListener("blur", dismiss);
document.removeEventListener("scroll", scroll, true);
signal?.removeEventListener("abort", dismiss);
if (restore && origin?.isConnected) origin.focus({ preventScroll: true });
};
const dismiss = () => close();
const outside = (event: PointerEvent) => { if (!root?.contains(event.target as Node)) close(); };
const scroll = (event: Event) => {
if (root?.contains(event.target as Node)) return;
const before = event.target && scrollPositions.get(event.target);
const current = event.target === document ? [window.scrollX, window.scrollY]
: event.target instanceof HTMLElement ? [event.target.scrollLeft, event.target.scrollTop] : undefined;
if (!before || !current || before[0] !== current[0] || before[1] !== current[1]) close();
};
const wrap = (items: ActionMenuItem[]): ActionMenuItem[] => items.map(item => "separator" in item ? item : {
...item,
...(item.children ? { children: wrap(item.children) } : {}),
...(!item.children || item.run ? { run: () => { close(true); if (!signal?.aborted) item.run?.(); } } : {}),
});
root = actionMenu(options.x, options.y, wrap(options.items), () => close(true), options.label ?? "Actions", options.parent);
window.addEventListener("pointerdown", outside, true);
window.addEventListener("resize", dismiss);
window.addEventListener("blur", dismiss);
document.addEventListener("scroll", scroll, true);
signal?.addEventListener("abort", dismiss, { once: true });
if (signal?.aborted) close();
return { close: () => close() };
}
+6 -3
View File
@@ -6,7 +6,7 @@
max-height: calc(100vh - 16px);
overflow-y: auto;
padding: var(--rs-menu-padding);
border: 1px solid var(--rs-border);
border: 1px solid var(--rs-menu-border);
border-radius: var(--rs-control-radius);
background: var(--rs-bg-elevated);
color: var(--rs-text);
@@ -33,10 +33,13 @@
}
.rs-menu > button:disabled { opacity: .4; cursor: default; }
.rs-menu > button[role="menuitemradio"][aria-checked="true"] { background: var(--rs-bg-active); }
.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);
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-basis: var(--rs-menu-icon-size); }
.rs-menu > button > .action-chevron { width: 13px; height: 13px; flex-basis: 13px; }
.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-label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.rs-menu > button > .action-chevron { width: 13px; height: 13px; flex: 0 0 13px; }
+7 -2
View File
@@ -3,8 +3,10 @@ import type { Token } from "markdown-it";
import { inlineMathEnd } from "./inlineMath.ts";
import { pluginHost } from "../plugins/registry.ts";
import { hasTableDelimiter } from "../editor/markdownTable.ts";
import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts";
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
markdown.use(footnotes);
export const escapeHtml = markdown.utils.escapeHtml;
// Require a row delimiter so deleting a blank line cannot turn prose into cells.
@@ -181,14 +183,17 @@ export function markdownImages(contents: string): string[] {
if (token.children) visit(token.children);
}
}
visit(markdown.parse(documentParts(contents).body, {}));
const env: FootnoteEnvironment = {};
visit(markdown.parse(documentParts(contents).body, env));
for (const note of env.noteFootnotes?.values() ?? []) visit(note.tokens);
return [...paths];
}
export function renderMarkdownHtml(contents: string, urls: Map<string, string>): string {
const { body, properties } = documentParts(contents);
const metadata = properties ? `<details class="md-properties"><summary>Properties</summary><pre>${escapeHtml(properties)}</pre></details>\n` : "";
return metadata + markdown.render(body, { urls });
const env = { urls };
return metadata + markdown.render(body, env) + renderFootnotes(markdown, env);
}
export type MarkdownSection = { start: number; end: number; html: string };
+2 -1
View File
@@ -12,7 +12,7 @@ export async function noteTemplates(): Promise<NoteTemplate[]> {
} catch { return []; }
}
export async function saveNoteTemplate(name: string, contents: string): Promise<void> {
export async function saveNoteTemplate(name: string, contents: string): Promise<string> {
const title = name.trim().replace(/\.md$/i, "");
if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) throw new Error("Enter a valid template name.");
const existing = await noteTemplates();
@@ -21,6 +21,7 @@ export async function saveNoteTemplate(name: string, contents: string): Promise<
await workspaceCreate(path, "file");
await workspaceWrite(path, contents, "");
window.dispatchEvent(new Event("runestone-templates-changed"));
return path;
}
export async function createNote(parent = "", template?: NoteTemplate): Promise<string> {