Send the remaining interface text through the catalog and audit it
Phase 4f. - scripts/i18nAudit.mjs runs in pnpm check. It fails for a key that the catalog does not have, a catalog key that the code does not use, and a row without all four languages. - message() marks a key that a variable carries to the translation call later: table formats, formula errors, and browser status messages. - 53 new rows with French, Japanese, and Simplified Chinese text for the status and error messages of the workbench, the tree, Settings, theme import, images, the built-in browser, and code blocks. The backlinks toggle now translates too. - 13 unused rows are gone. - Errors of the plugin API stay in English. docs/development.md has the rule in "Interface text". pnpm check, pnpm test (350 of 350), and the full smoke suite pass, except two tests that failed one time under load and passed on retry and 3 of 3 times alone.
This commit is contained in:
@@ -20,7 +20,7 @@ The [development guide](docs/development.md#architecture) maps the source folder
|
|||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `pnpm install --frozen-lockfile` | Install dependencies |
|
| `pnpm install --frozen-lockfile` | Install dependencies |
|
||||||
| `pnpm tauri dev` | Run the desktop app with hot reload |
|
| `pnpm tauri dev` | Run the desktop app with hot reload |
|
||||||
| `pnpm check` | Type checks of the app and the unit tests |
|
| `pnpm check` | Type checks of the app and the unit tests, then the translation catalog audit |
|
||||||
| `pnpm test` | Unit tests (`tests/unit/`) |
|
| `pnpm test` | Unit tests (`tests/unit/`) |
|
||||||
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust tests |
|
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust tests |
|
||||||
| `pnpm check:menus` | Menu surface inventory |
|
| `pnpm check:menus` | Menu surface inventory |
|
||||||
|
|||||||
+15
-2
@@ -170,14 +170,15 @@ Run these commands from the repository folder. They do not need an installer.
|
|||||||
|
|
||||||
| Command | Checks |
|
| Command | Checks |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `pnpm check` | Svelte and TypeScript types of the app, the unit tests (`tests/tsconfig.json`), the plugin SDK, and the example plugin |
|
| `pnpm check` | Svelte and TypeScript types of the app, the unit tests (`tests/tsconfig.json`), the plugin SDK, and the example plugin. Then the catalog audit. See [Interface text](#interface-text). |
|
||||||
| `pnpm test` | Unit tests in `tests/unit/` |
|
| `pnpm test` | Unit tests in `tests/unit/` |
|
||||||
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust unit tests |
|
| `cargo test --manifest-path src-tauri/Cargo.toml --lib` | Rust unit tests |
|
||||||
| `pnpm smoke` | Browser smoke tests. See [Browser smoke tests](#browser-smoke-tests). |
|
| `pnpm smoke` | Browser smoke tests. See [Browser smoke tests](#browser-smoke-tests). |
|
||||||
| `pnpm build` | The production frontend build |
|
| `pnpm build` | The production frontend build |
|
||||||
| `pnpm check:menus` | The inventory of menu surfaces. See [Interface design](ui-design.md). |
|
| `pnpm check:menus` | The inventory of menu surfaces. See [Interface design](ui-design.md). |
|
||||||
|
|
||||||
To run one test file, use `node --experimental-strip-types --test tests/unit/tables/selection.spec.ts`.
|
To run one test file, use `node --experimental-strip-types --import ./tests/unit/_svelte/register.mjs --test tests/unit/tables/selection.spec.ts`.
|
||||||
|
The `--import` hook compiles `.svelte.ts` modules, so a test can import them.
|
||||||
For type errors while you edit, run `pnpm check:watch`.
|
For type errors while you edit, run `pnpm check:watch`.
|
||||||
|
|
||||||
Some tests need files from outside this repository. Without those files, the tests skip and state the reason:
|
Some tests need files from outside this repository. Without those files, the tests skip and state the reason:
|
||||||
@@ -185,6 +186,18 @@ Some tests need files from outside this repository. Without those files, the tes
|
|||||||
- `tests/unit/release/installerVersion.spec.ts` needs the NSIS compiler that the Tauri CLI downloads on Windows.
|
- `tests/unit/release/installerVersion.spec.ts` needs the NSIS compiler that the Tauri CLI downloads on Windows.
|
||||||
- The Rust terminal tests start the real shells on the computer.
|
- The Rust terminal tests start the real shells on the computer.
|
||||||
|
|
||||||
|
### Interface text
|
||||||
|
|
||||||
|
All text that a user reads goes through the catalog in `src/lib/i18n/messages.ts`. Each row has the English key and the French, Japanese, and Simplified Chinese text.
|
||||||
|
|
||||||
|
1. Translate the text with `$t("…")` in a Svelte component or `tr("…")` in a TypeScript module.
|
||||||
|
2. For a value in the text, use a placeholder: `tr("Created {path}", { path })`. Do not join strings.
|
||||||
|
3. When a variable carries a key to the call, mark the key where you write it: `message("Bold")`.
|
||||||
|
4. Add a catalog row with all four languages.
|
||||||
|
|
||||||
|
Errors of the plugin API stay in English, because they are for plugin developers.
|
||||||
|
`pnpm check` runs `scripts/i18nAudit.mjs`. It fails for a key that the catalog does not have, a catalog key that the code does not use, and a row without all translations.
|
||||||
|
|
||||||
## Plugin SDK
|
## Plugin SDK
|
||||||
|
|
||||||
The plugin SDK in `packages/plugin-sdk/` is the only source of the public plugin types.
|
The plugin SDK in `packages/plugin-sdk/` is the only source of the public plugin types.
|
||||||
|
|||||||
+1
-1
@@ -9,7 +9,7 @@
|
|||||||
"build:installer": "node scripts/buildInstaller.mjs",
|
"build:installer": "node scripts/buildInstaller.mjs",
|
||||||
"preview": "vite preview",
|
"preview": "vite preview",
|
||||||
"prepare": "svelte-kit sync || echo ''",
|
"prepare": "svelte-kit sync || echo ''",
|
||||||
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tests/tsconfig.json && tsc -p packages/plugin-sdk/tsconfig.json --noEmit && tsc -p fixtures/plugins/tsconfig.json",
|
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json && svelte-check --tsconfig ./tests/tsconfig.json && tsc -p packages/plugin-sdk/tsconfig.json --noEmit && tsc -p fixtures/plugins/tsconfig.json && node scripts/i18nAudit.mjs",
|
||||||
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
|
||||||
"check:menus": "node scripts/menuSurfaceAudit.mjs",
|
"check:menus": "node scripts/menuSurfaceAudit.mjs",
|
||||||
"tauri": "tauri",
|
"tauri": "tauri",
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
// Check the translation catalog (src/lib/i18n/messages.ts) against the code:
|
||||||
|
// - unknown: the code translates a key that the catalog does not have,
|
||||||
|
// - unused: the catalog has a key that the code never translates,
|
||||||
|
// - untranslated: a catalog row has an empty or missing translation.
|
||||||
|
// The code translates a key with `$t("…")` in Svelte, `tr("…")` in TypeScript, or marks it with `message("…")`
|
||||||
|
// when a variable carries it to the translation call later. Every string literal in the first argument counts,
|
||||||
|
// so `tr(open ? "Close" : "Open")` uses both keys.
|
||||||
|
import { readdir, readFile } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||||
|
|
||||||
|
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||||
|
const catalogFile = path.join(root, "src/lib/i18n/messages.ts");
|
||||||
|
const calls = /(?:\$t|\btr|\bmessage)\(/g;
|
||||||
|
|
||||||
|
async function sources(dir) {
|
||||||
|
const entries = await readdir(dir, { withFileTypes: true });
|
||||||
|
const nested = await Promise.all(entries.map(entry => entry.isDirectory()
|
||||||
|
? sources(path.join(dir, entry.name))
|
||||||
|
: /\.(svelte|ts)$/.test(entry.name) ? [path.join(dir, entry.name)] : []));
|
||||||
|
return nested.flat();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The string literals of the first argument that starts at `start`. A literal in a comparison is not a key. */
|
||||||
|
function argumentKeys(source, start) {
|
||||||
|
const keys = [];
|
||||||
|
let depth = 0;
|
||||||
|
for (let index = start; index < source.length; index++) {
|
||||||
|
const char = source[index];
|
||||||
|
if (char === "\"" || char === "'" || char === "`") {
|
||||||
|
let value = "", end = index + 1, dynamic = false;
|
||||||
|
for (; end < source.length && source[end] !== char; end++) {
|
||||||
|
if (source[end] === "\\") { value += source[++end]; continue; }
|
||||||
|
if (char === "`" && source[end] === "$" && source[end + 1] === "{") dynamic = true;
|
||||||
|
value += source[end];
|
||||||
|
}
|
||||||
|
const compared = /[=!]==?\s*$/.test(source.slice(start, index)) || /^\s*[=!]==?/.test(source.slice(end + 1));
|
||||||
|
if (!dynamic && !compared) keys.push(value);
|
||||||
|
index = end;
|
||||||
|
} else if ("([{".includes(char)) depth++;
|
||||||
|
else if (")]}".includes(char)) { if (depth === 0) break; depth--; }
|
||||||
|
else if (char === "," && depth === 0) break;
|
||||||
|
}
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function auditCatalog() {
|
||||||
|
const { messageRows } = await import(pathToFileURL(catalogFile).href);
|
||||||
|
const catalog = new Map(messageRows.map(row => [row[0], row]));
|
||||||
|
const used = new Set();
|
||||||
|
const failures = [];
|
||||||
|
for (const file of await sources(path.join(root, "src"))) {
|
||||||
|
if (file === catalogFile) continue;
|
||||||
|
const source = await readFile(file, "utf8");
|
||||||
|
for (const match of source.matchAll(calls)) {
|
||||||
|
for (const key of argumentKeys(source, match.index + match[0].length)) {
|
||||||
|
used.add(key);
|
||||||
|
if (!catalog.has(key)) {
|
||||||
|
const line = source.slice(0, match.index).split("\n").length;
|
||||||
|
failures.push(`Unknown key: ${path.relative(root, file).replaceAll("\\", "/")}:${line}: ${key}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [key, row] of catalog) {
|
||||||
|
if (!used.has(key)) failures.push(`Unused key: ${key}`);
|
||||||
|
if (row.length < 4 || row.slice(1).some(value => !value?.trim())) failures.push(`Untranslated key: ${key}`);
|
||||||
|
}
|
||||||
|
return { failures, keys: catalog.size, used: used.size };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
const { failures, keys } = await auditCatalog();
|
||||||
|
if (failures.length) { console.error(failures.join("\n")); process.exitCode = 1; }
|
||||||
|
else console.log(`PASS: the code uses all ${keys} catalog keys, and each key has every translation.`);
|
||||||
|
}
|
||||||
@@ -261,7 +261,7 @@
|
|||||||
oncompositionend={event => { composing = false; if (event.data) void orderedInput('insertText', { text: event.data }); textInput.value = ''; }}
|
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 = ''; } }}
|
oninput={() => { if (!composing && textInput.value) { void orderedInput('insertText', { text: textInput.value }); textInput.value = ''; } }}
|
||||||
onblur={stopScroll}></textarea>
|
onblur={stopScroll}></textarea>
|
||||||
{#if image && ready && !blank}<img src={image} alt="Web page rendered by the browser" draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
|
{#if image && ready && !blank}<img src={image} alt={$t("Web page rendered by the browser")} draggable="false" onload={acknowledgeFrame} onerror={acknowledgeFrame}>{/if}
|
||||||
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
|
{#if scrollAnchor}<span class="scroll-anchor" style:left={`${scrollAnchor.x}px`} style:top={`${scrollAnchor.y}px`} aria-hidden="true">↕</span>{/if}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -48,7 +48,7 @@
|
|||||||
{#if busy}<p role="status">{$t("Please wait…")}</p>{/if}
|
{#if busy}<p role="status">{$t("Please wait…")}</p>{/if}
|
||||||
<div class="entries" aria-busy={busy}>
|
<div class="entries" aria-busy={busy}>
|
||||||
{#if kind === 'cookies'}
|
{#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={$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}
|
{#each cookies as cookie (cookie.id)}<div class="entry"><div><strong>{cookie.name || $t("(unnamed cookie)")}</strong><small>{cookie.domain} · {cookie.path}</small></div><button disabled={busy} aria-label={$t("Remove cookie {name} from {domain} at {path}", { name: cookie.name, domain: cookie.domain, path: cookie.path })} onclick={() => void remove('removeCookie', cookie.id)}><Icon icon="trash" />{$t("Remove")}</button></div>{/each}
|
||||||
{#if data && !cookies.length}<p>{$t("No matching cookies.")}</p>{/if}
|
{#if data && !cookies.length}<p>{$t("No matching cookies.")}</p>{/if}
|
||||||
{:else}
|
{:else}
|
||||||
{#each history as visit (visit.id)}<div class="entry"><div><strong>{visit.title || visit.url}</strong><small>{visit.url}</small><small>{new Date(visit.at).toLocaleString()}</small></div><button disabled={busy} aria-label={$t("Remove history entry {name}", { name: visit.title || visit.url })} onclick={() => void remove('removeHistory', visit.id)}><Icon icon="trash" />{$t("Remove")}</button></div>{/each}
|
{#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}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { tr } from "../i18n/index.ts";
|
||||||
import { mount, unmount } from 'svelte';
|
import { mount, unmount } from 'svelte';
|
||||||
import { get } from 'svelte/store';
|
import { get } from 'svelte/store';
|
||||||
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
|
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||||
@@ -60,13 +61,13 @@ export async function activate(api: PluginApi) {
|
|||||||
const web = ready && /^https?:\/\//.test(current?.url || '');
|
const web = ready && /^https?:\/\//.test(current?.url || '');
|
||||||
return [
|
return [
|
||||||
{ separator: true },
|
{ separator: true },
|
||||||
{ label: 'Move to new window', icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
|
{ label: tr("Move to new window"), icon: 'external', disabled: !ready, run: () => run('moveToWindow', { pinned }) },
|
||||||
{ label: 'Split right', icon: 'split-right', disabled: !ready, run: () => split('right') },
|
{ label: tr("Split right"), icon: 'split-right', disabled: !ready, run: () => split('right') },
|
||||||
{ label: 'Split down', icon: 'split-down', disabled: !ready, run: () => split('down') },
|
{ label: tr("Split down"), icon: 'split-down', disabled: !ready, run: () => split('down') },
|
||||||
{ separator: true },
|
{ separator: true },
|
||||||
{ label: 'Find…', icon: 'search', shortcut: 'Ctrl+F', disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
|
{ label: tr("Find…"), icon: 'search', shortcut: 'Ctrl+F', disabled: !ready, run: () => { api.openView(id); void saved.control?.find(); } },
|
||||||
{ label: 'Open in default browser', icon: 'external', disabled: !web, run: () => run('openExternal') },
|
{ label: tr("Open in default browser"), icon: 'external', disabled: !web, run: () => run('openExternal') },
|
||||||
{ label: 'Bookmark', icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
|
{ label: tr("Bookmark"), icon: 'bookmark', disabled: !web, run: () => run('bookmark') },
|
||||||
];
|
];
|
||||||
}, mount: container => {
|
}, mount: container => {
|
||||||
let runtimeId = '';
|
let runtimeId = '';
|
||||||
@@ -106,12 +107,12 @@ export async function activate(api: PluginApi) {
|
|||||||
});
|
});
|
||||||
api.registerTabDrop?.(async data => {
|
api.registerTabDrop?.(async data => {
|
||||||
const payload = JSON.parse(data);
|
const payload = JSON.parse(data);
|
||||||
if (!payload || typeof payload.tabId !== 'string' || typeof payload.transferToken !== 'string') throw new Error('Invalid browser tab transfer.');
|
if (!payload || typeof payload.tabId !== 'string' || typeof payload.transferToken !== 'string') throw new Error(tr("Invalid browser tab transfer."));
|
||||||
const existing = owners.get(payload.tabId);
|
const existing = owners.get(payload.tabId);
|
||||||
if (existing) { api.openView(existing.view); return; }
|
if (existing) { api.openView(existing.view); return; }
|
||||||
const snapshot = await request('adoptTab', { tabId: payload.tabId, transferToken: payload.transferToken });
|
const snapshot = await request('adoptTab', { tabId: payload.tabId, transferToken: payload.transferToken });
|
||||||
const current = snapshot.tabs.find(tab => tab.id === payload.tabId);
|
const current = snapshot.tabs.find(tab => tab.id === payload.tabId);
|
||||||
if (!current) throw new Error('The browser tab is unavailable.');
|
if (!current) throw new Error(tr("The browser tab is unavailable."));
|
||||||
await open(current.profileId, current.url, undefined, current.id, payload.pinned === true);
|
await open(current.profileId, current.url, undefined, current.id, payload.pinned === true);
|
||||||
});
|
});
|
||||||
const incoming = new URLSearchParams(location.search).get('browserTab');
|
const incoming = new URLSearchParams(location.search).get('browserTab');
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { message, tr } from "../i18n/index.ts";
|
||||||
import type { Snapshot } from './client';
|
import type { Snapshot } from './client';
|
||||||
|
|
||||||
type Transport = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
type Transport = (command: string, args?: Record<string, unknown>) => Promise<unknown>;
|
||||||
@@ -32,9 +33,9 @@ export class TabSession {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
private failure(operation: string, error: unknown, tabId = this.value.tabId, phase: 'ready' | 'disconnected' = 'disconnected') {
|
private failure(operation: string, error: unknown, tabId = this.value.tabId, phase: 'ready' | 'disconnected' = 'disconnected') {
|
||||||
this.update({ phase, message: phase === 'ready' ? 'The browser could not complete this request. Check the error details.' : connectionLost(error)
|
this.update({ phase, message: phase === 'ready' ? message('The browser could not complete this request. Check the error details.') : connectionLost(error)
|
||||||
? 'This tab lost its browser connection. Select Reconnect to restore the page.'
|
? message('This tab lost its browser connection. Select Reconnect to restore the page.')
|
||||||
: 'The browser could not complete this request. Check the details, then select Reconnect.',
|
: message('The browser could not complete this request. Check the details, then select Reconnect.'),
|
||||||
detail: { operation, reason: String(error), tabId, time: new Date().toISOString() } });
|
detail: { operation, reason: String(error), tabId, time: new Date().toISOString() } });
|
||||||
}
|
}
|
||||||
connect(): Promise<void> {
|
connect(): Promise<void> {
|
||||||
@@ -44,7 +45,7 @@ export class TabSession {
|
|||||||
return this.pending;
|
return this.pending;
|
||||||
}
|
}
|
||||||
private async restore() {
|
private async restore() {
|
||||||
this.update({ phase: 'connecting', message: this.value.tabId ? 'Reconnecting browser…' : 'Opening browser…' });
|
this.update({ phase: 'connecting', message: this.value.tabId ? message('Reconnecting browser…') : message('Opening browser…') });
|
||||||
let operation = 'state';
|
let operation = 'state';
|
||||||
// The host discards a failed transport before the next request.
|
// The host discards a failed transport before the next request.
|
||||||
for (let attempt = 0; attempt < 2; attempt++) {
|
for (let attempt = 0; attempt < 2; attempt++) {
|
||||||
@@ -66,7 +67,7 @@ export class TabSession {
|
|||||||
if (current.tabs.some(tab => tab.id === result.tabId)) {
|
if (current.tabs.some(tab => tab.id === result.tabId)) {
|
||||||
this.observe(current); this.update({ phase: 'ready', message: '' }); return;
|
this.observe(current); this.update({ phase: 'ready', message: '' }); return;
|
||||||
}
|
}
|
||||||
if (attempt === 1) throw new Error('The runtime restarted twice while opening this tab.');
|
if (attempt === 1) throw new Error(tr("The runtime restarted twice while opening this tab."));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (this.closed) return;
|
if (this.closed) return;
|
||||||
if (attempt === 0 && connectionLost(error)) continue;
|
if (attempt === 0 && connectionLost(error)) continue;
|
||||||
|
|||||||
@@ -166,14 +166,14 @@
|
|||||||
for (const path of linkCandidates(buffer.relPath, image.dataset.mdSrc || "", "md")) {
|
for (const path of linkCandidates(buffer.relPath, image.dataset.mdSrc || "", "md")) {
|
||||||
try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ }
|
try { await workspaceReadDataUrl(path); await workspaceReveal(path); return; } catch { /* Try the workspace-relative image. */ }
|
||||||
}
|
}
|
||||||
throw new Error("Could not find this image in the workspace.");
|
throw new Error($t("Could not find this image in the workspace."));
|
||||||
},
|
},
|
||||||
validate: async source => {
|
validate: async source => {
|
||||||
if (isRemoteImage(source)) return;
|
if (isRemoteImage(source)) return;
|
||||||
for (const path of linkCandidates(buffer.relPath, source, "md")) {
|
for (const path of linkCandidates(buffer.relPath, source, "md")) {
|
||||||
try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ }
|
try { await workspaceReadDataUrl(path); return; } catch { /* Try the workspace-relative image. */ }
|
||||||
}
|
}
|
||||||
throw new Error("Choose an image that exists in the workspace.");
|
throw new Error($t("Choose an image that exists in the workspace."));
|
||||||
},
|
},
|
||||||
report: message => { error = message; },
|
report: message => { error = message; },
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ export function codeMenu(view: EditorView, report: (message: string) => void) {
|
|||||||
try {
|
try {
|
||||||
if (kind === "paste") replace(await navigator.clipboard.readText());
|
if (kind === "paste") replace(await navigator.clipboard.readText());
|
||||||
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
|
else { await navigator.clipboard.writeText(selected); if (kind === "cut") replace(""); }
|
||||||
} 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 changeAll = () => {
|
const changeAll = () => {
|
||||||
if (!valid() || !word) return;
|
if (!valid() || !word) return;
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ async function copyImage(image: HTMLImageElement) {
|
|||||||
const canvas = document.createElement("canvas");
|
const canvas = document.createElement("canvas");
|
||||||
canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
|
canvas.width = image.naturalWidth; canvas.height = image.naturalHeight;
|
||||||
const context = canvas.getContext("2d");
|
const context = canvas.getContext("2d");
|
||||||
if (!context) throw new Error("Image clipboard is unavailable.");
|
if (!context) throw new Error(tr("Image clipboard is unavailable."));
|
||||||
context.drawImage(image, 0, 0);
|
context.drawImage(image, 0, 0);
|
||||||
return await new Promise<Blob>((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not copy image.")), "image/png"));
|
return await new Promise<Blob>((resolve, reject) => canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error("Could not copy image.")), "image/png"));
|
||||||
})();
|
})();
|
||||||
|
|||||||
@@ -77,7 +77,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
|
|||||||
if (!value) value = await navigator.clipboard.readText();
|
if (!value) value = await navigator.clipboard.readText();
|
||||||
if (value) apply(replacement(selection, value.replace(/\r?\n/g, source.includes("\r\n") ? "\r\n" : "\n")));
|
if (value) apply(replacement(selection, value.replace(/\r?\n/g, source.includes("\r\n") ? "\r\n" : "\n")));
|
||||||
}
|
}
|
||||||
} 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 paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) });
|
const paragraph = (label: string, style: ParagraphStyle, icon: "bullet" | "number" | "task" | "heading" | "paragraph" | "quote"): ActionMenuItem => ({ label, icon, run: () => apply(paragraphText(source, selection, style)) });
|
||||||
@@ -126,7 +126,7 @@ export function markdownMenu(editor: MarkdownMenuEditor, actions: TableContextAc
|
|||||||
if (!suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true });
|
if (!suggestions.length) suggestions.push({ label: tr("No spelling suggestions"), disabled: true });
|
||||||
suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => {
|
suggestions.push({ label: tr("Add to dictionary"), icon: "book", run: () => {
|
||||||
close();
|
close();
|
||||||
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report("Could not add the word to the dictionary."));
|
void invoke("spelling_suggestions", { word: word.word, languages: [result.language], add: true }).catch(() => report(tr("Could not add the word to the dictionary.")));
|
||||||
} });
|
} });
|
||||||
const focusedLabel = opened.element.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
|
const focusedLabel = opened.element.contains(document.activeElement) ? document.activeElement?.querySelector(".action-label")?.textContent : undefined;
|
||||||
opened.close();
|
opened.close();
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { tr } from '../i18n/index.ts';
|
import { message, tr } from '../i18n/index.ts';
|
||||||
import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
|
import { getMarkRange, type Editor, type JSONContent } from "@tiptap/core";
|
||||||
import { requestText } from "../workspace/dialogs.svelte";
|
import { requestText } from "../workspace/dialogs.svelte";
|
||||||
import { extractedCellMarkdown } from "./tableCellMarkdown";
|
import { extractedCellMarkdown } from "./tableCellMarkdown";
|
||||||
@@ -14,8 +14,8 @@ export type TableContextActions = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const cellFormats = [
|
export const cellFormats = [
|
||||||
["Bold", "bold"], ["Italic", "italic"], ["Strikethrough", "strike"], ["Highlight", "highlight"],
|
[message("Bold"), "bold"], [message("Italic"), "italic"], [message("Strikethrough"), "strike"], [message("Highlight"), "highlight"],
|
||||||
["Code", "code"], ["Math", "math"], ["Comment", "comment"], ["Clear formatting", "clear"],
|
[message("Code"), "code"], [message("Math"), "math"], [message("Comment"), "comment"], [message("Clear formatting"), "clear"],
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void, editSource: (range: { from: number; to: number }) => void): ActionMenuItem[] {
|
export function tableTextItems(editor: Editor, actions: TableContextActions, close: () => void, transaction: (run: () => void) => void, pending: (value: boolean) => void, report: (message: string) => void, editSource: (range: { from: number; to: number }) => void): ActionMenuItem[] {
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
// The table formula engine. Formulas are plain Markdown cell text.
|
// The table formula engine. Formulas are plain Markdown cell text.
|
||||||
// The engine does not evaluate JavaScript and does not read external data.
|
// The engine does not evaluate JavaScript and does not read external data.
|
||||||
export const formulaErrors = {
|
export const formulaErrors = {
|
||||||
"#ERROR!": "Invalid formula syntax or function arguments",
|
"#ERROR!": message("Invalid formula syntax or function arguments"),
|
||||||
"#REF!": "Cell reference is outside this table",
|
"#REF!": message("Cell reference is outside this table"),
|
||||||
"#VALUE!": "Expected a number",
|
"#VALUE!": message("Expected a number"),
|
||||||
"#NAME?": "Unknown function or cell name",
|
"#NAME?": message("Unknown function or cell name"),
|
||||||
"#DIV/0!": "Cannot divide by zero or average an empty range",
|
"#DIV/0!": message("Cannot divide by zero or average an empty range"),
|
||||||
"#CYCLE!": "Circular cell reference",
|
"#CYCLE!": message("Circular cell reference"),
|
||||||
"#NUM!": "Result is not a finite number",
|
"#NUM!": message("Result is not a finite number"),
|
||||||
"#LIMIT!": "Formula is too complex",
|
"#LIMIT!": message("Formula is too complex"),
|
||||||
} as const;
|
} as const;
|
||||||
export type FormulaErrorCode = keyof typeof formulaErrors;
|
export type FormulaErrorCode = keyof typeof formulaErrors;
|
||||||
type ErrorCode = FormulaErrorCode;
|
type ErrorCode = FormulaErrorCode;
|
||||||
@@ -150,4 +150,5 @@ export function evaluateTableFormulas(grid: string[][]): (FormulaResult | null)[
|
|||||||
return { formula, text: code, error: code };
|
return { formula, text: code, error: code };
|
||||||
}
|
}
|
||||||
}));
|
}));
|
||||||
}
|
}import { message } from "../i18n/index.ts";
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,8 @@ export function translate(language: Locale, message: string, values: Record<stri
|
|||||||
return template.replace(/\{(\w+)\}/g, (match, key: string) => Object.hasOwn(values, key) ? String(values[key]) : match);
|
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 const t = derived(locale, language => (message: string, values?: Record<string, string | number>) => translate(language, message, values));
|
||||||
|
/** Mark a catalog key that a variable carries to `$t` or `tr` later. The catalog audit counts it as used. */
|
||||||
|
export const message = <T extends string>(text: T): T => text;
|
||||||
export function tr(message: string, values?: Record<string, string | number>): string {
|
export function tr(message: string, values?: Record<string, string | number>): string {
|
||||||
return translate(get(locale), message, values);
|
return translate(get(locale), message, values);
|
||||||
}
|
}
|
||||||
|
|||||||
+54
-79
@@ -653,12 +653,6 @@ export const messageRows: [string, string, string, string][] = [
|
|||||||
"一致するファイルはありません。",
|
"一致するファイルはありません。",
|
||||||
"没有匹配的文件。"
|
"没有匹配的文件。"
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"{count} files",
|
|
||||||
"{count} fichiers",
|
|
||||||
"{count}個のファイル",
|
|
||||||
"{count} 个文件"
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
" · indexing…",
|
" · indexing…",
|
||||||
" · indexation…",
|
" · indexation…",
|
||||||
@@ -671,12 +665,6 @@ export const messageRows: [string, string, string, string][] = [
|
|||||||
"↑ ↓ 選択 · Enter {action} · Esc 閉じる",
|
"↑ ↓ 選択 · Enter {action} · Esc 閉じる",
|
||||||
"↑ ↓ 选择 · Enter {action} · Esc 关闭"
|
"↑ ↓ 选择 · Enter {action} · Esc 关闭"
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"open",
|
|
||||||
"ouvrir",
|
|
||||||
"開く",
|
|
||||||
"打开"
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"Window controls",
|
"Window controls",
|
||||||
"Commandes de la fenêtre",
|
"Commandes de la fenêtre",
|
||||||
@@ -1697,12 +1685,6 @@ export const messageRows: [string, string, string, string][] = [
|
|||||||
"再読み込み",
|
"再読み込み",
|
||||||
"重新加载"
|
"重新加载"
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"Stop",
|
|
||||||
"Arrêter",
|
|
||||||
"停止",
|
|
||||||
"停止"
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"Address or search",
|
"Address or search",
|
||||||
"Adresse ou recherche",
|
"Adresse ou recherche",
|
||||||
@@ -2489,30 +2471,6 @@ export const messageRows: [string, string, string, string][] = [
|
|||||||
"書式をクリア",
|
"書式をクリア",
|
||||||
"清除格式"
|
"清除格式"
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"Superscript",
|
|
||||||
"Exposant",
|
|
||||||
"上付き文字",
|
|
||||||
"上标"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"Subscript",
|
|
||||||
"Indice",
|
|
||||||
"下付き文字",
|
|
||||||
"下标"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"Underline",
|
|
||||||
"Souligner",
|
|
||||||
"下線",
|
|
||||||
"下划线"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"Style",
|
|
||||||
"Style",
|
|
||||||
"スタイル",
|
|
||||||
"样式"
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"Change all occurrences",
|
"Change all occurrences",
|
||||||
"Modifier toutes les occurrences",
|
"Modifier toutes les occurrences",
|
||||||
@@ -2681,18 +2639,6 @@ export const messageRows: [string, string, string, string][] = [
|
|||||||
"右に列を追加",
|
"右に列を追加",
|
||||||
"在右侧插入列"
|
"在右侧插入列"
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"Add column left",
|
|
||||||
"Ajouter une colonne à gauche",
|
|
||||||
"左に列を追加",
|
|
||||||
"在左侧插入列"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"Add column right",
|
|
||||||
"Ajouter une colonne à droite",
|
|
||||||
"右に列を追加",
|
|
||||||
"在右侧插入列"
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"Move column left",
|
"Move column left",
|
||||||
"Déplacer la colonne à gauche",
|
"Déplacer la colonne à gauche",
|
||||||
@@ -2729,18 +2675,6 @@ export const messageRows: [string, string, string, string][] = [
|
|||||||
"列で降順に並べ替え",
|
"列で降順に並べ替え",
|
||||||
"按列降序排序"
|
"按列降序排序"
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"Delete table",
|
|
||||||
"Supprimer le tableau",
|
|
||||||
"表を削除",
|
|
||||||
"删除表格"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"Insert table",
|
|
||||||
"Insérer un tableau",
|
|
||||||
"表を挿入",
|
|
||||||
"插入表格"
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"Clear selected values and keep the cells.",
|
"Clear selected values and keep the cells.",
|
||||||
"Effacer les valeurs sélectionnées et conserver les cellules.",
|
"Effacer les valeurs sélectionnées et conserver les cellules.",
|
||||||
@@ -2855,18 +2789,6 @@ export const messageRows: [string, string, string, string][] = [
|
|||||||
"{name}をアンインストールしますか?",
|
"{name}をアンインストールしますか?",
|
||||||
"卸载 {name}?"
|
"卸载 {name}?"
|
||||||
],
|
],
|
||||||
[
|
|
||||||
"{name} installed.",
|
|
||||||
"{name} installé.",
|
|
||||||
"{name}をインストールしました。",
|
|
||||||
"已安装 {name}。"
|
|
||||||
],
|
|
||||||
[
|
|
||||||
"{name} installed and enabled.",
|
|
||||||
"{name} installé et activé.",
|
|
||||||
"{name}をインストールして有効にしました。",
|
|
||||||
"已安装并启用 {name}。"
|
|
||||||
],
|
|
||||||
[
|
[
|
||||||
"{name} uninstalled. Settings and workspace documents were kept.",
|
"{name} uninstalled. Settings and workspace documents were kept.",
|
||||||
"{name} désinstallé. Les paramètres et documents ont été conservés.",
|
"{name} désinstallé. Les paramètres et documents ont été conservés.",
|
||||||
@@ -3490,7 +3412,60 @@ export const messageRows: [string, string, string, string][] = [
|
|||||||
["Tables", "Tableaux", "表", "表格"],
|
["Tables", "Tableaux", "表", "表格"],
|
||||||
["Table formulas", "Formules de tableau", "表の数式", "表格公式"],
|
["Table formulas", "Formules de tableau", "表の数式", "表格公式"],
|
||||||
["Calculate table cells that start with =. When this is off, formulas show as text.", "Calculer les cellules de tableau qui commencent par =. Désactivé, les formules s’affichent comme du texte.", "=で始まる表のセルを計算します。オフにすると、数式は文字列として表示されます。", "计算以 = 开头的表格单元格。关闭后,公式显示为文本。"],
|
["Calculate table cells that start with =. When this is off, formulas show as text.", "Calculer les cellules de tableau qui commencent par =. Désactivé, les formules s’affichent comme du texte.", "=で始まる表のセルを計算します。オフにすると、数式は文字列として表示されます。", "计算以 = 开头的表格单元格。关闭后,公式显示为文本。"],
|
||||||
["Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.", "Les formules de tableau sont maintenant intégrées. Vous pouvez supprimer cet ancien paquet. Vos formules restent dans vos fichiers. Pour activer ou désactiver les formules, ouvrez Paramètres → Général.", "表の数式は内蔵されました。この古いパッケージは削除できます。数式はファイルに残ります。数式のオン/オフは「設定 → 一般」で切り替えます。", "表格公式现已内置。可以移除此旧包。公式保留在文件中。要打开或关闭公式,请前往“设置 → 常规”。"]
|
["Table Formulas is now built in. You can remove this old package. Your formulas stay in your files. To turn formulas on or off, go to Settings → General.", "Les formules de tableau sont maintenant intégrées. Vous pouvez supprimer cet ancien paquet. Vos formules restent dans vos fichiers. Pour activer ou désactiver les formules, ouvrez Paramètres → Général.", "表の数式は内蔵されました。この古いパッケージは削除できます。数式はファイルに残ります。数式のオン/オフは「設定 → 一般」で切り替えます。", "表格公式现已内置。可以移除此旧包。公式保留在文件中。要打开或关闭公式,请前往“设置 → 常规”。"],
|
||||||
|
["Could not close settings: {reason}", "Impossible de fermer les paramètres : {reason}", "設定を閉じられませんでした: {reason}", "无法关闭设置:{reason}"],
|
||||||
|
["Could not read your settings. Default settings apply until you save new settings.", "Impossible de lire vos paramètres. Les paramètres par défaut s’appliquent jusqu’à ce que vous en enregistriez de nouveaux.", "設定を読み込めませんでした。新しい設定を保存するまで既定の設定が適用されます。", "无法读取您的设置。在您保存新设置之前,将使用默认设置。"],
|
||||||
|
["The new window did not accept the tab. The source tab remains open.", "La nouvelle fenêtre n’a pas accepté l’onglet. L’onglet d’origine reste ouvert.", "新しいウィンドウがタブを受け付けませんでした。元のタブは開いたままです。", "新窗口未接受该标签页。原标签页保持打开。"],
|
||||||
|
["Could not read your layout. Default layout applies for this window.", "Impossible de lire votre disposition. La disposition par défaut s’applique à cette fenêtre.", "レイアウトを読み込めませんでした。このウィンドウには既定のレイアウトが適用されます。", "无法读取您的布局。此窗口将使用默认布局。"],
|
||||||
|
["Could not save your layout. Layout changes apply for this window only.", "Impossible d’enregistrer votre disposition. Les modifications ne s’appliquent qu’à cette fenêtre.", "レイアウトを保存できませんでした。変更はこのウィンドウにのみ適用されます。", "无法保存您的布局。布局更改仅适用于此窗口。"],
|
||||||
|
["Invalid tab transfer.", "Transfert d’onglet non valide.", "タブの移動が無効です。", "标签页转移无效。"],
|
||||||
|
["Move tabs only between windows of the same workspace.", "Déplacez les onglets uniquement entre les fenêtres du même espace de travail.", "タブは同じワークスペースのウィンドウ間でのみ移動できます。", "只能在同一工作区的窗口之间移动标签页。"],
|
||||||
|
["This tab is already open in this window. The source tab remains open.", "Cet onglet est déjà ouvert dans cette fenêtre. L’onglet d’origine reste ouvert.", "このタブはこのウィンドウですでに開いています。元のタブは開いたままです。", "此标签页已在此窗口中打开。原标签页保持打开。"],
|
||||||
|
["Enable this tab's plugin before moving it to this window.", "Activez le plug-in de cet onglet avant de le déplacer vers cette fenêtre.", "このウィンドウに移動する前に、このタブのプラグインを有効にしてください。", "将此标签页移到此窗口之前,请先启用其插件。"],
|
||||||
|
["The plugin did not open this tab.", "Le plug-in n’a pas ouvert cet onglet.", "プラグインがこのタブを開きませんでした。", "插件未打开此标签页。"],
|
||||||
|
["The plugin did not open this document.", "Le plug-in n’a pas ouvert ce document.", "プラグインがこのドキュメントを開きませんでした。", "插件未打开此文档。"],
|
||||||
|
["This note is no longer available.", "Cette note n’est plus disponible.", "このノートは利用できなくなりました。", "此笔记已不可用。"],
|
||||||
|
["The workspace changed. Open the link menu again.", "L’espace de travail a changé. Ouvrez de nouveau le menu du lien.", "ワークスペースが変更されました。リンクメニューをもう一度開いてください。", "工作区已更改。请重新打开链接菜单。"],
|
||||||
|
["Enter a relative workspace path without reserved characters.", "Saisissez un chemin relatif dans l’espace de travail, sans caractères réservés.", "予約文字を含まないワークスペースの相対パスを入力してください。", "请输入不含保留字符的工作区相对路径。"],
|
||||||
|
["Open a workspace before renaming a document.", "Ouvrez un espace de travail avant de renommer un document.", "ドキュメント名を変更する前にワークスペースを開いてください。", "重命名文档前,请先打开工作区。"],
|
||||||
|
["The workspace changed. Reopen the document.", "L’espace de travail a changé. Rouvrez le document.", "ワークスペースが変更されました。ドキュメントを開き直してください。", "工作区已更改。请重新打开文档。"],
|
||||||
|
["Could not open the app browser.", "Impossible d’ouvrir le navigateur de l’application.", "アプリのブラウザーを開けませんでした。", "无法打开应用内浏览器。"],
|
||||||
|
["Could not add the word to the dictionary.", "Impossible d’ajouter le mot au dictionnaire.", "単語を辞書に追加できませんでした。", "无法将该词添加到词典。"],
|
||||||
|
["Copied workspace paths", "Chemins dans l’espace de travail copiés", "ワークスペースのパスをコピーしました", "已复制工作区路径"],
|
||||||
|
["Copied system paths", "Chemins système copiés", "システムのパスをコピーしました", "已复制系统路径"],
|
||||||
|
["Created {path}", "{path} créé", "{path} を作成しました", "已创建 {path}"],
|
||||||
|
["Moved {count} of {total} items", "{count} élément(s) sur {total} déplacé(s)", "{total} 個中 {count} 個の項目を移動しました", "已移动 {count}/{total} 个项目"],
|
||||||
|
["Copied {count} of {total} items", "{count} élément(s) sur {total} copié(s)", "{total} 個中 {count} 個の項目をコピーしました", "已复制 {count}/{total} 个项目"],
|
||||||
|
["The workspace changed. File moves stopped.", "L’espace de travail a changé. Les déplacements de fichiers sont arrêtés.", "ワークスペースが変更されました。ファイルの移動を停止しました。", "工作区已更改。文件移动已停止。"],
|
||||||
|
["The workspace changed. Paste stopped.", "L’espace de travail a changé. Le collage est arrêté.", "ワークスペースが変更されました。貼り付けを停止しました。", "工作区已更改。粘贴已停止。"],
|
||||||
|
["Move to new window", "Déplacer vers une nouvelle fenêtre", "新しいウィンドウに移動", "移到新窗口"],
|
||||||
|
["Split right", "Scinder à droite", "右に分割", "向右拆分"],
|
||||||
|
["Split down", "Scinder vers le bas", "下に分割", "向下拆分"],
|
||||||
|
["Find…", "Rechercher…", "検索…", "查找…"],
|
||||||
|
["Open in default browser", "Ouvrir dans le navigateur par défaut", "既定のブラウザーで開く", "在默认浏览器中打开"],
|
||||||
|
["Invalid browser tab transfer.", "Transfert d’onglet de navigateur non valide.", "ブラウザータブの移動が無効です。", "浏览器标签页转移无效。"],
|
||||||
|
["The browser tab is unavailable.", "L’onglet du navigateur n’est pas disponible.", "ブラウザータブを利用できません。", "浏览器标签页不可用。"],
|
||||||
|
["Web page rendered by the browser", "Page web affichée par le navigateur", "ブラウザーが表示したウェブページ", "由浏览器呈现的网页"],
|
||||||
|
["Mermaid diagram", "Diagramme Mermaid", "Mermaid 図", "Mermaid 图表"],
|
||||||
|
["Diagram source", "Source du diagramme", "図のソース", "图表源代码"],
|
||||||
|
["The runtime restarted twice while opening this tab.", "Le moteur a redémarré deux fois pendant l’ouverture de cet onglet.", "このタブを開く間にランタイムが2回再起動しました。", "打开此标签页时运行时重启了两次。"],
|
||||||
|
["Could not find this image in the workspace.", "Impossible de trouver cette image dans l’espace de travail.", "この画像がワークスペースに見つかりません。", "在工作区中找不到此图像。"],
|
||||||
|
["Choose an image that exists in the workspace.", "Choisissez une image qui existe dans l’espace de travail.", "ワークスペースにある画像を選択してください。", "请选择工作区中已有的图像。"],
|
||||||
|
["Image clipboard is unavailable.", "Le presse-papiers d’images n’est pas disponible.", "画像のクリップボードを利用できません。", "图像剪贴板不可用。"],
|
||||||
|
["Choose an image of 50 MiB or less.", "Choisissez une image de 50 Mio au plus.", "50 MiB 以下の画像を選択してください。", "请选择 50 MiB 或更小的图像。"],
|
||||||
|
["Choose a RuneStone theme JSON file.", "Choisissez un fichier de thème RuneStone au format JSON.", "RuneStone のテーマ JSON ファイルを選択してください。", "请选择 RuneStone 主题 JSON 文件。"],
|
||||||
|
["The theme needs schema 2, an ID, and a name.", "Le thème nécessite le schéma 2, un identifiant et un nom.", "テーマにはスキーマ 2、ID、名前が必要です。", "主题需要架构 2、ID 和名称。"],
|
||||||
|
["The theme needs {mode} colors.", "Le thème nécessite des couleurs {mode}.", "テーマには {mode} の色が必要です。", "主题需要 {mode} 颜色。"],
|
||||||
|
["Unknown theme color: {key}", "Couleur de thème inconnue : {key}", "不明なテーマの色: {key}", "未知的主题颜色:{key}"],
|
||||||
|
["Use a hexadecimal color for {key}.", "Utilisez une couleur hexadécimale pour {key}.", "{key} には16進数の色を使用してください。", "请为 {key} 使用十六进制颜色。"],
|
||||||
|
["The {mode} palette needs bg, text, and accent.", "La palette {mode} nécessite bg, text et accent.", "{mode} パレットには bg、text、accent が必要です。", "{mode} 调色板需要 bg、text 和 accent。"],
|
||||||
|
["Use an object for theme fonts.", "Utilisez un objet pour les polices du thème.", "テーマのフォントにはオブジェクトを使用してください。", "主题字体请使用对象。"],
|
||||||
|
["Unknown theme font: {role}", "Police de thème inconnue : {role}", "不明なテーマのフォント: {role}", "未知的主题字体:{role}"],
|
||||||
|
["Use a font family stack for {role}.", "Utilisez une liste de familles de polices pour {role}.", "{role} にはフォントファミリーのリストを使用してください。", "请为 {role} 使用字体系列列表。"],
|
||||||
|
["Resolve the disk changes before saving.", "Résolvez les modifications sur le disque avant d’enregistrer.", "保存する前にディスク上の変更を解決してください。", "保存前请先处理磁盘上的更改。"],
|
||||||
|
["Open a workspace first.", "Ouvrez d’abord un espace de travail.", "先にワークスペースを開いてください。", "请先打开工作区。"],
|
||||||
|
["Collapse backlinks", "Réduire les liens entrants", "バックリンクを折りたたむ", "折叠反向链接"],
|
||||||
|
["Expand backlinks", "Développer les liens entrants", "バックリンクを展開", "展开反向链接"]
|
||||||
];
|
];
|
||||||
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
|
export const catalogs: Record<Exclude<Locale, 'en'>, Record<string, string>> = {
|
||||||
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
fr: Object.fromEntries(messageRows.map(row => [row[0], row[1]])),
|
||||||
|
|||||||
@@ -354,7 +354,7 @@
|
|||||||
expanded = folders;
|
expanded = folders;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function copyText(text: string, label: string) {
|
async function copyText(text: string, done: string) {
|
||||||
try {
|
try {
|
||||||
await navigator.clipboard.writeText(text);
|
await navigator.clipboard.writeText(text);
|
||||||
} catch {
|
} catch {
|
||||||
@@ -365,7 +365,7 @@
|
|||||||
document.execCommand("copy");
|
document.execCommand("copy");
|
||||||
area.remove();
|
area.remove();
|
||||||
}
|
}
|
||||||
onStatus?.(`Copied ${label}`);
|
onStatus?.(done);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function persistMarks(change: (current: Marks) => Marks) {
|
async function persistMarks(change: (current: Marks) => Marks) {
|
||||||
@@ -416,7 +416,7 @@
|
|||||||
await load(parentRel(from));
|
await load(parentRel(from));
|
||||||
selectOnly(plan.to);
|
selectOnly(plan.to);
|
||||||
await focusTreePath(plan.to);
|
await focusTreePath(plan.to);
|
||||||
onStatus?.(`Renamed to ${plan.to}`);
|
onStatus?.($t("Renamed to {path}", { path: plan.to }));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error = err instanceof Error ? err.message : String(err);
|
error = err instanceof Error ? err.message : String(err);
|
||||||
} finally { moving = false; }
|
} finally { moving = false; }
|
||||||
@@ -512,7 +512,7 @@
|
|||||||
}
|
}
|
||||||
await load(parent);
|
await load(parent);
|
||||||
if (workspaceRoot !== operationRoot) return;
|
if (workspaceRoot !== operationRoot) return;
|
||||||
onStatus?.(`Created ${rel}`);
|
onStatus?.($t("Created {path}", { path: rel }));
|
||||||
if (kind === "folder") {
|
if (kind === "folder") {
|
||||||
startRename({ name: finalName, rel_path: rel, kind: "folder" });
|
startRename({ name: finalName, rel_path: rel, kind: "folder" });
|
||||||
} else {
|
} else {
|
||||||
@@ -554,7 +554,7 @@
|
|||||||
const paths = new Map(entries.map(entry => [entry.rel_path, entry.rel_path]));
|
const paths = new Map(entries.map(entry => [entry.rel_path, entry.rel_path]));
|
||||||
moving = true;
|
moving = true;
|
||||||
const result = await runTreeActions(place === "after" ? [...entries].reverse() : entries, async entry => {
|
const result = await runTreeActions(place === "after" ? [...entries].reverse() : entries, async entry => {
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
|
||||||
const plan = planDrop(entry.rel_path, target, place, namesIn);
|
const plan = planDrop(entry.rel_path, target, place, namesIn);
|
||||||
if (plan.action === "noop") return;
|
if (plan.action === "noop") return;
|
||||||
if (plan.action === "reorder") {
|
if (plan.action === "reorder") {
|
||||||
@@ -567,7 +567,7 @@
|
|||||||
const next = moveMarks(current, plan.from, plan.to);
|
const next = moveMarks(current, plan.from, plan.to);
|
||||||
return { ...next, order: { ...next.order, [plan.fromParent]: plan.orderFrom, [plan.toParent]: plan.orderTo } };
|
return { ...next, order: { ...next.order, [plan.fromParent]: plan.orderFrom, [plan.toParent]: plan.orderTo } };
|
||||||
});
|
});
|
||||||
if (!moved || workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
if (!moved || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
|
||||||
moves.push({ from: plan.from, to: plan.to });
|
moves.push({ from: plan.from, to: plan.to });
|
||||||
paths.set(plan.from, plan.to);
|
paths.set(plan.from, plan.to);
|
||||||
await load(plan.fromParent);
|
await load(plan.fromParent);
|
||||||
@@ -578,7 +578,7 @@
|
|||||||
if (place === "inside") expanded = new Set([...expanded, destination]);
|
if (place === "inside") expanded = new Set([...expanded, destination]);
|
||||||
selection = { paths: new Set(paths.values()), anchor: paths.values().next().value ?? null };
|
selection = { paths: new Set(paths.values()), anchor: paths.values().next().value ?? null };
|
||||||
error = result.failures.length ? result.failures.join("\n") : null;
|
error = result.failures.length ? result.failures.join("\n") : null;
|
||||||
onStatus?.(`Moved ${result.completed.length} of ${entries.length} items`);
|
onStatus?.($t("Moved {count} of {total} items", { count: result.completed.length, total: entries.length }));
|
||||||
if (moves.length || JSON.stringify(before.order) !== JSON.stringify(marks.order)) {
|
if (moves.length || JSON.stringify(before.order) !== JSON.stringify(marks.order)) {
|
||||||
undoMoves = [...undoMoves, { moves, before, after: session.marks.snapshot() }];
|
undoMoves = [...undoMoves, { moves, before, after: session.marks.snapshot() }];
|
||||||
redoMoves = [];
|
redoMoves = [];
|
||||||
@@ -621,13 +621,13 @@
|
|||||||
const applied: { from: string; to: string }[] = [];
|
const applied: { from: string; to: string }[] = [];
|
||||||
try {
|
try {
|
||||||
for (const move of redo ? batch.moves : [...batch.moves].reverse()) {
|
for (const move of redo ? batch.moves : [...batch.moves].reverse()) {
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
|
||||||
const from = redo ? move.from : move.to, to = redo ? move.to : move.from;
|
const from = redo ? move.from : move.to, to = redo ? move.to : move.from;
|
||||||
// The batch restores the marks after all moves, so each move leaves them alone.
|
// The batch restores the marks after all moves, so each move leaves them alone.
|
||||||
if (!await session.rename(from, to, null) || workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
if (!await session.rename(from, to, null) || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
|
||||||
applied.push({ from, to });
|
applied.push({ from, to });
|
||||||
}
|
}
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. File moves stopped.");
|
if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. File moves stopped."));
|
||||||
await persistMarks(current => replayMoveMarks(current, batch.before, batch.after, batch.moves, redo));
|
await persistMarks(current => replayMoveMarks(current, batch.before, batch.after, batch.moves, redo));
|
||||||
if (redo) { redoMoves = redoMoves.slice(0, -1); undoMoves = [...undoMoves, batch]; }
|
if (redo) { redoMoves = redoMoves.slice(0, -1); undoMoves = [...undoMoves, batch]; }
|
||||||
else { undoMoves = undoMoves.slice(0, -1); redoMoves = [...redoMoves, batch]; }
|
else { undoMoves = undoMoves.slice(0, -1); redoMoves = [...redoMoves, batch]; }
|
||||||
@@ -657,11 +657,11 @@
|
|||||||
const moves: MoveBatch["moves"] = [];
|
const moves: MoveBatch["moves"] = [];
|
||||||
moving = true;
|
moving = true;
|
||||||
const result = await runTreeActions(source.paths.map(rel_path => ({ rel_path, name: rel_path.split("/").pop()!, kind: "file" as const })), async entry => {
|
const result = await runTreeActions(source.paths.map(rel_path => ({ rel_path, name: rel_path.split("/").pop()!, kind: "file" as const })), async entry => {
|
||||||
if (workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped.");
|
if (workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. Paste stopped."));
|
||||||
if (source.cut) {
|
if (source.cut) {
|
||||||
const to = joinRel(parent, entry.name);
|
const to = joinRel(parent, entry.name);
|
||||||
if (to === entry.rel_path) return;
|
if (to === entry.rel_path) return;
|
||||||
if (!await session.rename(entry.rel_path, to) || workspaceRoot !== operationRoot) throw new Error("The workspace changed. Paste stopped.");
|
if (!await session.rename(entry.rel_path, to) || workspaceRoot !== operationRoot) throw new Error($t("The workspace changed. Paste stopped."));
|
||||||
moves.push({ from: entry.rel_path, to });
|
moves.push({ from: entry.rel_path, to });
|
||||||
} else await workspaceCopy(entry.rel_path, parent, operationRoot);
|
} else await workspaceCopy(entry.rel_path, parent, operationRoot);
|
||||||
});
|
});
|
||||||
@@ -677,7 +677,7 @@
|
|||||||
const result = await runTreeActions(roots, entry => workspaceCopy(entry.rel_path));
|
const result = await runTreeActions(roots, entry => workspaceCopy(entry.rel_path));
|
||||||
for (const parent of new Set(roots.map(entry => parentRel(entry.rel_path)))) await load(parent);
|
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;
|
error = result.failures.length ? result.failures.join("\n") : null;
|
||||||
onStatus?.(`Copied ${result.completed.length} of ${roots.length} items`);
|
onStatus?.($t("Copied {count} of {total} items", { count: result.completed.length, total: roots.length }));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Delete moves items to the system trash. One file needs no confirmation, because the
|
// Delete moves items to the system trash. One file needs no confirmation, because the
|
||||||
@@ -838,7 +838,7 @@
|
|||||||
label: multiple ? $t("Copy workspace paths") : $t("Copy workspace path"),
|
label: multiple ? $t("Copy workspace paths") : $t("Copy workspace path"),
|
||||||
icon: "copy",
|
icon: "copy",
|
||||||
run: () => {
|
run: () => {
|
||||||
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? "workspace paths" : "workspace path");
|
void copyText(entries.map(item => item.rel_path).join("\n"), multiple ? $t("Copied workspace paths") : $t("Copied workspace path"));
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -849,7 +849,7 @@
|
|||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const paths = await Promise.all(entries.map(item => workspaceAbsPath(item.rel_path)));
|
const paths = await Promise.all(entries.map(item => workspaceAbsPath(item.rel_path)));
|
||||||
await copyText(paths.join("\n"), multiple ? "system paths" : "system path");
|
await copyText(paths.join("\n"), multiple ? $t("Copied system paths") : $t("Copied system path"));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
error = err instanceof Error ? err.message : String(err);
|
error = err instanceof Error ? err.message : String(err);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
|
import { t } from "$lib/i18n";
|
||||||
import { onMount } from "svelte";
|
import { onMount } from "svelte";
|
||||||
import { isTauri } from "@tauri-apps/api/core";
|
import { isTauri } from "@tauri-apps/api/core";
|
||||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||||
@@ -11,7 +12,7 @@
|
|||||||
let error = $state("");
|
let error = $state("");
|
||||||
function read() {
|
function read() {
|
||||||
try { settings = readSettings(); }
|
try { settings = readSettings(); }
|
||||||
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
catch { error = $t("Could not read your settings. Default settings apply until you save new settings."); }
|
||||||
}
|
}
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
read();
|
read();
|
||||||
@@ -27,7 +28,7 @@
|
|||||||
async function close() {
|
async function close() {
|
||||||
if (!isTauri()) { window.location.assign("/"); return; }
|
if (!isTauri()) { window.location.assign("/"); return; }
|
||||||
try { await getCurrentWindow().close(); }
|
try { await getCurrentWindow().close(); }
|
||||||
catch (reason) { error = `Could not close settings: ${String(reason)}`; }
|
catch (reason) { error = $t("Could not close settings: {reason}", { reason: String(reason) }); }
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -286,27 +286,27 @@
|
|||||||
* The source tab closes only after this window accepts the tab.
|
* The source tab closes only after this window accepts the tab.
|
||||||
*/
|
*/
|
||||||
async function acceptTabTransfer(id: string, { index, startup = false }: { index?: number; startup?: boolean } = {}) {
|
async function acceptTabTransfer(id: string, { index, startup = false }: { index?: number; startup?: boolean } = {}) {
|
||||||
if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer.");
|
if (!TAB_TRANSFER_ID.test(id)) throw new Error($t("Invalid tab transfer."));
|
||||||
const current = documents;
|
const current = documents;
|
||||||
if (!workspace || !current || (switching && !startup)) throw new Error("Move tabs only between windows of the same workspace.");
|
if (!workspace || !current || (switching && !startup)) throw new Error($t("Move tabs only between windows of the same workspace."));
|
||||||
const payload = await takeTabTransfer(id, workspace.root);
|
const payload = await takeTabTransfer(id, workspace.root);
|
||||||
let accepted = false;
|
let accepted = false;
|
||||||
try {
|
try {
|
||||||
const transfer = parseTabTransfer(payload);
|
const transfer = parseTabTransfer(payload);
|
||||||
let path = "";
|
let path = "";
|
||||||
if ("buffer" in transfer) {
|
if ("buffer" in transfer) {
|
||||||
if (!current.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open.");
|
if (!current.importTab(transfer.buffer)) throw new Error($t("This tab is already open in this window. The source tab remains open."));
|
||||||
path = transfer.buffer.relPath;
|
path = transfer.buffer.relPath;
|
||||||
if (!startup) selectTab(path);
|
if (!startup) selectTab(path);
|
||||||
} else {
|
} else {
|
||||||
// A new window starts its plugins after the workspace opens. Wait for them there.
|
// A new window starts its plugins after the workspace opens. Wait for them there.
|
||||||
const deadline = Date.now() + (startup ? 15000 : 0);
|
const deadline = Date.now() + (startup ? 15000 : 0);
|
||||||
while (!await restorePluginTab(transfer.plugin as Parameters<typeof restorePluginTab>[0])) {
|
while (!await restorePluginTab(transfer.plugin as Parameters<typeof restorePluginTab>[0])) {
|
||||||
if (Date.now() >= deadline) throw new Error("Enable this tab's plugin before moving it to this window.");
|
if (Date.now() >= deadline) throw new Error($t("Enable this tab's plugin before moving it to this window."));
|
||||||
await new Promise(resolve => setTimeout(resolve, 100));
|
await new Promise(resolve => setTimeout(resolve, 100));
|
||||||
}
|
}
|
||||||
if (index !== undefined) {
|
if (index !== undefined) {
|
||||||
if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab.");
|
if (!$pluginView || $pluginView.placement !== "editor") throw new Error($t("The plugin did not open this tab."));
|
||||||
path = `plugin:${$pluginView.key}`;
|
path = `plugin:${$pluginView.key}`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -450,7 +450,7 @@
|
|||||||
if (tab.plugin && await openPluginDocument(tab.path)) {
|
if (tab.plugin && await openPluginDocument(tab.path)) {
|
||||||
await tick();
|
await tick();
|
||||||
const opened = $pluginEditors.find(view => view.document?.path === tab.path);
|
const opened = $pluginEditors.find(view => view.document?.path === tab.path);
|
||||||
if (!opened) throw new Error("The plugin did not open this document.");
|
if (!opened) throw new Error($t("The plugin did not open this document."));
|
||||||
if (tab.pinned !== !!opened.pinned) pinPluginEditor(opened.key);
|
if (tab.pinned !== !!opened.pinned) pinPluginEditor(opened.key);
|
||||||
order.push(opened.key);
|
order.push(opened.key);
|
||||||
paths.set(tab.path, `plugin:${opened.key}`);
|
paths.set(tab.path, `plugin:${opened.key}`);
|
||||||
@@ -567,7 +567,7 @@
|
|||||||
const offered = offerTabTransfer(token, workspace!.root, { ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading });
|
const offered = offerTabTransfer(token, workspace!.root, { ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading });
|
||||||
// A drag cannot wait for the offer. Report a failed drag offer here. `detachTab` reports its own.
|
// A drag cannot wait for the offer. Report a failed drag offer here. `detachTab` reports its own.
|
||||||
offered.catch(reason => { finish(false); if (!reportTimeout) error = String(reason); });
|
offered.catch(reason => { finish(false); if (!reportTimeout) error = String(reason); });
|
||||||
timer = setTimeout(() => { finish(); if (reportTimeout) error = "The new window did not accept the tab. The source tab remains open."; }, 30000);
|
timer = setTimeout(() => { finish(); if (reportTimeout) error = $t("The new window did not accept the tab. The source tab remains open."); }, 30000);
|
||||||
return { token, finish, offered };
|
return { token, finish, offered };
|
||||||
} catch (reason) { finish(); throw reason; }
|
} catch (reason) { finish(); throw reason; }
|
||||||
}
|
}
|
||||||
@@ -902,7 +902,7 @@
|
|||||||
async function renameNoteTitle(id: string, title: string) {
|
async function renameNoteTitle(id: string, title: string) {
|
||||||
const current = documents;
|
const current = documents;
|
||||||
const note = current?.buffers.find(tab => tab.id === id);
|
const note = current?.buffers.find(tab => tab.id === id);
|
||||||
if (!current || !note || switching) throw new Error("This note is no longer available.");
|
if (!current || !note || switching) throw new Error($t("This note is no longer available."));
|
||||||
const from = note.relPath;
|
const from = note.relPath;
|
||||||
const plan = planMarkdownTitleRename(from, title);
|
const plan = planMarkdownTitleRename(from, title);
|
||||||
if (plan.action === "error") throw new Error(plan.message);
|
if (plan.action === "error") throw new Error(plan.message);
|
||||||
@@ -947,7 +947,7 @@
|
|||||||
const targets = await session.linkTargets(origin, link.target, link.kind);
|
const targets = await session.linkTargets(origin, link.target, link.kind);
|
||||||
if ("ambiguous" in targets) throw new Error($t("More than one note matches {path}. Use its workspace path: {candidates}", { path: link.target, candidates: targets.ambiguous.join(", ") }));
|
if ("ambiguous" in targets) throw new Error($t("More than one note matches {path}. Use its workspace path: {candidates}", { path: link.target, candidates: targets.ambiguous.join(", ") }));
|
||||||
for (const path of targets.paths) {
|
for (const path of targets.paths) {
|
||||||
if (!valid()) throw new Error("The workspace changed. Open the link menu again.");
|
if (!valid()) throw new Error($t("The workspace changed. Open the link menu again."));
|
||||||
const parent = path.split("/").slice(0, -1).join("/");
|
const parent = path.split("/").slice(0, -1).join("/");
|
||||||
let files: TreeEntry[];
|
let files: TreeEntry[];
|
||||||
try { files = await workspaceList(parent); } catch { continue; }
|
try { files = await workspaceList(parent); } catch { continue; }
|
||||||
@@ -965,7 +965,7 @@
|
|||||||
if (!typed || !valid()) return;
|
if (!typed || !valid()) return;
|
||||||
let to = typed.trim().replaceAll("\\", "/");
|
let to = typed.trim().replaceAll("\\", "/");
|
||||||
if (move) {
|
if (move) {
|
||||||
if (!to || to.startsWith("/") || to.split("/").some(part => !part || part === "." || part === "..") || /[<>:"|?*\u0000-\u001f]/.test(to)) throw new Error("Enter a relative workspace path without reserved characters.");
|
if (!to || to.startsWith("/") || to.split("/").some(part => !part || part === "." || part === "..") || /[<>:"|?*\u0000-\u001f]/.test(to)) throw new Error($t("Enter a relative workspace path without reserved characters."));
|
||||||
} else {
|
} else {
|
||||||
const plan = planRename(file.rel_path, to);
|
const plan = planRename(file.rel_path, to);
|
||||||
if (plan.action === "noop") return;
|
if (plan.action === "noop") return;
|
||||||
@@ -1071,18 +1071,18 @@
|
|||||||
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
|
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
|
||||||
if (transferredWindow) { leftOpen = false; rightOpen = false; }
|
if (transferredWindow) { leftOpen = false; rightOpen = false; }
|
||||||
layoutReady = true;
|
layoutReady = true;
|
||||||
} catch { error = "Could not read your layout. Default layout applies for this window."; }
|
} catch { error = $t("Could not read your layout. Default layout applies for this window."); }
|
||||||
});
|
});
|
||||||
|
|
||||||
$effect(() => {
|
$effect(() => {
|
||||||
if (!layoutReady || transferredWindow) return;
|
if (!layoutReady || transferredWindow) return;
|
||||||
try { saveWorkbenchLayout(localStorage, { leftOpen, rightOpen, leftWidth, rightWidth, leftView }); }
|
try { saveWorkbenchLayout(localStorage, { leftOpen, rightOpen, leftWidth, rightWidth, leftView }); }
|
||||||
catch { error = "Could not save your layout. Layout changes apply for this window only."; }
|
catch { error = $t("Could not save your layout. Layout changes apply for this window only."); }
|
||||||
});
|
});
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
try { settings = readSettings(); }
|
try { settings = readSettings(); }
|
||||||
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
catch { error = $t("Could not read your settings. Default settings apply until you save new settings."); }
|
||||||
error = takeSettingsNotice() ?? error;
|
error = takeSettingsNotice() ?? error;
|
||||||
settingsReady = true;
|
settingsReady = true;
|
||||||
const stopSettings = onSettingsChange("general", () => { settings = readSettings(); });
|
const stopSettings = onSettingsChange("general", () => { settings = readSettings(); });
|
||||||
@@ -1109,11 +1109,11 @@
|
|||||||
}));
|
}));
|
||||||
unlisteners.push(handlePluginDocumentRename(async (from, name) => {
|
unlisteners.push(handlePluginDocumentRename(async (from, name) => {
|
||||||
const current = documents;
|
const current = documents;
|
||||||
if (!current || switching) throw new Error("Open a workspace before renaming a document.");
|
if (!current || switching) throw new Error($t("Open a workspace before renaming a document."));
|
||||||
const plan = planDocumentTitleRename(from, name);
|
const plan = planDocumentTitleRename(from, name);
|
||||||
if (plan.action === "error") throw new Error(plan.message);
|
if (plan.action === "error") throw new Error(plan.message);
|
||||||
if (plan.action === "noop") return from;
|
if (plan.action === "noop") return from;
|
||||||
if (!await session.rename(from, plan.to) || documents !== current) throw new Error("The workspace changed. Reopen the document.");
|
if (!await session.rename(from, plan.to) || documents !== current) throw new Error($t("The workspace changed. Reopen the document."));
|
||||||
return plan.to;
|
return plan.to;
|
||||||
}));
|
}));
|
||||||
unlisteners.push(guardPluginWrites(path => {
|
unlisteners.push(guardPluginWrites(path => {
|
||||||
@@ -1365,7 +1365,7 @@
|
|||||||
onRenameTitle={renameNoteTitle}
|
onRenameTitle={renameNoteTitle}
|
||||||
tableActions={{ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) }}
|
tableActions={{ onSearch: searchSelection, onExtract: (markdown, label, valid) => extractSelection(markdown, label, valid, pane.buffer) }}
|
||||||
linkActions={{
|
linkActions={{
|
||||||
browser: browserContribution ? async target => { if (!await browserContribution?.open(target)) throw new Error("Could not open the app browser."); } : undefined,
|
browser: browserContribution ? async target => { if (!await browserContribution?.open(target)) throw new Error($t("Could not open the app browser.")); } : undefined,
|
||||||
defaultBrowser: target => openUrl(target),
|
defaultBrowser: target => openUrl(target),
|
||||||
workspaceItems: link => workspaceLinkItems(link, pane.buffer?.relPath ?? "", pane.id),
|
workspaceItems: link => workspaceLinkItems(link, pane.buffer?.relPath ?? "", pane.id),
|
||||||
}}
|
}}
|
||||||
|
|||||||
@@ -126,8 +126,8 @@
|
|||||||
<button onclick={() => themeInput.click()}>{$t("Install theme")}</button>
|
<button onclick={() => themeInput.click()}>{$t("Install theme")}</button>
|
||||||
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? $t('Exporting…') : $t('Export theme template')}</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={() => {
|
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label={$t("Remove custom theme")} onclick={() => {
|
||||||
try { removeTheme(appearance.theme.slice(7)).catch(() => { error = 'Could not remove this theme.'; }); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
|
try { removeTheme(appearance.theme.slice(7)).catch(() => { error = $t("Could not remove this theme."); }); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
|
||||||
catch { error = 'Could not remove this theme.'; }
|
catch { error = $t("Could not remove this theme."); }
|
||||||
}} />{/if}
|
}} />{/if}
|
||||||
</div>
|
</div>
|
||||||
<p>{$t("Edit the exported JSON colors and fonts, then choose Install theme. The template contains one color palette and font families.")}</p>
|
<p>{$t("Edit the exported JSON colors and fonts, then choose Install theme. The template contains one color palette and font families.")}</p>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ function database(): Promise<IDBDatabase> {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
export async function saveBackgroundImage(file: Blob): Promise<string> {
|
export async function saveBackgroundImage(file: Blob): Promise<string> {
|
||||||
if (file.size > BACKGROUND_IMAGE_LIMIT) throw new Error('Choose an image of 50 MiB or less.');
|
if (file.size > BACKGROUND_IMAGE_LIMIT) throw new Error(tr("Choose an image of 50 MiB or less."));
|
||||||
const db = await database();
|
const db = await database();
|
||||||
const id = crypto.randomUUID();
|
const id = crypto.randomUUID();
|
||||||
try {
|
try {
|
||||||
@@ -43,4 +43,5 @@ export async function removeBackgroundImage(id: string): Promise<void> {
|
|||||||
transaction.onabort = () => reject(transaction.error);
|
transaction.onabort = () => reject(transaction.error);
|
||||||
});
|
});
|
||||||
} finally { db.close(); }
|
} finally { db.close(); }
|
||||||
}
|
}import { tr } from "../i18n/index.ts";
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { tr } from "../i18n/index.ts";
|
||||||
import { readSection, writeSection } from '../settings/store.ts';
|
import { readSection, writeSection } from '../settings/store.ts';
|
||||||
|
|
||||||
/** The old localStorage key. The customThemes section of the settings file replaces it. */
|
/** The old localStorage key. The customThemes section of the settings file replaces it. */
|
||||||
@@ -10,31 +11,31 @@ export type CustomTheme = { schema: 2; id: string; name: string; colors: ThemeCo
|
|||||||
export type LegacyCustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
|
export type LegacyCustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
|
||||||
|
|
||||||
export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" = "dark"): 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.");
|
if (!input || typeof input !== "object") throw new Error(tr("Choose a RuneStone theme JSON file."));
|
||||||
const value = input as Record<string, unknown>;
|
const value = input as Record<string, unknown>;
|
||||||
if ((value.schema !== 1 && value.schema !== 2) || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|
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.");
|
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error(tr("The theme needs schema 2, an ID, and a name."));
|
||||||
const colors = (mode: string): ThemeColors => {
|
const colors = (mode: string): ThemeColors => {
|
||||||
const source = value[mode];
|
const source = value[mode];
|
||||||
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(`The theme needs ${mode} colors.`);
|
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(tr("The theme needs {mode} colors.", { mode }));
|
||||||
const result: ThemeColors = {};
|
const result: ThemeColors = {};
|
||||||
for (const [key, color] of Object.entries(source)) {
|
for (const [key, color] of Object.entries(source)) {
|
||||||
if (!(COLOR_TOKENS as readonly string[]).includes(key)) throw new Error(`Unknown theme color: ${key}`);
|
if (!(COLOR_TOKENS as readonly string[]).includes(key)) throw new Error(tr("Unknown theme color: {key}", { key }));
|
||||||
if (typeof color !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color)) throw new Error(`Use a hexadecimal color for ${key}.`);
|
if (typeof color !== "string" || !/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color)) throw new Error(tr("Use a hexadecimal color for {key}.", { key }));
|
||||||
result[key as keyof ThemeColors] = color;
|
result[key as keyof ThemeColors] = color;
|
||||||
}
|
}
|
||||||
if (!result.bg || !result.text || !result.accent) throw new Error(`The ${mode} palette needs bg, text, and accent.`);
|
if (!result.bg || !result.text || !result.accent) throw new Error(tr("The {mode} palette needs bg, text, and accent.", { mode }));
|
||||||
return result;
|
return result;
|
||||||
};
|
};
|
||||||
if (value.schema === 1) { colors("light"); colors("dark"); }
|
if (value.schema === 1) { colors("light"); colors("dark"); }
|
||||||
let fonts: ThemeFonts | undefined;
|
let fonts: ThemeFonts | undefined;
|
||||||
if (value.fonts !== 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.');
|
if (!value.fonts || typeof value.fonts !== 'object' || Array.isArray(value.fonts)) throw new Error(tr("Use an object for theme fonts."));
|
||||||
fonts = {};
|
fonts = {};
|
||||||
for (const [role, stack] of Object.entries(value.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 (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(tr("Unknown theme font: {role}", { role }));
|
||||||
if (typeof stack !== 'string' || stack.length > 512 || !/^[\p{L}\p{N} _,'"-]+$/u.test(stack) || !stack.trim()
|
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}.`);
|
|| stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(tr("Use a font family stack for {role}.", { role }));
|
||||||
fonts[role as keyof ThemeFonts] = stack.trim();
|
fonts[role as keyof ThemeFonts] = stack.trim();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { tr } from "../i18n/index.ts";
|
||||||
import type { OpenBuffer, TreeEntry } from "./types";
|
import type { OpenBuffer, TreeEntry } from "./types";
|
||||||
|
|
||||||
export type DocumentIO = {
|
export type DocumentIO = {
|
||||||
@@ -171,7 +172,7 @@ export class Documents {
|
|||||||
if (this.disposed) return;
|
if (this.disposed) return;
|
||||||
const b = this.buffers.find(b => b.id === id);
|
const b = this.buffers.find(b => b.id === id);
|
||||||
if (!b || b.kind !== "text") return;
|
if (!b || b.kind !== "text") return;
|
||||||
if (b.diskContents !== undefined || b.diskError) throw new Error("Resolve the disk changes before saving.");
|
if (b.diskContents !== undefined || b.diskError) throw new Error(tr("Resolve the disk changes before saving."));
|
||||||
if (b.contents === b.saved) return;
|
if (b.contents === b.saved) return;
|
||||||
const contents = b.contents;
|
const contents = b.contents;
|
||||||
const path = b.relPath;
|
const path = b.relPath;
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { tr } from "../i18n/index.ts";
|
||||||
import MarkdownIt from "markdown-it";
|
import MarkdownIt from "markdown-it";
|
||||||
import type { Token } from "markdown-it";
|
import type { Token } from "markdown-it";
|
||||||
import { inlineMathEnd } from "./inlineMath.ts";
|
import { inlineMathEnd } from "./inlineMath.ts";
|
||||||
@@ -147,9 +148,9 @@ markdown.renderer.rules.link_open = (tokens, index, options, _env, renderer) =>
|
|||||||
markdown.renderer.rules.fence = (tokens, index) => {
|
markdown.renderer.rules.fence = (tokens, index) => {
|
||||||
const token = tokens[index];
|
const token = tokens[index];
|
||||||
const language = token.info.trim().split(/\s+/)[0];
|
const language = token.info.trim().split(/\s+/)[0];
|
||||||
const code = `<pre class="md-code" data-lang="${escapeHtml(language || "code")}"><button type="button" class="rs-fence-copy" aria-label="Copy code" title="Copy code">${copyIcon}</button><code${language ? ` class="language-${escapeHtml(language)}"` : ""}>${escapeHtml(token.content)}</code></pre>\n`;
|
const code = `<pre class="md-code" data-lang="${escapeHtml(language || "code")}"><button type="button" class="rs-fence-copy" aria-label="${tr("Copy code")}" title="${tr("Copy code")}">${copyIcon}</button><code${language ? ` class="language-${escapeHtml(language)}"` : ""}>${escapeHtml(token.content)}</code></pre>\n`;
|
||||||
return language.toLowerCase() === "mermaid"
|
return language.toLowerCase() === "mermaid"
|
||||||
? `<div class="md-mermaid"><div class="md-diagram" aria-label="Mermaid diagram"></div><details class="md-diagram-source"><summary>Diagram source</summary>${code}</details></div>\n`
|
? `<div class="md-mermaid"><div class="md-diagram" aria-label="${tr("Mermaid diagram")}"></div><details class="md-diagram-source"><summary>${tr("Diagram source")}</summary>${code}</details></div>\n`
|
||||||
: code;
|
: code;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { tr } from "../i18n/index.ts";
|
||||||
import { workspaceList, workspaceRead, workspaceReadMany, workspaceRename } from "./api";
|
import { workspaceList, workspaceRead, workspaceReadMany, workspaceRename } from "./api";
|
||||||
import { MARKS_PATH, type Marks } from "./marks";
|
import { MARKS_PATH, type Marks } from "./marks";
|
||||||
import { linkCandidates } from "./markdownLinks";
|
import { linkCandidates } from "./markdownLinks";
|
||||||
@@ -139,7 +140,7 @@ export class WorkspaceSession {
|
|||||||
*/
|
*/
|
||||||
async rename(from: string, to: string, marks: ((current: Marks) => Marks) | null = current => moveMarks(current, from, to)): Promise<boolean> {
|
async rename(from: string, to: string, marks: ((current: Marks) => Marks) | null = current => moveMarks(current, from, to)): Promise<boolean> {
|
||||||
const root = this.root;
|
const root = this.root;
|
||||||
if (!root) throw new Error("Open a workspace first.");
|
if (!root) throw new Error(tr("Open a workspace first."));
|
||||||
await workspaceRename(from, to, root);
|
await workspaceRename(from, to, root);
|
||||||
if (this.root !== root) return false;
|
if (this.root !== root) return false;
|
||||||
this.index.rename(from, to);
|
this.index.rename(from, to);
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { tr } from "../i18n/index.ts";
|
||||||
import { readSection, writeSection } from "../settings/store.ts";
|
import { readSection, writeSection } from "../settings/store.ts";
|
||||||
|
|
||||||
/** The old localStorage key. The general section of the settings file replaces it. */
|
/** The old localStorage key. The general section of the settings file replaces it. */
|
||||||
@@ -47,7 +48,7 @@ export function readSettings(): AppSettings {
|
|||||||
/** Check and save the settings. Throws at once for invalid values. The promise reports a failed save. */
|
/** Check and save the settings. Throws at once for invalid values. The promise reports a failed save. */
|
||||||
export function saveSettings(settings: AppSettings): Promise<void> {
|
export function saveSettings(settings: AppSettings): Promise<void> {
|
||||||
if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") {
|
if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") {
|
||||||
throw new Error("Choose a whole number from 1 to 300 seconds.");
|
throw new Error(tr("Choose a whole number from 1 to 300 seconds."));
|
||||||
}
|
}
|
||||||
return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true, tableFormulas: settings.tableFormulas !== false });
|
return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true, tableFormulas: settings.tableFormulas !== false });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// Tab transfer between windows of one workspace. The host keeps each offer in memory (src-tauri/src/tab_transfer.rs).
|
// Tab transfer between windows of one workspace. The host keeps each offer in memory (src-tauri/src/tab_transfer.rs).
|
||||||
// The source window offers a tab and closes it only after `tab-transfer-accepted`.
|
// The source window offers a tab and closes it only after `tab-transfer-accepted`.
|
||||||
// The receiving window takes the offer, opens the tab, and then finishes the offer.
|
// The receiving window takes the offer, opens the tab, and then finishes the offer.
|
||||||
|
import { tr } from "../i18n/index.ts";
|
||||||
import { invoke } from "@tauri-apps/api/core";
|
import { invoke } from "@tauri-apps/api/core";
|
||||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||||
@@ -16,7 +17,7 @@ export type TabTransferOffer = { reading: boolean } & ({ buffer: OpenBuffer } |
|
|||||||
/** Check the state of a taken offer. The new window and the tab ribbon use this one check. */
|
/** Check the state of a taken offer. The new window and the tab ribbon use this one check. */
|
||||||
export function parseTabTransfer(payload: string): TabTransfer {
|
export function parseTabTransfer(payload: string): TabTransfer {
|
||||||
let value: unknown;
|
let value: unknown;
|
||||||
try { value = JSON.parse(payload); } catch { throw new Error("Invalid tab transfer."); }
|
try { value = JSON.parse(payload); } catch { throw new Error(tr("Invalid tab transfer.")); }
|
||||||
const transfer = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
const transfer = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||||
const reading = transfer.reading === true;
|
const reading = transfer.reading === true;
|
||||||
const buffer = transfer.buffer as Record<string, unknown> | undefined;
|
const buffer = transfer.buffer as Record<string, unknown> | undefined;
|
||||||
@@ -25,7 +26,7 @@ export function parseTabTransfer(payload: string): TabTransfer {
|
|||||||
return { buffer: buffer as unknown as OpenBuffer, reading };
|
return { buffer: buffer as unknown as OpenBuffer, reading };
|
||||||
}
|
}
|
||||||
if (transfer.plugin && typeof transfer.plugin === "object") return { plugin: transfer.plugin, reading };
|
if (transfer.plugin && typeof transfer.plugin === "object") return { plugin: transfer.plugin, reading };
|
||||||
throw new Error("Invalid tab transfer.");
|
throw new Error(tr("Invalid tab transfer."));
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Offer a tab with the ID `id`. The window creates the ID, because a drag needs it at once. */
|
/** Offer a tab with the ID `id`. The window creates the ID, because a drag needs it at once. */
|
||||||
@@ -35,7 +36,7 @@ export function offerTabTransfer(id: string, root: string, offer: TabTransferOff
|
|||||||
|
|
||||||
/** Take an offer once. Fails when the offer expired or belongs to another workspace. */
|
/** Take an offer once. Fails when the offer expired or belongs to another workspace. */
|
||||||
export async function takeTabTransfer(id: string, root: string): Promise<string> {
|
export async function takeTabTransfer(id: string, root: string): Promise<string> {
|
||||||
if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer.");
|
if (!TAB_TRANSFER_ID.test(id)) throw new Error(tr("Invalid tab transfer."));
|
||||||
return invoke<string>("tab_transfer_take", { id, root });
|
return invoke<string>("tab_transfer_take", { id, root });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { tr } from "../i18n/index.ts";
|
||||||
import { workspaceCreate, workspaceList, workspaceRead, workspaceWrite } from "./api";
|
import { workspaceCreate, workspaceList, workspaceRead, workspaceWrite } from "./api";
|
||||||
import { uniqueName, joinRel } from "./treeDrop";
|
import { uniqueName, joinRel } from "./treeDrop";
|
||||||
|
|
||||||
@@ -14,7 +15,7 @@ export async function noteTemplates(): Promise<NoteTemplate[]> {
|
|||||||
|
|
||||||
export async function saveNoteTemplate(name: string, contents: string): Promise<string> {
|
export async function saveNoteTemplate(name: string, contents: string): Promise<string> {
|
||||||
const title = name.trim().replace(/\.md$/i, "");
|
const title = name.trim().replace(/\.md$/i, "");
|
||||||
if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) throw new Error("Enter a valid template name.");
|
if (!title || /[<>:"/\\|?*\x00-\x1f]/.test(title) || /[. ]$/.test(title)) throw new Error(tr("Enter a valid template name."));
|
||||||
const existing = await noteTemplates();
|
const existing = await noteTemplates();
|
||||||
const file = uniqueName(existing.map(template => template.name + ".md"), title + ".md");
|
const file = uniqueName(existing.map(template => template.name + ".md"), title + ".md");
|
||||||
const path = joinRel(TEMPLATE_FOLDER, file);
|
const path = joinRel(TEMPLATE_FOLDER, file);
|
||||||
|
|||||||
Reference in New Issue
Block a user