Skip to content

Commit 28d0099

Browse files
committed
Warn when closing tab if there is an unsaved, non-empty draft
Copy the `useUnsavedChanges` hook from the h repository and use it in AnnotationEditor to enable a warning if the user tries to close the tab while there is a non-empty draft. In the process, fix a bug where `returnValue` was set to an empty string when according to MDN, it must be set to a truthy value. Without this change, the hook works in Chrome but not Firefox. This change works in Chrome and Firefox, but not Safari. In Safari, the tab closes even when the `beforeunload` handler is active. Part of hypothesis/support#59.
1 parent 069eba5 commit 28d0099

File tree

4 files changed

+142
-0
lines changed

4 files changed

+142
-0
lines changed

src/sidebar/components/Annotation/AnnotationEditor.tsx

+7
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import { useSidebarStore } from '../../store';
2828
import type { Draft } from '../../store/modules/drafts';
2929
import MarkdownEditor from '../MarkdownEditor';
3030
import TagEditor from '../TagEditor';
31+
import { useUnsavedChanges } from '../hooks/unsaved-changes';
3132
import AnnotationLicense from './AnnotationLicense';
3233
import AnnotationPublishControl from './AnnotationPublishControl';
3334

@@ -75,6 +76,12 @@ function AnnotationEditor({
7576
const text = draft.text;
7677
const isEmpty = !text && !tags.length;
7778

79+
// Warn user if they try to close the tab while there is an open, non-empty
80+
// draft.
81+
//
82+
// WARNING: This does not work in all browsers. See hook docs for details.
83+
useUnsavedChanges(!isEmpty);
84+
7885
const onEditTags = useCallback(
7986
(tags: string[]) => {
8087
store.createDraft(draft.annotation, { ...draft, tags });

src/sidebar/components/Annotation/test/AnnotationEditor-test.js

+19
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ describe('AnnotationEditor', () => {
1818
let fakeSettings;
1919
let fakeToastMessenger;
2020
let fakeGroupsService;
21+
let fakeUseUnsavedChanges;
2122

2223
let fakeStore;
2324

@@ -74,8 +75,13 @@ describe('AnnotationEditor', () => {
7475
defaultAuthority: sinon.stub().returns(''),
7576
};
7677

78+
fakeUseUnsavedChanges = sinon.stub();
79+
7780
$imports.$mock(mockImportedComponents());
7881
$imports.$mock({
82+
'../hooks/unsaved-changes': {
83+
useUnsavedChanges: fakeUseUnsavedChanges,
84+
},
7985
'../../store': { useSidebarStore: () => fakeStore },
8086
'../../helpers/theme': { applyTheme: fakeApplyTheme },
8187
});
@@ -279,6 +285,19 @@ describe('AnnotationEditor', () => {
279285
assert.notCalled(fakeAnnotationsService.save);
280286
});
281287

288+
it('warns if user closes tab while there is a non-empty draft', () => {
289+
// If the draft is empty, the warning is disabled.
290+
const wrapper = createComponent();
291+
assert.calledWith(fakeUseUnsavedChanges, false);
292+
293+
// If the draft changes to non-empty, the warning is enabled.
294+
fakeUseUnsavedChanges.resetHistory();
295+
const draft = fixtures.defaultDraft();
296+
draft.text = 'something is here';
297+
wrapper.setProps({ draft });
298+
assert.calledWith(fakeUseUnsavedChanges, true);
299+
});
300+
282301
describe('handling publish options', () => {
283302
it('sets the publish control to disabled if the annotation is empty', () => {
284303
// default draft has no tags or text
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
import { mount } from '@hypothesis/frontend-testing';
2+
3+
import { useUnsavedChanges, hasUnsavedChanges } from '../unsaved-changes';
4+
5+
function TestUseUnsavedChanges({ unsaved, fakeWindow }) {
6+
useUnsavedChanges(unsaved, fakeWindow);
7+
return <div />;
8+
}
9+
10+
describe('useUnsavedChanges', () => {
11+
let fakeWindow;
12+
13+
function dispatchBeforeUnload() {
14+
const event = new Event('beforeunload', { cancelable: true });
15+
fakeWindow.dispatchEvent(event);
16+
return event;
17+
}
18+
19+
function createWidget(unsaved) {
20+
return mount(
21+
<TestUseUnsavedChanges fakeWindow={fakeWindow} unsaved={unsaved} />,
22+
);
23+
}
24+
25+
beforeEach(() => {
26+
// Use a dummy window to avoid triggering any handlers that respond to
27+
// "beforeunload" on the real window.
28+
fakeWindow = new EventTarget();
29+
});
30+
31+
it('does not increment unsaved-changes count if argument is false', () => {
32+
createWidget(false);
33+
assert.isFalse(hasUnsavedChanges());
34+
});
35+
36+
it('does not register "beforeunload" handler if argument is false', () => {
37+
createWidget(false);
38+
const event = dispatchBeforeUnload();
39+
assert.isFalse(event.defaultPrevented);
40+
});
41+
42+
it('increments unsaved-changes count if argument is true', () => {
43+
const wrapper = createWidget(true);
44+
assert.isTrue(hasUnsavedChanges());
45+
wrapper.unmount();
46+
assert.isFalse(hasUnsavedChanges());
47+
});
48+
49+
it('registers "beforeunload" handler if argument is true', () => {
50+
const wrapper = createWidget(true);
51+
const event = dispatchBeforeUnload();
52+
assert.isTrue(event.defaultPrevented);
53+
54+
// We don't test `event.returnValue` here because it returns `false` after
55+
// assignment in Chrome, even though the handler assigns it `true`.
56+
57+
// Unmount the widget, this should remove the handler.
58+
wrapper.unmount();
59+
const event2 = dispatchBeforeUnload();
60+
assert.isFalse(event2.defaultPrevented);
61+
});
62+
});
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import { useEffect } from 'preact/hooks';
2+
3+
/** Count of components with unsaved changes. */
4+
let unsavedCount = 0;
5+
6+
function preventUnload(e: BeforeUnloadEvent) {
7+
// `preventDefault` is the modern API for preventing unload.
8+
e.preventDefault();
9+
10+
// Setting `returnValue` to a truthy value is a legacy method needed for
11+
// Firefox. Note that in Chrome, reading `returnValue` will return false
12+
// afterwards.
13+
e.returnValue = true;
14+
}
15+
16+
/**
17+
* Return true if any active components have indicated they have unsaved changes
18+
* using {@link useUnsavedChanges}.
19+
*/
20+
export function hasUnsavedChanges() {
21+
return unsavedCount > 0;
22+
}
23+
24+
/**
25+
* Hook that registers the current component as having unsaved changes that
26+
* would be lost in the event of a navigation.
27+
*
28+
* WARNING: As of May 2025, this works in Chrome and Firefox, but not Safari.
29+
* See https://github.com/hypothesis/support/issues/59#issuecomment-2886335334.
30+
*
31+
* @param hasUnsavedChanges - True if current component has unsaved changes
32+
* @param window_ - Test seam
33+
*/
34+
export function useUnsavedChanges(
35+
hasUnsavedChanges: boolean,
36+
window_ = window,
37+
) {
38+
useEffect(() => {
39+
if (!hasUnsavedChanges) {
40+
return () => {};
41+
}
42+
43+
unsavedCount += 1;
44+
if (unsavedCount === 1) {
45+
window_.addEventListener('beforeunload', preventUnload);
46+
}
47+
return () => {
48+
unsavedCount -= 1;
49+
if (unsavedCount === 0) {
50+
window_.removeEventListener('beforeunload', preventUnload);
51+
}
52+
};
53+
}, [hasUnsavedChanges, window_]);
54+
}

0 commit comments

Comments
 (0)