From d44c4ca2d80867c7b1a3a2280da0b69e8a0e0caf Mon Sep 17 00:00:00 2001 From: David Luzar Date: Mon, 20 Jan 2020 18:37:42 +0100 Subject: [PATCH] flush autosave on unload (#473) --- src/index.tsx | 7 +++++++ src/utils.ts | 9 ++++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/index.tsx b/src/index.tsx index 1bf313c3..4fbd3565 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -211,6 +211,11 @@ export class App extends React.Component<{}, AppState> { e.preventDefault(); }; + private onUnload = () => { + this.saveDebounced(); + this.saveDebounced.flush(); + }; + public async componentDidMount() { document.addEventListener("copy", this.onCopy); document.addEventListener("paste", this.onPaste); @@ -219,6 +224,7 @@ export class App extends React.Component<{}, AppState> { document.addEventListener("keydown", this.onKeyDown, false); document.addEventListener("mousemove", this.getCurrentCursorPosition); window.addEventListener("resize", this.onResize, false); + window.addEventListener("unload", this.onUnload, false); let data; const searchParams = new URLSearchParams(window.location.search); @@ -253,6 +259,7 @@ export class App extends React.Component<{}, AppState> { false ); window.removeEventListener("resize", this.onResize, false); + window.removeEventListener("unload", this.onUnload, false); } public state: AppState = getDefaultAppState(); diff --git a/src/utils.ts b/src/utils.ts index 29b072d1..9085f3c2 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -57,10 +57,17 @@ export function debounce( timeout: number ) { let handle = 0; - return (...args: T) => { + let lastArgs: T; + const ret = (...args: T) => { + lastArgs = args; clearTimeout(handle); handle = window.setTimeout(() => fn(...args), timeout); }; + ret.flush = () => { + clearTimeout(handle); + fn(...lastArgs); + }; + return ret; } export function selectNode(node: Element) {