Update the browser, editor, settings, and installer

This commit is contained in:
Knotty Wyvern
2026-10-12 14:46:21 -07:00
parent 909894b9c8
commit f6eaa52949
163 changed files with 146260 additions and 534 deletions
+84 -21
View File
@@ -1,10 +1,13 @@
<script lang="ts">
import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import { state as browserState, pageErrors, request, frames } from './client';
import { state as browserState, pageErrors, request, frames, pageEvents, type PageMenu, type BrowserFrame } from './client';
import type { ActionMenuItem } from '$lib/ui/actionMenu';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { WheelQueue } from './inputQueue';
import { TabSession, type TabStatus } from './tabSession';
import { AutoScroll } from './autoScroll';
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string) => Promise<void> } = $props();
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string, url?: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: 'Opening browser…' });
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
const tabId = $derived(status.tabId);
@@ -12,14 +15,19 @@
const current = $derived($browserState?.tabs.find(tab => tab.id === tabId));
let address = $state(''); let editing = $state(false);
let image = $state(''); let surface: HTMLDivElement; let addressField: HTMLInputElement;
let width = 1000, height = 700;
let width = 1000, height = 700, textInput: HTMLTextAreaElement, composing = false;
let inputQueue = Promise.resolve();
const orderedInput = (command: string, args: Record<string, unknown>) => inputQueue = inputQueue.then(() => send(command, args));
const wheels = new WheelQueue(input => send('input', { input }));
let displayedFrame: BrowserFrame | undefined;
let closeMenu: (() => void) | undefined;
let opening = $state(false), openingError = $state(''), mounted = $state(false);
let findOpen = $state(false), findText = $state('');
let findField: HTMLInputElement | undefined = $state();
let findTimer: ReturnType<typeof setTimeout> | undefined;
const autoScroll = new AutoScroll();
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
let scrollFrame = 0, moveFrame = 0, wheelPending = false, movePending = false;
let scrollFrame = 0, moveFrame = 0, movePending = false;
let pendingMove: Record<string, unknown> | undefined;
let suppressedRelease = -1;
const result = $derived(current?.find?.text === findText ? current.find : null);
@@ -50,10 +58,53 @@
image = '';
if (!id) return;
frames.set(id, frame => {
if (frame.width > 0 && frame.height > 0 && frame.png.startsWith('iVBORw0KGgo')) image = `data:image/png;base64,${frame.png}`;
if (displayedFrame) acknowledgeFrame();
if (frame.width > 0 && frame.height > 0 && ['image/png', 'image/jpeg'].includes(frame.mime)) {
displayedFrame = frame; image = `data:${frame.mime};base64,${frame.data}`;
}
});
return () => { frames.delete(id); };
pageEvents.set(id, event => {
if (event.event === 'context-menu') showPageMenu(event);
else if (event.event === 'open-link' && event.url) void newTab(current?.profileId || 'user', event.url);
});
return () => { acknowledgeFrame(); frames.delete(id); pageEvents.delete(id); closeMenu?.(); };
});
function acknowledgeFrame() {
const frame = displayedFrame; displayedFrame = undefined;
if (frame) void request('frameAck', { tabId: frame.tabId, frameId: frame.frameId }).catch(() => {});
}
function showPageMenu(context: PageMenu) {
stopScroll(); closeMenu?.();
const action = (name: string) => () => { void send('contextAction', { token: context.token, action: name }); };
const edit = (name: string) => () => { void orderedInput('edit', { action: name }); };
const items: ActionMenuItem[] = [];
if (context.linkURL) items.push(
{ label: 'Open link in new tab', icon: 'file-plus', run: () => void newTab(current?.profileId || 'user', context.linkURL) },
{ label: 'Open link in default browser', icon: 'external', run: action('openExternal') },
{ label: 'Copy link address', icon: 'copy', run: action('copyLink') },
{ label: 'Save link as…', icon: 'save', run: action('saveLink') }, { separator: true });
if (context.hasImageContents) items.push(
{ label: 'Save image as…', icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
{ label: 'Copy image', icon: 'copy', run: action('copyImage') },
{ label: 'Copy image address', icon: 'copy', disabled: !context.srcURL, run: action('copyImageAddress') }, { separator: true });
if (context.isEditable) items.push(
{ label: 'Undo', icon: 'undo', shortcut: 'Ctrl+Z', disabled: !context.editFlags.canUndo, run: edit('undo') },
{ label: 'Redo', icon: 'redo', shortcut: 'Ctrl+Shift+Z', disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true },
{ label: 'Cut', icon: 'cut', shortcut: 'Ctrl+X', disabled: !context.editFlags.canCut, run: edit('cut') });
if (context.isEditable || context.selectionText) items.push({ label: 'Copy', icon: 'copy', shortcut: 'Ctrl+C', disabled: !context.editFlags.canCopy, run: edit('copy') });
if (context.isEditable) items.push(
{ label: 'Paste', icon: 'paste', shortcut: 'Ctrl+V', disabled: !context.editFlags.canPaste, run: edit('paste') },
{ label: 'Paste as plain text', icon: 'paste-text', shortcut: 'Ctrl+Shift+V', disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') },
{ label: 'Select all', icon: 'task', shortcut: 'Ctrl+A', run: edit('selectAll') }, { separator: true });
items.push({ label: 'Back', icon: 'arrow-left', disabled: !current?.canBack, run: () => void send('back') },
{ label: 'Forward', icon: 'arrow-right', disabled: !current?.canForward, run: () => void send('forward') },
{ label: 'Reload', icon: 'refresh', run: () => void send('reload') },
{ label: 'Find in page', icon: 'search', shortcut: 'Ctrl+F', run: () => void find() });
const rect = surface.getBoundingClientRect();
const menu = showActionMenu({ x: rect.left + context.x * rect.width / width, y: rect.top + context.y * rect.height / height,
items, label: 'Browser page actions' });
closeMenu = menu.close;
}
$effect(() => { if (mounted && ready && tabId) untrack(syncSize); });
async function send(command: string, args = {}) {
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
@@ -75,26 +126,25 @@
timer = setTimeout(syncSize, 100);
});
resize.observe(surface);
return () => { mounted = false; stopScroll(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
return () => { mounted = false; stopScroll(); wheels.close(); closeMenu?.(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
});
function syncSize() {
const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { stopScroll(); void send('visible', { visible: false }); return; }
width = Math.max(100, Math.min(2560, Math.round(rect.width)));
height = Math.max(100, Math.min(1600, Math.round(rect.height)));
void send('resize', { width, height }); void send('visible', { visible: true });
width = Math.max(100, Math.min(5120, Math.round(rect.width)));
height = Math.max(100, Math.min(3200, Math.round(rect.height)));
void send('resize', { width, height, scale: Math.max(1, Math.min(3, devicePixelRatio || 1)) }); void send('visible', { visible: true });
}
const modifiers = (event: MouseEvent | KeyboardEvent) => [event.shiftKey && 'shift', event.ctrlKey && 'control', event.altKey && 'alt', event.metaKey && 'meta'].filter(Boolean);
function stopScroll() { autoScroll.stop(); scrollAnchor = null; cancelAnimationFrame(scrollFrame); }
function stopScroll() { autoScroll.stop(); wheels.clear(); scrollAnchor = null; cancelAnimationFrame(scrollFrame); }
function scrollStep(time: number) {
if (!autoScroll.anchor || !ready) { stopScroll(); return; }
const delta = autoScroll.delta(time);
if (delta && !wheelPending && (delta.x || delta.y)) {
wheelPending = true;
if (delta && (delta.x || delta.y)) {
const rect = surface.getBoundingClientRect();
if (!rect.width || !rect.height) { wheelPending = false; stopScroll(); return; }
if (!rect.width || !rect.height) { stopScroll(); return; }
const anchor = autoScroll.anchor;
void send('input', { input: { type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x * width / rect.width)), y: Math.min(height - 1, Math.round(anchor.y * height / rect.height)), deltaX: -delta.x, deltaY: -delta.y } }).finally(() => wheelPending = false);
wheels.push({ type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x * width / rect.width)), y: Math.min(height - 1, Math.round(anchor.y * height / rect.height)), deltaX: -delta.x, deltaY: -delta.y });
}
scrollFrame = requestAnimationFrame(scrollStep);
}
@@ -108,7 +158,7 @@
});
}
function pointer(event: MouseEvent | WheelEvent, type: string) {
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') surface.focus();
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') textInput.focus({ preventScroll: true });
const rect = surface.getBoundingClientRect();
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
@@ -124,22 +174,29 @@
}
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x * width / rect.width))), y: Math.max(0, Math.min(height - 1, Math.round(point.y * height / rect.height))),
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
...('deltaY' in event ? { deltaY: -event.deltaY, deltaX: -event.deltaX } : {}) };
...('deltaY' in event ? { deltaY: -event.deltaY * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? height : 1), deltaX: -event.deltaX * (event.deltaMode === 1 ? 40 : event.deltaMode === 2 ? width : 1) } : {}) };
if (type === 'mouseWheel') { wheels.push(input as Parameters<WheelQueue['push']>[0]); return; }
if (type === 'mouseMove') {
pendingMove = input;
if (!moveFrame && !movePending) moveFrame = requestAnimationFrame(flushMove);
} else { pendingMove = undefined; void send('input', { input }); }
} else { pendingMove = undefined; void orderedInput('input', { input }); }
}
function key(event: KeyboardEvent, type: string) {
if (event.isComposing || composing || event.key === 'Process' || event.key === 'Dead') return;
if (autoScroll.anchor) { stopScroll(); if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); return; } }
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'f') { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') void find(); return; }
if (event.key === 'Escape' && findOpen) { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') closeFind(); return; }
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'l') { event.preventDefault(); addressField.focus(); addressField.select(); return; }
if ((event.ctrlKey || event.metaKey) && [',', 'w', 't'].includes(event.key.toLowerCase())) return;
event.preventDefault(); event.stopPropagation();
const editActions: Record<string, string> = { a: 'selectAll', c: 'copy', x: 'cut', v: event.shiftKey ? 'pasteAndMatchStyle' : 'paste', z: event.shiftKey ? 'redo' : 'undo', y: 'redo' };
if ((event.ctrlKey || event.metaKey) && editActions[event.key.toLowerCase()]) {
if (type === 'keyDown') void orderedInput('edit', { action: editActions[event.key.toLowerCase()] });
return;
}
const names: Record<string, string> = { ArrowLeft: 'LEFT', ArrowRight: 'RIGHT', ArrowUp: 'UP', ArrowDown: 'DOWN', Enter: 'ENTER', Backspace: 'BACKSPACE', Escape: 'ESCAPE', Delete: 'DELETE', Tab: 'TAB', Home: 'HOME', End: 'END', PageUp: 'PAGEUP', PageDown: 'PAGEDOWN', ' ': 'SPACE' };
void send('input', { input: { type, keyCode: names[event.key] || event.key, modifiers: modifiers(event) } });
if (type === 'keyDown' && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void send('input', { input: { type: 'char', keyCode: event.key } });
void orderedInput('input', { input: { type, keyCode: names[event.key] || event.key, modifiers: modifiers(event) } });
if (type === 'keyDown' && [...event.key].length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void orderedInput('insertText', { text: event.key });
}
</script>
<svelte:window onblur={stopScroll} />
@@ -184,11 +241,17 @@
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
{#if image && ready}<img src={image} alt="Web page rendered by the browser" draggable="false">{/if}
<textarea class="text-input" bind:this={textInput} aria-label="Web page text input" autocomplete="off" spellcheck="false"
oncompositionstart={() => composing = true}
oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }}
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
onblur={stopScroll}></textarea>
{#if image && ready}<img src={image} alt="Web page rendered by the browser" draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
</div>
</div>
<style>
.text-input{position:absolute;left:0;top:0;width:1px;height:1px;opacity:0;pointer-events:none;padding:0;border:0;}
.browser{display:flex;flex-direction:column;width:100%;height:100%;min-height:200px;background:var(--rs-bg);color:var(--rs-text);font-family:var(--rs-font-ui)}
.toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)}
.toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px}
+22 -7
View File
@@ -1,11 +1,25 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import WebData from './WebData.svelte';
import { state as browserState, request } from './client';
let selected = $state('user'), name = $state(''), message = $state('');
let search = $state('duckduckgo'), adblock = $state(true), internalLinks = $state(true), rules = $state('');
let homepage = $state(''), filterLists = $state(''), ready = $state(false), busy = $state(false);
const engines = [{ id: 'duckduckgo', name: 'DuckDuckGo' }, { id: 'google', name: 'Google' }, { id: 'bing', name: 'Bing' }];
let closePicker = () => {};
onDestroy(() => closePicker());
function picker(event: MouseEvent, profile = false) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: profile ? 'Profile' : 'Search engine',
parent: anchor.closest('dialog') ?? undefined,
items: (profile ? $browserState?.profiles || [] : engines).map(choice => ({ label: choice.name,
radio: true, checked: choice.id === (profile ? selected : search),
run: () => { if (profile) selected = choice.id; else search = choice.id; } })) }).close;
}
onMount(() => { void request('state').then(value => {
selected = value.profiles[0].id; search = value.settings.search; adblock = value.settings.adblock;
internalLinks = value.settings.linkDestination === 'internal'; rules = value.settings.personalRules;
@@ -35,17 +49,17 @@
<div class="card">
<label class="row"><span>Open web links in RuneStone<small>Turn this off to use your system browser.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Open web links in RuneStone" bind:checked={internalLinks}></label>
<label class="row"><span>Homepage<small>The page to open in each new browser tab. Leave blank for an empty page.</small></span><input class="address" type="url" aria-label="Homepage" placeholder="https://example.com" maxlength="8192" bind:value={homepage}></label>
<label class="row"><span>Search engine</span><select bind:value={search}><option value="duckduckgo">DuckDuckGo</option><option value="google">Google</option><option value="bing">Bing</option></select></label>
<div class="row"><span>Search engine</span><button type="button" class="picker" aria-label="Search engine" aria-haspopup="menu" onclick={event => picker(event)}>{engines.find(engine => engine.id === search)?.name ?? 'DuckDuckGo'}<Icon icon="chevron-down" /></button></div>
<label class="row"><span>Block ads and trackers<small>Apply the filter lists and personal rules to all browser tabs.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Block ads and trackers" bind:checked={adblock}></label>
<label class="row list-row"><span>Ad blocking lists<small>One HTTPS filter list URL per line, up to eight lists. New lists download when you save.</small></span><textarea aria-label="Ad blocking lists" rows="4" maxlength="66000" placeholder="https://easylist.to/easylist/easylist.txt" bind:value={filterLists}></textarea></label>
</div>
<label class="rules">Personal filter rules<small>Optional rules to add to the selected lists.</small><textarea rows="4" maxlength="100000" bind:value={rules}></textarea></label>
<label class="rules">Personal filter rules<small>Use one rule per line. Block a domain with ||ads.example.com^, allow it with @@||ads.example.com^, or hide an element with example.com##.advertisement. Save to apply the rules.</small><textarea rows="4" maxlength="100000" placeholder={'! Block an advertising domain\n||ads.example.com^\n! Hide an element on one site\nexample.com##.advertisement'} bind:value={rules}></textarea></label>
<button type="submit"><Icon icon="save" />{busy ? 'Saving…' : 'Save browser settings'}</button>
</fieldset>
</form>
<h3>Profiles</h3><p>New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.</p>
<div class="card profiles">
<label>Profile<select aria-label="Profile" bind:value={selected}>{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}</select></label>
<div class="profile-choice"><span>Profile</span><button type="button" class="picker" aria-label="Profile" aria-haspopup="menu" disabled={!ready} onclick={event => picker(event, true)}>{$browserState?.profiles.find(profile => profile.id === selected)?.name ?? 'Profile'}<Icon icon="chevron-down" /></button></div>
<label>New profile name<input bind:value={name} maxlength="60" placeholder="Profile name"></label>
<div class="actions"><button onclick={() => void create(false)}><Icon icon="plus" />New blank profile</button><button onclick={() => void create(true)}><Icon icon="copy" />Duplicate profile</button></div>
<p class="note">Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.</p>
@@ -59,9 +73,10 @@
.settings{color:var(--rs-text);font-family:var(--rs-font-ui)}h2{margin:0;font-size:var(--rs-settings-heading-size);font-weight:500;color:var(--rs-text-strong)}h3{margin:var(--rs-settings-section-gap) 0 var(--rs-settings-gap);font-size:14px;font-weight:500}
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.6}.card{padding:0 var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.row{display:flex;justify-content:space-between;align-items:center;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}.row+.row{border-top:1px solid var(--rs-border)}
input,select,textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px}
button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
.rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
input,textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px}
button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
.picker{justify-content:space-between;min-width:140px;max-width:100%;overflow-wrap:anywhere;text-align:left}
.rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label,.profile-choice{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
.actions{display:flex;flex-wrap:wrap;gap:8px}.note{margin-bottom:0}
fieldset{border:0;margin:0;padding:0;min-width:0}small{display:block;color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5;margin-top:5px}
.row>span{flex:1}.address,.list-row textarea{width:260px;max-width:48%;box-sizing:border-box}.list-row{align-items:flex-start}textarea{resize:vertical}
+1 -1
View File
@@ -17,7 +17,7 @@ export class AutoScroll {
const elapsed = this.previous ? Math.min(50, time - this.previous) : 0;
this.previous = time;
if (!this.anchor) return null;
const speed = (distance: number) => Math.sign(distance) * Math.min(1800, Math.max(0, Math.abs(distance) - 12) * 8);
const speed = (distance: number) => Math.sign(distance) * Math.min(3000, Math.max(0, Math.abs(distance) - 12) * 18);
return { x: speed(this.point.x - this.anchor.x) * elapsed / 1000, y: speed(this.point.y - this.anchor.y) * elapsed / 1000 };
}
}
+9 -4
View File
@@ -13,7 +13,10 @@ export type Snapshot = {
};
export const state = writable<Snapshot | null>(null);
export const pageErrors = writable<Record<string, string>>({});
export const frames = new Map<string, (frame: { png: string; width: number; height: number }) => void>();
export type BrowserFrame = { tabId: string; frameId: number; mime: 'image/png' | 'image/jpeg'; data: string; width: number; height: number };
export type PageMenu = { event: string; tabId: string; token: string; x: number; y: number; linkURL: string; srcURL: string; hasImageContents: boolean; isEditable: boolean; selectionText: string; editFlags: Record<string, boolean>; url?: string };
export const frames = new Map<string, (frame: BrowserFrame) => void>();
export const pageEvents = new Map<string, (event: PageMenu) => void>();
let snapshots = new SnapshotOrder();
let session: string | undefined;
function isSnapshot(value: unknown): value is Snapshot {
@@ -29,15 +32,17 @@ export async function request<T = Snapshot>(command: string, args: Record<string
export async function connect(signal: AbortSignal) {
session = await invoke<string>('browser_connect');
const window = getCurrentWebviewWindow();
const offState = await window.listen<{ event: string; state?: Snapshot; message?: string; tabId?: string }>('browser-state', ({ payload }) => {
const offState = await window.listen<PageMenu & { state?: Snapshot; message?: string }>('browser-state', ({ payload }) => {
if (signal.aborted) return;
if (isSnapshot(payload.state) && snapshots.accept(payload.state)) state.set(payload.state);
if (payload.message && payload.tabId) pageErrors.update(errors => ({ ...errors, [payload.tabId!]: payload.message! }));
if (payload.tabId) pageEvents.get(payload.tabId)?.(payload);
});
const offFrame = await window.listen<{ tabId: string; png: string; width: number; height: number }>('browser-frame', ({ payload }) => {
const offFrame = await window.listen<BrowserFrame>('browser-frame', ({ payload }) => {
if (!signal.aborted) frames.get(payload.tabId)?.(payload);
if (!frames.has(payload.tabId)) void request('frameAck', { tabId: payload.tabId, frameId: payload.frameId }).catch(() => {});
});
const stop = async () => { offState(); offFrame(); frames.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
const stop = async () => { offState(); offFrame(); frames.clear(); pageEvents.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
if (signal.aborted) await stop();
return stop;
}
+1 -1
View File
@@ -84,7 +84,7 @@ export async function activate(api: PluginApi) {
if (value.profileId) saved.profileId = value.profileId;
if (value.url) saved.url = value.url;
},
newTab: (profile: string) => open(profile),
newTab: (profile: string, url?: string) => open(profile, url),
} });
tabId = undefined;
saved.control = instance;
+32
View File
@@ -0,0 +1,32 @@
type Wheel = { type: 'mouseWheel'; x: number; y: number; deltaX: number; deltaY: number; modifiers?: unknown[] };
/** Keep one pending wheel event while the transport processes the current event. */
export class WheelQueue {
private pending?: Wheel;
private running = false;
private closed = false;
private send: (input: Wheel) => Promise<unknown>;
constructor(send: (input: Wheel) => Promise<unknown>) { this.send = send; }
push(input: Wheel) {
if (this.closed) return;
const previous = this.pending;
// A direction change replaces stale motion instead of replaying it later.
const add = (old: number, next: number) => Math.sign(old) === Math.sign(next) || !next ? old + next : next;
this.pending = { ...input,
deltaX: Math.max(-2000, Math.min(2000, previous ? add(previous.deltaX, input.deltaX) : input.deltaX)),
deltaY: Math.max(-2000, Math.min(2000, previous ? add(previous.deltaY, input.deltaY) : input.deltaY)) };
void this.flush();
}
clear() { this.pending = undefined; }
close() { this.closed = true; this.clear(); }
private async flush() {
if (this.running) return;
this.running = true;
try {
while (this.pending && !this.closed) {
const input = this.pending; this.pending = undefined;
await this.send(input);
}
} finally { this.running = false; }
}
}