Add interface languages and improve themes and workspace controls for 0.1.36

This commit is contained in:
Knotty Wyvern
2026-10-15 10:55:59 -07:00
parent b066359b66
commit 68e86ab6eb
98 changed files with 5499 additions and 874 deletions
+1
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import IconButton from '$lib/ui/IconButton.svelte';
+43 -42
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount, untrack, tick } from 'svelte';
import IconButton from '$lib/ui/IconButton.svelte';
import Icon from '$lib/ui/Icon.svelte';
@@ -9,7 +10,7 @@
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, url?: string) => Promise<void> } = $props();
let status = $state<TabStatus>({ tabId: '', phase: 'connecting', message: 'Opening browser…' });
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');
@@ -28,7 +29,7 @@
closeMenu?.();
const anchor = event.currentTarget as HTMLButtonElement;
const rect = anchor.getBoundingClientRect();
closeMenu = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: 'Browser profile',
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;
}
@@ -92,30 +93,30 @@
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 });
{ 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: '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 });
{ label: $t('Save image as…'), icon: 'save', disabled: !context.srcURL, run: action('saveImage') },
{ label: $t('Copy image'), icon: 'copy', run: action('copyImage') },
{ label: $t('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') });
{ label: $t('Undo'), icon: 'undo', shortcut: 'Ctrl+Z', disabled: !context.editFlags.canUndo, run: edit('undo') },
{ label: $t('Redo'), icon: 'redo', shortcut: 'Ctrl+Shift+Z', disabled: !context.editFlags.canRedo, run: edit('redo') }, { separator: true },
{ label: $t('Cut'), icon: 'cut', shortcut: 'Ctrl+X', disabled: !context.editFlags.canCut, run: edit('cut') });
if (context.isEditable || context.selectionText) items.push({ label: $t('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() });
{ label: $t('Paste'), icon: 'paste', shortcut: 'Ctrl+V', disabled: !context.editFlags.canPaste, run: edit('paste') },
{ label: $t('Paste as plain text'), icon: 'paste-text', shortcut: 'Ctrl+Shift+V', disabled: !context.editFlags.canPaste, run: edit('pasteAndMatchStyle') },
{ label: $t('Select all'), icon: 'task', shortcut: 'Ctrl+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: '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' });
items, label: $t('Browser page actions') });
closeMenu = menu.close;
}
$effect(() => { if (mounted && ready && tabId) untrack(syncSize); });
@@ -216,46 +217,46 @@
<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="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')} />
<button type="button" class="profile-choice" aria-label="Browser profile" aria-haspopup="menu" disabled={opening} onclick={chooseProfile}>
{$browserState?.profiles.find(profile => profile.id === current?.profileId)?.name ?? 'Profile'}<Icon icon="chevron-down" />
<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="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"
<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="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} />
<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">{status.message}</p>{/if}
{#if ready && status.message}<p class="error" role="alert">{status.message}</p>{/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>{status.message}</p><button class="reconnect" onclick={() => void connection.connect()}>Reconnect</button></div>
<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>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>
<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("Browser")}</dt><dd>{$t("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"
<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="Web page text input" autocomplete="off" spellcheck="false"
<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 = ''; } }}
+21 -20
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount, onDestroy } from 'svelte';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
@@ -14,7 +15,7 @@
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',
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),
@@ -26,15 +27,15 @@
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; }
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 = 'Enter a profile name.'; return; }
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 = ''; }
}
async function save() {
busy = true; message = 'Saving browser settings…';
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) });
@@ -42,30 +43,30 @@
}
</script>
<div class="settings">
<h2>Browser</h2><p>Choose how you browse within RuneStone.</p>
<h3>General</h3>
<h2>{$t("Browser")}</h2><p>{$t("Choose how you browse within RuneStone.")}</p>
<h3>{$t("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>
<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>
<label class="row"><span>{$t("Open web links in RuneStone")}<small>{$t("Turn this off to use your system browser.")}</small></span><input class="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="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 save.")}</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">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>
<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>
<button type="submit"><Icon icon="save" />{busy ? $t('Saving…') : $t('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>
<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>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>
<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="copy" />{$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>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>
<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}
</div>
+13 -12
View File
@@ -1,4 +1,5 @@
<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';
@@ -14,9 +15,9 @@
function chooseKind(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement, rect = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: rect.left, y: rect.bottom + 4, label: 'Web data type',
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' ? 'Cookies' : 'History',
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;
@@ -36,22 +37,22 @@
finally { if (ticket === generation) busy = false; }
}
</script>
<section aria-label="Individual web data">
<section aria-label={$t("Individual web data")}>
<div class="toolbar">
<div class="choice"><span>Show</span><button type="button" aria-label="Web data type" aria-haspopup="menu" onclick={chooseKind}>{kind === 'cookies' ? 'Cookies' : 'History'}<Icon icon="chevron-down" /></button></div>
<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 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>Remove individual entries for this profile. Open tabs stay open. Sites can create cookies again.</p>
<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">Please wait…</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 || '(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}
{#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={$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={`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}
{#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>
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte";
import type { Chrome, OpenBuffer } from "$lib/workspace/types";
import { isMarkdownPath, imageFiles, hasFileDrag, imageInsertion, workspaceImageLink } from "$lib/workspace/media";
@@ -275,7 +276,7 @@
<div
class="monaco-host"
role="application"
aria-label="Editor"
aria-label={$t("Editor")}
bind:this={host}
ondragover={(event) => {
if (isMarkdownPath(buffer.relPath) && onInsertImage && hasFileDrag(event.dataTransfer)) {
@@ -290,7 +291,7 @@
void takeImages(event, event.clipboardData);
}}
></div>
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>Dismiss</button></p>{/if}
{#if loadError}<p class="editor-notice" role="alert">{loadError}<button onclick={() => { loadError = null; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.monaco-host {
+14 -13
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte";
import { runScopeHandlers, type EditorView } from "@codemirror/view";
import { SearchQuery, closeSearchPanel, findNext, findPrevious, getSearchQuery, replaceAll, replaceNext, selectMatches, setSearchQuery } from "@codemirror/search";
@@ -44,34 +45,34 @@
</script>
<!-- svelte-ignore a11y_no_noninteractive_element_interactions (Handle shortcuts from the search controls.) -->
<section class="rs-find-bar" aria-label="Find and replace" onkeydown={keydown}>
<section class="rs-find-bar" aria-label={$t("Find and replace")} onkeydown={keydown}>
<div class="rs-find-row">
<div class="rs-find-field">
<Icon icon="search" />
<input type="text" name="search" {...{ "main-field": "true" }} aria-label="Find in document" placeholder="Find in document"
<input type="text" name="search" {...{ "main-field": "true" }} aria-label={$t("Find in document")} placeholder={$t("Find in document")}
aria-invalid={searchText !== "" && !query.valid} bind:value={() => searchText, value => { searchText = value; commit(); }} />
</div>
<div class="rs-find-actions">
<IconButton icon="up" label="Previous match (Shift+Enter)" onclick={() => findPrevious(view)} disabled={!query.valid} />
<IconButton icon="down" label="Next match (Enter)" onclick={() => findNext(view)} disabled={!query.valid} />
<button class="rs-find-button" type="button" onclick={() => selectMatches(view)} disabled={!query.valid}>Select all</button>
<IconButton icon="close" label="Close find (Escape)" onclick={() => closeSearchPanel(view)} />
<IconButton icon="up" label={$t("Previous match (Shift+Enter)")} onclick={() => findPrevious(view)} disabled={!query.valid} />
<IconButton icon="down" label={$t("Next match (Enter)")} onclick={() => findNext(view)} disabled={!query.valid} />
<button class="rs-find-button" type="button" onclick={() => selectMatches(view)} disabled={!query.valid}>{$t("Select all")}</button>
<IconButton icon="close" label={$t("Close find (Escape)")} onclick={() => closeSearchPanel(view)} />
</div>
</div>
<div class="rs-find-options">
<label><input type="checkbox" bind:checked={() => caseSensitive, value => { caseSensitive = value; commit(); }} />Match case</label>
<label><input type="checkbox" bind:checked={() => wholeWord, value => { wholeWord = value; commit(); }} />Whole word</label>
<label><input type="checkbox" bind:checked={() => regexp, value => { regexp = value; commit(); }} />Regex</label>
{#if searchText && !query.valid}<span class="rs-find-error" role="status">Invalid expression</span>{/if}
<label><input type="checkbox" bind:checked={() => caseSensitive, value => { caseSensitive = value; commit(); }} />{$t("Match case")}</label>
<label><input type="checkbox" bind:checked={() => wholeWord, value => { wholeWord = value; commit(); }} />{$t("Whole word")}</label>
<label><input type="checkbox" bind:checked={() => regexp, value => { regexp = value; commit(); }} />{$t("Regex")}</label>
{#if searchText && !query.valid}<span class="rs-find-error" role="status">{$t("Invalid expression")}</span>{/if}
</div>
{#if !view.state.readOnly}
<div class="rs-find-row">
<div class="rs-find-field">
<input type="text" name="replace" aria-label="Replace with" placeholder="Replace with" bind:value={() => replacement, value => { replacement = value; commit(); }} />
<input type="text" name="replace" aria-label={$t("Replace with")} placeholder={$t("Replace with")} bind:value={() => replacement, value => { replacement = value; commit(); }} />
</div>
<div class="rs-find-actions">
<button class="rs-find-button" type="button" onclick={() => replaceNext(view)} disabled={!query.valid}>Replace</button>
<button class="rs-find-button" type="button" onclick={() => replaceAll(view)} disabled={!query.valid}>Replace all</button>
<button class="rs-find-button" type="button" onclick={() => replaceNext(view)} disabled={!query.valid}>{$t("Replace")}</button>
<button class="rs-find-button" type="button" onclick={() => replaceAll(view)} disabled={!query.valid}>{$t("Replace all")}</button>
</div>
</div>
{/if}
+4 -3
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { pluginHost } from "$lib/plugins/registry";
import { isSpellingTarget } from "./spellingMenu";
import { untrack } from "svelte";
@@ -216,7 +217,7 @@
}),
imageDrops,
title.of(noteTitle(markdownTitle(current.relPath), onRenameTitle ? renameTitle : undefined)),
EditorView.contentAttributes.of({ role: "textbox", "aria-label": "Writing editor", "aria-multiline": "true", spellcheck: "true" }),
EditorView.contentAttributes.of({ role: "textbox", "aria-label": $t("Writing editor"), "aria-multiline": "true", spellcheck: "true" }),
EditorView.updateListener.of(update => {
if (update.docChanged || update.selectionSet) {
menu?.close(false);
@@ -395,7 +396,7 @@
});
</script>
<div class="live-writer" bind:this={host} role="application" aria-label="Markdown writing editor"
<div class="live-writer" bind:this={host} role="application" aria-label={$t("Markdown writing editor")}
ondragovercapture={(event) => {
if (!onInsertImage || !hasFileDrag(event.dataTransfer)) return;
event.preventDefault();
@@ -403,7 +404,7 @@
}}
ondropcapture={(event) => { if (editor) void insertImages(event, editor); }}
></div>
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>Dismiss</button></p>{/if}
{#if error}<p class="editor-notice" role="alert">{error}<button onclick={() => { error = ""; }}>{$t("Dismiss")}</button></p>{/if}
<style>
.live-writer { position: absolute; inset: 0; }
+2 -1
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte";
import type { OpenBuffer } from "$lib/workspace/types";
import { workspaceReadDataUrl } from "$lib/workspace/api";
@@ -228,7 +229,7 @@
<div
class="writer-host"
role="application"
aria-label="Writer"
aria-label={$t("Writer")}
bind:this={host}
ondragover={(event) => {
if (imageFiles(event.dataTransfer).length > 0) {
+10 -9
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { editor } from "monaco-editor";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
@@ -36,19 +37,19 @@ export function codeMenu(view: editor.IStandaloneCodeEditor, report: (message: s
};
const run = (id: string) => { close(); void view.getAction(id)?.run(); };
const items: ActionMenuItem[] = [
{ label: "Undo", icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } },
{ label: "Redo", icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } },
{ label: tr("Undo"), icon: "undo", shortcut: "Ctrl+Z", disabled: !model.canUndo(), run: () => { close(); view.trigger("code-menu", "undo", null); } },
{ label: tr("Redo"), icon: "redo", shortcut: "Ctrl+Shift+Z", disabled: !model.canRedo(), run: () => { close(); view.trigger("code-menu", "redo", null); } },
{ separator: true },
{ label: "Change all occurrences", icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") },
{ label: tr("Change all occurrences"), icon: "select", shortcut: "Ctrl+F2", disabled: !view.getAction("editor.action.changeAll")?.isSupported(), run: () => run("editor.action.changeAll") },
{ separator: true },
{ label: "Cut", icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
{ label: "Select all", icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } },
{ label: tr("Cut"), icon: "cut", shortcut: "Ctrl+X", disabled: !selected, run: () => void clipboard("cut") },
{ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", disabled: !selected, run: () => void clipboard("copy") },
{ label: tr("Paste"), icon: "paste", shortcut: "Ctrl+V", run: () => void clipboard("paste") },
{ label: tr("Select all"), icon: "select", shortcut: "Ctrl+A", run: () => { close(); view.setSelection(model.getFullModelRange()); } },
{ separator: true },
{ label: "Command palette", icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") },
{ label: tr("Command palette"), icon: "terminal", shortcut: "F1", run: () => run("editor.action.quickCommand") },
];
root = actionMenu(x, y, items, close, "Code text actions");
root = actionMenu(x, y, items, close, tr("Code text actions"));
}
return { open, close, destroy() {
close(false);
+4 -3
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type MarkdownIt from "markdown-it";
import type { Token } from "markdown-it";
type MarkdownParser = InstanceType<typeof MarkdownIt>;
@@ -60,15 +61,15 @@ export function footnotes(markdown: MarkdownParser) {
markdown.renderer.rules.note_footnote_definition = () => "";
markdown.renderer.rules.note_footnote_reference = (tokens, index) => {
const { number, reference } = tokens[index].meta as { number: number; reference: number };
return `<sup class="md-footnote-ref"><a href="#rs-fn-${number}" id="rs-fnref-${number}-${reference}" data-footnote-link aria-label="Footnote ${number}">${number}</a></sup>`;
return `<sup class="md-footnote-ref"><a href="#rs-fn-${number}" id="rs-fnref-${number}-${reference}" data-footnote-link aria-label="${markdown.utils.escapeHtml(tr('Footnote {number}', { number }))}">${number}</a></sup>`;
};
}
export function renderFootnotes(markdown: MarkdownParser, env: FootnoteEnvironment): string {
const notes = [...env.noteFootnotes?.values() ?? []].filter(note => note.number).sort((a, b) => a.number - b.number);
if (!notes.length) return "";
return '<section class="md-footnotes" aria-label="Footnotes"><ol>' + notes.map(note => {
const backlinks = Array.from({ length: note.references }, (_, index) => `<a href="#rs-fnref-${note.number}-${index + 1}" class="md-footnote-back" data-footnote-link aria-label="Back to reference ${note.number}${index ? `, occurrence ${index + 1}` : ""}" title="Back to reference">↩</a>`).join(" ");
return `<section class="md-footnotes" aria-label="${markdown.utils.escapeHtml(tr('Footnotes'))}"><ol>` + notes.map(note => {
const backlinks = Array.from({ length: note.references }, (_, index) => `<a href="#rs-fnref-${note.number}-${index + 1}" class="md-footnote-back" data-footnote-link aria-label="${markdown.utils.escapeHtml(index ? tr('Back to reference {number}, occurrence {occurrence}', { number: note.number, occurrence: index + 1 }) : tr('Back to reference {number}', { number: note.number }))}" title="${markdown.utils.escapeHtml(tr('Back to reference'))}">↩</a>`).join(" ");
return `<li id="rs-fn-${note.number}" tabindex="-1">${markdown.renderer.render(note.tokens, markdown.options, env)} ${backlinks}</li>`;
}).join("") + "</ol></section>";
}
+3 -2
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, WidgetType, keymap } from "@codemirror/view";
import { codeFolding, foldEffect, foldKeymap, foldedRanges, foldService, syntaxTree, unfoldEffect } from "@codemirror/language";
@@ -29,7 +30,7 @@ export function headingButton(label: string, collapsed: boolean): HTMLButtonElem
button.type = "button";
button.className = "rs-heading-toggle";
button.setAttribute("aria-expanded", String(!collapsed));
const title = `${collapsed ? "Expand" : "Collapse"} ${label || "heading"}`;
const title = tr(collapsed ? "Expand {name}" : "Collapse {name}", { name: label || tr("heading") });
button.setAttribute("aria-label", title);
tooltipCleanups.set(button, attachTooltip(button, () => button.getAttribute("aria-label") || ""));
const icon = actionIcon("chevron");
@@ -100,7 +101,7 @@ export function readerHeadingFolding(root: HTMLElement, collapsed: Set<string>)
headings.forEach(item => {
const button = item.heading.querySelector<HTMLButtonElement>(".rs-heading-toggle");
if (button) {
const label = `${collapsed.has(item.key) ? "Expand" : "Collapse"} ${item.label}`;
const label = tr(collapsed.has(item.key) ? "Expand {name}" : "Collapse {name}", { name: item.label });
button.setAttribute("aria-expanded", String(!collapsed.has(item.key)));
button.setAttribute("aria-label", label);
+21 -20
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { actionIcon, type ActionIcon } from "../ui/actionIcons";
import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
@@ -43,12 +44,12 @@ function button(label: string, icon: ActionIcon, action: () => void) {
function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
const dialog = document.createElement("dialog");
dialog.className = "image-lightbox";
dialog.setAttribute("aria-label", "Image zoom");
dialog.setAttribute("aria-label", tr("Image zoom"));
const header = document.createElement("div");
header.className = "image-lightbox-toolbar";
const name = document.createElement("span");
name.className = "image-lightbox-name";
name.textContent = original.dataset.mdSrc || original.alt || "Image";
name.textContent = original.dataset.mdSrc || original.alt || tr("Image");
const viewport = document.createElement("div");
viewport.className = "image-lightbox-viewport";
const image = original.cloneNode() as HTMLImageElement;
@@ -62,14 +63,14 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
scale = next;
image.style.width = scale ? `${image.naturalWidth * scale}px` : "";
viewport.classList.toggle("is-zoomed", scale > 0);
status.textContent = scale ? `${Math.round(scale * 100)}%` : "Fit";
status.textContent = scale ? `${Math.round(scale * 100)}%` : tr("Fit");
zoomOut.disabled = scale === 0;
zoomIn.disabled = scale >= 4;
}
const zoomOut = button("Zoom out", "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2));
const zoomIn = button("Zoom in", "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1));
const fit = button("Fit image", "select", () => resize(0));
const close = button("Close image", "close", () => dialog.close());
const zoomOut = button(tr("Zoom out"), "zoom-out", () => resize(scale <= .5 ? 0 : scale / 2));
const zoomIn = button(tr("Zoom in"), "zoom-in", () => resize(scale ? Math.min(4, scale * 2) : 1));
const fit = button(tr("Fit image"), "select", () => resize(0));
const close = button(tr("Close image"), "close", () => dialog.close());
header.append(name, zoomOut, status, zoomIn, fit, close);
viewport.append(image);
dialog.append(header, viewport);
@@ -93,17 +94,17 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
frame.contentEditable = "false";
frame.tabIndex = 0;
frame.setAttribute("role", "group");
frame.setAttribute("aria-label", `Image: ${image.alt || image.dataset.mdSrc || "image"}`);
frame.setAttribute("aria-label", tr("Image: {name}", { name: image.alt || image.dataset.mdSrc || tr("Image") }));
image.replaceWith(frame);
frame.append(image);
image.draggable = false;
const toolbar = document.createElement("span");
toolbar.className = "md-image-actions";
let closeZoom: (() => void) | undefined;
const zoom = button("Zoom in", "zoom-in", () => { closeZoom = zoomImage(image, zoom); });
const zoom = button(tr("Zoom in"), "zoom-in", () => { closeZoom = zoomImage(image, zoom); });
cleanup.push(() => closeZoom?.());
toolbar.append(zoom);
if (actions.edit) toolbar.append(button(actions.editing ? "Hide image source" : "Edit image source", "code", actions.editing && actions.done ? actions.done : actions.edit));
if (actions.edit) toolbar.append(button(actions.editing ? tr("Hide image source") : tr("Edit image source"), "code", actions.editing && actions.done ? actions.done : actions.edit));
frame.append(toolbar);
cleanup.push(() => toolbar.querySelectorAll<HTMLButtonElement>("button").forEach(button => tooltipCleanups.get(button)?.()));
let menu: HTMLElement | undefined;
@@ -125,19 +126,19 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
function openMenu(x: number, y: number) {
closeMenu(false); select();
const items: ActionMenuItem[] = [
{ label: "Copy image", icon: "copy", run: () => void run(() => copyImage(image)) },
...(actions.markdown ? [{ label: "Copy Markdown", icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []),
...(actions.swap ? [{ label: "Swap image…", icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []),
...(actions.remove ? [{ label: "Remove image", icon: "trash" as const, run: () => void run(actions.remove!) }] : []),
{ label: tr("Copy image"), icon: "copy", run: () => void run(() => copyImage(image)) },
...(actions.markdown ? [{ label: tr("Copy Markdown"), icon: "code" as const, run: () => void run(() => navigator.clipboard.writeText(actions.markdown!())) }] : []),
...(actions.swap ? [{ label: tr("Swap image…"), icon: "swap" as const, run: () => void run(() => actions.swap!(image)) }] : []),
...(actions.remove ? [{ label: tr("Remove image"), icon: "trash" as const, run: () => void run(actions.remove!) }] : []),
{ separator: true },
{ label: "Zoom in", icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } },
...(actions.edit ? [{ label: "Edit image source", icon: "code" as const, run: () => void run(actions.edit!) }] : []),
...(actions.open ? [{ label: "Open in new tab", icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []),
{ label: "Copy path", icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) },
...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: "Show in Explorer", icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []),
{ label: tr("Zoom in"), icon: "zoom-in", run: () => { closeMenu(false); closeZoom = zoomImage(image, zoom); } },
...(actions.edit ? [{ label: tr("Edit image source"), icon: "code" as const, run: () => void run(actions.edit!) }] : []),
...(actions.open ? [{ label: tr("Open in new tab"), icon: "external" as const, run: () => void run(() => actions.open!(image)) }] : []),
{ label: tr("Copy path"), icon: "link", run: () => void run(() => navigator.clipboard.writeText(image.dataset.mdSrc || "")) },
...(actions.reveal && !/^https?:/i.test(image.dataset.mdSrc || "") ? [{ label: tr("Show in Explorer"), icon: "external" as const, run: () => void run(() => actions.reveal!(image)) }] : []),
];
openingMenu = true;
try { menu = actionMenu(x, y, items, closeMenu, "Image actions"); }
try { menu = actionMenu(x, y, items, closeMenu, tr("Image actions")); }
finally { openingMenu = false; }
}
frame.addEventListener("mousedown", event => { if (!(event.target as Element).closest("button")) { event.preventDefault(); event.stopPropagation(); select(); } });
+4 -3
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { EditorView, WidgetType } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { imageControls, type ImageActions } from "./imageControls";
@@ -48,9 +49,9 @@ export class ImagePreview extends WidgetType {
report: this.context.report,
swap: async image => {
const before = view.state.doc;
const path = (await requestText("Image path relative to this note, or https URL", image.dataset.mdSrc || ""))?.trim();
const path = (await requestText(tr("Image path relative to this note, or https URL"), image.dataset.mdSrc || ""))?.trim();
if (!path || !dom.isConnected || view.state.doc !== before) return;
if (!isRemoteImage(path) && /^[a-z][a-z\d+.-]*:/i.test(path)) throw new Error("Choose a workspace image path or an http/https URL.");
if (!isRemoteImage(path) && /^[a-z][a-z\d+.-]*:/i.test(path)) throw new Error(tr("Choose a workspace image path or an http/https URL."));
await this.context.validate?.(path);
if (!dom.isConnected || view.state.doc !== before) return;
const target = path.replace(/[<>\s]/g, char => encodeURIComponent(char));
@@ -63,7 +64,7 @@ export class ImagePreview extends WidgetType {
if (!dom.querySelector("img")) {
const edit = document.createElement("button");
edit.type = "button"; edit.className = "image-action";
const label = this.editing ? "Hide image source" : "Edit image source";
const label = this.editing ? tr("Hide image source") : tr("Edit image source");
edit.setAttribute("aria-label", label); edit.dataset.editorTooltip = label;
edit.append(actionIcon("code"));
edit.addEventListener("click", event => { event.preventDefault(); event.stopPropagation(); (this.editing ? actions.done : actions.edit)?.(); });
+7 -6
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { ActionMenuItem } from "../ui/actionMenu";
export type MenuLink = { kind: "md" | "wiki"; target: string };
@@ -15,16 +16,16 @@ export function linkMenuItems(link: MenuLink, actions: DocumentLinkActions, clos
};
const external = /^(https?:\/\/|mailto:)/i.test(link.target);
const items: ActionMenuItem[] = external ? [
...(actions.browser && /^https?:\/\//i.test(link.target) ? [{ label: "Open link in app browser", icon: "globe" as const, run: run(() => actions.browser!(link.target)) }] : []),
...(actions.defaultBrowser ? [{ label: "Open link in default browser", icon: "external" as const, run: run(() => actions.defaultBrowser!(link.target)) }] : []),
...(actions.browser && /^https?:\/\//i.test(link.target) ? [{ label: tr("Open link in app browser"), icon: "globe" as const, run: run(() => actions.browser!(link.target)) }] : []),
...(actions.defaultBrowser ? [{ label: tr("Open link in default browser"), icon: "external" as const, run: run(() => actions.defaultBrowser!(link.target)) }] : []),
] : [];
if (!items.length && actions.open) items.push({ label: external ? "Open link" : "Open in new tab", icon: external ? "external" : "file-plus", run: run(() => actions.open!(link)) });
if (!items.length && actions.open) items.push({ label: external ? tr("Open link") : tr("Open in new tab"), icon: external ? "external" : "file-plus", run: run(() => actions.open!(link)) });
if (!external && actions.workspaceItems) {
const wrap = (item: ActionMenuItem): ActionMenuItem => "separator" in item ? item : { ...item, run: item.run ? run(item.run) : undefined, children: item.children?.map(wrap) };
const workspaceItems = actions.workspaceItems(link).filter(item => !edit || "separator" in item || !["Rename…", "Move file to…", "Open in default app"].includes(item.label));
const workspaceItems = actions.workspaceItems(link).filter(item => !edit || "separator" in item || ![tr("Rename…"), tr("Move file to…"), tr("Open in default app")].includes(item.label));
items.push(...workspaceItems.map(wrap));
}
items.push({ label: external ? "Copy URL" : "Copy link target", icon: "link", run: run(() => navigator.clipboard.writeText(link.target)) });
if (edit) items.push({ label: "Edit link", icon: "rename", run: () => { close(); edit(); } });
items.push({ label: external ? tr("Copy URL") : tr("Copy link target"), icon: "link", run: run(() => navigator.clipboard.writeText(link.target)) });
if (edit) items.push({ label: tr("Edit link"), icon: "rename", run: () => { close(); edit(); } });
return items;
}
+8 -7
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
@@ -40,8 +41,8 @@ class CodeCopy extends WidgetType {
const button = document.createElement("button");
button.type = "button";
button.className = "rs-fence-copy writer-code-copy";
button.setAttribute("aria-label", "Copy code");
button.dataset.editorTooltip = "Copy code";
button.setAttribute("aria-label", tr("Copy code"));
button.dataset.editorTooltip = tr("Copy code");
button.append(actionIcon("copy"));
button.onmousedown = event => event.preventDefault();
button.onclick = async event => {
@@ -49,11 +50,11 @@ class CodeCopy extends WidgetType {
try {
await navigator.clipboard.writeText(this.code);
button.dataset.copied = "true";
button.dataset.editorTooltip = "Copied";
button.setAttribute("aria-label", "Code copied");
button.dataset.editorTooltip = tr("Copied");
button.setAttribute("aria-label", tr("Code copied"));
} catch {
button.dataset.editorTooltip = "Could not copy code";
button.setAttribute("aria-label", "Could not copy code");
button.dataset.editorTooltip = tr("Could not copy code");
button.setAttribute("aria-label", tr("Could not copy code"));
}
};
return button;
@@ -86,7 +87,7 @@ class Checkbox extends WidgetType {
box.type = "checkbox";
box.checked = this.checked;
box.className = "writer-checkbox";
box.setAttribute("aria-label", this.checked ? "Mark task incomplete" : "Mark task complete");
box.setAttribute("aria-label", this.checked ? tr("Mark task incomplete") : tr("Mark task complete"));
box.addEventListener("mousedown", event => event.preventDefault());
box.addEventListener("click", event => {
event.stopPropagation();
+25 -24
View File
@@ -1,3 +1,4 @@
import { tr } from "../i18n/index.ts";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { wordAt } from "./spellingWord";
@@ -89,40 +90,40 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
editor.select(selectedLink.targetFrom, selectedLink.targetTo); editor.focus();
}), { separator: true as const }] : []),
...(editor.undo ? [
{ label: "Undo", icon: "undo" as const, shortcut: "Ctrl+Z", disabled: !editor.canUndo?.(), run: () => { close(); editor.undo?.(); } },
{ label: "Redo", icon: "redo" as const, shortcut: "Ctrl+Shift+Z", disabled: !editor.canRedo?.(), run: () => { close(); editor.redo?.(); } },
{ label: tr("Undo"), icon: "undo" as const, shortcut: "Ctrl+Z", disabled: !editor.canUndo?.(), run: () => { close(); editor.undo?.(); } },
{ label: tr("Redo"), icon: "redo" as const, shortcut: "Ctrl+Shift+Z", disabled: !editor.canRedo?.(), run: () => { close(); editor.redo?.(); } },
{ separator: true as const },
] : []),
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ label: tr("Add link"), icon: "link", run: () => link(false) },
{ label: tr("Add external link"), icon: "external", run: () => link(true) },
{ separator: true },
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
{ label: text ? tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }) : tr("Search selection"), icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const target = await actions.onExtract?.(text, text, valid);
if (target) apply(replacement(selection, `[[${target}|${text.replace(/[\[\]|]/g, "").replace(/\s+/g, " ").trim()}]]`));
}) },
{ label: "Format", icon: "format", children: cellFormats.flatMap(([label, kind]) => [
{ label: tr("Format"), icon: "format", children: cellFormats.flatMap(([label, kind]) => [
...(kind === "code" || kind === "clear" ? [{ separator: true } as const] : []),
{ label, icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) },
{ label: tr(label), icon: kind, disabled: kind === "clear" && !text, run: () => apply(formatText(source, selection, kind)) },
]) },
{ label: "Paragraph", icon: "paragraph", children: [
paragraph("Bullet list", "bullet", "bullet"), paragraph("Numbered list", "number", "number"), paragraph("Task list", "task", "task"),
{ label: tr("Paragraph"), icon: "paragraph", children: [
paragraph(tr("Bullet list"), "bullet", "bullet"), paragraph(tr("Numbered list"), "number", "number"), paragraph(tr("Task list"), "task", "task"),
{ separator: true },
...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(`Heading ${level}`, level, "heading")),
paragraph("Body", "body", "paragraph"), { separator: true }, paragraph("Quote", "quote", "quote"),
...([1, 2, 3, 4, 5, 6] as const).map(level => paragraph(tr("Heading {level}", { level }), level, "heading")),
paragraph(tr("Body"), "body", "paragraph"), { separator: true }, paragraph(tr("Quote"), "quote", "quote"),
] },
{ label: "Insert", icon: "insert", children: [
insert("Footnote", "footnote", "footnote"), insert("Table", "table", "table"), insert("Callout", "callout", "quote"), insert("Horizontal rule", "rule", "rule"),
{ separator: true }, insert("Code block", "code", "code"), insert("Math block", "math", "math"),
{ label: tr("Insert"), icon: "insert", children: [
insert(tr("Footnote"), "footnote", "footnote"), insert(tr("Table"), "table", "table"), insert(tr("Callout"), "callout", "quote"), insert(tr("Horizontal rule"), "rule", "rule"),
{ separator: true }, insert(tr("Code block"), "code", "code"), insert(tr("Math block"), "math", "math"),
] },
{ separator: true },
{ label: "Cut", icon: "cut", disabled: !text, run: () => clipboard("cut") },
{ label: "Copy", icon: "copy", disabled: !text, run: () => clipboard("copy") },
{ label: "Paste", icon: "paste", run: () => clipboard("paste") },
{ label: "Paste as plain text", icon: "paste-text", run: () => clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.selectAll(); } },
{ label: tr("Cut"), icon: "cut", disabled: !text, run: () => clipboard("cut") },
{ label: tr("Copy"), icon: "copy", disabled: !text, run: () => clipboard("copy") },
{ label: tr("Paste"), icon: "paste", run: () => clipboard("paste") },
{ label: tr("Paste as plain text"), icon: "paste-text", run: () => clipboard("plain") },
{ label: tr("Select all"), icon: "select", run: () => { close(); editor.selectAll(); } },
];
root = actionMenu(x, y, items, close, "Markdown text actions");
root = actionMenu(x, y, items, close, tr("Markdown text actions"));
const opened = root;
const word = spellingOffset === undefined ? null : wordAt(source, spellingOffset);
if (word && isTauri()) {
@@ -130,14 +131,14 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
void invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages }).then(result => {
if (!result.misspelled || root !== opened || !valid()) return;
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => apply(replacement(word, value)) }));
if (!suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true });
suggestions.push({ label: "Add to dictionary", icon: "book", run: () => {
if (!suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true });
suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => {
close();
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary."));
} });
const focusedLabel = opened.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
opened.remove();
root = actionMenu(x, y, [...suggestions, { separator: true }, ...items], close, "Markdown text actions");
root = actionMenu(x, y, [...suggestions, { separator: true }, ...items], close, tr("Markdown text actions"));
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
}).catch(() => { /* Editing actions remain available without spelling suggestions. */ });
}
+4 -3
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { Decoration, EditorView, WidgetType } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
@@ -19,14 +20,14 @@ class NoteTitle extends WidgetType {
const button = document.createElement("button");
button.type = "button";
button.className = "note-title-button";
button.setAttribute("aria-label", "Rename note");
button.setAttribute("aria-label", tr("Rename note"));
button.append(document.createTextNode(this.title), actionIcon("rename"));
button.dataset.editorTooltip = "Rename note";
button.dataset.editorTooltip = tr("Rename note");
heading.replaceChildren(button);
const input = document.createElement("input");
input.className = "note-title-input";
input.setAttribute("aria-label", "Note filename");
input.setAttribute("aria-label", tr("Note filename"));
input.autocomplete = "off";
input.spellcheck = false;
input.hidden = true;
+5 -4
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
import { linkMenuItems, type DocumentLinkActions } from "./linkMenu";
@@ -31,16 +32,16 @@ export function readingMenu(host: HTMLElement, actions: DocumentLinkActions, sea
previousFocus = document.activeElement instanceof HTMLElement && host.contains(document.activeElement) ? document.activeElement : host;
const items: ActionMenuItem[] = [];
if (text) items.push(
{ label: "Copy", icon: "copy", shortcut: "Ctrl+C", run: () => { close(); void navigator.clipboard.writeText(text).catch(() => report("Clipboard unavailable. Use Ctrl+C to copy.")); } },
{ label: `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”`, icon: "search", disabled: !search, run: () => { close(false); search?.(text); } },
{ label: tr("Copy"), icon: "copy", shortcut: "Ctrl+C", run: () => { close(); void navigator.clipboard.writeText(text).catch(() => report(tr("Clipboard unavailable. Use Ctrl+C to copy."))); } },
{ label: tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }), icon: "search", disabled: !search, run: () => { close(false); search?.(text); } },
);
if (anchor) {
if (items.length) items.push({ separator: true });
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: "Open link", icon: "link", run: () => { close(false); (anchor as HTMLElement).click(); } });
if (anchor.hasAttribute("data-footnote-link")) items.push({ label: tr("Open link"), icon: "link", run: () => { close(false); (anchor as HTMLElement).click(); } });
else items.push(...linkMenuItems({ kind: anchor.getAttribute("data-kind") === "wiki" ? "wiki" : "md", target: anchor.getAttribute("href") ?? "" }, actions, () => close(false), report));
}
const rect = keyboard ? (range?.getBoundingClientRect() ?? anchor?.getBoundingClientRect() ?? host.getBoundingClientRect()) : null;
root = actionMenu(rect?.left ?? (event as MouseEvent).clientX, rect?.bottom ?? (event as MouseEvent).clientY, items, close, "Reading actions");
root = actionMenu(rect?.left ?? (event as MouseEvent).clientX, rect?.bottom ?? (event as MouseEvent).clientY, items, close, tr("Reading actions"));
}
const outside = (event: Event) => { if (root && event.target instanceof Node && !root.contains(event.target)) close(false); };
const resize = () => close(false);
+16 -7
View File
@@ -1,3 +1,4 @@
import { tr } from "../i18n/index.ts";
import { invoke, isTauri } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { actionMenu, type ActionMenuItem } from "../ui/actionMenu";
@@ -87,32 +88,40 @@ export function mountSpellingMenu(): () => void {
const { target, x, y, word } = context;
const requestRevision = ++revision;
let items = spellingItems(payload.items, id => finish(id, true));
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body;
const show = () => {
const previous = active?.request === payload.request ? active.root : undefined;
const focusedLabel = previous?.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
previous?.remove();
const root = actionMenu(x, y, items, () => finish(null, true), tr("Spelling actions"), parent);
active = { request: payload.request, root, target };
if (focusedLabel) [...root.querySelectorAll<HTMLButtonElement>(":scope > button")].find(button => button.querySelector(".action-label")?.textContent === focusedLabel)?.focus();
};
if (payload.fallback_spelling) {
const readable = (entries: NativeSpellingItem[]): NativeSpellingItem[] => entries.filter(item => item.kind === 3 || item.label.trim()).map(item => ({ ...item, children: readable(item.children) }));
items = spellingItems(readable(payload.items), id => finish(id, true));
show();
if (word) {
const languages = [...new Set([target.lang, document.documentElement.lang, ...navigator.languages].filter(Boolean))];
try {
const result = await invoke<{ language: string; words: string[]; misspelled: boolean }>("spelling_suggestions", { word: word.word, languages });
const suggestions: ActionMenuItem[] = result.words.map(value => ({ label: value, run: () => { finish(); word.replace(value); } }));
if (result.misspelled && !suggestions.length) suggestions.push({ label: "No spelling suggestions", disabled: true });
if (result.misspelled) suggestions.push({ label: "Add to dictionary", icon: "book", run: () => {
if (result.misspelled && !suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true });
if (result.misspelled) suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => {
finish(null, true);
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(error => console.error("Could not add the word", error));
} }, { separator: true });
items = [...suggestions, ...items];
} catch {
items = [{ label: "Spelling suggestions unavailable", disabled: true }, { separator: true }, ...items];
items = [{ label: tr("Spelling suggestions unavailable"), disabled: true }, { separator: true }, ...items];
}
}
}
if (disposed || requestRevision !== revision || !target.isConnected || (payload.fallback_spelling && word && !word.valid())) {
if (disposed || requestRevision !== revision || (payload.fallback_spelling && active?.request !== payload.request) || !target.isConnected || (payload.fallback_spelling && word && !word.valid())) {
void invoke("spelling_menu_select", { request: payload.request, command: null });
return;
}
const parent = target.closest<HTMLDialogElement>("dialog[open]") ?? document.body;
const root = actionMenu(x, y, items, () => finish(null, true), "Spelling actions", parent);
active = { request: payload.request, root, target };
show();
}).then(async stop => {
if (disposed) { stop(); return; }
unlisten = stop;
+18 -17
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
import { requestText } from "../workspace/dialogs.svelte";
import { extractedCellMarkdown } from "./tableCellMarkdown";
@@ -29,15 +30,15 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
}
function link(external: boolean) {
void request(async () => {
const target = await requestText(external ? "External link URL" : "Link to note (name or workspace path)", external ? "https://" : text);
const target = await requestText(external ? tr("External link URL") : tr("Link to note (name or workspace path)"), external ? "https://" : text);
if (!target || !valid()) return;
if (external) {
try {
const url = new URL(target);
if (!(["http:", "https:"].includes(url.protocol) && url.hostname || url.protocol === "mailto:" && url.pathname.includes("@")) || /\s/.test(target)) throw new Error("Invalid URL");
} catch { report("Enter a valid http, https, or mailto link."); return; }
} catch { report(tr("Enter a valid http, https, or mailto link.")); return; }
}
if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report("Enter a note name or path without brackets or pipes."); return; }
if (!external && /[\[\]|\r\n]|^[a-z][a-z\d+.-]*:/i.test(target)) { report(tr("Enter a note name or path without brackets or pipes.")); return; }
run(() => {
const attrs = { href: target, "data-kind": external ? "md" : "wiki" };
if (selection.empty) editor.commands.insertContent({ type: "text", text: target, marks: [{ type: "link", attrs }] });
@@ -88,35 +89,35 @@ export function tableTextItems(editor: Editor, actions: TableContextActions, clo
}
});
}
} catch { report("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste."); }
} catch { report(tr("Clipboard unavailable. Use the keyboard shortcut to copy, cut, or paste.")); }
});
}
const items: ActionMenuItem[] = [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
{ label: "Add link", icon: "link", run: () => link(false) },
{ label: "Add external link", icon: "external", run: () => link(true) },
{ label: tr("Add link"), icon: "link", run: () => link(false) },
{ label: tr("Add external link"), icon: "external", run: () => link(true) },
{ separator: true },
{ label: text ? `Search for “${text.length > 32 ? text.slice(0, 32) + "…" : text}”` : "Search selection", icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: "Extract current selection…", icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
{ label: text ? tr("Search for “{text}”", { text: text.length > 32 ? text.slice(0, 32) + "…" : text }) : tr("Search selection"), icon: "search", disabled: !text || !actions.onSearch, run: () => { close(); actions.onSearch?.(text); } },
{ label: tr("Extract current selection…"), icon: "extract", disabled: !text || !actions.onExtract, run: () => void request(async () => {
const selected = doc.slice(selection.from, selection.to).content.toJSON() as JSONContent[] | null;
const markdown = extractedCellMarkdown(selected || []);
const target = await actions.onExtract?.(markdown, text, valid);
if (target) run(() => { editor.commands.insertContent({ type: "text", text: text.replace(/\s+/g, " ").trim(), marks: [{ type: "link", attrs: { href: target, "data-kind": "wiki" } }] }); });
}) },
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, disabled: selection.empty, run: () => run(() => {
{ label: tr("Format"), icon: "format", children: cellFormats.map(([label, kind]) => ({ label: tr(label), icon: kind, disabled: selection.empty, run: () => run(() => {
if (kind === "clear") editor.commands.unsetAllMarks(); else editor.commands.toggleMark(kind);
}) })) },
{ label: "Paragraph", icon: "paragraph", disabled: true, title: "Markdown table cells contain inline text" },
{ label: "Insert", icon: "insert", disabled: true, title: "Use the Row and Column menus to change the table" },
{ label: tr("Paragraph"), icon: "paragraph", disabled: true, title: tr("Markdown table cells contain inline text") },
{ label: tr("Insert"), icon: "insert", disabled: true, title: tr("Use the Row and Column menus to change the table") },
{ separator: true },
{ label: "Cut", icon: "cut", disabled: selection.empty, run: () => void clipboard("cut") },
{ label: "Copy", icon: "copy", disabled: selection.empty, run: () => void clipboard("copy") },
{ label: "Paste", icon: "paste", run: () => void clipboard("paste") },
{ label: "Paste as plain text", icon: "paste-text", run: () => void clipboard("plain") },
{ label: "Select all", icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } },
{ label: tr("Cut"), icon: "cut", disabled: selection.empty, run: () => void clipboard("cut") },
{ label: tr("Copy"), icon: "copy", disabled: selection.empty, run: () => void clipboard("copy") },
{ label: tr("Paste"), icon: "paste", run: () => void clipboard("paste") },
{ label: tr("Paste as plain text"), icon: "paste-text", run: () => void clipboard("plain") },
{ label: tr("Select all"), icon: "select", run: () => { close(); editor.commands.selectAll(); editor.view.focus(); } },
];
return sourceEditing ? [
...(selectedLink ? [...linkMenuItems(selectedLink, actions.linkActions?.() || {}, close, report, editLink), { separator: true as const }] : []),
...items.slice(items.findIndex(item => "label" in item && item.label === "Cut")),
...items.slice(items.findIndex(item => "label" in item && item.label === tr("Cut"))),
] : items;
}
+5 -4
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import { Editor, Extension, Mark, getMarkRange } from "@tiptap/core";
import { Plugin } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
@@ -96,7 +97,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
cell.removeAttribute("title");
if (result && cell !== active) cell.innerHTML = formulas.tableFormulaHtml(result);
if (cell === active) {
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : " · Type = to calculate"}`;
formulaStatus.textContent = `${address}${result ? ` = ${result.text}` : tr(" · Type = to calculate")}`;
formulaHint.textContent = result?.error ? formulas.formulaErrors[result.error] : "";
formulaHint.hidden = !formulaHint.textContent;
}
@@ -136,7 +137,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
cell.innerHTML = html;
cell.classList.remove("is-editing", "is-source-editing");
refreshFormulas();
formulaStatus.textContent = "Type = in a cell to calculate";
formulaStatus.textContent = tr("Type = in a cell to calculate");
formulaHint.hidden = true;
view.requestMeasure();
if (!firstEdit) view.dispatch({ annotations: isolateHistory.of("after") });
@@ -390,7 +391,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
wrapper.after(footer);
for (const kind of ["column", "row"] as const) {
const button = document.createElement("button");
const label = kind === "column" ? "Add column to the right" : "Add row below";
const label = kind === "column" ? tr("Add column to the right") : tr("Add row below");
button.type = "button";
button.className = `table-add table-add-${kind}`;
tooltipCleanup.push(attachTooltip(button, () => label));
@@ -409,7 +410,7 @@ export function tableControls(root: HTMLElement, view: EditorView, initialSource
}
for (const row of table.rows) for (const cell of row.cells) {
cell.tabIndex = 0;
cell.setAttribute("aria-label", `${formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : ""}Row ${row.rowIndex + 1}, column ${cell.cellIndex + 1}`);
cell.setAttribute("aria-label", (formulas ? formulas.cellAddress(row.rowIndex, cell.cellIndex) + " · " : "") + tr("Row {row}, column {column}", { row: row.rowIndex + 1, column: cell.cellIndex + 1 }));
cell.addEventListener("focus", () => activate(cell));
}
selectionControls = tableSelectionControls(root, wrapper, table, view, () => controller.source, finish, change, { get: () => editor, activate, editSource }, actions);
+4 -3
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { EditorView } from "@codemirror/view";
import { actionIcon } from "../ui/actionIcons";
import { moveTableAxis, type TableAxis } from "./tableStructure";
@@ -102,7 +103,7 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
if (!preview || !previewLabel || !drag) return;
const valid = drag.to !== undefined;
preview.classList.toggle("is-invalid-drop", !valid);
previewLabel.textContent = `${drag.axis === "row" ? "Row" : "Column"} ${drag.index + 1}${valid ? ` → ${drag.to! + 1}` : " · Release to cancel"}`;
previewLabel.textContent = `${drag.axis === "row" ? tr("Row") : tr("Column")} ${drag.index + 1}${valid ? ` → ${drag.to! + 1}` : tr(" · Release to cancel")}`;
const rect = preview.getBoundingClientRect();
const x = Math.max(8, Math.min(drag.x + 16, window.innerWidth - rect.width - 8));
const y = Math.max(8, Math.min(drag.y + 16, window.innerHeight - rect.height - 8));
@@ -171,8 +172,8 @@ export function tableDragControls(root: HTMLElement, wrapper: HTMLElement, table
button.type = "button";
button.className = `table-drag-handle table-drag-${axis}`;
button.dataset.index = String(index);
const label = `Move ${axis} ${index + 1}`;
const tooltip = `${label} · Drag to reorder · ${axis === "row" ? "↑/↓" : "←/→"} to move`;
const label = tr(axis === "row" ? "Move row {number}" : "Move column {number}", { number: index + 1 });
const tooltip = tr("{label} · Drag to reorder · {keys} to move", { label, keys: axis === "row" ? "↑/↓" : "←/→" });
button.setAttribute("aria-label", label);
tooltipCleanup.push(attachTooltip(button, () => drag ? "" : tooltip));
button.append(actionIcon("grip"));
+25 -24
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { EditorView } from "@codemirror/view";
import { isolateHistory } from "@codemirror/commands";
import { undo, redo } from "./writerHistory";
@@ -103,9 +104,9 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
apply((text, selected) => alignTableCells(text, selected, alignment));
};
const alignmentItems: ActionMenuItem[] = [
{ label: "Align left", icon: "left", run: () => align("left") },
{ label: "Align centre", icon: "center", run: () => align("center") },
{ label: "Align right", icon: "right", run: () => align("right") },
{ label: tr("Align left"), icon: "left", run: () => align("left") },
{ label: tr("Align centre"), icon: "center", run: () => align("center") },
{ label: tr("Align right"), icon: "right", run: () => align("right") },
].map(item => ({ ...item, title: "Alignment applies to the selected Markdown columns" } as ActionMenuItem));
const report = (message: string) => {
const status = root.querySelector<HTMLElement>(".table-edit-help");
@@ -114,34 +115,34 @@ export function tableSelectionControls(root: HTMLElement, wrapper: HTMLElement,
const items: ActionMenuItem[] = textEditor ? tableTextItems(textEditor, actions, closeMenu, run => {
view.dispatch({ annotations: isolateHistory.of("before") }); run(); view.dispatch({ annotations: isolateHistory.of("after") });
}, value => { pending = value; }, report, rich.editSource) : [
...(["cut", "copy", "paste"] as const).map(action => ({ label: action[0].toUpperCase() + action.slice(1), icon: action, run: () => void clipboard(action) })),
...(["cut", "copy", "paste"] as const).map(action => ({ label: tr(action[0].toUpperCase() + action.slice(1)), icon: action, run: () => void clipboard(action) })),
sep,
{ label: "Format", icon: "format", children: cellFormats.map(([label, kind]) => ({ label, icon: kind, run: () => format(kind) })) },
{ label: tr("Format"), icon: "format", children: cellFormats.map(([label, kind]) => ({ label: tr(label), icon: kind, run: () => format(kind) })) },
...alignmentItems,
sep, { label: "Clear cells", icon: "clear", run: clearCells, title: "Clear selected values and keep the cells." },
{ label: "Delete cells", icon: "trash", run: deleteCells, title: "Delete or Backspace removes full rows or columns. Other selections shift cells left." },
sep, { label: tr("Clear cells"), icon: "clear", run: clearCells, title: tr("Clear selected values and keep the cells.") },
{ label: tr("Delete cells"), icon: "trash", run: deleteCells, title: tr("Delete or Backspace removes full rows or columns. Other selections shift cells left.") },
];
if (textEditor) items.push(sep, { label: "Select cell", icon: "select", title: "Select this cell, then use Shift+arrow keys to extend the selection", run: () => { closeMenu(); select(cellRange); } });
if (textEditor) items.push(sep, { label: tr("Select cell"), icon: "select", title: tr("Select this cell, then use Shift+arrow keys to extend the selection"), run: () => { closeMenu(); select(cellRange); } });
items.push(sep,
{ label: "Row", icon: "row", children: [
{ label: "Add row above", icon: "row-before", disabled: row === 0, title: row === 0 ? "The first row is the Markdown header" : undefined, run: () => structural("row", "before") },
{ label: "Add row below", icon: "row-after", run: () => structural("row", "after") }, sep,
{ label: "Move row up", icon: "up", disabled: row <= 1, run: () => structural("row", "previous") },
{ label: "Move row down", icon: "down", disabled: row === 0 || row === lastRow, run: () => structural("row", "next") }, sep,
{ label: "Duplicate row", icon: "copy", run: () => structural("row", "duplicate") },
{ label: "Delete row", icon: "trash", run: () => structural("row", "delete") },
{ label: tr("Row"), icon: "row", children: [
{ label: tr("Add row above"), icon: "row-before", disabled: row === 0, title: row === 0 ? tr("The first row is the Markdown header") : undefined, run: () => structural("row", "before") },
{ label: tr("Add row below"), icon: "row-after", run: () => structural("row", "after") }, sep,
{ label: tr("Move row up"), icon: "up", disabled: row <= 1, run: () => structural("row", "previous") },
{ label: tr("Move row down"), icon: "down", disabled: row === 0 || row === lastRow, run: () => structural("row", "next") }, sep,
{ label: tr("Duplicate row"), icon: "copy", run: () => structural("row", "duplicate") },
{ label: tr("Delete row"), icon: "trash", run: () => structural("row", "delete") },
] },
{ label: "Column", icon: "column", children: [
{ label: "Add column to the left", icon: "column-before", run: () => structural("column", "before") },
{ label: "Add column to the right", icon: "column-after", run: () => structural("column", "after") }, sep,
{ label: "Move column left", icon: "move-left", disabled: column === 0, run: () => structural("column", "previous") },
{ label: "Move column right", icon: "move-right", disabled: column === lastColumn, run: () => structural("column", "next") }, sep,
{ label: tr("Column"), icon: "column", children: [
{ label: tr("Add column to the left"), icon: "column-before", run: () => structural("column", "before") },
{ label: tr("Add column to the right"), icon: "column-after", run: () => structural("column", "after") }, sep,
{ label: tr("Move column left"), icon: "move-left", disabled: column === 0, run: () => structural("column", "previous") },
{ label: tr("Move column right"), icon: "move-right", disabled: column === lastColumn, run: () => structural("column", "next") }, sep,
...alignmentItems, sep,
{ label: "Duplicate column", icon: "copy", run: () => structural("column", "duplicate") },
{ label: "Delete column", icon: "trash", run: () => structural("column", "delete") },
{ label: tr("Duplicate column"), icon: "copy", run: () => structural("column", "duplicate") },
{ label: tr("Delete column"), icon: "trash", run: () => structural("column", "delete") },
] }, sep,
{ label: "Sort by column (A to Z)", icon: "sort-asc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column)); } },
{ label: "Sort by column (Z to A)", icon: "sort-desc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column, true)); } },
{ label: tr("Sort by column (A to Z)"), icon: "sort-asc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column)); } },
{ label: tr("Sort by column (Z to A)"), icon: "sort-desc", disabled: lastRow < 2, run: () => { range ??= cellRange; apply(text => sortTableColumn(text, column, true)); } },
);
menu = actionMenu(x, y, items, returnFocus);
}
+34 -33
View File
@@ -1,3 +1,4 @@
import { tr } from '../i18n/index.ts';
import type { Editor } from "@tiptap/core";
import type { MenuItem } from "../layout/menuTypes";
@@ -47,93 +48,93 @@ export async function pasteClipboard(editor: Editor): Promise<void> {
export function writerContextItems(editor: Editor): MenuItem[] {
const inTable = editor.isActive("table");
return [
{ kind: "action", label: "Cut", run: () => void cutSelection(editor) },
{ kind: "action", label: "Copy", run: () => void copySelection(editor) },
{ kind: "action", label: "Paste", run: () => void pasteClipboard(editor) },
{ kind: "action", label: tr("Cut"), run: () => void cutSelection(editor) },
{ kind: "action", label: tr("Copy"), run: () => void copySelection(editor) },
{ kind: "action", label: tr("Paste"), run: () => void pasteClipboard(editor) },
{ kind: "sep" },
{
kind: "group",
label: "Style",
label: tr("Style"),
items: [
{ kind: "action", label: "Heading 1", run: () => editor.chain().focus().toggleHeading({ level: 1 }).run() },
{ kind: "action", label: "Heading 2", run: () => editor.chain().focus().toggleHeading({ level: 2 }).run() },
{ kind: "action", label: "Heading 3", run: () => editor.chain().focus().toggleHeading({ level: 3 }).run() },
{ kind: "action", label: "Heading 4", run: () => editor.chain().focus().toggleHeading({ level: 4 }).run() },
{ kind: "action", label: "Heading 5", run: () => editor.chain().focus().toggleHeading({ level: 5 }).run() },
{ kind: "action", label: "Heading 6", run: () => editor.chain().focus().toggleHeading({ level: 6 }).run() },
{ kind: "action", label: "Body", run: () => editor.chain().focus().setParagraph().run() },
{ kind: "action", label: "Quote", run: () => editor.chain().focus().toggleBlockquote().run() },
{ kind: "action", label: tr("Heading {level}", { level: 1 }), run: () => editor.chain().focus().toggleHeading({ level: 1 }).run() },
{ kind: "action", label: tr("Heading {level}", { level: 2 }), run: () => editor.chain().focus().toggleHeading({ level: 2 }).run() },
{ kind: "action", label: tr("Heading {level}", { level: 3 }), run: () => editor.chain().focus().toggleHeading({ level: 3 }).run() },
{ kind: "action", label: tr("Heading {level}", { level: 4 }), run: () => editor.chain().focus().toggleHeading({ level: 4 }).run() },
{ kind: "action", label: tr("Heading {level}", { level: 5 }), run: () => editor.chain().focus().toggleHeading({ level: 5 }).run() },
{ kind: "action", label: tr("Heading {level}", { level: 6 }), run: () => editor.chain().focus().toggleHeading({ level: 6 }).run() },
{ kind: "action", label: tr("Body"), run: () => editor.chain().focus().setParagraph().run() },
{ kind: "action", label: tr("Quote"), run: () => editor.chain().focus().toggleBlockquote().run() },
{ kind: "sep" },
{ kind: "action", label: "Bullet list", run: () => editor.chain().focus().toggleBulletList().run() },
{ kind: "action", label: "Numbered list", run: () => editor.chain().focus().toggleOrderedList().run() },
{ kind: "action", label: "Task list", run: () => editor.chain().focus().toggleTaskList().run() },
{ kind: "action", label: tr("Bullet list"), run: () => editor.chain().focus().toggleBulletList().run() },
{ kind: "action", label: tr("Numbered list"), run: () => editor.chain().focus().toggleOrderedList().run() },
{ kind: "action", label: tr("Task list"), run: () => editor.chain().focus().toggleTaskList().run() },
],
},
{
kind: "group",
label: "Format",
label: tr("Format"),
items: [
{ kind: "action", label: "Bold", run: () => editor.chain().focus().toggleBold().run() },
{ kind: "action", label: "Italic", run: () => editor.chain().focus().toggleItalic().run() },
{ kind: "action", label: "Strikethrough", run: () => editor.chain().focus().toggleStrike().run() },
{ kind: "action", label: "Highlight", run: () => editor.chain().focus().toggleHighlight().run() },
{ kind: "action", label: "Code", run: () => editor.chain().focus().toggleCode().run() },
{ kind: "action", label: "Math", run: () => editor.chain().focus().toggleMark("math").run() },
{ kind: "action", label: "Comment", run: () => editor.chain().focus().toggleMark("comment").run() },
{ kind: "action", label: tr("Bold"), run: () => editor.chain().focus().toggleBold().run() },
{ kind: "action", label: tr("Italic"), run: () => editor.chain().focus().toggleItalic().run() },
{ kind: "action", label: tr("Strikethrough"), run: () => editor.chain().focus().toggleStrike().run() },
{ kind: "action", label: tr("Highlight"), run: () => editor.chain().focus().toggleHighlight().run() },
{ kind: "action", label: tr("Code"), run: () => editor.chain().focus().toggleCode().run() },
{ kind: "action", label: tr("Math"), run: () => editor.chain().focus().toggleMark("math").run() },
{ kind: "action", label: tr("Comment"), run: () => editor.chain().focus().toggleMark("comment").run() },
{ kind: "sep" },
{ kind: "action", label: "Clear formatting", run: () => editor.chain().focus().unsetAllMarks().run() },
{ kind: "action", label: tr("Clear formatting"), run: () => editor.chain().focus().unsetAllMarks().run() },
],
},
{
kind: "group",
label: "Table",
label: tr("Table"),
items: [
{
kind: "action",
label: "Insert table",
label: tr("Insert table"),
run: () => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run(),
},
{ kind: "sep" },
{
kind: "action",
label: "Add row above",
label: tr("Add row above"),
disabled: !inTable,
run: () => editor.chain().focus().addRowBefore().run(),
},
{
kind: "action",
label: "Add row below",
label: tr("Add row below"),
disabled: !inTable,
run: () => editor.chain().focus().addRowAfter().run(),
},
{
kind: "action",
label: "Delete row",
label: tr("Delete row"),
disabled: !inTable,
run: () => editor.chain().focus().deleteRow().run(),
},
{ kind: "sep" },
{
kind: "action",
label: "Add column left",
label: tr("Add column left"),
disabled: !inTable,
run: () => editor.chain().focus().addColumnBefore().run(),
},
{
kind: "action",
label: "Add column right",
label: tr("Add column right"),
disabled: !inTable,
run: () => editor.chain().focus().addColumnAfter().run(),
},
{
kind: "action",
label: "Delete column",
label: tr("Delete column"),
disabled: !inTable,
run: () => editor.chain().focus().deleteColumn().run(),
},
{
kind: "action",
label: "Delete table",
label: tr("Delete table"),
disabled: !inTable,
run: () => editor.chain().focus().deleteTable().run(),
},
+40
View File
@@ -0,0 +1,40 @@
import { derived, get, writable } from 'svelte/store';
import { catalogs, type Locale } from './messages.ts';
export { type Locale } from './messages.ts';
export const LANGUAGE_KEY = 'runestone.language';
export const LANGUAGES: { id: Locale; name: string }[] = [
{ id: 'en', name: 'English' }, { id: 'fr', name: 'Français' },
{ id: 'ja', name: '日本語' }, { id: 'zh-CN', name: '简体中文' },
];
export function normalizeLocale(value: unknown): Locale {
return LANGUAGES.some(item => item.id === value) ? value as Locale : 'en';
}
export const locale = writable<Locale>('en');
export function translate(language: Locale, message: string, values: Record<string, string | number> = {}): string {
const template = language === 'en' || !Object.hasOwn(catalogs[language], message) ? message : catalogs[language][message];
return template.replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
}
export const t = derived(locale, language => (message: string, values?: Record<string, string | number>) => translate(language, message, values));
export function tr(message: string, values?: Record<string, string | number>): string {
return translate(get(locale), message, values);
}
function applyLocale(language: Locale) {
locale.set(language);
if (typeof document !== 'undefined') document.documentElement.lang = language;
}
export function setLocale(language: Locale) {
const valid = normalizeLocale(language);
localStorage.setItem(LANGUAGE_KEY, valid);
applyLocale(valid);
}
export function syncLocale() {
const read = () => {
try { applyLocale(normalizeLocale(localStorage.getItem(LANGUAGE_KEY))); }
catch { applyLocale('en'); }
};
const sync = (event: StorageEvent) => { if (event.key === LANGUAGE_KEY || event.key === null) read(); };
read();
window.addEventListener('storage', sync);
window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
}
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { loadMarks } from "$lib/workspace/marks";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
import type { TreeEntry } from "$lib/workspace/types";
@@ -20,10 +21,10 @@
</script>
<div class="pane">
<div class="pane-label">Bookmarks</div>
<div class="pane-label">{$t("Bookmarks")}</div>
<BrowserSlot kind="bookmarks" />
{#if bookmarks.length === 0}
<p class="placeholder">Right-click a file and choose Bookmark.</p>
<p class="placeholder">{$t("Right-click a file and choose Bookmark.")}</p>
{:else}
<ul>
{#each bookmarks as rel (rel)}
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { tick, untrack } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { pluginHost } from "$lib/plugins/registry";
@@ -75,12 +76,12 @@
</script>
<svelte:window onkeydown={keydown} />
<div class="browser-window" role="application" aria-label="RuneStone browser">
<div class="browser-window" role="application" aria-label={$t("RuneStone browser")}>
<header class="header" data-tauri-drag-region>
<TabBar {tabs} activePath={active} onSelect={select} onClose={close} onCloseTabs={close}
onMove={move} onPin={pinPluginEditor} fileActions={() => []} tabActions={actions}
tabDragData={dragData} onDropTab={(data, index) => void receive(data, index)} />
<IconButton icon="plus" label="New browser tab (Ctrl T)" disabled={!browser?.newTab || opening} onclick={() => void newTab()} />
<IconButton icon="plus" label={$t("New browser tab (Ctrl T)")} disabled={!browser?.newTab || opening} onclick={() => void newTab()} />
<div class="window-drag-space" data-tauri-drag-region></div>
<WindowControls onError={message => error = message} />
</header>
+15 -14
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { pluginHost } from "$lib/plugins/registry";
import type { GitLineInfo } from "$lib/git/contracts";
import EditorHost from "$lib/editor/EditorHost.svelte";
@@ -128,18 +129,18 @@
{#if !buffer || buffer.kind === "empty"}
<div class="empty">
{#if onCloseSplit}<IconButton icon="close" label="Close split" onclick={onCloseSplit} />{/if}
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
<div class="welcome-actions">
{#if hasWorkspace}
<div class="welcome-row">
<button onclick={onNewFile}><Icon icon="file-plus" /> New file <kbd>Ctrl N</kbd></button>
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> New note</button>{/if}
<button onclick={onQuickOpen}><Icon icon="search" /> Find file <kbd>Ctrl P</kbd></button>
<button onclick={onNewFile}><Icon icon="file-plus" /> {$t("New file")} <kbd>Ctrl N</kbd></button>
{#if onNewNote}<button onclick={onNewNote}><Icon icon="pen" /> {$t("New note")}</button>{/if}
<button onclick={onQuickOpen}><Icon icon="search" /> {$t("Find file")} <kbd>Ctrl P</kbd></button>
</div>
{/if}
<div class="welcome-row">
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> Open folder <kbd>Ctrl O</kbd></button>
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? "Opening browser…" : "Open browser"}</button>{/if}
<button onclick={onOpenWorkspace}><Icon icon="folder-open" /> {$t("Open folder")} <kbd>Ctrl O</kbd></button>
{#if onOpenBrowser}<button onclick={onOpenBrowser} disabled={browserOpening}><Icon icon="globe" /> {browserOpening ? $t("Opening browser…") : $t("Open browser")}</button>{/if}
</div>
</div>
</div>
@@ -153,25 +154,25 @@
</span>
{/if}
<div class="actions" bind:this={modeControls}>
{#if onCloseSplit}<IconButton icon="close" label="Close split" onclick={onCloseSplit} />{/if}
{#if onCloseSplit}<IconButton icon="close" label={$t("Close split")} onclick={onCloseSplit} />{/if}
{#if canPreview}
<ModeSwitcher
label="Document view"
label={$t("Document view")}
value={documentMode}
options={[
{ value: "edit", label: "Edit", icon: "pen" },
{ value: "read", label: "Read", icon: "book-open" },
{ value: "split", label: "Split", icon: "split" },
{ value: "edit", label: $t("Edit"), icon: "pen" },
{ value: "read", label: $t("Read"), icon: "book-open" },
{ value: "split", label: $t("Split"), icon: "split" },
]}
onchange={setDocumentMode}
/>
{/if}
<ModeSwitcher
label="Editor layout"
label={$t("Editor layout")}
value={chrome}
options={[
{ value: "Ide", label: "IDE", icon: "code" },
{ value: "Writing", label: "Writer", icon: "text" },
{ value: "Ide", label: $t("IDE"), icon: "code" },
{ value: "Writing", label: $t("Writer"), icon: "text" },
]}
shortcut=" (Ctrl E)"
onchange={(mode) => { if (mode !== chrome) onToggleChrome?.(); }}
+42 -42
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount, tick, untrack } from "svelte";
import { createNote, noteTemplates, type NoteTemplate } from "$lib/workspace/templates";
import { confirm } from "@tauri-apps/plugin-dialog";
@@ -19,7 +20,6 @@
import { moveMarks, replayMoveMarks } from "$lib/workspace/treeMoveHistory";
import { actionEntries, selectionRoots, setSelectedMarks, runTreeActions } from "$lib/workspace/treeActions";
import {
dropHint,
dropPlaceAt,
joinRel,
parentRel,
@@ -478,7 +478,7 @@
if (workspaceRoot !== operationRoot || error) return;
}
} else {
const typed = await requestText("File name, including any extension", "Untitled");
const typed = await requestText($t("File name, including any extension"), "Untitled");
if (!typed) {
return;
}
@@ -685,10 +685,10 @@
async function deleteEntries(entries: TreeEntry[]) {
const roots = selectionRoots(entries);
const message = entries.length === 1
? `Permanently delete ${entries[0].name}${entries[0].kind === "folder" ? " and everything inside it" : ""}?`
: `Permanently delete ${entries.length} selected items${entries.some(entry => entry.kind === "folder") ? " and all contents of selected folders" : ""}?\n\n${roots.map(entry => entry.rel_path).join("\n")}`;
? $t(entries[0].kind === "folder" ? "Permanently delete {name} and everything inside it?" : "Permanently delete {name}?", { name: entries[0].name })
: $t(entries.some(entry => entry.kind === "folder") ? "Permanently delete {count} selected items and all contents of selected folders?" : "Permanently delete {count} selected items?", { count: entries.length }) + "\n\n" + roots.map(entry => entry.rel_path).join("\n");
try {
if (!await confirm(message, { title: "Delete from disk", kind: "warning" })) return;
if (!await confirm(message, { title: $t("Delete from disk"), kind: "warning" })) return;
const result = await runTreeActions(roots, async entry => {
await workspaceDelete(entry.rel_path);
forgetFolder(entry.rel_path);
@@ -696,7 +696,7 @@
});
for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent);
error = result.failures.length ? result.failures.join("\n") : null;
onStatus?.(`Deleted ${result.completed.length} of ${roots.length} items`);
onStatus?.($t("Deleted {count} of {total} items", { count: result.completed.length, total: roots.length }));
} catch (err) {
error = err instanceof Error ? err.message : String(err);
}
@@ -713,16 +713,16 @@
return [
{
kind: "action",
label: "New file…",
label: $t("New file…"),
icon: "file-plus",
run: () => { void createIn(parent, "file"); },
},
...(templates.length || onManageTemplates ? [{ kind: "group" as const, label: "New note", icon: "file-plus" as const, run: () => { void fromTemplate(); }, items: [
{ kind: "action" as const, label: "Blank note", icon: "file-plus" as const, run: () => { void fromTemplate(); } },
...(templates.length || onManageTemplates ? [{ kind: "group" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); }, items: [
{ kind: "action" as const, label: $t("Blank note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } },
...templates.map(template => ({ kind: "action" as const, label: template.name, icon: "file-plus" as const, run: () => { void fromTemplate(template); } })),
...(onManageTemplates ? [{ kind: "sep" as const }, { kind: "action" as const, label: "Manage templates…", icon: "copy" as const, run: onManageTemplates }] : []),
] }] : [{ kind: "action" as const, label: "New note", icon: "file-plus" as const, run: () => { void fromTemplate(); } }]),
{ kind: "action", label: "New folder", icon: "folder-plus", run: () => { void createIn(parent, "folder"); } },
...(onManageTemplates ? [{ kind: "sep" as const }, { kind: "action" as const, label: $t("Manage templates…"), icon: "copy" as const, run: onManageTemplates }] : []),
] }] : [{ kind: "action" as const, label: $t("New note"), icon: "file-plus" as const, run: () => { void fromTemplate(); } }]),
{ kind: "action", label: $t("New folder"), icon: "folder-plus", run: () => { void createIn(parent, "folder"); } },
...$pluginDocumentTypes.filter(item => item.type.create).map(({ owner, type }): MenuItem => ({
kind: "action", label: type.create!.label, icon: type.icon === "kanban" ? "kanban" : "file-plus",
run: () => { void (async () => {
@@ -730,7 +730,7 @@
const typed = await requestText(create.label, create.defaultName);
if (typed === null) return;
const name = typed.trim().replace(new RegExp(`\\.${create.extension}$`, "i"), "");
if (!name || name.length > 100 || /[<>:"/\\|?*\x00-\x1f]/.test(name) || /[. ]$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) { error = "Enter a valid document name."; return; }
if (!name || name.length > 100 || /[<>:"/\\|?*\x00-\x1f]/.test(name) || /[. ]$/.test(name) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) { error = $t("Enter a valid document name."); return; }
const fileName = `${name}.${create.extension}`;
const path = joinRel(parent, fileName);
try {
@@ -746,11 +746,11 @@
function folderActions(parent: string): MenuItem[] {
return [
{ kind: "action", label: "Open in terminal", icon: "terminal", run: () => { void workspaceOpenTerminal(parent).catch(reason => error = String(reason)); } },
{ kind: "action", label: "Paste", icon: "paste", disabled: !clipboard || clipboard.root !== workspaceRoot || moving, run: () => { void pasteEntries(parent); } },
{ kind: "action", label: $t("Open in terminal"), icon: "terminal", run: () => { void workspaceOpenTerminal(parent).catch(reason => error = String(reason)); } },
{ kind: "action", label: $t("Paste"), icon: "paste", disabled: !clipboard || clipboard.root !== workspaceRoot || moving, run: () => { void pasteEntries(parent); } },
{ kind: "sep" },
{ kind: "action", label: undoMoves.at(-1)?.action === "rename" ? "Undo rename" : "Undo file move", icon: "undo", disabled: !undoMoves.length || moving, run: () => { void replayMoves(); } },
{ kind: "action", label: redoMoves.at(-1)?.action === "rename" ? "Redo rename" : "Redo file move", icon: "redo", disabled: !redoMoves.length || moving, run: () => { void replayMoves(true); } },
{ kind: "action", label: undoMoves.at(-1)?.action === "rename" ? $t("Undo rename") : $t("Undo file move"), icon: "undo", disabled: !undoMoves.length || moving, run: () => { void replayMoves(); } },
{ kind: "action", label: redoMoves.at(-1)?.action === "rename" ? $t("Redo rename") : $t("Redo file move"), icon: "redo", disabled: !redoMoves.length || moving, run: () => { void replayMoves(true); } },
];
}
@@ -763,7 +763,7 @@
{ kind: "sep" },
{
kind: "action",
label: "Show in Explorer",
label: $t("Show in Explorer"),
icon: "folder",
run: () => {
void workspaceReveal("").catch((err) => {
@@ -784,25 +784,25 @@
return [
...createItems,
...(!multiple && entry.kind === "file" && /\.md$/i.test(entry.name) && onSaveTemplate ? [
{ kind: "action" as const, label: "Save as template", icon: "copy" as const, run: () => onSaveTemplate?.(entry) },
{ kind: "action" as const, label: $t("Save as template"), icon: "copy" as const, run: () => onSaveTemplate?.(entry) },
] : []),
...(!multiple && entry.kind === "file" ? [
{ kind: "action" as const, label: "Open in new tab", icon: "file-plus" as const, run: () => onOpenFile(entry, true) },
{ kind: "action" as const, label: "Open in default app", icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
{ kind: "action" as const, label: $t("Open in new tab"), icon: "file-plus" as const, run: () => onOpenFile(entry, true) },
{ kind: "action" as const, label: $t("Open in default app"), icon: "external" as const, run: () => { void workspaceOpenDefault(entry.rel_path).catch(reason => error = String(reason)); } },
] : []),
...folderActions(entry.kind === "folder" ? entry.rel_path : parentRel(entry.rel_path)),
{ kind: "sep" },
{ kind: "action", label: "Cut", icon: "cut", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: true }; } },
{ kind: "action", label: "Copy", icon: "copy", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: false }; } },
{ kind: "action", label: $t("Cut"), icon: "cut", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: true }; } },
{ kind: "action", label: $t("Copy"), icon: "copy", run: () => { clipboard = { root: workspaceRoot, paths: selectionRoots(entries).map(item => item.rel_path), cut: false }; } },
{
kind: "action",
label: multiple ? `Make copies (${entries.length})` : "Make a copy",
label: multiple ? $t("Make copies ({count})", { count: entries.length }) : $t("Make a copy"),
icon: "copy",
run: () => { void copyEntries(entries); },
},
{
kind: "action",
label: bookmarked ? (multiple ? "Remove bookmarks" : "Remove bookmark") : "Bookmark",
label: bookmarked ? (multiple ? $t("Remove bookmarks") : $t("Remove bookmark")) : $t("Bookmark"),
icon: "bookmark",
run: () => {
void persistMarks({
@@ -814,7 +814,7 @@
{ kind: "sep" },
{
kind: "action",
label: multiple ? "Copy workspace paths" : "Copy workspace path",
label: multiple ? $t("Copy workspace paths") : $t("Copy workspace path"),
icon: "copy",
run: () => {
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path");
@@ -822,7 +822,7 @@
},
{
kind: "action",
label: multiple ? "Copy system paths" : "Copy system path",
label: multiple ? $t("Copy system paths") : $t("Copy system path"),
icon: "copy",
run: () => {
void (async () => {
@@ -837,7 +837,7 @@
},
{
kind: "action",
label: "Show in Explorer",
label: $t("Show in Explorer"),
icon: "folder",
run: () => {
void (async () => {
@@ -849,7 +849,7 @@
{ kind: "sep" },
{
kind: "action",
label: pinned ? "Unpin" : "Pin",
label: pinned ? $t("Unpin") : $t("Pin"),
icon: "pin",
run: () => {
void persistMarks({
@@ -860,7 +860,7 @@
},
{
kind: "action",
label: "Rename",
label: $t("Rename"),
icon: "rename",
disabled: multiple,
run: () => {
@@ -869,7 +869,7 @@
},
{
kind: "action",
label: multiple ? `Delete (${entries.length})` : "Delete",
label: multiple ? $t("Delete ({count})", { count: entries.length }) : $t("Delete"),
icon: "trash",
run: () => { void deleteEntries(entries); },
},
@@ -881,16 +881,16 @@
<div class="wrap">
<div class="ribbon tree-tools">
<IconButton icon="file-plus" label="New file" onclick={() => void createIn("", "file")} />
<IconButton icon="folder-plus" label="New folder" onclick={() => void createIn("", "folder")} />
<IconButton icon="file-plus" label={$t("New file")} onclick={() => void createIn("", "file")} />
<IconButton icon="folder-plus" label={$t("New folder")} onclick={() => void createIn("", "folder")} />
<IconButton
icon="sort"
label={sortMode === "custom" ? "Sort: custom" : sortMode === "name" ? "Sort: name" : "Sort: name Z-A"}
label={sortMode === "custom" ? $t("Sort: custom") : sortMode === "name" ? $t("Sort: name") : $t("Sort: name Z-A")}
onclick={cycleSort}
/>
<IconButton
icon={allCollapsed ? "unfold" : "fold"}
label={allCollapsed ? "Expand all" : "Collapse all"}
label={allCollapsed ? $t("Expand all") : $t("Collapse all")}
onclick={() => {
if (allCollapsed) {
void expandAll();
@@ -905,7 +905,7 @@
class="tree"
tabindex="-1"
role="navigation"
aria-label="Workspace files"
aria-label={$t("Workspace files")}
oncontextmenu={(event) => {
event.preventDefault();
menu = { x: event.clientX, y: event.clientY, entry: null };
@@ -915,10 +915,10 @@
<p class="error">{error}</p>
{/if}
{#if loading && !childrenMap[""]}
<p class="muted">Loading…</p>
<p class="muted">{$t("Loading…")}</p>
{/if}
{#if childrenMap[""]}
<ul role="tree" aria-label="Workspace files" aria-multiselectable="true">
<ul role="tree" aria-label={$t("Workspace files")} aria-multiselectable="true">
{#each childrenMap[""] as entry (entry.rel_path)}
<TreeNode
{entry}
@@ -952,18 +952,18 @@
{#if dragRel && dragPoint}
{@const landing = dropTarget ? findEntry(dropTarget.rel) : null}
<div class="drag-ghost" style:left="{dragPoint.x + 12}px" style:top="{dragPoint.y + 12}px">
<span>{dragEntries.length > 1 ? `${dragEntries.length} items` : dragRel.split("/").pop()}</span>
<span>{dragEntries.length > 1 ? $t("{count} items", { count: dragEntries.length }) : dragRel.split("/").pop()}</span>
{#if imageLanding}
<span class="hint">{isImagePath(dragRel ?? "") ? "Insert image" : "Insert link"}</span>
<span class="hint">{isImagePath(dragRel ?? "") ? $t("Insert image") : $t("Insert link")}</span>
{:else if landing && dropTarget}
<span class="hint">{dropHint(landing.name, dropTarget.place)}</span>
<span class="hint">{$t(dropTarget.place === "inside" ? "Into {name}" : dropTarget.place === "before" ? "Before {name}" : "After {name}", { name: landing.name })}</span>
{/if}
</div>
{/if}
{#if menu}
<ContextMenu
label="File actions"
label={$t("File actions")}
x={menu.x}
y={menu.y}
items={menuItems(menu.entry)}
+7 -6
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { pluginHost } from "$lib/plugins/registry";
import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api";
@@ -112,13 +113,13 @@
}
}
button.dataset.copied = "true";
button.setAttribute("aria-label", "Copied");
button.title = "Copied";
button.setAttribute("aria-label", $t("Copied"));
button.title = $t("Copied");
window.setTimeout(() => {
if (button.isConnected) {
delete button.dataset.copied;
button.setAttribute("aria-label", "Copy code");
button.title = "Copy code";
button.setAttribute("aria-label", $t("Copy code"));
button.title = $t("Copy code");
}
}, 1200);
}
@@ -181,12 +182,12 @@
<h1 class="document-title">{markdownTitle(noteRel)}</h1>
{#if onEditBlock}
{#each sections.filter(section => !editing || section.start < editing.start) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label="Edit document block" data-start={section.start} data-end={section.end}>{@html section.html}</div>
<div class="md-edit-block" role="button" tabindex="0" aria-label={$t("Edit document block")} data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each}
{#if editing && blockEditor}
{@render blockEditor()}
{#each sections.filter(section => section.start >= editing.end && section.end > editing.end) as section (section.start)}
<div class="md-edit-block" role="button" tabindex="0" aria-label="Edit document block" data-start={section.start} data-end={section.end}>{@html section.html}</div>
<div class="md-edit-block" role="button" tabindex="0" aria-label={$t("Edit document block")} data-start={section.start} data-end={section.end}>{@html section.html}</div>
{/each}
{/if}
{:else}
+9 -8
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { tick } from "svelte";
import type { OutlineItem } from "$lib/workspace/outline";
import Icon from "$lib/ui/Icon.svelte";
@@ -47,27 +48,27 @@
</script>
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions (The outline accepts focus for pane-local search shortcuts.) -->
<section class="outline" aria-label="Outline" tabindex="0" bind:this={pane} onkeydown={keydown}>
<section class="outline" aria-label={$t("Outline")} tabindex="0" bind:this={pane} onkeydown={keydown}>
<div class="pane-label">
<span>Outline</span>
<IconButton icon="search" label="Find in outline (Ctrl+F)" active={searchOpen} onclick={() => void openSearch()} />
<span>{$t("Outline")}</span>
<IconButton icon="search" label={$t("Find in outline (Ctrl+F)")} active={searchOpen} onclick={() => void openSearch()} />
</div>
{#if searchOpen}
<div class="rs-find-bar outline-search">
<div class="rs-find-row">
<div class="rs-find-field">
<Icon icon="search" />
<input bind:this={searchInput} bind:value={query} aria-label="Find in outline" placeholder="Find in outline" />
<input bind:this={searchInput} bind:value={query} aria-label={$t("Find in outline")} placeholder={$t("Find in outline")} />
</div>
<IconButton icon="close" label="Close outline find (Escape)" onclick={closeSearch} />
<IconButton icon="close" label={$t("Close outline find (Escape)")} onclick={closeSearch} />
</div>
<span class="match-count" role="status">{visibleItems.length} of {items.length} headings or symbols</span>
<span class="match-count" role="status">{$t("{visible} of {total} headings or symbols", { visible: visibleItems.length, total: items.length })}</span>
</div>
{/if}
{#if items.length === 0}
<p class="placeholder">No headings or symbols in this file.</p>
<p class="placeholder">{$t("No headings or symbols in this file.")}</p>
{:else if visibleItems.length === 0}
<p class="placeholder">No matching headings or symbols.</p>
<p class="placeholder">{$t("No matching headings or symbols.")}</p>
{:else}
<ul>
{#each visibleItems as item (item.line + item.text)}
+5 -4
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { workspaceList } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types";
import { onMount } from "svelte";
@@ -33,11 +34,11 @@
});
</script>
<dialog class="rs-picker" bind:this={dialog} aria-label={purpose} onpointerdown={(event) => {
<dialog class="rs-picker" bind:this={dialog} aria-label={$t(purpose)} onpointerdown={(event) => {
const bounds = dialog.getBoundingClientRect();
if (event.target === dialog && (event.clientX < bounds.left || event.clientX > bounds.right || event.clientY < bounds.top || event.clientY > bounds.bottom)) onClose();
}} oncancel={onClose}>
<input bind:this={input} bind:value={query} oninput={() => selected = 0} aria-label="Find a file" placeholder="Find a note or code file…" onkeydown={(event) => {
<input bind:this={input} bind:value={query} oninput={() => selected = 0} aria-label={$t("Find a file")} placeholder={$t("Find a note or code file…")} onkeydown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault(); selected = Math.max(0, Math.min(matches.length - 1, selected + (event.key === "ArrowDown" ? 1 : -1)));
dialog.querySelector(`[data-index="${selected}"]`)?.scrollIntoView({ block: "nearest" });
@@ -48,9 +49,9 @@
{#each matches as entry, index (entry.rel_path)}
<button class="rs-picker-row" data-index={index} aria-current={selected === index ? 'true' : undefined} onclick={() => pick(entry)}><span class="file-detail"><strong>{entry.name}</strong><span class="rs-picker-hint">{entry.rel_path}</span></span></button>
{/each}
{#if !matches.length}<p>{loading ? "Finding files…" : "No matching files."}</p>{/if}
{#if !matches.length}<p>{loading ? $t("Finding files…") : $t("No matching files.")}</p>{/if}
</div>
<footer>{error || `${files.length} files${loading ? " · indexing…" : ""}`} <span>↑ ↓ select · Enter {actionLabel} · Esc close</span></footer>
<footer>{error || `${files.length} files${loading ? $t(" · indexing…") : ""}`} <span>{$t("↑ ↓ select · Enter {action} · Esc close", { action: $t(actionLabel) })}</span></footer>
</dialog>
<style>
+4 -3
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import { workspaceSearch, type SearchHit } from "$lib/workspace/api";
import type { TreeEntry } from "$lib/workspace/types";
@@ -36,7 +37,7 @@
</script>
<div class="pane">
<div class="pane-label">Search</div>
<div class="pane-label">{$t("Search")}</div>
<form
class="bar"
onsubmit={(event) => {
@@ -44,8 +45,8 @@
void run();
}}
>
<input bind:value={query} placeholder="Search files and notes" />
<IconButton icon="search" label="Search workspace" type="submit" />
<input bind:value={query} placeholder={$t("Search files and notes")} />
<IconButton icon="search" label={$t("Search workspace")} type="submit" />
</form>
{#if error}
<p class="error">{error}</p>
+50 -33
View File
@@ -1,4 +1,7 @@
<script lang="ts">
import { t, locale, LANGUAGES, setLocale } from "$lib/i18n";
import { showActionMenu } from "$lib/ui/managedActionMenu";
import { onDestroy } from "svelte";
import PluginManager from "$lib/plugins/PluginManager.svelte";
import AppearanceSettings from "$lib/theme/AppearanceSettings.svelte";
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
@@ -20,13 +23,23 @@
onSave: (value: AppSettings) => void;
onClose: () => void;
} = $props();
let closeLanguage = () => {};
onDestroy(() => closeLanguage());
function languagePicker(event: MouseEvent) {
closeLanguage();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closeLanguage = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: $t("Language"), parent: dialog,
items: LANGUAGES.map(item => ({ label: item.name, radio: true, checked: $locale === item.id,
run: () => { try { setLocale(item.id); error = ""; message = $t("Changes saved."); } catch { error = $t("Could not save language settings."); } } })) }).close;
}
type Section = string;
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = [
{ id: "about", label: "Help and about", icon: "help", keywords: "help about version shortcuts keyboard guide" },
{ id: "general", label: "General", icon: "settings", keywords: "auto-save autosave save interval seconds files" },
{ id: "appearance", label: "Appearance", icon: "sun", keywords: "theme colors light dark Claude Sakura Harvest Moon Crimson Pilot Silver Serpent" },
{ id: "plugins", label: "Plug-ins", icon: "puzzle", keywords: "plugins extensions community" },
];
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = $derived([
{ id: "about", label: $t("Help and about"), icon: "help", keywords: "help about version shortcuts keyboard guide" },
{ id: "general", label: $t("General"), icon: "settings", keywords: "auto-save autosave save interval seconds files language français 日本語 简体中文" },
{ id: "appearance", label: $t("Appearance"), icon: "sun", keywords: "theme colors light dark Claude Sakura Harvest Moon Crimson Pilot Silver Serpent" },
{ id: "plugins", label: $t("Plug-ins"), icon: "puzzle", keywords: "plugins extensions community" },
]);
let section = $state<Section>(untrack(() => help ? "about" : "general"));
let query = $state("");
let seconds = $state<number | undefined>(untrack(() => settings.autosaveSeconds));
@@ -39,7 +52,7 @@
label: tool.title, icon: "settings" as const,
keywords: `${$installedPlugins.plugins.find(row => row.manifest.id === tool.owner)?.manifest.name ?? tool.owner} settings configuration`,
})));
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: "Browser", icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
const matches = $derived([...sections, ...(browserEnabled ? [{ id: "browser" as const, label: $t("Browser"), icon: "globe" as const, keywords: "browser profiles search cookies cache web privacy" }] : []), ...pluginSections].filter(item => `${item.label} ${item.keywords}`.toLowerCase().includes(query.trim().toLowerCase())));
const selected = $derived(matches.find(item => item.id === section) ?? matches[0]);
const selectedPlugin = $derived(pluginSections.find(item => item.id === selected?.id));
@@ -52,13 +65,13 @@
function apply(value: AppSettings) {
error = "";
try { onSave(value); message = "Changes saved."; }
catch { error = "Could not save these settings. Your previous settings still apply. Try again."; message = ""; }
try { onSave(value); message = $t("Changes saved."); }
catch { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; }
}
function changeInterval() {
if (!validAutosaveSeconds(seconds)) {
error = "Choose a whole number from 1 to 300 seconds.";
error = $t("Choose a whole number from 1 to 300 seconds.");
message = "";
return;
}
@@ -80,52 +93,54 @@
<dialog bind:this={dialog} class:help class:standalone aria-labelledby="settings-title" onkeydown={trapFocus} oncancel={event => { if (event.target === dialog) { event.preventDefault(); onClose(); } }}>
<header class:window-header={!!windowControls} data-tauri-drag-region={windowControls ? true : undefined}>
<h1 id="settings-title" data-tauri-drag-region={windowControls ? true : undefined}>{help ? "Help and about" : "Settings"}</h1>
<h1 id="settings-title" data-tauri-drag-region={windowControls ? true : undefined}>{help ? $t("Help and about") : $t("Settings")}</h1>
{#if windowControls}
{@render windowControls()}
{:else}
<IconButton icon="close" label={help ? "Close help" : "Close settings"} onclick={onClose} />
<IconButton icon="close" label={help ? $t("Close help") : $t("Close settings")} onclick={onClose} />
{/if}
</header>
<div class="body">
{#if !help}
<aside>
<label class="search"><Icon icon="search" /><input aria-label="Search settings" placeholder="Search settings…" bind:value={query} /></label>
<p class="nav-heading">Preferences</p>
<nav aria-label="Settings categories">
<label class="search"><Icon icon="search" /><input aria-label={$t("Search settings")} placeholder={$t("Search settings…")} bind:value={query} /></label>
<p class="nav-heading">{$t("Preferences")}</p>
<nav aria-label={$t("Settings categories")}>
{#each matches as item}
<button class:active={selected?.id === item.id} aria-current={selected?.id === item.id ? "page" : undefined} onclick={() => select(item.id)}><Icon icon={item.icon} />{item.label}</button>
{/each}
</nav>
<p class="scope">For all workspaces on this device.</p>
<p class="scope">{$t("For all workspaces on this device.")}</p>
</aside>
{/if}
<div class="content">
{#if windowError}<p class="error" role="alert">{windowError}</p>{/if}
{#if !selected}
<h2>No settings found</h2>
<p>Try “save”, “plug-ins”, or “help”.</p>
<button class="text-button" onclick={() => query = ""}>Clear search</button>
<h2>{$t("No settings found")}</h2>
<p>{$t("Try “save”, “plug-ins”, or “help”.")}</p>
<button class="text-button" onclick={() => query = ""}>{$t("Clear search")}</button>
{:else if selected.id === "general"}
<h2>General</h2>
<p class="intro">Choose how RuneStone saves your work.</p>
<h3>Files</h3>
<h2>{$t("General")}</h2>
<p class="intro">{$t("Choose how RuneStone saves your work.")}</p>
<h3>{$t('Language')}</h3>
<div class="card"><div class="setting-row language-row"><div><label for="language-picker">{$t('Display language')}</label><p>{$t('Choose the language for RuneStone controls.')}</p></div><button id="language-picker" class="text-button language-picker" aria-haspopup="menu" onclick={languagePicker}><Icon icon="globe" />{LANGUAGES.find(item => item.id === $locale)?.name}<Icon icon="chevron-down" /></button></div></div>
<h3>{$t("Files")}</h3>
<div class="card">
<div class="setting-row">
<div><label for="show-internal-folder">Show .runestone folder</label><p id="internal-folder-description">Show workspace settings and plugin data in the file tree.</p></div>
<div><label for="show-internal-folder">{$t("Show .runestone folder")}</label><p id="internal-folder-description">{$t("Show workspace settings and plugin data in the file tree.")}</p></div>
<input id="show-internal-folder" class="switch" type="checkbox" role="switch" aria-describedby="internal-folder-description" checked={settings.showInternalFolder} onchange={event => apply({ ...settings, showInternalFolder: event.currentTarget.checked })} />
</div>
<div class="setting-row">
<div><label for="autosave-enabled">Auto-save</label><p id="autosave-description">Save changed notes and scripts, including background tabs.</p></div>
<div><label for="autosave-enabled">{$t("Auto-save")}</label><p id="autosave-description">{$t("Save changed notes and scripts, including background tabs.")}</p></div>
<input id="autosave-enabled" class="switch" type="checkbox" role="switch" aria-describedby="autosave-description" checked={settings.autosaveEnabled} onchange={event => { apply({ ...settings, autosaveEnabled: event.currentTarget.checked }); event.currentTarget.checked = settings.autosaveEnabled; }} />
</div>
<div class="setting-row">
<div><label for="autosave-seconds">Auto-save interval</label><p id="interval-description">Time between saves, even while you type. Choose 1–300 seconds.</p></div>
<div class="interval"><input id="autosave-seconds" type="number" min={MIN_AUTOSAVE_SECONDS} max={MAX_AUTOSAVE_SECONDS} step="1" required disabled={!settings.autosaveEnabled} aria-describedby="interval-description" aria-invalid={!!error} bind:value={seconds} onchange={changeInterval} /><span>seconds</span></div>
<div><label for="autosave-seconds">{$t("Auto-save interval")}</label><p id="interval-description">{$t("Time between saves, even while you type. Choose 1–300 seconds.")}</p></div>
<div class="interval"><input id="autosave-seconds" type="number" min={MIN_AUTOSAVE_SECONDS} max={MAX_AUTOSAVE_SECONDS} step="1" required disabled={!settings.autosaveEnabled} aria-describedby="interval-description" aria-invalid={!!error} bind:value={seconds} onchange={changeInterval} /><span>{$t("seconds")}</span></div>
</div>
</div>
<p class="note">{settings.autosaveEnabled ? "Only changed files are saved." : "Auto-save is off. Use Ctrl+S to save your changes."} Disk conflicts keep your edits for review.</p>
<div class="section-footer"><button class="text-button" onclick={() => { seconds = DEFAULT_SETTINGS.autosaveSeconds; apply({ ...DEFAULT_SETTINGS }); }}>Restore defaults</button><span>Default: every 5 seconds</span></div>
<p class="note">{settings.autosaveEnabled ? $t("Only changed files are saved.") : $t("Auto-save is off. Use Ctrl+S to save your changes.")} {$t("Disk conflicts keep your edits for review.")}</p>
<div class="section-footer"><button class="text-button" onclick={() => { seconds = DEFAULT_SETTINGS.autosaveSeconds; apply({ ...DEFAULT_SETTINGS }); }}>{$t("Restore defaults")}</button><span>{$t("Default: every 5 seconds")}</span></div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<p class="saved" role="status">{message}</p>
{:else if selected.id === "appearance"}
@@ -137,13 +152,13 @@
{:else if selectedPlugin}
{#key selectedPlugin.id}<PluginSettings owner={selectedPlugin.owner} id={selectedPlugin.view} />{/key}
{:else}
<div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>Version {version}</p></div>
<div class="brand"><img src="/runestone.svg" alt="" width="88" height="88" /><h2>RuneStone</h2><p>{$t("Version {version}", { version })}</p></div>
<div class="card help-card">
<details><summary><Icon icon="book-open" /> Get started</summary><div class="help-copy"><p>Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.</p><p>Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.</p><p>Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.</p></div></details>
<details><summary><Icon icon="save" /> Save your work</summary><div class="help-copy"><p>Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.</p><p>If another app changes a file, RuneStone keeps your edits and offers both versions for review.</p></div></details>
<details><summary><Icon icon="code" /> Keyboard shortcuts</summary><dl><div><dt>Open a workspace</dt><dd><kbd>Ctrl+O</kbd></dd></div><div><dt>Find a file</dt><dd><kbd>Ctrl+P</kbd></dd></div><div><dt>Save the active file</dt><dd><kbd>Ctrl+S</kbd></dd></div><div><dt>Search the workspace</dt><dd><kbd>Ctrl+Shift+F</kbd></dd></div><div><dt>Open settings</dt><dd><kbd>Ctrl+,</kbd></dd></div><div><dt>Help and about</dt><dd><kbd>F1</kbd></dd></div></dl></details>
<details><summary><Icon icon="book-open" /> {$t("Get started")}</summary><div class="help-copy"><p>{$t("Use the folder button to open a workspace or create one. Your notes and scripts stay as ordinary files on disk.")}</p><p>{$t("Use the + beside the tabs for a new tab. Press Ctrl+N to create a file, or Ctrl+P to find one.")}</p><p>{$t("Press Ctrl+E to switch between writing and source editing. Use the terminal button to work with a shell beside your files.")}</p></div></details>
<details><summary><Icon icon="save" /> {$t("Save your work")}</summary><div class="help-copy"><p>{$t("Auto-save saves changed files at the interval in Settings → General. Ctrl+S saves the active file immediately.")}</p><p>{$t("If another app changes a file, RuneStone keeps your edits and offers both versions for review.")}</p></div></details>
<details><summary><Icon icon="code" /> {$t("Keyboard shortcuts")}</summary><dl><div><dt>{$t("Open a workspace")}</dt><dd><kbd>Ctrl+O</kbd></dd></div><div><dt>{$t("Find a file")}</dt><dd><kbd>Ctrl+P</kbd></dd></div><div><dt>{$t("Save the active file")}</dt><dd><kbd>Ctrl+S</kbd></dd></div><div><dt>{$t("Search the workspace")}</dt><dd><kbd>Ctrl+Shift+F</kbd></dd></div><div><dt>{$t("Open settings")}</dt><dd><kbd>Ctrl+,</kbd></dd></div><div><dt>{$t("Help and about")}</dt><dd><kbd>F1</kbd></dd></div></dl></details>
</div>
<p class="about-note">RuneStone is under development. Maintained by kwyvern-gh.</p>
<p class="about-note">{$t("RuneStone is under development. Maintained by kwyvern-gh.")}</p>
{/if}
</div>
</div>
@@ -179,6 +194,8 @@
.setting-row + .setting-row { border-top: 1px solid var(--rs-border); }
.setting-row label { font-weight: 500; }
.setting-row p { margin: 3px 0 0; font-size: var(--rs-settings-description-size); }
.language-row { flex-wrap: wrap; }
.language-picker { display:flex; align-items:center; gap:var(--rs-settings-gap); max-width:100%; }
.switch { appearance: none; width: 38px; height: 22px; flex: 0 0 38px; margin: 0; border-radius: 20px; background: var(--rs-bg-active); border: 1px solid var(--rs-text-dim); cursor: pointer; }
.switch::before { content: ""; display: block; width: 16px; height: 16px; margin: 2px; background: var(--rs-text); border-radius: 50%; transition: transform .12s; }
.switch:checked { background: var(--rs-accent); border-color: var(--rs-accent); }
+15 -14
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onDestroy, tick } from "svelte";
import { actionMenu, type ActionMenuItem } from "$lib/ui/actionMenu";
import { actionIcons } from "$lib/ui/actionIcons";
@@ -122,24 +123,24 @@
children: item.children ? wrapActions(item.children) : undefined };
});
menu = actionMenu(x, y, [
closing("Close", "one"),
closing("Close others", "others"),
closing("Close tabs after", "after"),
closing("Close all", "all"),
closing($t("Close"), "one"),
closing($t("Close others"), "others"),
closing($t("Close tabs after"), "after"),
closing($t("Close all"), "all"),
...(tabs[index].pinned !== undefined ? [
{ separator: true as const },
{ label: tabs[index].pinned ? "Unpin" : "Pin", icon: "pin" as const, run: run(() => onPin(path)) },
{ label: tabs[index].pinned ? $t("Unpin") : $t("Pin"), icon: "pin" as const, run: run(() => onPin(path)) },
] : []),
...wrapActions(tabActions(tabs[index])),
...(path === activePath ? wrapActions(fileActions(tabs[index])) : []),
{ separator: true },
{ label: "Move tab", icon: "swap", children: [
{ label: "Move tab left", icon: "move-left", disabled: index <= 0,
{ label: $t("Move tab"), icon: "swap", children: [
{ label: $t("Move tab left"), icon: "move-left", disabled: index <= 0,
run: run(() => { void move(path, index - 1); }) },
{ label: "Move tab right", icon: "move-right", disabled: index === tabs.length - 1,
{ label: $t("Move tab right"), icon: "move-right", disabled: index === tabs.length - 1,
run: run(() => { void move(path, index + 1); }) },
] },
], () => closeMenu(true), "Tab actions");
], () => closeMenu(true), $t("Tab actions"));
menu.classList.add("tab-menu");
}
@@ -255,7 +256,7 @@
<svelte:window onpointerdown={(event) => { if (menu && !menu.contains(event.target as Node)) closeMenu(); }} onresize={() => closeMenu()} />
<div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label="Working tabs" tabindex="-1"
<div bind:this={bar} class="tabs" class:receiving role="tablist" aria-label={$t("Working tabs")} tabindex="-1"
ondragover={dragOver} ondrop={dropTab}
ondragleave={(event) => { if (!(event.relatedTarget instanceof Node) || !bar.contains(event.relatedTarget)) { receiving = false; dropBefore = dropAfter = null; } }}>
{#each tabs as tab (tab.id)}
@@ -270,7 +271,7 @@
aria-controls={tab.panelId}
aria-describedby={tab.pinned ? `tab-pin-${tab.id}` : undefined}
aria-keyshortcuts="Alt+Shift+ArrowLeft Alt+Shift+ArrowRight"
title={`${tab.title}\n${tab.draggable ? "Drag to reorder or move to another RuneStone window." : "Drag to reorder."} Right-click for tab actions.`}
title={`${tab.title}\n${tab.draggable ? $t("Drag to reorder or move to another RuneStone window.") : $t("Drag to reorder.")} ${$t("Right-click for tab actions.")}`}
onclick={() => { if (suppressClick) { suppressClick = false; return; } onSelect(tab.relPath); }}
onpointerdown={(event) => { if (!tab.draggable) startDrag(event, tab.relPath); else suppressClick = false; }}
draggable={!!tab.draggable}
@@ -289,12 +290,12 @@
<TabIcon image={tab.iconImage} icon={tab.icon} />
<span class="tab-label">{tab.name}{tab.dirty ? " •" : ""}</span>
</button>
{#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>Pinned tab</span>{/if}
{#if tab.pinned}<span class="sr-only" id={`tab-pin-${tab.id}`}>{$t("Pinned tab")}</span>{/if}
<button
class="close"
type="button"
aria-label="Close {tab.name}"
title="Close {tab.name}"
aria-label={$t("Close {name}", { name: tab.name })}
title={$t("Close {name}", { name: tab.name })}
onclick={() => onClose(tab.relPath)}
onmousedown={onMiddleDown}
onmouseup={(event) => onMiddleUp(event, tab.relPath)}
+13 -12
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount } from "svelte";
import { confirm } from "@tauri-apps/plugin-dialog";
import { isTauri } from "@tauri-apps/api/core";
@@ -18,7 +19,7 @@
async function refresh() { templates = await noteTemplates(); window.dispatchEvent(new Event("runestone-templates-changed")); }
onMount(() => { dialog.showModal(); void refresh(); });
async function create() {
const name = await requestText("Template name", "New template");
const name = await requestText($t("Template name"), $t("New template"));
if (!name) return;
busy = true; error = "";
try { const path = await saveNoteTemplate(name, ""); await refresh(); edit({ path, name: path.split("/").at(-1)!.replace(/\.md$/i, "") }); }
@@ -26,10 +27,10 @@
finally { busy = false; }
}
async function rename(template: NoteTemplate) {
const name = await requestText("Template name", template.name);
const name = await requestText($t("Template name"), template.name);
if (!name) return;
const title = name.trim().replace(/\.md$/i, "");
if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) { error = "Enter a valid template name."; return; }
if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) { error = $t("Enter a valid template name."); return; }
const path = `${TEMPLATE_FOLDER}/${title}.md`;
if (path === template.path) return;
busy = true; error = "";
@@ -38,8 +39,8 @@
finally { busy = false; }
}
async function remove(template: NoteTemplate) {
const message = `Delete the template “${template.name}”? Existing notes stay unchanged.`;
const accepted = isTauri() ? await confirm(message, { title: "Delete template", kind: "warning" }) : window.confirm(message);
const message = $t("Delete the template “{name}”? Existing notes stay unchanged.", { name: template.name });
const accepted = isTauri() ? await confirm(message, { title: $t("Delete template"), kind: "warning" }) : window.confirm(message);
if (!accepted) return;
busy = true; error = "";
try { await workspaceDelete(template.path); onDeleted(template.path); await refresh(); }
@@ -49,17 +50,17 @@
</script>
<dialog bind:this={dialog} aria-labelledby="templates-title" oncancel={event => { event.preventDefault(); if (!busy) onClose(); }}>
<header><h2 id="templates-title">Document templates</h2><IconButton icon="close" label="Close templates" disabled={busy} onclick={onClose} /></header>
<p>Templates belong to this workspace. Edit a template to change future notes.</p>
<button class="new" disabled={busy} onclick={() => void create()}><Icon icon="file-plus" /> New template</button>
<header><h2 id="templates-title">{$t("Document templates")}</h2><IconButton icon="close" label={$t("Close templates")} disabled={busy} onclick={onClose} /></header>
<p>{$t("Templates belong to this workspace. Edit a template to change future notes.")}</p>
<button class="new" disabled={busy} onclick={() => void create()}><Icon icon="file-plus" /> {$t("New template")}</button>
<div class="list">
{#each templates as template (template.path)}
<div class="row"><span title={template.name}>{template.name}</span><div class="actions">
<IconButton icon="pen" label={`Edit ${template.name}`} disabled={busy} onclick={() => edit(template)} />
<button class="rename" aria-label={`Rename ${template.name}`} title={`Rename ${template.name}`} disabled={busy} onclick={() => void rename(template)}><Icon icon="text" /> Rename</button>
<IconButton icon="trash" label={`Delete ${template.name}`} disabled={busy} onclick={() => void remove(template)} />
<IconButton icon="pen" label={$t("Edit {name}", { name: template.name })} disabled={busy} onclick={() => edit(template)} />
<button class="rename" aria-label={$t("Rename {name}", { name: template.name })} title={$t("Rename {name}", { name: template.name })} disabled={busy} onclick={() => void rename(template)}><Icon icon="text" /> {$t("Rename")}</button>
<IconButton icon="trash" label={$t("Delete {name}", { name: template.name })} disabled={busy} onclick={() => void remove(template)} />
</div></div>
{:else}<p>No templates yet. Create one or use Save as template on a note.</p>{/each}
{:else}<p>{$t("No templates yet. Create one or use Save as template on a note.")}</p>{/each}
</div>
{#if error}<p role="alert">{error}</p>{/if}
</dialog>
+2 -1
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { dialogs, finishText } from "$lib/workspace/dialogs.svelte";
let element: HTMLDialogElement | undefined = $state();
let input: HTMLInputElement | undefined = $state();
@@ -17,7 +18,7 @@
<form onsubmit={(event) => { event.preventDefault(); finishText(dialogs.text?.value.trim() || null); }}>
<label for="text-request">{dialogs.text.title}</label>
<input id="text-request" bind:this={input} bind:value={dialogs.text.value} autocomplete="off" />
<div><button type="button" onclick={() => finishText(null)}>Cancel</button><button type="submit" disabled={!dialogs.text.value.trim()}>Continue</button></div>
<div><button type="button" onclick={() => finishText(null)}>{$t("Cancel")}</button><button type="submit" disabled={!dialogs.text.value.trim()}>{$t("Continue")}</button></div>
</form>
</dialog>
{/if}
+2 -1
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import type { TreeEntry } from "$lib/workspace/types";
import type { DropTarget } from "$lib/workspace/treeDrop";
import type { SelectionModifiers, TreeSelectionEdges } from "$lib/workspace/treeSelection";
@@ -133,7 +134,7 @@
{#if isRenaming}
<input
class="rename"
aria-label="File or folder name, including any extension"
aria-label={$t("File or folder name, including any extension")}
value={renameDraft}
use:focusSelect
onclick={(event) => event.stopPropagation()}
+72 -71
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import TerminalSlot from "$lib/plugins/TerminalSlot.svelte";
import PluginTools from "$lib/plugins/PluginTools.svelte";
import PluginAccessMenu from "$lib/plugins/PluginAccessMenu.svelte";
@@ -75,7 +76,7 @@
if (openingSettings) return;
openingSettings = true;
try { await invoke("settings_open_window"); }
catch (reason) { error = `Could not open settings: ${String(reason)}`; }
catch (reason) { error = $t("Could not open settings: {error}", { error: String(reason) }); }
finally { openingSettings = false; }
}
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
@@ -86,7 +87,7 @@
let tabs = $state<OpenBuffer[]>([]);
let activePath = $state<string | null>(null);
const buffer = $derived(tabs.find((tab) => tab.relPath === activePath) ?? null);
let status = $state("Open a workspace folder");
let status = $state($t("Open a workspace folder"));
let error = $state<string | null>(null);
let refreshToken = $state(0);
let view = $state<Chrome>("Writing");
@@ -277,7 +278,7 @@
async function terminalAction(action: Exclude<ReturnType<Contributions["terminal"]["shortcut"]>, null | "toggle">) {
if (!terminalEnabled) return;
if (!workspace) { error = "Open a workspace to start a terminal."; return; }
if (!workspace) { error = $t("Open a workspace to start a terminal."); return; }
const started = terminalStarted;
terminalStarted = true; terminalOpen = true;
if (bottomHeight < 220) bottomHeight = 260;
@@ -374,7 +375,7 @@
focusLine = null;
documents?.select(relPath);
focusDocumentPane(documentPanes.active, true);
status = documents?.active?.kind === "empty" ? "New tab" : relPath;
status = documents?.active?.kind === "empty" ? $t("New tab") : relPath;
}
function selectWorkingTab(path: string) {
@@ -403,7 +404,7 @@
const tab = workingTabs.find(tab => tab.id === item.id);
const actions = tab && "plugin" in tab ? pluginTabActions(tab.plugin) : [];
if (actions.some(action => "label" in action && /(?:move|open).*new window/i.test(action.label))) return actions;
return tab ? [{ label: "Open in new window", icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
return tab ? [{ label: $t("Open in new window"), icon: "external", disabled: !desktop || !workspace, run: () => { void detachTab(tab); } }, ...actions] : [];
}
async function detachTab(item: WorkbenchTab, keepSource = false) {
const tab = workingTabs.find(tab => tab.id === item.id);
@@ -451,7 +452,7 @@
focusLine = null;
documents.newTab();
terminalMaximized = false;
status = "New tab";
status = $t("New tab");
error = null;
}
@@ -471,7 +472,7 @@
if ("buffer" in target) {
if (!tab || (scope !== "one" && tab.pinned)) continue;
const contents = tab.contents;
if (contents !== tab.saved && !await confirm(`Discard unsaved edits in ${tab.name}?`, { title: "Close document", kind: "warning" })) break;
if (contents !== tab.saved && !await confirm($t("Discard unsaved edits in {name}?", { name: tab.name }), { title: $t("Close document"), kind: "warning" })) break;
if (documents !== current || switching || tab.contents !== contents) break;
if (scope !== "one" && tab.pinned) continue;
}
@@ -491,7 +492,7 @@
try {
const text = system ? await workspaceAbsPath(path) : path;
await navigator.clipboard.writeText(text);
status = system ? "Copied system path" : "Copied workspace path";
status = system ? $t("Copied system path") : $t("Copied workspace path");
} catch (err) { error = String(err); }
}
@@ -500,21 +501,21 @@
const items: ActionMenuItem[] = [];
if (tab.kind === "text" && isMarkdownPath(tab.relPath)) {
items.push(
{ label: "Save as template", icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
{ label: reading ? "Editing view" : "Reading view", icon: "book", run: () => activeEditor()?.toggleReadingView() },
{ label: isIde ? "Writing mode" : "Source mode", icon: "code", run: toggleChrome },
{ label: $t("Save as template"), icon: "copy", run: () => { void saveTemplate({ name: tab.name, rel_path: tab.relPath, kind: "file" }); } },
{ label: reading ? $t("Editing view") : $t("Reading view"), icon: "book", run: () => activeEditor()?.toggleReadingView() },
{ label: isIde ? $t("Writing mode") : $t("Source mode"), icon: "code", run: toggleChrome },
);
}
items.push({ separator: true },
{ label: "Rename…", icon: "rename", run: () => { void renameActive(); } },
{ label: $t("Rename…"), icon: "rename", run: () => { void renameActive(); } },
);
if (tab.kind === "text") items.push({ label: "Save a copy…", icon: "copy", run: () => { void saveCopy(); } });
if (tab.kind === "text") items.push({ label: $t("Save a copy…"), icon: "copy", run: () => { void saveCopy(); } });
items.push({ separator: true },
{ label: "Copy path", icon: "copy", children: [
{ label: "Workspace path", icon: "copy", run: () => { void copyTabPath(tab.relPath, false); } },
{ label: "System path", icon: "copy", run: () => { void copyTabPath(tab.relPath, true); } },
{ label: $t("Copy path"), icon: "copy", children: [
{ label: $t("Workspace path"), icon: "copy", run: () => { void copyTabPath(tab.relPath, false); } },
{ label: $t("System path"), icon: "copy", run: () => { void copyTabPath(tab.relPath, true); } },
] },
{ label: "Show in system explorer", icon: "folder", run: () => { void workspaceReveal(tab.relPath).catch(err => { error = String(err); }); } },
{ label: $t("Show in system explorer"), icon: "folder", run: () => { void workspaceReveal(tab.relPath).catch(err => { error = String(err); }); } },
);
return items;
}
@@ -595,7 +596,7 @@
if (!workspace || !current || !note) return null;
const folder = note.relPath.slice(0, note.relPath.lastIndexOf("/") + 1);
const suggested = label.replace(/[<>:"/\\|?*\r\n]/g, " ").trim().slice(0, 60) || "Extracted selection";
const name = await requestText("Extract selection to a new note (workspace relative path)", `${folder}${suggested}.md`);
const name = await requestText($t("Extract selection to a new note (workspace relative path)"), `${folder}${suggested}.md`);
if (!name || documents !== current || !valid() || saving || switching) return null;
const rel = name.replaceAll("\\", "/").replace(/\.md$/i, "") + ".md";
saving = true;
@@ -603,7 +604,7 @@
await workspaceCreate(rel, "file");
await workspaceWrite(rel, markdown + "\n", "");
refreshToken++;
status = `Extracted selection to ${rel}`;
status = $t("Extracted selection to {path}", { path: rel });
return `/${rel}`;
} catch (err) { error = String(err); return null; }
finally { saving = false; }
@@ -616,7 +617,7 @@
saving = true;
try {
await current.save(tab.id);
status = `Saved ${tab.relPath}`;
status = $t("Saved {path}", { path: tab.relPath });
error = null;
} catch (err) {
error = String(err);
@@ -631,9 +632,9 @@
try {
const result = await current.autosave();
if (documents !== current) return;
if (result.saved.length) status = `Autosaved ${result.saved.length} ${result.saved.length === 1 ? "file" : "files"}`;
if (result.saved.length) status = result.saved.length === 1 ? $t("Autosaved 1 file") : $t("Autosaved {count} files", { count: result.saved.length });
if (result.failed.length) {
error = result.failed.map(({ path, error }) => `Could not autosave ${path}: ${String(error)}`).join("\n");
error = result.failed.map(({ path, error }) => $t("Could not autosave {path}: {error}", { path, error: String(error) })).join("\n");
await current.refresh();
}
} finally { saving = false; }
@@ -641,7 +642,7 @@
async function saveCopy(tab = buffer) {
if (!tab || tab.kind !== "text") return;
const name = await requestText("Save a copy as (workspace relative path)", tab.relPath.replace(/(\.[^./]+)?$/, " copy$1"));
const name = await requestText($t("Save a copy as (workspace relative path)"), tab.relPath.replace(/(\.[^./]+)?$/, " copy$1"));
if (!name) return;
try {
await workspaceCreate(name, "file");
@@ -655,7 +656,7 @@
if (!workspace) {
return;
}
const name = await requestText("New file path relative to the workspace", "Untitled.md");
const name = await requestText($t("New file path relative to the workspace"), "Untitled.md");
if (!name) {
return;
}
@@ -673,12 +674,12 @@
}
async function saveTemplate(entry: TreeEntry) {
const name = await requestText("Template name", entry.name.replace(/\.md$/i, ""));
const name = await requestText($t("Template name"), entry.name.replace(/\.md$/i, ""));
if (!name) return;
try {
const contents = documents?.buffers.find(tab => tab.relPath === entry.rel_path)?.contents ?? await workspaceRead(entry.rel_path);
await saveNoteTemplate(name, contents);
status = `Saved template: ${name}`;
status = $t("Saved template: {name}", { name });
} catch (reason) { error = String(reason); }
}
@@ -697,9 +698,9 @@
const close = () => { menu.remove(); window.removeEventListener("pointerdown", outside); anchor?.focus(); };
const outside = (event: PointerEvent) => { if (!menu.contains(event.target as Node)) close(); };
const menu = actionMenu(event.clientX, event.clientY, [
{ label: "Blank note", icon: "file-plus", run: () => { close(); void create(); } },
{ label: $t("Blank note"), icon: "file-plus", run: () => { close(); void create(); } },
...templates.map(template => ({ label: template.name, icon: "file-plus" as const, run: () => { close(); void create(template); } })),
], close, "New note");
], close, $t("New note"));
window.addEventListener("pointerdown", outside);
}
@@ -806,7 +807,7 @@
current.rename(from, plan.to);
if (documents !== current) return;
refreshToken += 1;
status = `Renamed to ${plan.to}`;
status = $t("Renamed to {path}", { path: plan.to });
error = null;
}
@@ -816,7 +817,7 @@
}
const current = documents;
const from = activePath;
const typed = await requestText("Rename to", from.split("/").pop() ?? from);
const typed = await requestText($t("Rename to"), from.split("/").pop() ?? from);
if (typed == null || documents !== current || switching) {
return;
}
@@ -833,7 +834,7 @@
current?.rename(from, plan.to);
if (documents !== current) return;
refreshToken += 1;
status = `Renamed to ${plan.to}`;
status = $t("Renamed to {path}", { path: plan.to });
error = null;
} catch (err) {
error = err instanceof Error ? err.message : String(err);
@@ -852,13 +853,13 @@
const found = files.find(file => file.rel_path === path && file.kind === "file");
if (found) return found;
}
throw new Error(`Could not find ${link.target} in the workspace.`);
throw new Error($t("Could not find {path} in the workspace.", { path: link.target }));
};
const run = (action: (file: TreeEntry) => void | Promise<void>) => () => {
void entry().then(file => { if (valid()) return action(file); }).catch(reason => { error = String(reason); });
};
async function rename(file: TreeEntry, move = false) {
const typed = await requestText(move ? "Move file to (workspace path, including filename)" : "New file name", move ? file.rel_path : file.name);
const typed = await requestText(move ? $t("Move file to (workspace path, including filename)") : $t("New file name"), move ? file.rel_path : file.name);
if (!typed || !valid()) return;
let to = typed.trim().replaceAll("\\", "/");
if (move) {
@@ -877,31 +878,31 @@
applyPathRename(file.rel_path, to);
await saveMarks(moveMarks(marks, file.rel_path, to));
refreshToken++;
status = `Moved to ${to}`;
status = $t("Moved to {path}", { path: to });
}
return [
{ label: "Open to the right", icon: "split-right", run: run(file => openToRight(file, sourcePane)) },
{ label: "Open in new window", icon: "external", disabled: !desktop, run: run(async file => {
{ label: $t("Open to the right"), icon: "split-right", run: run(file => openToRight(file, sourcePane)) },
{ label: $t("Open in new window"), icon: "external", disabled: !desktop, run: run(async file => {
await openFile(file, undefined, "new");
if (!valid()) return;
const tab = workingTabs.find(tab => tab.relPath === file.rel_path);
if (tab) await detachTab(tab, true);
}) },
{ label: "Copy path", icon: "copy", children: [
{ label: "Workspace path", icon: "copy", run: run(file => copyTabPath(file.rel_path, false)) },
{ label: "System path", icon: "copy", run: run(file => copyTabPath(file.rel_path, true)) },
{ label: $t("Copy path"), icon: "copy", children: [
{ label: $t("Workspace path"), icon: "copy", run: run(file => copyTabPath(file.rel_path, false)) },
{ label: $t("System path"), icon: "copy", run: run(file => copyTabPath(file.rel_path, true)) },
] },
{ label: "Rename…", icon: "rename", run: run(file => rename(file)) },
{ label: "Move file to…", icon: "folder", run: run(file => rename(file, true)) },
{ label: "Bookmark", icon: "bookmark", run: run(async file => {
{ label: $t("Rename…"), icon: "rename", run: run(file => rename(file)) },
{ label: $t("Move file to…"), icon: "folder", run: run(file => rename(file, true)) },
{ label: $t("Bookmark"), icon: "bookmark", run: run(async file => {
const marks = await loadMarks();
if (!valid()) return;
if (!marks.bookmarks.includes(file.rel_path)) await saveMarks({ ...marks, bookmarks: [...marks.bookmarks, file.rel_path] });
refreshToken++; status = `Bookmarked ${file.name}`;
refreshToken++; status = $t("Bookmarked {name}", { name: file.name });
}) },
{ label: "Open in default app", icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
{ label: "Show in system explorer", icon: "folder", run: run(file => workspaceReveal(file.rel_path)) },
{ label: "Reveal file in navigation", icon: "folder", run: run(async file => { closePluginSidebar(); leftView = "files"; leftOpen = true; await tick(); await fileTree?.revealPath(file.rel_path); }) },
{ label: $t("Open in default app"), icon: "external", run: run(file => workspaceOpenDefault(file.rel_path)) },
{ label: $t("Show in system explorer"), icon: "folder", run: run(file => workspaceReveal(file.rel_path)) },
{ label: $t("Reveal file in navigation"), icon: "folder", run: run(async file => { closePluginSidebar(); leftView = "files"; leftOpen = true; await tick(); await fileTree?.revealPath(file.rel_path); }) },
];
}
@@ -922,7 +923,7 @@
return;
} catch { /* Try the workspace-root candidate after the note-relative path. */ }
}
error = `Could not open ${target}`;
error = $t("Could not open {path}", { path: target });
}
function onPointerMove(event: PointerEvent) {
@@ -1028,7 +1029,7 @@
closing = true;
try {
const message = [hasDirty ? "Unsaved edits will be discarded." : "", terminalStarted ? "Terminal sessions will end." : ""].filter(Boolean).join("\n");
if (await confirm(`${message}\nClose RuneStone?`, { title: "Close workspace", kind: "warning" })) await getCurrentWindow().destroy();
if (await confirm(`${message}\n${$t("Close RuneStone?")}`, { title: $t("Close workspace"), kind: "warning" })) await getCurrentWindow().destroy();
} finally { closing = false; }
}).then(register).catch(err => error = String(err));
const focus = () => { void documents?.refresh(); refreshToken++; };
@@ -1061,7 +1062,7 @@
class:left-open={!transferredWindow && leftOpen}
class:right-open={!transferredWindow && rightOpen}
role="application"
aria-label="RuneStone workbench"
aria-label={$t("RuneStone workbench")}
style:--left="{leftWidth}px"
style:--right="{rightWidth}px"
style:--bottom="{bottomHeight}px"
@@ -1075,19 +1076,19 @@
{#if !transferredWindow}
<IconButton
icon="files"
label="Files"
label={$t("Files")}
active={leftOpen && !$pluginSidebar && leftView === "files"}
onclick={() => selectLeft("files")}
/>
<IconButton
icon="search"
label="Search"
label={$t("Search")}
active={leftOpen && !$pluginSidebar && leftView === "search"}
onclick={() => selectLeft("search")}
/>
<IconButton
icon="bookmark"
label="Bookmarks"
label={$t("Bookmarks")}
active={leftOpen && !$pluginSidebar && leftView === "bookmarks"}
onclick={() => selectLeft("bookmarks")}
/>
@@ -1107,19 +1108,19 @@
fileActions={workingTabFileActions} tabActions={workingTabActions} onMove={moveWorkingTab}
onDetach={(tab) => { void detachTab(tab); }}
tabDragData={workingTabDragData} onDropTab={(data, index) => void receiveTab(data, index)} />
<IconButton icon="plus" label="New tab (Ctrl T)" onclick={newTab} />
<IconButton icon="plus" label={$t("New tab (Ctrl T)")} onclick={newTab} />
{#if desktop}<div class="window-drag-space" data-tauri-drag-region></div>{/if}
</div>
<div class="header-right" data-tauri-drag-region>
{#if browserContribution?.newTab}<IconButton icon="globe" label="New browser tab" disabled={browserOpening} onclick={() => void openBrowser()} />{/if}
{#if browserContribution?.newTab}<IconButton icon="globe" label={$t("New browser tab")} disabled={browserOpening} onclick={() => void openBrowser()} />{/if}
<PluginAccessMenu surface="open" compact />
<PluginTools />
<PluginAccessMenu surface="commands" compact />
<IconButton icon="save" label="Save" disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} />
{#if terminalEnabled}<IconButton icon="terminal" label="Terminal" active={terminalOpen} onclick={toggleTerminal} />{/if}
<IconButton icon="save" label={$t("Save")} disabled={editorPluginVisible || !dirty || saving} onclick={() => void save()} />
{#if terminalEnabled}<IconButton icon="terminal" label={$t("Terminal")} active={terminalOpen} onclick={toggleTerminal} />{/if}
{#if !transferredWindow}<IconButton
icon="panel-right"
label={rightOpen ? "Hide outline" : "Show outline"}
label={rightOpen ? $t("Hide outline") : $t("Show outline")}
active={rightOpen}
onclick={() => (rightOpen = !rightOpen)}
/>{/if}
@@ -1127,7 +1128,7 @@
</div>
</header>
{#if !transferredWindow}<nav class="plugin-ribbon" aria-label="Plugin shortcuts" hidden={ribbonNavigation.length === 0}>
{#if !transferredWindow}<nav class="plugin-ribbon" aria-label={$t("Plugin shortcuts")} hidden={ribbonNavigation.length === 0}>
{#each ribbonNavigation as item (`${item.owner}:${item.id}`)}
<IconButton
icon={item.icon === "list" || item.icon === "kanban" || item.icon === "globe" || item.icon === "git" ? item.icon : "puzzle"}
@@ -1147,7 +1148,7 @@
{/if}
<div class="native-left" class:sidebar-covered={!!$pluginSidebar}>
{#if !workspace}
{#if leftView === "bookmarks"}<BrowserSlot kind="bookmarks" />{:else}<p class="placeholder">No folder is open.</p>{/if}
{#if leftView === "bookmarks"}<BrowserSlot kind="bookmarks" />{:else}<p class="placeholder">{$t("No folder is open.")}</p>{/if}
{:else}
<div class="left-stack">
<div class="left-layer" class:shown={leftView === "files"}>
@@ -1183,12 +1184,12 @@
</div>
<div class="left-footer">
<div class="footer-start" bind:this={workspaceAnchor}>
<IconButton icon="folder-open" label="Open folder" onclick={chooseWorkspace} />
<span class="ws">{workspace ? workspace.name : "No workspace"}</span>
<IconButton icon="folder-open" label={$t("Open folder")} onclick={chooseWorkspace} />
<span class="ws">{workspace ? workspace.name : $t("No workspace")}</span>
</div>
<div class="footer-actions">
<IconButton icon="help" label="Help and about (F1)" onclick={() => preferences = "help"} />
<IconButton icon="settings" label="Settings (Ctrl+,)" onclick={() => void openSettings()} />
<IconButton icon="help" label={$t("Help and about (F1)")} onclick={() => preferences = "help"} />
<IconButton icon="settings" label={$t("Settings (Ctrl+,)")} onclick={() => void openSettings()} />
</div>
</div>
</aside>
@@ -1231,15 +1232,15 @@
onpointerdowncapture={() => focusDocumentPane(pane.id)}
onfocusin={() => focusDocumentPane(pane.id)}>
{#if pane.buffer?.diskError}
<div class="conflict" role="alert"><span>{pane.buffer.diskError}</span><button onclick={() => void saveCopy(pane.buffer)}>Save a copy</button><button onclick={() => void documents?.refresh()}>Retry</button></div>
<div class="conflict" role="alert"><span>{pane.buffer.diskError}</span><button onclick={() => void saveCopy(pane.buffer)}>{$t("Save a copy")}</button><button onclick={() => void documents?.refresh()}>{$t("Retry")}</button></div>
{:else if pane.buffer?.diskContents != null}
<div class="conflict" role="alert">
<span>This file changed on disk. Your edits are preserved. Review both versions before saving.</span>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>Use disk version</button>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>Keep my edits</button>
<button onclick={() => void saveCopy(pane.buffer)}>Save a copy</button>
<span>{$t("This file changed on disk. Your edits are preserved. Review both versions before saving.")}</span>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, true); }}>{$t("Use disk version")}</button>
<button onclick={() => { if (pane.buffer) documents?.resolve(pane.buffer.id, false); }}>{$t("Keep my edits")}</button>
<button onclick={() => void saveCopy(pane.buffer)}>{$t("Save a copy")}</button>
</div>
<details class="disk-review"><summary>View disk version</summary><pre>{pane.buffer.diskContents}</pre></details>
<details class="disk-review"><summary>{$t("View disk version")}</summary><pre>{pane.buffer.diskContents}</pre></details>
{/if}
<EditorPane
bind:this={paneComponents[pane.id]}
@@ -1290,7 +1291,7 @@
getSelection={() => selectedEditorText(buffer?.id)} onConfigureTasks={configureTasks} />
{/key}
{:else}
<p class="placeholder">Open a workspace to start the terminal.</p>
<p class="placeholder">{$t("Open a workspace to start the terminal.")}</p>
{/if}
</section>
{/if}
@@ -1322,7 +1323,7 @@
{#if workspace}
<span>{workspace.watch_mode} watch</span>
{/if}
<span>{isIde ? "IDE" : "Writer"}</span>
<span>{isIde ? $t("IDE") : $t("Writer")}</span>
</footer>
</div>
+49 -23
View File
@@ -1,7 +1,9 @@
<script lang="ts">
import { t, tr } from "$lib/i18n";
import { tick } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import { pickWorkspaceFolder, workspaceRecent } from "$lib/workspace/api";
import { attachTooltip } from "$lib/ui/tooltip";
import { pickWorkspaceFolder, workspaceRecent, workspaceForget } from "$lib/workspace/api";
let { currentRoot, anchor, onOpen }: {
currentRoot?: string; anchor?: HTMLElement;
@@ -19,21 +21,26 @@
let parent = $state("");
let returnFocus: HTMLElement | null = null;
const folderName = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path;
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : "Choose where to create your workspace.");
const removeTooltip = (node: HTMLElement) => ({ destroy: attachTooltip(node, () => tr("Remove from recent workspaces")) });
const destination = $derived(parent ? `${parent.replace(/[\\/]+$/, "")}${parent.includes("\\") ? "\\" : "/"}${name.trim()}` : $t("Choose where to create your workspace."));
export async function show() {
if (busy || creating) return;
if (menu.matches(":popover-open")) { menu.hidePopover(); return; }
returnFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
error = ""; loading = true;
const keyboard = anchor?.matches(":focus-visible") ?? false;
menu.showPopover();
position();
menu.querySelector<HTMLButtonElement>("button")?.focus();
menu.focus();
try { recent = await workspaceRecent(); }
catch (err) { error = `Could not load recent workspaces: ${String(err)}`; }
catch (err) { error = tr("Could not load recent workspaces: {error}", { error: String(err) }); }
finally { loading = false; }
await tick();
if (menu.matches(":popover-open")) { position(); menu.querySelector<HTMLButtonElement>("button")?.focus(); }
if (menu.matches(":popover-open")) {
position();
if (keyboard) (menu.querySelector<HTMLButtonElement>('button[aria-current="true"]') ?? menu.querySelector<HTMLButtonElement>("button"))?.focus();
}
}
function position() {
@@ -44,12 +51,25 @@
function close() { menu.hidePopover(); returnFocus?.focus(); }
async function forget(path: string) {
if (busy) return;
busy = true; error = "";
const index = recent.indexOf(path);
try { recent = await workspaceForget(path); }
catch (err) { error = tr("Could not remove workspace from recent workspaces: {error}", { error: String(err) }); }
finally { busy = false; }
await tick();
position();
const rows = menu.querySelectorAll<HTMLButtonElement>(".workspace-row");
(rows[Math.min(index, rows.length - 1)] ?? menu.querySelector<HTMLButtonElement>("footer button"))?.focus();
}
async function open(path: string) {
if (busy) return;
if (path === currentRoot) { close(); return; }
busy = true; error = "";
try { if (await onOpen(path)) close(); }
catch (err) { error = `Could not open workspace: ${String(err)}`; }
catch (err) { error = tr("Could not open workspace: {error}", { error: String(err) }); }
finally { busy = false; }
}
@@ -70,7 +90,7 @@
function cancel() { if (!busy) { creating = false; returnFocus?.focus(); } }
async function chooseLocation() {
busy = true; error = "";
try { const path = await pickWorkspaceFolder("Choose a location for the new workspace"); if (path) parent = path; }
try { const path = await pickWorkspaceFolder(tr("Choose a location for the new workspace")); if (path) parent = path; }
catch (err) { error = String(err); }
finally { busy = false; }
}
@@ -93,38 +113,41 @@
</script>
<svelte:window onresize={() => { if (menu?.matches(":popover-open")) position(); }} />
<div bind:this={menu} popover="auto" class="workspace-menu rs-picker" role="dialog" aria-label="Workspaces" tabindex="-1" onkeydown={navigate}>
<h2>Recent workspaces</h2>
<div bind:this={menu} popover="auto" class="workspace-menu rs-picker" role="dialog" aria-label={$t("Workspaces")} tabindex="-1" onkeydown={navigate}>
<h2>{$t("Recent workspaces")}</h2>
<div class="recent" aria-busy={loading || busy}>
{#if loading}<p>Loading workspaces…</p>
{:else if !recent.length}<p>No recent workspaces yet.</p>{/if}
{#each recent as path}
{#if loading}<p>{$t("Loading workspaces…")}</p>
{:else if !recent.length}<p>{$t("No recent workspaces yet.")}</p>{/if}
{#each recent as path (path)}
<div class="workspace-entry">
<button class="workspace-row rs-picker-row" aria-current={path === currentRoot ? "true" : undefined} disabled={busy} onclick={() => open(path)}>
<span class="rs-picker-icon"><Icon icon="folder-open" /></span>
<span class="details"><span>{folderName(path)}</span><small>{path}</small></span>
{#if path === currentRoot}<span class="current-label">Current</span>{/if}
{#if path === currentRoot}<span class="current-label">{$t("Current")}</span>{/if}
</button>
<button class="workspace-remove rs-picker-row" aria-label={$t("Remove {path} from recent workspaces", { path })} use:removeTooltip disabled={busy} onclick={() => forget(path)}><Icon icon="close" /></button>
</div>
{/each}
</div>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer>
<button class="rs-picker-row" disabled={busy} onclick={newWorkspace}><span class="rs-picker-icon"><Icon icon="folder-plus" /></span> New workspace…</button>
<button class="rs-picker-row" disabled={busy} onclick={browse}><span class="rs-picker-icon"><Icon icon="folder-open" /></span> Open another folder…</button>
<button class="rs-picker-row" disabled={busy} onclick={newWorkspace}><span class="rs-picker-icon"><Icon icon="folder-plus" /></span> {$t("New workspace…")}</button>
<button class="rs-picker-row" disabled={busy} onclick={browse}><span class="rs-picker-icon"><Icon icon="folder-open" /></span> {$t("Open another folder…")}</button>
</footer>
</div>
{#if creating}
<dialog bind:this={dialog} aria-labelledby="new-workspace-title" oncancel={(event) => { event.preventDefault(); cancel(); }}>
<form onsubmit={(event) => { event.preventDefault(); void create(); }}>
<h2 id="new-workspace-title"><Icon icon="folder-plus" /> New workspace</h2>
<p>Create a folder for your notes and files, then open it in a new window.</p>
<label for="workspace-name">Workspace name</label>
<input id="workspace-name" bind:this={input} bind:value={name} oninput={() => error = ""} placeholder="My workspace" autocomplete="off" required disabled={busy} />
<div class="location-label"><label for="workspace-location">Location</label><button type="button" disabled={busy} onclick={chooseLocation}><Icon icon="folder-open" /> Browse…</button></div>
<input id="workspace-location" value={parent} readonly placeholder="Choose a parent folder" />
<small class="destination">{parent ? "Will create: " : ""}{destination}</small>
<h2 id="new-workspace-title"><Icon icon="folder-plus" /> {$t("New workspace")}</h2>
<p>{$t("Create a folder for your notes and files, then open it in a new window.")}</p>
<label for="workspace-name">{$t("Workspace name")}</label>
<input id="workspace-name" bind:this={input} bind:value={name} oninput={() => error = ""} placeholder={$t("My workspace")} autocomplete="off" required disabled={busy} />
<div class="location-label"><label for="workspace-location">{$t("Location")}</label><button type="button" disabled={busy} onclick={chooseLocation}><Icon icon="folder-open" /> {$t("Browse…")}</button></div>
<input id="workspace-location" value={parent} readonly placeholder={$t("Choose a parent folder")} />
<small class="destination">{parent ? $t("Will create: {path}", { path: destination }) : destination}</small>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="actions"><button type="button" disabled={busy} onclick={cancel}>Cancel</button><button class="primary" type="submit" disabled={busy || !name.trim() || !parent}>{busy ? "Please wait…" : "Create workspace"}</button></div>
<div class="actions"><button type="button" disabled={busy} onclick={cancel}>{$t("Cancel")}</button><button class="primary" type="submit" disabled={busy || !name.trim() || !parent}>{busy ? $t("Please wait…") : $t("Create workspace")}</button></div>
</form>
</dialog>
{/if}
@@ -140,6 +163,9 @@
form button:focus-visible, input:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
form button:disabled { opacity: .5; }
.workspace-row, footer button { width: 100%; }
.workspace-entry { display: flex; align-items: stretch; }
.workspace-entry .workspace-row { flex: 1; min-width: 0; }
.workspace-entry .workspace-remove { width: 30px; flex: 0 0 30px; justify-content: center; padding-inline: 0; }
.details { min-width: 0; display: flex; flex: 1; flex-direction: column; gap: 3px; }
small { font-size: 11px; color: var(--rs-text-dim); overflow-wrap: anywhere; }
.current-label { font-size: 11px; color: var(--rs-accent); }
+6 -6
View File
@@ -1,6 +1,8 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { untrack } from "svelte";
import Icon from "$lib/ui/Icon.svelte";
import { attachTooltip } from "$lib/ui/tooltip";
import ContextMenu from "$lib/layout/ContextMenu.svelte";
import type { MenuItem } from "$lib/layout/menuTypes";
import { installedPlugins, pluginTools, pluginNavigation, openPluginView, runPluginCommand } from "./external";
@@ -9,7 +11,8 @@
let position = $state<{ x: number; y: number } | null>(null);
let error = $state("");
let pointerWasOpen = false;
const label = $derived(surface === "open" ? "Plug-in views" : "Commands");
const label = $derived(surface === "open" ? $t("Plug-in views") : $t("Commands"));
function tooltip(node: HTMLElement) { return { destroy: attachTooltip(node, () => compact ? label : "") }; }
const tools = $derived($pluginTools.filter(tool => tool.surface === surface
&& tool.owner !== "runestone.browser"
&& !(surface === "open" && tool.kind === "view" && $pluginNavigation.some(item => item.owner === tool.owner && item.id === tool.id && item.placement === "sidebar"))));
@@ -27,22 +30,19 @@
</script>
{#if tools.length}
<button class="access-button" class:compact bind:this={anchor} aria-label={label} aria-haspopup="menu" aria-expanded={position !== null} title={label}
<button class="access-button" class:compact bind:this={anchor} use:tooltip aria-label={label} aria-haspopup="menu" aria-expanded={position !== null}
onpointerdown={() => pointerWasOpen = position !== null}
onclick={event => { const close = event.detail > 0 ? pointerWasOpen : position !== null; const bounds = anchor!.getBoundingClientRect(); position = close ? null : { x: bounds.left, y: bounds.bottom + 4 }; }}>
<Icon icon={surface === "open" ? "puzzle" : "code"} />{#if !compact}<span>{label}</span>{/if}
{#if compact}<span class="access-tooltip" role="tooltip">{label}</span>{/if}
</button>
{/if}
{#if position && tools.length}<ContextMenu {...position} {items} {label} onClose={() => position = null} />{/if}
{#if error}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
{#if error}<p class="error" role="alert">{error}<button onclick={() => error = ""}>{$t("Dismiss")}</button></p>{/if}
<style>
.access-button { display: flex; align-items: center; gap: 6px; white-space: nowrap; min-height: 32px; padding: 5px 8px; border: 0; border-radius: var(--rs-control-radius); background: transparent; color: var(--rs-text); }
.access-button:hover, .access-button[aria-expanded="true"] { background: var(--rs-bg-active); }
.access-button:focus-visible { outline: 2px solid var(--rs-accent); outline-offset: -2px; }
.access-button.compact { position: relative; width: 28px; height: 28px; min-height: 28px; padding: 5px; }
.access-tooltip { display: none; position: absolute; top: calc(100% + 6px); right: 0; padding: 5px 8px; border-radius: var(--rs-control-radius); background: var(--rs-bg-elevated); border: 1px solid var(--rs-border); z-index: 60; pointer-events: none; }
.access-button:is(:hover, :focus-visible) .access-tooltip { display: block; }
.error { position: fixed; top: 48px; right: 12px; z-index: 60; max-width: 420px; padding: 12px; background: var(--rs-bg); color: var(--rs-error); border: 1px solid var(--rs-border); border-radius: var(--rs-control-radius); }
</style>
+42 -41
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onDestroy } from "svelte";
import { invoke, isTauri } from "@tauri-apps/api/core";
import Icon from "$lib/ui/Icon.svelte";
@@ -54,7 +55,7 @@
async function install(enabled: boolean) {
await run(async () => {
const result = await invoke<{ name: string; error: string | null }[]>("plugins_install", { tokens: selected, enabled });
message = result.filter(item => !item.error).map(item => `${item.name} installed${enabled ? " and enabled" : ""}.`).join(" ");
message = result.filter(item => !item.error).map(item => $t(enabled ? "{name} installed and enabled." : "{name} installed.", { name: item.name })).join(" ");
error = result.filter(item => item.error).map(item => `${item.name}: ${item.error}`).join("\n");
await invoke("plugins_cancel", { tokens: candidates.map(item => item.token) });
candidates = []; selected = []; await refreshPlugins(); previous?.focus();
@@ -74,7 +75,7 @@
async function toggle(id: string, enabled: boolean, hash?: string) {
await run(async () => {
await setPluginEnabled(id, enabled, hash);
message = "Changes saved.";
message = $t("Changes saved.");
});
}
async function prepare(plugin: InstalledPlugin) {
@@ -84,7 +85,7 @@
if (!plan) return;
const current = plan;
await run(async () => {
try { await invoke("plugins_remove", { token: current.token }); message = `${current.plugin.manifest.name} uninstalled. Settings and workspace documents were kept.`; }
try { await invoke("plugins_remove", { token: current.token }); message = $t("{name} uninstalled. Settings and workspace documents were kept.", { name: current.plugin.manifest.name }); }
finally { plan = null; await refreshPlugins(); previous?.focus(); }
});
}
@@ -100,91 +101,91 @@
}
</script>
<h2>Plug-ins</h2>
<p>Install a plugin ZIP file or get a release from a Git repository link.</p>
<h2>{$t("Plug-ins")}</h2>
<p>{$t("Install a plugin ZIP file or get a release from a Git repository link.")}</p>
<div class="toolbar">
<button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />Install plugin ZIP</button>
<button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />Install from Git link</button>
<IconButton icon="folder-open" label="Open plugins folder" disabled={!desktop || busy} onclick={() => reveal()} />
<button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />Refresh</button>
<button disabled={!desktop || busy} onclick={() => choose()}><Icon icon="file-plus" />{$t("Install plugin ZIP")}</button>
<button disabled={!desktop || busy} onclick={() => { error = ""; gitForm = true; }}><Icon icon="link" />{$t("Install from Git link")}</button>
<IconButton icon="folder-open" label={$t("Open plugins folder")} disabled={!desktop || busy} onclick={() => reveal()} />
<button disabled={!desktop || busy} onclick={() => run(refreshPlugins)}><Icon icon="refresh" />{$t("Refresh")}</button>
</div>
{#if $installedPlugins.root}<p class="path">{$installedPlugins.root}</p>{/if}
{#if !desktop}<p>Installation requires the RuneStone desktop app.</p>{/if}
{#if !desktop}<p>{$t("Installation requires the RuneStone desktop app.")}</p>{/if}
{#if $pluginServiceError}<p class="error" role="alert">{$pluginServiceError}</p>{/if}
<h3>Installed plugins</h3>
<p class="note">Plugins run with RuneStone's access. Only enable code you trust.</p>
{#if !external.length}<p>No plugins installed.</p>{/if}
<h3>{$t("Installed plugins")}</h3>
<p class="note">{$t("Plugins run with RuneStone's access. Only enable code you trust.")}</p>
{#if !external.length}<p>{$t("No plugins installed.")}</p>{/if}
{#each external as plugin (plugin.manifest.id)}
<div class="card">
<div class="row">
<div class="plugin-copy"><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · Full app access</small>
<div class="plugin-copy"><label for={`external-${plugin.manifest.id}`}>{plugin.manifest.name}</label><p>{plugin.manifest.description}</p><small>{plugin.manifest.author} · {plugin.manifest.version} · {$t("Full app access")}</small>
<div class="status">
<span class="badge">{plugin.manifest.id === "runestone.browser" ? "Included with RuneStone" : plugin.removal ? "Removal incomplete" : plugin.enabled ? "Enabled" : "Disabled"}</span>
<span class="badge">{plugin.manifest.id === "runestone.browser" ? $t("Included with RuneStone") : plugin.removal ? $t("Removal incomplete") : plugin.enabled ? $t("Enabled") : $t("Disabled")}</span>
<span class="note">
{#if plugin.installedAt != null}
Installed <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
{$t("Installed")} <time datetime={new Date(plugin.installedAt).toISOString()}>{installDateFormat.format(plugin.installedAt)}</time>
{:else}
Install date unknown
{$t("Install date unknown")}
{/if}
</span>
</div>
</div>
<div class="controls">
<input id={`external-${plugin.manifest.id}`} type="checkbox" role="switch" checked={plugin.manifest.id === "runestone.browser" || plugin.enabled} disabled={busy || plugin.removal || plugin.manifest.id === "runestone.browser"} onchange={event => { const value = event.currentTarget.checked; event.currentTarget.checked = plugin.enabled; void toggle(plugin.manifest.id, value, plugin.hash); }} />
<IconButton icon="folder-open" label="Show files" disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} />
<IconButton icon="folder-open" label={$t("Show files")} disabled={busy || plugin.removal} onclick={() => reveal(plugin.manifest.id)} />
{#if plugin.removal}
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = "Plugin file cleanup completed."; })}><Icon icon="refresh" />Retry cleanup</button>
<button disabled={busy} onclick={() => run(async () => { await invoke("plugins_retry_remove", { id: plugin.manifest.id }); await refreshPlugins(); message = $t("Plugin file cleanup completed."); })}><Icon icon="refresh" />{$t("Retry cleanup")}</button>
{:else}
<span class="danger"><IconButton icon="trash" label="Uninstall" disabled={busy} onclick={() => prepare(plugin)} /></span>
<span class="danger"><IconButton icon="trash" label={$t("Uninstall")} disabled={busy} onclick={() => prepare(plugin)} /></span>
{/if}
</div>
</div>
{#if plugin.manifest.id === "runestone.browser"}<p class="note">Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.</p>{/if}
{#if plugin.manifest.id === "runestone.browser"}<p class="note">{$t("Browser is now built in. You can remove this old package. Your browser profiles and bookmarks stay available.")}</p>{/if}
{#if plugin.error || $externalErrors[plugin.manifest.id]}<p class="error" role="alert">{plugin.error || $externalErrors[plugin.manifest.id]}</p>{/if}
</div>
{/each}
{#if $restartPlugins.length}<p class="note" role="status">Restart RuneStone to clear all code from plugins that stopped in this window.</p>{/if}
{#if $restartPlugins.length}<p class="note" role="status">{$t("Restart RuneStone to clear all code from plugins that stopped in this window.")}</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
{#if message}<p class="saved" role="status">{message}</p>{/if}
{#if candidates.length || plan || gitForm}
<dialog bind:this={modal} aria-labelledby="plugin-dialog-title" onkeydown={trap} oncancel={event => { event.preventDefault(); event.stopPropagation(); void cancel(); }}>
{#if gitForm}
<h2 id="plugin-dialog-title">Install from Git link</h2>
<p>Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.</p>
<h2 id="plugin-dialog-title">{$t("Install from Git link")}</h2>
<p>{$t("Get a Gitea release ZIP, then review it before installation. Git-link installation is an experimental feature.")}</p>
<form onsubmit={event => { event.preventDefault(); if (!busy) void fromGit(); }}>
<label class="field">Repository link<input type="url" required bind:value={gitUrl} disabled={busy} placeholder="https://host/owner/repository" /></label>
<label class="field">Release tag (optional)<input bind:value={gitTag} disabled={busy} placeholder="Latest release" maxlength="200" /></label>
<label class="field">Access token (optional)<input type="password" bind:value={gitToken} disabled={busy} autocomplete="off" /></label>
<p class="note">Private repositories need a token with read access. RuneStone does not save the token.</p>
{#if gitUrl.trim().startsWith("http:")}<p class="note">HTTP sends the token and package without encryption. Use it only for a trusted local server.</p>{/if}
<label class="field">{$t("Repository link")}<input type="url" required bind:value={gitUrl} disabled={busy} placeholder="https://host/owner/repository" /></label>
<label class="field">{$t("Release tag (optional)")}<input bind:value={gitTag} disabled={busy} placeholder={$t("Latest release")} maxlength="200" /></label>
<label class="field">{$t("Access token (optional)")}<input type="password" bind:value={gitToken} disabled={busy} autocomplete="off" /></label>
<p class="note">{$t("Private repositories need a token with read access. RuneStone does not save the token.")}</p>
{#if gitUrl.trim().startsWith("http:")}<p class="note">{$t("HTTP sends the token and package without encryption. Use it only for a trusted local server.")}</p>{/if}
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button type="button" bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button><button type="submit" disabled={busy || !gitUrl.trim()}><Icon icon="link" />{busy ? "Downloading…" : "Review release"}</button></footer>
<footer><button type="button" bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button type="submit" disabled={busy || !gitUrl.trim()}><Icon icon="link" />{busy ? $t("Downloading…") : $t("Review release")}</button></footer>
</form>
{:else if plan}
<h2 id="plugin-dialog-title">{`Uninstall ${plan.plugin.manifest.name}?`}</h2>
<h2 id="plugin-dialog-title">{$t("Uninstall {name}?", { name: plan.plugin.manifest.name })}</h2>
<p>{plan.plugin.manifest.author} · {plan.plugin.manifest.version}</p>
<p class="path">{plan.plugin.path}</p>
<p>This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.</p>
<p>{$t("This stops the plugin in every window and permanently deletes its installed folder. Settings, source packages, and workspace documents stay intact.")}</p>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer>
<button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button>
<button disabled={busy} onclick={async () => { const current = plan; await cancel(); if (current) await toggle(current.plugin.manifest.id, false); }}>Disable instead</button>
<button class="danger" disabled={busy} onclick={event => { if (event.detail < 2) void remove(); }}>{busy ? "Removing…" : "Uninstall and delete files"}</button>
<button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button>
<button disabled={busy} onclick={async () => { const current = plan; await cancel(); if (current) await toggle(current.plugin.manifest.id, false); }}>{$t("Disable instead")}</button>
<button class="danger" disabled={busy} onclick={event => { if (event.detail < 2) void remove(); }}>{busy ? $t("Removing…") : $t("Uninstall and delete files")}</button>
</footer>
{:else}
<h2 id="plugin-dialog-title">Review plugin installation</h2>
<p>Plugins run with RuneStone's access. Only enable code you trust.</p>
<h2 id="plugin-dialog-title">{$t("Review plugin installation")}</h2>
<p>{$t("Plugins run with RuneStone's access. Only enable code you trust.")}</p>
{#each candidates as candidate (candidate.token)}
<div class="candidate">
<label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? "Invalid package"}</label>
{#if candidate.manifest}<p>{candidate.manifest.author} · {candidate.manifest.version}</p><p>{candidate.manifest.description}</p><p class="path">Destination: {$installedPlugins.root}\{candidate.manifest.id}</p>{/if}
<p class="path">Source: {candidate.source}</p>
<label><input type="checkbox" bind:group={selected} value={candidate.token} disabled={busy || !!candidate.error} />{candidate.manifest?.name ?? $t("Invalid package")}</label>
{#if candidate.manifest}<p>{candidate.manifest.author} · {candidate.manifest.version}</p><p>{candidate.manifest.description}</p><p class="path">{$t("Destination: {path}", { path: `${$installedPlugins.root}\\${candidate.manifest.id}` })}</p>{/if}
<p class="path">{$t("Source: {path}", { path: candidate.source })}</p>
{#if candidate.error}<p class="error">{candidate.error}</p>{/if}
</div>
{/each}
{#if error}<p class="error" role="alert">{error}</p>{/if}
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>Cancel</button><button disabled={busy || !selected.length} onclick={() => install(false)}>Install</button><button disabled={busy || !selected.length} onclick={() => install(true)}>Install and enable</button></footer>
<footer><button bind:this={cancelButton} disabled={busy} onclick={() => cancel()}>{$t("Cancel")}</button><button disabled={busy || !selected.length} onclick={() => install(false)}>{$t("Install")}</button><button disabled={busy || !selected.length} onclick={() => install(true)}>{$t("Install and enable")}</button></footer>
{/if}
</dialog>
{/if}
+3 -2
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import IconButton from "$lib/ui/IconButton.svelte";
import { pluginView, mountPluginView } from "./external";
@@ -22,10 +23,10 @@
});
</script>
{#if error && $pluginView?.placement !== "dialog"}<p class="error" role="alert">{error}<button onclick={() => error = ""}>Dismiss</button></p>{/if}
{#if error && $pluginView?.placement !== "dialog"}<p class="error" role="alert">{error}<button onclick={() => error = ""}>{$t("Dismiss")}</button></p>{/if}
{#if $pluginView?.placement === "dialog"}
<dialog bind:this={dialog} aria-label={$pluginView.title} oncancel={event => { event.preventDefault(); pluginView.set(null); }}>
<header><h2>{$pluginView.title}</h2><IconButton icon="close" label="Close plugin view" onclick={() => pluginView.set(null)} /></header>
<header><h2>{$pluginView.title}</h2><IconButton icon="close" label={$t("Close plugin view")} onclick={() => pluginView.set(null)} /></header>
{#if error}<p class="error" role="alert">{error}</p>{/if}
<div class="plugin-content" bind:this={host}></div>
</dialog>
+1 -1
View File
@@ -3,7 +3,7 @@ import type { PluginCommand, PluginView } from "./sdk.ts";
export type PluginTool = {
owner: string; id: string; title: string; kind: "command" | "view";
surface: "commands" | "open" | "settings";
icon?: PluginView["icon"];
icon?: PluginCommand["icon"];
};
export function pluginAccess(owner: string, commands: Iterable<PluginCommand>, views: Iterable<PluginView>): PluginTool[] {
+2 -2
View File
@@ -105,8 +105,8 @@ export class BackgroundHub {
body.style.setProperty('--rs-background-previous-layer-positions', frame.previous ? image(frame.previous).positions : layerPositions);
body.style.setProperty('--rs-workarea-sidebar-bg', 'var(--rs-image-sidebar-bg)');
body.style.setProperty('--rs-workarea-editor-bg', 'var(--rs-image-editor-bg)');
body.style.setProperty('--rs-workarea-surface-opacity', '82%');
body.style.setProperty('--rs-workarea-plugin-bg', 'transparent');
body.style.setProperty('--rs-workarea-surface-opacity', 'var(--rs-surface-opacity, 82%)');
body.style.setProperty('--rs-workarea-plugin-bg', 'var(--rs-transparent-plugin-bg, transparent)');
body.style.setProperty('--rs-background-transition-image', frame.previous ? currentImage : 'none');
body.style.setProperty('--rs-background-previous-image', frame.previous ? image(frame.previous).image : 'none');
body.style.setProperty('--rs-background-previous-position', frame.previous?.position ?? frame.position);
+1
View File
@@ -254,6 +254,7 @@ async function activate(row: InstalledPlugin, builtin?: PluginModule) {
workspace: {
list: path => workspaceList(path ?? ""), read: workspaceRead,
listMarkdown: () => invoke<string[]>("workspace_list_markdown"),
readMany: paths => invoke<{ path: string; source?: string; error?: string }[]>("workspace_read_many", { paths }),
readBytes: workspaceReadBytes,
write: async (path, source, expected) => { canWrite(path); await workspaceWrite(path, source, expected); notifyPluginWorkspace(); },
subscribe: listener => { workspaceListeners.add(listener); return () => { workspaceListeners.delete(listener); }; },
+3
View File
@@ -4,6 +4,7 @@ import { registerCompletionInput } from "../completion/input.ts";
import { showActionMenu } from "../ui/managedActionMenu.ts";
import { backgroundHub } from "./backgrounds.ts";
import type { BackgroundFiles } from "./backgroundContracts.ts";
import { pluginTranslation } from "./translation.ts";
import type { Dispose, PluginApi, PluginCommand, PluginModule, PluginView, PluginDocumentType, PluginDocumentContext } from "./sdk.ts";
export function deadline<T>(work: Promise<T>, milliseconds = 5000): Promise<T> {
@@ -54,6 +55,7 @@ export class ExternalSession {
};
const api: PluginApi = {
id: this.id, signal: this.controller.signal,
i18n: pluginTranslation(() => this.check(), off => { this.contributions.push(off); }),
...(this.services.backgrounds ? { backgrounds: {
version: 1 as const,
chooseFolder: () => this.backgroundRequest(() => this.services.backgrounds!.chooseFolder()),
@@ -139,6 +141,7 @@ export class ExternalSession {
list: path => { this.check(); return this.services.workspace.list(path); },
...(this.services.workspace.listMarkdown ? { listMarkdown: () => { this.check(); return this.services.workspace.listMarkdown!(); } } : {}),
read: path => { this.check(); return this.services.workspace.read(path); },
...(this.services.workspace.readMany ? { readMany: (paths: string[]) => { this.check(); return this.services.workspace.readMany!(paths); } } : {}),
...(this.services.workspace.readBytes ? { readBytes: (path: string) => { this.check(); return this.services.workspace.readBytes!(path); } } : {}),
...(this.services.workspace.readOptional ? { readOptional: (path: string) => { this.check(); return this.services.workspace.readOptional!(path); } } : {}),
...(this.services.workspace.create ? { create: (path: string, contents: string) => { this.check(); return this.services.workspace.create!(path, contents); } } : {}),
+4 -1
View File
@@ -1,10 +1,11 @@
import type { Contributions } from "./contracts.ts";
import type { CompletionApi } from "../completion/contracts.ts";
import type { ActionMenuItem } from "../ui/actionMenu.ts";
import type { ActionIcon } from "../ui/actionIcons.ts";
export type { BackgroundFrame, BackgroundApi } from "./backgroundContracts.ts";
/** Package API v1. Compiled plugins export activate(api). */
export type Dispose = () => void | Promise<void>;
export interface PluginCommand { id: string; title: string; icon?: PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> }
export interface PluginCommand { id: string; title: string; icon?: ActionIcon | PluginView["icon"]; category?: "open" | "action"; run: () => void | Promise<void> }
export interface PluginView { id: string; title: string; settings?: boolean; launcher?: boolean; placement?: "dialog" | "editor" | "sidebar"; navigation?: boolean; toolbar?: boolean; pinned?: boolean; icon?: "list" | "kanban" | "puzzle" | "globe" | "git"; iconImage?: string | null; tabActions?: (context: { pinned: boolean }) => ActionMenuItem[]; tabDragData?: (context: { pinned: boolean }) => string | undefined; find?: () => void; saveTabState?: () => unknown; restoreTabState?: (state: unknown) => void | Promise<void>; mount: (container: HTMLElement, context?: { surface: "settings" | "view" }) => void | Dispose | Promise<void | Dispose> }
export interface PluginViewOpenOptions { split: "right" | "down"; relativeTo: string }
export interface PluginDocumentContext { id: string; path: string }
@@ -19,6 +20,7 @@ export interface PluginDocumentType {
mount(container: HTMLElement, document: PluginDocumentContext): void | Dispose | Promise<void | Dispose>;
}
export interface PluginApi {
i18n?: import("./translation.ts").PluginTranslation;
backgrounds?: import("./backgroundContracts.ts").BackgroundApi;
ui?: { showActionMenu(options: import("../ui/managedActionMenu.ts").MenuOptions): { close(): void } };
git?: import("../git/contracts.ts").GitApi;
@@ -44,6 +46,7 @@ export interface PluginApi {
list(path?: string): Promise<{ name: string; rel_path: string; kind: string }[]>;
listMarkdown?(): Promise<string[]>;
read(path: string): Promise<string>;
readMany?(paths: string[]): Promise<{ path: string; source?: string; error?: string }[]>;
readBytes?(path: string): Promise<Uint8Array>;
readOptional?(path: string): Promise<string | null>;
create?(path: string, contents: string): Promise<void>;
+30
View File
@@ -0,0 +1,30 @@
import { get } from 'svelte/store';
import { locale, translate, type Locale } from '../i18n/index.ts';
export type PluginCatalogs = Partial<Record<Locale, Record<string, string>>>;
export interface PluginTranslation {
readonly locale: Locale;
t(message: string, values?: Record<string, string | number>, catalogs?: PluginCatalogs): string;
subscribe(listener: (language: Locale) => void): () => void;
}
/** Translates only explicit interface messages. Document content stays with the plugin. */
export function pluginTranslation(check: () => void, track: (cleanup: () => void) => void): PluginTranslation {
return {
get locale() { check(); return get(locale); },
t(message, values = {}, catalogs = {}) {
check();
const language = get(locale);
const catalog = Object.hasOwn(catalogs, language) ? catalogs[language] : undefined;
if (!catalog || !Object.hasOwn(catalog, message)) return translate(language, message, values);
return catalog[message].replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
},
subscribe(listener) {
check();
if (typeof listener !== 'function') throw new Error('A language listener must be a function.');
const off = locale.subscribe(listener);
track(off);
return off;
},
};
}
+54 -37
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount, onDestroy } from 'svelte';
import { invoke, isTauri } from '@tauri-apps/api/core';
import { customThemes, installTheme, parseCustomTheme, removeTheme, type CustomTheme } from './customThemes';
@@ -18,37 +19,37 @@
let closePicker = () => {};
const themes = $derived([...BUILTIN_THEMES, ...installed.map(theme => ({ id: `custom:${theme.id}` as ThemeName, name: theme.name }))].flatMap(theme =>
themeModes(theme.id).map(mode => ({
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? 'Light' : 'Dark'}`,
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? $t('Light') : $t('Dark')}`,
}))));
onDestroy(() => closePicker());
function picker(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: 'Color theme', parent: anchor.closest('dialog') ?? undefined,
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: $t('Color theme'), parent: anchor.closest('dialog') ?? undefined,
items: themes.map(choice => ({ label: choice.name, radio: true, checked: choice.theme === appearance.theme && choice.mode === appearance.mode,
run: () => change({ ...appearance, theme: choice.theme, mode: choice.mode }) })) }).close;
}
const positionLabels = ['Center', 'Top left', 'Top center', 'Top right', 'Center left', 'Center right', 'Bottom left', 'Bottom center', 'Bottom right'];
const sizeLabels = ['Fill', 'Fit', 'Actual size'];
const positionLabels = $derived([$t('Center'), $t('Top left'), $t('Top center'), $t('Top right'), $t('Center left'), $t('Center right'), $t('Bottom left'), $t('Bottom center'), $t('Bottom right')]);
const sizeLabels = $derived([$t('Fill'), $t('Fit'), $t('Actual size')]);
function backgroundPicker(event: MouseEvent, field: 'position' | 'size') {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const values = field === 'position' ? BACKGROUND_POSITIONS : BACKGROUND_SIZES;
const labels = field === 'position' ? positionLabels : sizeLabels;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? 'Image position' : 'Image size', parent: anchor.closest('dialog') ?? undefined,
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? $t('Image position') : $t('Image size'), parent: anchor.closest('dialog') ?? undefined,
items: values.map((value, index) => ({ label: labels[index], radio: true, checked: value === appearance.newTabBackground?.[field],
run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close;
}
onMount(() => {
const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = 'Could not read appearance settings.'; } };
const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = $t('Could not read appearance settings.'); } };
read(); window.addEventListener('storage', read); window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', read); window.removeEventListener('focus', read); };
});
function change(next: Appearance) {
try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; return true; }
catch { error = 'Could not save appearance settings.'; return false; }
catch { error = $t('Could not save appearance settings.'); return false; }
}
function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber;
@@ -59,14 +60,14 @@
backgroundRevision++;
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: undefined }) && old) {
try { await removeBackgroundImage(old); } catch { error = 'Could not remove the saved image from storage.'; }
try { await removeBackgroundImage(old); } catch { error = $t('Could not remove the saved image from storage.'); }
}
}
async function importTheme(file?: File) {
if (!file) return;
try {
if (file.size > 65536) throw new Error('Choose a theme smaller than 64 KiB.');
const theme = parseCustomTheme(JSON.parse(await file.text()));
if (file.size > 65536) throw new Error($t('Choose a theme smaller than 64 KiB.'));
const theme = parseCustomTheme(JSON.parse(await file.text()), appearance.mode);
installTheme(theme); installed = customThemes();
change({ ...appearance, theme: `custom:${theme.id}` });
} catch (reason) { error = String(reason); }
@@ -76,7 +77,7 @@
if (!file) return;
const revision = ++backgroundRevision;
try {
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error('Choose a PNG, JPEG, WebP, or GIF image.');
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error($t('Choose a PNG, JPEG, WebP, or GIF image.'));
const imageId = await saveBackgroundImage(file);
if (revision !== backgroundRevision) { await removeBackgroundImage(imageId); return; }
const old = appearance.newTabBackground?.imageId;
@@ -90,59 +91,65 @@
if (exporting) return;
exporting = true; error = ''; status = '';
try {
const source = exportAppearanceTheme(appearance.theme);
const source = exportAppearanceTheme(appearance.theme, appearance.mode);
const contents = JSON.stringify(source, null, 2) + '\n';
if (isTauri()) {
const path = await invoke<string | null>('theme_export', { contents, defaultName: source.id + '.json' });
status = path ? `Theme saved to ${path}` : 'Export canceled.';
status = path ? $t('Theme saved to {path}', { path }) : $t('Export canceled.');
} else {
const url = URL.createObjectURL(new Blob([contents], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = source.id + '.json';
document.body.append(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
status = 'Theme download started.';
status = $t('Theme download started.');
}
} catch (reason) { error = `Could not export the theme: ${String(reason)}`; }
} catch (reason) { error = $t('Could not export the theme: {error}', { error: String(reason) }); }
finally { exporting = false; }
}
</script>
<h2>Appearance</h2>
<p>Choose a color theme variant.</p>
<h2>{$t("Appearance")}</h2>
<p>{$t("Choose a color theme variant.")}</p>
<div class="card">
<div class="setting-row"><span>Color theme</span><button class="picker" aria-label="Color theme" aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Color theme")}</span><button class="picker" aria-label={$t("Color theme")} aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div>
</div>
<div class="theme-preview" role="img" aria-label="Color theme preview">
<div class="theme-preview" role="img" aria-label={$t("Color theme preview")}>
<div class="preview-sidebar" aria-hidden="true"><span></span><span></span><span></span></div>
<div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">A place for your ideas.</span><span class="preview-selection">Selected text</span><span class="preview-link">Link</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></div>
<div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">{$t("A place for your ideas.")}</span><span class="preview-selection">{$t("Selected text")}</span><span class="preview-link">{$t("Link")}</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></div>
</div>
<div class="theme-actions">
<input bind:this={themeInput} type="file" accept=".json,application/json" aria-label="Theme JSON file" hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} />
<button onclick={() => themeInput.click()}>Install theme</button>
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? 'Exporting…' : 'Export theme template'}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label="Remove custom theme" onclick={() => {
<input bind:this={themeInput} type="file" accept=".json,application/json" aria-label={$t("Theme JSON file")} hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} />
<button onclick={() => themeInput.click()}>{$t("Install theme")}</button>
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? $t('Exporting…') : $t('Export theme template')}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label={$t("Remove custom theme")} onclick={() => {
try { removeTheme(appearance.theme.slice(7)); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
catch { error = 'Could not remove this theme.'; }
}} />{/if}
</div>
<p>Edit the exported JSON colors, then choose Install theme. Each theme has light and dark colors.</p>
{#if appearance.theme === 'sakura'}<p>Sakura uses a light appearance.</p>{/if}
<h3>Background image</h3>
<div class="background-preview" aria-label="Background image preview"><span>Background</span></div>
<p>{$t("Edit the exported JSON colors and fonts, then choose Install theme. The template contains one color palette and font families.")}</p>
{#if appearance.theme === 'sakura'}<p>{$t("Sakura uses a light appearance.")}</p>{/if}
<h3>{$t("Transparency")}</h3>
<div class="card">
<label><span>{$t("Transparent surfaces")}</span><input type="checkbox" role="switch" checked={appearance.transparency?.enabled !== false} onchange={event => change({ ...appearance, transparency: { amount: appearance.transparency?.amount ?? 18, enabled: event.currentTarget.checked } })} /></label>
<div class="setting-row"><label for="surface-transparency">{$t("Transparency amount")}</label><div class="overlay-controls"><input id="surface-transparency" type="range" min="0" max="100" step="1" disabled={appearance.transparency?.enabled === false} value={appearance.transparency?.amount ?? 18} oninput={event => change({ ...appearance, transparency: { enabled: true, amount: event.currentTarget.valueAsNumber } })} /><output for="surface-transparency">{appearance.transparency?.amount ?? 18}%</output></div></div>
</div>
<p>{$t("Turn off transparency to use opaque surfaces and reduce compositing work. Text and icons remain opaque.")}</p>
<h3>{$t("Background image")}</h3>
<div class="background-preview" aria-label={$t("Background image preview")}><span>{$t("Background")}</span></div>
{#if appearance.newTabBackground}
<div class="card">
<div class="setting-row"><span>Image position</span><button class="picker" aria-label="Image position" aria-haspopup="menu" onclick={event => backgroundPicker(event, 'position')}>{positionLabels[BACKGROUND_POSITIONS.indexOf(appearance.newTabBackground.position ?? 'center')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Image size</span><button class="picker" aria-label="Image size" aria-haspopup="menu" onclick={event => backgroundPicker(event, 'size')}>{sizeLabels[BACKGROUND_SIZES.indexOf(appearance.newTabBackground.size ?? 'cover')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Image overlay</span><div class="overlay-controls"><input type="range" aria-label="Image overlay" min="-100" max="100" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} /><label class="overlay-value"><input type="number" aria-label="Image overlay percentage" min="-100" max="100" step="1" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((appearance.newTabBackground?.overlay ?? 0) * 100)); }} /><span>%</span></label></div></div>
<div class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("Image position")} aria-haspopup="menu" onclick={event => backgroundPicker(event, 'position')}>{positionLabels[BACKGROUND_POSITIONS.indexOf(appearance.newTabBackground.position ?? 'center')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image size")}</span><button class="picker" aria-label={$t("Image size")} aria-haspopup="menu" onclick={event => backgroundPicker(event, 'size')}>{sizeLabels[BACKGROUND_SIZES.indexOf(appearance.newTabBackground.size ?? 'cover')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Image overlay")}</span><div class="overlay-controls"><input type="range" aria-label={$t("Image overlay")} min="-100" max="100" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} /><label class="overlay-value"><input type="number" aria-label={$t("Image overlay percentage")} min="-100" max="100" step="1" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((appearance.newTabBackground?.overlay ?? 0) * 100)); }} /><span>%</span></label></div></div>
</div>
<p>Move left to lighten the image or right to darken it.</p>
<p>{$t("Move left to lighten the image or right to darken it.")}</p>
{/if}
<div class="theme-actions">
<input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label="Background image file" hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} />
<button onclick={() => backgroundInput.click()}>Choose image…</button>
{#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>Remove image</button>{/if}
<button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>Reset background</button>
<input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} />
<button onclick={() => backgroundInput.click()}>{$t("Choose image…")}</button>
{#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>{$t("Remove image")}</button>{/if}
<button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>{$t("Reset background")}</button>
</div>
<p>PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.</p>
<p>{$t("PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.")}</p>
{#if status}<p role="status">{status}</p>{/if}
{#if error}<p role="alert">{error}</p>{/if}
<style>
@@ -170,6 +177,16 @@
.preview-number{color:var(--rs-syntax-number,var(--rs-special))}
.overlay-controls{display:flex;align-items:center;flex-wrap:wrap;gap:var(--rs-settings-gap);max-width:100%}
.overlay-controls input[type=range]{width:160px;max-width:100%;min-width:0}
input[type=checkbox]{accent-color:var(--rs-accent)}
.overlay-controls input[type=range]{appearance:none;background:transparent;height:var(--rs-settings-control-height);margin:0;cursor:pointer}
.overlay-controls input[type=range]::-webkit-slider-runnable-track{height:6px;background:var(--rs-bg-active);border:1px solid var(--rs-text-dim);border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]::-webkit-slider-thumb{appearance:none;width:18px;height:18px;margin-top:-7px;background:var(--rs-accent);border:2px solid var(--rs-text-strong);border-radius:50%}
.overlay-controls input[type=range]::-moz-range-track{height:4px;background:var(--rs-bg-active);border:1px solid var(--rs-text-dim);border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]::-moz-range-thumb{width:14px;height:14px;background:var(--rs-accent);border:2px solid var(--rs-text-strong);border-radius:50%}
.overlay-controls input[type=range]:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px;border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]:disabled{cursor:default}
.overlay-controls input[type=range]:disabled::-webkit-slider-thumb{background:var(--rs-text-dim)}
.overlay-controls input[type=range]:disabled::-moz-range-thumb{background:var(--rs-text-dim)}
.overlay-value{padding:0;gap:4px;flex-wrap:nowrap}
.overlay-value input{width:64px;min-height:var(--rs-settings-control-height);box-sizing:border-box;padding:4px 6px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);font:inherit}
.overlay-value input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
+3 -1
View File
@@ -1,8 +1,10 @@
<script lang="ts">
import { syncLocale } from '$lib/i18n';
import { onMount } from 'svelte';
import { APPEARANCE_KEY, applyAppearance, parseAppearance } from './appearance';
import { CUSTOM_THEMES_KEY } from './customThemes';
onMount(() => {
const stopLocale = syncLocale();
const read = () => {
try {
const raw = localStorage.getItem(APPEARANCE_KEY);
@@ -17,7 +19,7 @@
read();
window.addEventListener('storage', sync);
window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
return () => { stopLocale(); window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
});
</script>
+62 -19
View File
@@ -1,4 +1,4 @@
import { customThemes, type CustomTheme } from './customThemes.ts';
import { customThemes, FONT_ROLES, type ThemeFonts, type ThemeColors, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts';
export const APPEARANCE_KEY = 'runestone.appearance';
@@ -11,17 +11,22 @@ export const BUILTIN_THEMES = [
const LEGACY_THEME_IDS: Record<string, typeof THEMES[number]> = { holo: 'harvest-moon', asuka: 'crimson-pilot', malfoid: 'silver-serpent' };
export function themeModes(theme: string): readonly ('light' | 'dark')[] {
const character = characterTheme(theme);
return character ? [character.mode] : theme === 'sakura' ? ['light'] : ['light', 'dark'];
return theme.startsWith('custom:') ? [customThemeMode(customThemes().find(item => `custom:${item.id}` === theme)?.colors)] : character ? [character.mode] : theme === 'sakura' ? ['light'] : ['light', 'dark'];
}
export type ThemeName = typeof THEMES[number] | `custom:${string}`;
export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'] as const;
export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const;
export type Appearance = { theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } };
export type Appearance = { transparency?: { enabled: boolean; amount: number }; theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } };
export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' };
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown } | null): Appearance {
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null): Appearance {
const savedTheme = typeof value?.theme === 'string' && Object.hasOwn(LEGACY_THEME_IDS, value.theme) ? LEGACY_THEME_IDS[value.theme] : value?.theme;
const theme: ThemeName = typeof savedTheme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(savedTheme) || (THEMES as readonly string[]).includes(savedTheme)) ? savedTheme as ThemeName : 'default';
const result: Appearance = { theme, mode: characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') };
const selectedCustom = theme.startsWith('custom:') ? customThemes(value?.mode === 'light' ? 'light' : 'dark').find(item => `custom:${item.id}` === theme) : undefined;
const result: Appearance = { theme, mode: selectedCustom ? customThemeMode(selectedCustom.colors) : characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') };
if (value?.transparency && typeof value.transparency === 'object') {
const source = value.transparency as { enabled?: unknown; amount?: unknown };
result.transparency = { enabled: source.enabled !== false, amount: typeof source.amount === 'number' && Number.isFinite(source.amount) ? Math.max(0, Math.min(100, Math.round(source.amount))) : 18 };
}
const background = value?.newTabBackground;
if (background && typeof background === 'object') {
const source = background as { image?: unknown; imageId?: unknown; overlay?: unknown; position?: unknown; size?: unknown };
@@ -61,23 +66,56 @@ function builtinPalette(theme: ThemeName) {
if (character) return { light: character.surfaces, dark: character.surfaces };
return palettes[theme === 'claude' ? 'claude' : 'default'];
}
export function exportAppearanceTheme(theme: ThemeName): CustomTheme {
const custom = customThemes().find(item => `custom:${item.id}` === theme);
if (custom) return custom;
const palette = builtinPalette(theme);
const syntax = characterSyntax(theme);
const extra = characterTheme(theme) ? { ...syntax, 'accent-2': characterTheme(theme)!.secondary } : {};
return { schema: 1, id: 'my-theme', name: 'My theme',
light: { ...Object.fromEntries(keys.map((key, index) => [key, palette.light[index]])), ...extra },
dark: { ...Object.fromEntries(keys.map((key, index) => [key, palette.dark[index]])), ...extra } };
export function customThemeMode(colors?: ThemeColors): 'light' | 'dark' {
const hex = colors?.bg?.slice(1) ?? '141414';
const full = hex.length <= 4 ? [...hex.slice(0, 3)].map(value => value + value).join('') : hex.slice(0, 6);
const rgb = [0, 2, 4].map(index => parseInt(full.slice(index, index + 2), 16) / 255)
.map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4);
return rgb[0] * .2126 + rgb[1] * .7152 + rgb[2] * .0722 > .179 ? 'light' : 'dark';
}
export function exportAppearanceTheme(theme: ThemeName, mode: 'light' | 'dark' = 'dark'): CustomTheme {
const custom = customThemes(mode).find(item => `custom:${item.id}` === theme);
if (custom) mode = customThemeMode(custom.colors);
mode = characterTheme(theme)?.mode ?? (theme === 'sakura' ? 'light' : mode);
const palette = builtinPalette(theme)[mode];
const colors: ThemeColors = Object.fromEntries(keys.map((key, index) => [key, palette[index]]));
colors['accent-2'] = characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : colors.accent);
const semantic = mode === 'light' ? ['#b42323', '#8a5700', '#806600', '#287b29', '#7740a5'] : ['#f44747', '#d68a00', '#cca700', '#89d185', '#c792ea'];
if (theme === 'claude') { semantic[3] = '#788c5d'; semantic[4] = '#6a9bcc'; }
if (theme === 'sakura') { semantic[3] = '#618c71'; semantic[4] = '#cb6b91'; }
(['error', 'warn-hot', 'warn', 'ok', 'special'] as const).forEach((key, index) => colors[key] = semantic[index]);
const syntax = theme === 'sakura' ? ['#cb6b91', '#98556c', '#618c71', '#69a2bd', '#607fa9', '#687788'] : [colors.special, colors.accent, colors.text, colors['accent-2'], colors['accent-2'], colors['text-dim']];
(['parameter', 'keyword', 'local', 'static', 'instance', 'global'] as const).forEach((key, index) => colors[`syntax-${key}`] = syntax[index]);
Object.assign(colors, { 'syntax-string': colors.ok, 'syntax-number': colors.special, 'syntax-comment': colors['text-dim'], 'syntax-type': colors['accent-2'], 'syntax-function': colors['accent-2'] }, characterSyntax(theme));
return { schema: 2, id: custom?.id ?? 'my-theme', name: custom?.name ?? 'My theme', colors: { ...colors, ...custom?.colors }, fonts: { ...themeFonts(theme), ...custom?.fonts } };
}
export function themeFonts(theme: ThemeName): Required<ThemeFonts> {
const ui = '"Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif';
const prose = '"Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif';
const mono = '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace';
const fonts = { ui, prose, heading: prose, mono };
if (theme === 'claude') return { ...fonts, ui: '"Lora", Georgia, serif', prose: '"Lora", Georgia, serif', heading: '"Poppins", Arial, sans-serif' };
if (theme === 'harvest-moon') return { ...fonts, ui: 'Candara, "Trebuchet MS", "Segoe UI", sans-serif', prose: 'Constantia, Georgia, "Times New Roman", serif', heading: 'Constantia, Georgia, "Times New Roman", serif' };
if (theme === 'crimson-pilot') return { ...fonts, ui: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif', prose: '"Segoe UI", "Helvetica Neue", Arial, sans-serif', heading: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif' };
if (theme === 'silver-serpent') return { ...fonts, ui: 'Corbel, "Segoe UI", "Helvetica Neue", Arial, sans-serif', prose: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif', heading: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif' };
return fonts;
}
export function applyTransparency(value: Appearance['transparency'], root: HTMLElement) {
const supplied = value?.amount ?? 18;
const amount = value?.enabled === false ? 0 : Number.isFinite(supplied) ? Math.max(0, Math.min(100, supplied)) : 18;
root.dataset.transparency = amount ? 'on' : 'off';
root.style.setProperty('--rs-surface-opacity', `${100 - amount}%`);
root.style.setProperty('--rs-editor-surface-opacity', `${100 - amount * 10 / 18}%`);
root.style.setProperty('--rs-hover-surface-opacity', `${100 - amount * 8 / 18}%`);
root.style.setProperty('--rs-transparent-plugin-bg', amount ? 'transparent' : 'var(--rs-bg)');
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
function applyBackgroundSurfaces(root: HTMLElement, hasImage: boolean) {
root.style.setProperty('--rs-workarea-sidebar-bg', hasImage ? 'var(--rs-image-sidebar-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-workarea-editor-bg', hasImage ? 'var(--rs-image-editor-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? '82%' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'transparent' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? 'var(--rs-surface-opacity)' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'var(--rs-transparent-plugin-bg)' : 'var(--rs-bg)');
}
async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) {
const id = background?.imageId;
@@ -120,7 +158,11 @@ function applyBackgroundImage(root: HTMLElement, image?: string) {
if (previous) URL.revokeObjectURL(previous.url);
}
export function applyAppearance(value: Appearance, root = document.documentElement) {
const { theme, mode, newTabBackground } = normalizeAppearance(value);
const normalized = normalizeAppearance(value);
const { theme, newTabBackground } = normalized;
const custom = theme.startsWith('custom:') ? customThemes(normalized.mode).find(item => item.id === theme.slice(7)) : undefined;
const mode = custom ? customThemeMode(custom.colors) : normalized.mode;
applyTransparency(normalized.transparency, root);
root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)');
const overlay = newTabBackground?.overlay ?? 0;
const shade = overlay < 0 ? '255,255,255' : '0,0,0';
@@ -132,6 +174,8 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
root.dataset.theme = mode;
root.dataset.palette = theme;
root.style.colorScheme = mode;
const fonts = { ...themeFonts(theme), ...custom?.fonts };
FONT_ROLES.forEach(role => root.style.setProperty(`--rs-font-${role}`, fonts[role]));
const palette = builtinPalette(theme)[mode];
keys.forEach((key, index) => root.style.setProperty(`--rs-${key}`, palette[index]));
root.style.setProperty('--rs-accent-2', characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : 'var(--rs-accent)'));
@@ -149,8 +193,7 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
['parameter', 'keyword', 'local', 'static', 'instance', 'global'].forEach((key, index) => root.style.setProperty(`--rs-syntax-${key}`, syntax[index]));
for (const [key, color] of Object.entries(characterSyntax(theme))) root.style.setProperty(`--rs-${key}`, color);
root.style.setProperty('--rs-danger', 'var(--rs-error)');
const custom = theme.startsWith('custom:') ? customThemes().find(item => item.id === theme.slice(7)) : undefined;
if (custom) for (const [key, color] of Object.entries(custom[mode])) root.style.setProperty(`--rs-${key}`, color);
if (custom) for (const [key, color] of Object.entries(custom.colors)) root.style.setProperty(`--rs-${key}`, color);
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
}
export function saveAppearance(value: Appearance) {
+53 -8
View File
@@ -1,13 +1,16 @@
export const CUSTOM_THEMES_KEY = "runestone.custom-themes";
export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const;
export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>;
export type CustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
export const FONT_ROLES = ['ui', 'prose', 'heading', 'mono'] as const;
export type ThemeFonts = Partial<Record<typeof FONT_ROLES[number], string>>;
export type CustomTheme = { schema: 2; id: string; name: string; colors: ThemeColors; fonts?: ThemeFonts };
export type LegacyCustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
export function parseCustomTheme(input: unknown): CustomTheme {
export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" = "dark"): CustomTheme {
if (!input || typeof input !== "object") throw new Error("Choose a RuneStone theme JSON file.");
const value = input as Record<string, unknown>;
if (value.schema !== 1 || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 1, an ID, and a name.");
if ((value.schema !== 1 && value.schema !== 2) || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 2, an ID, and a name.");
const colors = (mode: string): ThemeColors => {
const source = value[mode];
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(`The theme needs ${mode} colors.`);
@@ -20,13 +23,55 @@ export function parseCustomTheme(input: unknown): CustomTheme {
if (!result.bg || !result.text || !result.accent) throw new Error(`The ${mode} palette needs bg, text, and accent.`);
return result;
};
return { schema: 1, id: value.id, name: value.name.trim(), light: colors("light"), dark: colors("dark") };
if (value.schema === 1) { colors("light"); colors("dark"); }
let fonts: ThemeFonts | undefined;
if (value.fonts !== undefined) {
if (!value.fonts || typeof value.fonts !== 'object' || Array.isArray(value.fonts)) throw new Error('Use an object for theme fonts.');
fonts = {};
for (const [role, stack] of Object.entries(value.fonts)) {
if (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(`Unknown theme font: ${role}`);
if (typeof stack !== 'string' || stack.length > 512 || !/^[\p{L}\p{N} _,'"-]+$/u.test(stack) || !stack.trim()
|| stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(`Use a font family stack for ${role}.`);
fonts[role as keyof ThemeFonts] = stack.trim();
}
}
return { schema: 2, id: value.id, name: value.name.trim(), colors: colors(value.schema === 1 ? legacyMode : "colors"), ...(fonts ? { fonts } : {}) };
}
export function customThemes(): CustomTheme[] {
const pendingLegacy = new Map<string, CustomTheme[]>();
export function customThemes(legacyMode?: "light" | "dark"): CustomTheme[] {
try {
const stored = JSON.parse(localStorage.getItem(CUSTOM_THEMES_KEY) || "[]");
return Array.isArray(stored) ? stored.flatMap(value => { try { return [parseCustomTheme(value)]; } catch { return []; } }) : [];
const raw = localStorage.getItem(CUSTOM_THEMES_KEY) || "[]";
const pending = pendingLegacy.get(raw);
if (pending) return pending.map(theme => ({ ...theme, colors: { ...theme.colors } }));
const stored = JSON.parse(raw);
if (!Array.isArray(stored)) return [];
if (!legacyMode) {
try { legacyMode = JSON.parse(localStorage.getItem('runestone.appearance') || 'null')?.mode === 'light' ? 'light' : 'dark'; }
catch { legacyMode = 'dark'; }
}
const parsed = stored.flatMap(value => { try { return [parseCustomTheme(value, legacyMode)]; } catch { return []; } });
if (stored.some(value => value?.schema === 1)) {
// Retain both original palettes before converting the saved selection to one palette.
try {
const backupKey = `${CUSTOM_THEMES_KEY}.legacy`;
const backup = JSON.parse(localStorage.getItem(backupKey) || '[]');
if (!Array.isArray(backup)) throw new Error('Invalid legacy backup');
const originals = backup;
for (const value of stored.filter(value => value?.schema === 1)) {
if (!originals.some(item => JSON.stringify(item) === JSON.stringify(value))) originals.push(value);
}
localStorage.setItem(backupKey, JSON.stringify(originals));
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(stored.map(value => {
try { return parseCustomTheme(value, legacyMode); } catch { return value; }
})));
} catch {
// Storage failures must not hide readable themes or change their chosen palette.
pendingLegacy.set(raw, parsed);
}
}
return parsed;
} catch { return []; }
}
+11 -7
View File
@@ -6,11 +6,15 @@
--rs-tooltip-shadow: 0 4px 16px #0005;
--rs-tooltip-font-size: 12px;
--rs-control-radius: 5px;
--rs-image-control-bg: color-mix(in srgb, var(--rs-bg) 82%, transparent);
--rs-image-control-hover-bg: color-mix(in srgb, var(--rs-bg-active) 92%, transparent);
--rs-image-sidebar-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-image-editor-bg: color-mix(in srgb, var(--rs-bg) 90%, transparent);
--rs-code-block-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-surface-opacity: 82%;
--rs-editor-surface-opacity: 90%;
--rs-hover-surface-opacity: 92%;
--rs-transparent-plugin-bg: transparent;
--rs-image-control-bg: color-mix(in srgb, var(--rs-bg) var(--rs-surface-opacity), transparent);
--rs-image-control-hover-bg: color-mix(in srgb, var(--rs-bg-active) var(--rs-hover-surface-opacity), transparent);
--rs-image-sidebar-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-image-editor-bg: color-mix(in srgb, var(--rs-bg) var(--rs-editor-surface-opacity), transparent);
--rs-code-block-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-workarea-sidebar-bg: var(--rs-bg-elevated);
--rs-workarea-editor-bg: var(--rs-bg);
--rs-workarea-surface-opacity: 100%;
@@ -30,8 +34,8 @@
--rs-menu-icon-gap: 8px;
--rs-menu-font-size: 13px;
--rs-menu-border: transparent;
--rs-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-menu-active-bg: color-mix(in srgb, var(--rs-bg-active) 82%, transparent);
--rs-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-menu-active-bg: color-mix(in srgb, var(--rs-bg-active) var(--rs-surface-opacity), transparent);
--rs-menu-shadow: 0 8px 30px #0006;
--rs-item-selection-radius: var(--rs-control-radius);
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent);
+5 -4
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount } from "svelte";
import { getCurrentWindow } from "@tauri-apps/api/window";
import IconButton from "./IconButton.svelte";
@@ -32,12 +33,12 @@
});
</script>
<div class="window-controls" role="group" aria-label="Window controls">
<IconButton icon="minimize" label="Minimize window" onclick={() => void run("minimize")} />
<div class="window-controls" role="group" aria-label={$t("Window controls")}>
<IconButton icon="minimize" label={$t("Minimize window")} onclick={() => void run("minimize")} />
<IconButton icon={maximized ? "window-restore" : "window-maximize"}
label={maximized ? "Restore window" : "Maximize window"} onclick={() => void run("toggleMaximize")} />
label={maximized ? $t("Restore window") : $t("Maximize window")} onclick={() => void run("toggleMaximize")} />
<div class="window-close">
<IconButton icon="close" label="Close window" onclick={() => void run("close")} />
<IconButton icon="close" label={$t("Close window")} onclick={() => void run("close")} />
</div>
</div>
+7
View File
@@ -1,5 +1,12 @@
// Stroke icons share the same 24px grid and weight as IconButton.
export const actionIcons = {
play: '<path d="m7 4 14 8-14 8Z"/>',
pause: '<path d="M7 4v16M17 4v16"/>',
'skip-forward': '<path d="m4 4 12 8-12 8ZM20 4v16"/>',
eye: '<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/>',
'eye-off': '<path d="m3 3 18 18M10.6 5.1 12 5c6.5 0 10 7 10 7a18 18 0 0 1-3.1 3.8M6.2 6.2A21 21 0 0 0 2 12s3.5 7 10 7a13 13 0 0 0 5.8-1.4M9.9 9.9a3 3 0 0 0 4.2 4.2"/>',
image: '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8" cy="8" r="1.5"/><path d="m21 15-5-5L5 21"/>',
settings: '<path d="M4 7h16M4 17h16"/><circle cx="9" cy="7" r="3"/><circle cx="15" cy="17" r="3"/>',
archive: '<path d="M4 8v12h16V8M3 3h18v5H3zM9 12h6"/>',
save: '<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><path d="M17 21v-8H7v8M7 3v5h8"/>',
refresh: '<path d="M20 7v5h-5M4 17v-5h5M6 7a7 7 0 0 1 12-1l2 3M4 15l2 3a7 7 0 0 0 12-1"/>',
+1 -1
View File
@@ -46,5 +46,5 @@
.rs-menu > button > .action-icon, .rs-picker-icon { width: var(--rs-menu-icon-size); height: var(--rs-menu-icon-size); flex: 0 0 var(--rs-menu-icon-size); }
.rs-picker-hint { display: block; color: var(--rs-text-dim); font-size: var(--rs-settings-description-size); }
.rs-picker-icon > svg { width: 100%; height: 100%; }
.rs-menu > button > .action-label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
.rs-menu > button > .action-label { flex: 1; min-width: 0; overflow: visible; text-overflow: clip; white-space: normal; overflow-wrap: anywhere; }
.rs-menu > button > .action-chevron { width: 13px; height: 13px; flex: 0 0 13px; }
+6 -1
View File
@@ -2,8 +2,9 @@ import { invoke } from "@tauri-apps/api/core";
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
import { open as openDialog } from "@tauri-apps/plugin-dialog";
import type { TreeEntry, WorkspaceEvent, WorkspaceInfo } from "./types";
import { tr } from "../i18n/index.ts";
export async function pickWorkspaceFolder(title = "Open workspace"): Promise<string | null> {
export async function pickWorkspaceFolder(title = tr("Open workspace")): Promise<string | null> {
const selected = await openDialog({
directory: true,
multiple: false,
@@ -31,6 +32,10 @@ export function workspaceRecent(): Promise<string[]> {
return invoke("workspace_recent");
}
export function workspaceForget(path: string): Promise<string[]> {
return invoke("workspace_forget", { path });
}
export function workspaceNew(parent: string, name: string): Promise<void> {
return invoke("workspace_new", { parent, name });
}