chore(react/type_widgets): save on window closing

This commit is contained in:
Elian Doran
2025-10-05 18:06:48 +03:00
parent 0dcaa8719f
commit 6ffe8a2eb5
4 changed files with 15 additions and 23 deletions

View File

@@ -668,6 +668,10 @@ export class AppContext extends Component {
this.beforeUnloadListeners.push(obj);
}
}
removeBeforeUnloadListener(listener: (() => boolean)) {
this.beforeUnloadListeners = this.beforeUnloadListeners.filter(l => l === listener);
}
}
const appContext = new AppContext(window.glob.isMainWindow);

View File

@@ -1,20 +0,0 @@
export default class NoteDetailWidget extends NoteContextAwareWidget {
private typeWidgets: Record<string, TypeWidget>;
private spacedUpdate: SpacedUpdate;
private type?: ExtendedNoteType;
private mime?: string;
constructor() {
super();
this.typeWidgets = {};
appContext.addBeforeUnloadListener(this);
}
beforeUnloadEvent() {
return this.spacedUpdate.isAllSavedAndTriggerUpdate();
}
}

View File

@@ -47,7 +47,9 @@ export default function NoteTitleWidget() {
// Prevent user from navigating away if the spaced update is not done.
useEffect(() => {
appContext.addBeforeUnloadListener(() => spacedUpdate.isAllSavedAndTriggerUpdate());
const listener = () => spacedUpdate.isAllSavedAndTriggerUpdate();
appContext.addBeforeUnloadListener(listener);
return () => appContext.removeBeforeUnloadListener(listener);
}, []);
useTriliumEvents([ "beforeNoteSwitch", "beforeNoteContextRemove" ], () => spacedUpdate.updateNowIfNecessary());

View File

@@ -1,5 +1,5 @@
import { MutableRef, useCallback, useContext, useDebugValue, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import { EventData, EventNames } from "../../components/app_context";
import appContext, { EventData, EventNames } from "../../components/app_context";
import { ParentComponent, refToJQuerySelector } from "./react_utils";
import SpacedUpdate from "../../services/spaced_update";
import { FilterLabelsByType, KeyboardActionNames, OptionNames, RelationNames } from "@triliumnext/commons";
@@ -23,7 +23,6 @@ import protected_session_holder from "../../services/protected_session_holder";
import server from "../../services/server";
import { removeIndividualBinding } from "../../services/shortcuts";
import { ViewScope } from "../../services/link";
import { VirtualConsolePrinter } from "happy-dom";
export function useTriliumEvent<T extends EventNames>(eventName: T, handler: (data: EventData<T>) => void) {
const parentComponent = useContext(ParentComponent);
@@ -128,6 +127,13 @@ export function useEditorSpacedUpdate({ note, noteContext, getData, onContentCha
await spacedUpdate.updateNowIfNecessary();
})
// Save if needed upon window/browser closing.
useEffect(() => {
const listener = () => spacedUpdate.isAllSavedAndTriggerUpdate();
appContext.addBeforeUnloadListener(listener);
return () => appContext.removeBeforeUnloadListener(listener);
}, []);
return spacedUpdate;
}