Update editor, workspace, Git services, appearance, and project guides
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import IconButton from '$lib/ui/IconButton.svelte';
|
||||
import { state as browserState, request } from './client';
|
||||
let { open }: { open: (profileId: string, url: string) => Promise<void> } = $props();
|
||||
let error = $state('');
|
||||
onMount(() => { void request('state').catch(reason => error = String(reason)); });
|
||||
</script>
|
||||
<div class="bookmarks">
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
{#each $browserState?.bookmarks || [] as item (item.id)}
|
||||
<div class="row"><button class="link" title={item.url} onclick={() => void open(item.profileId, item.url)}><Icon icon="globe" /><span>{item.title}</span></button><IconButton icon="close" label={`Remove ${item.title}`} onclick={() => void request('removeBookmark', { id: item.id })} /></div>
|
||||
{/each}
|
||||
</div>
|
||||
<style>
|
||||
.bookmarks{color:var(--rs-text);font-family:var(--rs-font-ui)}.row{display:flex;align-items:center;padding:0 5px;border-radius:var(--rs-control-radius)}.row:hover{background:var(--rs-bg-active)}
|
||||
.link{display:flex;align-items:center;gap:8px;flex:1;min-width:0;padding:7px 5px;border:0;border-radius:var(--rs-control-radius);color:inherit;background:transparent;text-align:left;cursor:pointer}
|
||||
span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.link:focus-visible{outline:2px solid var(--rs-accent)}p{color:var(--rs-error);padding:8px;font-size:12px}
|
||||
</style>
|
||||
@@ -0,0 +1,204 @@
|
||||
<script lang="ts">
|
||||
import { onMount, untrack, tick } from 'svelte';
|
||||
import IconButton from '$lib/ui/IconButton.svelte';
|
||||
import { state as browserState, pageErrors, request, frames } from './client';
|
||||
import { TabSession, type TabStatus } from './tabSession';
|
||||
import { AutoScroll } from './autoScroll';
|
||||
let { initial, onSessionChange, newTab }: { initial: { tabId?: string; profileId?: string; url?: string }; onSessionChange: (value: TabStatus) => void; newTab: (profileId: string) => Promise<void> } = $props();
|
||||
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: 'Opening browser…' });
|
||||
const connection = new TabSession(request, untrack(() => initial), value => { status = value; onSessionChange(value); });
|
||||
const tabId = $derived(status.tabId);
|
||||
const ready = $derived(status.phase === 'ready');
|
||||
const current = $derived($browserState?.tabs.find(tab => tab.id === tabId));
|
||||
let address = $state(''); let editing = $state(false);
|
||||
let image = $state(''); let surface: HTMLDivElement; let addressField: HTMLInputElement;
|
||||
let width = 1000, height = 700;
|
||||
let opening = $state(false), openingError = $state(''), mounted = $state(false);
|
||||
let findOpen = $state(false), findText = $state('');
|
||||
let findField: HTMLInputElement | undefined = $state();
|
||||
let findTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
const autoScroll = new AutoScroll();
|
||||
let scrollAnchor = $state<{ x: number; y: number } | null>(null);
|
||||
let scrollFrame = 0, moveFrame = 0, wheelPending = false, movePending = false;
|
||||
let pendingMove: Record<string, unknown> | undefined;
|
||||
let suppressedRelease = -1;
|
||||
const result = $derived(current?.find?.text === findText ? current.find : null);
|
||||
const documentKey = $derived(`${tabId}:${current?.url}:${!!current?.loading}`);
|
||||
$effect(() => {
|
||||
void documentKey;
|
||||
untrack(stopScroll);
|
||||
if (ready && findOpen) untrack(() => { if (findText && !current?.loading) search(); });
|
||||
});
|
||||
export async function find() {
|
||||
findOpen = true;
|
||||
await tick(); findField?.focus(); findField?.select();
|
||||
}
|
||||
export function detach() { connection.detach(); }
|
||||
export function action(command: string, args: Record<string, unknown> = {}) { return send(command, args); }
|
||||
function search(next = false, forward = true) {
|
||||
clearTimeout(findTimer);
|
||||
void send('find', { text: findText, next, forward });
|
||||
}
|
||||
function closeFind() { clearTimeout(findTimer); findOpen = false; void send('stopFind'); surface.focus(); }
|
||||
function findKey(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeFind(); }
|
||||
else if (event.key === 'Enter' && event.target === findField) { event.preventDefault(); event.stopPropagation(); search(true, !event.shiftKey); }
|
||||
}
|
||||
$effect(() => { if (!editing && current?.url) address = current.url === 'about:blank' ? '' : current.url; });
|
||||
$effect(() => {
|
||||
const id = tabId;
|
||||
image = '';
|
||||
if (!id) return;
|
||||
frames.set(id, frame => {
|
||||
if (frame.width > 0 && frame.height > 0 && frame.png.startsWith('iVBORw0KGgo')) image = `data:image/png;base64,${frame.png}`;
|
||||
});
|
||||
return () => { frames.delete(id); };
|
||||
});
|
||||
$effect(() => { if (mounted && ready && tabId) untrack(syncSize); });
|
||||
async function send(command: string, args = {}) {
|
||||
if (command === 'navigate') pageErrors.update(errors => { const next = { ...errors }; delete next[tabId]; return next; });
|
||||
await connection.send(command, args);
|
||||
}
|
||||
async function openTab(profileId = current?.profileId || $browserState?.profiles[0]?.id || 'user') {
|
||||
if (opening) return;
|
||||
opening = true;
|
||||
try { openingError = ''; await newTab(profileId); } catch (error) { openingError = `Could not open a browser tab: ${String(error)}`; }
|
||||
finally { opening = false; }
|
||||
}
|
||||
onMount(() => {
|
||||
mounted = true;
|
||||
const offState = browserState.subscribe(value => { if (value) connection.observe(value); });
|
||||
void connection.connect();
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const resize = new ResizeObserver(entries => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(syncSize, 100);
|
||||
});
|
||||
resize.observe(surface);
|
||||
return () => { mounted = false; stopScroll(); cancelAnimationFrame(moveFrame); clearTimeout(timer); clearTimeout(findTimer); resize.disconnect(); offState(); void connection.close(); };
|
||||
});
|
||||
function syncSize() {
|
||||
const rect = surface.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) { stopScroll(); void send('visible', { visible: false }); return; }
|
||||
width = Math.max(100, Math.min(2560, Math.round(rect.width)));
|
||||
height = Math.max(100, Math.min(1600, Math.round(rect.height)));
|
||||
void send('resize', { width, height }); void send('visible', { visible: true });
|
||||
}
|
||||
const modifiers = (event: MouseEvent | KeyboardEvent) => [event.shiftKey && 'shift', event.ctrlKey && 'control', event.altKey && 'alt', event.metaKey && 'meta'].filter(Boolean);
|
||||
function stopScroll() { autoScroll.stop(); scrollAnchor = null; cancelAnimationFrame(scrollFrame); }
|
||||
function scrollStep(time: number) {
|
||||
if (!autoScroll.anchor || !ready) { stopScroll(); return; }
|
||||
const delta = autoScroll.delta(time);
|
||||
if (delta && !wheelPending && (delta.x || delta.y)) {
|
||||
wheelPending = true;
|
||||
const rect = surface.getBoundingClientRect();
|
||||
if (!rect.width || !rect.height) { wheelPending = false; stopScroll(); return; }
|
||||
const anchor = autoScroll.anchor;
|
||||
void send('input', { input: { type: 'mouseWheel', x: Math.min(width - 1, Math.round(anchor.x * width / rect.width)), y: Math.min(height - 1, Math.round(anchor.y * height / rect.height)), deltaX: -delta.x, deltaY: -delta.y } }).finally(() => wheelPending = false);
|
||||
}
|
||||
scrollFrame = requestAnimationFrame(scrollStep);
|
||||
}
|
||||
function flushMove() {
|
||||
moveFrame = 0;
|
||||
if (!pendingMove || movePending) return;
|
||||
const input = pendingMove; pendingMove = undefined; movePending = true;
|
||||
void send('input', { input }).finally(() => {
|
||||
movePending = false;
|
||||
if (mounted && pendingMove) moveFrame = requestAnimationFrame(flushMove);
|
||||
});
|
||||
}
|
||||
function pointer(event: MouseEvent | WheelEvent, type: string) {
|
||||
event.preventDefault(); event.stopPropagation(); if (type === 'mouseDown') surface.focus();
|
||||
const rect = surface.getBoundingClientRect();
|
||||
const point = { x: event.clientX - rect.left, y: event.clientY - rect.top };
|
||||
if (type === 'mouseUp' && event.button === suppressedRelease) { suppressedRelease = -1; return; }
|
||||
if (type === 'mouseDown' && autoScroll.anchor) { suppressedRelease = event.button; stopScroll(); return; }
|
||||
if (type === 'mouseDown' && event.button === 1 && ready) {
|
||||
pendingMove = undefined; cancelAnimationFrame(moveFrame); moveFrame = 0;
|
||||
autoScroll.start(point); scrollAnchor = point; scrollFrame = requestAnimationFrame(scrollStep); return;
|
||||
}
|
||||
if (autoScroll.anchor) {
|
||||
if (type === 'mouseMove') autoScroll.move(point);
|
||||
if (type === 'mouseUp' && event.button === 1) { autoScroll.release(); if (!autoScroll.anchor) stopScroll(); }
|
||||
if (type === 'mouseWheel') stopScroll(); else return;
|
||||
}
|
||||
const input = { type, x: Math.max(0, Math.min(width - 1, Math.round(point.x * width / rect.width))), y: Math.max(0, Math.min(height - 1, Math.round(point.y * height / rect.height))),
|
||||
button: ['left', 'middle', 'right'][event.button] || 'left', clickCount: event.detail, modifiers: modifiers(event),
|
||||
...('deltaY' in event ? { deltaY: -event.deltaY, deltaX: -event.deltaX } : {}) };
|
||||
if (type === 'mouseMove') {
|
||||
pendingMove = input;
|
||||
if (!moveFrame && !movePending) moveFrame = requestAnimationFrame(flushMove);
|
||||
} else { pendingMove = undefined; void send('input', { input }); }
|
||||
}
|
||||
function key(event: KeyboardEvent, type: string) {
|
||||
if (autoScroll.anchor) { stopScroll(); if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); return; } }
|
||||
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && event.key.toLowerCase() === 'f') { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') void find(); return; }
|
||||
if (event.key === 'Escape' && findOpen) { event.preventDefault(); event.stopPropagation(); if (type === 'keyDown') closeFind(); return; }
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'l') { event.preventDefault(); addressField.focus(); addressField.select(); return; }
|
||||
if ((event.ctrlKey || event.metaKey) && [',', 'w', 't'].includes(event.key.toLowerCase())) return;
|
||||
event.preventDefault(); event.stopPropagation();
|
||||
const names: Record<string, string> = { ArrowLeft: 'LEFT', ArrowRight: 'RIGHT', ArrowUp: 'UP', ArrowDown: 'DOWN', Enter: 'ENTER', Backspace: 'BACKSPACE', Escape: 'ESCAPE', Delete: 'DELETE', Tab: 'TAB', Home: 'HOME', End: 'END', PageUp: 'PAGEUP', PageDown: 'PAGEDOWN', ' ': 'SPACE' };
|
||||
void send('input', { input: { type, keyCode: names[event.key] || event.key, modifiers: modifiers(event) } });
|
||||
if (type === 'keyDown' && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) void send('input', { input: { type: 'char', keyCode: event.key } });
|
||||
}
|
||||
</script>
|
||||
<svelte:window onblur={stopScroll} />
|
||||
<svelte:document onvisibilitychange={() => { if (document.hidden) stopScroll(); }} />
|
||||
<div class="browser" data-browser-tab={tabId} data-browser-state={status.phase}>
|
||||
<form class="toolbar" onsubmit={event => { event.preventDefault(); editing = false; void send('navigate', { input: address }); surface.focus(); }}>
|
||||
<IconButton icon="arrow-left" label="Back" disabled={!ready || !current?.canBack} onclick={() => void send('back')} />
|
||||
<IconButton icon="arrow-right" label="Forward" disabled={!ready || !current?.canForward} onclick={() => void send('forward')} />
|
||||
<IconButton icon={current?.loading ? 'stop' : 'refresh'} label={current?.loading ? 'Stop loading' : 'Reload'} disabled={!ready} onclick={() => void send(current?.loading ? 'stop' : 'reload')} />
|
||||
<input bind:this={addressField} bind:value={address} disabled={!ready} onfocus={() => editing = true} onblur={() => editing = false} aria-label="Address or search" placeholder="Search or enter an address" spellcheck="false" autocomplete="off">
|
||||
<IconButton icon="bookmark" label="Bookmark this page" disabled={!ready || !current?.url.startsWith('http')} onclick={() => void send('bookmark')} />
|
||||
<select aria-label="Browser profile" value={current?.profileId} disabled={opening} onchange={event => void openTab(event.currentTarget.value)}>
|
||||
{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}
|
||||
</select>
|
||||
</form>
|
||||
{#if findOpen}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Find controls share the Escape shortcut.) -->
|
||||
<form class="findbar" role="search" aria-label="Find in page" onkeydown={findKey} onsubmit={event => { event.preventDefault(); search(true); }}>
|
||||
<input bind:this={findField} bind:value={findText} aria-label="Find in page" placeholder="Find in page" maxlength="1000" autocomplete="off" spellcheck="false"
|
||||
disabled={!ready} oninput={() => { clearTimeout(findTimer); findTimer = setTimeout(() => search(), 120); }}>
|
||||
<span class="find-count" role="status" aria-live="polite">{!findText ? '' : !result || result.pending ? 'Searching…' : result.matches ? `${result.activeMatch} of ${result.matches}` : 'No matches'}</span>
|
||||
<IconButton icon="up" label="Previous match (Shift+Enter)" disabled={!ready || !findText} onclick={() => search(true, false)} />
|
||||
<IconButton icon="down" label="Next match (Enter)" disabled={!ready || !findText} onclick={() => search(true)} />
|
||||
<IconButton icon="close" label="Close find (Escape)" onclick={closeFind} />
|
||||
</form>
|
||||
{/if}
|
||||
{#if status.phase === 'connecting'}<p class="status" role="status">{status.message}</p>{/if}
|
||||
{#if ready && status.message}<p class="error" role="alert">{status.message}</p>{/if}
|
||||
{#if status.phase === 'disconnected'}
|
||||
<div class="error" role="alert"><p>{status.message}</p><button class="reconnect" onclick={() => void connection.connect()}>Reconnect</button></div>
|
||||
{/if}
|
||||
{#if status.detail}
|
||||
<details class="diagnostics"><summary>Browser error details</summary><dl>
|
||||
<dt>Operation</dt><dd>{status.detail.operation}</dd><dt>Reason</dt><dd>{status.detail.reason}</dd>
|
||||
<dt>Tab</dt><dd>{status.detail.tabId || 'Not created'}</dd><dt>Time</dt><dd>{status.detail.time}</dd>
|
||||
<dt>Browser</dt><dd>Included with RuneStone</dd>
|
||||
</dl></details>
|
||||
{/if}
|
||||
{#if openingError || $pageErrors[tabId]}<p class="error" role="alert">{openingError || $pageErrors[tabId]}</p>{/if}
|
||||
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (This surface forwards native browser input.) -->
|
||||
<div class="surface" class:autoscroll={!!scrollAnchor} bind:this={surface} role="application" aria-label="Web page" tabindex="0"
|
||||
onmousedown={event => pointer(event, 'mouseDown')} onmouseup={event => pointer(event, 'mouseUp')}
|
||||
onmousemove={event => pointer(event, 'mouseMove')} onwheel={event => pointer(event, 'mouseWheel')}
|
||||
onkeydown={event => key(event, 'keyDown')} onkeyup={event => key(event, 'keyUp')} onblur={stopScroll} onmouseleave={stopScroll} onauxclick={event => event.preventDefault()} oncontextmenu={event => event.preventDefault()}>
|
||||
{#if image && ready}<img src={image} alt="Web page rendered by the browser" draggable="false">{/if}
|
||||
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
|
||||
</div>
|
||||
</div>
|
||||
<style>
|
||||
.browser{display:flex;flex-direction:column;width:100%;height:100%;min-height:200px;background:var(--rs-bg);color:var(--rs-text);font-family:var(--rs-font-ui)}
|
||||
.toolbar,.findbar{display:flex;align-items:center;gap:4px;padding:5px 8px;border-bottom:1px solid var(--rs-border);background:var(--rs-bg-elevated)}
|
||||
.toolbar{flex-wrap:wrap}.toolbar input{flex:1 1 120px}.findbar input{max-width:320px}.find-count{font-size:12px;white-space:nowrap;color:var(--rs-text-dim);min-width:66px}
|
||||
input,select{min-width:0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;padding:5px 8px}
|
||||
input{flex:1}select{max-width:160px}input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent)}
|
||||
.surface{position:relative;flex:1;min-height:0;overflow:hidden;outline:none;background:var(--rs-bg)}.surface:focus-visible{box-shadow:inset 0 0 0 1px var(--rs-accent)}
|
||||
.surface.autoscroll{cursor:all-scroll}.scroll-anchor{position:absolute;transform:translate(-50%,-50%);display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--rs-text);border-radius:50%;background:var(--rs-bg-elevated);color:var(--rs-text);font-size:20px;pointer-events:none;box-shadow:0 1px 4px #0006}
|
||||
img{display:block;width:100%;height:100%;pointer-events:none;user-select:none}.error{margin:0;padding:5px 10px;color:var(--rs-error);font-size:12px}
|
||||
.error p{margin:4px 0}.status,.diagnostics{margin:0;padding:8px 10px;font-size:12px;color:var(--rs-text-dim)}
|
||||
.reconnect{padding:6px 12px;margin:4px 0;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);cursor:pointer}
|
||||
.reconnect:focus-visible,summary:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}summary{cursor:pointer}
|
||||
dl{display:grid;grid-template-columns:auto 1fr;gap:4px 12px}dd{margin:0;overflow-wrap:anywhere;user-select:text}
|
||||
</style>
|
||||
@@ -0,0 +1,73 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import WebData from './WebData.svelte';
|
||||
import { state as browserState, request } from './client';
|
||||
let selected = $state('user'), name = $state(''), message = $state('');
|
||||
let search = $state('duckduckgo'), adblock = $state(true), internalLinks = $state(true), rules = $state('');
|
||||
let homepage = $state(''), filterLists = $state(''), ready = $state(false), busy = $state(false);
|
||||
onMount(() => { void request('state').then(value => {
|
||||
selected = value.profiles[0].id; search = value.settings.search; adblock = value.settings.adblock;
|
||||
internalLinks = value.settings.linkDestination === 'internal'; rules = value.settings.personalRules;
|
||||
homepage = value.settings.homepage || ''; filterLists = (value.settings.filterLists || []).join('\n'); ready = true;
|
||||
}).catch(error => message = String(error)); });
|
||||
async function act(command: string, args: Record<string, unknown>) {
|
||||
try { const next = await request(command, args); message = 'Changes saved.'; return next; } catch (error) { message = String(error); return null; }
|
||||
}
|
||||
async function create(duplicate: boolean) {
|
||||
if (!name.trim()) { message = 'Enter a profile name.'; return; }
|
||||
const result = await act(duplicate ? 'duplicateProfile' : 'createProfile', duplicate ? { profileId: selected, name } : { name });
|
||||
if (result) { selected = result.profiles.at(-1)!.id; name = ''; }
|
||||
}
|
||||
async function save() {
|
||||
busy = true; message = 'Saving browser settings…';
|
||||
try {
|
||||
await act('settings', { search, adblock, linkDestination: internalLinks ? 'internal' : 'external', personalRules: rules,
|
||||
homepage, filterLists: filterLists.split(/\r?\n/).map(value => value.trim()).filter(Boolean) });
|
||||
} finally { busy = false; }
|
||||
}
|
||||
</script>
|
||||
<div class="settings">
|
||||
<h2>Browser</h2><p>Choose how you browse within RuneStone.</p>
|
||||
<h3>General</h3>
|
||||
<form onsubmit={event => { event.preventDefault(); if (ready && !busy) void save(); }}>
|
||||
<fieldset disabled={!ready || busy}>
|
||||
<div class="card">
|
||||
<label class="row"><span>Open web links in RuneStone<small>Turn this off to use your system browser.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Open web links in RuneStone" bind:checked={internalLinks}></label>
|
||||
<label class="row"><span>Homepage<small>The page to open in each new browser tab. Leave blank for an empty page.</small></span><input class="address" type="url" aria-label="Homepage" placeholder="https://example.com" maxlength="8192" bind:value={homepage}></label>
|
||||
<label class="row"><span>Search engine</span><select bind:value={search}><option value="duckduckgo">DuckDuckGo</option><option value="google">Google</option><option value="bing">Bing</option></select></label>
|
||||
<label class="row"><span>Block ads and trackers<small>Apply the filter lists and personal rules to all browser tabs.</small></span><input class="switch" type="checkbox" role="switch" aria-label="Block ads and trackers" bind:checked={adblock}></label>
|
||||
<label class="row list-row"><span>Ad blocking lists<small>One HTTPS filter list URL per line, up to eight lists. New lists download when you save.</small></span><textarea aria-label="Ad blocking lists" rows="4" maxlength="66000" placeholder="https://easylist.to/easylist/easylist.txt" bind:value={filterLists}></textarea></label>
|
||||
</div>
|
||||
<label class="rules">Personal filter rules<small>Optional rules to add to the selected lists.</small><textarea rows="4" maxlength="100000" bind:value={rules}></textarea></label>
|
||||
<button type="submit"><Icon icon="save" />{busy ? 'Saving…' : 'Save browser settings'}</button>
|
||||
</fieldset>
|
||||
</form>
|
||||
<h3>Profiles</h3><p>New profiles start blank. Duplicate a profile to copy its stored browsing data and bookmarks.</p>
|
||||
<div class="card profiles">
|
||||
<label>Profile<select aria-label="Profile" bind:value={selected}>{#each $browserState?.profiles || [] as profile}<option value={profile.id}>{profile.name}</option>{/each}</select></label>
|
||||
<label>New profile name<input bind:value={name} maxlength="60" placeholder="Profile name"></label>
|
||||
<div class="actions"><button onclick={() => void create(false)}><Icon icon="plus" />New blank profile</button><button onclick={() => void create(true)}><Icon icon="copy" />Duplicate profile</button></div>
|
||||
<p class="note">Duplication briefly restarts browser tabs. The copies remain separate. Agent permissions are not copied.</p>
|
||||
</div>
|
||||
<h3>Web data</h3><p>Clear data for the selected profile. Its browser tabs will close. Bookmarks remain.</p>
|
||||
<div class="actions"><button onclick={() => void act('clearData', { profileId: selected, kind: 'cache' })}>Clear cache</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'cookies' })}>Clear cookies</button><button onclick={() => void act('clearData', { profileId: selected, kind: 'history' })}>Clear history</button></div>
|
||||
<p role="status">{message}</p>
|
||||
{#if ready}<WebData profileId={selected} />{/if}
|
||||
</div>
|
||||
<style>
|
||||
.settings{color:var(--rs-text);font-family:var(--rs-font-ui)}h2{margin:0;font-size:var(--rs-settings-heading-size);font-weight:500;color:var(--rs-text-strong)}h3{margin:var(--rs-settings-section-gap) 0 var(--rs-settings-gap);font-size:14px;font-weight:500}
|
||||
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.6}.card{padding:0 var(--rs-settings-row-padding);background:var(--rs-bg-elevated);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
|
||||
.row{display:flex;justify-content:space-between;align-items:center;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}.row+.row{border-top:1px solid var(--rs-border)}
|
||||
input,select,textarea,button{border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg);color:var(--rs-text);font:inherit;box-sizing:border-box;min-height:var(--rs-settings-control-height);padding:4px 8px}
|
||||
button{display:inline-flex;align-items:center;gap:7px;background:var(--rs-bg-elevated);cursor:pointer}button:hover{background:var(--rs-bg-active)}button:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
|
||||
.rules{display:flex;flex-direction:column;gap:7px;margin:16px 0}.profiles{padding-top:16px;padding-bottom:8px}.profiles label{display:flex;flex-direction:column;gap:7px;margin-bottom:14px}
|
||||
.actions{display:flex;flex-wrap:wrap;gap:8px}.note{margin-bottom:0}
|
||||
fieldset{border:0;margin:0;padding:0;min-width:0}small{display:block;color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5;margin-top:5px}
|
||||
.row>span{flex:1}.address,.list-row textarea{width:260px;max-width:48%;box-sizing:border-box}.list-row{align-items:flex-start}textarea{resize:vertical}
|
||||
.switch{appearance:none;position:relative;flex:none;width:44px;height:26px;border:0;border-radius:999px;background:var(--rs-text-dim);padding:0;cursor:pointer;transition:background .15s}
|
||||
.switch::before{content:'';position:absolute;top:3px;left:3px;width:20px;height:20px;border-radius:50%;background:var(--rs-bg);box-shadow:0 1px 3px #0004;transition:transform .15s}
|
||||
.switch:checked{background:var(--rs-accent)}.switch:checked::before{transform:translateX(18px)}:disabled{opacity:.6;cursor:wait}
|
||||
@media(prefers-reduced-motion:reduce){.switch,.switch::before{transition:none}}
|
||||
@media(max-width:600px){.row{flex-wrap:wrap}.address,.list-row textarea{width:100%;max-width:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script lang="ts">
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import { request } from './client';
|
||||
let { profileId }: { profileId: string } = $props();
|
||||
type Cookie = { id: string; name: string; domain: string; path: string };
|
||||
type Visit = { id: string; url: string; title: string; at: number };
|
||||
type Data = { profileId: string; cookies: Cookie[]; history: Visit[] };
|
||||
let data = $state<Data | null>(null), error = $state(''), busy = $state(false), query = $state('');
|
||||
let kind = $state<'cookies' | 'history'>('cookies');
|
||||
let generation = 0;
|
||||
const cookies = $derived((data?.cookies || []).filter(item => `${item.domain} ${item.name} ${item.path}`.toLowerCase().includes(query.toLowerCase())));
|
||||
const history = $derived((data?.history || []).filter(item => `${item.title} ${item.url}`.toLowerCase().includes(query.toLowerCase())));
|
||||
$effect(() => { const id = profileId; data = null; query = ''; void refresh(id); return () => { generation++; }; });
|
||||
async function refresh(id = profileId) {
|
||||
const ticket = ++generation; busy = true; error = '';
|
||||
try { const next = await request<Data>('webData', { profileId: id }); if (ticket === generation && id === profileId) data = next; }
|
||||
catch (reason) { if (ticket === generation) error = String(reason); }
|
||||
finally { if (ticket === generation) busy = false; }
|
||||
}
|
||||
async function remove(command: string, id: string) {
|
||||
const selected = profileId; const ticket = ++generation; busy = true; error = '';
|
||||
try { await request(command, { profileId: selected, id }); if (ticket === generation && selected === profileId) await refresh(selected); }
|
||||
catch (reason) { if (ticket === generation) error = String(reason); }
|
||||
finally { if (ticket === generation) busy = false; }
|
||||
}
|
||||
</script>
|
||||
<section aria-label="Individual web data">
|
||||
<div class="toolbar">
|
||||
<label>Show<select aria-label="Web data type" bind:value={kind}><option value="cookies">Cookies</option><option value="history">History</option></select></label>
|
||||
<label class="search">Filter<input type="search" aria-label="Filter web data" bind:value={query} placeholder="Search this profile"></label>
|
||||
<button disabled={busy} onclick={() => void refresh()}><Icon icon="refresh" />Refresh</button>
|
||||
</div>
|
||||
<p>Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.</p>
|
||||
{#if error}<p role="alert">{error}</p>{/if}
|
||||
{#if busy}<p role="status">Please wait…</p>{/if}
|
||||
<div class="entries" aria-busy={busy}>
|
||||
{#if kind === 'cookies'}
|
||||
{#each cookies as cookie (cookie.id)}<div class="entry"><div><strong>{cookie.name || '(unnamed cookie)'}</strong><small>{cookie.domain} · {cookie.path}</small></div><button disabled={busy} aria-label={`Remove cookie ${cookie.name} from ${cookie.domain} at ${cookie.path}`} onclick={() => void remove('removeCookie', cookie.id)}><Icon icon="trash" />Remove</button></div>{/each}
|
||||
{#if data && !cookies.length}<p>No matching cookies.</p>{/if}
|
||||
{:else}
|
||||
{#each history as visit (visit.id)}<div class="entry"><div><strong>{visit.title || visit.url}</strong><small>{visit.url}</small><small>{new Date(visit.at).toLocaleString()}</small></div><button disabled={busy} aria-label={`Remove history entry ${visit.title || visit.url}`} onclick={() => void remove('removeHistory', visit.id)}><Icon icon="trash" />Remove</button></div>{/each}
|
||||
{#if data && !history.length}<p>No matching history.</p>{/if}
|
||||
{/if}
|
||||
</div>
|
||||
</section>
|
||||
<style>
|
||||
section{margin-top:var(--rs-settings-section-gap)}.toolbar{display:flex;align-items:end;gap:var(--rs-settings-gap);flex-wrap:wrap}
|
||||
label{display:flex;flex-direction:column;gap:4px}.search{flex:1;min-width:150px}input,select,button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);font:inherit;padding:4px 8px}
|
||||
button{display:inline-flex;align-items:center;justify-content:center;gap:6px;flex:none;cursor:pointer}button:hover{background:var(--rs-bg-active)}button:disabled{opacity:.6;cursor:wait}
|
||||
button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--rs-accent);outline-offset:1px}
|
||||
p,small{font-size:var(--rs-settings-description-size);color:var(--rs-text-dim);line-height:1.5}.entries{max-height:320px;overflow:auto;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);padding:0 var(--rs-settings-row-padding)}
|
||||
.entry{display:flex;gap:var(--rs-settings-gap);align-items:center;padding:var(--rs-settings-row-padding) 0}.entry+.entry{border-top:1px solid var(--rs-border)}.entry>div{flex:1;min-width:0;overflow-wrap:anywhere}small{display:block}strong{font-weight:500}[role=alert]{color:var(--rs-error)}
|
||||
@media(max-width:450px){.entry{flex-wrap:wrap}.entry>div{flex-basis:100%}}
|
||||
</style>
|
||||
@@ -0,0 +1,23 @@
|
||||
export type ScrollPoint = { x: number; y: number };
|
||||
|
||||
/** Middle-button scrolling uses wheel input because offscreen Chromium has no native scroll cursor. */
|
||||
export class AutoScroll {
|
||||
anchor: ScrollPoint | null = null;
|
||||
private point: ScrollPoint = { x: 0, y: 0 };
|
||||
private moved = false;
|
||||
private previous = 0;
|
||||
start(point: ScrollPoint) { this.anchor = { ...point }; this.point = { ...point }; this.moved = false; this.previous = 0; }
|
||||
move(point: ScrollPoint) {
|
||||
this.point = point;
|
||||
if (this.anchor && Math.hypot(point.x - this.anchor.x, point.y - this.anchor.y) > 12) this.moved = true;
|
||||
}
|
||||
release() { if (this.moved) this.stop(); }
|
||||
stop() { this.anchor = null; this.previous = 0; }
|
||||
delta(time: number) {
|
||||
const elapsed = this.previous ? Math.min(50, time - this.previous) : 0;
|
||||
this.previous = time;
|
||||
if (!this.anchor) return null;
|
||||
const speed = (distance: number) => Math.sign(distance) * Math.min(1800, Math.max(0, Math.abs(distance) - 12) * 8);
|
||||
return { x: speed(this.point.x - this.anchor.x) * elapsed / 1000, y: speed(this.point.y - this.anchor.y) * elapsed / 1000 };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import { writable } from 'svelte/store';
|
||||
import { SnapshotOrder } from './snapshotOrder';
|
||||
|
||||
export type Profile = { id: string; name: string };
|
||||
export type Tab = { id: string; transferToken?: string; profileId: string; title: string; favicon?: string | null; url: string; loading: boolean; blocked: number; canBack: boolean; canForward: boolean; find?: { text: string; matches: number; activeMatch: number; pending: boolean } | null };
|
||||
export type Snapshot = {
|
||||
runtimeId?: string; revision?: number;
|
||||
profiles: Profile[]; tabs: Tab[];
|
||||
bookmarks: { id: string; profileId: string; title: string; url: string }[];
|
||||
settings: { search: string; adblock: boolean; linkDestination: string; personalRules: string; homepage: string; filterLists: string[] };
|
||||
};
|
||||
export const state = writable<Snapshot | null>(null);
|
||||
export const pageErrors = writable<Record<string, string>>({});
|
||||
export const frames = new Map<string, (frame: { png: string; width: number; height: number }) => void>();
|
||||
let snapshots = new SnapshotOrder();
|
||||
let session: string | undefined;
|
||||
function isSnapshot(value: unknown): value is Snapshot {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const record = value as Record<string, unknown>;
|
||||
return Array.isArray(record.profiles) && Array.isArray(record.tabs) && Array.isArray(record.bookmarks) && !!record.settings && typeof record.settings === 'object';
|
||||
}
|
||||
export async function request<T = Snapshot>(command: string, args: Record<string, unknown> = {}): Promise<T> {
|
||||
const result = await invoke<T>('browser_request', { command, args, session });
|
||||
if (isSnapshot(result) && snapshots.accept(result)) state.set(result);
|
||||
return result;
|
||||
}
|
||||
export async function connect(signal: AbortSignal) {
|
||||
session = await invoke<string>('browser_connect');
|
||||
const window = getCurrentWebviewWindow();
|
||||
const offState = await window.listen<{ event: string; state?: Snapshot; message?: string; tabId?: string }>('browser-state', ({ payload }) => {
|
||||
if (signal.aborted) return;
|
||||
if (isSnapshot(payload.state) && snapshots.accept(payload.state)) state.set(payload.state);
|
||||
if (payload.message && payload.tabId) pageErrors.update(errors => ({ ...errors, [payload.tabId!]: payload.message! }));
|
||||
});
|
||||
const offFrame = await window.listen<{ tabId: string; png: string; width: number; height: number }>('browser-frame', ({ payload }) => {
|
||||
if (!signal.aborted) frames.get(payload.tabId)?.(payload);
|
||||
});
|
||||
const stop = async () => { offState(); offFrame(); frames.clear(); state.set(null); session = undefined; snapshots = new SnapshotOrder(); pageErrors.set({}); await invoke('browser_stop'); };
|
||||
if (signal.aborted) await stop();
|
||||
return stop;
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { mount, unmount } from 'svelte';
|
||||
import { get } from 'svelte/store';
|
||||
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import type { PluginApi, PluginViewOpenOptions } from '$lib/plugins/sdk';
|
||||
import Browser from './Browser.svelte';
|
||||
import Settings from './Settings.svelte';
|
||||
import Bookmarks from './Bookmarks.svelte';
|
||||
import { connect, request, state } from './client';
|
||||
import type { TabStatus } from './tabSession';
|
||||
|
||||
type BrowserControl = { find(): Promise<void>; detach(): void; action(command: string, args?: Record<string, unknown>): Promise<void> };
|
||||
type SavedView = { view: string; profileId?: string; url?: string; runtimeId: string; status?: TabStatus; control?: BrowserControl };
|
||||
|
||||
export async function activate(api: PluginApi) {
|
||||
const dispose = await connect(api.signal); api.onDispose(dispose);
|
||||
const owners = new Map<string, SavedView>();
|
||||
const offMove = await getCurrentWebviewWindow().listen<{ tabId: string }>('browser-tab-moved', ({ payload }) => {
|
||||
const saved = owners.get(payload.tabId);
|
||||
if (!saved) return;
|
||||
saved.control?.detach();
|
||||
api.closeView?.(saved.view);
|
||||
});
|
||||
api.onDispose(offMove);
|
||||
const off = state.subscribe(value => {
|
||||
for (const tab of value?.tabs || []) {
|
||||
const saved = owners.get(tab.id);
|
||||
if (saved) {
|
||||
saved.profileId = tab.profileId; if (tab.url) saved.url = tab.url;
|
||||
api.updateViewTitle?.(saved.view, `${tab.title || 'Browser'} · ${value!.profiles.find(p => p.id === tab.profileId)?.name || 'User'}`.slice(0, 200));
|
||||
api.updateViewIcon?.(saved.view, tab.favicon ?? null);
|
||||
}
|
||||
}
|
||||
});
|
||||
api.onDispose(off);
|
||||
const mounts = new Set<() => Promise<void>>();
|
||||
function retain(instance: ReturnType<typeof mount>) {
|
||||
let result: Promise<void> | undefined;
|
||||
const cleanup = () => result ??= unmount(instance).then(() => { mounts.delete(cleanup); });
|
||||
mounts.add(cleanup); return cleanup;
|
||||
}
|
||||
api.onDispose(async () => { await Promise.all([...mounts].map(cleanup => cleanup())); });
|
||||
async function open(profileId?: string, url?: string, options?: PluginViewOpenOptions, tabId?: string, pinned = false) {
|
||||
const id = `tab-${crypto.randomUUID()}`;
|
||||
const saved: SavedView = { view: id, profileId, url, runtimeId: '' };
|
||||
const run = (command: string, args?: Record<string, unknown>) => { void saved.control?.action(command, args); };
|
||||
const split = (direction: 'right' | 'down') => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
void open(current?.profileId || saved.profileId, current?.url || saved.url || 'about:blank', { split: direction, relativeTo: id });
|
||||
};
|
||||
api.registerView({ id, title: 'Browser', placement: 'editor', icon: 'globe', pinned, launcher: false,
|
||||
tabDragData: ({ pinned }) => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
if (saved.status?.phase !== 'ready' || !current?.transferToken) return undefined;
|
||||
return JSON.stringify({ tabId: current.id, transferToken: current.transferToken, pinned });
|
||||
},
|
||||
find: () => { api.openView(id); void saved.control?.find(); },
|
||||
tabActions: ({ pinned }) => {
|
||||
const current = get(state)?.tabs.find(tab => tab.id === saved.runtimeId);
|
||||
const ready = saved.status?.phase === 'ready';
|
||||
const web = ready && /^https?:\/\//.test(current?.url || '');
|
||||
return [
|
||||
{ separator: true },
|
||||
{ label: 'Move to new window', icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
|
||||
{ label: 'Split right', icon: 'split-right', disabled: !ready, run: () => split('right') },
|
||||
{ label: 'Split down', icon: 'split-down', disabled: !ready, run: () => split('down') },
|
||||
{ separator: true },
|
||||
{ label: 'Find…', icon: 'search', shortcut: 'Ctrl+F', disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
|
||||
{ label: 'Open in default browser', icon: 'external', disabled: !web, run: () => run('openExternal') },
|
||||
{ label: 'Bookmark', icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
|
||||
];
|
||||
}, mount: container => {
|
||||
let runtimeId = '';
|
||||
const instance = mount(Browser, { target: container, props: {
|
||||
initial: { tabId, profileId: saved.profileId, url: saved.url },
|
||||
onSessionChange: value => {
|
||||
saved.status = value;
|
||||
if (value.tabId !== runtimeId || value.phase === 'closed') {
|
||||
owners.delete(runtimeId);
|
||||
runtimeId = value.phase === 'closed' ? '' : value.tabId;
|
||||
if (runtimeId) owners.set(runtimeId, saved);
|
||||
}
|
||||
saved.runtimeId = runtimeId;
|
||||
api.updateViewIcon?.(saved.view, get(state)?.tabs.find(tab => tab.id === runtimeId)?.favicon ?? null);
|
||||
if (value.profileId) saved.profileId = value.profileId;
|
||||
if (value.url) saved.url = value.url;
|
||||
},
|
||||
newTab: (profile: string) => open(profile),
|
||||
} });
|
||||
tabId = undefined;
|
||||
saved.control = instance;
|
||||
const cleanup = retain(instance);
|
||||
return async () => { await cleanup(); if (saved.control === instance) saved.control = undefined; };
|
||||
} });
|
||||
api.openView(id, options);
|
||||
}
|
||||
api.registerCommand({ id: 'new-tab', title: 'New browser tab', category: 'open', run: () => open() });
|
||||
api.contribute('browser', {
|
||||
newTab: () => open(),
|
||||
mountSettings: container => retain(mount(Settings, { target: container })),
|
||||
mountBookmarks: container => retain(mount(Bookmarks, { target: container, props: { open } })),
|
||||
open: async url => {
|
||||
const value = await request('state');
|
||||
if (value.settings.linkDestination === 'external') return false;
|
||||
await open(undefined, url); return true;
|
||||
},
|
||||
});
|
||||
api.registerTabDrop?.(async data => {
|
||||
const payload = JSON.parse(data);
|
||||
if (!payload || typeof payload.tabId !== 'string' || typeof payload.transferToken !== 'string') throw new Error('Invalid browser tab transfer.');
|
||||
const existing = owners.get(payload.tabId);
|
||||
if (existing) { api.openView(existing.view); return; }
|
||||
const snapshot = await request('adoptTab', { tabId: payload.tabId, transferToken: payload.transferToken });
|
||||
const current = snapshot.tabs.find(tab => tab.id === payload.tabId);
|
||||
if (!current) throw new Error('The browser tab is unavailable.');
|
||||
await open(current.profileId, current.url, undefined, current.id, payload.pinned === true);
|
||||
});
|
||||
const incoming = new URLSearchParams(location.search).get('browserTab');
|
||||
if (incoming) {
|
||||
const snapshot = await request('adoptTab', { tabId: incoming });
|
||||
const current = snapshot.tabs.find(tab => tab.id === incoming);
|
||||
await open(current?.profileId, current?.url, undefined, incoming, new URLSearchParams(location.search).get('browserPinned') === 'true');
|
||||
const url = new URL(location.href);
|
||||
url.searchParams.delete('browserTab'); url.searchParams.delete('browserPinned');
|
||||
history.replaceState(null, '', url.pathname + url.search);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
export class SnapshotOrder {
|
||||
private runtimeId = '';
|
||||
private revision = -1;
|
||||
private retired = new Set<string>();
|
||||
|
||||
accept(value: { runtimeId?: string; revision?: number }): boolean {
|
||||
if (!value.runtimeId || !Number.isSafeInteger(value.revision)) return true;
|
||||
if (this.retired.has(value.runtimeId)) return false;
|
||||
if (value.runtimeId !== this.runtimeId) {
|
||||
if (this.runtimeId) this.retired.add(this.runtimeId);
|
||||
this.runtimeId = value.runtimeId;
|
||||
this.revision = -1;
|
||||
}
|
||||
if (value.revision! <= this.revision) return false;
|
||||
this.revision = value.revision!;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { Snapshot } from './client';
|
||||
|
||||
type Transport = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||
export type TabStatus = {
|
||||
tabId: string; profileId?: string; url?: string;
|
||||
phase: 'connecting' | 'ready' | 'disconnected' | 'closed';
|
||||
message: string;
|
||||
detail?: { operation: string; reason: string; tabId: string; time: string };
|
||||
};
|
||||
const connectionLost = (error: unknown) => /Unknown browser tab|stopped responding|timed out|response did not match|broken pipe|os error (109|232|10053|10054)\b/i.test(String(error));
|
||||
|
||||
export class TabSession {
|
||||
value: TabStatus;
|
||||
private transport: Transport;
|
||||
private changed: (value: TabStatus) => void;
|
||||
private pending?: Promise<void>;
|
||||
private closed = false;
|
||||
private recovered = false;
|
||||
constructor(transport: Transport, initial: { tabId?: string; profileId?: string; url?: string }, changed: (value: TabStatus) => void) {
|
||||
this.transport = transport; this.changed = changed;
|
||||
this.value = { ...initial, tabId: initial.tabId || '', phase: 'connecting', message: 'Opening browser…' };
|
||||
}
|
||||
private update(value: Partial<TabStatus>) {
|
||||
this.value = { ...this.value, ...value }; this.changed(this.value);
|
||||
}
|
||||
observe(snapshot: Snapshot) {
|
||||
const tab = snapshot.tabs.find(tab => tab.id === this.value.tabId);
|
||||
if (tab) {
|
||||
this.value.profileId = tab.profileId;
|
||||
// The first snapshot can arrive before navigation starts.
|
||||
if (tab.url) this.value.url = tab.url;
|
||||
}
|
||||
}
|
||||
private failure(operation: string, error: unknown, tabId = this.value.tabId, phase: 'ready' | 'disconnected' = 'disconnected') {
|
||||
this.update({ phase, message: phase === 'ready' ? 'The browser could not complete this request. Check the error details.' : connectionLost(error)
|
||||
? 'This tab lost its browser connection. Select Reconnect to restore the page.'
|
||||
: 'The browser could not complete this request. Check the details, then select Reconnect.',
|
||||
detail: { operation, reason: String(error), tabId, time: new Date().toISOString() } });
|
||||
}
|
||||
connect(): Promise<void> {
|
||||
if (this.closed) return Promise.resolve();
|
||||
if (this.pending) return this.pending;
|
||||
this.pending = this.restore().finally(() => { this.pending = undefined; });
|
||||
return this.pending;
|
||||
}
|
||||
private async restore() {
|
||||
this.update({ phase: 'connecting', message: this.value.tabId ? 'Reconnecting browser…' : 'Opening browser…' });
|
||||
let operation = 'state';
|
||||
// The host discards a failed transport before the next request.
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
operation = 'state';
|
||||
const snapshot = await this.transport('state') as Snapshot;
|
||||
if (this.closed) return;
|
||||
if (snapshot.tabs.some(tab => tab.id === this.value.tabId)) {
|
||||
this.observe(snapshot); this.update({ phase: 'ready', message: '' }); return;
|
||||
}
|
||||
const profileId = this.value.profileId || snapshot.profiles[0]?.id;
|
||||
operation = 'newTab';
|
||||
const result = await this.transport('newTab', { profileId, ...(this.value.url ? { url: this.value.url } : {}) }) as { tabId: string };
|
||||
if (this.closed) { await this.transport('closeTab', { tabId: result.tabId }).catch(() => {}); return; }
|
||||
this.update({ tabId: result.tabId, profileId });
|
||||
operation = 'state';
|
||||
const current = await this.transport('state') as Snapshot;
|
||||
if (this.closed) return;
|
||||
if (current.tabs.some(tab => tab.id === result.tabId)) {
|
||||
this.observe(current); this.update({ phase: 'ready', message: '' }); return;
|
||||
}
|
||||
if (attempt === 1) throw new Error('The runtime restarted twice while opening this tab.');
|
||||
} catch (error) {
|
||||
if (this.closed) return;
|
||||
if (attempt === 0 && connectionLost(error)) continue;
|
||||
this.failure(operation, error); return;
|
||||
}
|
||||
}
|
||||
}
|
||||
async send(command: string, args: Record<string, unknown> = {}) {
|
||||
if (this.closed || this.value.phase !== 'ready') return;
|
||||
const tabId = this.value.tabId;
|
||||
try {
|
||||
await this.transport(command, { ...args, tabId });
|
||||
if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' });
|
||||
} catch (error) {
|
||||
// Replies from the previous connection cannot replace the current error.
|
||||
if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return;
|
||||
const lost = connectionLost(error);
|
||||
this.failure(command, error, tabId, lost ? 'disconnected' : 'ready');
|
||||
if (lost && !this.recovered) {
|
||||
this.recovered = true;
|
||||
await this.connect();
|
||||
// Only an explicit address submission is safe to repeat.
|
||||
if (command === 'navigate' && this.value.phase === 'ready') await this.send(command, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
detach() { this.closed = true; this.update({ phase: 'closed' }); }
|
||||
async close() {
|
||||
if (this.closed) return;
|
||||
this.closed = true;
|
||||
const tabId = this.value.tabId;
|
||||
this.update({ phase: 'closed' });
|
||||
if (tabId) await this.transport('closeTab', { tabId }).catch(() => {});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user