mirror of
https://github.com/inventree/InvenTree.git
synced 2026-11-18 14:07:41 +00:00
[UI] Warn before closing the template editor with unsaved changes (#13280)
* Warn before closing the template editor with unsaved changes - Allow DetailDrawer close actions to be intercepted (onBeforeClose) - Track the saved template code in the TemplateEditor - Ask for confirmation before discarding unsaved changes (drawer close / page unload) Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Treat a failed unsaved-changes check as unsaved - Ask for confirmation if the editor code cannot be read - Reject the plugin preview update if no handler is registered, so the template is not assumed to be saved Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Do not treat unavailable editor code as saved An editor which is still initializing (e.g. a plugin editor) returns no code yet. Fall back to the code which was last handed to the editor, and ask for confirmation if the editor content is unknown. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Only mark the template as saved when the preview returns a promise A preview handler which returns synchronously does not report whether the template was actually stored, so keep the editor marked as unsaved. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
129cfe7383
commit
1f51dfe64b
6 files changed
+222
-27
No files matched your search
@@ -16,6 +16,7 @@ import * as classes from './DetailDrawer.css';
|
||||
* @param position - drawer position
|
||||
* @param renderContent - function used to render the drawer content
|
||||
* @param urlPrefix - set an additional url segment, useful when multiple drawers are rendered on one page (e.g. "user/")
|
||||
* @param onBeforeClose - optional callback to intercept closing of the drawer (e.g. to confirm unsaved changes). Call the provided "close" function to actually close the drawer.
|
||||
*/
|
||||
export interface DrawerProps {
|
||||
title: string;
|
||||
@@ -24,6 +25,7 @@ export interface DrawerProps {
|
||||
urlPrefix?: string;
|
||||
size?: UiSizeType;
|
||||
closeOnEscape?: boolean;
|
||||
onBeforeClose?: (close: () => void) => void;
|
||||
}
|
||||
|
||||
export function DetailDrawerComponent({
|
||||
@@ -31,7 +33,8 @@ export function DetailDrawerComponent({
|
||||
position = 'right',
|
||||
size,
|
||||
closeOnEscape = true,
|
||||
renderContent
|
||||
renderContent,
|
||||
onBeforeClose
|
||||
}: Readonly<DrawerProps>) {
|
||||
const navigate = useNavigate();
|
||||
const { id } = useParams();
|
||||
@@ -43,13 +46,27 @@ export function DetailDrawerComponent({
|
||||
useShallow((state) => [state.detailDrawerStack, state.addDetailDrawer])
|
||||
);
|
||||
|
||||
// Run a "close" action, optionally allowing the owner of the drawer to intercept it
|
||||
const guardedClose = useCallback(
|
||||
(close: () => void) => {
|
||||
if (onBeforeClose) {
|
||||
onBeforeClose(close);
|
||||
} else {
|
||||
close();
|
||||
}
|
||||
},
|
||||
[onBeforeClose]
|
||||
);
|
||||
|
||||
return (
|
||||
<Drawer
|
||||
opened={opened}
|
||||
onClose={() => {
|
||||
navigate('../');
|
||||
addDetailDrawer(false);
|
||||
}}
|
||||
onClose={() =>
|
||||
guardedClose(() => {
|
||||
navigate('../');
|
||||
addDetailDrawer(false);
|
||||
})
|
||||
}
|
||||
position={position}
|
||||
closeOnEscape={closeOnEscape}
|
||||
size={size}
|
||||
@@ -60,10 +77,12 @@ export function DetailDrawerComponent({
|
||||
{detailDrawerStack > 0 && (
|
||||
<ActionIcon
|
||||
variant='outline'
|
||||
onClick={() => {
|
||||
navigate(-1);
|
||||
addDetailDrawer(-1);
|
||||
}}
|
||||
onClick={() =>
|
||||
guardedClose(() => {
|
||||
navigate(-1);
|
||||
addDetailDrawer(-1);
|
||||
})
|
||||
}
|
||||
>
|
||||
<IconChevronLeft />
|
||||
</ActionIcon>
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
Stack,
|
||||
Tabs
|
||||
} from '@mantine/core';
|
||||
import { useWindowEvent } from '@mantine/hooks';
|
||||
import { openConfirmModal } from '@mantine/modals';
|
||||
import {
|
||||
hideNotification,
|
||||
@@ -85,15 +86,78 @@ export type TemplateEditorProps = {
|
||||
template: TemplateI;
|
||||
// Name of the file field on the template model (e.g. 'template' or 'snippet')
|
||||
fileField?: string;
|
||||
// Populated by the editor with a function to check for unsaved changes
|
||||
unsavedChangesRef?: UnsavedChangesRef;
|
||||
};
|
||||
|
||||
export type UnsavedChangesRef = React.MutableRefObject<
|
||||
(() => Promise<boolean>) | null
|
||||
>;
|
||||
|
||||
// Compare template code, ignoring differences in line endings
|
||||
function codeDiffers(a: string, b: string): boolean {
|
||||
return a.replace(/\r\n/g, '\n') !== b.replace(/\r\n/g, '\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Guard a drawer which contains a TemplateEditor against accidental closing.
|
||||
*
|
||||
* - Pass "unsavedChangesRef" to the TemplateEditor component
|
||||
* - Pass "onBeforeClose" to the DetailDrawer component
|
||||
*/
|
||||
export function useTemplateEditorCloseGuard() {
|
||||
const unsavedChangesRef: UnsavedChangesRef = useRef(null);
|
||||
|
||||
const onBeforeClose = useCallback((close: () => void) => {
|
||||
const check = unsavedChangesRef.current;
|
||||
|
||||
if (!check) {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
check()
|
||||
.then((unsaved) => {
|
||||
if (!unsaved) {
|
||||
close();
|
||||
return;
|
||||
}
|
||||
|
||||
openConfirmModal({
|
||||
title: t`Unsaved Changes`,
|
||||
children: (
|
||||
<Alert
|
||||
color='yellow'
|
||||
icon={<IconAlertTriangle />}
|
||||
title={t`The template has unsaved changes`}
|
||||
>
|
||||
{t`If you close the editor now, your changes will be lost. Do you want to proceed?`}
|
||||
</Alert>
|
||||
),
|
||||
labels: {
|
||||
confirm: t`Discard Changes`,
|
||||
cancel: t`Keep Editing`
|
||||
},
|
||||
confirmProps: {
|
||||
color: 'red'
|
||||
},
|
||||
onConfirm: close
|
||||
});
|
||||
})
|
||||
.catch(() => close());
|
||||
}, []);
|
||||
|
||||
return { unsavedChangesRef, onBeforeClose };
|
||||
}
|
||||
|
||||
export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
||||
const {
|
||||
templateUrl,
|
||||
editors,
|
||||
previewAreas,
|
||||
template,
|
||||
fileField = 'template'
|
||||
fileField = 'template',
|
||||
unsavedChangesRef
|
||||
} = props;
|
||||
const editorRef = useRef<EditorRef | null>(null);
|
||||
const previewRef = useRef<PreviewAreaRef | null>(null);
|
||||
@@ -115,6 +179,62 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
||||
|
||||
const codeRef = useRef<string | undefined>(undefined);
|
||||
|
||||
// The template code as it is currently stored on the server
|
||||
const savedCodeRef = useRef<string | undefined>(undefined);
|
||||
|
||||
// Check if the code in the editor differs from the code stored on the server
|
||||
const hasUnsavedChanges = useCallback(async () => {
|
||||
if (savedCodeRef.current === undefined) return false;
|
||||
|
||||
try {
|
||||
// An editor which is still initializing (e.g. a plugin editor) cannot provide its code yet:
|
||||
// fall back to the code which was last handed to the editor
|
||||
const code =
|
||||
(await Promise.resolve(editorRef.current?.getCode())) ??
|
||||
codeRef.current;
|
||||
|
||||
// The editor content is unknown: err on the side of asking for confirmation
|
||||
if (code === undefined) return true;
|
||||
|
||||
return codeDiffers(code, savedCodeRef.current);
|
||||
} catch {
|
||||
// The editor state is unknown: err on the side of asking for confirmation
|
||||
return true;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Expose the check to the parent component (e.g. to guard closing of a drawer)
|
||||
useEffect(() => {
|
||||
if (!unsavedChangesRef) return;
|
||||
|
||||
unsavedChangesRef.current = hasUnsavedChanges;
|
||||
|
||||
return () => {
|
||||
unsavedChangesRef.current = null;
|
||||
};
|
||||
}, [unsavedChangesRef, hasUnsavedChanges]);
|
||||
|
||||
// Warn before the page is closed or reloaded with unsaved changes
|
||||
// Note: this must be synchronous, so editors which provide their code asynchronously are not covered
|
||||
useWindowEvent('beforeunload', (event) => {
|
||||
let code: unknown;
|
||||
|
||||
try {
|
||||
code = editorRef.current?.getCode();
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
typeof code === 'string' &&
|
||||
savedCodeRef.current !== undefined &&
|
||||
codeDiffers(code, savedCodeRef.current)
|
||||
) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
});
|
||||
|
||||
const loadCodeToEditor = useCallback(async (code: string) => {
|
||||
try {
|
||||
return await Promise.resolve(editorRef.current?.setCode(code));
|
||||
@@ -158,6 +278,8 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
||||
})
|
||||
.then((res) => {
|
||||
codeRef.current = res.data;
|
||||
savedCodeRef.current =
|
||||
typeof res.data === 'string' ? res.data : undefined;
|
||||
loadCodeToEditor(res.data);
|
||||
})
|
||||
.catch(() => {
|
||||
@@ -215,15 +337,24 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
||||
if (code === undefined || !previewItem) return;
|
||||
|
||||
setIsPreviewLoading(true);
|
||||
Promise.resolve(
|
||||
previewRef.current?.updatePreview(
|
||||
code,
|
||||
previewItem,
|
||||
saveTemplate,
|
||||
props
|
||||
)
|
||||
)
|
||||
|
||||
const result = previewRef.current?.updatePreview(
|
||||
code,
|
||||
previewItem,
|
||||
saveTemplate,
|
||||
props
|
||||
);
|
||||
|
||||
// Only a returned promise reports whether the template was actually stored
|
||||
const isConfirmed = typeof (result as any)?.then === 'function';
|
||||
|
||||
Promise.resolve(result)
|
||||
.then(() => {
|
||||
if (saveTemplate && isConfirmed) {
|
||||
// The preview area has stored the template on the server
|
||||
savedCodeRef.current = code;
|
||||
}
|
||||
|
||||
setRenderingErrors(null);
|
||||
|
||||
notifications.hide('template-preview');
|
||||
@@ -274,6 +405,7 @@ export function TemplateEditor(props: Readonly<TemplateEditorProps>) {
|
||||
api
|
||||
.patch(templateUrl, formData)
|
||||
.then(() => {
|
||||
savedCodeRef.current = code;
|
||||
hideNotification('template-save');
|
||||
showNotification({
|
||||
id: 'template-save',
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
export { TemplateEditor } from './TemplateEditor';
|
||||
export {
|
||||
TemplateEditor,
|
||||
useTemplateEditorCloseGuard
|
||||
} from './TemplateEditor';
|
||||
export { CodeEditor } from './CodeEditor';
|
||||
export { PdfPreview } from './PdfPreview';
|
||||
@@ -143,7 +143,19 @@ export const getPluginTemplatePreview = (
|
||||
);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
updatePreview: (...args) => updatePreviewRef.current?.(...args)
|
||||
updatePreview: (...args) => {
|
||||
const updatePreview = updatePreviewRef.current;
|
||||
|
||||
if (!updatePreview) {
|
||||
// The plugin has not registered its handler (yet):
|
||||
// fail, so that the editor does not assume the template was saved
|
||||
return Promise.reject(
|
||||
new Error(t`The template preview is not ready yet.`)
|
||||
);
|
||||
}
|
||||
|
||||
return updatePreview(...args);
|
||||
}
|
||||
}));
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -25,8 +25,10 @@ import { type ReactNode, useCallback, useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
CodeEditor,
|
||||
TemplateEditor
|
||||
TemplateEditor,
|
||||
useTemplateEditorCloseGuard
|
||||
} from '../../components/editors/TemplateEditor';
|
||||
import type { UnsavedChangesRef } from '../../components/editors/TemplateEditor/TemplateEditor';
|
||||
import { AttachmentLink } from '../../components/items/AttachmentLink';
|
||||
import { DescriptionColumn } from '../../components/tables/ColumnRenderers';
|
||||
import { InvenTreeTable } from '../../components/tables/InvenTreeTable';
|
||||
@@ -47,9 +49,11 @@ export type SnippetI = {
|
||||
};
|
||||
|
||||
export function SnippetDrawer({
|
||||
id
|
||||
id,
|
||||
unsavedChangesRef
|
||||
}: Readonly<{
|
||||
id: string | number;
|
||||
unsavedChangesRef?: UnsavedChangesRef;
|
||||
}>) {
|
||||
const {
|
||||
instance: snippet,
|
||||
@@ -90,6 +94,7 @@ export function SnippetDrawer({
|
||||
fileField='snippet'
|
||||
editors={[CodeEditor]}
|
||||
previewAreas={[]}
|
||||
unsavedChangesRef={unsavedChangesRef}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
@@ -98,6 +103,9 @@ export function SnippetDrawer({
|
||||
export default function SnippetTable() {
|
||||
const table = useTable('report-snippet');
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Warn the user before closing the editor with unsaved changes
|
||||
const closeGuard = useTemplateEditorCloseGuard();
|
||||
const user = useUserState();
|
||||
|
||||
const openDetailDrawer = useCallback((pk: number) => navigate(`${pk}/`), []);
|
||||
@@ -215,8 +223,14 @@ export default function SnippetTable() {
|
||||
title={t`Edit Snippet`}
|
||||
size={'90%'}
|
||||
closeOnEscape={false}
|
||||
onBeforeClose={closeGuard.onBeforeClose}
|
||||
renderContent={(id) => {
|
||||
return <SnippetDrawer id={id ?? ''} />;
|
||||
return (
|
||||
<SnippetDrawer
|
||||
id={id ?? ''}
|
||||
unsavedChangesRef={closeGuard.unsavedChangesRef}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<Alert icon={<IconInfoCircle />} title={t`Snippets`}>
|
||||
|
||||
@@ -23,11 +23,13 @@ import type { TableColumn, TableColumnFilterType } from '@lib/types/Tables';
|
||||
import {
|
||||
CodeEditor,
|
||||
PdfPreview,
|
||||
TemplateEditor
|
||||
TemplateEditor,
|
||||
useTemplateEditorCloseGuard
|
||||
} from '../../components/editors/TemplateEditor';
|
||||
import type {
|
||||
Editor,
|
||||
PreviewArea
|
||||
PreviewArea,
|
||||
UnsavedChangesRef
|
||||
} from '../../components/editors/TemplateEditor/TemplateEditor';
|
||||
import { ApiIcon } from '../../components/items/ApiIcon';
|
||||
import { AttachmentLink } from '../../components/items/AttachmentLink';
|
||||
@@ -87,10 +89,12 @@ export interface TemplateProps {
|
||||
|
||||
export function TemplateDrawer({
|
||||
id,
|
||||
templateProps
|
||||
templateProps,
|
||||
unsavedChangesRef
|
||||
}: Readonly<{
|
||||
id: string | number;
|
||||
templateProps: TemplateProps;
|
||||
unsavedChangesRef?: UnsavedChangesRef;
|
||||
}>) {
|
||||
const { modelType, templateEndpoint, printingEndpoint } = templateProps;
|
||||
|
||||
@@ -198,6 +202,7 @@ export function TemplateDrawer({
|
||||
template={template}
|
||||
editors={editors}
|
||||
previewAreas={previews}
|
||||
unsavedChangesRef={unsavedChangesRef}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
@@ -212,6 +217,9 @@ export function TemplateTable({
|
||||
|
||||
const table = useTable(`${templateEndpoint}-template`);
|
||||
const navigate = useNavigate();
|
||||
|
||||
// Warn the user before closing the editor with unsaved changes
|
||||
const closeGuard = useTemplateEditorCloseGuard();
|
||||
const user = useUserState();
|
||||
|
||||
const openDetailDrawer = useCallback((pk: number) => navigate(`${pk}/`), []);
|
||||
@@ -427,8 +435,15 @@ export function TemplateTable({
|
||||
title={t`Edit Template`}
|
||||
size={'90%'}
|
||||
closeOnEscape={false}
|
||||
onBeforeClose={closeGuard.onBeforeClose}
|
||||
renderContent={(id) => {
|
||||
return <TemplateDrawer id={id ?? ''} templateProps={templateProps} />;
|
||||
return (
|
||||
<TemplateDrawer
|
||||
id={id ?? ''}
|
||||
templateProps={templateProps}
|
||||
unsavedChangesRef={closeGuard.unsavedChangesRef}
|
||||
/>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
<InvenTreeTable
|
||||
|
||||
Reference in new issue
Block a user