Keep preferences in one settings file and move tab transfer to the host
Keep the user preferences in settings.json in the app config folder. WebView storage can be lost, and the host cannot read it. The file has a schema number, a revision number, and one value for each section: general, appearance, customThemes, customThemesLegacy, and language. - settings_read gives all sections, the revision, and a one-time notice. - settings_write replaces one section, writes the file atomically, and sends settings-changed to all windows. The limit is 8 MiB. - settings_migrate writes the first file only when no file exists. - The host moves a damaged file to settings.corrupt-<seconds>.json, starts from the defaults, and reports this one time. Each window loads the sections before its first render. One store in src/lib/settings/store.ts replaces the storage listeners. When no file exists, the window normalizes the old localStorage values and migrates them. The old keys stay in place for one release. The window layout and the open tabs stay in localStorage on purpose. The browser preview keeps all preferences in localStorage. Keep tab transfer offers in host memory, not in localStorage, because an offer can hold unsaved text. A window takes an offer once. The host checks the workspace root and a 120 second expiry. When the receiver accepts the tab, the host sends tab-transfer-accepted to the source window only. A refused offer stays open, and the source tab stays open. A new window and a drop on the tab ribbon use one check. The smoke harness serves the new commands from one shared state for each browser context. Tests read saved values from the mock settings file. Rust, unit, and smoke tests cover the changes.
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import { derived, get, writable } from 'svelte/store';
|
||||
import { catalogs, type Locale } from './messages.ts';
|
||||
import { onSettingsChange, readSection, writeSection } from '../settings/store.ts';
|
||||
export { type Locale } from './messages.ts';
|
||||
/** The old localStorage key. The language section of the settings file replaces it. */
|
||||
export const LANGUAGE_KEY = 'runestone.language';
|
||||
export const LANGUAGES: { id: Locale; name: string }[] = [
|
||||
{ id: 'en', name: 'English' }, { id: 'fr', name: 'Français' },
|
||||
@@ -22,19 +24,19 @@ function applyLocale(language: Locale) {
|
||||
locale.set(language);
|
||||
if (typeof document !== 'undefined') document.documentElement.lang = language;
|
||||
}
|
||||
export function setLocale(language: Locale) {
|
||||
/** Save and apply a language. Throws at once if browser storage refuses it. The promise reports a failed save. */
|
||||
export function setLocale(language: Locale): Promise<void> {
|
||||
const valid = normalizeLocale(language);
|
||||
localStorage.setItem(LANGUAGE_KEY, valid);
|
||||
const saved = writeSection('language', valid);
|
||||
applyLocale(valid);
|
||||
return saved;
|
||||
}
|
||||
/** Apply the saved language now and after each change in any window. Returns a function that stops it. */
|
||||
export function syncLocale() {
|
||||
const read = () => {
|
||||
try { applyLocale(normalizeLocale(localStorage.getItem(LANGUAGE_KEY))); }
|
||||
try { applyLocale(normalizeLocale(readSection('language'))); }
|
||||
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); };
|
||||
return onSettingsChange('language', read);
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
standalone?: boolean;
|
||||
windowError?: string;
|
||||
windowControls?: Snippet;
|
||||
onSave: (value: AppSettings) => void;
|
||||
onSave: (value: AppSettings) => void | Promise<void>;
|
||||
onClose: () => void;
|
||||
} = $props();
|
||||
let closeLanguage = () => {};
|
||||
@@ -32,7 +32,10 @@
|
||||
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;
|
||||
run: () => {
|
||||
const failed = () => { error = $t("Could not save language settings."); message = ""; };
|
||||
try { setLocale(item.id).catch(failed); error = ""; message = $t("Changes saved."); } catch { failed(); }
|
||||
} })) }).close;
|
||||
}
|
||||
type Section = string;
|
||||
const sections: { id: Section; label: string; icon: IconName; keywords: string }[] = $derived([
|
||||
@@ -66,8 +69,9 @@
|
||||
|
||||
function apply(value: AppSettings) {
|
||||
error = "";
|
||||
try { onSave(value); message = $t("Changes saved."); }
|
||||
catch { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; }
|
||||
const failed = () => { error = $t("Could not save these settings. Your previous settings still apply. Try again."); message = ""; };
|
||||
try { Promise.resolve(onSave(value)).catch(failed); message = $t("Changes saved."); }
|
||||
catch { failed(); }
|
||||
}
|
||||
|
||||
function changeInterval() {
|
||||
|
||||
@@ -4,27 +4,25 @@
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import SettingsDialog from "./SettingsDialog.svelte";
|
||||
import WindowControls from "$lib/ui/WindowControls.svelte";
|
||||
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
||||
import { onSettingsChange, takeSettingsNotice } from "$lib/settings/store";
|
||||
import { DEFAULT_SETTINGS, readSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
||||
|
||||
let settings = $state<AppSettings>({ ...DEFAULT_SETTINGS });
|
||||
let error = $state("");
|
||||
function read() {
|
||||
try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); }
|
||||
try { settings = readSettings(); }
|
||||
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
||||
}
|
||||
onMount(() => {
|
||||
read();
|
||||
const sync = (event: StorageEvent) => {
|
||||
if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) read();
|
||||
};
|
||||
window.addEventListener("storage", sync);
|
||||
window.addEventListener("focus", read);
|
||||
return () => { window.removeEventListener("storage", sync); window.removeEventListener("focus", read); };
|
||||
error = takeSettingsNotice() ?? error;
|
||||
return onSettingsChange("general", read);
|
||||
});
|
||||
function save(next: AppSettings) {
|
||||
saveSettings(localStorage, next);
|
||||
const saved = saveSettings(next);
|
||||
settings = { ...next };
|
||||
error = "";
|
||||
return saved;
|
||||
}
|
||||
async function close() {
|
||||
if (!isTauri()) { window.location.assign("/"); return; }
|
||||
|
||||
@@ -33,7 +33,9 @@
|
||||
import WorkspacePicker from "./WorkspacePicker.svelte";
|
||||
import SettingsDialog from "./SettingsDialog.svelte";
|
||||
import BrowserSlot from "$lib/plugins/BrowserSlot.svelte";
|
||||
import { DEFAULT_SETTINGS, SETTINGS_KEY, parseSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
||||
import { DEFAULT_SETTINGS, readSettings, saveSettings, type AppSettings } from "$lib/workspace/settings";
|
||||
import { onSettingsChange, takeSettingsNotice } from "$lib/settings/store";
|
||||
import { TAB_TRANSFER_ID, cancelTabTransfer, finishTabTransfer, offerTabTransfer, onTabTransferAccepted, parseTabTransfer, takeTabTransfer } from "$lib/workspace/tabTransfer";
|
||||
import { DEFAULT_WORKBENCH_LAYOUT, WORKBENCH_LAYOUT_KEY, parseWorkbenchLayout, saveWorkbenchLayout, type WorkbenchLayout } from "$lib/workspace/workbenchLayout";
|
||||
import FileTree from "./FileTree.svelte";
|
||||
import EditorPane from "./EditorPane.svelte";
|
||||
@@ -302,33 +304,52 @@
|
||||
try { return (view && pluginTabDragData(view)) || JSON.stringify({ tabTransfer: prepareTabTransfer(item).token }); }
|
||||
catch (reason) { error = String(reason); return; }
|
||||
}
|
||||
/**
|
||||
* Take a tab from another window of this workspace. Both entry points use this one check:
|
||||
* a new window opened with `?tabTransfer=<id>` (`startup`), and a drop on the tab ribbon (`index`).
|
||||
* The source tab closes only after this window accepts the tab.
|
||||
*/
|
||||
async function acceptTabTransfer(id: string, { index, startup = false }: { index?: number; startup?: boolean } = {}) {
|
||||
if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer.");
|
||||
const current = documents;
|
||||
if (!workspace || !current || (switching && !startup)) throw new Error("Move tabs only between windows of the same workspace.");
|
||||
const payload = await takeTabTransfer(id, workspace.root);
|
||||
let accepted = false;
|
||||
try {
|
||||
const transfer = parseTabTransfer(payload);
|
||||
let path = "";
|
||||
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.");
|
||||
path = transfer.buffer.relPath;
|
||||
if (!startup) selectTab(path);
|
||||
} else {
|
||||
// A new window starts its plugins after the workspace opens. Wait for them there.
|
||||
const deadline = Date.now() + (startup ? 15000 : 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.");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
if (index !== undefined) {
|
||||
if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab.");
|
||||
path = `plugin:${$pluginView.key}`;
|
||||
}
|
||||
}
|
||||
setReading(transfer.reading);
|
||||
accepted = true;
|
||||
if (index !== undefined) {
|
||||
await tick();
|
||||
moveWorkingTab(path, index);
|
||||
}
|
||||
} finally {
|
||||
// Without this acknowledgement, the source tab stays open.
|
||||
await finishTabTransfer(id, accepted).catch(reason => console.warn("Could not finish the tab transfer.", reason));
|
||||
}
|
||||
}
|
||||
async function receiveTab(data: string, index: number) {
|
||||
try {
|
||||
const payload = JSON.parse(data);
|
||||
if (typeof payload?.tabTransfer === "string") {
|
||||
if (!/^[0-9a-f-]{36}$/i.test(payload.tabTransfer)) throw new Error("Invalid tab transfer.");
|
||||
const key = `runestone.tab-transfer.${payload.tabTransfer}`;
|
||||
const raw = localStorage.getItem(key);
|
||||
if (!raw) throw new Error("This tab transfer expired. Drag the tab again.");
|
||||
const transfer = JSON.parse(raw);
|
||||
if (!workspace || switching || !documents || transfer.root !== workspace.root) throw new Error("Move tabs only between windows of the same workspace.");
|
||||
if (!Number.isFinite(transfer.created) || transfer.created < Date.now() - 120000) throw new Error("Invalid tab transfer.");
|
||||
let path: string;
|
||||
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string"
|
||||
&& typeof transfer.buffer.saved === "string") {
|
||||
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window. The source tab remains open.");
|
||||
path = transfer.buffer.relPath;
|
||||
selectTab(path);
|
||||
} else if (transfer.plugin) {
|
||||
if (!await restorePluginTab(transfer.plugin)) throw new Error("Enable this tab's plugin before moving it to this window.");
|
||||
if (!$pluginView || $pluginView.placement !== "editor") throw new Error("The plugin did not open this tab.");
|
||||
path = `plugin:${$pluginView.key}`;
|
||||
} else throw new Error("Invalid tab transfer.");
|
||||
setReading(transfer.reading === true);
|
||||
await tick();
|
||||
moveWorkingTab(path, index);
|
||||
localStorage.setItem(key + ".accepted", "true");
|
||||
localStorage.removeItem(key);
|
||||
await acceptTabTransfer(payload.tabTransfer, { index });
|
||||
error = null;
|
||||
return;
|
||||
}
|
||||
@@ -432,6 +453,7 @@
|
||||
const active = workingTabs.find(tab => tab.relPath === activeTabPath);
|
||||
const activeDocument = active && ("buffer" in active ? active.buffer.relPath : active.plugin.document?.path);
|
||||
const session: DocumentSession = { version: 1, documents, activePath: activeDocument ?? activePath };
|
||||
// The open tabs stay in localStorage on purpose: per-machine view state that is harmless to lose.
|
||||
try { localStorage.setItem(documentSessionKey(workspace.root), JSON.stringify(session)); }
|
||||
catch (reason) { console.warn("Could not save document tabs.", reason); }
|
||||
}
|
||||
@@ -480,29 +502,8 @@
|
||||
status = workspace.root;
|
||||
refreshToken += 1;
|
||||
const token = new URLSearchParams(location.search).get("tabTransfer");
|
||||
if (token && /^[0-9a-f-]{36}$/i.test(token)) {
|
||||
const key = `runestone.tab-transfer.${token}`;
|
||||
const raw = localStorage.getItem(key);
|
||||
if (raw) {
|
||||
const transfer = JSON.parse(raw);
|
||||
if (transfer.root === workspace.root && transfer.created > Date.now() - 120000
|
||||
&& (transfer.buffer || transfer.plugin)) {
|
||||
if (transfer.buffer && typeof transfer.buffer.relPath === "string" && typeof transfer.buffer.contents === "string") {
|
||||
if (!documents.importTab(transfer.buffer)) throw new Error("This tab is already open in this window.");
|
||||
}
|
||||
else if (transfer.plugin) {
|
||||
const deadline = Date.now() + 15000;
|
||||
while (!await restorePluginTab(transfer.plugin)) {
|
||||
if (Date.now() > deadline) throw new Error("Enable the plugin before moving this tab.");
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
} else throw new Error("Invalid tab transfer.");
|
||||
setReading(transfer.reading === true);
|
||||
localStorage.setItem(key + ".accepted", "true");
|
||||
localStorage.removeItem(key);
|
||||
}
|
||||
}
|
||||
} else await restoreDocumentTabs();
|
||||
if (token && TAB_TRANSFER_ID.test(token)) await acceptTabTransfer(token, { startup: true });
|
||||
else await restoreDocumentTabs();
|
||||
}
|
||||
} catch (err) { error = String(err); }
|
||||
finally { switching = false; workbenchReady = true; }
|
||||
@@ -555,33 +556,44 @@
|
||||
let transfer: ReturnType<typeof prepareTabTransfer> | undefined;
|
||||
try {
|
||||
transfer = prepareTabTransfer(tab, keepSource, true);
|
||||
await transfer.offered;
|
||||
await workspaceOpenWindow(workspace.root, transfer.token);
|
||||
} catch (reason) { transfer?.finish(); error = String(reason); }
|
||||
}
|
||||
// The offers of this window that wait for another window, by offer ID.
|
||||
const pendingTransfers = new Map<string, () => void>();
|
||||
onMount(() => {
|
||||
if (!desktop) return;
|
||||
const stop = onTabTransferAccepted(id => pendingTransfers.get(id)?.());
|
||||
return () => { void stop.then(unlisten => unlisten()); };
|
||||
});
|
||||
function prepareTabTransfer(tab: EditorTab, keepSource = false, reportTimeout = false) {
|
||||
const current = documents;
|
||||
const bufferSnapshot = (buffer?: OpenBuffer) => JSON.stringify(buffer ? { ...buffer, diskError: buffer.diskError ?? null } : undefined);
|
||||
const snapshot = "buffer" in tab ? bufferSnapshot(tab.buffer) : JSON.stringify(pluginTabState(tab.plugin));
|
||||
const token = crypto.randomUUID(), key = `runestone.tab-transfer.${token}`;
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const finish = () => {
|
||||
window.removeEventListener("storage", accepted);
|
||||
const token = crypto.randomUUID();
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
let done = false;
|
||||
const finish = (withdraw = true) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
pendingTransfers.delete(token);
|
||||
clearTimeout(timer);
|
||||
localStorage.removeItem(key);
|
||||
localStorage.removeItem(key + ".accepted");
|
||||
if (withdraw) void cancelTabTransfer(token).catch(() => {});
|
||||
};
|
||||
const accepted = (event: StorageEvent) => {
|
||||
if (event.key !== key + ".accepted" || event.newValue !== "true") return;
|
||||
// Close the source tab only if it did not change during the transfer.
|
||||
pendingTransfers.set(token, () => {
|
||||
if (!keepSource && "buffer" in tab) {
|
||||
if (documents === current && bufferSnapshot(current?.buffers.find(buffer => buffer.id === tab.buffer.id)) === snapshot) current?.close(tab.relPath);
|
||||
} else if (!keepSource && "plugin" in tab && JSON.stringify(pluginTabState(tab.plugin)) === snapshot) closePluginEditor(tab.plugin.key);
|
||||
finish();
|
||||
};
|
||||
finish(false);
|
||||
});
|
||||
try {
|
||||
localStorage.setItem(key, JSON.stringify({ root: workspace!.root, created: Date.now(), ...("buffer" in tab ? { buffer: tab.buffer } : { plugin: pluginTabState(tab.plugin) }), reading }));
|
||||
window.addEventListener("storage", accepted);
|
||||
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.
|
||||
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);
|
||||
return { token, finish };
|
||||
return { token, finish, offered };
|
||||
} catch (reason) { finish(); throw reason; }
|
||||
}
|
||||
function pinWorkingTab(path: string) {
|
||||
@@ -1127,12 +1139,14 @@
|
||||
}
|
||||
|
||||
function updateSettings(next: AppSettings) {
|
||||
saveSettings(localStorage, next);
|
||||
const saved = saveSettings(next);
|
||||
settings = { ...next };
|
||||
return saved;
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
try {
|
||||
// The layout stays in localStorage on purpose: per-machine view state that is harmless to lose.
|
||||
const layout = parseWorkbenchLayout(localStorage.getItem(WORKBENCH_LAYOUT_KEY));
|
||||
({ leftOpen, rightOpen, leftWidth, rightWidth, leftView } = layout);
|
||||
if (transferredWindow) { leftOpen = false; rightOpen = false; }
|
||||
@@ -1147,16 +1161,14 @@
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
try { settings = parseSettings(localStorage.getItem(SETTINGS_KEY)); }
|
||||
try { settings = readSettings(); }
|
||||
catch { error = "Could not read your settings. Default settings apply until you save new settings."; }
|
||||
error = takeSettingsNotice() ?? error;
|
||||
settingsReady = true;
|
||||
const syncSettings = (event: StorageEvent) => {
|
||||
if (event.storageArea === localStorage && (event.key === SETTINGS_KEY || event.key === null)) settings = parseSettings(event.newValue);
|
||||
};
|
||||
window.addEventListener("storage", syncSettings);
|
||||
const stopSettings = onSettingsChange("general", () => { settings = readSettings(); });
|
||||
window.addEventListener("keydown", onPreferencesKeydown, true);
|
||||
return () => {
|
||||
window.removeEventListener("storage", syncSettings);
|
||||
stopSettings();
|
||||
window.removeEventListener("keydown", onPreferencesKeydown, true);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// The first desktop settings file comes from the old localStorage values.
|
||||
// RuneStone leaves the old values in localStorage for one release, without further use.
|
||||
import { LEGACY_KEYS, type SettingsSection, type SettingsSections } from './store.ts';
|
||||
import { parseSettings } from '../workspace/settings.ts';
|
||||
import { normalizeLocale } from '../i18n/index.ts';
|
||||
import { parseCustomTheme, type CustomTheme } from '../theme/customThemes.ts';
|
||||
import { normalizeAppearance } from '../theme/appearance.ts';
|
||||
|
||||
function parse(raw: string | null): unknown {
|
||||
if (raw === null) return undefined;
|
||||
try { return JSON.parse(raw); } catch { return undefined; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read and normalize the old values. A missing key gives no section, so its defaults apply.
|
||||
* Version 1 custom themes become version 2 themes with the palette of the saved appearance mode.
|
||||
* Their original versions go to `customThemesLegacy`, together with an existing backup.
|
||||
*/
|
||||
export function migrateLegacyPreferences(read: (key: string) => string | null): SettingsSections {
|
||||
const raw = (section: SettingsSection) => { try { return read(LEGACY_KEYS[section]); } catch { return null; } };
|
||||
const result: SettingsSections = {};
|
||||
const general = raw('general');
|
||||
if (general !== null) result.general = parseSettings(general);
|
||||
const language = raw('language');
|
||||
if (language !== null) result.language = normalizeLocale(language);
|
||||
|
||||
const appearanceRaw = raw('appearance');
|
||||
const appearance = parse(appearanceRaw) as { mode?: unknown } | null | undefined;
|
||||
const legacyMode = appearance?.mode === 'light' ? 'light' : 'dark';
|
||||
const stored = parse(raw('customThemes'));
|
||||
const backup = parse(raw('customThemesLegacy'));
|
||||
const originals: unknown[] = Array.isArray(backup) ? [...backup] : [];
|
||||
let themes: CustomTheme[] = [];
|
||||
if (Array.isArray(stored)) {
|
||||
themes = stored.flatMap(value => { try { return [parseCustomTheme(value, legacyMode)]; } catch { return []; } });
|
||||
for (const value of stored.filter(value => value?.schema === 1)) {
|
||||
if (!originals.some(item => JSON.stringify(item) === JSON.stringify(value))) originals.push(value);
|
||||
}
|
||||
result.customThemes = themes;
|
||||
}
|
||||
if (originals.length) result.customThemesLegacy = originals;
|
||||
if (appearanceRaw !== null) {
|
||||
const value = appearance && typeof appearance === 'object' && !Array.isArray(appearance) ? appearance : null;
|
||||
result.appearance = normalizeAppearance(value, themes);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// User preferences. The desktop host keeps them in `<app config dir>/settings.json` (src-tauri/src/preferences.rs).
|
||||
// Each window loads all sections once at startup, then reads them from memory.
|
||||
// A write goes to the host, and the host sends `settings-changed` to all windows.
|
||||
//
|
||||
// Without the desktop host (`pnpm dev` in a browser), the sections stay in localStorage under their old keys.
|
||||
//
|
||||
// These values stay in localStorage on purpose, because they are per-machine view state that is harmless to lose:
|
||||
// `runestone.workbenchLayout` (src/lib/workspace/workbenchLayout.ts) and the open tabs of each workspace
|
||||
// (`documentSessionKey` in src/lib/workspace/documentSession.ts).
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
|
||||
export const SETTINGS_SECTIONS = ['general', 'appearance', 'customThemes', 'customThemesLegacy', 'language'] as const;
|
||||
export type SettingsSection = typeof SETTINGS_SECTIONS[number];
|
||||
export type SettingsSections = Partial<Record<SettingsSection, unknown>>;
|
||||
|
||||
/** The old localStorage key of each section: the browser preview storage, and the source of the first desktop file. */
|
||||
export const LEGACY_KEYS: Readonly<Record<SettingsSection, string>> = {
|
||||
general: 'runestone.settings',
|
||||
appearance: 'runestone.appearance',
|
||||
customThemes: 'runestone.custom-themes',
|
||||
customThemesLegacy: 'runestone.custom-themes.legacy',
|
||||
language: 'runestone.language',
|
||||
};
|
||||
|
||||
/** Make the first settings file from the old localStorage values. `read` returns the value of a key, or null. */
|
||||
export type Migration = (read: (key: string) => string | null) => SettingsSections;
|
||||
|
||||
type Snapshot = { exists: boolean; revision: number; sections: SettingsSections; notice?: string };
|
||||
type Change = { section: SettingsSection; revision: number; value: unknown };
|
||||
type Waiter = { resolve: () => void; reject: (reason: unknown) => void };
|
||||
|
||||
const cache: SettingsSections = {};
|
||||
const revisions = new Map<SettingsSection, number>();
|
||||
const subscribers = new Map<SettingsSection, Set<() => void>>();
|
||||
const queued = new Map<SettingsSection, { value: unknown; waiters: Waiter[] }>();
|
||||
const writing = new Set<SettingsSection>();
|
||||
// The newest change from another window that arrived during a local write of the same section.
|
||||
const deferred = new Map<SettingsSection, Change>();
|
||||
let started: Promise<void> | undefined;
|
||||
let notice: string | null = null;
|
||||
|
||||
function desktop() { return isTauri(); }
|
||||
|
||||
// The language section was a plain string in localStorage. The other sections were JSON.
|
||||
function decode(section: SettingsSection, raw: string | null): unknown {
|
||||
if (raw === null) return undefined;
|
||||
if (section === 'language') return raw;
|
||||
try { return JSON.parse(raw); } catch { return undefined; }
|
||||
}
|
||||
function encode(section: SettingsSection, value: unknown): string {
|
||||
return section === 'language' && typeof value === 'string' ? value : JSON.stringify(value);
|
||||
}
|
||||
|
||||
function notify(section: SettingsSection) {
|
||||
for (const callback of [...subscribers.get(section) ?? []]) {
|
||||
try { callback(); } catch (reason) { console.error(`A ${section} settings subscriber failed.`, reason); }
|
||||
}
|
||||
}
|
||||
|
||||
function receive(change: Change) {
|
||||
if (!(SETTINGS_SECTIONS as readonly string[]).includes(change.section)) return;
|
||||
// During a local write of this section, apply the newest change only after the write ends.
|
||||
// Otherwise an older event can show an old value for a moment.
|
||||
if (writing.has(change.section) || queued.has(change.section)) {
|
||||
if ((deferred.get(change.section)?.revision ?? -1) < change.revision) deferred.set(change.section, change);
|
||||
return;
|
||||
}
|
||||
if ((revisions.get(change.section) ?? -1) >= change.revision) return;
|
||||
revisions.set(change.section, change.revision);
|
||||
cache[change.section] = change.value ?? undefined;
|
||||
notify(change.section);
|
||||
}
|
||||
|
||||
function applySnapshot(snapshot: Snapshot) {
|
||||
for (const section of SETTINGS_SECTIONS) {
|
||||
if ((revisions.get(section) ?? -1) >= snapshot.revision) continue;
|
||||
revisions.set(section, snapshot.revision);
|
||||
cache[section] = snapshot.sections[section];
|
||||
}
|
||||
}
|
||||
|
||||
async function start(migrate: Migration) {
|
||||
if (!desktop()) {
|
||||
// The browser preview: other tabs report their changes through storage events.
|
||||
window.addEventListener('storage', event => {
|
||||
if (event.key === null) { SETTINGS_SECTIONS.forEach(notify); return; }
|
||||
const section = SETTINGS_SECTIONS.find(item => LEGACY_KEYS[item] === event.key);
|
||||
if (section) notify(section);
|
||||
});
|
||||
return;
|
||||
}
|
||||
// Listen before the read, so that no change between the read and the listener goes missing.
|
||||
await listen<Change>('settings-changed', event => receive(event.payload));
|
||||
let snapshot: Snapshot;
|
||||
try { snapshot = await invoke<Snapshot>('settings_read'); }
|
||||
catch (reason) {
|
||||
notice = `RuneStone could not read your settings, so the default settings apply: ${String(reason)}`;
|
||||
return;
|
||||
}
|
||||
if (!snapshot.exists) {
|
||||
const sections = migrate(key => { try { return localStorage.getItem(key); } catch { return null; } });
|
||||
try { snapshot = await invoke<Snapshot>('settings_migrate', { sections }); }
|
||||
catch (reason) {
|
||||
// Use the old values in this window, and keep them in localStorage for the next start.
|
||||
snapshot = { exists: false, revision: 0, sections };
|
||||
notice = `RuneStone could not save your settings file: ${String(reason)}`;
|
||||
}
|
||||
}
|
||||
applySnapshot(snapshot);
|
||||
notice ??= snapshot.notice ?? null;
|
||||
}
|
||||
|
||||
/** Load all sections once. Later calls return the same promise. */
|
||||
export function initSettings(migrate: Migration): Promise<void> {
|
||||
return started ??= start(migrate);
|
||||
}
|
||||
|
||||
/** A message for the user about the settings file, at most once for each window. */
|
||||
export function takeSettingsNotice(): string | null {
|
||||
const value = notice;
|
||||
notice = null;
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The stored value of a section, or undefined. Normalize it before use. */
|
||||
export function readSection(section: SettingsSection): unknown {
|
||||
if (desktop()) return cache[section];
|
||||
try { return decode(section, localStorage.getItem(LEGACY_KEYS[section])); }
|
||||
catch { return undefined; }
|
||||
}
|
||||
|
||||
async function flush(section: SettingsSection) {
|
||||
writing.add(section);
|
||||
try {
|
||||
for (let entry = queued.get(section); entry; entry = queued.get(section)) {
|
||||
queued.delete(section);
|
||||
try {
|
||||
const change = await invoke<Change>('settings_write', { section, value: entry.value ?? null });
|
||||
revisions.set(section, Math.max(revisions.get(section) ?? -1, change.revision));
|
||||
entry.waiters.forEach(waiter => waiter.resolve());
|
||||
} catch (reason) { entry.waiters.forEach(waiter => waiter.reject(reason)); }
|
||||
}
|
||||
} finally {
|
||||
writing.delete(section);
|
||||
const late = deferred.get(section);
|
||||
deferred.delete(section);
|
||||
// A write of another window that the host saved after this window's last write wins.
|
||||
if (late) receive(late);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace a section. This window reads the new value at once, and its subscribers run at once.
|
||||
* Without the desktop host, a refused browser storage write throws before anything changes.
|
||||
* On the desktop, the promise rejects when the host cannot save the file. Quick writes of one section
|
||||
* merge, so the host saves only the last value.
|
||||
*/
|
||||
export function writeSection(section: SettingsSection, value: unknown): Promise<void> {
|
||||
if (!desktop()) {
|
||||
localStorage.setItem(LEGACY_KEYS[section], encode(section, value));
|
||||
notify(section);
|
||||
return Promise.resolve();
|
||||
}
|
||||
cache[section] = value;
|
||||
notify(section);
|
||||
return new Promise((resolve, reject) => {
|
||||
const entry = queued.get(section) ?? { value, waiters: [] };
|
||||
entry.value = value;
|
||||
entry.waiters.push({ resolve, reject });
|
||||
queued.set(section, entry);
|
||||
if (!writing.has(section)) void flush(section);
|
||||
});
|
||||
}
|
||||
|
||||
/** Run `callback` after each change of `section` in this window or another window. Returns a function that stops it. */
|
||||
export function onSettingsChange(section: SettingsSection, callback: () => void): () => void {
|
||||
const list = subscribers.get(section) ?? new Set();
|
||||
list.add(callback);
|
||||
subscribers.set(section, list);
|
||||
return () => { list.delete(callback); };
|
||||
}
|
||||
@@ -7,7 +7,8 @@
|
||||
import Icon from '$lib/ui/Icon.svelte';
|
||||
import { showActionMenu } from '$lib/ui/managedActionMenu';
|
||||
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
|
||||
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, parseAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
|
||||
import { onSettingsChange } from '$lib/settings/store';
|
||||
import { DEFAULT_APPEARANCE, BUILTIN_THEMES, themeModes, BACKGROUND_POSITIONS, BACKGROUND_SIZES, readAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
|
||||
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
|
||||
let error = $state('');
|
||||
let status = $state('');
|
||||
@@ -43,12 +44,16 @@
|
||||
run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close;
|
||||
}
|
||||
onMount(() => {
|
||||
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); };
|
||||
const read = () => { try { installed = customThemes(); appearance = readAppearance(); } catch { error = $t('Could not read appearance settings.'); } };
|
||||
read();
|
||||
const stops = [onSettingsChange('appearance', read), onSettingsChange('customThemes', read)];
|
||||
return () => stops.forEach(stop => stop());
|
||||
});
|
||||
function change(next: Appearance) {
|
||||
try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; return true; }
|
||||
try {
|
||||
saveAppearance(next).catch(() => { error = $t('Could not save appearance settings.'); });
|
||||
appearance = normalizeAppearance(next); error = ''; return true;
|
||||
}
|
||||
catch { error = $t('Could not save appearance settings.'); return false; }
|
||||
}
|
||||
function changeOverlay(input: HTMLInputElement) {
|
||||
@@ -68,7 +73,7 @@
|
||||
try {
|
||||
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();
|
||||
installTheme(theme).catch(reason => { error = String(reason); }); installed = customThemes();
|
||||
change({ ...appearance, theme: `custom:${theme.id}` });
|
||||
} catch (reason) { error = String(reason); }
|
||||
finally { themeInput.value = ''; }
|
||||
@@ -121,7 +126,7 @@
|
||||
<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' }); }
|
||||
try { removeTheme(appearance.theme.slice(7)).catch(() => { error = 'Could not remove this theme.'; }); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
|
||||
catch { error = 'Could not remove this theme.'; }
|
||||
}} />{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,27 +1,24 @@
|
||||
<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';
|
||||
import { onSettingsChange, readSection, writeSection } from '$lib/settings/store';
|
||||
import { applyAppearance, readAppearance } from './appearance';
|
||||
onMount(() => {
|
||||
const stopLocale = syncLocale();
|
||||
const read = () => {
|
||||
try {
|
||||
const raw = localStorage.getItem(APPEARANCE_KEY);
|
||||
const appearance = parseAppearance(raw);
|
||||
const canonical = JSON.stringify(appearance);
|
||||
if (raw !== null && raw !== canonical) localStorage.setItem(APPEARANCE_KEY, canonical);
|
||||
const stored = readSection('appearance');
|
||||
const appearance = readAppearance();
|
||||
// Save the normalized value, for example a new ID for a renamed theme.
|
||||
if (stored !== undefined && JSON.stringify(stored) !== JSON.stringify(appearance)) {
|
||||
writeSection('appearance', appearance).catch(() => { /* The normalized value applies until the next save. */ });
|
||||
}
|
||||
applyAppearance(appearance);
|
||||
}
|
||||
catch { /* Keep the current appearance if storage is unavailable. */ }
|
||||
catch { /* Keep the current appearance if the settings are unavailable. */ }
|
||||
};
|
||||
const sync = (event: StorageEvent) => { if (event.key === APPEARANCE_KEY || event.key === CUSTOM_THEMES_KEY || event.key === null) read(); };
|
||||
read();
|
||||
window.addEventListener('storage', sync);
|
||||
window.addEventListener('focus', read);
|
||||
return () => { stopLocale(); window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
|
||||
const stops = [onSettingsChange('appearance', read), onSettingsChange('customThemes', read)];
|
||||
return () => { stopLocale(); stops.forEach(stop => stop()); };
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
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';
|
||||
import { readSection, writeSection } from '../settings/store.ts';
|
||||
/** The old localStorage key. The appearance section of the settings file replaces it. */
|
||||
export const APPEARANCE_KEY = 'runestone.appearance';
|
||||
export const THEMES = ['default', 'claude', 'sakura', 'harvest-moon', 'crimson-pilot', 'silver-serpent'] as const;
|
||||
export const BUILTIN_THEMES = [
|
||||
@@ -18,10 +20,11 @@ export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', '
|
||||
export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const;
|
||||
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; transparency?: unknown } | null): Appearance {
|
||||
/** `themes` is the list of custom themes. By default, it is the saved list. */
|
||||
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null, themes?: CustomTheme[]): 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 selectedCustom = theme.startsWith('custom:') ? customThemes(value?.mode === 'light' ? 'light' : 'dark').find(item => `custom:${item.id}` === theme) : undefined;
|
||||
const selectedCustom = theme.startsWith('custom:') ? (themes ?? 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 };
|
||||
@@ -43,6 +46,11 @@ export function parseAppearance(raw: string | null): Appearance {
|
||||
try { return normalizeAppearance(JSON.parse(raw || 'null')); }
|
||||
catch { return { ...DEFAULT_APPEARANCE }; }
|
||||
}
|
||||
/** The saved appearance, normalized. */
|
||||
export function readAppearance(): Appearance {
|
||||
const value = readSection('appearance');
|
||||
return normalizeAppearance(value && typeof value === 'object' && !Array.isArray(value) ? value : null);
|
||||
}
|
||||
const keys = ['bg', 'bg-elevated', 'bg-active', 'border', 'text-dim', 'text', 'text-strong', 'accent', 'selection'] as const;
|
||||
const palettes = {
|
||||
default: {
|
||||
@@ -203,9 +211,11 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
|
||||
}
|
||||
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
|
||||
}
|
||||
export function saveAppearance(value: Appearance) {
|
||||
/** Save and apply an appearance. Throws at once if browser storage refuses it. The promise reports a failed save. */
|
||||
export function saveAppearance(value: Appearance): Promise<void> {
|
||||
const appearance = normalizeAppearance(value);
|
||||
localStorage.setItem(APPEARANCE_KEY, JSON.stringify(appearance));
|
||||
const saved = writeSection('appearance', appearance);
|
||||
applyAppearance(appearance);
|
||||
return saved;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { readSection, writeSection } from '../settings/store.ts';
|
||||
|
||||
/** The old localStorage key. The customThemes section of the settings file replaces it. */
|
||||
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>>;
|
||||
@@ -38,48 +41,24 @@ export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" =
|
||||
return { schema: 2, id: value.id, name: value.name.trim(), colors: colors(value.schema === 1 ? legacyMode : "colors"), ...(fonts ? { fonts } : {}) };
|
||||
}
|
||||
|
||||
const pendingLegacy = new Map<string, CustomTheme[]>();
|
||||
|
||||
/** The saved custom themes. Version 1 themes use the palette of `legacyMode`, by default the saved appearance mode. */
|
||||
export function customThemes(legacyMode?: "light" | "dark"): CustomTheme[] {
|
||||
try {
|
||||
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);
|
||||
const stored = readSection('customThemes');
|
||||
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;
|
||||
if (!legacyMode) legacyMode = (readSection('appearance') as { mode?: unknown } | undefined)?.mode === 'light' ? 'light' : 'dark';
|
||||
const mode = legacyMode;
|
||||
return stored.flatMap(value => { try { return [parseCustomTheme(value, mode)]; } catch { return []; } });
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
export function installTheme(theme: CustomTheme): void {
|
||||
/** Throws at once if browser storage refuses the change. The promise reports a failed save. */
|
||||
export function installTheme(theme: CustomTheme): Promise<void> {
|
||||
const list = customThemes().filter(item => item.id !== theme.id);
|
||||
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify([...list, parseCustomTheme(theme)]));
|
||||
return writeSection('customThemes', [...list, parseCustomTheme(theme)]);
|
||||
}
|
||||
|
||||
export function removeTheme(id: string): void {
|
||||
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(customThemes().filter(item => item.id !== id)));
|
||||
/** Throws at once if browser storage refuses the change. The promise reports a failed save. */
|
||||
export function removeTheme(id: string): Promise<void> {
|
||||
return writeSection('customThemes', customThemes().filter(item => item.id !== id));
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { readSection, writeSection } from "../settings/store.ts";
|
||||
|
||||
/** The old localStorage key. The general section of the settings file replaces it. */
|
||||
export const SETTINGS_KEY = "runestone.settings";
|
||||
export const MIN_AUTOSAVE_SECONDS = 1;
|
||||
export const MAX_AUTOSAVE_SECONDS = 300;
|
||||
@@ -19,20 +22,28 @@ export function validAutosaveSeconds(value: unknown): value is number {
|
||||
&& value >= MIN_AUTOSAVE_SECONDS && value <= MAX_AUTOSAVE_SECONDS;
|
||||
}
|
||||
|
||||
export function parseSettings(raw: string | null): AppSettings {
|
||||
try {
|
||||
const value = JSON.parse(raw ?? "null");
|
||||
return {
|
||||
autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled,
|
||||
autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds,
|
||||
showInternalFolder: value?.showInternalFolder === true,
|
||||
};
|
||||
} catch { return { ...DEFAULT_SETTINGS }; }
|
||||
export function normalizeSettings(input: unknown): AppSettings {
|
||||
const value = input && typeof input === "object" ? input as Record<string, unknown> : null;
|
||||
return {
|
||||
autosaveEnabled: typeof value?.autosaveEnabled === "boolean" ? value.autosaveEnabled : DEFAULT_SETTINGS.autosaveEnabled,
|
||||
autosaveSeconds: validAutosaveSeconds(value?.autosaveSeconds) ? value.autosaveSeconds : DEFAULT_SETTINGS.autosaveSeconds,
|
||||
showInternalFolder: value?.showInternalFolder === true,
|
||||
};
|
||||
}
|
||||
|
||||
export function saveSettings(storage: Pick<Storage, "setItem">, settings: AppSettings): void {
|
||||
export function parseSettings(raw: string | null): AppSettings {
|
||||
try { return normalizeSettings(JSON.parse(raw ?? "null")); }
|
||||
catch { return { ...DEFAULT_SETTINGS }; }
|
||||
}
|
||||
|
||||
export function readSettings(): AppSettings {
|
||||
return normalizeSettings(readSection("general"));
|
||||
}
|
||||
|
||||
/** Check and save the settings. Throws at once for invalid values. The promise reports a failed save. */
|
||||
export function saveSettings(settings: AppSettings): Promise<void> {
|
||||
if (!validAutosaveSeconds(settings.autosaveSeconds) || typeof settings.autosaveEnabled !== "boolean") {
|
||||
throw new Error("Choose a whole number from 1 to 300 seconds.");
|
||||
}
|
||||
storage.setItem(SETTINGS_KEY, JSON.stringify(settings));
|
||||
return writeSection("general", { autosaveEnabled: settings.autosaveEnabled, autosaveSeconds: settings.autosaveSeconds, showInternalFolder: settings.showInternalFolder === true });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
// 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 receiving window takes the offer, opens the tab, and then finishes the offer.
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
|
||||
import { getCurrentWindow } from "@tauri-apps/api/window";
|
||||
import type { OpenBuffer } from "./types";
|
||||
|
||||
export const TAB_TRANSFER_ID = /^[0-9a-f-]{36}$/i;
|
||||
|
||||
export type TabTransfer = { reading: boolean } & ({ buffer: OpenBuffer } | { plugin: unknown });
|
||||
|
||||
/** The state that the source window sends. */
|
||||
export type TabTransferOffer = { reading: boolean } & ({ buffer: OpenBuffer } | { plugin: unknown });
|
||||
|
||||
/** Check the state of a taken offer. The new window and the tab ribbon use this one check. */
|
||||
export function parseTabTransfer(payload: string): TabTransfer {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(payload); } catch { throw new Error("Invalid tab transfer."); }
|
||||
const transfer = value && typeof value === "object" ? value as Record<string, unknown> : {};
|
||||
const reading = transfer.reading === true;
|
||||
const buffer = transfer.buffer as Record<string, unknown> | undefined;
|
||||
if (buffer && typeof buffer === "object" && typeof buffer.relPath === "string"
|
||||
&& typeof buffer.contents === "string" && typeof buffer.saved === "string") {
|
||||
return { buffer: buffer as unknown as OpenBuffer, reading };
|
||||
}
|
||||
if (transfer.plugin && typeof transfer.plugin === "object") return { plugin: transfer.plugin, reading };
|
||||
throw new Error("Invalid tab transfer.");
|
||||
}
|
||||
|
||||
/** Offer a tab with the ID `id`. The window creates the ID, because a drag needs it at once. */
|
||||
export function offerTabTransfer(id: string, root: string, offer: TabTransferOffer): Promise<string> {
|
||||
return invoke("tab_transfer_offer", { id, root, payload: JSON.stringify(offer) });
|
||||
}
|
||||
|
||||
/** Take an offer once. Fails when the offer expired or belongs to another workspace. */
|
||||
export async function takeTabTransfer(id: string, root: string): Promise<string> {
|
||||
if (!TAB_TRANSFER_ID.test(id)) throw new Error("Invalid tab transfer.");
|
||||
return invoke<string>("tab_transfer_take", { id, root });
|
||||
}
|
||||
|
||||
/** End a take. `accepted` tells the source window to close its tab. A refused offer stays open for another window. */
|
||||
export function finishTabTransfer(id: string, accepted: boolean): Promise<void> {
|
||||
return invoke("tab_transfer_finish", { id, accepted });
|
||||
}
|
||||
|
||||
/** Withdraw an offer that no window took. */
|
||||
export function cancelTabTransfer(id: string): Promise<void> {
|
||||
return invoke("tab_transfer_cancel", { id });
|
||||
}
|
||||
|
||||
/** Run `handler` when another window accepts a tab of this window. */
|
||||
export function onTabTransferAccepted(handler: (id: string) => void): Promise<UnlistenFn> {
|
||||
return listen<{ id: string }>("tab-transfer-accepted", event => handler(event.payload.id), { target: getCurrentWindow().label });
|
||||
}
|
||||
Reference in New Issue
Block a user