feat(launcher): remember last selected directory in file and folder pickers

Persist per-category dialog directories under userData/dialog-paths.json and resolve existing parent fallbacks for folder pickers, save archive import/export, online backup selection, and mod preset/folder dialogs.
This commit is contained in:
N0VAN0M4LY committed 2026-12-04 19:55:04 +08:00
1 parent 8f1d175d55
commit b3211b89cd
6 files changed
+226 -12

No files matched your search

+11 -3
View File
@@ -32,6 +32,7 @@ import {
} from '../services/mods/mods-service.ts';
import { resourcePaths } from '../services/resources/resource-paths.ts';
import { changeSaveAccount, changeSaveResearch, copyOnlineData, createSave, discoverOnlineData, exportSave, getSaveAvatarChoices, getSaveAvatarPreview, getSaveDetails, getSaveList, getSaveResearch, importSelectedBackups, listSaveBackups, pickOfficialBackups, pickSaveArchive, previewSelectedBackups, removeSave, restoreSaveBackup, saveWriteInProgress, selectSave, setSaveCurrencies, takeSaveBackup, transferSave } from '../services/saves/manage-saves.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../util/dialog-paths.ts';
import { broadcast, handle } from './register.ts';
/** Registers the handler of every contract channel. One line per channel; the work is in services/. */
@@ -68,11 +69,18 @@ export function registerIpcHandlers(): void {
BrowserWindow.fromWebContents(sender)?.close();
});
handle('dialog:pickFolder', async ({ title }, sender) => {
handle('dialog:pickFolder', async ({ title, defaultPath }, sender) => {
const window = BrowserWindow.fromWebContents(sender);
const options = { properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>, ...(title ? { title } : {}) };
const resolvedDefaultPath = await resolveDialogDefaultPath('folder', defaultPath);
const options = {
properties: ['openDirectory', 'createDirectory'] as Array<'openDirectory' | 'createDirectory'>,
...(title ? { title } : {}),
...(resolvedDefaultPath ? { defaultPath: resolvedDefaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return { path: result.canceled ? null : (result.filePaths[0] ?? null) };
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
if (chosen) await rememberDialogPath('folder', chosen);
return { path: chosen };
});
handle('install:prepareCopy', () => createCopyDraft());
@@ -17,6 +17,7 @@ import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import { ModPresetTransferSchema, type ModListItem, type ModsStateView } from '@shared/schemas/mods.ts';
import { readJsonOr, writeJsonAtomic } from '../../util/atomic-json.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
import { getSettings, updateSettings } from '../config/settings-store.ts';
import { listCopies } from '../install/install-record.ts';
import { resourcePaths } from '../resources/resource-paths.ts';
@@ -236,8 +237,10 @@ export async function exportModPreset(
if (!preset) throw new AppError('mods_preset_invalid');
const safeName = preset.name.replace(/[^A-Za-z0-9\u4e00-\u9fa5._-]+/g, '-').replace(/^-+|-+$/g, '') || 'preset';
const defaultDir = await resolveDialogDefaultPath('mod-preset');
const fileName = `${safeName}.wto-mods-preset.json`;
const dialogOptions = {
defaultPath: `${safeName}.wto-mods-preset.json`,
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
};
const choice = window
@@ -252,6 +255,7 @@ export async function exportModPreset(
enabled: { ...preset.enabled },
};
await writeFile(choice.filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8');
await rememberDialogPath('mod-preset', choice.filePath);
return { path: choice.filePath };
}
@@ -260,9 +264,11 @@ export async function importModPreset(
window: BrowserWindow | null,
): Promise<{ readonly imported: boolean; readonly state: ModsStateView }> {
const copy = await requireCopy(copyId);
const defaultPath = await resolveDialogDefaultPath('mod-preset');
const dialogOptions = {
properties: ['openFile'] as Array<'openFile'>,
filters: [{ name: 'WTOffline Mod Preset', extensions: ['json'] }],
...(defaultPath ? { defaultPath } : {}),
};
const choice = window
? await dialog.showOpenDialog(window, dialogOptions)
@@ -270,6 +276,7 @@ export async function importModPreset(
if (choice.canceled || !choice.filePaths[0]) {
return { imported: false, state: await buildModsStateView(copy) };
}
await rememberDialogPath('mod-preset', choice.filePaths[0]);
let parsedRaw: unknown;
try {
@@ -309,6 +316,7 @@ export async function setModsFolder(copyId: string, folderPath: string | null):
}
}
await updateSettings({ modsFolder: folderPath });
if (folderPath !== null) await rememberDialogPath('mods-folder', folderPath);
const copy = await requireCopy(copyId);
return buildModsStateView(copy);
}
@@ -6,6 +6,7 @@ import { AppError } from '@shared/errors.ts';
import type { InstallRecord } from '@shared/schemas/install.ts';
import type { AccountEdits, CurrencyEdits, OfficialImportOptions, OfficialPreview, OnlineDataSource, SaveBackup, SaveDetails, SaveList, SaveRegistration, SaveTransfer, ResearchBranch, ResearchOperation, SaveAvatarChoices, SaveResearch } from '@shared/schemas/saves.ts';
import type { SaveReply, SaveResult, SaveTask } from '../../workers/save-protocol.ts';
import { rememberDialogPath, resolveDialogDefaultPath } from '../../util/dialog-paths.ts';
import { maintenanceInProgress } from '../copies/copy-maintenance.ts';
import { canonicalCopyPath, copyPathContains, listCopies, updateCopyRecord } from '../install/install-record.ts';
import { gameProcessRunning, launchInProgress } from '../launch/launch-controller.ts';
@@ -95,15 +96,27 @@ export async function setSaveCurrencies(copyId: string, userId: string, values:
}
export async function pickSaveArchive(window: BrowserWindow | null): Promise<{ path: string | null }> {
const options = { properties: ['openFile' as const], filters: [{ name: 'ZIP', extensions: ['zip'] }] };
const defaultPath = await resolveDialogDefaultPath('save-archive');
const options = {
properties: ['openFile' as const],
filters: [{ name: 'ZIP', extensions: ['zip'] }],
...(defaultPath ? { defaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return { path: result.canceled ? null : result.filePaths[0] ?? null };
const chosen = result.canceled ? null : (result.filePaths[0] ?? null);
if (chosen) await rememberDialogPath('save-archive', chosen);
return { path: chosen };
}
export async function exportSave(copyId: string, userId: string, window: BrowserWindow | null): Promise<{ path: string | null }> {
const copy = await requireCopy(copyId);
await getSaveDetails(copyId, userId);
const options = { defaultPath: `WTOffline-save-${userId}.zip`, filters: [{ name: 'ZIP', extensions: ['zip'] }] };
const defaultDir = await resolveDialogDefaultPath('save-archive');
const fileName = `WTOffline-save-${userId}.zip`;
const options = {
defaultPath: defaultDir ? join(defaultDir, fileName) : fileName,
filters: [{ name: 'ZIP', extensions: ['zip'] }],
};
const result = window ? await dialog.showSaveDialog(window, options) : await dialog.showSaveDialog(options);
if (result.canceled || !result.filePath) return { path: null };
try {
@@ -113,6 +126,7 @@ export async function exportSave(copyId: string, userId: string, window: Browser
console.error('[saves] could not export the save:', error);
throw new AppError('save_operation_failed');
}
await rememberDialogPath('save-archive', result.filePath);
return { path: result.filePath };
}
@@ -275,9 +289,16 @@ export async function copyOnlineData(copyId: string, userId: string, accountId:
}
export async function pickOfficialBackups(window: BrowserWindow | null): Promise<string[]> {
const options = { properties: ['openFile' as const, 'multiSelections' as const], filters: [{ name: 'BLK', extensions: ['blk'] }] };
const defaultPath = await resolveDialogDefaultPath('official-backups');
const options = {
properties: ['openFile' as const, 'multiSelections' as const],
filters: [{ name: 'BLK', extensions: ['blk'] }],
...(defaultPath ? { defaultPath } : {}),
};
const result = window ? await dialog.showOpenDialog(window, options) : await dialog.showOpenDialog(options);
return result.canceled ? [] : result.filePaths;
if (result.canceled || result.filePaths.length === 0) return [];
if (result.filePaths[0]) await rememberDialogPath('official-backups', result.filePaths[0]);
return result.filePaths;
}
export async function previewSelectedBackups(
+171
View File
@@ -0,0 +1,171 @@
import { stat } from 'node:fs/promises';
import { dirname, isAbsolute, join, resolve } from 'node:path';
import { readJsonOr, writeJsonAtomic } from './atomic-json.ts';
/**
* Remembers the last directory chosen in native open/save dialogs, keyed by dialog category,
* persisted to `<userData>/dialog-paths.json`. Read/write errors are swallowed so dialog
* behavior is never disrupted.
*/
export type DialogPathCategory =
| 'folder'
| 'save-archive'
| 'official-backups'
| 'mods-folder'
| 'mod-preset';
export interface DialogPathStore {
resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined>;
rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void>;
}
const DIALOG_PATHS_FILENAME = 'dialog-paths.json';
const LAST_KEY = 'last';
const MAX_ANCESTOR_STEPS = 128;
/**
* Resolve `candidate` to an existing directory:
* - If it is an existing directory, return its normalized path.
* - If it is an existing file or does not exist, walk up to the nearest existing ancestor directory.
* - Return `undefined` when no existing ancestor directory can be reached.
*/
export async function resolveExistingDirectory(candidate: string | null | undefined): Promise<string | undefined> {
if (!candidate) return undefined;
const trimmed = candidate.trim();
if (!trimmed || !isAbsolute(trimmed)) return undefined;
let current = resolve(trimmed);
for (let step = 0; step < MAX_ANCESTOR_STEPS; step++) {
try {
const info = await stat(current);
if (info.isDirectory()) return current;
} catch {
// Missing or inaccessible path; continue walking toward the filesystem root.
}
const parent = dirname(current);
if (parent === current) return undefined;
current = parent;
}
return undefined;
}
/** Create a dialog-path store backed by the JSON file path returned by `resolveStorePath`. */
export function createDialogPathStore(
resolveStorePath: () => Promise<string | null> | string | null,
): DialogPathStore {
let cached: Map<string, string> | null = null;
let loading: Promise<Map<string, string>> | null = null;
let pending: Promise<void> = Promise.resolve();
async function loadMap(): Promise<Map<string, string>> {
if (cached) return cached;
if (loading) return loading;
loading = (async () => {
const map = new Map<string, string>();
const storePath = await resolveStorePath();
if (storePath) {
try {
const raw = await readJsonOr(storePath, null);
if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
if (typeof value === 'string' && value.trim().length > 0) {
map.set(key, value);
}
}
}
} catch (error) {
console.warn('[dialog-paths] failed to read dialog paths:', error);
}
}
cached = map;
return map;
})().finally(() => {
loading = null;
});
return loading;
}
return {
async resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined> {
try {
const explicitDir = await resolveExistingDirectory(explicitPath);
if (explicitDir) return explicitDir;
const map = await loadMap();
const categoryPath = map.get(category);
if (categoryPath) {
const resolved = await resolveExistingDirectory(categoryPath);
if (resolved) return resolved;
}
const lastPath = map.get(LAST_KEY);
if (lastPath && lastPath !== categoryPath) {
const resolved = await resolveExistingDirectory(lastPath);
if (resolved) return resolved;
}
} catch (error) {
console.warn('[dialog-paths] failed to resolve default dialog path:', error);
}
return undefined;
},
async rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
const dir = await resolveExistingDirectory(selectedPath);
if (!dir) return;
const operation = pending.then(async () => {
const map = await loadMap();
if (map.get(category) === dir && map.get(LAST_KEY) === dir) return;
map.set(category, dir);
map.set(LAST_KEY, dir);
const storePath = await resolveStorePath();
if (!storePath) return;
try {
await writeJsonAtomic(storePath, Object.fromEntries(map));
} catch (error) {
console.warn('[dialog-paths] failed to save dialog paths:', error);
}
});
pending = operation.then(() => undefined, () => undefined);
await operation;
},
};
}
async function defaultStorePath(): Promise<string | null> {
try {
const mod = await import('electron') as {
readonly app?: { getPath?: (name: 'userData') => string };
readonly default?: { app?: { getPath?: (name: 'userData') => string } };
};
const electronApp = mod.app ?? mod.default?.app;
if (typeof electronApp?.getPath !== 'function') return null;
return join(electronApp.getPath('userData'), DIALOG_PATHS_FILENAME);
} catch {
return null;
}
}
const defaultStore = createDialogPathStore(defaultStorePath);
export function resolveDialogDefaultPath(
category: DialogPathCategory,
explicitPath?: string | null,
): Promise<string | undefined> {
return defaultStore.resolveDialogDefaultPath(category, explicitPath);
}
export function rememberDialogPath(category: DialogPathCategory, selectedPath: string): Promise<void> {
return defaultStore.rememberDialogPath(category, selectedPath);
}
@@ -14,7 +14,10 @@ interface FolderFieldProps {
export function FolderField({ path, dialogTitle, disabled = false, onChosen, onError }: FolderFieldProps) {
const { t } = useTranslation();
const choose = (): void => {
ipcInvoke('dialog:pickFolder', { title: dialogTitle })
ipcInvoke('dialog:pickFolder', {
title: dialogTitle,
...(path ? { defaultPath: path } : {}),
})
.then(({ path: chosen }) => {
if (chosen) onChosen(chosen);
})
+5 -2
View File
@@ -65,8 +65,11 @@ export const ipcContract = {
output: z.object({ path: z.string().nullable() }),
},
'dialog:pickFolder': {
/** The dialog title, already translated by the window. */
input: z.object({ title: z.string().optional() }),
/** The dialog title, already translated by the window, and an optional starting path. */
input: z.object({
title: z.string().optional(),
defaultPath: z.string().optional(),
}),
/** The chosen folder, or null when the player cancelled. */
output: z.object({ path: z.string().nullable() }),
},