Update editor, workspace, Git services, appearance, and project guides
This commit is contained in:
+28
-18
@@ -17,9 +17,12 @@ body {
|
||||
color: var(--rs-text-strong);
|
||||
font-family: var(--rs-font-ui);
|
||||
font-size: 13px;
|
||||
font-weight: var(--rs-font-weight);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
h1, h2, h3, h4, h5, h6 { font-family: var(--rs-font-heading); }
|
||||
|
||||
button,
|
||||
input,
|
||||
textarea,
|
||||
@@ -96,25 +99,28 @@ button:disabled {
|
||||
min-width: 0;
|
||||
margin: 0 auto;
|
||||
color: var(--rs-text);
|
||||
font: var(--rs-prose-size)/1.75 var(--rs-font-prose);
|
||||
font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.reading h1, .reading h2, .reading h3,
|
||||
.reading h4, .reading h5, .reading h6 {
|
||||
.reading h4, .reading h5, .reading h6, .live-writer .writer-heading {
|
||||
color: var(--rs-text-strong);
|
||||
font-weight: 650;
|
||||
line-height: 1.3;
|
||||
font-family: var(--rs-font-heading);
|
||||
font-weight: var(--rs-heading-weight);
|
||||
line-height: 1.4;
|
||||
letter-spacing: -0.02em;
|
||||
margin: 1.8em 0 0.65em;
|
||||
margin: .9em 0 .4em;
|
||||
scroll-margin-top: 24px;
|
||||
}
|
||||
.reading h1 { font-size: 2.1em; margin-top: 0; margin-bottom: 0.8em; }
|
||||
.reading h2 { font-size: 1.5em; padding-bottom: 0.4em; border-bottom: 1px solid var(--rs-border); }
|
||||
.reading h3 { font-size: 1.2em; }
|
||||
.reading h4 { font-size: 1.05em; }
|
||||
.reading h5, .reading h6 { font-size: 1em; color: var(--rs-text-dim); }
|
||||
.document-title, .reading .document-title { margin: 0 0 .85em; color: var(--rs-text-strong); font: 650 2em/1.3 var(--rs-font-prose); overflow-wrap: anywhere; }
|
||||
.reading h1, .live-writer .writer-h1 { font-size: 1.6em; }
|
||||
.reading h2, .live-writer .writer-h2 { font-size: 1.35em; }
|
||||
.reading h1:not(.document-title), .reading h2, .live-writer .writer-h1, .live-writer .writer-h2 { padding-bottom: .25em; border-bottom: 1px solid var(--rs-border); }
|
||||
.reading h3, .live-writer .writer-h3 { font-size: 1.15em; }
|
||||
.reading h4, .live-writer .writer-h4 { font-size: 1.05em; }
|
||||
.reading h5, .reading h6, .live-writer .writer-h5, .live-writer .writer-h6 { font-size: 1em; color: var(--rs-text-dim); }
|
||||
.live-writer .writer-heading { margin: 0; padding-top: .3em; }
|
||||
.document-title, .reading .document-title { margin: 0 0 .85em; color: var(--rs-text-strong); font: var(--rs-heading-weight) 1.8em/1.3 var(--rs-font-heading); overflow-wrap: anywhere; }
|
||||
.note-title-button { position: relative; display: inline-flex; align-items: center; gap: 12px; max-width: 100%; padding: 0; border: 0; background: transparent; color: inherit; font: inherit; text-align: left; overflow-wrap: anywhere; cursor: text; }
|
||||
.note-title-button .action-icon { opacity: .45; }
|
||||
.note-title-button:hover .action-icon, .note-title-button:focus-visible .action-icon { opacity: 1; color: var(--rs-accent); }
|
||||
@@ -126,14 +132,14 @@ button:disabled {
|
||||
.note-title-error { margin: -.8em 0 1em; color: var(--rs-danger, #e57878); font: 13px/1.5 var(--rs-font-ui); }
|
||||
.note-title-button[hidden], .note-title-input[hidden], .note-title-error[hidden] { display: none; }
|
||||
.reading > :first-child { margin-top: 0; }
|
||||
.reading p { margin: 0 0 1.1em; }
|
||||
.reading strong { font-weight: 650; color: var(--rs-text-strong); }
|
||||
.reading p { margin: 0 0 .75em; white-space: pre-line; }
|
||||
.reading strong { font-weight: 600; color: var(--rs-text-strong); }
|
||||
.reading a { color: var(--rs-accent); text-decoration-thickness: 1px; text-underline-offset: 3px; }
|
||||
.reading a:hover { color: var(--rs-accent-2); }
|
||||
.reading hr { border: 0; border-top: 1px solid var(--rs-border); margin: 2em 0; }
|
||||
|
||||
.reading ul, .reading ol { padding-left: 1.6em; margin: 0 0 1.2em; }
|
||||
.reading li { padding-left: 0.25em; margin: 0.35em 0; }
|
||||
.reading ul, .reading ol { padding-left: 1.6em; margin: 0 0 .75em; }
|
||||
.reading li { padding-left: 0.25em; margin: .1em 0; }
|
||||
.reading li::marker { color: var(--rs-text-dim); }
|
||||
.reading li > p { margin-bottom: 0.6em; }
|
||||
.reading li > ul, .reading li > ol { margin: 0.35em 0 0.5em; }
|
||||
@@ -224,7 +230,7 @@ button:disabled {
|
||||
.rs-fence-copy:hover { color: var(--rs-text-strong); background: var(--rs-bg-active); }
|
||||
.rs-fence-copy[data-copied] { color: var(--rs-ok); }
|
||||
|
||||
.reading .md-table-scroll { overflow-x: auto; margin: 1.4em 0; border: 1px solid var(--rs-border); border-radius: 0; }
|
||||
.reading .md-table-scroll { width: fit-content; max-width: 100%; overflow-x: auto; margin: 1.4em 0; border: 1px solid var(--rs-border); border-radius: 0; }
|
||||
.md-table-formula { color: var(--rs-accent); font-variant-numeric: tabular-nums; }
|
||||
.md-table-formula.is-error { color: var(--rs-danger, #ed8796); text-decoration: underline dotted; }
|
||||
.table-footer { display: grid; gap: 8px; margin: 0 26px 1.4em; min-width: 0; font: 12px/1.5 var(--rs-font-ui); color: var(--rs-text-dim); white-space: normal; overflow-wrap: anywhere; }
|
||||
@@ -243,10 +249,11 @@ button:disabled {
|
||||
.table-formula-hint { padding: 8px 10px; border-left: 2px solid var(--rs-accent); background: var(--rs-bg-elevated); color: var(--rs-text); }
|
||||
.table-formula-hint[hidden] { display: none; }
|
||||
.table-edit-help { font: inherit; color: var(--rs-text-dim); }
|
||||
.reading table { border-collapse: collapse; width: 100%; font-size: 0.9em; overflow-wrap: normal; word-break: normal; }
|
||||
.reading th, .reading td { padding: 10px 14px; text-align: left; vertical-align: top; border-bottom: 1px solid var(--rs-border); min-width: 8rem; max-width: 26rem; white-space: normal; overflow-wrap: break-word; }
|
||||
.reading table { border-collapse: collapse; width: auto; max-width: 100%; font-size: 0.95em; line-height: var(--rs-table-line-height); overflow-wrap: normal; word-break: normal; }
|
||||
.reading th, .reading td { padding: var(--rs-table-cell-padding); text-align: left; vertical-align: top; border-bottom: 1px solid var(--rs-border); min-width: 3rem; max-width: 26rem; white-space: normal; overflow-wrap: break-word; }
|
||||
.reading :is(th, td):empty::before,
|
||||
.reading :is(th, td) > p:empty::before { content: "\200b"; }
|
||||
.reading :is(th, td) > p { margin: 0; }
|
||||
.reading th { background: var(--rs-bg-active); font-weight: 600; color: var(--rs-text-strong); }
|
||||
.reading tbody tr:nth-child(even) { background: var(--rs-line-highlight); }
|
||||
.reading tbody tr:last-child td { border-bottom: 0; }
|
||||
@@ -388,3 +395,6 @@ button:disabled {
|
||||
.reading .md-inline-math { font-family: var(--rs-font-mono); font-style: italic; }
|
||||
.reading .md-inline-comment { display: none; }
|
||||
.writer-table .md-inline-comment { display: inline; color: var(--rs-text-dim); background: var(--rs-bg-active); }
|
||||
|
||||
.reading:not(.cm-content) :is(p, h1, h2, h3, h4, h5, h6):not(td *, th *) { position: relative; }
|
||||
.reading:not(.cm-content) :is(p, h1, h2, h3, h4, h5, h6):not(td *, th *):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; }
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import IconButton from '$lib/ui/IconButton.svelte';
|
||||
import { state as browserState, request } from './client';
|
||||
let { open }: { open: (profileId: string, url: string) => Promise<void> } = $props();
|
||||
let error = $state('');
|
||||
onMount(() => { void request('state').catch(reason => error = String(reason)); });
|
||||
</script>
|
||||
<div class="bookmarks">
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
{#each $browserState?.bookmarks || [] as item (item.id)}
|
||||
<div class="row"><button class="link" title={item.url} onclick={() => void open(item.profileId, item.url)}><Icon icon="globe" /><span>{item.title}</span></button><IconButton icon="close" label={`Remove ${item.title}`} onclick={() => void request('removeBookmark', { id: item.id })} /></div>
|
||||
{/each}
|
||||
</div>
|
||||
<style>
|
||||
.bookmarks{color:var(--rs-text);font-family:var(--rs-font-ui)}.row{display:flex;align-items:center;padding:0 5px;border-radius:var(--rs-control-radius)}.row:hover{background:var(--rs-bg-active)}
|
||||
.link{display:flex;align-items:center;gap:8px;flex:1;min-width:0;padding:7px 5px;border:0;border-radius:var(--rs-control-radius);color:inherit;background:transparent;text-align:left;cursor:pointer}
|
||||
span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.link:focus-visible{outline:2px solid var(--rs-accent)}p{color:var(--rs-error);padding:8px;font-size:12px}
|
||||
</style>
|
||||
@@ -0,0 +1,204 @@
|
||||
<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 { 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 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);
|
||||
const ready = $derived(status.phase === 'ready');
|
||||
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 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 pendingMove: Record<string, unknown> | undefined;
|
||||
let suppressedRelease = -1;
|
||||
const result = $derived(current?.find?.text === findText ? current.find : null);
|
||||
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
|
||||
$effect(() => {
|
||||
void documentKey;
|
||||
untrack(stopScroll);
|
||||
if (ready && findOpen) untrack(() => { if (findText && !current?.loading) search(); });
|
||||
});
|
||||
export async function find() {
|
||||
findOpen = true;
|
||||
await tick(); findField?.focus(); findField?.select();
|
||||
}
|
||||
export function detach() { connection.detach(); }
|
||||
export function action(command: string, args: Record<string, unknown> = {}) { return send(command, args); }
|
||||
function search(next = false, forward = true) {
|
||||
clearTimeout(findTimer);
|
||||
void send('find', { text: findText, next, forward });
|
||||
}
|
||||
function closeFind() { clearTimeout(findTimer); findOpen = false; void send('stopFind'); surface.focus(); }
|
||||
function findKey(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeFind(); }
|
||||
else if (event.key === 'Enter' && event.target === findField) { event.preventDefault(); event.stopPropagation(); search(true, !event.shiftKey); }
|
||||
}
|
||||
$effect(() => { if (!editing && current?.url) address = current.url === 'about:blank' ? '' : current.url; });
|
||||
$effect(() => {
|
||||
const id = tabId;
|
||||
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}`;
|
||||
});
|
||||
return () => { frames.delete(id); };
|
||||
});
|
||||
$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; });
|
||||
await connection.send(command, args);
|
||||
}
|
||||
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
|
||||
if (opening) return;
|
||||
opening = true;
|
||||
try { openingError = ''; await newTab(profileId); } catch (error) { openingError = `Could not open a browser tab: ${String(error)}`; }
|
||||
finally { opening = false; }
|
||||
}
|
||||
onMount(() => {
|
||||
mounted = true;
|
||||
const offState = browserState.subscribe(value => { if (value) connection.observe(value); });
|
||||
void connection.connect();
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const resize = new ResizeObserver(entries => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(syncSize, 100);
|
||||
});
|
||||
resize.observe(surface);
|
||||
return () => { mounted = false; stopScroll(); 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 });
|
||||
}
|
||||
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 scrollStep(time: number) {
|
||||
if (!autoScroll.anchor || !ready) { stopScroll(); return; }
|
||||
const delta = autoScroll.delta(time);
|
||||
if (delta && !wheelPending && (delta.x || delta.y)) {
|
||||
wheelPending = true;
|
||||
const rect = surface.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) { wheelPending = false; 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);
|
||||
}
|
||||
scrollFrame = requestAnimationFrame(scrollStep);
|
||||
}
|
||||
function flushMove() {
|
||||
moveFrame = 0;
|
||||
if (!pendingMove || movePending) return;
|
||||
const input = pendingMove; pendingMove = undefined; movePending = true;
|
||||
void send('input', { input }).finally(() => {
|
||||
movePending = false;
|
||||
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove);
|
||||
});
|
||||
}
|
||||
function pointer(event: MouseEvent | WheelEvent, type: string) {
|
||||
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') surface.focus();
|
||||
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; }
|
||||
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
|
||||
if (type === 'mouseDown' && event.button === 1 && ready) {
|
||||
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0;
|
||||
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); return;
|
||||
}
|
||||
if (autoScroll.anchor) {
|
||||
if (type === 'mouseMove') autoScroll.move(point);
|
||||
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
|
||||
if (type === 'mouseWheel') stopScroll(); else return;
|
||||
}
|
||||
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 } : {}) };
|
||||
if (type === 'mouseMove') {
|
||||
pendingMove = input;
|
||||
if (!moveFrame && !movePending) moveFrame = requestAnimationFrame(flushMove);
|
||||
} else { pendingMove = undefined; void send('input', { input }); }
|
||||
}
|
||||
function key(event: KeyboardEvent, type: string) {
|
||||
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 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 } });
|
||||
}
|
||||
</script>
|
||||
<svelte:window onblur={stopScroll} />
|
||||
<svelte:document onvisibilitychange={() => { if (document.hidden) stopScroll(); }} />
|
||||
<div class="browser" data-browser-tab={tabId} data-browser-state={status.phase}>
|
||||
<form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}>
|
||||
<IconButton icon="arrow-left" label="Back" disabled={!ready || !current?.canBack} onclick={() => void send('back')} />
|
||||
<IconButton icon="arrow-right" label="Forward" disabled={!ready || !current?.canForward} onclick={() => void send('forward')} />
|
||||
<IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : 'Reload'} disabled={!ready} onclick={() => void send(current?.loading ? 'stop' : 'reload')} />
|
||||
<input bind:this={addressField} bind:value={address} disabled={!ready} onfocus={() => editing = true} onblur={() => editing = false} aria-label="Address or search" placeholder="Search or enter an address" spellcheck="false" autocomplete="off">
|
||||
<IconButton icon="bookmark" label="Bookmark this page" disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} />
|
||||
<select aria-label="Browser profile" value={current?.profileId} disabled={opening} onchange={event => void openTab(event.currentTarget.value)}>
|
||||
{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}
|
||||
</select>
|
||||
</form>
|
||||
{#if findOpen}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) -->
|
||||
<form class="findbar" role="search" aria-label="Find in page" onkeydown={findKey} onsubmit={event => { event.preventDefault(); search(true); }}>
|
||||
<input bind:this={findField} bind:value={findText} aria-label="Find in page" placeholder="Find in page" maxlength="1000" autocomplete="off" spellcheck="false"
|
||||
disabled={!ready} oninput={() => { clearTimeout(findTimer); findTimer = setTimeout(() => search(), 120); }}>
|
||||
<span class="find-count" role="status" aria-live="polite">{!findText ? '' : !result || result.pending ? 'Searching…' : result.matches ? `${result.activeMatch} of ${result.matches}` : 'No matches'}</span>
|
||||
<IconButton icon="up" label="Previous match (Shift+Enter)" disabled={!ready || !findText} onclick={() => search(true, false)} />
|
||||
<IconButton icon="down" label="Next match (Enter)" disabled={!ready || !findText} onclick={() => search(true)} />
|
||||
<IconButton icon="close" label="Close find (Escape)" onclick={closeFind} />
|
||||
</form>
|
||||
{/if}
|
||||
{#if status.phase === 'connecting'}<p class="status" role="status">{status.message}</p>{/if}
|
||||
{#if ready && status.message}<p class="error" role="alert">{status.message}</p>{/if}
|
||||
{#if status.phase === 'disconnected'}
|
||||
<div class="error" role="alert"><p>{status.message}</p><button class="reconnect" onclick={() => void connection.connect()}>Reconnect</button></div>
|
||||
{/if}
|
||||
{#if status.detail}
|
||||
<details class="diagnostics"><summary>Browser error details</summary><dl>
|
||||
<dt>Operation</dt><dd>{status.detail.operation}</dd><dt>Reason</dt><dd>{status.detail.reason}</dd>
|
||||
<dt>Tab</dt><dd>{status.detail.tabId || 'Not created'}</dd><dt>Time</dt><dd>{status.detail.time}</dd>
|
||||
<dt>Browser</dt><dd>Included with RuneStone</dd>
|
||||
</dl></details>
|
||||
{/if}
|
||||
{#if openingError || $pageErrors[tabId]}<p class="error" role="alert">{openingError || $pageErrors[tabId]}</p>{/if}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (This surface forwards native browser input.) -->
|
||||
<div class="surface" class:autoscroll={!!scrollAnchor} bind:this={surface} role="application" aria-label="Web page" tabindex="0"
|
||||
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
|
||||
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
|
||||
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}
|
||||
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
<style>
|
||||
.browser{display:flex;flex-direction:column;width:100%;height:100%;min-height:200px;background:var(--rs-bg);color:var(--rs-text);font-family:var(--rs-font-ui)}
|
||||
.toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)}
|
||||
.toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px}
|
||||
input,select{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
|
||||
input{flex:1}select{max-width:160px}input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent)}
|
||||
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
|
||||
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006}
|
||||
img{display:block;width:100%;height:100%;pointer-events:none;user-select:none}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
|
||||
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
|
||||
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
|
||||
.reconnect:focus-visible,summary:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}summary{cursor:pointer}
|
||||
dl{display:grid;grid-template-columns:auto 1fr;gap:4px 12px}dd{margin:0;overflow-wrap:anywhere;user-select:text}
|
||||
</style>
|
||||
@@ -0,0 +1,73 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
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);
|
||||
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;
|
||||
homepage = value.settings.homepage || ''; filterLists = (value.settings.filterLists || []).join('\n'); ready = true;
|
||||
}).catch(error => message = String(error)); });
|
||||
async function act(command: string, args: Record<string, unknown>) {
|
||||
try { const next = await request(command, args); message = 'Changes saved.'; return next; } catch (error) { message = String(error); return null; }
|
||||
}
|
||||
async function create(duplicate: boolean) {
|
||||
if (!name.trim()) { message = 'Enter a profile name.'; return; }
|
||||
const result = await act(duplicate ? 'duplicateProfile' : 'createProfile', duplicate ? { profileId: selected, name } : { name });
|
||||
if (result) { selected = result.profiles.at(-1)!.id; name = ''; }
|
||||
}
|
||||
async function save() {
|
||||
busy = true; message = 'Saving browser settings…';
|
||||
try {
|
||||
await act('settings', { search, adblock, linkDestination: internalLinks ? 'internal' : 'external', personalRules: rules,
|
||||
homepage, filterLists: filterLists.split(/\r?\n/).map(value => value.trim()).filter(Boolean) });
|
||||
} finally { busy = false; }
|
||||
}
|
||||
</script>
|
||||
<div class="settings">
|
||||
<h2>Browser</h2><p>Choose how you browse within RuneStone.</p>
|
||||
<h3>General</h3>
|
||||
<form onsubmit={event => { event.preventDefault(); if (ready && !busy) void save(); }}>
|
||||
<fieldset disabled={!ready || busy}>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
<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>
|
||||
</div>
|
||||
<h3>Web data</h3><p>Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.</p>
|
||||
<div class="actions"><button onclick={() => void act('clearData', { profileId: selected, kind: 'cache' })}>Clear cache</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'cookies' })}>Clear cookies</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'history' })}>Clear history</button></div>
|
||||
<p role="status">{message}</p>
|
||||
{#if ready}<WebData profileId={selected} />{/if}
|
||||
</div>
|
||||
<style>
|
||||
.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}
|
||||
.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}
|
||||
.switch{appearance:none;position:relative;flex:none;width:44px;height:26px;border:0;border-radius:999px;background:var(--rs-text-dim);padding:0;cursor:pointer;transition:background .15s}
|
||||
.switch::before{content:'';position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:50%;background:var(--rs-bg);box-shadow:0 1px 3px #0004;transition:transform .15s}
|
||||
.switch:checked{background:var(--rs-accent)}.switch:checked::before{transform:translateX(18px)}:disabled{opacity:.6;cursor:wait}
|
||||
@media(prefers-reduced-motion:reduce){.switch,.switch::before{transition:none}}
|
||||
@media(max-width:600px){.row{flex-wrap:wrap}.address,.list-row textarea{width:100%;max-width:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script lang="ts">
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import { request } from './client';
|
||||
let { profileId }: { profileId: string } = $props();
|
||||
type Cookie = { id: string; name: string; domain: string; path: string };
|
||||
type Visit = { id: string; url: string; title: string; at: number };
|
||||
type Data = { profileId: string; cookies: Cookie[]; history: Visit[] };
|
||||
let data = $state<Data | null>(null), error = $state(''), busy = $state(false), query = $state('');
|
||||
let kind = $state<'cookies' | 'history'>('cookies');
|
||||
let generation = 0;
|
||||
const cookies = $derived((data?.cookies || []).filter(item => `${item.domain} ${item.name} ${item.path}`.toLowerCase().includes(query.toLowerCase())));
|
||||
const history = $derived((data?.history || []).filter(item => `${item.title} ${item.url}`.toLowerCase().includes(query.toLowerCase())));
|
||||
$effect(() => { const id = profileId; data = null; query = ''; void refresh(id); return () => { generation++; }; });
|
||||
async function refresh(id = profileId) {
|
||||
const ticket = ++generation; busy = true; error = '';
|
||||
try { const next = await request<Data>('webData', { profileId: id }); if (ticket === generation && id === profileId) data = next; }
|
||||
catch (reason) { if (ticket === generation) error = String(reason); }
|
||||
finally { if (ticket === generation) busy = false; }
|
||||
}
|
||||
async function remove(command: string, id: string) {
|
||||
const selected = profileId; const ticket = ++generation; busy = true; error = '';
|
||||
try { await request(command, { profileId: selected, id }); if (ticket === generation && selected === profileId) await refresh(selected); }
|
||||
catch (reason) { if (ticket === generation) error = String(reason); }
|
||||
finally { if (ticket === generation) busy = false; }
|
||||
}
|
||||
</script>
|
||||
<section aria-label="Individual web data">
|
||||
<div class="toolbar">
|
||||
<label>Show<select aria-label="Web data type" bind:value={kind}><option value="cookies">Cookies</option><option value="history">History</option></select></label>
|
||||
<label class="search">Filter<input type="search" aria-label="Filter web data" bind:value={query} placeholder="Search this profile"></label>
|
||||
<button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />Refresh</button>
|
||||
</div>
|
||||
<p>Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.</p>
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
{#if busy}<p role="status">Please wait…</p>{/if}
|
||||
<div class="entries" aria-busy={busy}>
|
||||
{#if kind === 'cookies'}
|
||||
{#each cookies as cookie (cookie.id)}<div class="entry"><div><strong>{cookie.name || '(unnamed cookie)'}</strong><small>{cookie.domain} · {cookie.path}</small></div><button disabled={busy} aria-label={`Remove cookie ${cookie.name} from ${cookie.domain} at ${cookie.path}`} onclick={() => void remove('removeCookie', cookie.id)}><Icon icon="trash" />Remove</button></div>{/each}
|
||||
{#if data && !cookies.length}<p>No matching cookies.</p>{/if}
|
||||
{:else}
|
||||
{#each history as visit (visit.id)}<div class="entry"><div><strong>{visit.title || visit.url}</strong><small>{visit.url}</small><small>{new Date(visit.at).toLocaleString()}</small></div><button disabled={busy} aria-label={`Remove history entry ${visit.title || visit.url}`} onclick={() => void remove('removeHistory', visit.id)}><Icon icon="trash" />Remove</button></div>{/each}
|
||||
{#if data && !history.length}<p>No matching history.</p>{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
<style>
|
||||
section{margin-top:var(--rs-settings-section-gap)}.toolbar{display:flex;align-items:end;gap:var(--rs-settings-gap);flex-wrap:wrap}
|
||||
label{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,select,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
|
||||
button{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;cursor:pointer}button:hover{background:var(--rs-bg-active)}button:disabled{opacity:.6;cursor:wait}
|
||||
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
|
||||
p,small{font-size:var(--rs-settings-description-size);color:var(--rs-text-dim);line-height:1.5}.entries{max-height:320px;overflow:auto;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);padding:0 var(--rs-settings-row-padding)}
|
||||
.entry{display:flex;gap:var(--rs-settings-gap);align-items:center;padding:var(--rs-settings-row-padding) 0}.entry+.entry{border-top:1px solid var(--rs-border)}.entry>div{flex:1;min-width:0;overflow-wrap:anywhere}small{display:block}strong{font-weight:500}[role=alert]{color:var(--rs-error)}
|
||||
@media(max-width:450px){.entry{flex-wrap:wrap}.entry>div{flex-basis:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,23 @@
|
||||
export type ScrollPoint = { x: number; y: number };
|
||||
|
||||
/** Middle-button scrolling uses wheel input because offscreen Chromium has no native scroll cursor. */
|
||||
export class AutoScroll {
|
||||
anchor: ScrollPoint | null = null;
|
||||
private point: ScrollPoint = { x: 0, y: 0 };
|
||||
private moved = false;
|
||||
private previous = 0;
|
||||
start(point: ScrollPoint) { this.anchor = { ...point }; this.point = { ...point }; this.moved = false; this.previous = 0; }
|
||||
move(point: ScrollPoint) {
|
||||
this.point = point;
|
||||
if (this.anchor && Math.hypot(point.x - this.anchor.x, point.y - this.anchor.y) > 12) this.moved = true;
|
||||
}
|
||||
release() { if (this.moved) this.stop(); }
|
||||
stop() { this.anchor = null; this.previous = 0; }
|
||||
delta(time: number) {
|
||||
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);
|
||||
return { x: speed(this.point.x - this.anchor.x) * elapsed / 1000, y: speed(this.point.y - this.anchor.y) * elapsed / 1000 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import { writable } from 'svelte/store';
|
||||
import { SnapshotOrder } from './snapshotOrder';
|
||||
|
||||
export type Profile = { id: string; name: string };
|
||||
export type Tab = { id: string; transferToken?: string; profileId: string; title: string; favicon?: string | null; url: string; loading: boolean; blocked: number; canBack: boolean; canForward: boolean; find?: { text: string; matches: number; activeMatch: number; pending: boolean } | null };
|
||||
export type Snapshot = {
|
||||
runtimeId?: string; revision?: number;
|
||||
profiles: Profile[]; tabs: Tab[];
|
||||
bookmarks: { id: string; profileId: string; title: string; url: string }[];
|
||||
settings: { search: string; adblock: boolean; linkDestination: string; personalRules: string; homepage: string; filterLists: string[] };
|
||||
};
|
||||
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>();
|
||||
let snapshots = new SnapshotOrder();
|
||||
let session: string | undefined;
|
||||
function isSnapshot(value: unknown): value is Snapshot {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return Array.isArray(record.profiles) && Array.isArray(record.tabs) && Array.isArray(record.bookmarks) && !!record.settings && typeof record.settings === 'object';
|
||||
}
|
||||
export async function request<T = Snapshot>(command: string, args: Record<string, unknown> = {}): Promise<T> {
|
||||
const result = await invoke<T>('browser_request', { command, args, session });
|
||||
if (isSnapshot(result) && snapshots.accept(result)) state.set(result);
|
||||
return result;
|
||||
}
|
||||
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 }) => {
|
||||
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! }));
|
||||
});
|
||||
const offFrame = await window.listen<{ tabId: string; png: string; width: number; height: number }>('browser-frame', ({ payload }) => {
|
||||
if (!signal.aborted) frames.get(payload.tabId)?.(payload);
|
||||
});
|
||||
const stop = async () => { offState(); offFrame(); frames.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
|
||||
if (signal.aborted) await stop();
|
||||
return stop;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { mount, unmount } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import type { PluginApi, PluginViewOpenOptions } from '$lib/plugins/sdk';
|
||||
import Browser from './Browser.svelte';
|
||||
import Settings from './Settings.svelte';
|
||||
import Bookmarks from './Bookmarks.svelte';
|
||||
import { connect, request, state } from './client';
|
||||
import type { TabStatus } from './tabSession';
|
||||
|
||||
type BrowserControl = { find(): Promise<void>; detach(): void; action(command: string, args?: Record<string, unknown>): Promise<void> };
|
||||
type SavedView = { view: string; profileId?: string; url?: string; runtimeId: string; status?: TabStatus; control?: BrowserControl };
|
||||
|
||||
export async function activate(api: PluginApi) {
|
||||
const dispose = await connect(api.signal); api.onDispose(dispose);
|
||||
const owners = new Map<string, SavedView>();
|
||||
const offMove = await getCurrentWebviewWindow().listen<{ tabId: string }>('browser-tab-moved', ({ payload }) => {
|
||||
const saved = owners.get(payload.tabId);
|
||||
if (!saved) return;
|
||||
saved.control?.detach();
|
||||
api.closeView?.(saved.view);
|
||||
});
|
||||
api.onDispose(offMove);
|
||||
const off = state.subscribe(value => {
|
||||
for (const tab of value?.tabs || []) {
|
||||
const saved = owners.get(tab.id);
|
||||
if (saved) {
|
||||
saved.profileId = tab.profileId; if (tab.url) saved.url = tab.url;
|
||||
api.updateViewTitle?.(saved.view, `${tab.title || 'Browser'} · ${value!.profiles.find(p => p.id === tab.profileId)?.name || 'User'}`.slice(0, 200));
|
||||
api.updateViewIcon?.(saved.view, tab.favicon ?? null);
|
||||
}
|
||||
}
|
||||
});
|
||||
api.onDispose(off);
|
||||
const mounts = new Set<() => Promise<void>>();
|
||||
function retain(instance: ReturnType<typeof mount>) {
|
||||
let result: Promise<void> | undefined;
|
||||
const cleanup = () => result ??= unmount(instance).then(() => { mounts.delete(cleanup); });
|
||||
mounts.add(cleanup); return cleanup;
|
||||
}
|
||||
api.onDispose(async () => { await Promise.all([...mounts].map(cleanup => cleanup())); });
|
||||
async function open(profileId?: string, url?: string, options?: PluginViewOpenOptions, tabId?: string, pinned = false) {
|
||||
const id = `tab-${crypto.randomUUID()}`;
|
||||
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
|
||||
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
|
||||
const split = (direction: 'right' | 'down') => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { split: direction, relativeTo: id });
|
||||
};
|
||||
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
|
||||
tabDragData: ({ pinned }) => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
if (saved.status?.phase !== 'ready' || !current?.transferToken) return undefined;
|
||||
return JSON.stringify({ tabId: current.id, transferToken: current.transferToken, pinned });
|
||||
},
|
||||
find: () => { api.openView(id); void saved.control?.find(); },
|
||||
tabActions: ({ pinned }) => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
const ready = saved.status?.phase === 'ready';
|
||||
const web = ready && /^https?:\/\//.test(current?.url || '');
|
||||
return [
|
||||
{ separator: true },
|
||||
{ label: 'Move to new window', icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
|
||||
{ label: 'Split right', icon: 'split-right', disabled: !ready, run: () => split('right') },
|
||||
{ label: 'Split down', icon: 'split-down', disabled: !ready, run: () => split('down') },
|
||||
{ separator: true },
|
||||
{ label: 'Find…', icon: 'search', shortcut: 'Ctrl+F', disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
|
||||
{ label: 'Open in default browser', icon: 'external', disabled: !web, run: () => run('openExternal') },
|
||||
{ label: 'Bookmark', icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
|
||||
];
|
||||
}, mount: container => {
|
||||
let runtimeId = '';
|
||||
const instance = mount(Browser, { target: container, props: {
|
||||
initial: { tabId, profileId: saved.profileId, url: saved.url },
|
||||
onSessionChange: value => {
|
||||
saved.status = value;
|
||||
if (value.tabId !== runtimeId || value.phase === 'closed') {
|
||||
owners.delete(runtimeId);
|
||||
runtimeId = value.phase === 'closed' ? '' : value.tabId;
|
||||
if (runtimeId) owners.set(runtimeId, saved);
|
||||
}
|
||||
saved.runtimeId = runtimeId;
|
||||
api.updateViewIcon?.(saved.view, get(state)?.tabs.find(tab => tab.id === runtimeId)?.favicon ?? null);
|
||||
if (value.profileId) saved.profileId = value.profileId;
|
||||
if (value.url) saved.url = value.url;
|
||||
},
|
||||
newTab: (profile: string) => open(profile),
|
||||
} });
|
||||
tabId = undefined;
|
||||
saved.control = instance;
|
||||
const cleanup = retain(instance);
|
||||
return async () => { await cleanup(); if (saved.control === instance) saved.control = undefined; };
|
||||
} });
|
||||
api.openView(id, options);
|
||||
}
|
||||
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run: () => open() });
|
||||
api.contribute('browser', {
|
||||
newTab: () => open(),
|
||||
mountSettings: container => retain(mount(Settings, { target: container })),
|
||||
mountBookmarks: container => retain(mount(Bookmarks, { target: container, props: { open } })),
|
||||
open: async url => {
|
||||
const value = await request('state');
|
||||
if (value.settings.linkDestination === 'external') return false;
|
||||
await open(undefined, url); return true;
|
||||
},
|
||||
});
|
||||
api.registerTabDrop?.(async data => {
|
||||
const payload = JSON.parse(data);
|
||||
if (!payload || typeof payload.tabId !== 'string' || typeof payload.transferToken !== 'string') throw new Error('Invalid browser tab transfer.');
|
||||
const existing = owners.get(payload.tabId);
|
||||
if (existing) { api.openView(existing.view); return; }
|
||||
const snapshot = await request('adoptTab', { tabId: payload.tabId, transferToken: payload.transferToken });
|
||||
const current = snapshot.tabs.find(tab => tab.id === payload.tabId);
|
||||
if (!current) throw new Error('The browser tab is unavailable.');
|
||||
await open(current.profileId, current.url, undefined, current.id, payload.pinned === true);
|
||||
});
|
||||
const incoming = new URLSearchParams(location.search).get('browserTab');
|
||||
if (incoming) {
|
||||
const snapshot = await request('adoptTab', { tabId: incoming });
|
||||
const current = snapshot.tabs.find(tab => tab.id === incoming);
|
||||
await open(current?.profileId, current?.url, undefined, incoming, new URLSearchParams(location.search).get('browserPinned') === 'true');
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.delete('browserTab'); url.searchParams.delete('browserPinned');
|
||||
history.replaceState(null, '', url.pathname + url.search);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export class SnapshotOrder {
|
||||
private runtimeId = '';
|
||||
private revision = -1;
|
||||
private retired = new Set<string>();
|
||||
|
||||
accept(value: { runtimeId?: string; revision?: number }): boolean {
|
||||
if (!value.runtimeId || !Number.isSafeInteger(value.revision)) return true;
|
||||
if (this.retired.has(value.runtimeId)) return false;
|
||||
if (value.runtimeId !== this.runtimeId) {
|
||||
if (this.runtimeId) this.retired.add(this.runtimeId);
|
||||
this.runtimeId = value.runtimeId;
|
||||
this.revision = -1;
|
||||
}
|
||||
if (value.revision! <= this.revision) return false;
|
||||
this.revision = value.revision!;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { Snapshot } from './client';
|
||||
|
||||
type Transport = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||
export type TabStatus = {
|
||||
tabId: string; profileId?: string; url?: string;
|
||||
phase: 'connecting' | 'ready' | 'disconnected' | 'closed';
|
||||
message: string;
|
||||
detail?: { operation: string; reason: string; tabId: string; time: string };
|
||||
};
|
||||
const connectionLost = (error: unknown) => /Unknown browser tab|stopped responding|timed out|response did not match|broken pipe|os error (109|232|10053|10054)\b/i.test(String(error));
|
||||
|
||||
export class TabSession {
|
||||
value: TabStatus;
|
||||
private transport: Transport;
|
||||
private changed: (value: TabStatus) => void;
|
||||
private pending?: Promise<void>;
|
||||
private closed = false;
|
||||
private recovered = false;
|
||||
constructor(transport: Transport, initial: { tabId?: string; profileId?: string; url?: string }, changed: (value: TabStatus) => void) {
|
||||
this.transport = transport; this.changed = changed;
|
||||
this.value = { ...initial, tabId: initial.tabId || '', phase: 'connecting', message: 'Opening browser…' };
|
||||
}
|
||||
private update(value: Partial<TabStatus>) {
|
||||
this.value = { ...this.value, ...value }; this.changed(this.value);
|
||||
}
|
||||
observe(snapshot: Snapshot) {
|
||||
const tab = snapshot.tabs.find(tab => tab.id === this.value.tabId);
|
||||
if (tab) {
|
||||
this.value.profileId = tab.profileId;
|
||||
// The first snapshot can arrive before navigation starts.
|
||||
if (tab.url) this.value.url = tab.url;
|
||||
}
|
||||
}
|
||||
private failure(operation: string, error: unknown, tabId = this.value.tabId, phase: 'ready' | 'disconnected' = 'disconnected') {
|
||||
this.update({ phase, message: phase === 'ready' ? 'The browser could not complete this request. Check the error details.' : connectionLost(error)
|
||||
? 'This tab lost its browser connection. Select Reconnect to restore the page.'
|
||||
: 'The browser could not complete this request. Check the details, then select Reconnect.',
|
||||
detail: { operation, reason: String(error), tabId, time: new Date().toISOString() } });
|
||||
}
|
||||
connect(): Promise<void> {
|
||||
if (this.closed) return Promise.resolve();
|
||||
if (this.pending) return this.pending;
|
||||
this.pending = this.restore().finally(() => { this.pending = undefined; });
|
||||
return this.pending;
|
||||
}
|
||||
private async restore() {
|
||||
this.update({ phase: 'connecting', message: this.value.tabId ? 'Reconnecting browser…' : 'Opening browser…' });
|
||||
let operation = 'state';
|
||||
// The host discards a failed transport before the next request.
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
operation = 'state';
|
||||
const snapshot = await this.transport('state') as Snapshot;
|
||||
if (this.closed) return;
|
||||
if (snapshot.tabs.some(tab => tab.id === this.value.tabId)) {
|
||||
this.observe(snapshot); this.update({ phase: 'ready', message: '' }); return;
|
||||
}
|
||||
const profileId = this.value.profileId || snapshot.profiles[0]?.id;
|
||||
operation = 'newTab';
|
||||
const result = await this.transport('newTab', { profileId, ...(this.value.url ? { url: this.value.url } : {}) }) as { tabId: string };
|
||||
if (this.closed) { await this.transport('closeTab', { tabId: result.tabId }).catch(() => {}); return; }
|
||||
this.update({ tabId: result.tabId, profileId });
|
||||
operation = 'state';
|
||||
const current = await this.transport('state') as Snapshot;
|
||||
if (this.closed) return;
|
||||
if (current.tabs.some(tab => tab.id === result.tabId)) {
|
||||
this.observe(current); this.update({ phase: 'ready', message: '' }); return;
|
||||
}
|
||||
if (attempt === 1) throw new Error('The runtime restarted twice while opening this tab.');
|
||||
} catch (error) {
|
||||
if (this.closed) return;
|
||||
if (attempt === 0 && connectionLost(error)) continue;
|
||||
this.failure(operation, error); return;
|
||||
}
|
||||
}
|
||||
}
|
||||
async send(command: string, args: Record<string, unknown> = {}) {
|
||||
if (this.closed || this.value.phase !== 'ready') return;
|
||||
const tabId = this.value.tabId;
|
||||
try {
|
||||
await this.transport(command, { ...args, tabId });
|
||||
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
|
||||
} catch (error) {
|
||||
// Replies from the previous connection cannot replace the current error.
|
||||
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
|
||||
const lost = connectionLost(error);
|
||||
this.failure(command, error, tabId, lost ? 'disconnected' : 'ready');
|
||||
if (lost && !this.recovered) {
|
||||
this.recovered = true;
|
||||
await this.connect();
|
||||
// Only an explicit address submission is safe to repeat.
|
||||
if (command === 'navigate' && this.value.phase === 'ready') await this.send(command, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
detach() { this.closed = true; this.update({ phase: 'closed' }); }
|
||||
async close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
const tabId = this.value.tabId;
|
||||
this.update({ phase: 'closed' });
|
||||
if (tabId) await this.transport('closeTab', { tabId }).catch(() => {});
|
||||
}
|
||||
}
|
||||
@@ -6,27 +6,32 @@
|
||||
import { editorSession } from "./sessions";
|
||||
import { registerSelection } from "./selection";
|
||||
import { monacoChrome } from "./monacoChrome";
|
||||
import { codeFont } from "./codeFont";
|
||||
import { connectMonacoCompletion } from "$lib/completion/monaco";
|
||||
import { markdownMenu } from "./markdownMenu";
|
||||
import type { TableContextActions } from "./tableCellActions";
|
||||
import { documentLinks, documentLinkAt } from "./documentLinks";
|
||||
|
||||
type Props = {
|
||||
buffer: OpenBuffer;
|
||||
chrome: Chrome;
|
||||
onChange: (value: string, id: string) => void;
|
||||
onInsertImage?: (file: File) => Promise<string | null>;
|
||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||
focusLine?: number | null;
|
||||
onSelectionLine?: (line: number) => void;
|
||||
tableActions?: TableContextActions;
|
||||
shouldFocusOnMount?: () => boolean;
|
||||
};
|
||||
|
||||
let { buffer, chrome, onChange, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
|
||||
let { buffer, chrome, onChange, onInsertImage, onOpenLink, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true }: Props = $props();
|
||||
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor: import("monaco-editor").editor.IStandaloneCodeEditor | undefined;
|
||||
let ready = $state(0);
|
||||
let applying = false;
|
||||
let loadError = $state<string | null>(null);
|
||||
const documentPath = $derived(buffer.relPath);
|
||||
|
||||
async function takeImages(event: DragEvent | ClipboardEvent, data: DataTransfer | null) {
|
||||
if (!isMarkdownPath(buffer.relPath) || !onInsertImage) {
|
||||
@@ -77,6 +82,8 @@
|
||||
|
||||
$effect(() => {
|
||||
const el = host;
|
||||
// Buffer snapshots change on each edit. Only a path change remounts Monaco.
|
||||
const path = documentPath;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
@@ -88,19 +95,19 @@
|
||||
let releaseDrop: (() => void) | undefined;
|
||||
let releaseCompletion: (() => void) | undefined;
|
||||
const listeners: { dispose(): void }[] = [];
|
||||
void import("./monacoEnv").then(({ monaco }) => {
|
||||
void import("./monacoEnv").then(({ monaco, currentTheme }) => {
|
||||
if (cancelled || !el.isConnected) {
|
||||
return;
|
||||
}
|
||||
session = editorSession(monaco, untrack(() => buffer));
|
||||
const mode = untrack(() => chrome);
|
||||
const model = session.model;
|
||||
const markdown = isMarkdownPath(untrack(() => buffer.relPath));
|
||||
const markdown = isMarkdownPath(path);
|
||||
const view = monaco.editor.create(el, {
|
||||
model,
|
||||
theme: "runestone-dark",
|
||||
theme: currentTheme,
|
||||
automaticLayout: true,
|
||||
fontFamily: "Cascadia Code, JetBrains Mono, Consolas, ui-monospace, monospace",
|
||||
...codeFont(el),
|
||||
scrollBeyondLastLine: false,
|
||||
smoothScrolling: true,
|
||||
cursorBlinking: "smooth",
|
||||
@@ -112,6 +119,37 @@
|
||||
...monacoChrome(mode),
|
||||
});
|
||||
editor = view;
|
||||
const linkPath = `/${encodeURIComponent(untrack(() => buffer.id))}/`;
|
||||
if (markdown) listeners.push(monaco.languages.registerLinkProvider("markdown", {
|
||||
provideLinks(candidate) {
|
||||
if (candidate !== model) return { links: [] };
|
||||
return { links: documentLinks(model.getValue()).map(link => {
|
||||
const from = model.getPositionAt(link.from), to = model.getPositionAt(link.to);
|
||||
return { range: new monaco.Range(from.lineNumber, from.column, to.lineNumber, to.column),
|
||||
url: `runestone-link://document${linkPath}${link.kind}?${encodeURIComponent(link.target)}`, tooltip: "Open link" };
|
||||
}) };
|
||||
},
|
||||
}));
|
||||
listeners.push(monaco.editor.registerLinkOpener({ open(resource) {
|
||||
const url = resource.toString(true);
|
||||
if (resource.scheme === "runestone-link" && resource.path.startsWith(linkPath)) {
|
||||
onOpenLink?.(resource.path.slice(linkPath.length) === "wiki" ? "wiki" : "md", decodeURIComponent(resource.query));
|
||||
return true;
|
||||
}
|
||||
if (view.hasTextFocus() && /^(https?:|mailto:)/i.test(url) && onOpenLink) { onOpenLink("md", url); return true; }
|
||||
return false;
|
||||
} }));
|
||||
const openSourceLink = (event: MouseEvent) => {
|
||||
if (!markdown || event.button !== 0 || (!event.ctrlKey && !event.metaKey) || !onOpenLink) return;
|
||||
const position = view.getTargetAtClientPoint(event.clientX, event.clientY)?.position;
|
||||
const link = position && documentLinkAt(model.getValue(), model.getOffsetAt(position));
|
||||
if (!link) return;
|
||||
event.preventDefault(); event.stopImmediatePropagation();
|
||||
onOpenLink(link.kind, link.target);
|
||||
};
|
||||
el.addEventListener("mousedown", openSourceLink, true);
|
||||
listeners.push({ dispose: () => el.removeEventListener("mousedown", openSourceLink, true) });
|
||||
listeners.push(view.onDidChangeCursorPosition(event => onSelectionLine?.(event.position.lineNumber)));
|
||||
if (markdown) {
|
||||
releaseDrop = registerImageDropTarget(el, (path, point) => { void importImages(view, [], view.getTargetAtClientPoint(point.x, point.y)?.position, path); });
|
||||
menu = markdownMenu({
|
||||
@@ -149,6 +187,7 @@
|
||||
releaseCompletion = connectMonacoCompletion(monaco, view, documentId, markdown);
|
||||
releaseSelection = registerSelection(documentId, () => view.getSelections()?.map(range => model.getValueInRange(range)).join("\n") || "");
|
||||
if (session.view) view.restoreViewState(session.view);
|
||||
onSelectionLine?.(view.getPosition()?.lineNumber ?? 1);
|
||||
ready += 1;
|
||||
contentListener = model.onDidChangeContent(() => {
|
||||
if (applying) {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
<script lang="ts">
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
import { untrack } from "svelte";
|
||||
import { Compartment, EditorState } from "@codemirror/state";
|
||||
import { Compartment, EditorState, EditorSelection, Transaction } from "@codemirror/state";
|
||||
import { EditorView, drawSelection, keymap } from "@codemirror/view";
|
||||
import { defaultKeymap, history, historyField, historyKeymap, indentWithTab, isolateHistory } from "@codemirror/commands";
|
||||
import { defaultKeymap, indentWithTab, isolateHistory } from "@codemirror/commands";
|
||||
import { writerHistory, historyKeymap } from "./writerHistory";
|
||||
import { markdown, markdownLanguage } from "@codemirror/lang-markdown";
|
||||
import { noteFormats } from "./noteFormats";
|
||||
import { searchKeymap } from "@codemirror/search";
|
||||
@@ -25,6 +27,7 @@
|
||||
import { markdownMenu } from "./markdownMenu";
|
||||
import { tableNavigation } from "./tableNavigation";
|
||||
import { completionExtension } from "$lib/completion/codemirror";
|
||||
import { documentLinkAt } from "./documentLinks";
|
||||
|
||||
type Props = {
|
||||
buffer: OpenBuffer;
|
||||
@@ -33,17 +36,21 @@
|
||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||
onInsertImage?: (file: File) => Promise<string | null>;
|
||||
focusLine?: number | null;
|
||||
onSelectionLine?: (line: number) => void;
|
||||
tableActions?: TableContextActions;
|
||||
shouldFocusOnMount?: () => boolean;
|
||||
focusTitle?: boolean;
|
||||
onTitleFocused?: () => void;
|
||||
};
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
|
||||
let { buffer, onChange, onRenameTitle, onOpenLink, onInsertImage, focusLine = null, onSelectionLine, tableActions = {}, shouldFocusOnMount = () => true, focusTitle = false, onTitleFocused }: Props = $props();
|
||||
let host: HTMLDivElement | undefined = $state();
|
||||
let editor = $state.raw<EditorView>();
|
||||
let error = $state("");
|
||||
let model: import("monaco-editor").editor.ITextModel | undefined;
|
||||
let ModelSelection: typeof import("monaco-editor").Selection;
|
||||
let lastValue = "";
|
||||
let publishing = false;
|
||||
let historySelections: Map<number, EditorSelection> | undefined;
|
||||
let freshState: ((source: string) => EditorState) | undefined;
|
||||
let refreshVersion = 0;
|
||||
let historyTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
@@ -71,15 +78,32 @@
|
||||
return urls.size !== previousSize;
|
||||
}
|
||||
|
||||
function publish(value: string, id: string) {
|
||||
// CodeMirror stores one character per line break. Serialize only at the model
|
||||
// boundary, so pasted LF and CRLF text both create real editor lines.
|
||||
function modelSource(state: EditorState) {
|
||||
return state.doc.sliceString(0, undefined, model?.getEOL() ?? "\n");
|
||||
}
|
||||
|
||||
function publish(value: string, id: string, startState: EditorState, state: EditorState) {
|
||||
if (!model || value === model.getValue()) return;
|
||||
const before = model.getValue();
|
||||
historySelections?.set(model.getAlternativeVersionId(), startState.selection);
|
||||
const previous = model.getValue();
|
||||
let start = 0;
|
||||
while (start < before.length && start < value.length && before[start] === value[start]) start++;
|
||||
let oldEnd = before.length, newEnd = value.length;
|
||||
while (oldEnd > start && newEnd > start && before[oldEnd - 1] === value[newEnd - 1]) { oldEnd--; newEnd--; }
|
||||
while (start < previous.length && start < value.length && previous[start] === value[start]) start++;
|
||||
let oldEnd = previous.length, newEnd = value.length;
|
||||
while (oldEnd > start && newEnd > start && previous[oldEnd - 1] === value[newEnd - 1]) { oldEnd--; newEnd--; }
|
||||
const from = model.getPositionAt(start), to = model.getPositionAt(oldEnd);
|
||||
model.pushEditOperations(null, [{ range: { startLineNumber: from.lineNumber, startColumn: from.column, endLineNumber: to.lineNumber, endColumn: to.column }, text: value.slice(start, newEnd) }], () => null);
|
||||
const cursorState = (state: EditorState) => state.selection.ranges.map(range => {
|
||||
const anchor = state.doc.lineAt(range.anchor), head = state.doc.lineAt(range.head);
|
||||
return new ModelSelection(anchor.number, range.anchor - anchor.from + 1, head.number, range.head - head.from + 1);
|
||||
});
|
||||
// The model emits changes synchronously. Do not echo this Writer edit back
|
||||
// into CodeMirror while its update listener still runs.
|
||||
publishing = true;
|
||||
try {
|
||||
model.pushEditOperations(cursorState(startState), [{ range: { startLineNumber: from.lineNumber, startColumn: from.column, endLineNumber: to.lineNumber, endColumn: to.column }, text: value.slice(start, newEnd) }], () => cursorState(state));
|
||||
} finally { publishing = false; }
|
||||
historySelections?.set(model.getAlternativeVersionId(), state.selection);
|
||||
clearTimeout(historyTimer);
|
||||
historyTimer = setTimeout(() => model?.pushStackElement(), 500);
|
||||
lastValue = model.getValue();
|
||||
@@ -124,6 +148,7 @@
|
||||
if (!el) return;
|
||||
let cancelled = false;
|
||||
let session: ReturnType<typeof editorSession> | undefined;
|
||||
let contentListener: { dispose(): void } | undefined;
|
||||
let releaseSelection: (() => void) | undefined;
|
||||
let menu: ReturnType<typeof markdownMenu> | undefined;
|
||||
let releaseDrop: (() => void) | undefined;
|
||||
@@ -135,16 +160,29 @@
|
||||
if (cancelled) return;
|
||||
session = editorSession(monaco, untrack(() => buffer));
|
||||
model = session.model;
|
||||
ModelSelection = monaco.Selection;
|
||||
historySelections = session.writerSelections;
|
||||
lastValue = untrack(() => buffer.contents);
|
||||
if (model.getValue() !== lastValue) model.setValue(lastValue);
|
||||
model.pushStackElement();
|
||||
const extensions = [
|
||||
completionExtension(current.id),
|
||||
EditorState.lineSeparator.of(model.getEOL()),
|
||||
markdown({ base: markdownLanguage, extensions: [noteFormats] }),
|
||||
// Rich cell serialization can change delimiters away from the caret.
|
||||
// Keep a burst of typing together even when those source edits aren't adjacent.
|
||||
history({ joinToEvent: (transaction, adjacent) => adjacent || transaction.isUserEvent("input.type.table") }), drawSelection(),
|
||||
writerHistory.of({
|
||||
undo: () => {
|
||||
clearTimeout(historyTimer);
|
||||
model!.pushStackElement();
|
||||
if (!model!.canUndo()) return false;
|
||||
void model!.undo();
|
||||
return true;
|
||||
},
|
||||
redo: () => {
|
||||
clearTimeout(historyTimer);
|
||||
if (!model!.canRedo()) return false;
|
||||
void model!.redo();
|
||||
return true;
|
||||
},
|
||||
}), drawSelection(),
|
||||
EditorView.theme({}, { dark: true }),
|
||||
tableNavigation,
|
||||
writerSearch,
|
||||
@@ -173,18 +211,33 @@
|
||||
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
|
||||
EditorView.contentAttributes.of({ role: "textbox", "aria-label": "Writing editor", "aria-multiline": "true", spellcheck: "true" }),
|
||||
EditorView.updateListener.of(update => {
|
||||
if (update.docChanged || update.selectionSet) menu?.close(false);
|
||||
if (update.docChanged || update.selectionSet) {
|
||||
menu?.close(false);
|
||||
onSelectionLine?.(update.state.doc.lineAt(update.state.selection.main.head).number);
|
||||
}
|
||||
const isolation = update.transactions.map(transaction => transaction.annotation(isolateHistory));
|
||||
const separate = update.transactions.some(transaction => {
|
||||
const event = transaction.annotation(Transaction.userEvent);
|
||||
return transaction.docChanged && event && !/^(input\.type|delete)($|\.)/.test(event);
|
||||
});
|
||||
if (separate || (update.selectionSet && !update.docChanged)) model?.pushStackElement();
|
||||
if (isolation.some(value => value === "before" || value === "full")) model?.pushStackElement();
|
||||
if (update.docChanged) {
|
||||
scroll = scroll?.map(update.changes);
|
||||
publish(update.state.sliceDoc(), current.id);
|
||||
publish(modelSource(update.state), current.id, update.startState, update.state);
|
||||
void loadImages(current.relPath, update.state.sliceDoc()).then(changed => {
|
||||
if (changed && editor === update.view) update.view.dispatch({ effects: refreshImages.of() });
|
||||
});
|
||||
}
|
||||
if (isolation.some(value => value === "after" || value === "full")) {
|
||||
clearTimeout(historyTimer);
|
||||
model?.pushStackElement();
|
||||
}
|
||||
}),
|
||||
EditorView.domEventHandlers({
|
||||
contextmenu(event, view) {
|
||||
if (event.target instanceof Element && event.target.closest(".writer-table")) return false;
|
||||
if (useSpellingMenu(event, view.state.selection.main.empty)) { menu?.close(false); return false; }
|
||||
event.preventDefault();
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
const selection = view.state.selection.main;
|
||||
@@ -200,12 +253,15 @@
|
||||
if (coords) menu?.open(coords.left, coords.bottom);
|
||||
return true;
|
||||
},
|
||||
click(event) {
|
||||
mousedown(event, view) {
|
||||
if (!event.ctrlKey && !event.metaKey) return false;
|
||||
if (event.button !== 0) return false;
|
||||
const link = event.target instanceof Element ? event.target.closest("[data-href], a") : null;
|
||||
if (!link) return false;
|
||||
const position = view.posAtCoords({ x: event.clientX, y: event.clientY });
|
||||
const sourceLink = position === null ? undefined : documentLinkAt(view.state.doc.toString(), position);
|
||||
if (!link && !sourceLink) return false;
|
||||
event.preventDefault();
|
||||
onOpenLink?.(link.getAttribute("data-kind") === "wiki" ? "wiki" : "md", link.getAttribute("data-href") || link.getAttribute("href") || "");
|
||||
onOpenLink?.(sourceLink?.kind ?? (link?.getAttribute("data-kind") === "wiki" ? "wiki" : "md"), sourceLink?.target ?? link?.getAttribute("data-href") ?? link?.getAttribute("href") ?? "");
|
||||
return true;
|
||||
},
|
||||
paste(event, view) {
|
||||
@@ -217,11 +273,28 @@
|
||||
freshState = source => EditorState.create({ doc: source, extensions });
|
||||
const saved = session.writer;
|
||||
const state = saved?.source === lastValue
|
||||
? EditorState.fromJSON(saved.state, { extensions }, { history: historyField })
|
||||
? EditorState.fromJSON(saved.state, { extensions })
|
||||
: freshState(lastValue);
|
||||
// Restore through CodeMirror's layout pass, once its viewport is measured.
|
||||
const view = new EditorView({ state, parent: el, scrollTo: saved?.source === lastValue ? saved.scroll : undefined });
|
||||
editor = view;
|
||||
onSelectionLine?.(view.state.doc.lineAt(view.state.selection.main.head).number);
|
||||
// Writer and IDE use the same model and undo stack for this document.
|
||||
contentListener = model.onDidChangeContent(event => {
|
||||
if (publishing) return;
|
||||
const value = model!.getValue();
|
||||
if (value === modelSource(view.state)) return;
|
||||
lastValue = value;
|
||||
const changes = event.changes.map(change => ({
|
||||
from: view.state.doc.line(change.range.startLineNumber).from + change.range.startColumn - 1,
|
||||
to: view.state.doc.line(change.range.endLineNumber).from + change.range.endColumn - 1,
|
||||
insert: change.text,
|
||||
}));
|
||||
if (event.isFlush) historySelections?.clear();
|
||||
const selection = event.isUndoing || event.isRedoing ? historySelections?.get(model!.getAlternativeVersionId()) : undefined;
|
||||
view.dispatch({ changes, selection, scrollIntoView: !!selection, annotations: Transaction.addToHistory.of(false) });
|
||||
onChange(value, current.id);
|
||||
});
|
||||
scroll = saved?.source === lastValue ? saved.scroll : view.scrollSnapshot();
|
||||
// Svelte may detach the old tab before effect cleanup runs, at which point
|
||||
// DOM scroll offsets read as zero. Capture while the view is still mounted.
|
||||
@@ -246,10 +319,11 @@
|
||||
refreshVersion++;
|
||||
clearTimeout(historyTimer);
|
||||
model?.pushStackElement();
|
||||
contentListener?.dispose();
|
||||
menu?.destroy();
|
||||
releaseDrop?.();
|
||||
releaseScroll?.();
|
||||
if (session && editor && scroll) session.writer = { source: editor.state.sliceDoc(), state: editor.state.toJSON({ history: historyField }), scroll };
|
||||
if (session && editor && scroll) session.writer = { source: modelSource(editor.state), state: editor.state.toJSON(), scroll };
|
||||
editor?.destroy();
|
||||
releaseSelection?.();
|
||||
editor = undefined;
|
||||
@@ -318,22 +392,28 @@
|
||||
.live-writer { position: absolute; inset: 0; }
|
||||
.live-writer :global(.cm-editor) { height: 100%; color: var(--rs-text); background: transparent; }
|
||||
.live-writer :global(.cm-editor.cm-focused) { outline: none; }
|
||||
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-prose-size)/1.75 var(--rs-font-prose); scrollbar-gutter: stable; }
|
||||
.live-writer :global(.cm-scroller) { overflow: auto; font: var(--rs-font-weight) var(--rs-prose-size)/var(--rs-prose-line) var(--rs-font-prose); scrollbar-gutter: stable; }
|
||||
.live-writer :global(.cm-content) { max-width: 868px; width: 100%; margin: 0 auto; padding: clamp(24px, 4vw, 56px) clamp(22px, 4vw, 64px) 35vh; caret-color: var(--rs-text-strong); }
|
||||
.live-writer :global(.cm-line) { padding: 0; }
|
||||
.live-writer :global(.cm-line) { padding: 0; position: relative; }
|
||||
.live-writer :global(.cm-line:hover)::before { content: ""; position: absolute; left: -14px; top: 2px; bottom: 2px; width: 3px; border-radius: var(--rs-control-radius); background: var(--rs-text-dim); opacity: .5; pointer-events: none; }
|
||||
.live-writer :global(.cm-panels) { background: var(--rs-bg-elevated); color: var(--rs-text); }
|
||||
.live-writer :global(.cm-cursor) { border-left-color: var(--rs-text-strong); }
|
||||
.live-writer :global(.cm-selectionBackground), .live-writer :global(.cm-focused .cm-selectionBackground) { background: var(--rs-bg-active); }
|
||||
.live-writer :global(.writer-heading) { color: var(--rs-text-strong); font-weight: 650; line-height: 1.4; }
|
||||
.live-writer :global(.writer-h1) { font-size: 2.1em; }
|
||||
.live-writer :global(.writer-h2) { font-size: 1.5em; }
|
||||
.live-writer :global(.writer-h3) { font-size: 1.2em; }
|
||||
.live-writer :global(.writer-strong) { font-weight: 650; color: var(--rs-text-strong); }
|
||||
.live-writer :global(.writer-blank) { font-size: .75em; }
|
||||
.live-writer :global(.writer-strong) { font-weight: 600; color: var(--rs-text-strong); }
|
||||
.live-writer :global(.writer-emphasis) { font-style: italic; }
|
||||
.live-writer :global(.writer-strike), .live-writer :global(.writer-completed) { text-decoration: line-through; color: var(--rs-text-dim); }
|
||||
.live-writer :global(.writer-link) { color: var(--rs-accent); text-decoration: underline; text-underline-offset: 3px; }
|
||||
.live-writer :global(.writer-inline-code), .live-writer :global(.writer-code-source) { font-family: var(--rs-font-mono); font-size: .9em; }
|
||||
.live-writer :global(.writer-inline-code) { background: var(--rs-bg-elevated); border-radius: 3px; }
|
||||
.live-writer :global(.writer-code-line) { padding: 0 20px; border-inline: 1px solid var(--rs-border); background: var(--rs-bg-elevated); font: 13px/1.65 var(--rs-font-mono); tab-size: 4; }
|
||||
.live-writer :global(.writer-code-first) { padding-top: 10px; border-top: 1px solid var(--rs-border); border-radius: var(--rs-control-radius) var(--rs-control-radius) 0 0; padding-right: 44px; }
|
||||
.live-writer :global(.writer-code-last) { padding-bottom: 10px; border-bottom: 1px solid var(--rs-border); border-radius: 0 0 var(--rs-control-radius) var(--rs-control-radius); }
|
||||
.live-writer :global(.writer-code-fence) { color: var(--rs-text-dim); }
|
||||
.live-writer :global(.writer-code-copy) { top: 4px; border-radius: var(--rs-control-radius); }
|
||||
.live-writer :global(.writer-code-copy:focus-visible) { outline: 1px solid var(--rs-accent); outline-offset: -2px; }
|
||||
.live-writer :global(.writer-code-tooltip) { display: none; position: absolute; z-index: 2; top: 100%; right: 0; padding: 4px 8px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: 12px/1.5 var(--rs-font-ui); white-space: nowrap; pointer-events: none; }
|
||||
.live-writer :global(.writer-code-copy:focus-visible .writer-code-tooltip) { display: block; }
|
||||
.live-writer :global(.writer-highlight) { background: #e7c56a38; color: var(--rs-text-strong); }
|
||||
.live-writer :global(.writer-math) { font-family: var(--rs-font-mono); font-style: italic; }
|
||||
.live-writer :global(.writer-comment) { color: var(--rs-text-dim); background: var(--rs-bg-active); }
|
||||
@@ -346,10 +426,10 @@
|
||||
.live-writer :global(.writer-preview) { display: flow-root; max-width: none; margin: 0; }
|
||||
.live-writer :global(.writer-preview > :last-child) { margin-bottom: 0; }
|
||||
.live-writer :global(.writer-preview img) { max-width: 100%; }
|
||||
.live-writer :global(.writer-table) { position: relative; margin: 1.4em 0 0; padding: 26px; }
|
||||
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 4px; }
|
||||
.live-writer :global(.writer-table) { position: relative; width: fit-content; max-width: 100%; margin: 1.4em 0 0; padding: 26px; }
|
||||
.live-writer :global(.writer-table .md-table-scroll) { margin: 0; border-radius: 0; }
|
||||
.live-writer :global(.writer-table td), .live-writer :global(.writer-table th) { cursor: text; }
|
||||
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1.75em; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.live-writer :global(.writer-cell-editor) { outline: none; min-height: 1lh; white-space: pre-wrap; overflow-wrap: break-word; }
|
||||
.live-writer :global(.writer-table p) { margin: 0; }
|
||||
.live-writer :global(.table-add) { position: absolute; display: block; padding: 0; opacity: 0; border: 1px solid var(--rs-border); background: var(--rs-bg-elevated); color: var(--rs-text-dim); cursor: pointer; transition: opacity 100ms; }
|
||||
.live-writer :global(.table-add:hover), .live-writer :global(.table-add:focus-visible) { opacity: 1; color: var(--rs-accent); border-color: var(--rs-accent-deep); outline: none; }
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
import ContextMenu from "$lib/layout/ContextMenu.svelte";
|
||||
import type { MenuItem } from "$lib/layout/menuTypes";
|
||||
import { writerContextItems } from "./writerMenu";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
|
||||
type Props = {
|
||||
buffer: OpenBuffer;
|
||||
@@ -132,9 +133,10 @@
|
||||
],
|
||||
content: html,
|
||||
editorProps: {
|
||||
attributes: { class: "reading writer-doc" },
|
||||
attributes: { class: "reading writer-doc", spellcheck: "true" },
|
||||
handleDOMEvents: {
|
||||
contextmenu: (pmView, event) => {
|
||||
if (useSpellingMenu(event, pmView.state.selection.empty)) { menu = null; return false; }
|
||||
event.preventDefault();
|
||||
if (!editor) {
|
||||
return true;
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
export function codeFont(element: HTMLElement) {
|
||||
const style = getComputedStyle(element);
|
||||
return {
|
||||
fontFamily: style.getPropertyValue("--rs-font-mono").trim() || '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace',
|
||||
fontWeight: style.getPropertyValue("--rs-code-font-weight").trim() || "300",
|
||||
fontSize: Number.parseFloat(style.getPropertyValue("--rs-code-font-size")) || 13,
|
||||
lineHeight: Number.parseFloat(style.getPropertyValue("--rs-code-line-height")) || 21,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { markdownLanguage } from "@codemirror/lang-markdown";
|
||||
|
||||
export type DocumentLink = { from: number; to: number; kind: "md" | "wiki"; target: string };
|
||||
|
||||
/** Source ranges survive the change from formatted text to editable Markdown. */
|
||||
export function documentLinks(source: string): DocumentLink[] {
|
||||
const links: DocumentLink[] = [];
|
||||
const literal: { from: number; to: number }[] = [];
|
||||
markdownLanguage.parser.parse(source).iterate({ enter(node) {
|
||||
if (["FencedCode", "CodeBlock", "InlineCode", "Image"].includes(node.name)) {
|
||||
literal.push({ from: node.from, to: node.to });
|
||||
return false;
|
||||
}
|
||||
if (node.name !== "Link" && node.name !== "Autolink") return;
|
||||
const url = node.node.getChild("URL");
|
||||
if (!url) return;
|
||||
const target = source.slice(url.from, url.to).replace(/^<|>$/g, "").replace(/\\([\\()])/g, "$1");
|
||||
links.push({ from: node.from, to: node.to, kind: "md", target });
|
||||
return false;
|
||||
} });
|
||||
const occupied = (from: number, to: number) => [...literal, ...links].some(range => from < range.to && to > range.from);
|
||||
for (const match of source.matchAll(/\[\[([^\]\n]+)\]\]/g)) {
|
||||
if (occupied(match.index, match.index + match[0].length)) continue;
|
||||
links.push({ from: match.index, to: match.index + match[0].length, kind: "wiki", target: match[1].split("|")[0].trim() });
|
||||
}
|
||||
for (const match of source.matchAll(/(?:https?:\/\/|mailto:)[^\s<>]+/g)) {
|
||||
if (occupied(match.index, match.index + match[0].length)) continue;
|
||||
const target = match[0].replace(/[.,;:!?]+$/, "").replace(/\)+$/, suffix => {
|
||||
const open = (match[0].match(/\(/g) || []).length, close = (match[0].match(/\)/g) || []).length;
|
||||
return suffix.slice(0, Math.max(0, suffix.length - Math.max(0, close - open)));
|
||||
});
|
||||
links.push({ from: match.index, to: match.index + target.length, kind: "md", target });
|
||||
}
|
||||
return links.sort((a, b) => a.from - b.from);
|
||||
}
|
||||
|
||||
export function documentLinkAt(source: string, position: number) {
|
||||
return documentLinks(source).find(link => position >= link.from && position < link.to);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type { TableContextActions } from "./tableCellActions";
|
||||
import { imageControls } from "./imageControls";
|
||||
import { ImagePreview, type ImageContext } from "./imagePreview";
|
||||
import { imageSource, editImageSource, imageSourceRanges } from "./imageSource";
|
||||
import { actionIcon } from "../ui/actionIcons";
|
||||
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
|
||||
@@ -16,6 +17,40 @@ const previewFormulas = new WeakMap<HTMLElement, unknown>();
|
||||
export const refreshImages = StateEffect.define<void>();
|
||||
const imageCleanups = new WeakMap<HTMLElement, () => void>();
|
||||
|
||||
class CodeCopy extends WidgetType {
|
||||
constructor(readonly code: string) { super(); }
|
||||
eq(other: CodeCopy) { return this.code === other.code; }
|
||||
toDOM() {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.className = "rs-fence-copy writer-code-copy";
|
||||
button.setAttribute("aria-label", "Copy code");
|
||||
button.title = "Copy code";
|
||||
const help = document.createElement("span");
|
||||
help.className = "writer-code-tooltip";
|
||||
help.setAttribute("role", "tooltip");
|
||||
help.textContent = "Copy code";
|
||||
button.append(actionIcon("copy"), help);
|
||||
button.onmousedown = event => event.preventDefault();
|
||||
button.onclick = async event => {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
try {
|
||||
await navigator.clipboard.writeText(this.code);
|
||||
button.dataset.copied = "true";
|
||||
button.title = "Copied";
|
||||
help.textContent = "Copied";
|
||||
button.setAttribute("aria-label", "Code copied");
|
||||
} catch {
|
||||
button.title = "Could not copy code";
|
||||
help.textContent = "Could not copy code";
|
||||
button.setAttribute("aria-label", "Could not copy code");
|
||||
}
|
||||
};
|
||||
return button;
|
||||
}
|
||||
ignoreEvent() { return true; }
|
||||
}
|
||||
|
||||
class Divider extends WidgetType {
|
||||
eq(other: Divider) { return other instanceof Divider; }
|
||||
toDOM(view: EditorView) {
|
||||
@@ -109,6 +144,9 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
const imageNodes = imageSourceRanges(source);
|
||||
for (const section of renderMarkdownSections(source, urls)) {
|
||||
if (!/(?:<pre|<table|<img|md-properties|md-callout|missing-image)/.test(section.html)) continue;
|
||||
// Code remains a real editor surface. A preview swap loses the first drag
|
||||
// and changes block height when focus or the selection moves elsewhere.
|
||||
if (/^<pre\b/.test(section.html)) continue;
|
||||
// The first rendered section includes leading blank lines. Keep those
|
||||
// editable when the user exits above a table at the start of a note.
|
||||
if (/<table>/.test(section.html)) section.start += /^(?:[ \t]*\r?\n)+/.exec(source.slice(section.start, section.end))?.[0].length ?? 0;
|
||||
@@ -146,6 +184,10 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
ranges.push(Decoration.replace({ widget: new Preview(section.html, source.slice(section.start, end), actions, false, height), block: true, atomic: true }).range(section.start, end));
|
||||
}
|
||||
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
|
||||
for (let number = 1; number <= state.doc.lines; number++) {
|
||||
const line = state.doc.line(number);
|
||||
if (!line.text.trim() && !hidden(line.from, line.to)) ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
|
||||
}
|
||||
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
|
||||
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
|
||||
const codeRanges: { from: number; to: number }[] = [];
|
||||
@@ -153,7 +195,15 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
|
||||
if (hidden(node.from, node.to)) return false;
|
||||
if (node.name === "FencedCode" || node.name === "CodeBlock") {
|
||||
codeRanges.push({ from: node.from, to: node.to });
|
||||
mark(node.from, node.to, "writer-code-source");
|
||||
const first = state.doc.lineAt(node.from), last = state.doc.lineAt(node.to);
|
||||
const fenced = node.name === "FencedCode";
|
||||
const closed = fenced && /^\s*(`{3,}|~{3,})\s*$/.test(last.text) && last.number > first.number;
|
||||
const code = fenced ? source.slice(Math.min(first.to + 1, node.to), closed ? last.from : node.to) : source.slice(node.from, node.to);
|
||||
ranges.push(Decoration.widget({ widget: new CodeCopy(code), side: 1 }).range(first.to));
|
||||
for (let number = first.number; number <= last.number; number++) {
|
||||
const line = state.doc.line(number);
|
||||
ranges.push(Decoration.line({ class: `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const line = state.doc.lineAt(node.from);
|
||||
|
||||
@@ -2,6 +2,10 @@ export type TableCell = { text: string; from: number; to: number };
|
||||
export type TableRow = { from: number; to: number; indent: string; cells: TableCell[] };
|
||||
export type MarkdownTable = { rows: TableRow[]; columns: number; eol: string; end: number };
|
||||
|
||||
export function hasTableDelimiter(line: string): boolean {
|
||||
return /(^|[^\\])(?:\\\\)*\|/.test(line);
|
||||
}
|
||||
|
||||
function row(text: string, from: number): TableRow {
|
||||
const pipes: number[] = [];
|
||||
for (let index = 0; index < text.length; index++) {
|
||||
@@ -30,7 +34,7 @@ export function parseMarkdownTable(source: string): MarkdownTable | null {
|
||||
let offset = 0;
|
||||
const eol = source.includes("\r\n") ? "\r\n" : "\n";
|
||||
for (const line of source.split(eol)) {
|
||||
if (!line.trim()) break;
|
||||
if (!line.trim() || (rows.length >= 2 && !hasTableDelimiter(line))) break;
|
||||
rows.push(row(line, offset));
|
||||
offset += line.length + eol.length;
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ export function monacoChrome(mode: Chrome) {
|
||||
wordWrap: "on" as const,
|
||||
lineNumbers: "off" as const,
|
||||
minimap: { enabled: false },
|
||||
fontSize: 16,
|
||||
lineHeight: 26,
|
||||
folding: false,
|
||||
glyphMargin: false,
|
||||
lineDecorationsWidth: 24,
|
||||
@@ -19,8 +17,6 @@ export function monacoChrome(mode: Chrome) {
|
||||
wordWrap: "off" as const,
|
||||
lineNumbers: "on" as const,
|
||||
minimap: { enabled: true, scale: 1 },
|
||||
fontSize: 14,
|
||||
lineHeight: 22,
|
||||
folding: true,
|
||||
glyphMargin: true,
|
||||
lineDecorationsWidth: 10,
|
||||
|
||||
+34
-21
@@ -8,25 +8,38 @@ self.MonacoEnvironment = {
|
||||
},
|
||||
};
|
||||
|
||||
monaco.editor.defineTheme("runestone-dark", {
|
||||
base: "vs-dark",
|
||||
inherit: true,
|
||||
rules: [],
|
||||
colors: {
|
||||
"editor.background": "#141414",
|
||||
"editor.foreground": "#e6e6e6",
|
||||
"editor.lineHighlightBackground": "#ffffff0d",
|
||||
"editor.selectionBackground": "#264f78",
|
||||
"editorCursor.foreground": "#82aaff",
|
||||
"editorLineNumber.foreground": "#5a5a5a",
|
||||
"editorLineNumber.activeForeground": "#c8c8c8",
|
||||
"editorGutter.background": "#141414",
|
||||
"editorWidget.background": "#1c1c1c",
|
||||
"editorWidget.border": "#2e2e2e",
|
||||
"minimap.background": "#1c1c1c",
|
||||
"editorIndentGuide.background1": "#2e2e2e",
|
||||
"editorIndentGuide.activeBackground1": "#3e3e3e",
|
||||
},
|
||||
});
|
||||
|
||||
export let currentTheme = 'runestone-default-dark';
|
||||
function updateTheme() {
|
||||
const style = getComputedStyle(document.documentElement);
|
||||
const color = (name: string) => style.getPropertyValue(`--rs-${name}`).trim();
|
||||
const sakura = document.documentElement.dataset.palette === 'sakura';
|
||||
// Monaco permits only letters, digits, and hyphens in registered theme names.
|
||||
const palette = (document.documentElement.dataset.palette || 'default').replace(/[^a-z0-9-]/gi, '-');
|
||||
currentTheme = `runestone-${palette}-${document.documentElement.dataset.theme || 'dark'}`;
|
||||
monaco.editor.defineTheme(currentTheme, {
|
||||
base: document.documentElement.dataset.theme === 'light' ? 'vs' : 'vs-dark',
|
||||
inherit: true,
|
||||
rules: sakura ? [
|
||||
{ token: 'keyword', foreground: color('syntax-keyword').replace('#', '') },
|
||||
{ token: 'variable.parameter', foreground: color('syntax-parameter').replace('#', '') },
|
||||
{ token: 'variable', foreground: color('syntax-local').replace('#', '') },
|
||||
{ token: 'variable.predefined', foreground: color('syntax-global').replace('#', '') },
|
||||
{ token: 'variable.property', foreground: color('syntax-instance').replace('#', '') },
|
||||
{ token: 'variable.static', foreground: color('syntax-static').replace('#', '') },
|
||||
] : [],
|
||||
colors: {
|
||||
'editor.background': color('bg'), 'editor.foreground': color('text'),
|
||||
'editor.lineHighlightBackground': color('bg-active'), 'editor.selectionBackground': color('selection'),
|
||||
'editorCursor.foreground': color('accent'), 'editorLineNumber.foreground': color('text-dim'),
|
||||
'editorLineNumber.activeForeground': color('text'), 'editorGutter.background': color('bg'),
|
||||
'editorWidget.background': color('bg-elevated'), 'editorWidget.border': color('border'),
|
||||
'minimap.background': color('bg-elevated'), 'editorIndentGuide.background1': color('border'),
|
||||
'editorIndentGuide.activeBackground1': color('text-dim'),
|
||||
},
|
||||
});
|
||||
monaco.editor.setTheme(currentTheme);
|
||||
}
|
||||
updateTheme();
|
||||
window.addEventListener('runestone-theme-changed', updateTheme);
|
||||
if (import.meta.hot) import.meta.hot.dispose(() => window.removeEventListener('runestone-theme-changed', updateTheme));
|
||||
export { monaco };
|
||||
|
||||
@@ -5,6 +5,7 @@ import { languageFor } from "./languageFor";
|
||||
type Session = {
|
||||
model: Monaco.editor.ITextModel;
|
||||
view: Monaco.editor.ICodeEditorViewState | null;
|
||||
writerSelections: Map<number, import("@codemirror/state").EditorSelection>;
|
||||
writer?: { source: string; state: ReturnType<import("@codemirror/state").EditorState["toJSON"]>; scroll: ReturnType<import("@codemirror/view").EditorView["scrollSnapshot"]> };
|
||||
};
|
||||
const sessions = new Map<string, Session>();
|
||||
@@ -15,6 +16,7 @@ export function editorSession(monaco: typeof Monaco, buffer: OpenBuffer): Sessio
|
||||
session = {
|
||||
model: monaco.editor.createModel(buffer.contents, languageFor(buffer.relPath), monaco.Uri.parse(`inmemory://runestone/${buffer.id}/${buffer.name}`)),
|
||||
view: null,
|
||||
writerSelections: new Map(),
|
||||
};
|
||||
sessions.set(buffer.id, session);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import type { ActionIcon } from "../ui/actionIcons";
|
||||
|
||||
/** WebView2 owns spelling suggestions and applies corrections to the original word. */
|
||||
export function isSpellingTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof HTMLElement)) return false;
|
||||
if (target instanceof HTMLTextAreaElement || (target instanceof HTMLInputElement && ["text", "search"].includes(target.type))) {
|
||||
return target.spellcheck && !target.disabled && !target.readOnly;
|
||||
}
|
||||
const editable = target.closest<HTMLElement>('[contenteditable="true"][spellcheck="true"]');
|
||||
return !!editable && target.isContentEditable
|
||||
&& !target.closest('a, code, pre, button, [data-href], [spellcheck="false"], .writer-inline-code, .writer-code-source, .writer-code-line');
|
||||
}
|
||||
|
||||
export function useSpellingMenu(event: MouseEvent, selectionEmpty: boolean): boolean {
|
||||
return selectionEmpty && isSpellingTarget(event.target);
|
||||
}
|
||||
|
||||
export type NativeSpellingItem = {
|
||||
id: number; name: string; label: string; shortcut: string; kind: number;
|
||||
enabled: boolean; checked: boolean; children: NativeSpellingItem[];
|
||||
};
|
||||
type NativeMenu = { request: string; items: NativeSpellingItem[] };
|
||||
const icons: Record<string, ActionIcon> = {
|
||||
undo: "undo", redo: "redo",
|
||||
cut: "cut", copy: "copy", paste: "paste", pasteAndMatchStyle: "paste-text",
|
||||
selectAll: "select", addToDictionary: "book", spellCheck: "book", spellingAndGrammar: "book",
|
||||
};
|
||||
|
||||
function nativeLabel(label: string): string {
|
||||
// Windows uses ampersands for access keys and doubles literal ampersands.
|
||||
return label.replace(/&&|&/g, value => value === "&&" ? "&" : "");
|
||||
}
|
||||
|
||||
export function spellingItems(items: NativeSpellingItem[], select: (id: number) => void): ActionMenuItem[] {
|
||||
return items.map(item => item.kind === 3 ? { separator: true } : {
|
||||
label: nativeLabel(item.label), icon: icons[item.name], shortcut: item.shortcut || undefined,
|
||||
disabled: !item.enabled, checked: item.kind === 1 || item.kind === 2 ? item.checked : undefined,
|
||||
radio: item.kind === 2,
|
||||
children: item.kind === 4 ? spellingItems(item.children, select) : undefined,
|
||||
run: () => select(item.id),
|
||||
});
|
||||
}
|
||||
|
||||
/** Mount once per app window. Other platforms keep their native spelling menu. */
|
||||
export function mountSpellingMenu(): () => void {
|
||||
if (!isTauri()) return () => {};
|
||||
let disposed = false, unlisten: (() => void) | undefined;
|
||||
let context: { target: HTMLElement; x: number; y: number } | undefined;
|
||||
let active: { request: string; root: HTMLElement; target: HTMLElement } | undefined;
|
||||
const finish = (command: number | null = null, restoreFocus = false) => {
|
||||
if (!active) return;
|
||||
const { request, root, target } = active;
|
||||
active = undefined;
|
||||
root.remove();
|
||||
if (restoreFocus && target.isConnected) target.focus({ preventScroll: true });
|
||||
void invoke("spelling_menu_select", { request, command }).catch(error => console.error("Cannot close the spelling menu", error));
|
||||
};
|
||||
const remember = (event: MouseEvent) => {
|
||||
finish();
|
||||
if (event.defaultPrevented || !isSpellingTarget(event.target)) { context = undefined; return; }
|
||||
const target = (event.target as HTMLElement).closest<HTMLElement>('[contenteditable="true"], textarea, input')!;
|
||||
const bounds = document.getSelection()?.rangeCount ? document.getSelection()!.getRangeAt(0).getBoundingClientRect() : target.getBoundingClientRect();
|
||||
context = { target, x: event.clientX || bounds.left, y: event.clientY || bounds.bottom };
|
||||
};
|
||||
const outside = (event: PointerEvent) => { if (active && !active.root.contains(event.target as Node)) finish(); };
|
||||
const scroll = (event: Event) => { if (active && !active.root.contains(event.target as Node)) finish(); };
|
||||
const cancel = () => finish();
|
||||
window.addEventListener("contextmenu", remember);
|
||||
window.addEventListener("pointerdown", outside);
|
||||
window.addEventListener("resize", cancel);
|
||||
window.addEventListener("blur", cancel);
|
||||
window.addEventListener("pagehide", cancel);
|
||||
document.addEventListener("scroll", scroll, true);
|
||||
void listen<NativeMenu>("spelling-menu", ({ payload }) => {
|
||||
finish();
|
||||
if (disposed || !context?.target.isConnected) {
|
||||
void invoke("spelling_menu_select", { request: payload.request, command: null, fallback: true });
|
||||
return;
|
||||
}
|
||||
const { target, x, y } = context;
|
||||
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body;
|
||||
const root = actionMenu(x, y, spellingItems(payload.items, id => finish(id, true)), () => finish(null, true), "Spelling actions", parent);
|
||||
active = { request: payload.request, root, target };
|
||||
}).then(async stop => {
|
||||
if (disposed) { stop(); return; }
|
||||
unlisten = stop;
|
||||
await invoke("spelling_menu_install");
|
||||
if (disposed) await invoke("spelling_menu_uninstall");
|
||||
}).catch(error => console.warn("Native spelling menu remains active", error));
|
||||
return () => {
|
||||
disposed = true;
|
||||
finish(); unlisten?.();
|
||||
void invoke("spelling_menu_uninstall").catch(() => {});
|
||||
window.removeEventListener("contextmenu", remember);
|
||||
window.removeEventListener("pointerdown", outside);
|
||||
window.removeEventListener("resize", cancel);
|
||||
window.removeEventListener("blur", cancel);
|
||||
window.removeEventListener("pagehide", cancel);
|
||||
document.removeEventListener("scroll", scroll, true);
|
||||
};
|
||||
}
|
||||
@@ -4,7 +4,8 @@ import StarterKit from "@tiptap/starter-kit";
|
||||
import Link from "@tiptap/extension-link";
|
||||
import Image from "@tiptap/extension-image";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { isolateHistory, undo, redo } from "@codemirror/commands";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { undo, redo } from "./writerHistory";
|
||||
import { appendTableColumn, appendTableRow, parseMarkdownTable, replaceTableCell } from "./markdownTable";
|
||||
import { tableCellMarkdown } from "./tableCellMarkdown";
|
||||
import { tableSelectionControls } from "./tableSelectionControls";
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { undo, redo, isolateHistory } from "@codemirror/commands";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { undo, redo } from "./writerHistory";
|
||||
import type { Editor } from "@tiptap/core";
|
||||
import { useSpellingMenu } from "./spellingMenu";
|
||||
import { changeTableStructure, sortTableColumn, type TableAxis, type TableOperation } from "./tableStructure";
|
||||
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
|
||||
import { cellFormats, tableTextItems, type TableContextActions } from "./tableCellActions";
|
||||
@@ -138,7 +140,10 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
}
|
||||
table.addEventListener("mousedown", event => {
|
||||
const cell = cellAt(event.target);
|
||||
if (cell && event.button === 2) { event.preventDefault(); return; }
|
||||
if (cell && event.button === 2) {
|
||||
if (!useSpellingMenu(event, !range && !!rich.get()?.state.selection.empty)) event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (!cell || event.button !== 0 || event.ctrlKey || event.metaKey) return;
|
||||
closeMenu(); down = point(cell); dragging = false;
|
||||
if (event.shiftKey) {
|
||||
@@ -163,6 +168,7 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
|
||||
table.addEventListener("click", event => { if (dragging) { event.preventDefault(); event.stopPropagation(); dragging = false; } }, { ...options, capture: true });
|
||||
table.addEventListener("contextmenu", event => {
|
||||
const cell = cellAt(event.target); if (!cell) return;
|
||||
if (useSpellingMenu(event, !range && !!rich.get()?.state.selection.empty)) { closeMenu(); return; }
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
if (cell.classList.contains("is-cell-selected")) showMenu(event.clientX, event.clientY, point(cell));
|
||||
else {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Facet } from "@codemirror/state";
|
||||
import type { Command, KeyBinding } from "@codemirror/view";
|
||||
import { undo as localUndo, redo as localRedo } from "@codemirror/commands";
|
||||
|
||||
export const writerHistory = Facet.define<{ undo: () => boolean; redo: () => boolean }>();
|
||||
|
||||
export const undo: Command = view => {
|
||||
const shared = view.state.facet(writerHistory)[0];
|
||||
return shared ? shared.undo() : localUndo(view);
|
||||
};
|
||||
export const redo: Command = view => {
|
||||
const shared = view.state.facet(writerHistory)[0];
|
||||
return shared ? shared.redo() : localRedo(view);
|
||||
};
|
||||
|
||||
export const historyKeymap: readonly KeyBinding[] = [
|
||||
{ key: "Mod-z", run: undo, preventDefault: true },
|
||||
{ key: "Mod-y", run: redo, preventDefault: true },
|
||||
{ key: "Mod-Shift-z", run: redo, preventDefault: true },
|
||||
];
|
||||
@@ -0,0 +1,62 @@
|
||||
export interface GitChange {
|
||||
path: string;
|
||||
originalPath?: string;
|
||||
index: string;
|
||||
worktree: string;
|
||||
}
|
||||
|
||||
export interface GitStatus {
|
||||
available: boolean;
|
||||
repository: boolean;
|
||||
branch: string | null;
|
||||
changes: GitChange[];
|
||||
}
|
||||
|
||||
export interface GitLineInfo {
|
||||
commit: string;
|
||||
author: string;
|
||||
/** The author date in ISO 8601 format. */
|
||||
date: string;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export interface GitApi {
|
||||
status(): Promise<GitStatus>;
|
||||
diff(path: string, staged: boolean): Promise<string>;
|
||||
stage(paths: string[]): Promise<void>;
|
||||
unstage(paths: string[]): Promise<void>;
|
||||
commit(message: string): Promise<void>;
|
||||
push(): Promise<void>;
|
||||
pull(): Promise<void>;
|
||||
graph(): Promise<GitGraph>;
|
||||
commitDetails(commit: string): Promise<GitCommitDetails>;
|
||||
commitDiff(commit: string, path: string): Promise<string>;
|
||||
blame(path: string, line: number): Promise<GitLineInfo | null>;
|
||||
}
|
||||
|
||||
export interface GitGraphCommit {
|
||||
id: string;
|
||||
parents: string[];
|
||||
refs: string[];
|
||||
summary: string;
|
||||
author: string;
|
||||
date: string;
|
||||
}
|
||||
|
||||
export interface GitGraph {
|
||||
commits: GitGraphCommit[];
|
||||
}
|
||||
|
||||
export interface GitCommitFile {
|
||||
path: string;
|
||||
originalPath?: string;
|
||||
status: string;
|
||||
}
|
||||
export interface GitCommitDetails {
|
||||
id: string;
|
||||
parents: string[];
|
||||
author: string;
|
||||
date: string;
|
||||
message: string;
|
||||
files: GitCommitFile[];
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import type { GitApi, GitLineInfo } from "./contracts.ts";
|
||||
|
||||
export const gitApi: GitApi = {
|
||||
status: () => invoke("git_status"),
|
||||
diff: (path, staged) => invoke("git_diff", { path, staged }),
|
||||
stage: (paths) => invoke("git_stage", { paths }),
|
||||
unstage: (paths) => invoke("git_unstage", { paths }),
|
||||
commit: (message) => invoke("git_commit", { message }),
|
||||
push: () => invoke("git_push"),
|
||||
pull: () => invoke("git_pull"),
|
||||
graph: () => invoke("git_graph"),
|
||||
commitDetails: (commit) => invoke("git_commit_details", { commit }),
|
||||
commitDiff: (commit, path) => invoke("git_commit_diff", { commit, path }),
|
||||
blame: async (path, line) => {
|
||||
const info = await invoke<GitLineInfo | null>("git_blame", { path, line });
|
||||
if (!info) return null;
|
||||
const date = new Date(Number(info.date) * 1000);
|
||||
return { ...info, date: Number.isNaN(date.getTime()) ? info.date : date.toISOString() };
|
||||
},
|
||||
};
|
||||
@@ -1,4 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import type { GitLineInfo } from "$lib/git/contracts";
|
||||
import EditorHost from "$lib/editor/EditorHost.svelte";
|
||||
import LiveWriter from "$lib/editor/LiveWriter.svelte";
|
||||
import { onDestroy, tick } from "svelte";
|
||||
@@ -25,6 +27,7 @@
|
||||
onOpenLink?: (kind: "md" | "wiki", target: string) => void;
|
||||
onOpenWorkspace: () => void;
|
||||
onNewFile: () => void;
|
||||
onNewNote?: (event: MouseEvent) => void;
|
||||
onQuickOpen: () => void;
|
||||
onOpenBrowser?: () => void;
|
||||
browserOpening?: boolean;
|
||||
@@ -32,7 +35,28 @@
|
||||
tableActions?: TableContextActions;
|
||||
};
|
||||
|
||||
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions }: Props = $props();
|
||||
let { buffer, tabs, chrome, reading, focusLine, onChange, onRenameTitle, onInsertImage, onToggleReading, onToggleChrome, onOpenLink, onOpenWorkspace, onNewFile, onNewNote, onQuickOpen, onOpenBrowser, browserOpening = false, hasWorkspace, tableActions }: Props = $props();
|
||||
let selectedLine = $state(1);
|
||||
let lineInfo = $state<GitLineInfo | null>(null);
|
||||
const git = $derived.by(() => { void $pluginHost; return pluginHost.get("git"); });
|
||||
$effect(() => { void buffer?.id; selectedLine = 1; });
|
||||
$effect(() => {
|
||||
void buffer?.id;
|
||||
const path = buffer?.relPath, line = selectedLine, provider = git;
|
||||
const dirty = buffer?.contents !== buffer?.saved;
|
||||
const available = buffer?.kind === "text" && !reading;
|
||||
lineInfo = null;
|
||||
if (!path || !provider || !available || dirty) return;
|
||||
let cancelled = false;
|
||||
const timer = setTimeout(() => {
|
||||
void provider.blame(path, line).then(info => { if (!cancelled) lineInfo = info; }).catch(() => {});
|
||||
}, 250);
|
||||
return () => { cancelled = true; clearTimeout(timer); };
|
||||
});
|
||||
function lineDate(value: string, detailed = false) {
|
||||
const date = new Date(/^\d+$/.test(value) ? Number(value) * 1000 : value);
|
||||
return Number.isNaN(date.getTime()) ? value : detailed ? date.toLocaleString() : date.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });
|
||||
}
|
||||
let previewMode = $state<"split" | "preview">("split");
|
||||
let modeControls = $state<HTMLDivElement>();
|
||||
let titleFocusId = $state<string | null>(null);
|
||||
@@ -100,6 +124,7 @@
|
||||
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
|
||||
{#if hasWorkspace}
|
||||
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button>
|
||||
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> New note</button>{/if}
|
||||
<button onclick={onQuickOpen}><Icon icon="search" /> Find a file <kbd>Ctrl P</kbd></button>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -109,6 +134,11 @@
|
||||
<div class="editor">
|
||||
<div class="chrome-bar">
|
||||
<span class="breadcrumb" title={buffer.relPath}>{buffer.relPath}</span>
|
||||
{#if lineInfo}
|
||||
<span class="line-history" title={`Line ${selectedLine} · ${lineInfo.author} · ${lineDate(lineInfo.date, true)}\n${lineInfo.summary} (${lineInfo.commit.slice(0, 8)})`}>
|
||||
<Icon icon="git" /><span>Ln {selectedLine} · {lineDate(lineInfo.date)}</span>
|
||||
</span>
|
||||
{/if}
|
||||
<div class="actions" bind:this={modeControls}>
|
||||
{#if canPreview}
|
||||
<ModeSwitcher
|
||||
@@ -141,10 +171,10 @@
|
||||
<div class="editor-wrap" class:hidden={reading && canPreview && previewMode === "preview"}>
|
||||
{#key buffer.id}
|
||||
{#if !isIde && canPreview && !reading}
|
||||
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount}
|
||||
<LiveWriter {buffer} {onChange} {onRenameTitle} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line}
|
||||
focusTitle={titleFocusId === buffer.id} onTitleFocused={() => { titleFocusId = null; }} />
|
||||
{:else}
|
||||
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {focusLine} {tableActions} {shouldFocusOnMount} />
|
||||
<EditorHost {buffer} {chrome} {onChange} {onInsertImage} {onOpenLink} {focusLine} {tableActions} {shouldFocusOnMount} onSelectionLine={(line) => selectedLine = line} />
|
||||
{/if}
|
||||
{/key}
|
||||
</div>
|
||||
@@ -161,6 +191,9 @@
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
.line-history { display: inline-flex; align-items: center; gap: 5px; min-width: 0; max-width: 40%; color: var(--rs-text-dim); font-size: 11px; white-space: nowrap; }
|
||||
.line-history span { overflow: hidden; text-overflow: ellipsis; }
|
||||
.line-history :global(svg) { width: 14px; height: 14px; flex-shrink: 0; }
|
||||
.breadcrumb { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; margin-right: auto; }
|
||||
.welcome-actions { display: flex; flex-wrap: wrap; justify-content: center; gap: 12px; }
|
||||
.welcome-actions button { display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); padding: 10px 14px; }
|
||||
@@ -193,9 +226,10 @@
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
height: 42px;
|
||||
min-height: 34px;
|
||||
flex-shrink: 0;
|
||||
padding: 0 10px;
|
||||
background: var(--rs-bg-elevated);
|
||||
background: var(--rs-bg);
|
||||
border-bottom: 1px solid var(--rs-border);
|
||||
color: var(--rs-text-dim);
|
||||
flex: 0 0 auto;
|
||||
|
||||
+185
-31
@@ -1,5 +1,6 @@
|
||||
<script lang="ts">
|
||||
import { untrack } from "svelte";
|
||||
import { onMount, tick, untrack } from "svelte";
|
||||
import { createNote, noteTemplates, type NoteTemplate } from "$lib/workspace/templates";
|
||||
import { confirm } from "@tauri-apps/plugin-dialog";
|
||||
import { requestText } from "$lib/workspace/dialogs.svelte";
|
||||
import type { TreeEntry } from "$lib/workspace/types";
|
||||
@@ -11,8 +12,11 @@
|
||||
workspaceList,
|
||||
workspaceRename,
|
||||
workspaceReveal,
|
||||
workspaceOpenDefault,
|
||||
workspaceOpenTerminal,
|
||||
} from "$lib/workspace/api";
|
||||
import { loadMarks, saveMarks, type Marks } from "$lib/workspace/marks";
|
||||
import { moveMarks, replayMoveMarks } from "$lib/workspace/treeMoveHistory";
|
||||
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
|
||||
import {
|
||||
dropHint,
|
||||
@@ -24,7 +28,7 @@
|
||||
type DropPlace,
|
||||
type DropTarget,
|
||||
} from "$lib/workspace/treeDrop";
|
||||
import { planRename, planDocumentTitleRename } from "$lib/workspace/renamePath";
|
||||
import { planRename } from "$lib/workspace/renamePath";
|
||||
import { selectTreePath, treeSelectionEdges, visibleTreePaths, type SelectionModifiers, type TreeSelection } from "$lib/workspace/treeSelection";
|
||||
import ContextMenu from "./ContextMenu.svelte";
|
||||
import type { MenuItem } from "./menuTypes";
|
||||
@@ -43,6 +47,8 @@
|
||||
onEntryRenamed?: (from: string, to: string) => void;
|
||||
onCreated?: (entry: TreeEntry) => void;
|
||||
keysActive?: boolean;
|
||||
showInternal?: boolean;
|
||||
onSaveTemplate?: (entry: TreeEntry) => void;
|
||||
};
|
||||
|
||||
let {
|
||||
@@ -55,6 +61,8 @@
|
||||
onEntryRenamed,
|
||||
onCreated,
|
||||
keysActive = true,
|
||||
showInternal = false,
|
||||
onSaveTemplate,
|
||||
}: Props = $props();
|
||||
|
||||
let expanded = $state<Set<string>>(new Set([""]));
|
||||
@@ -73,10 +81,21 @@
|
||||
const selectionEdges = $derived(treeSelectionEdges(visiblePaths, selection.paths));
|
||||
let renameRel = $state<string | null>(null);
|
||||
let renameDraft = $state("");
|
||||
let renameDocument = false;
|
||||
let skipClick = false;
|
||||
let imageLanding = $state(false);
|
||||
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 };
|
||||
let undoMoves = $state<MoveBatch[]>([]);
|
||||
let redoMoves = $state<MoveBatch[]>([]);
|
||||
let moving = $state(false);
|
||||
let templates = $state<NoteTemplate[]>([]);
|
||||
onMount(() => {
|
||||
const read = () => { void noteTemplates().then(value => templates = value); };
|
||||
read(); window.addEventListener("runestone-templates-changed", read);
|
||||
return () => window.removeEventListener("runestone-templates-changed", read);
|
||||
});
|
||||
$effect(() => () => cancelDrag?.());
|
||||
|
||||
const pins = $derived(new Set(marks.pins));
|
||||
@@ -117,7 +136,7 @@
|
||||
async function load(rel: string) {
|
||||
loading = true;
|
||||
try {
|
||||
const entries = await workspaceList(rel);
|
||||
const entries = await workspaceList(rel, showInternal);
|
||||
childrenMap = { ...childrenMap, [rel]: sortEntries(rel, entries) };
|
||||
void inspectPluginDocuments(entries);
|
||||
error = null;
|
||||
@@ -130,6 +149,7 @@
|
||||
|
||||
$effect(() => {
|
||||
void workspaceRoot;
|
||||
undoMoves = []; redoMoves = []; clipboard = null;
|
||||
expanded = new Set([""]);
|
||||
selection = { paths: new Set(), anchor: null };
|
||||
childrenMap = {};
|
||||
@@ -142,6 +162,7 @@
|
||||
|
||||
$effect(() => {
|
||||
void refreshToken;
|
||||
void showInternal;
|
||||
void $pluginDocumentTypes;
|
||||
const keys = untrack(() => Object.keys(childrenMap));
|
||||
for (const key of keys) {
|
||||
@@ -352,8 +373,7 @@
|
||||
function startRename(entry: TreeEntry) {
|
||||
selectOnly(entry.rel_path);
|
||||
renameRel = entry.rel_path;
|
||||
renameDocument = entry.kind === "file" && (!!$pluginDocuments[entry.rel_path] || /\.(md|markdown|mdown)$/i.test(entry.name));
|
||||
renameDraft = renameDocument ? entry.name.replace(/\.[^.]+$/, "") : entry.name;
|
||||
renameDraft = entry.name;
|
||||
}
|
||||
|
||||
function cancelRename() {
|
||||
@@ -366,7 +386,7 @@
|
||||
if (!from) {
|
||||
return;
|
||||
}
|
||||
const plan = renameDocument ? planDocumentTitleRename(from, renameDraft) : planRename(from, renameDraft);
|
||||
const plan = planRename(from, renameDraft);
|
||||
cancelRename();
|
||||
if (plan.action === "noop") {
|
||||
return;
|
||||
@@ -390,6 +410,26 @@
|
||||
if (!keysActive) {
|
||||
return;
|
||||
}
|
||||
if (event.target instanceof Element && treeElement?.contains(event.target)
|
||||
&& !event.target.closest('input, textarea, [contenteditable="true"]')
|
||||
&& (event.ctrlKey || event.metaKey) && !event.altKey) {
|
||||
const key = event.key.toLowerCase();
|
||||
if (key === "z" || key === "y") {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
void replayMoves(key === "y" || event.shiftKey);
|
||||
return;
|
||||
}
|
||||
const entries = selectionRoots([...selection.paths].map(findEntry).filter((entry): entry is TreeEntry => !!entry));
|
||||
if ((key === "c" || key === "x") && entries.length) {
|
||||
event.preventDefault(); clipboard = { root: workspaceRoot, paths: entries.map(entry => entry.rel_path), cut: key === "x" }; return;
|
||||
}
|
||||
if (key === "v") {
|
||||
event.preventDefault();
|
||||
const selected = entries[0];
|
||||
void pasteEntries(selected?.kind === "folder" ? selected.rel_path : selected ? parentRel(selected.rel_path) : "");
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (event.key !== "F2" || event.ctrlKey || event.metaKey || event.altKey) {
|
||||
return;
|
||||
}
|
||||
@@ -409,22 +449,23 @@
|
||||
startRename(entry);
|
||||
}
|
||||
|
||||
async function createIn(parent: string, kind: "folder" | "note") {
|
||||
async function createIn(parent: string, kind: "folder" | "note" | "file") {
|
||||
let name: string;
|
||||
if (kind === "note") {
|
||||
name = "untitled.md";
|
||||
} else {
|
||||
const typed = await requestText("Folder name", "folder");
|
||||
const typed = await requestText(kind === "folder" ? "Folder name" : "File name, including any extension", kind === "folder" ? "folder" : "Untitled");
|
||||
if (!typed) {
|
||||
return;
|
||||
}
|
||||
if (typed.includes("/") || typed.includes("\\")) {
|
||||
error = "Name cannot contain a path separator";
|
||||
const plan = planRename("", typed);
|
||||
if (plan.action === "error") {
|
||||
error = plan.message;
|
||||
return;
|
||||
}
|
||||
name = typed;
|
||||
name = typed.trim();
|
||||
}
|
||||
const finalName = uniqueName(namesIn(parent), name);
|
||||
const finalName = kind === "file" ? name : uniqueName(namesIn(parent), name);
|
||||
const rel = joinRel(parent, finalName);
|
||||
try {
|
||||
await workspaceCreate(rel, kind === "folder" ? "folder" : "file");
|
||||
@@ -438,7 +479,7 @@
|
||||
}
|
||||
await load(parent);
|
||||
onStatus?.(`Created ${rel}`);
|
||||
if (kind === "note") {
|
||||
if (kind !== "folder") {
|
||||
onCreated?.({ name: finalName, rel_path: rel, kind: "file" });
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -452,16 +493,22 @@
|
||||
}
|
||||
|
||||
async function handleDrop(target: TreeEntry, entries: TreeEntry[], place: DropPlace) {
|
||||
if (moving) return;
|
||||
const operationRoot = workspaceRoot;
|
||||
const before = structuredClone($state.snapshot(marks));
|
||||
const moves: MoveBatch["moves"] = [];
|
||||
const destination = place === "inside" ? target.rel_path : parentRel(target.rel_path);
|
||||
// Load collapsed folders before checking for name conflicts.
|
||||
try {
|
||||
childrenMap = { ...childrenMap, [destination]: sortEntries(destination, await workspaceList(destination)) };
|
||||
childrenMap = { ...childrenMap, [destination]: sortEntries(destination, await workspaceList(destination, showInternal)) };
|
||||
} catch (err) {
|
||||
error = err instanceof Error ? err.message : String(err);
|
||||
return;
|
||||
}
|
||||
const paths = new Map(entries.map(entry => [entry.rel_path, entry.rel_path]));
|
||||
moving = true;
|
||||
const result = await runTreeActions(place === "after" ? [...entries].reverse() : entries, async entry => {
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
const plan = planDrop(entry.rel_path, target, place, namesIn);
|
||||
if (plan.action === "noop") return;
|
||||
if (plan.action === "reorder") {
|
||||
@@ -471,14 +518,17 @@
|
||||
await load(plan.parent);
|
||||
return;
|
||||
}
|
||||
await workspaceRename(plan.from, plan.to);
|
||||
await workspaceRename(plan.from, plan.to, operationRoot);
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
moves.push({ from: plan.from, to: plan.to });
|
||||
paths.set(plan.from, plan.to);
|
||||
forgetFolder(plan.from);
|
||||
onEntryRenamed?.(plan.from, plan.to);
|
||||
const order = { ...marks.order };
|
||||
const next = moveMarks(marks, plan.from, plan.to);
|
||||
const order = { ...next.order };
|
||||
order[plan.fromParent] = plan.orderFrom;
|
||||
order[plan.toParent] = plan.orderTo;
|
||||
await persistMarks({ ...marks, order });
|
||||
await persistMarks({ ...next, order });
|
||||
await load(plan.fromParent);
|
||||
if (plan.toParent !== plan.fromParent) {
|
||||
await load(plan.toParent);
|
||||
@@ -488,6 +538,82 @@
|
||||
selection = { paths: new Set(paths.values()), anchor: paths.values().next().value ?? null };
|
||||
error = result.failures.length ? result.failures.join("\n") : null;
|
||||
onStatus?.(`Moved ${result.completed.length} of ${entries.length} items`);
|
||||
if (moves.length || JSON.stringify(before.order) !== JSON.stringify(marks.order)) {
|
||||
undoMoves = [...undoMoves, { moves, before, after: structuredClone($state.snapshot(marks)) }];
|
||||
redoMoves = [];
|
||||
}
|
||||
moving = false;
|
||||
await focusTreePath(paths.values().next().value);
|
||||
}
|
||||
|
||||
async function focusTreePath(path?: string) {
|
||||
await tick();
|
||||
const target = [...treeElement.querySelectorAll<HTMLElement>("[data-tree-rel]")].find(node => node.dataset.treeRel === path);
|
||||
(target ?? treeElement).focus({ preventScroll: true });
|
||||
}
|
||||
|
||||
async function replayMoves(redo = false) {
|
||||
if (moving) return;
|
||||
const stack = redo ? redoMoves : undoMoves;
|
||||
const batch = stack.at(-1);
|
||||
if (!batch) return;
|
||||
const operationRoot = workspaceRoot;
|
||||
moving = true;
|
||||
const applied: { from: string; to: string }[] = [];
|
||||
try {
|
||||
for (const move of redo ? batch.moves : [...batch.moves].reverse()) {
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
const from = redo ? move.from : move.to, to = redo ? move.to : move.from;
|
||||
await workspaceRename(from, to, operationRoot);
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
applied.push({ from, to });
|
||||
onEntryRenamed?.(from, to);
|
||||
}
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
||||
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("");
|
||||
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.");
|
||||
} catch (reason) {
|
||||
const rollbackErrors: string[] = [];
|
||||
for (const move of applied.reverse()) {
|
||||
if (workspaceRoot !== operationRoot) { rollbackErrors.push("The original workspace is unavailable."); break; }
|
||||
try { await workspaceRename(move.to, move.from, operationRoot); onEntryRenamed?.(move.to, move.from); }
|
||||
catch (failure) { rollbackErrors.push(String(failure)); }
|
||||
}
|
||||
if (rollbackErrors.length) { undoMoves = []; redoMoves = []; }
|
||||
error = [String(reason), ...rollbackErrors].join("\n");
|
||||
} finally { moving = false; }
|
||||
}
|
||||
|
||||
async function pasteEntries(parent: string) {
|
||||
if (!clipboard || clipboard.root !== workspaceRoot || moving) return;
|
||||
const source = clipboard;
|
||||
const operationRoot = workspaceRoot;
|
||||
const before = structuredClone($state.snapshot(marks));
|
||||
const moves: MoveBatch["moves"] = [];
|
||||
moving = true;
|
||||
const result = await runTreeActions(source.paths.map(rel_path => ({ rel_path, name: rel_path.split("/").pop()!, kind: "file" as const })), async entry => {
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped.");
|
||||
if (source.cut) {
|
||||
const to = joinRel(parent, entry.name);
|
||||
if (to === entry.rel_path) return;
|
||||
await workspaceRename(entry.rel_path, to, operationRoot);
|
||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped.");
|
||||
moves.push({ from: entry.rel_path, to });
|
||||
onEntryRenamed?.(entry.rel_path, to);
|
||||
await persistMarks(moveMarks(marks, entry.rel_path, to));
|
||||
} else await workspaceCopy(entry.rel_path, parent, operationRoot);
|
||||
});
|
||||
if (moves.length) { undoMoves = [...undoMoves, { moves, before, after: structuredClone($state.snapshot(marks)) }]; redoMoves = []; }
|
||||
if (source.cut) clipboard = result.failures.length ? { ...source, paths: source.paths.filter(path => !moves.some(move => move.from === path)) } : null;
|
||||
for (const folder of new Set([parent, ...source.paths.map(parentRel)])) await load(folder);
|
||||
error = result.failures.length ? result.failures.join("\n") : null;
|
||||
moving = false;
|
||||
}
|
||||
|
||||
async function copyEntries(entries: TreeEntry[]) {
|
||||
@@ -519,23 +645,25 @@
|
||||
}
|
||||
|
||||
function paneMenuItems(parent: string): MenuItem[] {
|
||||
const fromTemplate = async (template?: NoteTemplate) => {
|
||||
try {
|
||||
const path = await createNote(parent, template);
|
||||
await load(parent);
|
||||
onCreated?.({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
||||
} catch (reason) { error = String(reason); }
|
||||
};
|
||||
return [
|
||||
{
|
||||
kind: "action",
|
||||
label: "Create folder",
|
||||
icon: "folder-plus",
|
||||
run: () => {
|
||||
void createIn(parent, "folder");
|
||||
},
|
||||
},
|
||||
{
|
||||
kind: "action",
|
||||
label: "Create new note",
|
||||
label: "New file…",
|
||||
icon: "file-plus",
|
||||
run: () => {
|
||||
void createIn(parent, "note");
|
||||
},
|
||||
run: () => { void createIn(parent, "file"); },
|
||||
},
|
||||
...(templates.length ? [{ kind: "group" as const, label: "New note", icon: "file-plus" as const, 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); } })),
|
||||
] }] : [{ 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 => ({
|
||||
kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus",
|
||||
run: () => { void (async () => {
|
||||
@@ -557,11 +685,24 @@
|
||||
];
|
||||
}
|
||||
|
||||
function folderActions(parent: string): MenuItem[] {
|
||||
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); } },
|
||||
];
|
||||
}
|
||||
|
||||
function menuItems(entry: TreeEntry | null): MenuItem[] {
|
||||
if (!entry) {
|
||||
return [
|
||||
...paneMenuItems(""),
|
||||
{ kind: "sep" },
|
||||
...folderActions(""),
|
||||
{ kind: "sep" },
|
||||
{
|
||||
kind: "action",
|
||||
label: "Show in Explorer",
|
||||
@@ -584,6 +725,17 @@
|
||||
: [];
|
||||
return [
|
||||
...createItems,
|
||||
...(!multiple && entry.kind === "file" && /\.md$/i.test(entry.name) && onSaveTemplate ? [
|
||||
{ kind: "action" as const, label: "Save as template", icon: "copy" as const, run: () => onSaveTemplate?.(entry) },
|
||||
] : []),
|
||||
...(!multiple && entry.kind === "file" ? [
|
||||
{ kind: "action" as const, label: "Open in new tab", icon: "file-plus" as const, run: () => onOpenFile(entry, true) },
|
||||
{ kind: "action" as const, label: "Open in default app", icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
|
||||
] : []),
|
||||
...folderActions(entry.kind === "folder" ? entry.rel_path : parentRel(entry.rel_path)),
|
||||
{ kind: "sep" },
|
||||
{ kind: "action", label: "Cut", icon: "cut", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: true }; } },
|
||||
{ kind: "action", label: "Copy", icon: "copy", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: false }; } },
|
||||
{
|
||||
kind: "action",
|
||||
label: multiple ? `Make copies (${entries.length})` : "Make a copy",
|
||||
@@ -671,7 +823,7 @@
|
||||
|
||||
<div class="wrap">
|
||||
<div class="ribbon tree-tools">
|
||||
<IconButton icon="file-plus" label="New file" onclick={() => void createIn("", "note")} />
|
||||
<IconButton icon="file-plus" label="New file" onclick={() => void createIn("", "file")} />
|
||||
<IconButton icon="folder-plus" label="New folder" onclick={() => void createIn("", "folder")} />
|
||||
<IconButton
|
||||
icon="sort"
|
||||
@@ -691,7 +843,9 @@
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
bind:this={treeElement}
|
||||
class="tree"
|
||||
tabindex="-1"
|
||||
role="navigation"
|
||||
aria-label="Workspace files"
|
||||
oncontextmenu={(event) => {
|
||||
|
||||
@@ -1,20 +1,22 @@
|
||||
<script lang="ts">
|
||||
import PluginManager from "$lib/plugins/PluginManager.svelte";
|
||||
import AppearanceSettings from "$lib/theme/AppearanceSettings.svelte";
|
||||
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
|
||||
import PluginSettings from "$lib/plugins/PluginSettings.svelte";
|
||||
import { installedPlugins, pluginTools } from "$lib/plugins/external";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import { onMount, untrack } from "svelte";
|
||||
import { onMount, untrack, type Snippet } from "svelte";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import IconButton, { type IconName } from "$lib/ui/IconButton.svelte";
|
||||
import { DEFAULT_SETTINGS, MIN_AUTOSAVE_SECONDS, MAX_AUTOSAVE_SECONDS, validAutosaveSeconds, type AppSettings } from "$lib/workspace/settings";
|
||||
import { version, license } from "../../../package.json";
|
||||
|
||||
let { settings, help = false, standalone = false, windowError = "", onSave, onClose }: {
|
||||
let { settings, help = false, standalone = false, windowError = "", windowControls, onSave, onClose }: {
|
||||
settings: AppSettings;
|
||||
help?: boolean;
|
||||
standalone?: boolean;
|
||||
windowError?: string;
|
||||
windowControls?: Snippet;
|
||||
onSave: (value: AppSettings) => void;
|
||||
onClose: () => void;
|
||||
} = $props();
|
||||
@@ -22,6 +24,7 @@
|
||||
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [
|
||||
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
|
||||
{ id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" },
|
||||
{ id: "appearance", label: "Appearance", icon: "sun", keywords: "theme colors light dark GPT Claude Terminal Sakura" },
|
||||
{ id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" },
|
||||
];
|
||||
let section = $state<Section>(untrack(() => help ? "about" : "general"));
|
||||
@@ -76,9 +79,13 @@
|
||||
</script>
|
||||
|
||||
<dialog bind:this={dialog} class:help class:standalone aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}>
|
||||
<header>
|
||||
<h1 id="settings-title">{help ? "Help and about" : "Settings"}</h1>
|
||||
<IconButton icon="close" label={help ? "Close help" : "Close settings"} onclick={onClose} />
|
||||
<header class:window-header={!!windowControls} data-tauri-drag-region={windowControls ? true : undefined}>
|
||||
<h1 id="settings-title" data-tauri-drag-region={windowControls ? true : undefined}>{help ? "Help and about" : "Settings"}</h1>
|
||||
{#if windowControls}
|
||||
{@render windowControls()}
|
||||
{:else}
|
||||
<IconButton icon="close" label={help ? "Close help" : "Close settings"} onclick={onClose} />
|
||||
{/if}
|
||||
</header>
|
||||
<div class="body">
|
||||
{#if !help}
|
||||
@@ -104,6 +111,10 @@
|
||||
<p class="intro">Choose how RuneStone saves your work.</p>
|
||||
<h3>Files</h3>
|
||||
<div class="card">
|
||||
<div class="setting-row">
|
||||
<div><label for="show-internal-folder">Show .runestone folder</label><p id="internal-folder-description">Show workspace settings and plugin data in the file tree.</p></div>
|
||||
<input id="show-internal-folder" class="switch" type="checkbox" role="switch" aria-describedby="internal-folder-description" checked={settings.showInternalFolder} onchange={event => apply({ ...settings, showInternalFolder: event.currentTarget.checked })} />
|
||||
</div>
|
||||
<div class="setting-row">
|
||||
<div><label for="autosave-enabled">Auto-save</label><p id="autosave-description">Save changed notes and scripts, including background tabs.</p></div>
|
||||
<input id="autosave-enabled" class="switch" type="checkbox" role="switch" aria-describedby="autosave-description" checked={settings.autosaveEnabled} onchange={event => { apply({ ...settings, autosaveEnabled: event.currentTarget.checked }); event.currentTarget.checked = settings.autosaveEnabled; }} />
|
||||
@@ -117,6 +128,8 @@
|
||||
<div class="section-footer"><button class="text-button" onclick={() => { seconds = DEFAULT_SETTINGS.autosaveSeconds; apply({ ...DEFAULT_SETTINGS }); }}>Restore defaults</button><span>Default: every 5 seconds</span></div>
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{message}</p>
|
||||
{:else if selected.id === "appearance"}
|
||||
<AppearanceSettings />
|
||||
{:else if selected.id === "plugins"}
|
||||
<PluginManager />
|
||||
{:else if selected.id === "browser"}
|
||||
@@ -141,40 +154,42 @@
|
||||
dialog::backdrop { background: #0008; }
|
||||
dialog.standalone { width: 100vw; height: 100dvh; margin: 0; border: 0; border-radius: 0; box-shadow: none; }
|
||||
dialog.help { width: min(650px, calc(100vw - 32px)); }
|
||||
header { height: 48px; padding: 0 14px 0 20px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
h1 { font-size: 14px; font-weight: 600; margin: 0; }
|
||||
.body { display: flex; height: calc(100% - 48px); }
|
||||
aside { width: 220px; flex-shrink: 0; padding: 18px 12px; background: var(--rs-bg-elevated); border-right: 1px solid var(--rs-border); display: flex; flex-direction: column; overflow: auto; }
|
||||
.search { display: flex; gap: 7px; align-items: center; background: var(--rs-bg-active); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 8px; color: var(--rs-text-dim); }
|
||||
header { height: var(--rs-titlebar-height); padding: 0 4px 0 12px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid var(--rs-border); background: var(--rs-bg-elevated); }
|
||||
header.window-header { padding-right: 0; user-select: none; }
|
||||
h1 { font-size: 13px; font-weight: 600; margin: 0; }
|
||||
.body { display: flex; height: calc(100% - var(--rs-titlebar-height)); min-height: 0; }
|
||||
aside { width: 220px; flex-shrink: 0; padding: 12px 8px; background: var(--rs-bg-elevated); border-right: 1px solid var(--rs-border); display: flex; flex-direction: column; overflow: auto; }
|
||||
.search { display: flex; gap: var(--rs-settings-gap); align-items: center; min-height: var(--rs-settings-control-height); background: var(--rs-bg-active); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 4px 8px; color: var(--rs-text-dim); }
|
||||
.search:focus-within { outline: 2px solid var(--rs-accent); }
|
||||
.search input { width: 100%; min-width: 0; border: 0; padding: 0; outline: none; background: transparent; color: var(--rs-text); }
|
||||
.nav-heading { margin: 24px 10px 8px; font-size: 11px; color: var(--rs-text-dim); }
|
||||
nav { display: flex; flex-direction: column; gap: 4px; }
|
||||
nav button { display: flex; align-items: center; gap: 10px; width: 100%; padding: 10px; border: 0; border-radius: var(--rs-control-radius); background: transparent; text-align: left; }
|
||||
.nav-heading { margin: 16px 8px 6px; font-size: 11px; color: var(--rs-text-dim); }
|
||||
nav { display: flex; flex-direction: column; gap: 2px; }
|
||||
nav button { display: flex; align-items: center; gap: var(--rs-settings-gap); width: 100%; min-height: var(--rs-settings-control-height); padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; text-align: left; }
|
||||
nav button:hover { background: var(--rs-bg-active); }
|
||||
nav button.active { background: var(--rs-item-selection-bg); box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); border-radius: var(--rs-item-selection-radius); }
|
||||
.scope { margin: auto 10px 0; padding-top: 24px; color: var(--rs-text-dim); font-size: 12px; }
|
||||
.content { padding: 30px 32px; flex: 1; min-width: 0; overflow-y: auto; }
|
||||
h2 { margin: 0; font-size: 23px; font-weight: 600; color: var(--rs-text-strong); }
|
||||
h3 { margin: 28px 0 12px; font-size: 14px; font-weight: 600; }
|
||||
p { color: var(--rs-text-dim); line-height: 1.6; }
|
||||
.intro { margin: 7px 0 24px; }
|
||||
.card { padding: 0 20px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: 10px; }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 22px 0; }
|
||||
.content { padding: 20px 24px; flex: 1; min-width: 0; min-height: 0; overflow-y: auto; }
|
||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); font-weight: 600; color: var(--rs-text-strong); }
|
||||
h3 { margin: var(--rs-settings-section-gap) 0 8px; font-size: 13px; font-weight: 600; }
|
||||
p { color: var(--rs-text-dim); line-height: 1.45; }
|
||||
.intro { margin: 6px 0 var(--rs-settings-section-gap); }
|
||||
.card { padding: 0 12px; background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.setting-row { display: flex; align-items: center; justify-content: space-between; gap: 16px; padding: var(--rs-settings-row-padding) 0; }
|
||||
.setting-row > div:first-child { min-width: 0; }
|
||||
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
|
||||
.setting-row label { font-weight: 500; }
|
||||
.setting-row p { margin: 5px 0 0; font-size: 12px; }
|
||||
.setting-row p { margin: 3px 0 0; font-size: var(--rs-settings-description-size); }
|
||||
.switch { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; margin: 0; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
|
||||
.switch::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; transition: transform .12s; }
|
||||
.switch:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
|
||||
.switch:checked::before { transform: translateX(16px); background: var(--rs-bg); }
|
||||
.interval { display: flex; flex-direction: column; align-items: flex-end; gap: 5px; font-size: 11px; color: var(--rs-text-dim); }
|
||||
.interval input { width: 84px; padding: 9px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font-size: 14px; }
|
||||
.interval input { width: 72px; min-height: var(--rs-settings-control-height); padding: 4px 6px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg); color: var(--rs-text); font-size: 13px; }
|
||||
.interval input:disabled { opacity: .45; }
|
||||
.note, .section-footer, .about-note { font-size: 12px; }
|
||||
.note { margin: 16px 0 24px; }
|
||||
.note { margin: 10px 0 var(--rs-settings-section-gap); }
|
||||
.section-footer { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; justify-content: space-between; color: var(--rs-text-dim); }
|
||||
.text-button { border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); padding: 8px 12px; color: var(--rs-text); }
|
||||
.text-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); padding: 4px 8px; color: var(--rs-text); }
|
||||
.text-button:hover { background: var(--rs-bg-active); }
|
||||
.saved { font-size: 12px; color: var(--rs-ok); min-height: 20px; }
|
||||
.error { color: var(--rs-error); }
|
||||
@@ -193,11 +208,11 @@
|
||||
.about-note { text-align: center; margin: 20px 0 0; }
|
||||
@media (max-width: 660px) {
|
||||
.body { flex-direction: column; }
|
||||
aside { width: 100%; padding: 12px; border-right: 0; border-bottom: 1px solid var(--rs-border); flex-shrink: 0; }
|
||||
nav { flex-direction: row; margin-top: 10px; }
|
||||
nav button { width: auto; flex: 1; padding: 8px; gap: 6px; }
|
||||
aside { width: 100%; max-height: 40%; padding: 8px; border-right: 0; border-bottom: 1px solid var(--rs-border); flex-shrink: 0; }
|
||||
nav { flex-direction: row; flex-wrap: wrap; margin-top: 6px; }
|
||||
nav button { width: auto; flex: 1 1 auto; padding: 5px 8px; gap: 6px; }
|
||||
.nav-heading, .scope { display: none; }
|
||||
.content { padding: 24px 18px; }
|
||||
.content { padding: 16px 12px; }
|
||||
.setting-row { gap: 14px; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { isTauri } from "@tauri-apps/api/core";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import SettingsDialog from "./SettingsDialog.svelte";
|
||||
import WindowControls from "$lib/ui/WindowControls.svelte";
|
||||
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
||||
|
||||
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
|
||||
@@ -32,4 +33,5 @@
|
||||
}
|
||||
</script>
|
||||
|
||||
<SettingsDialog {settings} standalone windowError={error} onSave={save} onClose={() => void close()} />
|
||||
{#snippet controls()}<WindowControls onError={message => error = message} />{/snippet}
|
||||
<SettingsDialog {settings} standalone windowError={error} windowControls={isTauri() ? controls : undefined} onSave={save} onClose={() => void close()} />
|
||||
|
||||
@@ -18,9 +18,10 @@
|
||||
tabActions?: (tab: WorkbenchTab) => ActionMenuItem[];
|
||||
tabDragData?: (tab: WorkbenchTab) => string | undefined;
|
||||
onDropTab?: (data: string, index: number) => void;
|
||||
onDetach?: (tab: WorkbenchTab) => void;
|
||||
};
|
||||
|
||||
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab }: Props = $props();
|
||||
let { tabs, activePath, onSelect, onClose, onMove, onCloseTabs, onPin, fileActions, tabActions = () => [], tabDragData = () => undefined, onDropTab, onDetach }: Props = $props();
|
||||
const transferType = "application/x-runestone-tab";
|
||||
let bar: HTMLDivElement;
|
||||
let dragged = $state<string | null>(null);
|
||||
@@ -168,6 +169,8 @@
|
||||
cancelDrag();
|
||||
closeMenu();
|
||||
suppressClick = false;
|
||||
const pointerTarget = event.currentTarget as HTMLElement;
|
||||
pointerTarget.setPointerCapture(event.pointerId);
|
||||
const startX = event.clientX, startY = event.clientY, pointerId = event.pointerId;
|
||||
let x = startX, y = startY, started = false, destination: number | null = null, frame = 0;
|
||||
const update = () => {
|
||||
@@ -192,6 +195,7 @@
|
||||
frame = requestAnimationFrame(scroll);
|
||||
};
|
||||
const clean = () => {
|
||||
if (pointerTarget.hasPointerCapture(pointerId)) pointerTarget.releasePointerCapture(pointerId);
|
||||
cancelAnimationFrame(frame);
|
||||
dragged = dropBefore = dropAfter = null;
|
||||
window.removeEventListener("pointermove", onMovePointer);
|
||||
@@ -216,6 +220,10 @@
|
||||
const target = destination;
|
||||
clean();
|
||||
if (started && target !== null) void move(path, target);
|
||||
else if (started && (x < 0 || y < 0 || x > window.innerWidth || y > window.innerHeight)) {
|
||||
const tab = tabs.find(tab => tab.relPath === path);
|
||||
if (tab) onDetach?.(tab);
|
||||
}
|
||||
};
|
||||
const onEscape = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); clean(); }
|
||||
@@ -267,7 +275,11 @@
|
||||
onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }}
|
||||
draggable={!!tab.draggable}
|
||||
ondragstart={(event) => startTabTransfer(event, tab)}
|
||||
ondragend={finishTabTransfer}
|
||||
ondragend={(event) => {
|
||||
const outside = event.clientX < 0 || event.clientY < 0 || event.clientX > window.innerWidth || event.clientY > window.innerHeight;
|
||||
if (dragged && event.dataTransfer?.dropEffect === "none" && outside) onDetach?.(tab);
|
||||
finishTabTransfer();
|
||||
}}
|
||||
onkeydown={(event) => onKey(event, tab.relPath)}
|
||||
oncontextmenu={(event) => { event.preventDefault(); event.stopPropagation(); showMenu(event.currentTarget, tab.relPath, event.clientX, event.clientY); }}
|
||||
onmousedown={onMiddleDown}
|
||||
@@ -300,7 +312,7 @@
|
||||
min-height: 32px;
|
||||
overflow-x: auto;
|
||||
background: var(--rs-bg-elevated);
|
||||
border-bottom: 1px solid var(--rs-border);
|
||||
box-shadow: inset 0 -1px var(--rs-border);
|
||||
}
|
||||
.tabs:empty { min-width: 80px; }
|
||||
.tabs.receiving { box-shadow: inset 0 -2px var(--rs-accent); }
|
||||
@@ -311,17 +323,19 @@
|
||||
align-items: center;
|
||||
max-width: 220px;
|
||||
flex-shrink: 0;
|
||||
border-radius: var(--rs-item-selection-radius);
|
||||
border-radius: var(--rs-item-selection-radius) var(--rs-item-selection-radius) 0 0;
|
||||
border-right: 1px solid var(--rs-border);
|
||||
background: var(--rs-bg);
|
||||
background: transparent;
|
||||
border-bottom: 1px solid var(--rs-border);
|
||||
}
|
||||
|
||||
.tab.active {
|
||||
background: var(--rs-item-selection-bg);
|
||||
box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border);
|
||||
background: var(--rs-bg);
|
||||
border-bottom-color: transparent;
|
||||
}
|
||||
|
||||
.tab:hover { background: var(--rs-bg-active); }
|
||||
.tab:focus-within { box-shadow: inset 0 0 0 var(--rs-item-selection-width) var(--rs-item-selection-border); }
|
||||
.tab:not(.active):hover { background: var(--rs-bg-active); }
|
||||
.tab.dragging { opacity: 0.5; }
|
||||
.tabs:has(.dragging) .tab > button:first-child { cursor: grabbing; }
|
||||
.tab.drop-before::before, .tab.drop-after::after {
|
||||
|
||||
@@ -133,6 +133,7 @@
|
||||
{#if isRenaming}
|
||||
<input
|
||||
class="rename"
|
||||
aria-label="File or folder name, including any extension"
|
||||
value={renameDraft}
|
||||
use:focusSelect
|
||||
onclick={(event) => event.stopPropagation()}
|
||||
@@ -155,7 +156,7 @@
|
||||
{:else}
|
||||
<span class="name">{label}</span>
|
||||
{/if}
|
||||
{#if ext}
|
||||
{#if ext && !isRenaming}
|
||||
<span class="mark ext">{ext}</span>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -220,7 +221,7 @@
|
||||
}
|
||||
|
||||
.row.active {
|
||||
background: var(--rs-bg-active);
|
||||
background: var(--rs-item-selection-bg);
|
||||
color: var(--rs-text-strong);
|
||||
}
|
||||
|
||||
@@ -236,12 +237,15 @@
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
visibility: hidden;
|
||||
border: var(--rs-item-selection-width) solid var(--rs-item-selection-border);
|
||||
border-top: 0;
|
||||
border-bottom: 0;
|
||||
border-radius: inherit;
|
||||
}
|
||||
|
||||
:global(.tree:focus-within) .selection-outline { visibility: visible; }
|
||||
|
||||
.selection-outline.full-top { border-top: var(--rs-item-selection-width) solid var(--rs-item-selection-border); }
|
||||
.selection-outline.full-bottom { border-bottom: var(--rs-item-selection-width) solid var(--rs-item-selection-border); }
|
||||
|
||||
|
||||
+187
-42
@@ -3,10 +3,10 @@
|
||||
import PluginTools from "$lib/plugins/PluginTools.svelte";
|
||||
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
|
||||
import PluginEditor from "$lib/plugins/PluginEditor.svelte";
|
||||
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
|
||||
import { pluginSplits, pinPluginEditor, pluginTabActions, pluginTabState, restorePluginTab, pluginTabDragData, dropPluginTab, findPluginEditor } from "$lib/plugins/external";
|
||||
import { containsPane, paneBounds } from "$lib/workspace/splitLayout";
|
||||
import { pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
|
||||
import { onMount, tick } from "svelte";
|
||||
import { pluginSidebar, closePluginSidebar, pluginNavigation, openPluginView, pluginView, pluginEditors, pluginEditorActive, selectPluginEditor, closePluginEditor, openPluginDocument, renamePluginDocuments, removePluginDocuments, notifyPluginWorkspace, guardPluginWrites, handlePluginFileOpen, handlePluginDocumentRename, cancelPluginDocumentOpen, type OpenPluginView } from "$lib/plugins/external";
|
||||
import { onMount, tick, untrack } from "svelte";
|
||||
import { selectedEditorText } from "$lib/editor/selection";
|
||||
import { pluginHost } from "$lib/plugins/registry";
|
||||
import type { Contributions } from "$lib/plugins/contracts";
|
||||
@@ -17,7 +17,8 @@
|
||||
import { Documents } from "$lib/workspace/documents";
|
||||
import { tabsToClose, type TabCloseScope } from "$lib/workspace/tabActions";
|
||||
import { orderWorkbenchTabs, type WorkbenchTab } from "$lib/workspace/workbenchTabs";
|
||||
import type { ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
|
||||
import { createNote, noteTemplates, saveNoteTemplate, type NoteTemplate } from "$lib/workspace/templates";
|
||||
import { requestText } from "$lib/workspace/dialogs.svelte";
|
||||
import TextDialog from "./TextDialog.svelte";
|
||||
import QuickOpen from "./QuickOpen.svelte";
|
||||
@@ -25,6 +26,7 @@
|
||||
import SettingsDialog from "./SettingsDialog.svelte";
|
||||
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
|
||||
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
||||
import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout, type WorkbenchLayout } from "$lib/workspace/workbenchLayout";
|
||||
import FileTree from "./FileTree.svelte";
|
||||
import EditorPane from "./EditorPane.svelte";
|
||||
import TabBar from "./TabBar.svelte";
|
||||
@@ -79,13 +81,15 @@
|
||||
let error = $state<string | null>(null);
|
||||
let refreshToken = $state(0);
|
||||
let view = $state<Chrome>("Writing");
|
||||
let leftWidth = $state(260);
|
||||
let rightWidth = $state(240);
|
||||
let layoutReady = $state(false);
|
||||
let leftWidth = $state(DEFAULT_WORKBENCH_LAYOUT.leftWidth);
|
||||
let rightWidth = $state(DEFAULT_WORKBENCH_LAYOUT.rightWidth);
|
||||
let bottomHeight = $state(180);
|
||||
let leftView = $state<"files" | "search" | "bookmarks">("files");
|
||||
let leftView = $state<WorkbenchLayout["leftView"]>(DEFAULT_WORKBENCH_LAYOUT.leftView);
|
||||
let searchRequest = $state<{ text: string; id: number } | null>(null);
|
||||
let leftOpen = $state(true);
|
||||
let rightOpen = $state(true);
|
||||
let leftOpen = $state(DEFAULT_WORKBENCH_LAYOUT.leftOpen);
|
||||
let rightOpen = $state(DEFAULT_WORKBENCH_LAYOUT.rightOpen);
|
||||
$effect(() => { if ($pluginSidebar) leftOpen = true; });
|
||||
let terminalOpen = $state(false);
|
||||
let reading = $state(false);
|
||||
let quickOpen = $state(false);
|
||||
@@ -94,6 +98,8 @@
|
||||
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 ribbonNavigation = $derived($pluginNavigation.filter(item => item.placement !== "sidebar" && !item.toolbar));
|
||||
const browserContribution = $derived.by(() => { void $pluginHost; return pluginHost.get("browser"); });
|
||||
let browserOpening = $state(false);
|
||||
async function openBrowser() {
|
||||
@@ -125,6 +131,7 @@
|
||||
|
||||
let saving = $state(false);
|
||||
let switching = false;
|
||||
let workbenchReady = $state(false);
|
||||
let documents: Documents | null = null;
|
||||
let editorPane: EditorPane | undefined = $state();
|
||||
let closingTabs = false;
|
||||
@@ -165,6 +172,13 @@
|
||||
})),
|
||||
]);
|
||||
const workingTabs = $derived(orderWorkbenchTabs(availableTabs, tabOrder));
|
||||
$effect(() => {
|
||||
if (workbenchReady && !availableTabs.length) untrack(() => {
|
||||
const previousError = error;
|
||||
newTab();
|
||||
error = previousError;
|
||||
});
|
||||
});
|
||||
function workingTabDragData(tab: WorkbenchTab) {
|
||||
const view = $pluginEditors.find(view => view.key === tab.id);
|
||||
return view ? pluginTabDragData(view) : undefined;
|
||||
@@ -241,7 +255,9 @@
|
||||
}
|
||||
|
||||
function selectLeft(next: "files" | "search" | "bookmarks") {
|
||||
if (leftOpen && leftView === next) {
|
||||
const hadSidebar = !!$pluginSidebar;
|
||||
closePluginSidebar();
|
||||
if (!hadSidebar && leftOpen && leftView === next) {
|
||||
leftOpen = false;
|
||||
return;
|
||||
}
|
||||
@@ -270,9 +286,31 @@
|
||||
documents = createDocuments();
|
||||
status = workspace.root;
|
||||
refreshToken += 1;
|
||||
const token = new URLSearchParams(location.search).get("tabTransfer");
|
||||
if (token && /^[0-9a-f-]{36}$/i.test(token)) {
|
||||
const key = `runestone.tab-transfer.${token}`;
|
||||
const raw = localStorage.getItem(key);
|
||||
if (raw) {
|
||||
const transfer = JSON.parse(raw);
|
||||
if (transfer.root === workspace.root && transfer.created > Date.now() - 120000
|
||||
&& (transfer.buffer || transfer.plugin)) {
|
||||
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") documents.importTab(transfer.buffer);
|
||||
else if (transfer.plugin) {
|
||||
const deadline = Date.now() + 15000;
|
||||
while (!await restorePluginTab(transfer.plugin)) {
|
||||
if (Date.now() > deadline) throw new Error("Enable the plugin before moving this tab.");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
} else throw new Error("Invalid tab transfer.");
|
||||
reading = transfer.reading === true;
|
||||
localStorage.setItem(key + ".accepted", "true");
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) { error = String(err); }
|
||||
finally { switching = false; }
|
||||
finally { switching = false; workbenchReady = true; }
|
||||
}
|
||||
|
||||
function selectTab(relPath: string) {
|
||||
@@ -307,7 +345,40 @@
|
||||
}
|
||||
function workingTabActions(item: WorkbenchTab): ActionMenuItem[] {
|
||||
const tab = workingTabs.find(tab => tab.id === item.id);
|
||||
return tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
|
||||
const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
|
||||
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
|
||||
return tab ? [{ label: "Open in new window", icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
|
||||
}
|
||||
async function detachTab(item: WorkbenchTab) {
|
||||
const tab = workingTabs.find(tab => tab.id === item.id);
|
||||
if (!tab || !workspace || !desktop) return;
|
||||
if ("plugin" in tab) {
|
||||
const action = pluginTabActions(tab.plugin).find(action => "label" in action && /(?:move|open).*new window/i.test(action.label));
|
||||
if (action && "run" in action && !action.disabled) { action.run?.(); return; }
|
||||
}
|
||||
const current = documents;
|
||||
const snapshot = JSON.stringify("buffer" in tab ? tab.buffer : pluginTabState(tab.plugin));
|
||||
const token = crypto.randomUUID(), key = `runestone.tab-transfer.${token}`;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const finish = () => {
|
||||
window.removeEventListener("storage", accepted);
|
||||
clearTimeout(timer);
|
||||
localStorage.removeItem(key);
|
||||
localStorage.removeItem(key + ".accepted");
|
||||
};
|
||||
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);
|
||||
} else if (JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key);
|
||||
finish();
|
||||
};
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify({ root: workspace.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }));
|
||||
window.addEventListener("storage", accepted);
|
||||
timer = setTimeout(() => { finish(); error = "The new window did not accept the tab. The source tab remains open."; }, 30000);
|
||||
await workspaceOpenWindow(workspace.root, token);
|
||||
} catch (reason) { finish(); error = String(reason); }
|
||||
}
|
||||
function pinWorkingTab(path: string) {
|
||||
const tab = workingTabs.find(tab => tab.relPath === path);
|
||||
@@ -372,6 +443,7 @@
|
||||
const items: ActionMenuItem[] = [];
|
||||
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
|
||||
items.push(
|
||||
{ label: "Save as template", icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
|
||||
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => editorPane?.toggleReadingView() },
|
||||
{ label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome },
|
||||
);
|
||||
@@ -544,8 +616,47 @@
|
||||
}
|
||||
}
|
||||
|
||||
async function saveTemplate(entry: TreeEntry) {
|
||||
const name = await requestText("Template name", entry.name.replace(/\.md$/i, ""));
|
||||
if (!name) return;
|
||||
try {
|
||||
const contents = documents?.buffers.find(tab => tab.relPath === entry.rel_path)?.contents ?? await workspaceRead(entry.rel_path);
|
||||
await saveNoteTemplate(name, contents);
|
||||
status = `Saved template: ${name}`;
|
||||
} catch (reason) { error = String(reason); }
|
||||
}
|
||||
|
||||
async function newNote(event?: MouseEvent) {
|
||||
if (!workspace) return;
|
||||
const create = async (template?: NoteTemplate) => {
|
||||
try {
|
||||
const path = await createNote("", template);
|
||||
refreshToken++;
|
||||
await openCreatedFile({ name: path.split("/").pop()!, rel_path: path, kind: "file" });
|
||||
} catch (reason) { error = String(reason); }
|
||||
};
|
||||
const templates = await noteTemplates();
|
||||
if (!templates.length || !event) { await create(); return; }
|
||||
const anchor = event.currentTarget instanceof HTMLElement ? event.currentTarget : document.activeElement as HTMLElement;
|
||||
const close = () => { menu.remove(); window.removeEventListener("pointerdown", outside); anchor?.focus(); };
|
||||
const outside = (event: PointerEvent) => { if (!menu.contains(event.target as Node)) close(); };
|
||||
const menu = actionMenu(event.clientX, event.clientY, [
|
||||
{ label: "Blank note", icon: "file-plus", run: () => { close(); void create(); } },
|
||||
...templates.map(template => ({ label: template.name, icon: "file-plus" as const, run: () => { close(); void create(template); } })),
|
||||
], close, "New note");
|
||||
window.addEventListener("pointerdown", outside);
|
||||
}
|
||||
|
||||
function onPreferencesKeydown(event: KeyboardEvent) {
|
||||
if (event.target instanceof Element && event.target.closest("dialog, [role=dialog], [role=menu]")) return;
|
||||
if (event.ctrlKey && !event.altKey && !event.metaKey && event.key === "Tab" && workingTabs.length) {
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const index = workingTabs.findIndex(tab => tab.relPath === activeTabPath);
|
||||
const next = (index + (event.shiftKey ? -1 : 1) + workingTabs.length) % workingTabs.length;
|
||||
selectWorkingTab(workingTabs[next].relPath);
|
||||
return;
|
||||
}
|
||||
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key === ",") {
|
||||
event.preventDefault(); event.stopPropagation(); void openSettings();
|
||||
}
|
||||
@@ -699,7 +810,7 @@
|
||||
const shell = event.currentTarget as HTMLElement;
|
||||
const rect = shell.getBoundingClientRect();
|
||||
if (dragging === "left") {
|
||||
leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left - ($pluginNavigation.length ? 44 : 0)));
|
||||
leftWidth = Math.min(480, Math.max(160, event.clientX - rect.left - (ribbonNavigation.length ? 44 : 0)));
|
||||
}
|
||||
if (dragging === "right") {
|
||||
rightWidth = Math.min(480, Math.max(160, rect.right - event.clientX));
|
||||
@@ -715,6 +826,20 @@
|
||||
settings = { ...next };
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
try {
|
||||
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
|
||||
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
|
||||
layoutReady = true;
|
||||
} catch { error = "Could not read your layout. Default layout applies for this window."; }
|
||||
});
|
||||
|
||||
$effect(() => {
|
||||
if (!layoutReady) return;
|
||||
try { saveWorkbenchLayout(localStorage, { leftOpen, rightOpen, leftWidth, rightWidth, leftView }); }
|
||||
catch { error = "Could not save your layout. Layout changes apply for this window only."; }
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); }
|
||||
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
||||
@@ -741,6 +866,9 @@
|
||||
void restoreLast();
|
||||
let disposed = false;
|
||||
const unlisteners: (() => void)[] = [];
|
||||
unlisteners.push(handlePluginFileOpen(async path => {
|
||||
await openFile({ name: path.split("/").pop() ?? path, rel_path: path, kind: "file" });
|
||||
}));
|
||||
unlisteners.push(handlePluginDocumentRename(async (from, name) => {
|
||||
const current = documents;
|
||||
if (!current || switching) throw new Error("Open a workspace before renaming a document.");
|
||||
@@ -801,7 +929,7 @@
|
||||
|
||||
<div
|
||||
class="shell"
|
||||
class:has-ribbon={$pluginNavigation.length > 0}
|
||||
class:has-ribbon={ribbonNavigation.length > 0}
|
||||
class:left-open={leftOpen}
|
||||
class:right-open={rightOpen}
|
||||
role="application"
|
||||
@@ -818,34 +946,48 @@
|
||||
<IconButton
|
||||
icon="files"
|
||||
label="Files"
|
||||
active={leftOpen && leftView === "files"}
|
||||
active={leftOpen && !$pluginSidebar && leftView === "files"}
|
||||
onclick={() => selectLeft("files")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="search"
|
||||
label="Search"
|
||||
active={leftOpen && leftView === "search"}
|
||||
active={leftOpen && !$pluginSidebar && leftView === "search"}
|
||||
onclick={() => selectLeft("search")}
|
||||
/>
|
||||
<IconButton
|
||||
icon="bookmark"
|
||||
label="Bookmarks"
|
||||
active={leftOpen && leftView === "bookmarks"}
|
||||
active={leftOpen && !$pluginSidebar && leftView === "bookmarks"}
|
||||
onclick={() => selectLeft("bookmarks")}
|
||||
/>
|
||||
{#each sidebarNavigation as item (`${item.owner}:${item.id}`)}
|
||||
<IconButton
|
||||
icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" || item.icon === "git" ? item.icon : "puzzle"}
|
||||
label={item.title}
|
||||
active={leftOpen && $pluginSidebar?.owner === item.owner && $pluginSidebar?.id === item.id}
|
||||
onclick={() => openPluginView(item.owner, item.id)}
|
||||
/>
|
||||
{/each}
|
||||
</div>
|
||||
<div class="header-center" data-tauri-drag-region>
|
||||
<TabBar tabs={workingTabs} activePath={activeTabPath} onSelect={selectWorkingTab} onClose={closeTab}
|
||||
onCloseTabs={(path, scope) => void closeTabs(path, scope)} onPin={pinWorkingTab}
|
||||
fileActions={workingTabFileActions} tabActions={workingTabActions} onMove={moveWorkingTab}
|
||||
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" />
|
||||
<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}
|
||||
<PluginTools />
|
||||
<PluginAccessMenu surface="commands" />
|
||||
<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
|
||||
@@ -858,13 +1000,13 @@
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={$pluginNavigation.length === 0}>
|
||||
{#each $pluginNavigation as item (`${item.owner}:${item.id}`)}
|
||||
<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 : "puzzle"}
|
||||
icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" || item.icon === "git" ? item.icon : "puzzle"}
|
||||
label={item.title}
|
||||
side="right"
|
||||
active={$pluginView?.owner === item.owner && $pluginView?.id === item.id && !$pluginView?.document && ($pluginView?.placement === "dialog" || $pluginEditorActive)}
|
||||
active={($pluginSidebar?.owner === item.owner && $pluginSidebar?.id === item.id) || $pluginView?.owner === item.owner && $pluginView?.id === item.id && !$pluginView?.document && ($pluginView?.placement === "dialog" || $pluginEditorActive)}
|
||||
onclick={() => openPluginView(item.owner, item.id)}
|
||||
/>
|
||||
{/each}
|
||||
@@ -873,6 +1015,10 @@
|
||||
{#if leftOpen}
|
||||
<aside class="left">
|
||||
<div class="left-body">
|
||||
{#if $pluginSidebar}
|
||||
{#key $pluginSidebar.key}<PluginEditor view={$pluginSidebar} />{/key}
|
||||
{/if}
|
||||
<div class="native-left" class:sidebar-covered={!!$pluginSidebar}>
|
||||
{#if !workspace}
|
||||
{#if leftView === "bookmarks"}<BrowserSlot kind="bookmarks" />{:else}<p class="placeholder">No folder is open.</p>{/if}
|
||||
{:else}
|
||||
@@ -880,10 +1026,12 @@
|
||||
<div class="left-layer" class:shown={leftView === "files"}>
|
||||
<FileTree
|
||||
workspaceRoot={workspace.root}
|
||||
showInternal={settings.showInternalFolder}
|
||||
onSaveTemplate={(entry) => { void saveTemplate(entry); }}
|
||||
activePath={editorPluginVisible ? $pluginView?.document?.path ?? null : activePath}
|
||||
onOpenFile={(entry, newTab) => void openFile(entry, undefined, newTab ? "new" : "current")}
|
||||
{refreshToken}
|
||||
keysActive={leftView === "files"}
|
||||
keysActive={leftOpen && !$pluginSidebar && leftView === "files"}
|
||||
onCreated={(entry) => {
|
||||
void openCreatedFile(entry);
|
||||
}}
|
||||
@@ -902,6 +1050,7 @@
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
<div class="left-footer">
|
||||
<div class="footer-start" bind:this={workspaceAnchor}>
|
||||
@@ -961,6 +1110,7 @@
|
||||
hasWorkspace={!!workspace}
|
||||
onOpenWorkspace={() => void chooseWorkspace()}
|
||||
onNewFile={() => void newFile()}
|
||||
onNewNote={(event) => { void newNote(event); }}
|
||||
onQuickOpen={() => quickOpen = true}
|
||||
onOpenBrowser={browserContribution?.newTab ? () => void openBrowser() : undefined}
|
||||
{browserOpening}
|
||||
@@ -1043,7 +1193,7 @@
|
||||
display: grid;
|
||||
--ribbon-width: 0px;
|
||||
grid-template-columns: var(--ribbon-width) minmax(0, 1fr);
|
||||
grid-template-rows: 36px minmax(0, 1fr) 22px;
|
||||
grid-template-rows: var(--rs-titlebar-height) minmax(0, 1fr) 22px;
|
||||
background: var(--rs-bg);
|
||||
}
|
||||
|
||||
@@ -1086,22 +1236,10 @@
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
background: var(--rs-bg-elevated);
|
||||
border-bottom: 1px solid var(--rs-border);
|
||||
box-shadow: inset 0 -1px var(--rs-border);
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.shell.left-open .header {
|
||||
grid-template-columns: calc(var(--left) + var(--ribbon-width)) minmax(0, 1fr) auto;
|
||||
}
|
||||
|
||||
.shell.right-open .header {
|
||||
grid-template-columns: auto minmax(0, 1fr) minmax(max-content, var(--right));
|
||||
}
|
||||
|
||||
.shell.left-open.right-open .header {
|
||||
grid-template-columns: calc(var(--left) + var(--ribbon-width)) minmax(0, 1fr) minmax(max-content, var(--right));
|
||||
}
|
||||
|
||||
.header-left,
|
||||
.header-right {
|
||||
display: flex;
|
||||
@@ -1109,6 +1247,7 @@
|
||||
justify-content: center;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.header-center {
|
||||
@@ -1117,12 +1256,14 @@
|
||||
justify-content: flex-start;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
padding: 0 8px;
|
||||
padding: 0;
|
||||
border-left: 1px solid var(--rs-border);
|
||||
border-right: 1px solid var(--rs-border);
|
||||
}
|
||||
|
||||
.header-left, .header-center, .header-right { height: 100%; }
|
||||
.shell.left-open .header-left { width: calc(var(--ribbon-width) + var(--left) + 1px); padding-left: calc(var(--ribbon-width) + 4px); }
|
||||
.header-left :global(.icon-btn), .header-right :global(.icon-btn) { flex-shrink: 0; }
|
||||
.header-right { justify-content: flex-end; }
|
||||
.window-drag-space { flex: 0 0 40px; align-self: stretch; }
|
||||
|
||||
@@ -1134,15 +1275,16 @@
|
||||
background: transparent;
|
||||
border-bottom: 0;
|
||||
}
|
||||
.header-center :global(.tabs:empty) { min-width: 80px; }
|
||||
|
||||
.header-center :global(.tab) {
|
||||
flex: 0 1 180px;
|
||||
width: 180px;
|
||||
min-width: 96px;
|
||||
max-width: 180px;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.header-center :global(.tab.active) {
|
||||
background: var(--rs-item-selection-bg);
|
||||
background: var(--rs-bg);
|
||||
}
|
||||
|
||||
.ws {
|
||||
@@ -1215,6 +1357,9 @@
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.native-left { display: flex; flex-direction: column; min-height: 0; }
|
||||
.native-left.sidebar-covered { display: none; }
|
||||
|
||||
.left-stack {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import ContextMenu from "$lib/layout/ContextMenu.svelte";
|
||||
import type { MenuItem } from "$lib/layout/menuTypes";
|
||||
import { installedPlugins, pluginTools, openPluginView, runPluginCommand } from "./external";
|
||||
let { surface }: { surface: "commands" | "open" } = $props();
|
||||
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("");
|
||||
@@ -25,10 +25,11 @@
|
||||
</script>
|
||||
|
||||
{#if tools.length}
|
||||
<button class="access-button" bind:this={anchor} aria-haspopup="menu" aria-expanded={position !== null} title={label}
|
||||
<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"} /><span>{label}</span>
|
||||
<Icon icon={surface === "open" ? "chevron-down" : "code"} />{#if !compact}<span>{label}</span>{/if}
|
||||
{#if compact}<span class="access-tooltip" role="tooltip">{label}</span>{/if}
|
||||
</button>
|
||||
{/if}
|
||||
{#if position && tools.length}<ContextMenu {...position} {items} {label} onClose={() => position = null} />{/if}
|
||||
@@ -38,5 +39,8 @@
|
||||
.access-button { display: flex; align-items: center; gap: 6px; white-space: nowrap; min-height: 32px; padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
|
||||
.access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-bg-active); }
|
||||
.access-button:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
|
||||
.access-button.compact { position: relative; width: 28px; height: 28px; min-height: 28px; padding: 5px; }
|
||||
.access-tooltip { display: none; position: absolute; top: calc(100% + 6px); right: 0; padding: 5px 8px; border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); z-index: 60; pointer-events: none; }
|
||||
.access-button:is(:hover, :focus-visible) .access-tooltip { display: block; }
|
||||
.error { position: fixed; top: 48px; right: 12px; z-index: 60; max-width: 420px; padding: 12px; background: var(--rs-bg); color: var(--rs-error); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
</style>
|
||||
|
||||
@@ -25,7 +25,9 @@
|
||||
<div id={`plugin-editor-${view.key}`} class="plugin-editor-pane"
|
||||
role="tabpanel" aria-label={view.title} tabindex="-1">
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<div class="plugin-editor-content" bind:this={host}></div>
|
||||
{#key `${view.owner}:${view.id}:${view.document?.path ?? ""}`}
|
||||
<div class="plugin-editor-content" bind:this={host}></div>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
<style>
|
||||
|
||||
@@ -117,22 +117,20 @@
|
||||
{#each external as plugin (plugin.manifest.id)}
|
||||
<div class="card">
|
||||
<div class="row">
|
||||
<div><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · Full app access</small></div>
|
||||
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.enabled} disabled={busy || plugin.removal} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
|
||||
</div>
|
||||
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
|
||||
<div class="actions">
|
||||
<div class="status">
|
||||
<span class="badge">{plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span>
|
||||
<span class="note">
|
||||
{#if plugin.installedAt != null}
|
||||
Installed <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
|
||||
{:else}
|
||||
Install date unknown
|
||||
{/if}
|
||||
</span>
|
||||
<div class="plugin-copy"><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · Full app access</small>
|
||||
<div class="status">
|
||||
<span class="badge">{plugin.manifest.id === "runestone.browser" ? "Included with RuneStone" : plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span>
|
||||
<span class="note">
|
||||
{#if plugin.installedAt != null}
|
||||
Installed <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
|
||||
{:else}
|
||||
Install date unknown
|
||||
{/if}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.manifest.id === "runestone.browser" || plugin.enabled} disabled={busy || plugin.removal || plugin.manifest.id === "runestone.browser"} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
|
||||
<IconButton icon="folder-open" label="Show files" disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} />
|
||||
{#if plugin.removal}
|
||||
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = "Plugin file cleanup completed."; })}><Icon icon="refresh" />Retry cleanup</button>
|
||||
@@ -141,11 +139,13 @@
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{#if plugin.manifest.id === "runestone.browser"}<p class="note">Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.</p>{/if}
|
||||
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
|
||||
</div>
|
||||
{/each}
|
||||
{#if $restartPlugins.length}<p class="note" role="status">Restart RuneStone to clear all code from plugins that stopped in this window.</p>{/if}
|
||||
{#if error}<p class="error" role="alert">{error}</p>{/if}
|
||||
<p class="saved" role="status">{message}</p>
|
||||
{#if message}<p class="saved" role="status">{message}</p>{/if}
|
||||
|
||||
{#if candidates.length || plan || gitForm}
|
||||
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
|
||||
@@ -190,37 +190,41 @@
|
||||
{/if}
|
||||
|
||||
<style>
|
||||
h2 { margin: 0; font-size: 23px; color: var(--rs-text-strong); }
|
||||
h3 { font-size: 14px; margin: 24px 0 10px; }
|
||||
p { color: var(--rs-text-dim); line-height: 1.6; }
|
||||
button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; padding: 8px 10px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
h2 { margin: 0; font-size: var(--rs-settings-heading-size); color: var(--rs-text-strong); }
|
||||
h3 { font-size: 13px; margin: var(--rs-settings-section-gap) 0 8px; }
|
||||
p { margin: 6px 0 10px; color: var(--rs-text-dim); line-height: 1.45; }
|
||||
button { display: inline-flex; align-items: center; justify-content: center; gap: var(--rs-settings-gap); min-height: var(--rs-settings-control-height); padding: 4px 8px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
button:hover:not(:disabled) { background: var(--rs-bg-active); }
|
||||
button:disabled { opacity: .5; }
|
||||
.toolbar, .actions, footer { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; }
|
||||
.card { background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); padding: 0 14px 10px; margin-bottom: 10px; }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 14px 0 8px; }
|
||||
.row > div { min-width: 0; overflow-wrap: anywhere; }
|
||||
.row p { margin: 5px 0; font-size: 12px; }
|
||||
.toolbar, footer { display: flex; align-items: center; flex-wrap: wrap; gap: var(--rs-settings-gap); }
|
||||
.card { border-bottom: 1px solid var(--rs-border); }
|
||||
.row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: var(--rs-settings-row-padding) 0; }
|
||||
.plugin-copy { flex: 1; min-width: 0; overflow-wrap: anywhere; }
|
||||
.row p { margin: 3px 0; font-size: var(--rs-settings-description-size); }
|
||||
label { font-weight: 500; }
|
||||
.path { overflow-wrap: anywhere; font-size: 11px; }
|
||||
small, .badge, .note { color: var(--rs-text-dim); font-size: 12px; }
|
||||
.status { display: flex; flex: 1 1 240px; flex-wrap: wrap; align-items: center; gap: 4px 12px; }
|
||||
.controls { display: flex; align-items: center; gap: 6px; margin-left: auto; }
|
||||
.controls :global(.icon-btn) { width: 32px; height: 32px; flex-basis: 32px; }
|
||||
small, .badge, .note { color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); }
|
||||
.status { display: flex; flex-wrap: wrap; align-items: center; gap: 2px 8px; margin-top: 3px; }
|
||||
.controls { display: flex; flex: 0 0 auto; align-items: center; gap: 4px; }
|
||||
.controls .danger { display: flex; }
|
||||
.controls .danger :global(.icon-btn) { color: var(--rs-error); }
|
||||
.error { color: var(--rs-error); white-space: pre-wrap; }
|
||||
.saved { color: var(--rs-ok); min-height: 20px; }
|
||||
.danger { color: var(--rs-error); }
|
||||
input[role=switch] { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
|
||||
input[role=switch] { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; margin: 0 4px 0 0; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
|
||||
input[role=switch]::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; }
|
||||
input[role=switch]:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
|
||||
input[role=switch]:checked::before { transform: translateX(16px); background: var(--rs-bg); }
|
||||
dialog { width: min(650px, 90vw); max-height: 85vh; padding: 24px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
dialog { width: min(650px, 90vw); max-height: 85vh; padding: 16px; color: var(--rs-text); background: var(--rs-bg); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
dialog::backdrop { background: #0009; }
|
||||
footer { justify-content: flex-end; margin-top: 24px; }
|
||||
.candidate { padding: 16px 0; border-bottom: 1px solid var(--rs-border); }
|
||||
footer { justify-content: flex-end; margin-top: var(--rs-settings-section-gap); }
|
||||
.candidate { padding: var(--rs-settings-row-padding) 0; border-bottom: 1px solid var(--rs-border); }
|
||||
.candidate label { display: flex; gap: 8px; }
|
||||
.field { display: flex; flex-direction: column; gap: 6px; margin: 14px 0; }
|
||||
.field input { min-width: 0; padding: 8px 10px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
.field { display: flex; flex-direction: column; gap: 6px; margin: 10px 0; }
|
||||
.field input { min-width: 0; min-height: var(--rs-settings-control-height); padding: 4px 8px; color: var(--rs-text); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
|
||||
@media (max-width: 420px) {
|
||||
.row { flex-wrap: wrap; }
|
||||
.plugin-copy { flex-basis: 100%; }
|
||||
.controls { margin-left: auto; }
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -15,6 +15,7 @@ export interface TerminalMount {
|
||||
export type FormulaErrorCode = "#ERROR!" | "#REF!" | "#VALUE!" | "#NAME?" | "#DIV/0!" | "#CYCLE!" | "#NUM!" | "#LIMIT!";
|
||||
export type FormulaResult = { formula: string; text: string; value?: number; error?: FormulaErrorCode };
|
||||
export interface Contributions {
|
||||
git: { blame(path: string, line: number): Promise<import("../git/contracts.ts").GitLineInfo | null> };
|
||||
browser: {
|
||||
newTab?(): Promise<void>;
|
||||
mountSettings(container: HTMLElement): Dispose | Promise<Dispose>;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { completionTransport } from "../completion/transport";
|
||||
import { invoke, isTauri } from "@tauri-apps/api/core";
|
||||
import { listen } from "@tauri-apps/api/event";
|
||||
import { workspaceList, workspaceRead, workspaceReadBytes, workspaceWrite } from "../workspace/api";
|
||||
import { gitApi } from "../git/service";
|
||||
import { ExternalSession, deadline } from "./externalSession";
|
||||
import { pluginAccess, type PluginTool } from "./access";
|
||||
import { containsPane, splitPane, removePane, type SplitLayout } from "../workspace/splitLayout";
|
||||
@@ -12,7 +13,9 @@ import type { PluginModule, PluginSnapshot, InstalledPlugin, Dispose, PluginView
|
||||
export const installedPlugins = writable<PluginSnapshot>({ root: "", plugins: [] });
|
||||
export const externalErrors = writable<Record<string, string>>({});
|
||||
export const pluginTools = writable<PluginTool[]>([]);
|
||||
export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor"; document?: PluginDocumentContext; icon?: "kanban" | "file" | "globe"; iconImage?: string | null; pinned?: boolean; draggable?: boolean }
|
||||
export interface OpenPluginView { key: string; owner: string; id: string; title: string; placement: "dialog" | "editor" | "sidebar"; document?: PluginDocumentContext; icon?: "kanban" | "file" | "globe" | "git"; iconImage?: string | null; pinned?: boolean; draggable?: boolean }
|
||||
export const pluginSidebar = writable<OpenPluginView | null>(null);
|
||||
export function closePluginSidebar() { pluginSidebar.set(null); }
|
||||
export const pluginView = writable<OpenPluginView | null>(null);
|
||||
export const pluginEditors = writable<OpenPluginView[]>([]);
|
||||
export const pluginSplits = writable<SplitLayout[]>([]);
|
||||
@@ -20,6 +23,28 @@ export function pinPluginEditor(key: string) {
|
||||
pluginEditors.update(views => views.map(view => view.key === key ? { ...view, pinned: !view.pinned } : view));
|
||||
}
|
||||
export function pluginTabActions(view: OpenPluginView) { return sessions.get(view.owner)?.session.views.get(view.id)?.tabActions?.({ pinned: !!view.pinned }) ?? []; }
|
||||
export function pluginTabState(view: OpenPluginView) {
|
||||
return { owner: view.owner, id: view.id, document: view.document, pinned: view.pinned,
|
||||
state: sessions.get(view.owner)?.session.views.get(view.id)?.saveTabState?.() };
|
||||
}
|
||||
export async function restorePluginTab(transfer: ReturnType<typeof pluginTabState>): Promise<boolean> {
|
||||
const session = sessions.get(transfer.owner)?.session;
|
||||
if (!session) return false;
|
||||
if (transfer.document) {
|
||||
if (!await openPluginDocument(transfer.document.path)) return false;
|
||||
} else {
|
||||
const view = session.views.get(transfer.id);
|
||||
if (!view || view.placement !== "editor") return false;
|
||||
if (transfer.state !== undefined) {
|
||||
if (!view.restoreTabState) throw new Error("This plugin cannot restore its tab state.");
|
||||
await view.restoreTabState(transfer.state);
|
||||
}
|
||||
show(transfer.owner, transfer.id);
|
||||
}
|
||||
const opened = get(pluginView);
|
||||
if (opened && !!opened.pinned !== !!transfer.pinned) pinPluginEditor(opened.key);
|
||||
return true;
|
||||
}
|
||||
export function pluginTabDragData(view: OpenPluginView): string | undefined {
|
||||
const data = sessions.get(view.owner)?.session.views.get(view.id)?.tabDragData?.({ pinned: !!view.pinned });
|
||||
return data === undefined ? undefined : JSON.stringify({ owner: view.owner, data });
|
||||
@@ -39,7 +64,7 @@ export function findPluginEditor(view: OpenPluginView): boolean {
|
||||
}
|
||||
export const pluginDocumentTypes = writable<{ owner: string; type: PluginDocumentType }[]>([]);
|
||||
export const pluginDocuments = writable<Record<string, { icon: "kanban" | "file"; title: string }>>({});
|
||||
export const pluginNavigation = writable<{ owner: string; id: string; title: string; icon?: PluginView["icon"] }[]>([]);
|
||||
export const pluginNavigation = writable<{ owner: string; id: string; title: string; icon?: PluginView["icon"]; placement?: PluginView["placement"]; toolbar?: boolean }[]>([]);
|
||||
export const pluginEditorActive = writable(false);
|
||||
export const pluginServiceError = writable("");
|
||||
export const restartPlugins = writable<string[]>([]);
|
||||
@@ -54,6 +79,11 @@ let generation = 0;
|
||||
let documentOpenVersion = 0;
|
||||
export function cancelPluginDocumentOpen() { documentOpenVersion++; }
|
||||
const workspaceListeners = new Set<() => void>();
|
||||
let openFile: ((path: string) => Promise<void>) | undefined;
|
||||
export function handlePluginFileOpen(handler: (path: string) => Promise<void>): () => void {
|
||||
openFile = handler;
|
||||
return () => { if (openFile === handler) openFile = undefined; };
|
||||
}
|
||||
let renameDocument: ((path: string, name: string) => Promise<string>) | undefined;
|
||||
export function handlePluginDocumentRename(handler: (path: string, name: string) => Promise<string>): () => void {
|
||||
renameDocument = handler;
|
||||
@@ -144,7 +174,7 @@ export async function createPluginDocument(owner: string, id: string, path: stri
|
||||
|
||||
function publish() {
|
||||
pluginEditors.update(views => views.map(view => view.document ? view : { ...view, title: sessions.get(view.owner)?.session.views.get(view.id)?.title ?? view.title, iconImage: sessions.get(view.owner)?.session.views.get(view.id)?.iconImage }));
|
||||
pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon }))));
|
||||
pluginNavigation.set([...sessions].flatMap(([owner, { session }]) => [...session.views.values()].filter(view => view.navigation || view.toolbar).map(view => ({ owner, id: view.id, title: view.title, icon: view.icon, placement: view.placement, toolbar: view.toolbar }))));
|
||||
pluginDocumentTypes.set([...sessions].flatMap(([owner, { session }]) => [...session.documentTypes.values()].map(type => ({ owner, type }))));
|
||||
pluginTools.set([...sessions].flatMap(([owner, { session }]) => pluginAccess(owner, session.commands.values(), session.views.values())));
|
||||
externalErrors.set({ ...errors });
|
||||
@@ -157,21 +187,26 @@ async function stop(id: string) {
|
||||
const loaded = sessions.get(id);
|
||||
if (!loaded) return;
|
||||
sessions.delete(id);
|
||||
pluginSidebar.update(view => view?.owner === id ? null : view);
|
||||
for (const view of get(pluginEditors)) if (view.owner === id) closePluginEditor(view.key);
|
||||
pluginDocuments.set({});
|
||||
pluginView.update(view => view?.owner === id ? null : view);
|
||||
restarted.add(id); restartPlugins.set([...restarted]);
|
||||
let error: string | undefined;
|
||||
try { await loaded.session.stop(); } catch (reason) { error = String(reason); report(id, reason); }
|
||||
await release(id, error); publish();
|
||||
if (loaded.hash !== "builtin") await release(id, error); publish();
|
||||
}
|
||||
function show(owner: string, id: string, options?: PluginViewOpenOptions) {
|
||||
const view = sessions.get(owner)?.session.views.get(id);
|
||||
if (view) {
|
||||
const placement = view.placement ?? "dialog";
|
||||
if (placement === "sidebar") {
|
||||
pluginSidebar.set({ key: owner + ":" + id, owner, id, title: view.title, placement });
|
||||
return;
|
||||
}
|
||||
if (placement === "editor") {
|
||||
const existing = get(pluginEditors).find(item => item.owner === owner && item.id === id && !item.document);
|
||||
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: !!view.tabDragData, iconImage: view.iconImage, ...(view.icon === "globe" ? { icon: "globe" as const } : {}) };
|
||||
const editor: OpenPluginView = existing ?? { key: crypto.randomUUID(), owner, id, title: view.title, placement, pinned: !!view.pinned, draggable: !!view.tabDragData, iconImage: view.iconImage, ...(["globe", "kanban", "git"].includes(view.icon ?? "") ? { icon: view.icon as "globe" | "kanban" | "git" } : {}) };
|
||||
if (!existing && options) {
|
||||
const source = get(pluginEditors).find(item => item.owner === owner && item.id === options.relativeTo);
|
||||
if (!source || !["right", "down"].includes(options.split)) throw new Error("The source pane is unavailable.");
|
||||
@@ -191,11 +226,23 @@ function show(owner: string, id: string, options?: PluginViewOpenOptions) {
|
||||
pluginEditorActive.set(false);
|
||||
}
|
||||
}
|
||||
async function activate(row: InstalledPlugin) {
|
||||
function replaceEditorView(owner: string, current: OpenPluginView | undefined, nextId: string) {
|
||||
const next = sessions.get(owner)?.session.views.get(nextId);
|
||||
if (!current || !next || next.placement !== "editor") throw new Error("The editor view is unavailable.");
|
||||
for (const duplicate of get(pluginEditors)) {
|
||||
if (duplicate.owner === owner && duplicate.id === nextId && !duplicate.document && duplicate.key !== current.key) closePluginEditor(duplicate.key);
|
||||
}
|
||||
const replacement: OpenPluginView = { ...current, id: nextId, title: next.title, document: undefined, iconImage: next.iconImage, icon: ["globe", "kanban", "git"].includes(next.icon ?? "") ? next.icon as "globe" | "kanban" | "git" : undefined };
|
||||
pluginEditors.update(views => views.map(view => view.key === current.key ? replacement : view));
|
||||
selectPluginEditor(replacement);
|
||||
}
|
||||
async function activate(row: InstalledPlugin, builtin?: PluginModule) {
|
||||
const id = row.manifest.id;
|
||||
let leased = false;
|
||||
const session = new ExternalSession(id, {
|
||||
completionTransport,
|
||||
git: gitApi,
|
||||
openFile: async path => { if (!openFile) throw new Error("File opening is unavailable."); await openFile(path); },
|
||||
workspace: {
|
||||
list: path => workspaceList(path ?? ""), read: workspaceRead,
|
||||
listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
|
||||
@@ -226,14 +273,23 @@ async function activate(row: InstalledPlugin) {
|
||||
if (!renameDocument) throw new Error("Document renaming is unavailable.");
|
||||
canWrite(document.path);
|
||||
return renameDocument(document.path, name);
|
||||
}, viewId => { for (const view of get(pluginEditors)) if (view.owner === id && view.id === viewId) closePluginEditor(view.key); });
|
||||
}, viewId => { for (const view of get(pluginEditors)) if (view.owner === id && view.id === viewId) closePluginEditor(view.key); }, (currentId, nextId) => {
|
||||
const current = get(pluginEditors).find(view => view.owner === id && view.id === currentId && !view.document);
|
||||
replaceEditorView(id, current, nextId);
|
||||
}, (document, nextId) => {
|
||||
const current = get(pluginEditors).find(view => view.owner === id && view.document?.id === document.id && view.document.path === document.path);
|
||||
replaceEditorView(id, current, nextId);
|
||||
});
|
||||
try {
|
||||
let module: PluginModule;
|
||||
if (builtin) module = builtin;
|
||||
else {
|
||||
const code = await invoke<string>("plugins_load", { id, hash: row.hash }); leased = true;
|
||||
const url = URL.createObjectURL(new Blob([code], { type: "text/javascript" }));
|
||||
let module: PluginModule;
|
||||
try { module = await deadline(import(/* @vite-ignore */ url)); }
|
||||
catch (reason) { await release(id, String(reason)); leased = false; throw reason; }
|
||||
finally { URL.revokeObjectURL(url); }
|
||||
}
|
||||
sessions.set(id, { hash: row.hash, session });
|
||||
await session.start(module);
|
||||
delete errors[id]; publish();
|
||||
@@ -255,11 +311,13 @@ export function refreshPlugins(): Promise<void> {
|
||||
if (!snapshot || version !== generation) return;
|
||||
installedPlugins.set(snapshot); pluginServiceError.set("");
|
||||
for (const id of sessions.keys()) {
|
||||
if (sessions.get(id)?.hash === "builtin") continue;
|
||||
const row = snapshot.plugins.find(row => row.manifest.id === id);
|
||||
if (!row?.enabled || row.hash !== sessions.get(id)?.hash) await stop(id);
|
||||
}
|
||||
for (const row of snapshot.plugins) {
|
||||
const id = row.manifest.id;
|
||||
if (id === "runestone.browser") continue;
|
||||
if (allowedPlugins && !allowedPlugins.includes(id)) continue;
|
||||
if (!row.enabled) { failures.delete(id); continue; }
|
||||
if (!sessions.has(id) && failures.get(id) !== row.hash && version === generation) await activate(row);
|
||||
@@ -289,6 +347,11 @@ export function startExternalPlugins(allowed?: string[]): () => void {
|
||||
let disposed = false;
|
||||
let off: (() => void) | undefined;
|
||||
void listen("plugins-changed", () => { void refreshPlugins(); }).then(unlisten => { if (disposed) unlisten(); else off = unlisten; }).catch(reason => pluginServiceError.set(String(reason)));
|
||||
queue = queue.then(async () => {
|
||||
if (disposed || (allowed && !allowed.includes("runestone.browser"))) return;
|
||||
const module = await import("../browser/index");
|
||||
await activate({ manifest: { schemaVersion: 1, id: "runestone.browser", name: "Browser", author: "RuneStone", description: "Built-in browser", version: "0.0.0", apiVersion: 1, entry: "builtin", access: "full-app" }, hash: "builtin", enabled: true, installedAt: null, path: "", error: null, removal: false }, module);
|
||||
}).catch(reason => report("runestone.browser", reason));
|
||||
void refreshPlugins();
|
||||
const focus = () => { void refreshPlugins(); };
|
||||
window.addEventListener("focus", focus);
|
||||
|
||||
@@ -23,17 +23,21 @@ export class ExternalSession {
|
||||
private contributions: Dispose[] = [];
|
||||
private registry: ContributionRegistry;
|
||||
readonly id: string;
|
||||
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
|
||||
private services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] };
|
||||
private changed: () => void;
|
||||
private show: PluginApi["openView"];
|
||||
private close?: PluginApi["closeView"];
|
||||
private replace?: PluginApi["replaceView"];
|
||||
private replaceDocument?: PluginApi["replaceDocumentWithView"];
|
||||
private receiveTab?: (data: string) => void | Promise<void>;
|
||||
private openDocument: (path: string) => Promise<void>;
|
||||
private renameDocument?: PluginApi["renameDocument"];
|
||||
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"]) {
|
||||
constructor(id: string, services: Pick<PluginApi, "workspace" | "settings" | "assets"> & { openFile?: PluginApi["openFile"]; git?: PluginApi["git"]; completionTransport?: NonNullable<PluginApi["completion"]>["transport"] }, changed: () => void, show: PluginApi["openView"], registry: ContributionRegistry = pluginHost, openDocument: (path: string) => Promise<void> = async () => { throw new Error("Document views are unavailable."); }, renameDocument?: PluginApi["renameDocument"], close?: PluginApi["closeView"], replace?: PluginApi["replaceView"], replaceDocument?: PluginApi["replaceDocumentWithView"]) {
|
||||
this.openDocument = openDocument;
|
||||
this.renameDocument = renameDocument;
|
||||
this.close = close;
|
||||
this.replace = replace;
|
||||
this.replaceDocument = replaceDocument;
|
||||
this.registry = registry; this.id = id; this.services = services; this.changed = changed; this.show = show;
|
||||
}
|
||||
private check() { if (this.stopped) throw new Error("This plugin is disabled."); }
|
||||
@@ -45,6 +49,19 @@ export class ExternalSession {
|
||||
};
|
||||
const api: PluginApi = {
|
||||
id: this.id, signal: 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); },
|
||||
stage: (paths: string[]) => { this.check(); return this.services.git!.stage(paths); },
|
||||
unstage: (paths: string[]) => { this.check(); return this.services.git!.unstage(paths); },
|
||||
commit: (message: string) => { this.check(); return this.services.git!.commit(message); },
|
||||
blame: (path: string, line: number) => { this.check(); return this.services.git!.blame(path, line); },
|
||||
push: () => { this.check(); return this.services.git!.push(); },
|
||||
pull: () => { this.check(); return this.services.git!.pull(); },
|
||||
graph: () => { this.check(); return this.services.git!.graph(); },
|
||||
commitDetails: (commit: string) => { this.check(); return this.services.git!.commitDetails!(commit); },
|
||||
commitDiff: (commit: string, path: string) => { this.check(); return this.services.git!.commitDiff!(commit, path); },
|
||||
} } : {}),
|
||||
completion: {
|
||||
version: 1,
|
||||
registerProvider: provider => { this.check(); const off = completionHub.registerProvider({ ...provider, id: this.id + ":" + provider.id }); this.contributions.push(off); return off; },
|
||||
@@ -57,7 +74,7 @@ export class ExternalSession {
|
||||
},
|
||||
contribute: (key, value) => { this.check(); this.contributions.push(this.registry.register(this.id, key, value)); },
|
||||
registerCommand: item => { if (item.category !== undefined && !["open", "action"].includes(item.category)) throw new Error("Unknown plugin command category."); if (typeof item.run !== "function") throw new Error("A command needs a run function."); register(this.commands, item); },
|
||||
registerView: item => { if ([item.settings, item.launcher].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); if (item.placement !== undefined && !["dialog", "editor"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
|
||||
registerView: item => { if ([item.settings, item.launcher, item.navigation, item.toolbar].some(value => value !== undefined && typeof value !== "boolean")) throw new Error("Plugin view access options must be boolean."); if (item.placement !== undefined && !["dialog", "editor", "sidebar"].includes(item.placement)) throw new Error("Unknown plugin view placement."); if (typeof item.mount !== "function") throw new Error("A view needs a mount function."); register(this.views, item); },
|
||||
registerTabDrop: receive => { this.check(); if (typeof receive !== "function" || this.receiveTab) throw new Error("Invalid or duplicate tab receiver."); this.receiveTab = receive; },
|
||||
updateViewTitle: (id, title) => {
|
||||
this.check(); const view = this.views.get(id);
|
||||
@@ -76,9 +93,12 @@ export class ExternalSession {
|
||||
register(this.documentTypes, item);
|
||||
},
|
||||
openDocument: path => { this.check(); return this.openDocument(path); },
|
||||
...(this.services.openFile ? { openFile: (path: string) => { this.check(); return this.services.openFile!(path); } } : {}),
|
||||
...(this.renameDocument ? { renameDocument: (document: PluginDocumentContext, name: string) => { this.check(); return this.renameDocument!(document, name); } } : {}),
|
||||
openView: (id, options) => { this.check(); if (!this.views.has(id)) throw new Error("Unknown plugin view."); this.show(id, options); },
|
||||
...(this.close ? { closeView: (id: string) => { this.check(); this.close!(id); } } : {}),
|
||||
...(this.replace ? { replaceView: (currentId: string, nextId: string) => { this.check(); if (!this.views.has(currentId) || !this.views.has(nextId)) throw new Error("Unknown plugin view."); this.replace!(currentId, nextId); } } : {}),
|
||||
...(this.replaceDocument ? { replaceDocumentWithView: (document: PluginDocumentContext, nextId: string) => { this.check(); if (!this.views.has(nextId)) throw new Error("Unknown plugin view."); this.replaceDocument!(document, nextId); } } : {}),
|
||||
onDispose: cleanup => { this.check(); if (typeof cleanup !== "function") throw new Error("Cleanup must be a function."); this.cleanups.push(cleanup); },
|
||||
workspace: {
|
||||
...(this.services.workspace.subscribe ? { subscribe: (listener: () => void) => {
|
||||
|
||||
@@ -9,7 +9,7 @@ export class ContributionRegistry {
|
||||
return this.entries.get(key)?.value as Contributions[K] | undefined;
|
||||
}
|
||||
register<K extends keyof Contributions>(owner: string, key: K, value: Contributions[K]): () => void {
|
||||
if (key !== "terminal" && key !== "tableFormulas" && key !== "browser") throw new Error("Unknown plugin contribution.");
|
||||
if (key !== "terminal" && key !== "tableFormulas" && key !== "browser" && key !== "git") throw new Error("Unknown plugin contribution.");
|
||||
if (this.entries.has(key)) throw new Error(`Contribution already registered: ${key}`);
|
||||
const entry = { owner, value };
|
||||
this.entries.set(key, entry); this.emit();
|
||||
|
||||
@@ -4,7 +4,7 @@ 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 PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; placement?: "dialog" | "editor"; navigation?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
|
||||
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 }
|
||||
export interface PluginDocumentType {
|
||||
@@ -18,6 +18,7 @@ export interface PluginDocumentType {
|
||||
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
|
||||
}
|
||||
export interface PluginApi {
|
||||
git?: import("../git/contracts.ts").GitApi;
|
||||
completion?: CompletionApi;
|
||||
readonly id: string;
|
||||
readonly signal: AbortSignal;
|
||||
@@ -29,9 +30,12 @@ export interface PluginApi {
|
||||
updateViewIcon?(id: string, image: string | null): void;
|
||||
registerDocumentType(type: PluginDocumentType): void;
|
||||
openDocument(path: string): Promise<void>;
|
||||
openFile?(path: string): Promise<void>;
|
||||
renameDocument?(document: PluginDocumentContext, name: string): Promise<string>;
|
||||
openView(id: string, options?: PluginViewOpenOptions): void;
|
||||
closeView?(id: string): void;
|
||||
replaceView?(currentId: string, nextId: string): void;
|
||||
replaceDocumentWithView?(document: PluginDocumentContext, nextId: string): void;
|
||||
onDispose(cleanup: Dispose): void;
|
||||
workspace: {
|
||||
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
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';
|
||||
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
|
||||
let error = $state('');
|
||||
let installed = $state<CustomTheme[]>([]);
|
||||
let themeInput: HTMLInputElement;
|
||||
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.'; }
|
||||
}
|
||||
async function importTheme(file?: File) {
|
||||
if (!file) return;
|
||||
try {
|
||||
if (file.size > 65536) throw new Error('Choose a theme smaller than 64 KiB.');
|
||||
const theme = parseCustomTheme(JSON.parse(await file.text()));
|
||||
installTheme(theme); installed = customThemes();
|
||||
change({ ...appearance, theme: `custom:${theme.id}` });
|
||||
} 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);
|
||||
}
|
||||
</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>
|
||||
<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>
|
||||
{#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.'; }
|
||||
}} />{/if}
|
||||
</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}
|
||||
{#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}
|
||||
[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}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { APPEARANCE_KEY, applyAppearance, parseAppearance } from './appearance';
|
||||
import { CUSTOM_THEMES_KEY } from './customThemes';
|
||||
onMount(() => {
|
||||
const read = () => {
|
||||
try {
|
||||
const raw = localStorage.getItem(APPEARANCE_KEY);
|
||||
const appearance = parseAppearance(raw);
|
||||
const canonical = JSON.stringify(appearance);
|
||||
if (raw !== null && raw !== canonical) localStorage.setItem(APPEARANCE_KEY, canonical);
|
||||
applyAppearance(appearance);
|
||||
}
|
||||
catch { /* Keep the current appearance if storage is unavailable. */ }
|
||||
};
|
||||
const sync = (event: StorageEvent) => { if (event.key === APPEARANCE_KEY || event.key === CUSTOM_THEMES_KEY || event.key === null) read(); };
|
||||
read();
|
||||
window.addEventListener('storage', sync);
|
||||
window.addEventListener('focus', read);
|
||||
return () => { window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { customThemes } from './customThemes.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 DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' };
|
||||
export function normalizeAppearance(value: { theme?: unknown; mode?: 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' };
|
||||
}
|
||||
export function parseAppearance(raw: string | null): Appearance {
|
||||
try { return normalizeAppearance(JSON.parse(raw || 'null')); }
|
||||
catch { return { ...DEFAULT_APPEARANCE }; }
|
||||
}
|
||||
const keys = ['bg', 'bg-elevated', 'bg-active', 'border', 'text-dim', 'text', 'text-strong', 'accent', 'selection'] as const;
|
||||
const palettes = {
|
||||
default: {
|
||||
dark: ['#141414','#1c1c1c','#2a2a2a','#2e2e2e','#9a9a9a','#e6e6e6','#f3f3f3','#82aaff','#264f78'],
|
||||
light: ['#f3f3f3','#ffffff','#e8e8e8','#d4d4d4','#626262','#1e1e1e','#111111','#315fb3','#add6ff'],
|
||||
},
|
||||
// Anthropic brand guidelines: https://github.com/anthropics/skills/blob/main/skills/brand-guidelines/SKILL.md
|
||||
claude: {
|
||||
dark: ['#141413','#20201e','#32322e','#5a5952','#b0aea5','#faf9f5','#faf9f5','#d97757','#674435'],
|
||||
light: ['#faf9f5','#faf9f5','#e8e6dc','#b0aea5','#67665f','#141413','#141413','#d97757','#e8e6dc'],
|
||||
},
|
||||
// Palette from pm-image:7968b79c-9d80-40a5-9e9a-696c26aacfb9. Sakura supports light mode only.
|
||||
sakura: {
|
||||
light: ['#fefcfc','#fefcfc','#dbeacb','#f8dbe6','#687788','#513346','#321c2a','#98556c','#ffc9dc'],
|
||||
},
|
||||
};
|
||||
export function applyAppearance(value: Appearance, root = document.documentElement) {
|
||||
const { theme, mode } = normalizeAppearance(value);
|
||||
root.dataset.theme = mode;
|
||||
root.dataset.palette = theme;
|
||||
root.style.colorScheme = mode;
|
||||
const palette = theme === 'sakura' ? palettes.sakura.light : palettes[theme === 'claude' ? 'claude' : 'default'][mode];
|
||||
keys.forEach((key, index) => root.style.setProperty(`--rs-${key}`, palette[index]));
|
||||
root.style.setProperty('--rs-accent-2', theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : 'var(--rs-accent)');
|
||||
root.style.setProperty('--rs-accent-dim', 'color-mix(in srgb, var(--rs-accent) 80%, var(--rs-bg))');
|
||||
root.style.setProperty('--rs-accent-deep', 'color-mix(in srgb, var(--rs-accent) 60%, var(--rs-bg))');
|
||||
const semantic = mode === 'light' ? ['#b42323', '#8a5700', '#806600', '#287b29', '#7740a5']
|
||||
: ['#f44747', '#d68a00', '#cca700', '#89d185', '#c792ea'];
|
||||
if (theme === 'claude') { semantic[3] = '#788c5d'; semantic[4] = '#6a9bcc'; }
|
||||
if (theme === 'sakura') { semantic[3] = '#618c71'; semantic[4] = '#cb6b91'; }
|
||||
['error', 'warn-hot', 'warn', 'ok', 'special'].forEach((key, index) => root.style.setProperty(`--rs-${key}`, semantic[index]));
|
||||
const syntax = theme === 'sakura'
|
||||
? ['#cb6b91', '#98556c', '#618c71', '#69a2bd', '#607fa9', '#687788']
|
||||
: ['var(--rs-special)', 'var(--rs-accent)', 'var(--rs-text)', 'var(--rs-accent-2)', 'var(--rs-accent-2)', 'var(--rs-text-dim)'];
|
||||
['parameter', 'keyword', 'local', 'static', 'instance', 'global'].forEach((key, index) => root.style.setProperty(`--rs-syntax-${key}`, syntax[index]));
|
||||
root.style.setProperty('--rs-danger', 'var(--rs-error)');
|
||||
const custom = theme.startsWith('custom:') ? customThemes().find(item => item.id === theme.slice(7)) : undefined;
|
||||
if (custom) for (const [key, color] of Object.entries(custom[mode])) root.style.setProperty(`--rs-${key}`, color);
|
||||
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
|
||||
}
|
||||
export function saveAppearance(value: Appearance) {
|
||||
const appearance = normalizeAppearance(value);
|
||||
localStorage.setItem(APPEARANCE_KEY, JSON.stringify(appearance));
|
||||
applyAppearance(appearance);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
export const CUSTOM_THEMES_KEY = "runestone.custom-themes";
|
||||
export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special"] as const;
|
||||
export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>;
|
||||
export type CustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
|
||||
|
||||
export function parseCustomTheme(input: unknown): CustomTheme {
|
||||
if (!input || typeof input !== "object") throw new Error("Choose a RuneStone theme JSON file.");
|
||||
const value = input as Record<string, unknown>;
|
||||
if (value.schema !== 1 || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|
||||
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 1, an ID, and a name.");
|
||||
const colors = (mode: string): ThemeColors => {
|
||||
const source = value[mode];
|
||||
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(`The theme needs ${mode} colors.`);
|
||||
const result: ThemeColors = {};
|
||||
for (const [key, color] of Object.entries(source)) {
|
||||
if (!(COLOR_TOKENS as readonly string[]).includes(key)) throw new Error(`Unknown theme color: ${key}`);
|
||||
if (typeof color !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color)) throw new Error(`Use a hexadecimal color for ${key}.`);
|
||||
result[key as keyof ThemeColors] = color;
|
||||
}
|
||||
if (!result.bg || !result.text || !result.accent) throw new Error(`The ${mode} palette needs bg, text, and accent.`);
|
||||
return result;
|
||||
};
|
||||
return { schema: 1, id: value.id, name: value.name.trim(), light: colors("light"), dark: colors("dark") };
|
||||
}
|
||||
|
||||
export function customThemes(): CustomTheme[] {
|
||||
try {
|
||||
const stored = JSON.parse(localStorage.getItem(CUSTOM_THEMES_KEY) || "[]");
|
||||
return Array.isArray(stored) ? stored.flatMap(value => { try { return [parseCustomTheme(value)]; } catch { return []; } }) : [];
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
export function installTheme(theme: CustomTheme): void {
|
||||
const list = customThemes().filter(item => item.id !== theme.id);
|
||||
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify([...list, parseCustomTheme(theme)]));
|
||||
}
|
||||
|
||||
export function removeTheme(id: string): void {
|
||||
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(customThemes().filter(item => item.id !== id)));
|
||||
}
|
||||
@@ -1,11 +1,19 @@
|
||||
:root {
|
||||
--rs-control-radius: 5px;
|
||||
--rs-menu-width: 264px;
|
||||
--rs-titlebar-height: 36px;
|
||||
--rs-settings-row-padding: 10px;
|
||||
--rs-settings-control-height: 28px;
|
||||
--rs-settings-heading-size: 18px;
|
||||
--rs-settings-description-size: 12px;
|
||||
--rs-settings-gap: 8px;
|
||||
--rs-settings-section-gap: 16px;
|
||||
--rs-menu-width: 248px;
|
||||
--rs-menu-padding: 5px;
|
||||
--rs-menu-row-height: 30px;
|
||||
--rs-menu-row-padding: 6px 10px;
|
||||
--rs-menu-icon-size: 17px;
|
||||
--rs-menu-icon-gap: 10px;
|
||||
--rs-menu-row-height: 26px;
|
||||
--rs-menu-row-padding: 3px 8px;
|
||||
--rs-menu-icon-size: 14px;
|
||||
--rs-menu-icon-gap: 8px;
|
||||
--rs-menu-font-size: 12px;
|
||||
--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);
|
||||
@@ -30,9 +38,17 @@
|
||||
|
||||
--rs-font-ui: "Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif;
|
||||
--rs-font-prose: "Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif;
|
||||
--rs-font-mono: "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace;
|
||||
--rs-prose-size: 16px;
|
||||
--rs-prose-line: 1.65;
|
||||
--rs-font-heading: var(--rs-font-prose);
|
||||
--rs-font-mono: "Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace;
|
||||
--rs-code-font-weight: 300;
|
||||
--rs-code-font-size: 13px;
|
||||
--rs-code-line-height: 21px;
|
||||
--rs-font-weight: 400;
|
||||
--rs-heading-weight: 500;
|
||||
--rs-table-cell-padding: 4px 10px;
|
||||
--rs-table-line-height: 1.5;
|
||||
--rs-prose-size: 15px;
|
||||
--rs-prose-line: 1.6;
|
||||
--rs-code-size: 13px;
|
||||
--rs-h1-size: 1.6em;
|
||||
--rs-h2-size: 1.4em;
|
||||
@@ -61,3 +77,13 @@
|
||||
--rs-selection: #add6ff;
|
||||
--rs-line-highlight: #0000000d;
|
||||
}
|
||||
|
||||
[data-palette="claude"] {
|
||||
--rs-font-ui: "Lora", Georgia, serif;
|
||||
--rs-font-prose: "Lora", Georgia, serif;
|
||||
--rs-font-heading: "Poppins", Arial, sans-serif;
|
||||
}
|
||||
|
||||
[data-palette="sakura"] {
|
||||
--rs-item-selection-bg: var(--rs-selection);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,11 @@
|
||||
</script>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
{#if icon === "settings"}
|
||||
<path d="m9 3-1 3-3 1-2 3 2 2v3l3 2 1 4h5l1-3 3-1 3-4-2-2V8l-3-2-1-3Z" /><circle cx="12" cy="12" r="3" />
|
||||
<path d="M9.5 6 10 3 14 3 14.5 6 15.95 6.83 18.79 5.77 20.79 9.23 18.45 11.17 18.45 12.83 20.79 14.77 18.79 18.23 15.95 17.17 14.5 18 14 21 10 21 9.5 18 8.05 17.17 5.21 18.23 3.21 14.77 5.55 12.83 5.55 11.17 3.21 9.23 5.21 5.77 8.05 6.83Z" /><circle cx="12" cy="12" r="3" />
|
||||
{:else if icon === "sun"}
|
||||
<circle cx="12" cy="12" r="4" /><path d="M12 2v2m0 16v2M2 12h2m16 0h2M5 5l1.5 1.5m11 11L19 19M5 19l1.5-1.5m11-11L19 5" />
|
||||
{:else if icon === "git"}
|
||||
{@html actionIcons.git}
|
||||
{:else if icon === "globe"}
|
||||
<circle cx="12" cy="12" r="9" /><ellipse cx="12" cy="12" rx="4" ry="9" /><path d="M3 12h18" />
|
||||
{:else if icon === "arrow-left"}
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
import Icon from "./Icon.svelte";
|
||||
export type IconName =
|
||||
| "globe"
|
||||
| "git"
|
||||
| "arrow-left"
|
||||
| "arrow-right"
|
||||
| "copy"
|
||||
| "stop"
|
||||
| "settings"
|
||||
| "sun"
|
||||
| "help"
|
||||
| "puzzle"
|
||||
| "link"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<script lang="ts">
|
||||
import { onDestroy, tick } from "svelte";
|
||||
import { tick } from "svelte";
|
||||
import Icon from "./Icon.svelte";
|
||||
import type { IconName } from "./IconButton.svelte";
|
||||
|
||||
@@ -17,19 +17,13 @@
|
||||
let hovered = false;
|
||||
let keyboardFocus = false;
|
||||
let group: HTMLDivElement;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const expansionDelay = 1500;
|
||||
const selected = $derived(Math.max(0, options.findIndex(option => option.value === value)));
|
||||
|
||||
function scheduleExpansion() {
|
||||
clearTimeout(timer);
|
||||
if (!expanded && (hovered || keyboardFocus)) {
|
||||
timer = setTimeout(() => { expanded = true; }, expansionDelay);
|
||||
}
|
||||
if (hovered || keyboardFocus) expanded = true;
|
||||
}
|
||||
|
||||
function collapse() {
|
||||
clearTimeout(timer);
|
||||
expanded = false;
|
||||
}
|
||||
|
||||
@@ -39,7 +33,6 @@
|
||||
}
|
||||
|
||||
async function choose(index: number) {
|
||||
// Cycling should leave a full pause before the targets start moving.
|
||||
scheduleExpansion();
|
||||
const hadFocus = group.contains(document.activeElement);
|
||||
onchange(options[index].value);
|
||||
@@ -50,7 +43,6 @@
|
||||
|
||||
function keydown(event: KeyboardEvent) {
|
||||
keyboardFocus = true;
|
||||
if (event.key === "Enter" || event.key === " ") clearTimeout(timer);
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
@@ -59,7 +51,6 @@
|
||||
group.querySelector<HTMLButtonElement>(`[data-value="${value}"]`)?.focus();
|
||||
} else if (["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
clearTimeout(timer);
|
||||
expanded = true;
|
||||
const index = event.key === "Home" ? 0 : event.key === "End" ? options.length - 1
|
||||
: (selected + (event.key === "ArrowRight" ? 1 : -1) + options.length) % options.length;
|
||||
@@ -67,7 +58,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
onDestroy(() => clearTimeout(timer));
|
||||
</script>
|
||||
|
||||
<div
|
||||
@@ -107,7 +97,7 @@
|
||||
tabindex={expanded || option.value === value ? 0 : -1}
|
||||
onmouseenter={() => { tooltipDismissed = false; }}
|
||||
onfocus={() => { tooltipDismissed = false; }}
|
||||
onpointerdown={() => { keyboardFocus = false; clearTimeout(timer); }}
|
||||
onpointerdown={() => { keyboardFocus = false; }}
|
||||
onpointerup={scheduleExpansion}
|
||||
onpointercancel={scheduleExpansion}
|
||||
onkeydown={keydown}
|
||||
@@ -127,15 +117,14 @@
|
||||
flex: 0 0 auto;
|
||||
width: calc(var(--segment) * var(--count) + 6px);
|
||||
height: 34px;
|
||||
border: 1px solid var(--rs-border);
|
||||
border-radius: 8px;
|
||||
transition: width 180ms ease;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--rs-control-radius);
|
||||
}
|
||||
.selection {
|
||||
position: absolute;
|
||||
inset: 2px auto 2px 2px;
|
||||
width: var(--segment);
|
||||
border-radius: 5px;
|
||||
border-radius: var(--rs-control-radius);
|
||||
background: var(--rs-bg-active);
|
||||
transform: translateX(calc(var(--selected) * var(--segment)));
|
||||
transition: transform 180ms ease;
|
||||
@@ -152,14 +141,14 @@
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 5px;
|
||||
border-radius: var(--rs-control-radius);
|
||||
background: transparent;
|
||||
color: var(--rs-text-dim);
|
||||
font-size: 12px;
|
||||
transform: translateX(calc(var(--index) * var(--segment)));
|
||||
transition: transform 180ms ease, opacity 120ms ease;
|
||||
transition: opacity 120ms ease;
|
||||
}
|
||||
button.current { color: var(--rs-accent); }
|
||||
button.current { color: var(--rs-text-strong); }
|
||||
button:hover { color: var(--rs-text-strong); }
|
||||
button.concealed { visibility: hidden; opacity: 0; pointer-events: none; }
|
||||
button:hover, button:focus-visible { z-index: 1; }
|
||||
|
||||
@@ -55,7 +55,7 @@
|
||||
flex-basis: 40px;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
border-radius: var(--rs-control-radius);
|
||||
}
|
||||
.window-close :global(.icon-btn:hover) { background: #c42b1c; color: white; }
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
// Stroke icons share the same 24px grid and weight as IconButton.
|
||||
export const actionIcons = {
|
||||
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"/>',
|
||||
git: '<circle cx="7" cy="5" r="2"/><circle cx="7" cy="19" r="2"/><circle cx="17" cy="6" r="2"/><path d="M7 7v10m0-5h4a6 6 0 0 0 6-6"/>',
|
||||
globe: '<circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/>',
|
||||
puzzle: '<path d="M9 3H4v6a3 3 0 1 1 0 6v5h6a3 3 0 1 1 6 0h4v-6a3 3 0 1 0 0-6V3h-5a3 3 0 1 1-6 0Z"/>',
|
||||
'split-right': '<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M12 4v16m3-11 3 3-3 3"/>',
|
||||
|
||||
+18
-13
@@ -1,21 +1,24 @@
|
||||
import { actionIcon, type ActionIcon } from "./actionIcons";
|
||||
|
||||
export type ActionMenuItem = { label: string; icon?: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; title?: string } | { separator: true };
|
||||
export type ActionMenuItem = { label: string; icon?: ActionIcon; shortcut?: string; run?: () => void; children?: ActionMenuItem[]; disabled?: boolean; checked?: boolean; radio?: boolean; title?: string } | { separator: true };
|
||||
|
||||
export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClose: () => void, label = "Table actions") {
|
||||
export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClose: () => void, label = "Table actions", parent: HTMLElement = document.body) {
|
||||
const root = document.createElement("div"); root.className = "rs-menu table-cell-menu"; root.setAttribute("role", "menu"); root.setAttribute("aria-label", label);
|
||||
let opened: HTMLElement | undefined, owner: HTMLButtonElement | undefined;
|
||||
const opened: { button: HTMLButtonElement; panel: HTMLElement }[] = [];
|
||||
if (label.startsWith("Terminal")) root.style.width = "min(430px, calc(100vw - 16px))";
|
||||
const submenus = new Map<HTMLButtonElement, HTMLElement>();
|
||||
function hideSubmenu() { if (opened) opened.hidden = true; owner?.setAttribute("aria-expanded", "false"); opened = undefined; owner = undefined; }
|
||||
function hideSubmenu(parent: HTMLElement = root) {
|
||||
const keep = parent === root ? 0 : opened.findIndex(entry => entry.panel === parent) + 1;
|
||||
for (const { button, panel } of opened.splice(keep)) { panel.hidden = true; button.setAttribute("aria-expanded", "false"); }
|
||||
}
|
||||
function positionSubmenu(button: HTMLButtonElement, panel: HTMLElement) {
|
||||
const rect = button.getBoundingClientRect(), size = panel.getBoundingClientRect(), main = root.getBoundingClientRect();
|
||||
const rect = button.getBoundingClientRect(), size = panel.getBoundingClientRect(), main = button.parentElement!.getBoundingClientRect();
|
||||
panel.style.left = `${Math.max(8, main.right + size.width < innerWidth - 8 ? main.right - 2 : main.left - size.width + 2)}px`;
|
||||
panel.style.top = `${Math.max(8, Math.min(rect.top - 5, innerHeight - size.height - 8))}px`;
|
||||
}
|
||||
function reveal(button: HTMLButtonElement, panel: HTMLElement, focus = false) {
|
||||
if (opened !== panel) hideSubmenu();
|
||||
opened = panel; owner = button; panel.hidden = false; button.setAttribute("aria-expanded", "true");
|
||||
if (!opened.some(entry => entry.panel === panel)) { hideSubmenu(button.parentElement!); opened.push({ button, panel }); }
|
||||
panel.hidden = false; button.setAttribute("aria-expanded", "true");
|
||||
positionSubmenu(button, panel);
|
||||
if (focus) panel.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus({ preventScroll: true });
|
||||
}
|
||||
@@ -23,9 +26,10 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
|
||||
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.icon ? actionIcon(item.icon) : document.createElement("span");
|
||||
const icon = item.checked ? 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); }
|
||||
@@ -37,7 +41,7 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
|
||||
button.addEventListener("mousemove", () => { if (!button.disabled) reveal(button, submenu); });
|
||||
button.addEventListener("click", () => reveal(button, submenu, true));
|
||||
} else {
|
||||
if (panel === root) button.addEventListener("mousemove", hideSubmenu);
|
||||
button.addEventListener("mousemove", () => hideSubmenu(panel));
|
||||
button.addEventListener("click", event => { event.stopPropagation(); item.run?.(); });
|
||||
}
|
||||
}
|
||||
@@ -46,7 +50,7 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
|
||||
root.addEventListener("mousedown", event => { event.preventDefault(); event.stopPropagation(); });
|
||||
root.addEventListener("focusin", event => {
|
||||
const button = event.target as HTMLElement;
|
||||
if (button.parentElement === root && button !== owner) hideSubmenu();
|
||||
if (!opened.some(entry => entry.button === button) && button.parentElement) hideSubmenu(button.parentElement);
|
||||
});
|
||||
root.addEventListener("keydown", event => {
|
||||
event.stopPropagation();
|
||||
@@ -57,10 +61,11 @@ export function actionMenu(x: number, y: number, items: ActionMenuItem[], onClos
|
||||
event.preventDefault(); buttons[event.key === "Home" ? 0 : event.key === "End" ? buttons.length - 1 : (index + (event.key === "ArrowDown" ? 1 : -1) + buttons.length) % buttons.length]?.focus();
|
||||
}
|
||||
if (event.key === "ArrowRight" && submenus.has(focused)) { event.preventDefault(); reveal(focused, submenus.get(focused)!, true); }
|
||||
if (event.key === "ArrowLeft" && opened?.contains(focused)) { event.preventDefault(); const previous = owner; hideSubmenu(); previous?.focus(); }
|
||||
const entry = opened.find(entry => entry.panel === panel);
|
||||
if (event.key === "ArrowLeft" && entry) { event.preventDefault(); hideSubmenu(entry.button.parentElement!); entry.button.focus(); }
|
||||
});
|
||||
root.addEventListener("scroll", event => { if (event.target === root && opened && owner) positionSubmenu(owner, opened); });
|
||||
document.body.append(root);
|
||||
root.addEventListener("scroll", () => { for (const { button, panel } of opened) positionSubmenu(button, panel); }, true);
|
||||
parent.append(root);
|
||||
root.style.left = `${Math.max(8, Math.min(x, innerWidth - root.offsetWidth - 8))}px`;
|
||||
root.style.top = `${Math.max(8, Math.min(y, innerHeight - root.offsetHeight - 8))}px`;
|
||||
root.querySelector<HTMLButtonElement>(":scope > button:not(:disabled)")?.focus();
|
||||
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
background: var(--rs-bg-elevated);
|
||||
color: var(--rs-text);
|
||||
box-shadow: var(--rs-menu-shadow);
|
||||
font: 13px/1.4 var(--rs-font-ui);
|
||||
font: var(--rs-menu-font-size)/1.4 var(--rs-font-ui);
|
||||
}
|
||||
|
||||
.rs-menu.table-cell-submenu { z-index: 1001; }
|
||||
|
||||
@@ -19,8 +19,8 @@ export function workspaceOpen(path: string): Promise<WorkspaceInfo> {
|
||||
return invoke("workspace_open", { path });
|
||||
}
|
||||
|
||||
export function workspaceOpenWindow(path: string): Promise<void> {
|
||||
return invoke("workspace_open_window", { path });
|
||||
export function workspaceOpenWindow(path: string, transfer?: string): Promise<void> {
|
||||
return invoke("workspace_open_window", { path, transfer });
|
||||
}
|
||||
|
||||
export function workspaceLastPath(): Promise<string | null> {
|
||||
@@ -35,8 +35,8 @@ export function workspaceNew(parent: string, name: string): Promise<void> {
|
||||
return invoke("workspace_new", { parent, name });
|
||||
}
|
||||
|
||||
export function workspaceList(rel: string): Promise<TreeEntry[]> {
|
||||
return invoke("workspace_list", { rel });
|
||||
export function workspaceList(rel: string, showInternal = false): Promise<TreeEntry[]> {
|
||||
return invoke("workspace_list", { rel, showInternal });
|
||||
}
|
||||
|
||||
export function workspaceRead(rel: string): Promise<string> {
|
||||
@@ -55,8 +55,8 @@ export function workspaceCreate(rel: string, kind: "file" | "folder"): Promise<v
|
||||
return invoke("workspace_create", { rel, kind });
|
||||
}
|
||||
|
||||
export function workspaceRename(from: string, to: string): Promise<void> {
|
||||
return invoke("workspace_rename", { from, to });
|
||||
export function workspaceRename(from: string, to: string, expectedRoot?: string): Promise<void> {
|
||||
return invoke("workspace_rename", { from, to, expectedRoot });
|
||||
}
|
||||
|
||||
export function workspaceDelete(rel: string): Promise<void> {
|
||||
@@ -77,14 +77,17 @@ export type CopyResult = {
|
||||
kind: "file" | "folder";
|
||||
};
|
||||
|
||||
export function workspaceCopy(rel: string): Promise<CopyResult> {
|
||||
return invoke("workspace_copy", { rel });
|
||||
export function workspaceCopy(rel: string, parent?: string, expectedRoot?: string): Promise<CopyResult> {
|
||||
return invoke("workspace_copy", { rel, parent, expectedRoot });
|
||||
}
|
||||
|
||||
export function workspaceAbsPath(rel: string): Promise<string> {
|
||||
return invoke("workspace_abs_path", { rel });
|
||||
}
|
||||
|
||||
export function workspaceOpenDefault(rel: string): Promise<void> { return invoke("workspace_open_default", { rel }); }
|
||||
export function workspaceOpenTerminal(rel: string): Promise<void> { return invoke("workspace_open_terminal", { rel }); }
|
||||
|
||||
export function workspaceReveal(rel: string): Promise<void> {
|
||||
return invoke("workspace_reveal", { rel });
|
||||
}
|
||||
|
||||
@@ -46,6 +46,14 @@ export class Documents {
|
||||
this.emit();
|
||||
}
|
||||
|
||||
importTab(buffer: OpenBuffer) {
|
||||
if (this.disposed || this.buffers.some(tab => tab.relPath === buffer.relPath)) return false;
|
||||
this.buffers = this.buffers.filter(tab => tab.kind !== "empty");
|
||||
this.buffers.push({ ...buffer, id: crypto.randomUUID(), tabId: undefined });
|
||||
this.select(buffer.relPath);
|
||||
return true;
|
||||
}
|
||||
|
||||
async open(entry: TreeEntry, target: "current" | "new" = "new") {
|
||||
const request = ++this.selection;
|
||||
const previous = target === "current" || this.active?.kind === "empty" ? this.active : undefined;
|
||||
|
||||
@@ -2,10 +2,18 @@ import MarkdownIt from "markdown-it";
|
||||
import type { Token } from "markdown-it";
|
||||
import { inlineMathEnd } from "./inlineMath.ts";
|
||||
import { pluginHost } from "../plugins/registry.ts";
|
||||
import { hasTableDelimiter } from "../editor/markdownTable.ts";
|
||||
|
||||
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
|
||||
export const escapeHtml = markdown.utils.escapeHtml;
|
||||
|
||||
// Require a row delimiter so deleting a blank line cannot turn prose into cells.
|
||||
// Markdown-it checks blockquote terminators while it reads a table body.
|
||||
markdown.block.ruler.before("table", "table_prose_boundary", (state, line, _end, silent) => {
|
||||
return silent && state.parentType === "table" &&
|
||||
!hasTableDelimiter(state.src.slice(state.bMarks[line] + state.tShift[line], state.eMarks[line]));
|
||||
}, { alt: ["blockquote"] });
|
||||
|
||||
// Inline note formats also round-trip through the table cell editor.
|
||||
markdown.inline.ruler.before("emphasis", "note_formats", (state, silent) => {
|
||||
const marker = ["==", "%%", "$"].find(value => state.src.startsWith(value, state.pos));
|
||||
|
||||
@@ -5,11 +5,13 @@ export const MAX_AUTOSAVE_SECONDS = 300;
|
||||
export interface AppSettings {
|
||||
autosaveEnabled: boolean;
|
||||
autosaveSeconds: number;
|
||||
showInternalFolder: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS: Readonly<AppSettings> = {
|
||||
autosaveEnabled: true,
|
||||
autosaveSeconds: 5,
|
||||
showInternalFolder: false,
|
||||
};
|
||||
|
||||
export function validAutosaveSeconds(value: unknown): value is number {
|
||||
@@ -23,6 +25,7 @@ export function parseSettings(raw: string | null): AppSettings {
|
||||
return {
|
||||
autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled,
|
||||
autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds,
|
||||
showInternalFolder: value?.showInternalFolder === true,
|
||||
};
|
||||
} catch { return { ...DEFAULT_SETTINGS }; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { workspaceCreate, workspaceList, workspaceRead, workspaceWrite } from "./api";
|
||||
import { uniqueName, joinRel } from "./treeDrop";
|
||||
|
||||
export const TEMPLATE_FOLDER = ".runestone/templates";
|
||||
export type NoteTemplate = { name: string; path: string };
|
||||
|
||||
export async function noteTemplates(): Promise<NoteTemplate[]> {
|
||||
try {
|
||||
return (await workspaceList(TEMPLATE_FOLDER)).filter(entry => entry.kind === "file" && /\.md$/i.test(entry.name))
|
||||
.map(entry => ({ name: entry.name.replace(/\.md$/i, ""), path: entry.rel_path }))
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
export async function saveNoteTemplate(name: string, contents: string): Promise<void> {
|
||||
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();
|
||||
const file = uniqueName(existing.map(template => template.name + ".md"), title + ".md");
|
||||
const path = joinRel(TEMPLATE_FOLDER, file);
|
||||
await workspaceCreate(path, "file");
|
||||
await workspaceWrite(path, contents, "");
|
||||
window.dispatchEvent(new Event("runestone-templates-changed"));
|
||||
}
|
||||
|
||||
export async function createNote(parent = "", template?: NoteTemplate): Promise<string> {
|
||||
const contents = template ? await workspaceRead(template.path) : "";
|
||||
const names = (await workspaceList(parent)).map(entry => entry.name);
|
||||
const path = joinRel(parent, uniqueName(names, template ? `${template.name}.md` : "untitled.md"));
|
||||
await workspaceCreate(path, "file");
|
||||
if (contents) await workspaceWrite(path, contents, "");
|
||||
return path;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Marks } from "./marks";
|
||||
type Move = { from: string; to: string };
|
||||
const parent = (path: string) => path.split("/").slice(0, -1).join("/");
|
||||
const name = (path: string) => path.split("/").at(-1)!;
|
||||
|
||||
export function moveMarks(current: Marks, from: string, to: string): Marks {
|
||||
const map = (path: string) => path === from || path.startsWith(from + "/") ? to + path.slice(from.length) : path;
|
||||
const order = Object.fromEntries(Object.entries(current.order).map(([key, value]) => [map(key), [...value]]));
|
||||
if (parent(from) === parent(to)) {
|
||||
const list = order[parent(from)];
|
||||
if (list) order[parent(from)] = list.map(item => item === name(from) ? name(to) : item);
|
||||
} else {
|
||||
if (order[parent(from)]) order[parent(from)] = order[parent(from)].filter(item => item !== name(from));
|
||||
if (order[parent(to)] && !order[parent(to)].includes(name(to))) order[parent(to)].push(name(to));
|
||||
}
|
||||
return { pins: current.pins.map(map), bookmarks: current.bookmarks.map(map), order };
|
||||
}
|
||||
|
||||
export function replayMoveMarks(current: Marks, before: Marks, after: Marks, moves: Move[], redo: boolean): Marks {
|
||||
let result = current;
|
||||
for (const move of redo ? moves : [...moves].reverse()) result = moveMarks(result, redo ? move.from : move.to, redo ? move.to : move.from);
|
||||
const target = redo ? after : before;
|
||||
const order = { ...result.order };
|
||||
for (const folder of new Set([...Object.keys(before.order), ...Object.keys(after.order)])) {
|
||||
if (JSON.stringify(before.order[folder]) === JSON.stringify(after.order[folder])) continue;
|
||||
const known = new Set([...(before.order[folder] ?? []), ...(after.order[folder] ?? [])]);
|
||||
const added = (order[folder] ?? []).filter(item => !known.has(item));
|
||||
order[folder] = [...(target.order[folder] ?? []), ...added];
|
||||
}
|
||||
return { ...result, order };
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
export const WORKBENCH_LAYOUT_KEY = "runestone.workbenchLayout";
|
||||
|
||||
export interface WorkbenchLayout {
|
||||
leftOpen: boolean;
|
||||
rightOpen: boolean;
|
||||
leftWidth: number;
|
||||
rightWidth: number;
|
||||
leftView: "files" | "search" | "bookmarks";
|
||||
}
|
||||
|
||||
export const DEFAULT_WORKBENCH_LAYOUT: Readonly<WorkbenchLayout> = {
|
||||
leftOpen: true,
|
||||
rightOpen: true,
|
||||
leftWidth: 260,
|
||||
rightWidth: 240,
|
||||
leftView: "files",
|
||||
};
|
||||
|
||||
function width(value: unknown, fallback: number): number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value >= 160 && value <= 480 ? value : fallback;
|
||||
}
|
||||
|
||||
export function parseWorkbenchLayout(raw: string | null): WorkbenchLayout {
|
||||
try {
|
||||
const value = JSON.parse(raw ?? "null");
|
||||
return {
|
||||
leftOpen: typeof value?.leftOpen === "boolean" ? value.leftOpen : DEFAULT_WORKBENCH_LAYOUT.leftOpen,
|
||||
rightOpen: typeof value?.rightOpen === "boolean" ? value.rightOpen : DEFAULT_WORKBENCH_LAYOUT.rightOpen,
|
||||
leftWidth: width(value?.leftWidth, DEFAULT_WORKBENCH_LAYOUT.leftWidth),
|
||||
rightWidth: width(value?.rightWidth, DEFAULT_WORKBENCH_LAYOUT.rightWidth),
|
||||
leftView: ["files", "search", "bookmarks"].includes(value?.leftView) ? value.leftView : DEFAULT_WORKBENCH_LAYOUT.leftView,
|
||||
};
|
||||
} catch { return { ...DEFAULT_WORKBENCH_LAYOUT }; }
|
||||
}
|
||||
|
||||
export function saveWorkbenchLayout(storage: Pick<Storage, "setItem">, layout: WorkbenchLayout): void {
|
||||
storage.setItem(WORKBENCH_LAYOUT_KEY, JSON.stringify(layout));
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
<script lang="ts">
|
||||
import "../app.css";
|
||||
import ThemeSync from "$lib/theme/ThemeSync.svelte";
|
||||
import { onMount } from "svelte";
|
||||
import { isSpellingTarget, mountSpellingMenu } from "$lib/editor/spellingMenu";
|
||||
|
||||
let { children } = $props();
|
||||
onMount(mountSpellingMenu);
|
||||
</script>
|
||||
|
||||
<svelte:window oncontextmenu={(event) => event.preventDefault()} />
|
||||
<svelte:window oncontextmenu={(event) => { if (!isSpellingTarget(event.target)) event.preventDefault(); }} />
|
||||
|
||||
<ThemeSync />
|
||||
{@render children()}
|
||||
|
||||
Reference in New Issue
Block a user