caseGlobalConfig.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import { getCellLocalPath, setCellLocalPath } from './cell/cellLocal';
  2. import { getOfflineMapDir, setOfflineMapDir } from './map/offlineMap';
  3. type PersistedCaseGlobalConfig = {
  4. offlineMapDir?: string;
  5. cellLocalPath?: string;
  6. };
  7. const normalizeText = (value: unknown) => String(value ?? '').trim();
  8. const isPlainObject = (value: unknown): value is Record<string, unknown> =>
  9. Object.prototype.toString.call(value) === '[object Object]';
  10. export async function readPersistedCaseGlobalConfig(): Promise<PersistedCaseGlobalConfig> {
  11. const ipcRenderer = (window as any)?.electron?.ipcRenderer;
  12. if (!ipcRenderer?.invoke) return {};
  13. try {
  14. const payload = await ipcRenderer.invoke('controller/os/readCaseGlobalConfig');
  15. if (!isPlainObject(payload)) return {};
  16. return {
  17. offlineMapDir: normalizeText(payload.offlineMapDir),
  18. cellLocalPath: normalizeText(payload.cellLocalPath),
  19. };
  20. } catch {
  21. return {};
  22. }
  23. }
  24. export async function writePersistedCaseGlobalConfig(patch: Partial<PersistedCaseGlobalConfig>): Promise<boolean> {
  25. const ipcRenderer = (window as any)?.electron?.ipcRenderer;
  26. if (!ipcRenderer?.invoke) return false;
  27. try {
  28. const payload: Partial<PersistedCaseGlobalConfig> = {};
  29. if (Object.prototype.hasOwnProperty.call(patch, 'offlineMapDir')) {
  30. payload.offlineMapDir = normalizeText(patch.offlineMapDir);
  31. }
  32. if (Object.prototype.hasOwnProperty.call(patch, 'cellLocalPath')) {
  33. payload.cellLocalPath = normalizeText(patch.cellLocalPath);
  34. }
  35. return !!(await ipcRenderer.invoke('controller/os/writeCaseGlobalConfig', payload));
  36. } catch {
  37. return false;
  38. }
  39. }
  40. export async function hydratePersistedCaseGlobalConfig() {
  41. const config = await readPersistedCaseGlobalConfig();
  42. const offlineMapDir = normalizeText(config.offlineMapDir);
  43. const cellLocalPath = normalizeText(config.cellLocalPath);
  44. if (offlineMapDir && !getOfflineMapDir()) {
  45. setOfflineMapDir(offlineMapDir);
  46. }
  47. if (cellLocalPath && !getCellLocalPath()) {
  48. setCellLocalPath(cellLocalPath);
  49. }
  50. return {
  51. offlineMapDir: getOfflineMapDir(),
  52. cellLocalPath: getCellLocalPath(),
  53. };
  54. }