mirror of https://github.com/usememos/memos
fix: prevent stale comment drafts from being restored
parent
acbc914dea
commit
e520b637fd
@ -1,25 +1,49 @@
|
|||||||
import { debounce } from "lodash-es";
|
|
||||||
|
|
||||||
export const CACHE_DEBOUNCE_DELAY = 500;
|
export const CACHE_DEBOUNCE_DELAY = 500;
|
||||||
|
|
||||||
|
const pendingSaves = new Map<string, ReturnType<typeof window.setTimeout>>();
|
||||||
|
|
||||||
export const cacheService = {
|
export const cacheService = {
|
||||||
key: (username: string, cacheKey?: string): string => {
|
key: (username: string, cacheKey?: string): string => {
|
||||||
return `${username}-${cacheKey || ""}`;
|
return `${username}-${cacheKey || ""}`;
|
||||||
},
|
},
|
||||||
|
|
||||||
save: debounce((key: string, content: string) => {
|
save: (key: string, content: string) => {
|
||||||
if (content.trim()) {
|
const pendingSave = pendingSaves.get(key);
|
||||||
localStorage.setItem(key, content);
|
if (pendingSave) {
|
||||||
} else {
|
window.clearTimeout(pendingSave);
|
||||||
localStorage.removeItem(key);
|
|
||||||
}
|
}
|
||||||
}, CACHE_DEBOUNCE_DELAY),
|
|
||||||
|
const timeoutId = window.setTimeout(() => {
|
||||||
|
pendingSaves.delete(key);
|
||||||
|
|
||||||
|
if (content.trim()) {
|
||||||
|
localStorage.setItem(key, content);
|
||||||
|
} else {
|
||||||
|
localStorage.removeItem(key);
|
||||||
|
}
|
||||||
|
}, CACHE_DEBOUNCE_DELAY);
|
||||||
|
|
||||||
|
pendingSaves.set(key, timeoutId);
|
||||||
|
},
|
||||||
|
|
||||||
load(key: string): string {
|
load(key: string): string {
|
||||||
return localStorage.getItem(key) || "";
|
return localStorage.getItem(key) || "";
|
||||||
},
|
},
|
||||||
|
|
||||||
clear(key: string): void {
|
clear(key: string): void {
|
||||||
|
const pendingSave = pendingSaves.get(key);
|
||||||
|
if (pendingSave) {
|
||||||
|
window.clearTimeout(pendingSave);
|
||||||
|
pendingSaves.delete(key);
|
||||||
|
}
|
||||||
|
|
||||||
localStorage.removeItem(key);
|
localStorage.removeItem(key);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
clearAll(): void {
|
||||||
|
for (const timeoutId of pendingSaves.values()) {
|
||||||
|
window.clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
pendingSaves.clear();
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
Loading…
Reference in New Issue