RuneStone 1.0.0

This commit is contained in:
Knotty Wyvern
2026-11-16 04:21:21 -07:00
commit b52eeb14a1
827 changed files with 241421 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
<script lang="ts">
import { t } from "$lib/i18n";
import Icon from '$lib/ui/Icon.svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import { state as browserState, request } from './client';
import { engine, engineReady } from './engine';
let { open }: { open: (profileId: string, url: string) => Promise<void> } = $props();
let error = $state('');
// The bookmarks live in the engine. A missing engine is not started here.
const installed = $derived(engineReady($engine));
let loaded = false;
$effect(() => {
if (!installed) { loaded = false; return; }
if (loaded) return;
loaded = true;
void request('state').catch(reason => error = String(reason));
});
</script>
<div class="bookmarks">
{#if !installed}<p class="note">{$t("Install the browser engine to see the browser bookmarks.")}</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
{#each installed ? $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-hover-bg)}
.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-focus)}p{padding:8px;font-size:12px}.error{color:var(--rs-error)}.note{margin:0;color:var(--rs-text-dim)}
</style>
+340
View File
@@ -0,0 +1,340 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { keys } from '$lib/ui/shortcuts';
import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import Icon from '$lib/ui/Icon.svelte';
import { state as browserState, pageErrors, request, frames, pageEvents, type PageMenu, type BrowserFrame } from './client';
import type { ActionMenuItem } from '$lib/ui/actionMenu';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { WheelQueue } from './inputQueue';
import { TabSession, type TabStatus } from './tabSession';
import { engine } from './engine';
import { AutoScroll } from './autoScroll';
import { keepCopiedImage } from '$lib/workspace/copiedImage';
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: $t('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));
const blank = $derived(!current?.url || current.url === 'about:blank');
let address = $state(''); let editing = $state(false);
let image = $state(''), imageBox = $state({ width: 0, height: 0, x: 0, y: 0, exact: false }); let surface: HTMLDivElement; let addressField: HTMLInputElement;
let width = 1000, height = 700, textInput: HTMLTextAreaElement, composing = false;
let inputQueue = Promise.resolve();
const orderedInput = (command: string, args: Record<string, unknown>) => inputQueue = inputQueue.then(() => send(command, args));
function pageFocus(focused: boolean) { void orderedInput('focus', { focused }); }
const wheels = new WheelQueue(input => send('input', { input }));
let displayedFrame: BrowserFrame | undefined;
let closeMenu: (() => void) | undefined;
function chooseProfile(event: MouseEvent) {
closeMenu?.();
const anchor = event.currentTarget as HTMLButtonElement;
const rect = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: $t('Browser profile'),
items: ($browserState?.profiles || []).map(profile => ({ label: profile.name, radio: true,
checked: profile.id === current?.profileId, run: () => void openTab(profile.id) })) }).close;
}
let opening = $state(false), openingError = $state(''), mounted = $state(false);
let findOpen = $state(false), findText = $state('');
let findField: HTMLInputElement | undefined = $state();
let findTimer: ReturnType<typeof setTimeout> | undefined;
const autoScroll = new AutoScroll();
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
let scrollFrame = 0, moveFrame = 0, movePending = false;
let pendingMove: Record<string, unknown> | undefined;
let suppressedRelease = -1, middlePressed = false;
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 (displayedFrame) acknowledgeFrame();
if (frame.width > 0 && frame.height > 0 && ['image/png', 'image/jpeg'].includes(frame.mime)) {
displayedFrame = frame;
if (blank) { image = ''; acknowledgeFrame(); }
else {
image = `data:${frame.mime};base64,${frame.data}`; imageBox = frameBox(frame);
}
}
});
pageEvents.set(id, event => {
if (event.event === 'context-menu') showPageMenu(event);
else if (event.event === 'open-link' && event.url) void newTab(current?.profileId || 'user', event.url);
});
return () => { acknowledgeFrame(); frames.delete(id); pageEvents.delete(id); closeMenu?.(); };
});
/**
* Return the CSS box that shows each frame pixel on one screen pixel: the frame size in CSS pixels, and the offset
* from the surface edge to the next device pixel edge. A stretched or misaligned frame is resampled and blurs text.
* `exact` is true when the frame scale is the display scale. Then the image uses nearest-pixel sampling, because
* layout rounds the CSS size to 1/64 pixel and a scale of 0.99998 still blends neighbour pixels.
* Chromium uses nearest-pixel sampling only to scale up, so the size rounds up to the next 1/64 pixel.
* The image has its own compositor layer. A shared layer can start at a fractional device pixel and blend the frame again.
*/
function frameBox(frame: BrowserFrame) {
const scale = frame.scale || 1, ratio = devicePixelRatio || 1, rect = surface.getBoundingClientRect();
const align = (edge: number) => (Math.ceil(edge * ratio - 0.001) - edge * ratio) / ratio;
const size = (pixels: number) => Math.ceil(pixels / scale * 64) / 64;
return { width: size(frame.width), height: size(frame.height), x: align(rect.left), y: align(rect.top), exact: scale === ratio };
}
function acknowledgeFrame() {
const frame = displayedFrame; displayedFrame = undefined;
if (frame) void request('frameAck', { tabId: frame.tabId, frameId: frame.frameId }).catch(() => {});
}
function showPageMenu(context: PageMenu) {
stopScroll(); closeMenu?.();
const action = (name: string) => () => { void send('contextAction', { token: context.token, action: name }); };
const edit = (name: string) => () => { void orderedInput('edit', { action: name }); };
const items: ActionMenuItem[] = [];
if (context.linkURL) items.push(
{ label: $t('Open link in new tab'), icon: 'file-plus', run: () => void newTab(current?.profileId || 'user', context.linkURL) },
{ label: $t('Open link in default browser'), icon: 'external', run: action('openExternal') },
{ label: $t('Copy link address'), icon: 'copy', run: action('copyLink') },
{ label: $t('Save link as…'), icon: 'save', run: action('saveLink') }, { separator: true });
if (context.hasImageContents) items.push(
{ label: $t('Open image in new tab'), icon: 'file-plus', disabled: !context.srcURL, run: () => void newTab(current?.profileId || 'user', context.srcURL) },
{ label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
{ label: $t('Copy image'), icon: 'copy', run: () => copyImage(context) },
{ label: $t('Copy image address'), icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push(
{ label: $t('Undo'), icon: 'undo', shortcut: keys('Mod+Z'), disabled: !context.editFlags.canUndo, run: edit('undo') },
{ label: $t('Redo'), icon: 'redo', shortcut: keys('Mod+Shift+Z'), disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true },
{ label: $t('Cut'), icon: 'cut', shortcut: keys('Mod+X'), disabled: !context.editFlags.canCut, run: edit('cut') });
if (context.isEditable || context.selectionText) items.push({ label: $t('Copy'), icon: 'copy', shortcut: keys('Mod+C'), disabled: !context.editFlags.canCopy, run: edit('copy') });
if (context.isEditable) items.push(
{ label: $t('Paste'), icon: 'paste', shortcut: keys('Mod+V'), disabled: !context.editFlags.canPaste, run: edit('paste') },
{ label: $t('Paste as plain text'), icon: 'paste-text', shortcut: keys('Mod+Shift+V'), disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') },
{ label: $t('Select all'), icon: 'task', shortcut: keys('Mod+A'), run: edit('selectAll') }, { separator: true });
items.push({ label: $t('Back'), icon: 'arrow-left', disabled: !current?.canBack, run: () => void send('back') },
{ label: $t('Forward'), icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') },
{ label: $t('Reload'), icon: 'refresh', run: () => void send('reload') },
{ label: $t('Find in page'), icon: 'search', shortcut: keys('Mod+F'), run: () => void find() });
const rect = surface.getBoundingClientRect();
const menu = showActionMenu({ x: rect.left + imageBox.x + context.x, y: rect.top + imageBox.y + context.y,
items, label: $t('Browser page actions') });
closeMenu = menu.close;
}
$effect(() => { if (mounted && ready && tabId) untrack(syncSize); });
async function send(command: string, args = {}) {
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
await connection.send(command, args);
}
// A paste of a copied image uses the bytes that the page loaded. The engine gives them in parts.
// A paste can come before the reply, so the copy is known at once by its address.
function copyImage(context: PageMenu) {
const owner = tabId;
const data = (async () => {
const reply = await connection.send('contextAction', { token: context.token, action: 'copyImage' }) as { copied?: { token: string; mime: string } } | null | undefined;
const copied = reply?.copied;
if (!copied) return undefined;
let data = '';
for (let offset: number | null = 0; offset !== null;) {
const part: { data: string; next: number | null } = await request('copiedImage', { tabId: owner, token: copied.token, offset });
data += part.data; offset = part.next;
}
return `data:${copied.mime};base64,${data}`;
})().catch(() => undefined);
if (context.srcURL) keepCopiedImage(context.srcURL, data);
}
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);
// A move to a monitor with a different display scale changes the pixel ratio but not always the surface size.
let pixelRatio: MediaQueryList;
const watchPixelRatio = () => { pixelRatio = matchMedia(`(resolution: ${devicePixelRatio}dppx)`); pixelRatio.addEventListener('change', changePixelRatio, { once: true }); };
const changePixelRatio = () => { watchPixelRatio(); syncSize(); };
watchPixelRatio();
return () => { mounted = false; pixelRatio.removeEventListener('change', changePixelRatio); stopScroll(); wheels.close(); closeMenu?.(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
});
function syncSize() {
const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { stopScroll(); void send('visible', { visible: false }); return; }
width = Math.max(100, Math.min(5120, Math.round(rect.width)));
height = Math.max(100, Math.min(3200, Math.round(rect.height)));
void send('resize', { width, height, scale: Math.max(1, Math.min(3, devicePixelRatio || 1)) }); void send('visible', { visible: true });
}
const modifiers = (event: MouseEvent | KeyboardEvent) => [event.shiftKey && 'shift', event.ctrlKey && 'control', event.altKey && 'alt', event.metaKey && 'meta'].filter(Boolean);
function stopScroll() { autoScroll.stop(); wheels.clear(); scrollAnchor = null; cancelAnimationFrame(scrollFrame); }
function scrollStep(time: number) {
if (!autoScroll.anchor || !ready) { stopScroll(); return; }
const delta = autoScroll.delta(time);
if (delta && (delta.x || delta.y)) {
const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { stopScroll(); return; }
const anchor = autoScroll.anchor;
wheels.push({ type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x - imageBox.x)), y: Math.min(height - 1, Math.round(anchor.y - imageBox.y)), deltaX: -delta.x, deltaY: -delta.y });
}
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);
});
}
// The frame has the CSS size of the page viewport. A surface point less the frame offset is the same page point.
function pagePoint(point: { x: number; y: number }) {
return { x: Math.max(0, Math.min(width - 1, Math.round(point.x - imageBox.x))), y: Math.max(0, Math.min(height - 1, Math.round(point.y - imageBox.y))) };
}
// A middle-click starts scrolling at once. On a link, it stops the scroll and opens the link in a new tab.
async function openLinkAt(input: { x: number; y: number }) {
const owner = tabId;
const found = await request<{ url: string | null }>('linkAt', { tabId: owner, ...input }).catch(() => null);
if (!found?.url || owner !== tabId || !autoScroll.anchor) return;
stopScroll();
if (middlePressed) suppressedRelease = 1;
void newTab(current?.profileId || 'user', found.url);
}
function pointer(event: MouseEvent | WheelEvent, type: string) {
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
const rect = surface.getBoundingClientRect();
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
if (event.button === 1) middlePressed = type === 'mouseDown';
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);
void openLinkAt(pagePoint(point)); 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, ...pagePoint(point),
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
if (type === 'mouseMove') {
pendingMove = input;
if (!moveFrame && !movePending) moveFrame = requestAnimationFrame(flushMove);
} else { pendingMove = undefined; void orderedInput('input', { input }); }
}
function key(event: KeyboardEvent, type: string) {
if (event.isComposing || composing || event.key === 'Process' || event.key === 'Dead') return;
if (autoScroll.anchor) { stopScroll(); if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); return; } }
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'f') { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') void find(); return; }
if (event.key === 'Escape' && findOpen) { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') closeFind(); return; }
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'l') { event.preventDefault(); addressField.focus(); addressField.select(); return; }
if ((event.ctrlKey || event.metaKey) && [',', 'w', 't'].includes(event.key.toLowerCase())) return;
event.preventDefault(); event.stopPropagation();
const editActions: Record<string, string> = { a: 'selectAll', c: 'copy', x: 'cut', v: event.shiftKey ? 'pasteAndMatchStyle' : 'paste', z: event.shiftKey ? 'redo' : 'undo', y: 'redo' };
if ((event.ctrlKey || event.metaKey) && editActions[event.key.toLowerCase()]) {
if (type === 'keyDown') void orderedInput('edit', { action: editActions[event.key.toLowerCase()] });
return;
}
const names: Record<string, string> = { ArrowLeft: 'LEFT', ArrowRight: 'RIGHT', ArrowUp: 'UP', ArrowDown: 'DOWN', Enter: 'ENTER', Backspace: 'BACKSPACE', Escape: 'ESCAPE', Delete: 'DELETE', Tab: 'TAB', Home: 'HOME', End: 'END', PageUp: 'PAGEUP', PageDown: 'PAGEDOWN', ' ': 'SPACE' };
void orderedInput('input', { input: { type, keyCode: names[event.key] || event.key, modifiers: modifiers(event) } });
if (type === 'keyDown' && [...event.key].length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void orderedInput('insertText', { text: event.key });
}
</script>
<svelte:window onblur={() => { stopScroll(); pageFocus(false); }} onfocus={() => { if (surface?.contains(document.activeElement)) pageFocus(true); }} />
<svelte:document onvisibilitychange={() => { if (document.hidden) { stopScroll(); pageFocus(false); } else if (surface?.contains(document.activeElement)) pageFocus(true); }} />
<div class="browser" class:blank data-browser-tab={tabId} data-browser-state={status.phase}>
<form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}>
<IconButton icon="arrow-left" label={$t("Back")} disabled={!ready || !current?.canBack} onclick={() => void send('back')} />
<IconButton icon="arrow-right" label={$t("Forward")} disabled={!ready || !current?.canForward} onclick={() => void send('forward')} />
<IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : $t('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={$t("Address or search")} placeholder={$t("Search or enter an address")} spellcheck="false" autocomplete="off">
<IconButton icon="bookmark" label={$t("Bookmark this page")} disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} />
<button type="button" class="profile-choice" aria-label={$t("Browser profile")} aria-haspopup="menu" disabled={opening} onclick={chooseProfile}>
{$browserState?.profiles.find(profile => profile.id === current?.profileId)?.name ?? $t('Profile')}<Icon icon="chevron-down" />
</button>
</form>
{#if findOpen}
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) -->
<form class="findbar" role="search" aria-label={$t("Find in page")} onkeydown={findKey} onsubmit={event => { event.preventDefault(); search(true); }}>
<input bind:this={findField} bind:value={findText} aria-label={$t("Find in page")} placeholder={$t("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={$t("Previous match (Shift+Enter)")} disabled={!ready || !findText} onclick={() => search(true, false)} />
<IconButton icon="down" label={$t("Next match (Enter)")} disabled={!ready || !findText} onclick={() => search(true)} />
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={closeFind} />
</form>
{/if}
{#if status.phase === 'connecting'}<p class="status" role="status">{$t(status.message)}</p>{/if}
{#if ready && status.message}<p class="error" role="alert">{$t(status.message)}</p>{/if}
{#if status.phase === 'disconnected'}
<div class="error" role="alert"><p>{$t(status.message)}</p><button class="reconnect" onclick={() => void connection.connect()}>{$t("Reconnect")}</button></div>
{/if}
{#if status.detail}
<details class="diagnostics"><summary>{$t("Browser error details")}</summary><dl>
<dt>{$t("Operation")}</dt><dd>{status.detail.operation}</dd><dt>{$t("Reason")}</dt><dd>{status.detail.reason}</dd>
<dt>{$t("Tab")}</dt><dd>{status.detail.tabId || $t('Not created')}</dd><dt>{$t("Time")}</dt><dd>{status.detail.time}</dd>
<dt>{$t("Engine")}</dt><dd>{$engine?.version ?? ''}</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={$t("Web page")} tabindex="0"
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
onfocusin={() => pageFocus(true)} onfocusout={event => { if (!surface.contains(event.relatedTarget as Node | null)) pageFocus(false); }}
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
<textarea class="text-input" bind:this={textInput} aria-label={$t("Web page text input")} autocomplete="off" spellcheck="false"
oncompositionstart={() => composing = true}
oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }}
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
onblur={stopScroll}></textarea>
{#if image && ready && !blank}<img src={image} class:exact={imageBox.exact} style:width={`${imageBox.width}px`} style:height={`${imageBox.height}px`} style:transform={`translate(${imageBox.x}px, ${imageBox.y}px)`} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true"><Icon icon="scroll" /></span>{/if}
</div>
</div>
<style>
.text-input{position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;padding:0;border:0;}
.browser{display:flex;flex-direction:column;width:100%;height:100%;min-height:200px;background:var(--rs-bg);color:var(--rs-text);font-family:var(--rs-font-ui)}
.toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)}
.toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px}
input,.profile-choice{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
input{flex:1}.profile-choice{max-width:160px;display:flex;align-items:center;gap:var(--rs-menu-icon-gap);cursor:pointer}input:focus-visible,.profile-choice:focus-visible{outline:2px solid var(--rs-focus)}
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
.browser.blank,.blank .surface{background:transparent}
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:26px;height:26px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);pointer-events:none;box-shadow:0 1px 4px #0006}.scroll-anchor :global(svg){width:20px;height:20px;flex-basis:20px}
img{display:block;pointer-events:none;user-select:none;will-change:transform}img.exact{image-rendering:pixelated}.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-focus);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>
+17
View File
@@ -0,0 +1,17 @@
<script lang="ts">
import type { ComponentProps } from "svelte";
import Browser from "./Browser.svelte";
import EngineSetup from "./EngineSetup.svelte";
import { engine, engineReady } from "./engine";
// A browser tab shows the engine setup until the engine can start. Then it opens the page.
let props: ComponentProps<typeof Browser> = $props();
let browser = $state<ReturnType<typeof Browser>>();
export async function find() { await browser?.find(); }
export function detach() { browser?.detach(); }
export async function action(command: string, args: Record<string, unknown> = {}) { await browser?.action(command, args); }
</script>
{#if engineReady($engine)}
<Browser bind:this={browser} {...props} />
{:else}
<EngineSetup variant="tab" url={props.initial.url} />
{/if}
+78
View File
@@ -0,0 +1,78 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { confirm } from "@tauri-apps/plugin-dialog";
import { openUrl } from "@tauri-apps/plugin-opener";
import Icon from "$lib/ui/Icon.svelte";
import { engine, installEngine, installEngineFile, cancelEngine, removeEngine, megabytes } from "./engine";
// `tab` fills a browser tab while the engine is missing. `settings` is the Engine section of Settings → Browser.
let { variant, url = "" }: { variant: "tab" | "settings"; url?: string } = $props();
let failure = $state("");
const status = $derived($engine);
const phase = $derived(status?.state ?? "missing");
const busy = $derived(phase === "downloading" || phase === "installing");
const error = $derived(failure || status?.error || "");
const web = $derived(variant === "tab" && /^https?:\/\//i.test(url));
async function run(action: () => Promise<unknown>) {
failure = "";
try { await action(); } catch (reason) { failure = String(reason); }
}
async function remove() {
const accepted = await confirm($t("Remove the browser engine? Open browser tabs close. Your profiles, bookmarks, and history stay."), { title: $t("Remove browser engine"), kind: "warning", okLabel: $t("Remove"), cancelLabel: $t("Cancel") });
if (accepted) await run(removeEngine);
}
</script>
<section class="engine {variant}" aria-labelledby={`engine-${variant}`} data-engine-state={phase}>
{#if variant === "tab"}<span class="mark"><Icon icon="globe" /></span>{/if}
<h3 id={`engine-${variant}`}>{$t("Browser engine")}</h3>
{#if phase === "installed"}
<p>{$t("Version {version} is installed.", { version: status?.version ?? "" })}</p>
{:else if phase === "development"}
<p>{$t("This development build uses the engine in src-tauri/browser-engine.")}</p>
{:else if phase === "unavailable"}
<p>{$t("No browser engine is available for this platform yet.")}</p>
{:else if phase === "downloading"}
<p role="status">{$t("Downloading the browser engine: {received} of {total}.", { received: megabytes(status?.received ?? 0), total: megabytes(status?.bytes ?? 0) })}</p>
<progress max={status?.bytes || 1} value={status?.received ?? 0} aria-label={$t("Download progress")}></progress>
{:else if phase === "installing"}
<p role="status">{$t("Installing the browser engine…")}</p>
<progress aria-label={$t("Installation progress")}></progress>
{:else if phase === "update"}
<p>{$t("This RuneStone version needs browser engine {version}. The download is {size}.", { version: status?.version ?? "", size: megabytes(status?.bytes ?? 0) })}</p>
{:else}
<p>{$t("The built-in browser needs its engine. The engine is a separate download of {size}.", { size: megabytes(status?.bytes ?? 0) })}</p>
{/if}
{#if error && !busy}<p class="error" role="alert"><Icon icon="alert" /><span>{$t("The browser engine could not be installed: {reason}", { reason: error })}</span></p>{/if}
<div class="actions">
{#if busy}
<button type="button" disabled={phase === "installing"} onclick={() => void run(cancelEngine)}><Icon icon="close" />{$t("Cancel")}</button>
{:else if phase === "missing" || phase === "update"}
<button type="button" class="primary" onclick={() => void run(installEngine)}><Icon icon={error ? "refresh" : "download"} />{error ? $t("Retry") : phase === "update" ? $t("Update the engine") : $t("Download the engine")}</button>
<button type="button" onclick={() => void run(installEngineFile)}><Icon icon="folder-open" />{$t("Install from file…")}</button>
{:else if phase === "installed" && variant === "settings"}
<button type="button" class="danger" onclick={() => void remove()}><Icon icon="trash" />{$t("Remove engine")}</button>
{/if}
{#if web}<button type="button" onclick={() => void run(() => openUrl(url))}><Icon icon="globe" />{$t("Open in default browser")}</button>{/if}
</div>
</section>
<style>
.engine { color: var(--rs-text); font-family: var(--rs-font-ui); }
.engine.tab { box-sizing: border-box; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; height: 100%; min-height: 200px; padding: 24px 16px; text-align: center; background: var(--rs-bg); }
.engine.settings { padding: var(--rs-settings-row-padding); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
.mark { display: grid; place-items: center; width: 48px; height: 48px; color: var(--rs-accent); }
.mark :global(svg) { width: 40px; height: 40px; }
h3 { margin: 0 0 4px; font-size: 14px; font-weight: 500; color: var(--rs-text-strong); }
.tab h3 { font-size: var(--rs-settings-heading-size); }
p { margin: 4px 0; max-width: 60ch; color: var(--rs-text); font-size: var(--rs-settings-description-size); line-height: 1.6; }
.error { display: flex; align-items: flex-start; gap: 6px; color: var(--rs-error); text-align: left; }
.error :global(svg) { flex: none; width: 16px; height: 16px; margin-top: 2px; }
.error span { overflow-wrap: anywhere; }
progress { width: min(320px, 100%); height: 8px; accent-color: var(--rs-accent); }
.actions { display: flex; flex-wrap: wrap; justify-content: inherit; gap: 8px; margin-top: 8px; }
.tab .actions { justify-content: center; }
button { display: inline-flex; align-items: center; gap: 7px; min-height: var(--rs-settings-control-height); padding: 4px 10px; border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); color: var(--rs-text); font: inherit; cursor: pointer; }
button:hover:not(:disabled) { background: var(--rs-bg-active); }
button:focus-visible { outline: 2px solid var(--rs-focus); outline-offset: 1px; }
button:disabled { color: var(--rs-text-dim); cursor: default; }
button.primary, button.primary:hover { border-color: var(--rs-accent); background: var(--rs-accent); color: var(--rs-on-accent); }
button.danger { border-color: var(--rs-error); color: var(--rs-error); }
</style>
+103
View File
@@ -0,0 +1,103 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import WebData from './WebData.svelte';
import EngineSetup from './EngineSetup.svelte';
import { state as browserState, request } from './client';
import { engine, engineReady } from './engine';
let selected = $state('user'), name = $state(''), message = $state('');
let search = $state('duckduckgo'), adblock = $state(true), internalLinks = $state(true), rules = $state('');
let homepage = $state(''), filterLists = $state(''), ready = $state(false), busy = $state(false);
const engines = [{ id: 'duckduckgo', name: 'DuckDuckGo' }, { id: 'google', name: 'Google' }, { id: 'bing', name: 'Bing' }];
let closePicker = () => {};
onDestroy(() => closePicker());
function picker(event: MouseEvent, profile = false) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: profile ? $t('Profile') : $t('Search engine'),
parent: anchor.closest('dialog') ?? undefined,
items: (profile ? $browserState?.profiles || [] : engines).map(choice => ({ label: choice.name,
radio: true, checked: choice.id === (profile ? selected : search),
run: () => { if (profile) selected = choice.id; else { search = choice.id; void save(); } } })) }).close;
}
// The browser settings live in the engine, so they load when the engine can start.
const installed = $derived(engineReady($engine));
let loading = false;
$effect(() => {
if (!installed) { ready = false; loading = false; return; }
if (loading) return;
loading = true;
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 = $t('Changes saved.'); return next; } catch (error) { message = String(error); return null; }
}
async function create(duplicate: boolean) {
if (!name.trim()) { message = $t('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 = ''; }
}
// Settings apply at once: a switch or a choice on change, a text field when it loses focus.
// A change during a save starts one more save after it.
let pending = false;
async function save() {
if (!ready) return;
if (busy) { pending = true; return; }
busy = true; message = $t('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; }
if (pending) { pending = false; void save(); }
}
</script>
<div class="settings">
<h2>{$t("Browser")}</h2><p>{$t("Choose how you browse within RuneStone.")}</p>
<EngineSetup variant="settings" />
{#if !installed}
<p class="note">{$t("The other browser settings show after the engine is installed.")}</p>
{:else}
<h3>{$t("General")}</h3>
<fieldset disabled={!ready} onchange={() => void save()}>
<div class="card">
<label class="row"><span>{$t("Open web links in RuneStone")}<small>{$t("Turn this off to use your system browser.")}</small></span><input class="rs-switch" type="checkbox" role="switch" aria-label={$t("Open web links in RuneStone")} bind:checked={internalLinks}></label>
<label class="row"><span>{$t("Homepage")}<small>{$t("The page to open in each new browser tab. Leave blank for an empty page.")}</small></span><input class="address" type="url" aria-label={$t("Homepage")} placeholder="https://example.com" maxlength="8192" bind:value={homepage}></label>
<div class="row"><span>{$t("Search engine")}</span><button type="button" class="picker" aria-label={$t("Search engine")} aria-haspopup="menu" onclick={event => picker(event)}>{engines.find(engine => engine.id === search)?.name ?? 'DuckDuckGo'}<Icon icon="chevron-down" /></button></div>
<label class="row"><span>{$t("Block ads and trackers")}<small>{$t("Apply the filter lists and personal rules to all browser tabs.")}</small></span><input class="rs-switch" type="checkbox" role="switch" aria-label={$t("Block ads and trackers")} bind:checked={adblock}></label>
<label class="row list-row"><span>{$t("Ad blocking lists")}<small>{$t("One HTTPS filter list URL per line, up to eight lists. New lists download when you leave the field.")}</small></span><textarea aria-label={$t("Ad blocking lists")} rows="4" maxlength="66000" placeholder="https://easylist.to/easylist/easylist.txt" bind:value={filterLists}></textarea></label>
</div>
<label class="rules">{$t("Personal filter rules")}<small>{$t("Use one rule per line. Block a domain with ||ads.example.com^, allow it with @@||ads.example.com^, or hide an element with example.com##.advertisement. Save to apply the rules.")}</small><textarea rows="4" maxlength="100000" placeholder={'! Block an advertising domain\n||ads.example.com^\n! Hide an element on one site\nexample.com##.advertisement'} bind:value={rules}></textarea></label>
</fieldset>
<h3>{$t("Profiles")}</h3><p>{$t("New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.")}</p>
<div class="card profiles">
<div class="profile-choice"><span>{$t("Profile")}</span><button type="button" class="picker" aria-label={$t("Profile")} aria-haspopup="menu" disabled={!ready} onclick={event => picker(event, true)}>{$browserState?.profiles.find(profile => profile.id === selected)?.name ?? $t('Profile')}<Icon icon="chevron-down" /></button></div>
<label>{$t("New profile name")}<input bind:value={name} maxlength="60" placeholder={$t("Profile name")}></label>
<div class="actions"><button onclick={() => void create(false)}><Icon icon="plus" />{$t("New blank profile")}</button><button onclick={() => void create(true)}><Icon icon="duplicate" />{$t("Duplicate profile")}</button></div>
<p class="note">{$t("Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.")}</p>
</div>
<h3>{$t("Web data")}</h3><p>{$t("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' })}>{$t("Clear cache")}</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'cookies' })}>{$t("Clear cookies")}</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'history' })}>{$t("Clear history")}</button></div>
<p role="status">{message}</p>
{#if ready}<WebData profileId={selected} />{/if}
{/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:not(.rs-switch),textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px}
button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-focus);outline-offset:1px}
.picker{justify-content:space-between;min-width:140px;max-width:100%;overflow-wrap:anywhere;text-align:left}
.rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label,.profile-choice{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
.actions{display:flex;flex-wrap:wrap;gap:8px}.note{margin-bottom:0}
fieldset{border:0;margin:0;padding:0;min-width:0}small{display:block;color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5;margin-top:5px}
.row>span{flex:1}.address,.list-row textarea{width:260px;max-width:48%;box-sizing:border-box}.list-row{align-items:flex-start}textarea{resize:vertical}
@media(max-width:600px){.row{flex-wrap:wrap}.address,.list-row textarea{width:100%;max-width:100%}}
</style>
+67
View File
@@ -0,0 +1,67 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { request } from './client';
let { profileId }: { profileId: string } = $props();
type Cookie = { id: string; name: string; domain: string; path: string };
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 closePicker = () => {};
onDestroy(() => closePicker());
function chooseKind(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement, rect = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: $t('Web data type'),
parent: anchor.closest('dialog') ?? undefined,
items: (['cookies', 'history'] as const).map(value => ({ label: value === 'cookies' ? $t('Cookies') : $t('History'),
radio: true, checked: kind === value, run: () => kind = value })) }).close;
}
let generation = 0;
const cookies = $derived((data?.cookies || []).filter(item => `${item.domain} ${item.name} ${item.path}`.toLowerCase().includes(query.toLowerCase())));
const history = $derived((data?.history || []).filter(item => `${item.title} ${item.url}`.toLowerCase().includes(query.toLowerCase())));
$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={$t("Individual web data")}>
<div class="toolbar">
<div class="choice"><span>{$t("Show")}</span><button type="button" aria-label={$t("Web data type")} aria-haspopup="menu" onclick={chooseKind}>{kind === 'cookies' ? $t('Cookies') : $t('History')}<Icon icon="chevron-down" /></button></div>
<label class="search">{$t("Filter")}<input type="search" aria-label={$t("Filter web data")} bind:value={query} placeholder={$t("Search this profile")}></label>
<button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />{$t("Refresh")}</button>
</div>
<p>{$t("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">{$t("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 || $t("(unnamed cookie)")}</strong><small>{cookie.domain} · {cookie.path}</small></div><button disabled={busy} aria-label={$t("Remove cookie {name} from {domain} at {path}", { name: cookie.name, domain: cookie.domain, path: cookie.path })} onclick={() => void remove('removeCookie', cookie.id)}><Icon icon="trash" />{$t("Remove")}</button></div>{/each}
{#if data && !cookies.length}<p>{$t("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={$t("Remove history entry {name}", { name: visit.title || visit.url })} onclick={() => void remove('removeHistory', visit.id)}><Icon icon="trash" />{$t("Remove")}</button></div>{/each}
{#if data && !history.length}<p>{$t("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,.choice{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
button{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;cursor:pointer}button:hover{background:var(--rs-bg-active)}button:disabled{opacity:.6;cursor:wait}
button:focus-visible,input:focus-visible{outline:2px solid var(--rs-focus);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>
+23
View File
@@ -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(3000, Math.max(0, Math.abs(distance) - 12) * 18);
return { x: speed(this.point.x - this.anchor.x) * elapsed / 1000, y: speed(this.point.y - this.anchor.y) * elapsed / 1000 };
}
}
+48
View File
@@ -0,0 +1,48 @@
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 type BrowserFrame = { tabId: string; frameId: number; mime: 'image/png' | 'image/jpeg'; data: string; width: number; height: number; scale?: number };
export type PageMenu = { event: string; tabId: string; token: string; x: number; y: number; linkURL: string; srcURL: string; hasImageContents: boolean; isEditable: boolean; selectionText: string; editFlags: Record<string, boolean>; url?: string };
export const frames = new Map<string, (frame: BrowserFrame) => void>();
export const pageEvents = new Map<string, (event: PageMenu) => void>();
let snapshots = new SnapshotOrder();
let session: string | undefined;
function isSnapshot(value: unknown): value is Snapshot {
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<PageMenu & { state?: Snapshot; message?: string }>('browser-state', ({ payload }) => {
if (signal.aborted) return;
if (isSnapshot(payload.state) && snapshots.accept(payload.state)) state.set(payload.state);
if (payload.message && payload.tabId) pageErrors.update(errors => ({ ...errors, [payload.tabId!]: payload.message! }));
if (payload.tabId) pageEvents.get(payload.tabId)?.(payload);
});
const offFrame = await window.listen<BrowserFrame>('browser-frame', ({ payload }) => {
if (!signal.aborted) frames.get(payload.tabId)?.(payload);
if (!frames.has(payload.tabId)) void request('frameAck', { tabId: payload.tabId, frameId: payload.frameId }).catch(() => {});
});
const stop = async () => { offState(); offFrame(); frames.clear(); pageEvents.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
if (signal.aborted) await stop();
return stop;
}
+28
View File
@@ -0,0 +1,28 @@
import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import { writable } from 'svelte/store';
import { tr } from '../i18n/index.ts';
/** The engine states of `browser_engine_status`. See src-tauri/src/browser_engine.rs. */
export type EngineStatus = {
state: 'installed' | 'missing' | 'update' | 'downloading' | 'installing' | 'unavailable' | 'development';
version: string; bytes: number; received: number; error: string | null;
};
export const engine = writable<EngineStatus | null>(null);
/** True when the engine can start: the pinned version is installed, or a development engine is staged. */
export const engineReady = (status: EngineStatus | null) => status?.state === 'installed' || status?.state === 'development';
const update = (status: EngineStatus) => { engine.set(status); return status; };
/** Follow the engine status in this window. A failed status request reports the engine as unavailable. */
export async function watchEngine(signal: AbortSignal) {
const off = await listen<EngineStatus>('browser-engine', ({ payload }) => { if (!signal.aborted) engine.set(payload); });
try { update(await invoke<EngineStatus>('browser_engine_status')); }
catch (error) { update({ state: 'unavailable', version: '', bytes: 0, received: 0, error: String(error) }); }
return () => { off(); engine.set(null); };
}
export const installEngine = () => invoke<EngineStatus>('browser_engine_install').then(update);
export const installEngineFile = () => invoke<EngineStatus>('browser_engine_install_file').then(update);
export const cancelEngine = () => invoke<EngineStatus>('browser_engine_cancel').then(update);
export const removeEngine = () => invoke<EngineStatus>('browser_engine_remove').then(update);
/** A download size in megabytes, such as "161 MB". */
export const megabytes = (bytes: number) => tr('{size} MB', { size: Math.max(bytes ? 1 : 0, Math.round(bytes / 1_000_000)) });
+134
View File
@@ -0,0 +1,134 @@
import { tr } from "../i18n/index.ts";
import { keys } from '../ui/shortcuts.ts';
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 BrowserTab from './BrowserTab.svelte';
import Settings from './Settings.svelte';
import Bookmarks from './Bookmarks.svelte';
import { connect, request, state } from './client';
import { engine, engineReady, watchEngine } from './engine';
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 offEngine = await watchEngine(api.signal); api.onDispose(offEngine);
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); };
// A new tab with the home page of the profile opens in a pane beside this tab.
const split = (direction: 'right' | 'down') => {
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
void open(current?.profileId || saved.profileId, undefined, { 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: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
{ label: tr("New tab to the right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
{ label: tr("New tab below"), icon: 'split-down', disabled: !ready, run: () => split('down') },
{ separator: true },
{ label: tr("Find…"), icon: 'search', shortcut: keys('Mod+F'), disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
{ label: tr("Bookmark"), icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
];
}, mount: container => {
let runtimeId = '';
const instance = mount(BrowserTab, { 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, url?: string) => open(profile, url),
} });
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', icon: 'globe', run: () => open() });
api.contribute('browser', {
// A new tab shows the engine setup when the engine is missing.
newTab: url => open(undefined, url),
mountSettings: container => retain(mount(Settings, { target: container })),
mountBookmarks: container => retain(mount(Bookmarks, { target: container, props: { open } })),
// A web link never starts a download. Without an engine, the link opens in the system browser.
open: async url => {
if (!engineReady(get(engine))) return false;
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(tr("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(tr("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);
}
}
+32
View File
@@ -0,0 +1,32 @@
type Wheel = { type: 'mouseWheel'; x: number; y: number; deltaX: number; deltaY: number; modifiers?: unknown[] };
/** Keep one pending wheel event while the transport processes the current event. */
export class WheelQueue {
private pending?: Wheel;
private running = false;
private closed = false;
private send: (input: Wheel) => Promise<unknown>;
constructor(send: (input: Wheel) => Promise<unknown>) { this.send = send; }
push(input: Wheel) {
if (this.closed) return;
const previous = this.pending;
// A direction change replaces stale motion instead of replaying it later.
const add = (old: number, next: number) => Math.sign(old) === Math.sign(next) || !next ? old + next : next;
this.pending = { ...input,
deltaX: Math.max(-2000, Math.min(2000, previous ? add(previous.deltaX, input.deltaX) : input.deltaX)),
deltaY: Math.max(-2000, Math.min(2000, previous ? add(previous.deltaY, input.deltaY) : input.deltaY)) };
void this.flush();
}
clear() { this.pending = undefined; }
close() { this.closed = true; this.clear(); }
private async flush() {
if (this.running) return;
this.running = true;
try {
while (this.pending && !this.closed) {
const input = this.pending; this.pending = undefined;
await this.send(input);
}
} finally { this.running = false; }
}
}
+18
View File
@@ -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;
}
}
+107
View File
@@ -0,0 +1,107 @@
import { message, tr } from "../i18n/index.ts";
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' ? message('The browser could not complete this request. Check the error details.') : connectionLost(error)
? message('This tab lost its browser connection. Select Reconnect to restore the page.')
: message('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 ? message('Reconnecting browser…') : message('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(tr("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;
}
}
}
/** Returns the reply of the engine, or undefined when the request did not complete. */
async send(command: string, args: Record<string, unknown> = {}): Promise<unknown> {
if (this.closed || this.value.phase !== 'ready') return;
const tabId = this.value.tabId;
try {
const reply = 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: '' });
return reply;
} 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(() => {});
}
}