mirror of https://github.com/usememos/memos
fix: preserve draft content when tab is suspended or editor remounts
Gate auto-save on initialization to prevent empty content from overwriting cached drafts on remount. Flush drafts synchronously on visibilitychange/ pagehide so Chromium tab suspension cannot drop pending debounced saves. Restore cached draft over saved memo content when they differ (inline editing).pull/5762/head^2
parent
938c405b0f
commit
9ca71229a6
@ -1,9 +1,42 @@
|
||||
import { useEffect } from "react";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { cacheService } from "../services";
|
||||
|
||||
export const useAutoSave = (content: string, username: string, cacheKey: string | undefined) => {
|
||||
export const useAutoSave = (content: string, username: string, cacheKey: string | undefined, enabled = true) => {
|
||||
const latestContentRef = useRef(content);
|
||||
|
||||
useEffect(() => {
|
||||
latestContentRef.current = content;
|
||||
}, [content]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
const key = cacheService.key(username, cacheKey);
|
||||
cacheService.save(key, content);
|
||||
}, [content, username, cacheKey]);
|
||||
}, [content, username, cacheKey, enabled]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return;
|
||||
|
||||
const key = cacheService.key(username, cacheKey);
|
||||
const flushDraft = () => {
|
||||
cacheService.saveNow(key, latestContentRef.current);
|
||||
};
|
||||
const handleVisibilityChange = () => {
|
||||
if (document.visibilityState === "hidden") {
|
||||
flushDraft();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("pagehide", flushDraft);
|
||||
document.addEventListener("visibilitychange", handleVisibilityChange);
|
||||
|
||||
return () => {
|
||||
// Flush on unmount (e.g. editor closes) to ensure the draft is persisted
|
||||
// before the component is torn down — distinct from the visibility flush above.
|
||||
flushDraft();
|
||||
window.removeEventListener("pagehide", flushDraft);
|
||||
document.removeEventListener("visibilitychange", handleVisibilityChange);
|
||||
};
|
||||
}, [username, cacheKey, enabled]);
|
||||
};
|
||||
|
||||
Loading…
Reference in New Issue