Skip to content

Warn when closing tab if there is an unsaved, non-empty draft #7083

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions src/sidebar/components/Annotation/AnnotationEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { useSidebarStore } from '../../store';
import type { Draft } from '../../store/modules/drafts';
import MarkdownEditor from '../MarkdownEditor';
import TagEditor from '../TagEditor';
import { useUnsavedChanges } from '../hooks/unsaved-changes';
import AnnotationLicense from './AnnotationLicense';
import AnnotationPublishControl from './AnnotationPublishControl';

Expand Down Expand Up @@ -75,6 +76,12 @@ function AnnotationEditor({
const text = draft.text;
const isEmpty = !text && !tags.length;

// Warn user if they try to close the tab while there is an open, non-empty
// draft.
//
// WARNING: This does not work in all browsers. See hook docs for details.
useUnsavedChanges(!isEmpty);

const onEditTags = useCallback(
(tags: string[]) => {
store.createDraft(draft.annotation, { ...draft, tags });
Expand Down
19 changes: 19 additions & 0 deletions src/sidebar/components/Annotation/test/AnnotationEditor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ describe('AnnotationEditor', () => {
let fakeSettings;
let fakeToastMessenger;
let fakeGroupsService;
let fakeUseUnsavedChanges;

let fakeStore;

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

fakeUseUnsavedChanges = sinon.stub();

$imports.$mock(mockImportedComponents());
$imports.$mock({
'../hooks/unsaved-changes': {
useUnsavedChanges: fakeUseUnsavedChanges,
},
'../../store': { useSidebarStore: () => fakeStore },
'../../helpers/theme': { applyTheme: fakeApplyTheme },
});
Expand Down Expand Up @@ -279,6 +285,19 @@ describe('AnnotationEditor', () => {
assert.notCalled(fakeAnnotationsService.save);
});

it('warns if user closes tab while there is a non-empty draft', () => {
// If the draft is empty, the warning is disabled.
const wrapper = createComponent();
assert.calledWith(fakeUseUnsavedChanges, false);

// If the draft changes to non-empty, the warning is enabled.
fakeUseUnsavedChanges.resetHistory();
const draft = fixtures.defaultDraft();
draft.text = 'something is here';
wrapper.setProps({ draft });
assert.calledWith(fakeUseUnsavedChanges, true);
});

describe('handling publish options', () => {
it('sets the publish control to disabled if the annotation is empty', () => {
// default draft has no tags or text
Expand Down
62 changes: 62 additions & 0 deletions src/sidebar/components/hooks/test/unsaved-changes-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { mount } from '@hypothesis/frontend-testing';

import { useUnsavedChanges, hasUnsavedChanges } from '../unsaved-changes';

function TestUseUnsavedChanges({ unsaved, fakeWindow }) {
useUnsavedChanges(unsaved, fakeWindow);
return <div />;
}

describe('useUnsavedChanges', () => {
let fakeWindow;

function dispatchBeforeUnload() {
const event = new Event('beforeunload', { cancelable: true });
fakeWindow.dispatchEvent(event);
return event;
}

function createWidget(unsaved) {
return mount(
<TestUseUnsavedChanges fakeWindow={fakeWindow} unsaved={unsaved} />,
);
}

beforeEach(() => {
// Use a dummy window to avoid triggering any handlers that respond to
// "beforeunload" on the real window.
fakeWindow = new EventTarget();
});

it('does not increment unsaved-changes count if argument is false', () => {
createWidget(false);
assert.isFalse(hasUnsavedChanges());
});

it('does not register "beforeunload" handler if argument is false', () => {
createWidget(false);
const event = dispatchBeforeUnload();
assert.isFalse(event.defaultPrevented);
});

it('increments unsaved-changes count if argument is true', () => {
const wrapper = createWidget(true);
assert.isTrue(hasUnsavedChanges());
wrapper.unmount();
assert.isFalse(hasUnsavedChanges());
});

it('registers "beforeunload" handler if argument is true', () => {
const wrapper = createWidget(true);
const event = dispatchBeforeUnload();
assert.isTrue(event.defaultPrevented);

// We don't test `event.returnValue` here because it returns `false` after
// assignment in Chrome, even though the handler assigns it `true`.

// Unmount the widget, this should remove the handler.
wrapper.unmount();
const event2 = dispatchBeforeUnload();
assert.isFalse(event2.defaultPrevented);
});
});
55 changes: 55 additions & 0 deletions src/sidebar/components/hooks/unsaved-changes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { useEffect } from 'preact/hooks';
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Next week I will look at upstreaming this into the frontend-shared library.


/** Count of components with unsaved changes. */
let unsavedCount = 0;

function preventUnload(e: BeforeUnloadEvent) {
// `preventDefault` is the modern API for preventing unload.
e.preventDefault();

// Setting `returnValue` to a truthy value is a legacy method needed for
// Firefox. Note that in Chrome, reading `returnValue` will return false
// afterwards.
e.returnValue = true;
}

/**
* Return true if any active components have indicated they have unsaved changes
* using {@link useUnsavedChanges}.
*/
export function hasUnsavedChanges() {
return unsavedCount > 0;
}

/**
* Hook that registers the current component as having unsaved changes that
* would be lost in the event of a navigation.
*
* WARNING: As of May 2025, this works in Chrome and Firefox, but not Safari.
* See https://github.com/hypothesis/support/issues/59#issuecomment-2886335334.
*
* @param hasUnsavedChanges - True if current component has unsaved changes
* @param window_ - Test seam
*/
export function useUnsavedChanges(
hasUnsavedChanges: boolean,
/* istanbul ignore next - test seam */
window_ = window,
) {
useEffect(() => {
if (!hasUnsavedChanges) {
return () => {};
}

unsavedCount += 1;
if (unsavedCount === 1) {
window_.addEventListener('beforeunload', preventUnload);
}
return () => {
unsavedCount -= 1;
if (unsavedCount === 0) {
window_.removeEventListener('beforeunload', preventUnload);
}
};
}, [hasUnsavedChanges, window_]);
}