321 lines
12 KiB
JavaScript
321 lines
12 KiB
JavaScript
// Rôle : synchronise l'état optimiste des toolboxes avec une file d'écritures IndexedDB.
|
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
import {
|
|
getModuleDataEntries as dbGetModuleDataEntries,
|
|
getLinks as dbGetLinks,
|
|
getSetting as dbGetSetting,
|
|
getStorageEstimate,
|
|
getToolboxSnapshot as dbGetToolboxSnapshot,
|
|
getToolboxes as dbGetToolboxes,
|
|
mutateToolboxStorage as dbMutateToolboxStorage,
|
|
setSetting as dbSetSetting,
|
|
} from "../../../utils/indexedDbStorage.js";
|
|
import {
|
|
compactToolboxesForStorage,
|
|
moduleStorageKey,
|
|
normalizeToolbox,
|
|
prepareModuleDataForStorage
|
|
} from "./toolboxStorage.js";
|
|
import { applyModuleDataValue, removeModuleDataKeys } from "./optimisticModuleData.js";
|
|
import { createPersistenceQueue } from "./persistenceQueue.js";
|
|
import { createQuotaRefresh } from "./quotaRefresh.js";
|
|
import { DEFERRED_MODULE_DATA, getDeferredModuleKeys, mergeLoadedModuleData } from "./deferredModuleData.js";
|
|
import { AUTO_BACKUP_DATA_CHANGED_EVENT } from "./autoBackup.js";
|
|
import { createStorageMutation, getStorageMutationNotice } from "./storageMutation.js";
|
|
|
|
const STORAGE_CHANNEL = "sokkog:toolbox-storage";
|
|
|
|
function normalizeToolboxes(toolboxes) {
|
|
return compactToolboxesForStorage(toolboxes).map(normalizeToolbox).filter(Boolean);
|
|
}
|
|
|
|
function normalizeToolboxesForStorage(toolboxes) {
|
|
return compactToolboxesForStorage(normalizeToolboxes(toolboxes));
|
|
}
|
|
|
|
async function readStoredState({ preservedModuleData = {}, refreshedModuleKeys = [] } = {}) {
|
|
const [toolboxes, links, toastPosition] = await Promise.all([
|
|
dbGetToolboxes(), dbGetLinks(), dbGetSetting("toastPosition", "right")
|
|
]);
|
|
const normalizedToolboxes = (Array.isArray(toolboxes) ? toolboxes : []).map(normalizeToolbox).filter(Boolean);
|
|
const registeredKeys = new Set(normalizedToolboxes.flatMap((toolbox) => (toolbox.modules || [])
|
|
.map((module) => `${toolbox.id}:${module.id}`)));
|
|
const deferredKeys = getDeferredModuleKeys(normalizedToolboxes);
|
|
const refreshed = new Set(refreshedModuleKeys);
|
|
const excludedKeys = [...registeredKeys].filter((key) => {
|
|
if (refreshed.has(key)) return false;
|
|
if (preservedModuleData[key] !== undefined && preservedModuleData[key] !== DEFERRED_MODULE_DATA) return true;
|
|
return deferredKeys.includes(key);
|
|
});
|
|
const excluded = new Set(excludedKeys);
|
|
const modules = await dbGetModuleDataEntries([...registeredKeys].filter((key) => !excluded.has(key)));
|
|
const moduleData = Object.fromEntries([
|
|
...deferredKeys.map((key) => [key, DEFERRED_MODULE_DATA]),
|
|
...(modules || []).map((entry) => [entry.key, entry.data])
|
|
]);
|
|
for (const key of excludedKeys) {
|
|
const preserved = preservedModuleData[key];
|
|
if (preserved !== undefined && preserved !== DEFERRED_MODULE_DATA) moduleData[key] = preserved;
|
|
}
|
|
for (const key of refreshed) {
|
|
if (deferredKeys.includes(key) && !(modules || []).some((entry) => entry.key === key)) delete moduleData[key];
|
|
}
|
|
return {
|
|
toolboxes: normalizedToolboxes,
|
|
links: links && typeof links === "object" ? links : {},
|
|
moduleData,
|
|
toastPosition: toastPosition === "left" ? "left" : "right"
|
|
};
|
|
}
|
|
|
|
export function useIndexedToolboxes(onError) {
|
|
const [ready, setReady] = useState(false);
|
|
const [loadError, setLoadError] = useState("");
|
|
const [loadAttempt, setLoadAttempt] = useState(0);
|
|
const writableRef = useRef(false);
|
|
const pendingReadsRef = useRef(new Map());
|
|
const storageChannelRef = useRef(null);
|
|
const [state, setState] = useState({ toolboxes: [], links: {}, moduleData: {}, toastPosition: "right" });
|
|
const [persistenceStatus, setPersistenceStatus] = useState({ phase: "loading", pendingCount: 0, lastConfirmedAt: "", message: "" });
|
|
const [queue] = useState(() => createPersistenceQueue(state, setState, setPersistenceStatus));
|
|
const [storageUsage, setStorageUsage] = useState({ used: 0, limit: 0, ratio: 0 });
|
|
const quotaRefreshRef = useRef(null);
|
|
const reportStorageError = useCallback((error) => {
|
|
onError(error?.message || "Erreur de stockage IndexedDB.");
|
|
}, [onError]);
|
|
|
|
useEffect(() => {
|
|
const refresh = createQuotaRefresh({
|
|
estimate: getStorageEstimate,
|
|
onResult: (estimate) => {
|
|
const used = estimate.usage || 0;
|
|
const limit = estimate.quota || 0;
|
|
setStorageUsage((current) => current.used === used && current.limit === limit
|
|
? current
|
|
: { used, limit, ratio: limit ? Math.min(1, used / limit) : 0 });
|
|
}
|
|
});
|
|
quotaRefreshRef.current = refresh;
|
|
return () => {
|
|
refresh.dispose();
|
|
quotaRefreshRef.current = null;
|
|
};
|
|
}, []);
|
|
const refreshQuota = useCallback(() => quotaRefreshRef.current?.request(), []);
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
async function loadStore() {
|
|
try {
|
|
const storedState = await readStoredState();
|
|
if (cancelled) return;
|
|
queue.initialize(storedState);
|
|
writableRef.current = true;
|
|
setReady(true);
|
|
refreshQuota();
|
|
} catch (error) {
|
|
if (!cancelled) {
|
|
setLoadError(error?.message || "Erreur de stockage IndexedDB.");
|
|
}
|
|
}
|
|
}
|
|
loadStore();
|
|
return () => { cancelled = true; writableRef.current = false; };
|
|
}, [queue, refreshQuota, loadAttempt]);
|
|
|
|
useEffect(() => {
|
|
if (!ready || typeof BroadcastChannel === "undefined") return undefined;
|
|
const channel = new BroadcastChannel(STORAGE_CHANNEL);
|
|
storageChannelRef.current = channel;
|
|
channel.onmessage = (event) => {
|
|
if (!writableRef.current || !event.data || event.data.type !== "changed") return;
|
|
const current = queue.getCurrent();
|
|
const refreshedModuleKeys = (event.data.moduleKeys || []).filter((key) => current.moduleData[key] !== DEFERRED_MODULE_DATA);
|
|
void queue.enqueue(
|
|
(confirmed) => confirmed,
|
|
(next) => readStoredState({ preservedModuleData: next.moduleData, refreshedModuleKeys }),
|
|
reportStorageError,
|
|
{ trackStatus: false }
|
|
);
|
|
};
|
|
return () => {
|
|
channel.close();
|
|
if (storageChannelRef.current === channel) storageChannelRef.current = null;
|
|
};
|
|
}, [queue, ready, reportStorageError]);
|
|
|
|
function retryLoad() {
|
|
if (ready || !loadError) return;
|
|
setLoadError("");
|
|
setLoadAttempt((attempt) => attempt + 1);
|
|
}
|
|
|
|
function enqueue(apply, persist, { marksBackupDirty = true } = {}) {
|
|
if (!writableRef.current) return Promise.resolve(false);
|
|
const result = queue.enqueue(apply, persist, reportStorageError);
|
|
void result.then((success) => {
|
|
if (!success) return;
|
|
refreshQuota();
|
|
if (marksBackupDirty && typeof window !== "undefined") {
|
|
window.dispatchEvent(new window.Event(AUTO_BACKUP_DATA_CHANGED_EVENT));
|
|
}
|
|
});
|
|
return result;
|
|
}
|
|
|
|
async function persistMutation(next, confirmed) {
|
|
const expectedStorage = {
|
|
toolboxes: compactToolboxesForStorage(confirmed.toolboxes),
|
|
links: confirmed.links,
|
|
moduleData: confirmed.moduleData
|
|
};
|
|
const nextStorage = {
|
|
toolboxes: compactToolboxesForStorage(next.toolboxes),
|
|
links: next.links,
|
|
moduleData: next.moduleData
|
|
};
|
|
const mutation = createStorageMutation(expectedStorage, nextStorage);
|
|
if (!mutation.changed) return next;
|
|
const notice = getStorageMutationNotice(mutation);
|
|
try {
|
|
await dbMutateToolboxStorage(mutation, { normalizeToolboxes: normalizeToolboxesForStorage });
|
|
} catch (error) {
|
|
if (error?.name === "StorageConflictError") {
|
|
error.confirmedState = await readStoredState({
|
|
preservedModuleData: confirmed.moduleData,
|
|
refreshedModuleKeys: notice.moduleKeys
|
|
});
|
|
}
|
|
throw error;
|
|
}
|
|
const persisted = await readStoredState({
|
|
preservedModuleData: next.moduleData
|
|
});
|
|
storageChannelRef.current?.postMessage({ type: "changed", ...notice });
|
|
return persisted;
|
|
}
|
|
|
|
function persistToolboxes(value) {
|
|
if (!writableRef.current) return false;
|
|
const apply = typeof value === "function" ? value : () => value;
|
|
enqueue(
|
|
(current) => ({ ...current, toolboxes: normalizeToolboxes(apply(current.toolboxes)) }),
|
|
persistMutation
|
|
);
|
|
return true;
|
|
}
|
|
|
|
function persistLinks(value) {
|
|
if (!writableRef.current) return false;
|
|
enqueue(
|
|
(current) => ({ ...current, links: typeof value === "function" ? value(current.links) : value }),
|
|
persistMutation
|
|
);
|
|
return true;
|
|
}
|
|
|
|
function getModuleData(toolboxId, moduleId, fallback) {
|
|
return queue.getCurrent().moduleData[moduleStorageKey(toolboxId, moduleId)] ?? fallback;
|
|
}
|
|
|
|
function updateModuleData(toolboxId, moduleId, value, moduleType = "") {
|
|
if (!writableRef.current) return false;
|
|
if (queue.getCurrent().moduleData[moduleStorageKey(toolboxId, moduleId)] === DEFERRED_MODULE_DATA) return false;
|
|
const compact = prepareModuleDataForStorage(queue.getCurrent().toolboxes, toolboxId, moduleId, value, moduleType);
|
|
const key = moduleStorageKey(toolboxId, moduleId);
|
|
const hasModule = (current) => current.toolboxes.some((toolbox) => toolbox.id === toolboxId && toolbox.modules.some((module) => module.id === moduleId));
|
|
enqueue(
|
|
(current) => hasModule(current) ? { ...current, moduleData: applyModuleDataValue(current.moduleData, key, compact) } : current,
|
|
persistMutation
|
|
);
|
|
return true;
|
|
}
|
|
|
|
function removeModuleData(toolboxId, moduleId) {
|
|
const key = moduleStorageKey(toolboxId, moduleId);
|
|
return enqueue(
|
|
(current) => ({ ...current, moduleData: removeModuleDataKeys(current.moduleData, [key]) }),
|
|
persistMutation
|
|
);
|
|
}
|
|
|
|
function removeToolboxModuleData(toolbox) {
|
|
if (!writableRef.current) return Promise.resolve(false);
|
|
const keys = (toolbox?.modules || []).map((module) => moduleStorageKey(toolbox.id, module.id));
|
|
if (!keys.length) return Promise.resolve(true);
|
|
return enqueue(
|
|
(current) => ({ ...current, moduleData: removeModuleDataKeys(current.moduleData, keys) }),
|
|
persistMutation
|
|
);
|
|
}
|
|
|
|
function persistToolboxSnapshot(updater) {
|
|
return enqueue((current) => {
|
|
const next = updater(current);
|
|
return { ...current, ...next, toolboxes: normalizeToolboxes(next.toolboxes) };
|
|
}, persistMutation);
|
|
}
|
|
|
|
const ensureModuleData = useCallback((toolboxId, moduleId) => {
|
|
const key = moduleStorageKey(toolboxId, moduleId);
|
|
if (queue.getCurrent().moduleData[key] !== DEFERRED_MODULE_DATA) return Promise.resolve();
|
|
if (pendingReadsRef.current.has(key)) return pendingReadsRef.current.get(key);
|
|
const request = (async () => {
|
|
const entries = await dbGetModuleDataEntries([key]);
|
|
if (!writableRef.current) return;
|
|
await queue.enqueue((current) => ({
|
|
...current, moduleData: mergeLoadedModuleData(current.moduleData, [key], entries)
|
|
}), () => {}, undefined, { trackStatus: false });
|
|
})();
|
|
pendingReadsRef.current.set(key, request);
|
|
void request.then(() => pendingReadsRef.current.delete(key), () => pendingReadsRef.current.delete(key));
|
|
return request;
|
|
}, [queue]);
|
|
|
|
async function getExportSnapshot(toolboxId, options = {}) {
|
|
if (!writableRef.current) return null;
|
|
let snapshot;
|
|
const success = await queue.enqueue((current) => current, async () => {
|
|
const stored = await dbGetToolboxSnapshot(toolboxId);
|
|
const toolboxes = (stored.toolboxes || []).map(normalizeToolbox).filter(Boolean);
|
|
snapshot = {
|
|
toolboxes,
|
|
links: stored.links,
|
|
moduleData: stored.moduleData,
|
|
toastPosition: queue.getCurrent().toastPosition
|
|
};
|
|
}, options.onError || reportStorageError, { trackStatus: false });
|
|
return success ? snapshot : null;
|
|
}
|
|
|
|
function setToastPosition(position) {
|
|
if (!writableRef.current) return false;
|
|
const toastPosition = position === "left" ? "left" : "right";
|
|
enqueue(
|
|
(current) => ({ ...current, toastPosition }),
|
|
() => dbSetSetting("toastPosition", toastPosition),
|
|
{ marksBackupDirty: false }
|
|
);
|
|
}
|
|
|
|
return {
|
|
...state,
|
|
ready,
|
|
loadError,
|
|
retryLoad,
|
|
persistenceStatus,
|
|
storageUsage,
|
|
setToolboxes: persistToolboxes,
|
|
setLinks: persistLinks,
|
|
getModuleData,
|
|
ensureModuleData,
|
|
isModuleDataReady: (toolboxId, moduleId) => state.moduleData[moduleStorageKey(toolboxId, moduleId)] !== DEFERRED_MODULE_DATA,
|
|
getExportSnapshot,
|
|
updateModuleData,
|
|
removeModuleData,
|
|
removeToolboxModuleData,
|
|
setToastPosition,
|
|
refreshQuota,
|
|
persistToolboxSnapshot
|
|
};
|
|
}
|