Autosave mit Wiederherstellen (IndexedDB alle 30 s bei ungespeicherten Aenderungen; Angebot beim Start und beim Oeffnen: Wiederherstellen/Verwerfen/Spaeter); Meldungen per Toast statt window.alert
This commit is contained in:
1 parent
c75408c0e6
commit
dadcf7b4a0
8 files changed
+249
-18
No files matched your search
+37
-7
@@ -49,6 +49,7 @@ import { ExportSaveDialog } from "./ui/ExportSaveDialog";
|
||||
import { PromptDialog } from "./ui/PromptDialog";
|
||||
import { LockConflictDialog } from "./ui/LockConflictDialog";
|
||||
import { UnsavedChangesDialog } from "./ui/UnsavedChangesDialog";
|
||||
import { RecoverAutosaveDialog } from "./ui/RecoverAutosaveDialog";
|
||||
import { Toast } from "./ui/Toast";
|
||||
import { isTauriRuntime, PROJECT_TEMPLATE_EXT } from "./io/projectFile";
|
||||
import { stepTextToImportedMeshes } from "./io/stepImport";
|
||||
@@ -1809,6 +1810,10 @@ export default function App() {
|
||||
// und die Ausführung eines bestätigten DXF/DWG-Imports — gebündelt in
|
||||
// useProjectFileActions(), siehe dort.
|
||||
const {
|
||||
recovery,
|
||||
onRecoverRestore,
|
||||
onRecoverDiscard,
|
||||
onRecoverLater,
|
||||
projectFileInputRef,
|
||||
projectTemplateFileInputRef,
|
||||
lockConflict,
|
||||
@@ -2389,17 +2394,19 @@ export default function App() {
|
||||
runClashCheck(p0)
|
||||
.then((clashes) => {
|
||||
setProject((p) => applyClashMarkers(p, clashes, activeCategoryCode));
|
||||
window.alert(
|
||||
// window.alert ist im Tauri-WKWebView wirkungslos → Toast.
|
||||
notify(
|
||||
clashes.length === 0
|
||||
? t("clash.none")
|
||||
: `${t("clash.found")}: ${clashes.length}\n` +
|
||||
: `${t("clash.found")}: ${clashes.length} — ` +
|
||||
clashes
|
||||
.slice(0, 20)
|
||||
.map((c, k) => `K${k + 1}: ${c.a.kind} ↔ ${c.b.kind}${c.volume !== null ? ` · ${c.volume.toFixed(3)} m³` : ""}`)
|
||||
.join("\n"),
|
||||
.slice(0, 5)
|
||||
.map((c, k) => `K${k + 1} ${c.a.kind}↔${c.b.kind}${c.volume !== null ? ` ${c.volume.toFixed(3)} m³` : ""}`)
|
||||
.join(", "),
|
||||
clashes.length === 0 ? "info" : "warning",
|
||||
);
|
||||
})
|
||||
.catch((err) => window.alert(`${t("clash.failed")}: ${err instanceof Error ? err.message : String(err)}`));
|
||||
.catch((err) => notify(`${t("clash.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"));
|
||||
},
|
||||
onUndo: undo,
|
||||
onRedo: redo,
|
||||
@@ -3194,6 +3201,7 @@ export default function App() {
|
||||
}
|
||||
if (bootPhase === "start") {
|
||||
return (
|
||||
<>
|
||||
<StartScreen
|
||||
onNewProject={() => {
|
||||
onNewProject();
|
||||
@@ -3210,6 +3218,19 @@ export default function App() {
|
||||
setBootPhase("editor");
|
||||
}}
|
||||
/>
|
||||
{recovery && (
|
||||
<RecoverAutosaveDialog
|
||||
path={recovery.path}
|
||||
savedAt={recovery.savedAt}
|
||||
onRestore={() => {
|
||||
onRecoverRestore();
|
||||
setBootPhase("editor");
|
||||
}}
|
||||
onDiscard={onRecoverDiscard}
|
||||
onLater={onRecoverLater}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3248,7 +3269,7 @@ export default function App() {
|
||||
.then((text) => stepTextToImportedMeshes(text, f.name))
|
||||
.then((objs) => addContextObjectsAndFit(objs))
|
||||
.catch((err) =>
|
||||
window.alert(`${t("step.import.failed")}: ${err instanceof Error ? err.message : String(err)}`),
|
||||
notify(`${t("step.import.failed")}: ${err instanceof Error ? err.message : String(err)}`, "error"),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
@@ -3908,6 +3929,15 @@ export default function App() {
|
||||
/>
|
||||
)}
|
||||
|
||||
{recovery && (
|
||||
<RecoverAutosaveDialog
|
||||
path={recovery.path}
|
||||
savedAt={recovery.savedAt}
|
||||
onRestore={onRecoverRestore}
|
||||
onDiscard={onRecoverDiscard}
|
||||
onLater={onRecoverLater}
|
||||
/>
|
||||
)}
|
||||
{lockConflict && (
|
||||
<LockConflictDialog
|
||||
info={lockConflict.info}
|
||||
|
||||
@@ -1750,6 +1750,12 @@ export const de = {
|
||||
"step.import.failed": "STEP-Import fehlgeschlagen",
|
||||
"step.import.done": "STEP importiert: {n} Körper",
|
||||
"menu.native.importStep": "STEP importieren …",
|
||||
"recover.title": "Ungesicherte Arbeit gefunden",
|
||||
"recover.message": "Von „{name}“ gibt es eine automatische Sicherung vom {when}, die nicht gespeichert wurde.",
|
||||
"recover.unsaved": "unbenanntes Projekt",
|
||||
"recover.restore": "Wiederherstellen",
|
||||
"recover.discard": "Verwerfen",
|
||||
"recover.later": "Später",
|
||||
"project.open.failed": "Projekt konnte nicht geöffnet werden.",
|
||||
"menu.native.clashCheck": "Kollisionsprüfung …",
|
||||
"clash.none": "Keine Kollisionen gefunden.",
|
||||
|
||||
@@ -1711,6 +1711,12 @@ export const en: Record<TranslationKey, string> = {
|
||||
"step.import.failed": "STEP import failed",
|
||||
"step.import.done": "STEP imported: {n} solids",
|
||||
"menu.native.importStep": "Import STEP …",
|
||||
"recover.title": "Unsaved work found",
|
||||
"recover.message": "There is an automatic backup of “{name}” from {when} that was never saved.",
|
||||
"recover.unsaved": "untitled project",
|
||||
"recover.restore": "Restore",
|
||||
"recover.discard": "Discard",
|
||||
"recover.later": "Later",
|
||||
"project.open.failed": "Project could not be opened.",
|
||||
"menu.native.clashCheck": "Clash detection …",
|
||||
"clash.none": "No clashes found.",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// Autosave mit Wiederherstellen (lessons-bimcraft [13]): solange das Projekt ungespeicherte
|
||||
// Änderungen hat, landet alle {@link AUTOSAVE_INTERVAL_MS} eine Kopie in IndexedDB
|
||||
// (`projectStore.ts`; unter Tauri liegt sie im App-Datenordner der Webview, im Browser im
|
||||
// Profil). Schlüssel = Dateipfad bzw. „unsaved" für ein noch nie gespeichertes Projekt.
|
||||
//
|
||||
// Lebenszyklus: Speichern oder bewusstes Verwerfen löscht die Kopie. Bleibt sie liegen
|
||||
// (Absturz, Fenster ohne Speichern geschlossen), bietet Dossier sie beim nächsten Start bzw.
|
||||
// beim Öffnen derselben Datei an: Wiederherstellen · Verwerfen · Später.
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import { deleteProject, loadProjectRecord, saveProject } from "./projectStore";
|
||||
|
||||
export const AUTOSAVE_INTERVAL_MS = 30_000;
|
||||
const PREFIX = "autosave:";
|
||||
const UNSAVED = "unsaved";
|
||||
|
||||
/** Schlüssel der Wiederherstellungskopie für eine Datei (oder ein ungespeichertes Projekt). */
|
||||
export const autosaveKey = (path: string | null): string => PREFIX + (path ?? UNSAVED);
|
||||
|
||||
export const writeAutosave = (path: string | null, project: Project): Promise<void> =>
|
||||
saveProject(autosaveKey(path), project);
|
||||
|
||||
export const readAutosave = (path: string | null): Promise<{ project: Project; savedAt: number } | null> =>
|
||||
loadProjectRecord(autosaveKey(path));
|
||||
|
||||
export const clearAutosave = (path: string | null): Promise<void> => deleteProject(autosaveKey(path));
|
||||
|
||||
/** Eine angebotene Wiederherstellung. */
|
||||
export interface AutosaveRecovery {
|
||||
path: string | null;
|
||||
project: Project;
|
||||
savedAt: number;
|
||||
}
|
||||
|
||||
/** Ob ein Projekt überhaupt etwas Sicherungswürdiges enthält (leere Projekte nicht sichern). */
|
||||
export function hasContent(p: Project): boolean {
|
||||
return (
|
||||
p.walls.length > 0 ||
|
||||
p.drawings2d.length > 0 ||
|
||||
(p.openings?.length ?? 0) > 0 ||
|
||||
(p.ceilings?.length ?? 0) > 0 ||
|
||||
(p.roofs?.length ?? 0) > 0 ||
|
||||
(p.stairs?.length ?? 0) > 0 ||
|
||||
(p.rooms?.length ?? 0) > 0 ||
|
||||
(p.columns?.length ?? 0) > 0 ||
|
||||
(p.extrudedSolids?.length ?? 0) > 0 ||
|
||||
(p.context?.length ?? 0) > 0
|
||||
);
|
||||
}
|
||||
@@ -134,6 +134,23 @@ export async function loadProject(name: string): Promise<Project | null> {
|
||||
}
|
||||
}
|
||||
|
||||
/** Wie {@link loadProject}, mit Speicherzeitpunkt (ms seit Epoche). */
|
||||
export async function loadProjectRecord(name: string): Promise<{ project: Project; savedAt: number } | null> {
|
||||
if (!name || !isAvailable()) return null;
|
||||
try {
|
||||
const db = await openDb();
|
||||
const record = await new Promise<ProjectRecord | undefined>((resolve, reject) => {
|
||||
const tx = db.transaction(STORE_NAME, "readonly");
|
||||
const request = tx.objectStore(STORE_NAME).get(name);
|
||||
request.onsuccess = () => resolve(request.result as ProjectRecord | undefined);
|
||||
request.onerror = () => reject(request.error ?? new Error("Lesen fehlgeschlagen"));
|
||||
});
|
||||
return record ? { project: record.project, savedAt: record.savedAt } : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Listet alle gespeicherten Projekte (Name + Speicherzeitpunkt), alphabetisch
|
||||
* nach Name sortiert. Ohne IndexedDB oder bei Fehler: leere Liste.
|
||||
|
||||
@@ -6,7 +6,11 @@
|
||||
//
|
||||
// Extrahiert aus App.tsx. Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import { parseProjectFile, serializeProject } from "../io/projectFormat";
|
||||
import { useStore } from "./appStore";
|
||||
import type { NotifyKind } from "./notifySlice";
|
||||
import { parseProjectFile, parseProjectObject, serializeProject } from "../io/projectFormat";
|
||||
import { AUTOSAVE_INTERVAL_MS, clearAutosave, hasContent, readAutosave, writeAutosave } from "./autosave";
|
||||
import type { AutosaveRecovery } from "./autosave";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { RefObject } from "react";
|
||||
import { t } from "../i18n";
|
||||
@@ -128,10 +132,10 @@ export type ImportDialogState = {
|
||||
* Liest Projekt-Text über den gemeinsamen Format-Parser (Version, Migration, Toleranz) und
|
||||
* meldet Fehler sichtbar statt nur in der Konsole. `null` = nicht ladbar.
|
||||
*/
|
||||
function readProjectOrReport(content: string): Project | null {
|
||||
function readProjectOrReport(content: string, notify: (msg: string, kind?: NotifyKind) => void): Project | null {
|
||||
const r = parseProjectFile(content);
|
||||
if (!r.ok) {
|
||||
window.alert(`${t("project.open.failed")}\n\n${r.error}`);
|
||||
notify(`${t("project.open.failed")} ${r.error}`, "error");
|
||||
return null;
|
||||
}
|
||||
for (const w of r.warnings) console.info(`Projekt geladen mit Hinweis: ${w}`);
|
||||
@@ -155,6 +159,8 @@ export function useProjectFileActions(
|
||||
// über den nativen Dialog (openProjectFileNative), der einen echten Pfad für
|
||||
// den Lock liefert (File-API im Browser hat keinen echten Dateipfad).
|
||||
const projectFileInputRef = useRef<HTMLInputElement>(null);
|
||||
// Meldungen als Toast (window.alert ist im Tauri-WKWebView wirkungslos).
|
||||
const notify = useStore((s) => s.notify);
|
||||
// Verstecktes Datei-Input für „Neu aus Vorlage" (Datei wählen) — derselbe
|
||||
// Browser-Fallback wie `projectFileInputRef`, nur mit `.obpt`-Filter.
|
||||
const projectTemplateFileInputRef = useRef<HTMLInputElement>(null);
|
||||
@@ -187,10 +193,50 @@ export function useProjectFileActions(
|
||||
* kommentarlose Überschreiben (Bug: Cmd+N löschte bisher stillschweigend).
|
||||
*/
|
||||
const guardDiscard = (action: () => void) => {
|
||||
if (project !== lastSavedProjectRef.current) setPendingDiscard(() => action);
|
||||
else action();
|
||||
if (project !== lastSavedProjectRef.current) {
|
||||
// Bewusst verworfen (oder vorher gespeichert) → Wiederherstellungskopie ist hinfällig.
|
||||
const path = openedProjectPathRef.current;
|
||||
setPendingDiscard(() => () => {
|
||||
void clearAutosave(path);
|
||||
action();
|
||||
});
|
||||
} else action();
|
||||
};
|
||||
|
||||
// ── Autosave + Wiederherstellen (s. state/autosave.ts) ─────────────────────
|
||||
const projectRef = useRef(project);
|
||||
projectRef.current = project;
|
||||
const lastAutosavedRef = useRef<Project | null>(null);
|
||||
const [recovery, setRecovery] = useState<AutosaveRecovery | null>(null);
|
||||
useEffect(() => {
|
||||
const id = window.setInterval(() => {
|
||||
const p = projectRef.current;
|
||||
if (p === lastSavedProjectRef.current || p === lastAutosavedRef.current || !hasContent(p)) return;
|
||||
lastAutosavedRef.current = p;
|
||||
void writeAutosave(openedProjectPathRef.current, p);
|
||||
}, AUTOSAVE_INTERVAL_MS);
|
||||
return () => window.clearInterval(id);
|
||||
}, []);
|
||||
const offerRecovery = (path: string | null) => {
|
||||
void readAutosave(path).then((r) => {
|
||||
if (r) setRecovery({ path, project: r.project, savedAt: r.savedAt });
|
||||
});
|
||||
};
|
||||
// Start: Kopie eines nie gespeicherten Projekts aus der letzten Sitzung?
|
||||
useEffect(() => offerRecovery(null), []);
|
||||
const onRecoverRestore = () => {
|
||||
if (!recovery) return;
|
||||
const parsed = parseProjectObject(recovery.project);
|
||||
if (parsed.ok) setProject(parsed.project); // bleibt „ungespeichert" bis zum Speichern
|
||||
else notify(`${t("project.open.failed")} ${parsed.error}`, "error");
|
||||
setRecovery(null);
|
||||
};
|
||||
const onRecoverDiscard = () => {
|
||||
if (recovery) void clearAutosave(recovery.path);
|
||||
setRecovery(null);
|
||||
};
|
||||
const onRecoverLater = () => setRecovery(null);
|
||||
|
||||
// Best-effort Lock-Freigabe beim Fenster-Schliessen (sauberes Timing; der
|
||||
// OS-Lock fällt bei Prozessende/Absturz ohnehin automatisch weg). No-op ohne Tauri.
|
||||
useEffect(() => {
|
||||
@@ -289,7 +335,11 @@ export function useProjectFileActions(
|
||||
return saveProjectFile(json, project.name, (path) =>
|
||||
addRecentProject(path, project.name || "modell"),
|
||||
).then((saved) => {
|
||||
if (saved) lastSavedProjectRef.current = project;
|
||||
if (saved) {
|
||||
lastSavedProjectRef.current = project;
|
||||
void clearAutosave(openedProjectPathRef.current);
|
||||
void clearAutosave(null);
|
||||
}
|
||||
return saved;
|
||||
});
|
||||
};
|
||||
@@ -310,7 +360,7 @@ export function useProjectFileActions(
|
||||
// Ersetzt ebenfalls das bisherige Projekt → über `guardDiscard`.
|
||||
const applyTemplateContent = (content: string): boolean => {
|
||||
try {
|
||||
const parsed = readProjectOrReport(content);
|
||||
const parsed = readProjectOrReport(content, notify);
|
||||
if (!parsed) return false;
|
||||
guardDiscard(() => {
|
||||
releaseCurrentProjectLock();
|
||||
@@ -371,7 +421,7 @@ export function useProjectFileActions(
|
||||
// + ob WIR den Schreib-Lock für die neue Datei halten.
|
||||
const applyOpenedProjectFile = (path: string, content: string, lockOwned: boolean) => {
|
||||
try {
|
||||
const parsed = readProjectOrReport(content);
|
||||
const parsed = readProjectOrReport(content, notify);
|
||||
if (!parsed) {
|
||||
if (lockOwned) void releaseProjectLock(path);
|
||||
return;
|
||||
@@ -383,6 +433,7 @@ export function useProjectFileActions(
|
||||
openedProjectPathRef.current = path;
|
||||
projectLockOwnedRef.current = lockOwned;
|
||||
addRecentProject(path, parsed.name || "modell");
|
||||
offerRecovery(path);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("Projekt-Import fehlgeschlagen:", err);
|
||||
@@ -463,10 +514,10 @@ export function useProjectFileActions(
|
||||
.then((r) => {
|
||||
downloadTextFile(r.text, filename);
|
||||
if (r.skipped.length > 0) {
|
||||
window.alert(t("step.export.skipped", { n: r.skipped.length }));
|
||||
notify(t("step.export.skipped", { n: r.skipped.length }), "warning");
|
||||
}
|
||||
})
|
||||
.catch((e) => window.alert(`${t("step.export.failed")}: ${e instanceof Error ? e.message : String(e)}`));
|
||||
.catch((e) => notify(`${t("step.export.failed")}: ${e instanceof Error ? e.message : String(e)}`, "error"));
|
||||
break;
|
||||
}
|
||||
};
|
||||
@@ -492,7 +543,7 @@ export function useProjectFileActions(
|
||||
const r = new FileReader();
|
||||
r.onload = () => {
|
||||
try {
|
||||
const parsed = readProjectOrReport(String(r.result ?? ""));
|
||||
const parsed = readProjectOrReport(String(r.result ?? ""), notify);
|
||||
if (!parsed) return;
|
||||
// Browser-Pfad hat keinen echten Dateipfad → kein Lock für die neue
|
||||
// Datei, aber ein evtl. vorher (unter Tauri) gehaltener Lock wird frei.
|
||||
@@ -575,6 +626,10 @@ export function useProjectFileActions(
|
||||
projectLockOwnedRef,
|
||||
lockConflict,
|
||||
setLockConflict,
|
||||
recovery,
|
||||
onRecoverRestore,
|
||||
onRecoverDiscard,
|
||||
onRecoverLater,
|
||||
pendingDiscard,
|
||||
setPendingDiscard,
|
||||
openImportForFile,
|
||||
|
||||
@@ -8048,3 +8048,8 @@ body {
|
||||
[data-native-hole] body {
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
/* Wiederherstellen-Dialog: muss auch über dem Startbildschirm (z-index 2000) liegen. */
|
||||
.imp-overlay.recover-overlay {
|
||||
z-index: 2100;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
// Angebot, eine Autosave-Kopie wiederherzustellen (s. state/autosave.ts) — gleiches
|
||||
// Overlay-Muster wie `UnsavedChangesDialog` (kein `window.confirm`, im Tauri-WKWebView
|
||||
// wirkungslos). „Später" lässt die Kopie liegen; sie wird beim nächsten Start erneut angeboten.
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { t } from "../i18n";
|
||||
|
||||
export interface RecoverAutosaveDialogProps {
|
||||
/** Dateipfad der Kopie (null = nie gespeichertes Projekt). */
|
||||
path: string | null;
|
||||
savedAt: number;
|
||||
onRestore: () => void;
|
||||
onDiscard: () => void;
|
||||
onLater: () => void;
|
||||
}
|
||||
|
||||
export function RecoverAutosaveDialog({ path, savedAt, onRestore, onDiscard, onLater }: RecoverAutosaveDialogProps) {
|
||||
useEffect(() => {
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === "Escape") onLater();
|
||||
};
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, [onLater]);
|
||||
|
||||
const when = new Date(savedAt).toLocaleString();
|
||||
const name = path ? path.split(/[\\/]/).pop() : t("recover.unsaved");
|
||||
|
||||
return (
|
||||
<div className="imp-overlay recover-overlay" onClick={onLater}>
|
||||
<div
|
||||
className="imp-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
aria-label={t("recover.title")}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
<header className="imp-head">
|
||||
<span className="imp-head-title">{t("recover.title")}</span>
|
||||
<button className="imp-close" onClick={onLater} aria-label={t("export.close")}>
|
||||
×
|
||||
</button>
|
||||
</header>
|
||||
<div className="imp-body">
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("recover.message", { name: name ?? "", when })}</div>
|
||||
</section>
|
||||
</div>
|
||||
<footer className="imp-foot">
|
||||
<button className="imp-btn" onClick={onLater}>
|
||||
{t("recover.later")}
|
||||
</button>
|
||||
<button className="imp-btn danger" onClick={onDiscard}>
|
||||
{t("recover.discard")}
|
||||
</button>
|
||||
<button className="imp-btn primary" onClick={onRestore}>
|
||||
{t("recover.restore")}
|
||||
</button>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user