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:
@@ -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);
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user