@rebasepro/cms 0.25.1 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js +1 -1
- package/dist/collection_editor/ui/collection_editor/AICollectionGeneratorPopover.js.map +1 -1
- package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.d.ts +7 -1
- package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js +9 -2
- package/dist/collection_editor/ui/collection_editor/SchemaChangeDialog.js.map +1 -1
- package/dist/collection_editor/useLiveSchemaEditing.js +4 -1
- package/dist/collection_editor/useLiveSchemaEditing.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableReferenceField.js +1 -1
- package/dist/components/CollectionTableBinding/fields/TableReferenceField.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.d.ts +1 -2
- package/dist/components/CollectionTableBinding/internal/CollectionTableToolbar.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/EntityTableCell.d.ts +1 -2
- package/dist/components/CollectionTableBinding/internal/EntityTableCell.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewActions.js +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewActions.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewBinding.js +2 -28
- package/dist/components/CollectionViewBinding/CollectionViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.d.ts +12 -0
- package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js +33 -0
- package/dist/components/CollectionViewBinding/DefaultCollectionEmptyState.js.map +1 -0
- package/dist/components/CollectionsScopeContext.d.ts +5 -1
- package/dist/components/CollectionsScopeContext.js +10 -2
- package/dist/components/CollectionsScopeContext.js.map +1 -1
- package/dist/components/DefaultAppBar.js +2 -1
- package/dist/components/DefaultAppBar.js.map +1 -1
- package/dist/components/DefaultDrawer.js +16 -4
- package/dist/components/DefaultDrawer.js.map +1 -1
- package/dist/components/DefaultMissingReference.d.ts +8 -0
- package/dist/components/DefaultMissingReference.js +13 -0
- package/dist/components/DefaultMissingReference.js.map +1 -0
- package/dist/components/EntityFormPanel.d.ts +7 -2
- package/dist/components/EntityFormPanel.js +72 -29
- package/dist/components/EntityFormPanel.js.map +1 -1
- package/dist/components/HomePage/ContentHomePage.js +4 -3
- package/dist/components/HomePage/ContentHomePage.js.map +1 -1
- package/dist/components/HomePage/HomePageDnD.js +3 -1
- package/dist/components/HomePage/HomePageDnD.js.map +1 -1
- package/dist/components/HomePage/SmallNavigationCard.js +25 -0
- package/dist/components/HomePage/SmallNavigationCard.js.map +1 -0
- package/dist/components/RebaseAuthGate.js +3 -2
- package/dist/components/RebaseAuthGate.js.map +1 -1
- package/dist/components/RebaseLayout.d.ts +4 -1
- package/dist/components/RebaseLayout.js +7 -1
- package/dist/components/RebaseLayout.js.map +1 -1
- package/dist/components/RebaseShell.d.ts +4 -1
- package/dist/components/RebaseShell.js.map +1 -1
- package/dist/components/SideDialogs.js +10 -4
- package/dist/components/SideDialogs.js.map +1 -1
- package/dist/components/app/Scaffold.js +5 -1
- package/dist/components/app/Scaffold.js.map +1 -1
- package/dist/components/field_configs.js +1 -1
- package/dist/components/history/EntityHistoryView.js +6 -4
- package/dist/components/history/EntityHistoryView.js.map +1 -1
- package/dist/components/history/LastEditedByIndicator.d.ts +2 -1
- package/dist/data_export/export/export.d.ts +2 -13
- package/dist/data_export/export/export.js +1 -36
- package/dist/data_export/export/export.js.map +1 -1
- package/dist/form/EntityForm.d.ts +1 -1
- package/dist/form/EntityForm.js +17 -13
- package/dist/form/EntityForm.js.map +1 -1
- package/dist/form/EntityFormBinding.d.ts +1 -1
- package/dist/form/EntityFormBinding.js +42 -4
- package/dist/form/EntityFormBinding.js.map +1 -1
- package/dist/form/PropertyFieldBinding.js +1 -1
- package/dist/form/components/FieldBlock.d.ts +8 -1
- package/dist/form/components/FieldBlock.js +16 -2
- package/dist/form/components/FieldBlock.js.map +1 -1
- package/dist/form/components/FormSections.js +1 -1
- package/dist/form/components/FormSections.js.map +1 -1
- package/dist/form/components/LabelWithIcon.js +5 -2
- package/dist/form/components/LabelWithIcon.js.map +1 -1
- package/dist/form/field_bindings/DateTimeFieldBinding.js +2 -1
- package/dist/form/field_bindings/DateTimeFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/ReadOnlyFieldBinding.js +28 -1
- package/dist/form/field_bindings/ReadOnlyFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/RelationFieldBinding.js +7 -3
- package/dist/form/field_bindings/RelationFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/SelectFieldBinding.js +63 -42
- package/dist/form/field_bindings/SelectFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/SwitchFieldBinding.js +2 -1
- package/dist/form/field_bindings/SwitchFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/TextFieldBinding.js +8 -6
- package/dist/form/field_bindings/TextFieldBinding.js.map +1 -1
- package/dist/form/form_utils.d.ts +18 -1
- package/dist/form/form_utils.js +38 -2
- package/dist/form/form_utils.js.map +1 -1
- package/dist/form/index.d.ts +1 -1
- package/dist/form/label_placement.d.ts +23 -0
- package/dist/form/label_placement.js +71 -0
- package/dist/form/label_placement.js.map +1 -0
- package/dist/form/resolve_form_properties.d.ts +35 -3
- package/dist/form/resolve_form_properties.js +67 -6
- package/dist/form/resolve_form_properties.js.map +1 -1
- package/dist/hooks/useHistory.d.ts +5 -0
- package/dist/hooks/useHistory.js +22 -6
- package/dist/hooks/useHistory.js.map +1 -1
- package/dist/index.d.ts +50 -0
- package/dist/index.js +34 -7
- package/dist/preview/components/ReferencePreview.js +1 -1
- package/dist/preview/components/ReferencePreview.js.map +1 -1
- package/dist/preview/components/RelationPreview.js +1 -1
- package/dist/preview/components/RelationPreview.js.map +1 -1
- package/dist/types/components/EntityFormProps.d.ts +11 -0
- package/package.json +11 -10
- package/recipes/README.md +131 -0
- package/recipes/bulk-set-status.tsx +62 -0
- package/recipes/calendar-view.tsx +123 -0
- package/recipes/custom-login.tsx +60 -0
- package/recipes/my-preferences.tsx +68 -0
- package/recipes/orders-dashboard.tsx +125 -0
- package/recipes/site-settings.tsx +63 -0
|
@@ -40,8 +40,14 @@ function SideDialogs() {
|
|
|
40
40
|
}
|
|
41
41
|
function SideDialogView({ offsetPosition, panel, panelIndex, isTopPanel }) {
|
|
42
42
|
const [drawerCloseRequested, setDrawerCloseRequested] = useState(false);
|
|
43
|
-
const [blocked,
|
|
43
|
+
const [blocked, setBlockedState] = useState(false);
|
|
44
44
|
const [blockedNavigationMessage, setBlockedNavigationMessage] = useState();
|
|
45
|
+
const blockedRef = React.useRef(false);
|
|
46
|
+
const setBlocked = useCallback((value) => {
|
|
47
|
+
blockedRef.current = value;
|
|
48
|
+
setBlockedState(value);
|
|
49
|
+
}, []);
|
|
50
|
+
const isBlocked = useCallback(() => blockedRef.current, []);
|
|
45
51
|
const pendingCloseRef = React.useRef(false);
|
|
46
52
|
const setPendingClose = useCallback((value) => {
|
|
47
53
|
pendingCloseRef.current = value;
|
|
@@ -52,7 +58,7 @@ function SideDialogView({ offsetPosition, panel, panelIndex, isTopPanel }) {
|
|
|
52
58
|
const preventDismiss = useCallback((e) => {
|
|
53
59
|
e.preventDefault();
|
|
54
60
|
}, []);
|
|
55
|
-
const { dialogProps, triggerDialog } = useUnsavedChangesDialog(
|
|
61
|
+
const { dialogProps, triggerDialog } = useUnsavedChangesDialog(isBlocked, () => setBlocked(false));
|
|
56
62
|
useEffect(() => {
|
|
57
63
|
if (panel) widthRef.current = panel.width;
|
|
58
64
|
}, [panel]);
|
|
@@ -66,7 +72,7 @@ function SideDialogView({ offsetPosition, panel, panelIndex, isTopPanel }) {
|
|
|
66
72
|
setDrawerCloseRequested(false);
|
|
67
73
|
};
|
|
68
74
|
const onCloseRequest = useCallback((force) => {
|
|
69
|
-
if (
|
|
75
|
+
if (blockedRef.current && !force) {
|
|
70
76
|
setDrawerCloseRequested(true);
|
|
71
77
|
triggerDialog();
|
|
72
78
|
} else {
|
|
@@ -74,7 +80,6 @@ function SideDialogView({ offsetPosition, panel, panelIndex, isTopPanel }) {
|
|
|
74
80
|
panel?.onClose?.();
|
|
75
81
|
}
|
|
76
82
|
}, [
|
|
77
|
-
blocked,
|
|
78
83
|
triggerDialog,
|
|
79
84
|
sideDialogsController,
|
|
80
85
|
panel
|
|
@@ -91,6 +96,7 @@ function SideDialogView({ offsetPosition, panel, panelIndex, isTopPanel }) {
|
|
|
91
96
|
setPendingClose
|
|
92
97
|
}), [
|
|
93
98
|
blocked,
|
|
99
|
+
setBlocked,
|
|
94
100
|
setBlockedNavigationMessage,
|
|
95
101
|
width,
|
|
96
102
|
onCloseRequest,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SideDialogs.js","names":[],"sources":["../../src/components/SideDialogs.tsx"],"sourcesContent":["import type { SideDialogPanelProps } from \"../hooks/useSideDialogsController\";\nimport React, { useCallback, useContext, useEffect, useState, useMemo } from \"react\";\nimport { useSideDialogsController } from \"../hooks\";\nimport { Sheet, Dialog } from \"@rebasepro/ui\";\nimport { useUnsavedChangesDialog, UnsavedChangesDialog } from \"@rebasepro/app\";\nimport { ErrorBoundary } from \"@rebasepro/ui\";\nimport type { SidePanelBindingProps } from \"@rebasepro/cms-types\";\n\n\nexport type SideDialogController = {\n blocked: boolean,\n setBlocked: (blocked: boolean) => void,\n setBlockedNavigationMessage: (message?: React.ReactNode) => void,\n width?: string,\n close: (force?: boolean) => void;\n pendingClose: boolean,\n setPendingClose: (pendingClose: boolean) => void\n}\n\nconst SideDialogContext = React.createContext<SideDialogController>({\n width: \"\",\n blocked: false,\n setBlocked: (blocked: boolean) => {\n },\n setBlockedNavigationMessage: (message?: React.ReactNode) => {\n },\n close: () => {\n },\n pendingClose: false,\n setPendingClose: () => {\n\n }\n});\n\n/**\n * This hook is used to access the properties of a particular side dialog,\n * in contrast with {@link useSideDialogsController} which handles the\n * state of all the dialogs.\n */\nexport const useSideDialogContext = () => useContext<SideDialogController>(SideDialogContext);\n\n/**\n * This is the component in charge of rendering the side dialogs used\n * for editing entities. Use the {@link useSidePanel} to open\n * and control the dialogs.\n * This component needs a parent {@link Rebase}\n * {@link useSideDialogsController}\n * @group Components\n */\nexport function SideDialogs() {\n\n const sideDialogsController = useSideDialogsController();\n\n const sidePanels = sideDialogsController.sidePanels;\n\n // A trailing `undefined` slot (\"ghost panel\") is always appended so that\n // close animations work correctly. Index-based keys ensure that when the\n // last real panel is removed, the ghost inherits key=0 — re-using the\n // same SideDialogView instance so the Sheet smoothly transitions from\n // open → closed rather than unmounting instantly.\n const panels: (SideDialogPanelProps | undefined)[] = [...sidePanels];\n panels.push(undefined);\n\n return <>\n {\n panels.map((panel, index) =>\n <SideDialogView\n key={`side_dialog_${index}`}\n panel={panel}\n panelIndex={index}\n offsetPosition={sidePanels.length - index - 1}\n isTopPanel={index === sidePanels.length - 1}/>)\n }\n </>;\n}\n\nfunction SideDialogView({\n offsetPosition,\n panel,\n panelIndex,\n isTopPanel\n}: {\n offsetPosition: number,\n panel?: SideDialogPanelProps,\n panelIndex: number,\n isTopPanel: boolean\n}) {\n\n // was the closing of the dialog requested by the drawer\n const [drawerCloseRequested, setDrawerCloseRequested] = useState<boolean>(false);\n const [blocked, setBlocked] = useState(false);\n const [blockedNavigationMessage, setBlockedNavigationMessage] = useState<React.ReactNode | undefined>();\n\n // Held in a ref, read through a getter, because of *when* it is written and\n // read. \"Save and close\" raises it and submits the form in one click\n // handler, and the callback that acts on it — the form's `onSaved` — was\n // captured before React could re-render with the new value. As state the\n // flag was therefore always read one save late: the first \"save and close\"\n // saved and left the panel open, and the *next* save closed it.\n // Nothing renders from it, so a ref loses nothing.\n const pendingCloseRef = React.useRef(false);\n const setPendingClose = useCallback((value: boolean) => {\n pendingCloseRef.current = value;\n }, []);\n\n const widthRef = React.useRef<string | undefined>(panel?.width);\n const width = widthRef.current;\n\n const sideDialogsController = useSideDialogsController();\n\n // Prevent non-topmost dialogs from being dismissed by outside clicks.\n // When stacked Sheets exist, clicking the overlay of the topmost dialog\n // would otherwise propagate and dismiss lower dialogs too.\n const preventDismiss = useCallback((e: Event) => {\n e.preventDefault();\n }, []);\n\n const { dialogProps, triggerDialog } = useUnsavedChangesDialog(\n blocked,\n () => setBlocked(false)\n );\n\n useEffect(() => {\n if (panel)\n widthRef.current = panel.width;\n }, [panel])\n\n const handleDrawerCloseOk = () => {\n setBlocked(false);\n setDrawerCloseRequested(false);\n sideDialogsController.close();\n panel?.onClose?.();\n };\n\n const handleDrawerCloseCancel = () => {\n setDrawerCloseRequested(false);\n };\n\n const onCloseRequest = useCallback((force?: boolean) => {\n if (blocked && !force) {\n setDrawerCloseRequested(true);\n triggerDialog();\n } else {\n sideDialogsController.close();\n panel?.onClose?.();\n }\n }, [blocked, triggerDialog, sideDialogsController, panel]);\n\n const contextValue = useMemo(() => ({\n blocked,\n setBlocked,\n setBlockedNavigationMessage,\n width,\n close: onCloseRequest,\n get pendingClose() {\n return pendingCloseRef.current;\n },\n setPendingClose\n }), [blocked, setBlockedNavigationMessage, width, onCloseRequest, setPendingClose]);\n\n const additionalProps = panel?.additional as SidePanelBindingProps | undefined;\n const isDialogMode = additionalProps?.collection?.openEntityMode === \"dialog\";\n\n return (\n <SideDialogContext.Provider value={contextValue}>\n\n {isDialogMode ? (\n <Dialog\n open={Boolean(panel)}\n onOpenChange={(open) => {\n if (!open) {\n onCloseRequest();\n }\n }}\n maxWidth=\"4xl\"\n scrollable={false}\n >\n {panel && (\n <div className=\"flex flex-col h-[75vh] min-h-[500px] w-full min-w-0 max-w-full overflow-hidden\">\n <ErrorBoundary>\n {panel.component}\n </ErrorBoundary>\n </div>\n )}\n </Dialog>\n ) : (\n <Sheet\n open={Boolean(panel)}\n includeBackgroundOverlay={true}\n overlayStyle={{ zIndex: 40 + panelIndex * 10 }}\n style={{ zIndex: 45 + panelIndex * 10 }}\n onOpenChange={(open) => {\n if (!open) {\n onCloseRequest();\n }\n }}\n onPointerDownOutside={!isTopPanel ? preventDismiss : undefined}\n onInteractOutside={!isTopPanel ? preventDismiss : undefined}\n title={\"Side dialog \" + panel?.key}\n >\n {panel &&\n <div\n className={\"transform max-w-[100vw] lg:max-w-[95vw] flex flex-col h-full transition-all duration-250 ease-in-out bg-surface-card \"}\n style={{\n width: panel.width,\n transform: `translateX(-${offsetPosition * 200}px)`\n }}\n >\n <ErrorBoundary>\n {panel.component}\n </ErrorBoundary>\n </div>}\n\n {!panel && <div style={{ width }}/>}\n\n </Sheet>\n )}\n\n <UnsavedChangesDialog\n {...dialogProps}\n handleOk={() => {\n dialogProps.handleOk();\n if (drawerCloseRequested) {\n handleDrawerCloseOk();\n }\n }}\n handleCancel={() => {\n dialogProps.handleCancel();\n if (drawerCloseRequested) {\n handleDrawerCloseCancel();\n }\n }}\n body={blockedNavigationMessage || \"There are unsaved changes\"}/>\n\n </SideDialogContext.Provider>\n\n );\n}\n"],"mappings":";;;;;;AAmBA,IAAM,oBAAoB,MAAM,cAAoC;CAChE,OAAO;CACP,SAAS;CACT,aAAa,YAAqB,CAClC;CACA,8BAA8B,YAA8B,CAC5D;CACA,aAAa,CACb;CACA,cAAc;CACd,uBAAuB,CAEvB;AACJ,CAAC;;;;;;AAOD,IAAa,6BAA6B,WAAiC,iBAAiB;;;;;;;;;AAU5F,SAAgB,cAAc;CAI1B,MAAM,aAFwB,yBAEX,CAAA,CAAsB;CAOzC,MAAM,SAA+C,CAAC,GAAG,UAAU;CACnE,OAAO,KAAK,KAAA,CAAS;CAErB,OAAO,oBAAA,UAAA,EAAA,UAEC,OAAO,KAAK,OAAO,UACf,oBAAC,gBAAD;EAEW;EACP,YAAY;EACZ,gBAAgB,WAAW,SAAS,QAAQ;EAC5C,YAAY,UAAU,WAAW,SAAS;CAAG,GAJxC,eAAe,OAIyB,CAAC,EAE5D,CAAA;AACN;AAEA,SAAS,eAAe,EACpB,gBACA,OACA,YACA,cAMD;CAGC,MAAM,CAAC,sBAAsB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,SAAS;IACpB,IAAI,CAAC,MACD,eAAe;GAEvB;GACA,UAAS;GACT,YAAY;aAEX,SACG,oBAAC,OAAD;IAAK,WAAU;cACX,oBAAC,eAAD,EAAA,UACK,MAAM,UACI,CAAA;GACd,CAAA;EAEL,CAAA,IAER,qBAAC,OAAD;GACI,MAAM,QAAQ,KAAK;GACnB,0BAA0B;GAC1B,cAAc,EAAE,QAAQ,KAAK,aAAa,GAAG;GAC7C,OAAO,EAAE,QAAQ,KAAK,aAAa,GAAG;GACtC,eAAe,SAAS;IACpB,IAAI,CAAC,MACD,eAAe;GAEvB;GACA,sBAAsB,CAAC,aAAa,iBAAiB,KAAA;GACrD,mBAAmB,CAAC,aAAa,iBAAiB,KAAA;GAClD,OAAO,iBAAiB,OAAO;aAZnC,CAcK,SACG,oBAAC,OAAD;IACI,WAAW;IACX,OAAO;KACH,OAAO,MAAM;KACb,WAAW,eAAe,iBAAiB,IAAI;IACnD;cAEA,oBAAC,eAAD,EAAA,UACK,MAAM,UACI,CAAA;GACd,CAAA,GAER,CAAC,SAAS,oBAAC,OAAD,EAAK,OAAO,EAAE,MAAM,EAAG,CAAA,CAE/B;MAGX,oBAAC,sBAAD;GACI,GAAI;GACJ,gBAAgB;IACZ,YAAY,SAAS;IACrB,IAAI,sBACA,oBAAoB;GAE5B;GACA,oBAAoB;IAChB,YAAY,aAAa;IACzB,IAAI,sBACA,wBAAwB;GAEhC;GACA,MAAM,4BAA4B;EAA6B,CAAA,CAE3C;;AAGpC"}
|
|
1
|
+
{"version":3,"file":"SideDialogs.js","names":[],"sources":["../../src/components/SideDialogs.tsx"],"sourcesContent":["import type { SideDialogPanelProps } from \"../hooks/useSideDialogsController\";\nimport React, { useCallback, useContext, useEffect, useState, useMemo } from \"react\";\nimport { useSideDialogsController } from \"../hooks\";\nimport { Sheet, Dialog } from \"@rebasepro/ui\";\nimport { useUnsavedChangesDialog, UnsavedChangesDialog } from \"@rebasepro/app\";\nimport { ErrorBoundary } from \"@rebasepro/ui\";\nimport type { SidePanelBindingProps } from \"@rebasepro/cms-types\";\n\n\nexport type SideDialogController = {\n blocked: boolean,\n setBlocked: (blocked: boolean) => void,\n setBlockedNavigationMessage: (message?: React.ReactNode) => void,\n width?: string,\n close: (force?: boolean) => void;\n pendingClose: boolean,\n setPendingClose: (pendingClose: boolean) => void\n}\n\nconst SideDialogContext = React.createContext<SideDialogController>({\n width: \"\",\n blocked: false,\n setBlocked: (blocked: boolean) => {\n },\n setBlockedNavigationMessage: (message?: React.ReactNode) => {\n },\n close: () => {\n },\n pendingClose: false,\n setPendingClose: () => {\n\n }\n});\n\n/**\n * This hook is used to access the properties of a particular side dialog,\n * in contrast with {@link useSideDialogsController} which handles the\n * state of all the dialogs.\n */\nexport const useSideDialogContext = () => useContext<SideDialogController>(SideDialogContext);\n\n/**\n * This is the component in charge of rendering the side dialogs used\n * for editing entities. Use the {@link useSidePanel} to open\n * and control the dialogs.\n * This component needs a parent {@link Rebase}\n * {@link useSideDialogsController}\n * @group Components\n */\nexport function SideDialogs() {\n\n const sideDialogsController = useSideDialogsController();\n\n const sidePanels = sideDialogsController.sidePanels;\n\n // A trailing `undefined` slot (\"ghost panel\") is always appended so that\n // close animations work correctly. Index-based keys ensure that when the\n // last real panel is removed, the ghost inherits key=0 — re-using the\n // same SideDialogView instance so the Sheet smoothly transitions from\n // open → closed rather than unmounting instantly.\n const panels: (SideDialogPanelProps | undefined)[] = [...sidePanels];\n panels.push(undefined);\n\n return <>\n {\n panels.map((panel, index) =>\n <SideDialogView\n key={`side_dialog_${index}`}\n panel={panel}\n panelIndex={index}\n offsetPosition={sidePanels.length - index - 1}\n isTopPanel={index === sidePanels.length - 1}/>)\n }\n </>;\n}\n\nfunction SideDialogView({\n offsetPosition,\n panel,\n panelIndex,\n isTopPanel\n}: {\n offsetPosition: number,\n panel?: SideDialogPanelProps,\n panelIndex: number,\n isTopPanel: boolean\n}) {\n\n // was the closing of the dialog requested by the drawer\n const [drawerCloseRequested, setDrawerCloseRequested] = useState<boolean>(false);\n const [blocked, setBlockedState] = useState(false);\n const [blockedNavigationMessage, setBlockedNavigationMessage] = useState<React.ReactNode | undefined>();\n\n // Mirrored in a ref for the same reason as `pendingCloseRef` below. A save\n // reports the form clean and then moves the panel — onto the record it\n // just created, or closed — in one tick, and the guard reads this flag\n // inside that navigation. As state alone it was still set there, so\n // \"Create\" asked \"There are unsaved changes\" about a record already saved,\n // and left the URL on `#new_side`.\n const blockedRef = React.useRef(false);\n const setBlocked = useCallback((value: boolean) => {\n blockedRef.current = value;\n setBlockedState(value);\n }, []);\n const isBlocked = useCallback(() => blockedRef.current, []);\n\n // Held in a ref, read through a getter, because of *when* it is written and\n // read. \"Save and close\" raises it and submits the form in one click\n // handler, and the callback that acts on it — the form's `onSaved` — was\n // captured before React could re-render with the new value. As state the\n // flag was therefore always read one save late: the first \"save and close\"\n // saved and left the panel open, and the *next* save closed it.\n // Nothing renders from it, so a ref loses nothing.\n const pendingCloseRef = React.useRef(false);\n const setPendingClose = useCallback((value: boolean) => {\n pendingCloseRef.current = value;\n }, []);\n\n const widthRef = React.useRef<string | undefined>(panel?.width);\n const width = widthRef.current;\n\n const sideDialogsController = useSideDialogsController();\n\n // Prevent non-topmost dialogs from being dismissed by outside clicks.\n // When stacked Sheets exist, clicking the overlay of the topmost dialog\n // would otherwise propagate and dismiss lower dialogs too.\n const preventDismiss = useCallback((e: Event) => {\n e.preventDefault();\n }, []);\n\n const { dialogProps, triggerDialog } = useUnsavedChangesDialog(\n isBlocked,\n () => setBlocked(false)\n );\n\n useEffect(() => {\n if (panel)\n widthRef.current = panel.width;\n }, [panel])\n\n const handleDrawerCloseOk = () => {\n setBlocked(false);\n setDrawerCloseRequested(false);\n sideDialogsController.close();\n panel?.onClose?.();\n };\n\n const handleDrawerCloseCancel = () => {\n setDrawerCloseRequested(false);\n };\n\n const onCloseRequest = useCallback((force?: boolean) => {\n if (blockedRef.current && !force) {\n setDrawerCloseRequested(true);\n triggerDialog();\n } else {\n sideDialogsController.close();\n panel?.onClose?.();\n }\n }, [triggerDialog, sideDialogsController, panel]);\n\n const contextValue = useMemo(() => ({\n blocked,\n setBlocked,\n setBlockedNavigationMessage,\n width,\n close: onCloseRequest,\n get pendingClose() {\n return pendingCloseRef.current;\n },\n setPendingClose\n }), [blocked, setBlocked, setBlockedNavigationMessage, width, onCloseRequest, setPendingClose]);\n\n const additionalProps = panel?.additional as SidePanelBindingProps | undefined;\n const isDialogMode = additionalProps?.collection?.openEntityMode === \"dialog\";\n\n return (\n <SideDialogContext.Provider value={contextValue}>\n\n {isDialogMode ? (\n <Dialog\n open={Boolean(panel)}\n onOpenChange={(open) => {\n if (!open) {\n onCloseRequest();\n }\n }}\n maxWidth=\"4xl\"\n scrollable={false}\n >\n {panel && (\n <div className=\"flex flex-col h-[75vh] min-h-[500px] w-full min-w-0 max-w-full overflow-hidden\">\n <ErrorBoundary>\n {panel.component}\n </ErrorBoundary>\n </div>\n )}\n </Dialog>\n ) : (\n <Sheet\n open={Boolean(panel)}\n includeBackgroundOverlay={true}\n overlayStyle={{ zIndex: 40 + panelIndex * 10 }}\n style={{ zIndex: 45 + panelIndex * 10 }}\n onOpenChange={(open) => {\n if (!open) {\n onCloseRequest();\n }\n }}\n onPointerDownOutside={!isTopPanel ? preventDismiss : undefined}\n onInteractOutside={!isTopPanel ? preventDismiss : undefined}\n title={\"Side dialog \" + panel?.key}\n >\n {panel &&\n <div\n className={\"transform max-w-[100vw] lg:max-w-[95vw] flex flex-col h-full transition-all duration-250 ease-in-out bg-surface-card \"}\n style={{\n width: panel.width,\n transform: `translateX(-${offsetPosition * 200}px)`\n }}\n >\n <ErrorBoundary>\n {panel.component}\n </ErrorBoundary>\n </div>}\n\n {!panel && <div style={{ width }}/>}\n\n </Sheet>\n )}\n\n <UnsavedChangesDialog\n {...dialogProps}\n handleOk={() => {\n dialogProps.handleOk();\n if (drawerCloseRequested) {\n handleDrawerCloseOk();\n }\n }}\n handleCancel={() => {\n dialogProps.handleCancel();\n if (drawerCloseRequested) {\n handleDrawerCloseCancel();\n }\n }}\n body={blockedNavigationMessage || \"There are unsaved changes\"}/>\n\n </SideDialogContext.Provider>\n\n );\n}\n"],"mappings":";;;;;;AAmBA,IAAM,oBAAoB,MAAM,cAAoC;CAChE,OAAO;CACP,SAAS;CACT,aAAa,YAAqB,CAClC;CACA,8BAA8B,YAA8B,CAC5D;CACA,aAAa,CACb;CACA,cAAc;CACd,uBAAuB,CAEvB;AACJ,CAAC;;;;;;AAOD,IAAa,6BAA6B,WAAiC,iBAAiB;;;;;;;;;AAU5F,SAAgB,cAAc;CAI1B,MAAM,aAFwB,yBAEX,CAAA,CAAsB;CAOzC,MAAM,SAA+C,CAAC,GAAG,UAAU;CACnE,OAAO,KAAK,KAAA,CAAS;CAErB,OAAO,oBAAA,UAAA,EAAA,UAEC,OAAO,KAAK,OAAO,UACf,oBAAC,gBAAD;EAEW;EACP,YAAY;EACZ,gBAAgB,WAAW,SAAS,QAAQ;EAC5C,YAAY,UAAU,WAAW,SAAS;CAAG,GAJxC,eAAe,OAIyB,CAAC,EAE5D,CAAA;AACN;AAEA,SAAS,eAAe,EACpB,gBACA,OACA,YACA,cAMD;CAGC,MAAM,CAAC,sBAAsB,2BAA2B,SAAkB,KAAK;CAC/E,MAAM,CAAC,SAAS,mBAAmB,SAAS,KAAK;CACjD,MAAM,CAAC,0BAA0B,+BAA+B,SAAsC;CAQtG,MAAM,aAAa,MAAM,OAAO,KAAK;CACrC,MAAM,aAAa,aAAa,UAAmB;EAC/C,WAAW,UAAU;EACrB,gBAAgB,KAAK;CACzB,GAAG,CAAC,CAAC;CACL,MAAM,YAAY,kBAAkB,WAAW,SAAS,CAAC,CAAC;CAS1D,MAAM,kBAAkB,MAAM,OAAO,KAAK;CAC1C,MAAM,kBAAkB,aAAa,UAAmB;EACpD,gBAAgB,UAAU;CAC9B,GAAG,CAAC,CAAC;CAEL,MAAM,WAAW,MAAM,OAA2B,OAAO,KAAK;CAC9D,MAAM,QAAQ,SAAS;CA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AQ,KAAK,aAAa,GAAG;GACtC,eAAe,SAAS;IACpB,IAAI,CAAC,MACD,eAAe;GAEvB;GACA,sBAAsB,CAAC,aAAa,iBAAiB,KAAA;GACrD,mBAAmB,CAAC,aAAa,iBAAiB,KAAA;GAClD,OAAO,iBAAiB,OAAO;aAZnC,CAcK,SACG,oBAAC,OAAD;IACI,WAAW;IACX,OAAO;KACH,OAAO,MAAM;KACb,WAAW,eAAe,iBAAiB,IAAI;IACnD;cAEA,oBAAC,eAAD,EAAA,UACK,MAAM,UACI,CAAA;GACd,CAAA,GAER,CAAC,SAAS,oBAAC,OAAD,EAAK,OAAO,EAAE,MAAM,EAAG,CAAA,CAE/B;MAGX,oBAAC,sBAAD;GACI,GAAI;GACJ,gBAAgB;IACZ,YAAY,SAAS;IACrB,IAAI,sBACA,oBAAoB;GAE5B;GACA,oBAAoB;IAChB,YAAY,aAAa;IACzB,IAAI,sBACA,wBAAwB;GAEhC;GACA,MAAM,4BAA4B;EAA6B,CAAA,CAE3C;;AAGpC"}
|
|
@@ -4,7 +4,7 @@ import React, { useCallback, useMemo } from "react";
|
|
|
4
4
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
5
5
|
import { deepEqual } from "fast-equals";
|
|
6
6
|
import { ErrorBoundary, IconButton, MenuIcon, Sheet, cls, defaultBorderMixin } from "@rebasepro/ui";
|
|
7
|
-
import { ConnectionLostBanner, useLargeLayout, useTranslation } from "@rebasepro/app";
|
|
7
|
+
import { ConnectionLostBanner, RlsSimulationBanner, useLargeLayout, useTranslation } from "@rebasepro/app";
|
|
8
8
|
/**
|
|
9
9
|
* Namespaced by base path: two admins served from one origin are two different
|
|
10
10
|
* navigations, and a single key would have them overwrite each other's drawer.
|
|
@@ -160,6 +160,10 @@ var Scaffold = React.memo(function Scaffold(props) {
|
|
|
160
160
|
"lg:pt-0 lg:pb-2": padding,
|
|
161
161
|
"lg:pt-2": !hasAppBar && padding
|
|
162
162
|
}) }),
|
|
163
|
+
/* @__PURE__ */ jsx(RlsSimulationBanner, { className: cls("px-2 pt-1", {
|
|
164
|
+
"lg:pt-0 lg:pb-2": padding,
|
|
165
|
+
"lg:pt-2": !hasAppBar && padding
|
|
166
|
+
}) }),
|
|
163
167
|
/* @__PURE__ */ jsx("div", {
|
|
164
168
|
className: cls("bg-surface-sheet", "grow overflow-auto m-0", "lg:border lg:border-hairline", {
|
|
165
169
|
"mt-1 lg:m-0 lg:mx-2 lg:mb-2 lg:rounded-xl": padding,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Scaffold.js","names":[],"sources":["../../../src/components/app/Scaffold.tsx"],"sourcesContent":["import React, { PropsWithChildren, useCallback, useMemo } from \"react\";\nimport { cls, defaultBorderMixin, IconButton, Sheet, Tooltip } from \"@rebasepro/ui\";\nimport { ChevronLeftIcon, ErrorBoundary, MenuIcon } from \"@rebasepro/ui\";\nimport { deepEqual as equal } from \"fast-equals\"\n\nimport { ConnectionLostBanner, useLargeLayout, useTranslation } from \"@rebasepro/app\";\nimport { useUrlController } from \"../../hooks/navigation/contexts/UrlContext\";\nimport { AppContext } from \"./useApp\";\n\nexport const DRAWER_WIDTH = 280;\n\n/**\n * Namespaced by base path: two admins served from one origin are two different\n * navigations, and a single key would have them overwrite each other's drawer.\n */\nexport function drawerOpenStorageKey(basePath: string | undefined) {\n return `rebase-drawer-open:${basePath || \"/\"}`;\n}\n\n/** `null` when the user has never toggled the drawer, or storage is unavailable. */\nfunction readStoredDrawerOpen(key: string): boolean | null {\n if (typeof window === \"undefined\") return null;\n try {\n const stored = window.localStorage.getItem(key);\n return stored === null ? null : stored === \"true\";\n } catch (e) {\n // Storage can be blocked: private mode, sandboxed iframe, cookie policy.\n return null;\n }\n}\n\nfunction writeStoredDrawerOpen(key: string, open: boolean) {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(key, String(open));\n } catch (e) {\n // Same as above: a drawer that forgets is better than a crash.\n }\n}\n\n/**\n * @group Core\n */\nexport interface ScaffoldProps {\n\n /**\n * Expand the collapsed drawer while the pointer is over it. On by default —\n * pass `false` to keep the rail a rail until the user clicks the toggle.\n */\n autoOpenDrawer?: boolean;\n\n /**\n * Start with the drawer expanded rather than collapsed to icons.\n *\n * Distinct from {@link autoOpenDrawer}, which is a hover behaviour: this one\n * only seeds the very first visit. Once the user toggles the drawer, that\n * choice is stored in `localStorage` and wins over this prop on every load.\n *\n * Ignored on small layouts, where an expanded drawer covers the content it is\n * meant to navigate.\n */\n defaultDrawerOpen?: boolean;\n\n /**\n * Logo to be displayed in the top bar and drawer.\n * Note that this has no effect if you are using a custom AppBar or Drawer.\n */\n logo?: string;\n\n /**\n * If true, the main content will be padded in large layouts. Defaults to true.\n */\n padding?: boolean;\n\n className?: string;\n\n style?: React.CSSProperties;\n}\n\n/**\n * This view acts as a scaffold for Rebase.\n *\n * It is in charge of displaying the navigation drawer, top bar and main\n * collection views.\n * This component needs a parent {@link Rebase}\n *\n * @param props\n\n * @group Core\n */\nexport const Scaffold = React.memo<PropsWithChildren<ScaffoldProps>>(\n function Scaffold(props: PropsWithChildren<ScaffoldProps>) {\n\n const {\n children,\n autoOpenDrawer = true,\n defaultDrawerOpen = false,\n logo,\n className,\n style,\n padding = true\n } = props;\n\n // `toArray` keeps strings and numbers, and those have no `.type` at all.\n // Reading `child.type.componentType` off one threw a TypeError from\n // inside the layout, which is a bewildering way to be told that a stray\n // text node — a conditional that rendered `\"\"`, a template string —\n // reached the Scaffold. Anything that is not an element is just \"other\".\n const slotOf = (child: React.ReactNode): string | undefined =>\n React.isValidElement(child)\n ? (child.type as { componentType?: string })?.componentType\n : undefined;\n\n const childArray = React.Children.toArray(children);\n const drawerChildren = childArray.filter((child) => slotOf(child) === \"Drawer\");\n if (drawerChildren.length > 1) {\n throw Error(\"Only one Drawer component is allowed in Scaffold\");\n }\n const appBarChildren = childArray.filter((child) => slotOf(child) === \"AppBar\");\n if (appBarChildren.length > 1) {\n throw Error(\"Only one AppBar component is allowed in Scaffold\");\n }\n const otherChildren = childArray\n .filter((child) => slotOf(child) !== \"Drawer\" && slotOf(child) !== \"AppBar\");\n const includeDrawer = drawerChildren.length > 0;\n const largeLayout = useLargeLayout();\n\n const storageKey = drawerOpenStorageKey(useUrlController().basePath);\n\n // Seeded once, deliberately: a `useEffect` syncing this to the prop would\n // re-expand the drawer under a user who had just collapsed it.\n const [drawerOpen, setDrawerOpenState] = React.useState(defaultDrawerOpen && largeLayout);\n const [onHover, setOnHover] = React.useState(false);\n\n // The stored choice is a client-only fact, so it is applied after the first\n // render rather than seeded into it: reading storage while rendering would\n // make the client disagree with server-rendered HTML. A layout effect runs\n // before paint, so the drawer still arrives in its remembered state.\n // `defaultDrawerOpen` seeds the very first visit and is ignored after that.\n React.useLayoutEffect(() => {\n const stored = readStoredDrawerOpen(storageKey);\n if (stored === null) return;\n setDrawerOpenState(stored && largeLayout);\n // Deliberately not re-run on `largeLayout`: crossing the breakpoint is\n // the effect below, and re-running here would undo a user's toggle.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [storageKey]);\n\n // One piece of state drives two different things: the expanded rail on\n // large layouts, and the modal sheet on small ones. Carrying an expanded\n // rail across the breakpoint would drop that sheet, overlay and all, over\n // the content — so the crossing resets it, and widening again restores\n // whatever the user last chose.\n const wasLargeLayout = React.useRef(largeLayout);\n React.useEffect(() => {\n if (wasLargeLayout.current === largeLayout) return;\n wasLargeLayout.current = largeLayout;\n setDrawerOpenState(largeLayout ? (readStoredDrawerOpen(storageKey) ?? defaultDrawerOpen) : false);\n }, [largeLayout, defaultDrawerOpen, storageKey]);\n\n const setDrawerOpen = useCallback((open: boolean) => {\n setDrawerOpenState(open);\n // Small layouts render the drawer as a modal sheet. Remembering that\n // one would greet the next load with an overlay over the content.\n if (!largeLayout) return;\n writeStoredDrawerOpen(storageKey, open);\n }, [largeLayout, storageKey]);\n\n // The pointer has left, but a popover the drawer opened is still up, so the\n // collapse is owed rather than cancelled. See `setOnHoverFalse`.\n const collapseWhenPopoverCloses = React.useRef(false);\n\n const setOnHoverTrue = useCallback(() => {\n // Hover expansion is the default; `autoOpenDrawer={false}` opts out for\n // admins that want the rail to stay a rail until the toggle is clicked.\n if (!autoOpenDrawer) return;\n collapseWhenPopoverCloses.current = false;\n setOnHover(true);\n }, [autoOpenDrawer]);\n const setOnHoverFalse = useCallback(() => {\n // Don't collapse the drawer out from under an open popover/dropdown —\n // its content is portalled outside the drawer, so reaching for it reads\n // as a mouseleave. The collapse is owed until that popover closes.\n if (document.querySelector(\"[data-radix-popper-content-wrapper]\")) {\n collapseWhenPopoverCloses.current = true;\n return;\n }\n collapseWhenPopoverCloses.current = false;\n setOnHover(false);\n }, []);\n\n // Nothing fires a second mouseleave when the popover finally closes, so the\n // owed collapse has to be noticed rather than waited for. Only mounted\n // while the drawer is actually floating open.\n React.useEffect(() => {\n if (!onHover) return;\n const collapseIfOwed = () => {\n if (!collapseWhenPopoverCloses.current) return;\n if (document.querySelector(\"[data-radix-popper-content-wrapper]\")) return;\n collapseWhenPopoverCloses.current = false;\n setOnHover(false);\n };\n const observer = new MutationObserver(collapseIfOwed);\n observer.observe(document.body, {\n childList: true,\n subtree: true\n });\n return () => observer.disconnect();\n }, [onHover]);\n\n const handleDrawerOpen = useCallback(() => {\n setDrawerOpen(true);\n }, [setDrawerOpen]);\n\n const handleDrawerClose = useCallback(() => {\n setDrawerOpen(false);\n }, [setDrawerOpen]);\n\n const computedDrawerOpen: boolean = drawerOpen;\n const computedDrawerHovered = Boolean(largeLayout && onHover);\n\n const hasAppBar = Boolean(appBarChildren.length > 0);\n const appContextValue = useMemo(() => ({\n hasDrawer: Boolean(includeDrawer),\n drawerOpen: computedDrawerOpen,\n drawerHovered: computedDrawerHovered,\n openDrawer: handleDrawerOpen,\n closeDrawer: handleDrawerClose,\n closeHover: setOnHoverFalse,\n logo\n }), [includeDrawer, computedDrawerOpen, computedDrawerHovered, handleDrawerOpen, handleDrawerClose, setOnHoverFalse, logo]);\n\n return (\n <AppContext.Provider value={appContextValue}>\n <div\n className={cls(\"flex h-screen w-screen overflow-hidden\",\n \"bg-surface-frame\",\n \"text-surface-900 dark:text-white\", className)}\n style={{\n paddingTop: \"env(safe-area-inset-top)\",\n paddingLeft: \"env(safe-area-inset-left)\",\n paddingRight: \"env(safe-area-inset-right)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n height: \"100dvh\",\n ...style\n }}>\n {appBarChildren}\n\n <DrawerWrapper\n displayed={includeDrawer}\n onMouseEnter={setOnHoverTrue}\n onMouseMove={setOnHoverTrue}\n onMouseLeave={setOnHoverFalse}\n open={drawerOpen}\n hovered={onHover}\n setDrawerOpen={setDrawerOpen}>\n {includeDrawer && drawerChildren}\n </DrawerWrapper>\n\n <main\n className=\"flex flex-col grow overflow-auto\">\n\n {hasAppBar && <DrawerHeader/>}\n\n {/* Above the sheet, so it is there on every screen: while\n the realtime connection is down, every live view is\n showing what it last received. */}\n <ConnectionLostBanner className={cls(\"px-2 pt-1\", {\n \"lg:pt-0 lg:pb-2\": padding,\n \"lg:pt-2\": !hasAppBar && padding\n })}/>\n\n <div\n // The sheet is one lightness step above the frame AND carries a\n // plain hairline on its edge. The step alone (#090a0c to #111316,\n // #eff0f3 to #f8f9fa) is about 3 L* on both themes, under what a\n // dimmed screen renders, and the first pass of this system removed\n // the line on the theory that the step would do its work; the\n // frame and the sheet then read as one black. The reference's own\n // content sheet carries this line. Only in the inset `lg` layout:\n // edge-to-edge on small screens, a border draws at the viewport.\n className={cls(\"bg-surface-sheet\", \"grow overflow-auto m-0\", \"lg:border lg:border-hairline\", {\n \"mt-1 lg:m-0 lg:mx-2 lg:mb-2 lg:rounded-xl\": padding,\n // No app bar means no DrawerHeader spacer above, so inset the\n // panel by the same amount as its sides and bottom.\n // Must come after the padding classes, which reset lg margins.\n \"lg:mt-2\": !hasAppBar && padding,\n \"lg:mt-4\": !hasAppBar && !padding\n })}>\n\n <ErrorBoundary>\n {otherChildren}\n </ErrorBoundary>\n\n </div>\n </main>\n </div>\n </AppContext.Provider>\n );\n },\n equal\n)\n\nconst DrawerHeader = () => {\n return (\n <div className=\"flex flex-col min-h-14\"></div>\n );\n};\n\nfunction DrawerWrapper(props: {\n children: React.ReactNode,\n displayed: boolean,\n open: boolean,\n logo?: string,\n hovered: boolean,\n setDrawerOpen: (open: boolean) => void,\n onMouseEnter: () => void,\n onMouseMove: () => void,\n onMouseLeave: () => void\n}) {\n\n const layoutWidth = !props.displayed ? 0 : (props.open ? DRAWER_WIDTH : 72);\n const visualWidth = !props.displayed ? 0 : ((props.open || props.hovered) ? DRAWER_WIDTH : 72);\n\n const isFloating = props.hovered && !props.open;\n const { t } = useTranslation();\n\n // The drawer is part of the frame, on both themes. When it floats over the\n // sheet it needs an edge, because a frame-coloured panel over the sheet is\n // an object at that moment; docked, it is a region and gets none.\n const innerDrawer = <div\n className={cls(\"h-full overflow-hidden bg-surface-frame\", defaultBorderMixin,\n isFloating ? \"absolute top-0 left-0 bottom-0 z-50 shadow-lg border-r\" : \"relative\")}\n style={{\n width: visualWidth,\n transition: \"left 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, opacity 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, width 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms\"\n }}\n >\n\n <div className={\"flex flex-col h-full\"}>\n {props.children}\n </div>\n\n </div>;\n\n const largeLayout = useLargeLayout();\n if (!largeLayout) {\n if (!props.displayed)\n return null;\n return <>\n <IconButton\n aria-label={t(\"open_menu\")}\n onClick={() => props.setDrawerOpen(true)}\n className=\"absolute sm:top-2 sm:left-4 top-1 left-2\"\n >\n <MenuIcon/>\n </IconButton>\n <Sheet side={\"left\"}\n transparent={true}\n open={props.open}\n onOpenChange={props.setDrawerOpen}\n title={t(\"navigation_drawer\")}\n overlayClassName={\"bg-surface-scrim\"}\n >\n {innerDrawer}\n </Sheet>\n </>;\n }\n\n return (\n <div\n className=\"z-20 relative flex-shrink-0 overflow-visible\"\n onMouseEnter={props.onMouseEnter}\n onMouseMove={props.onMouseMove}\n onMouseLeave={props.onMouseLeave}\n style={{\n width: layoutWidth,\n minWidth: layoutWidth,\n transition: \"left 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, opacity 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, width 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms\"\n }}>\n\n {innerDrawer}\n\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,qBAAqB,UAA8B;CAC/D,OAAO,sBAAsB,YAAY;AAC7C;;AAGA,SAAS,qBAAqB,KAA6B;CACvD,IAAI,OAAO,WAAW,aAAa,OAAO;CAC1C,IAAI;EACA,MAAM,SAAS,OAAO,aAAa,QAAQ,GAAG;EAC9C,OAAO,WAAW,OAAO,OAAO,WAAW;CAC/C,SAAS,GAAG;EAER,OAAO;CACX;AACJ;AAEA,SAAS,sBAAsB,KAAa,MAAe;CACvD,IAAI,OAAO,WAAW,aAAa;CACnC,IAAI;EACA,OAAO,aAAa,QAAQ,KAAK,OAAO,IAAI,CAAC;CACjD,SAAS,GAAG,CAEZ;AACJ;;;;;;;;;;;;AAoDA,IAAa,WAAW,MAAM,KAC1B,SAAS,SAAS,OAAyC;CAEvD,MAAM,EACF,UACA,iBAAiB,MACjB,oBAAoB,OACpB,MACA,WACA,OACA,UAAU,SACV;CAOJ,MAAM,UAAU,UACZ,MAAM,eAAe,KAAK,IACnB,MAAM,MAAqC,gBAC5C,KAAA;CAEV,MAAM,aAAa,MAAM,SAAS,QAAQ,QAAQ;CAClD,MAAM,iBAAiB,WAAW,QAAQ,UAAU,OAAO,KAAK,MAAM,QAAQ;CAC9E,IAAI,eAAe,SAAS,GACxB,MAAM,MAAM,kDAAkD;CAElE,MAAM,iBAAiB,WAAW,QAAQ,UAAU,OAAO,KAAK,MAAM,QAAQ;CAC9E,IAAI,eAAe,SAAS,GACxB,MAAM,MAAM,kDAAkD;CAElE,MAAM,gBAAgB,WACjB,QAAQ,UAAU,OAAO,KAAK,MAAM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../src/components/app/Scaffold.tsx"],"sourcesContent":["import React, { PropsWithChildren, useCallback, useMemo } from \"react\";\nimport { cls, defaultBorderMixin, IconButton, Sheet, Tooltip } from \"@rebasepro/ui\";\nimport { ChevronLeftIcon, ErrorBoundary, MenuIcon } from \"@rebasepro/ui\";\nimport { deepEqual as equal } from \"fast-equals\"\n\nimport { ConnectionLostBanner, RlsSimulationBanner, useLargeLayout, useTranslation } from \"@rebasepro/app\";\nimport { useUrlController } from \"../../hooks/navigation/contexts/UrlContext\";\nimport { AppContext } from \"./useApp\";\n\nexport const DRAWER_WIDTH = 280;\n\n/**\n * Namespaced by base path: two admins served from one origin are two different\n * navigations, and a single key would have them overwrite each other's drawer.\n */\nexport function drawerOpenStorageKey(basePath: string | undefined) {\n return `rebase-drawer-open:${basePath || \"/\"}`;\n}\n\n/** `null` when the user has never toggled the drawer, or storage is unavailable. */\nfunction readStoredDrawerOpen(key: string): boolean | null {\n if (typeof window === \"undefined\") return null;\n try {\n const stored = window.localStorage.getItem(key);\n return stored === null ? null : stored === \"true\";\n } catch (e) {\n // Storage can be blocked: private mode, sandboxed iframe, cookie policy.\n return null;\n }\n}\n\nfunction writeStoredDrawerOpen(key: string, open: boolean) {\n if (typeof window === \"undefined\") return;\n try {\n window.localStorage.setItem(key, String(open));\n } catch (e) {\n // Same as above: a drawer that forgets is better than a crash.\n }\n}\n\n/**\n * @group Core\n */\nexport interface ScaffoldProps {\n\n /**\n * Expand the collapsed drawer while the pointer is over it. On by default —\n * pass `false` to keep the rail a rail until the user clicks the toggle.\n */\n autoOpenDrawer?: boolean;\n\n /**\n * Start with the drawer expanded rather than collapsed to icons.\n *\n * Distinct from {@link autoOpenDrawer}, which is a hover behaviour: this one\n * only seeds the very first visit. Once the user toggles the drawer, that\n * choice is stored in `localStorage` and wins over this prop on every load.\n *\n * Ignored on small layouts, where an expanded drawer covers the content it is\n * meant to navigate.\n */\n defaultDrawerOpen?: boolean;\n\n /**\n * Logo to be displayed in the top bar and drawer.\n * Note that this has no effect if you are using a custom AppBar or Drawer.\n */\n logo?: string;\n\n /**\n * If true, the main content will be padded in large layouts. Defaults to true.\n */\n padding?: boolean;\n\n className?: string;\n\n style?: React.CSSProperties;\n}\n\n/**\n * This view acts as a scaffold for Rebase.\n *\n * It is in charge of displaying the navigation drawer, top bar and main\n * collection views.\n * This component needs a parent {@link Rebase}\n *\n * @param props\n\n * @group Core\n */\nexport const Scaffold = React.memo<PropsWithChildren<ScaffoldProps>>(\n function Scaffold(props: PropsWithChildren<ScaffoldProps>) {\n\n const {\n children,\n autoOpenDrawer = true,\n defaultDrawerOpen = false,\n logo,\n className,\n style,\n padding = true\n } = props;\n\n // `toArray` keeps strings and numbers, and those have no `.type` at all.\n // Reading `child.type.componentType` off one threw a TypeError from\n // inside the layout, which is a bewildering way to be told that a stray\n // text node — a conditional that rendered `\"\"`, a template string —\n // reached the Scaffold. Anything that is not an element is just \"other\".\n const slotOf = (child: React.ReactNode): string | undefined =>\n React.isValidElement(child)\n ? (child.type as { componentType?: string })?.componentType\n : undefined;\n\n const childArray = React.Children.toArray(children);\n const drawerChildren = childArray.filter((child) => slotOf(child) === \"Drawer\");\n if (drawerChildren.length > 1) {\n throw Error(\"Only one Drawer component is allowed in Scaffold\");\n }\n const appBarChildren = childArray.filter((child) => slotOf(child) === \"AppBar\");\n if (appBarChildren.length > 1) {\n throw Error(\"Only one AppBar component is allowed in Scaffold\");\n }\n const otherChildren = childArray\n .filter((child) => slotOf(child) !== \"Drawer\" && slotOf(child) !== \"AppBar\");\n const includeDrawer = drawerChildren.length > 0;\n const largeLayout = useLargeLayout();\n\n const storageKey = drawerOpenStorageKey(useUrlController().basePath);\n\n // Seeded once, deliberately: a `useEffect` syncing this to the prop would\n // re-expand the drawer under a user who had just collapsed it.\n const [drawerOpen, setDrawerOpenState] = React.useState(defaultDrawerOpen && largeLayout);\n const [onHover, setOnHover] = React.useState(false);\n\n // The stored choice is a client-only fact, so it is applied after the first\n // render rather than seeded into it: reading storage while rendering would\n // make the client disagree with server-rendered HTML. A layout effect runs\n // before paint, so the drawer still arrives in its remembered state.\n // `defaultDrawerOpen` seeds the very first visit and is ignored after that.\n React.useLayoutEffect(() => {\n const stored = readStoredDrawerOpen(storageKey);\n if (stored === null) return;\n setDrawerOpenState(stored && largeLayout);\n // Deliberately not re-run on `largeLayout`: crossing the breakpoint is\n // the effect below, and re-running here would undo a user's toggle.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [storageKey]);\n\n // One piece of state drives two different things: the expanded rail on\n // large layouts, and the modal sheet on small ones. Carrying an expanded\n // rail across the breakpoint would drop that sheet, overlay and all, over\n // the content — so the crossing resets it, and widening again restores\n // whatever the user last chose.\n const wasLargeLayout = React.useRef(largeLayout);\n React.useEffect(() => {\n if (wasLargeLayout.current === largeLayout) return;\n wasLargeLayout.current = largeLayout;\n setDrawerOpenState(largeLayout ? (readStoredDrawerOpen(storageKey) ?? defaultDrawerOpen) : false);\n }, [largeLayout, defaultDrawerOpen, storageKey]);\n\n const setDrawerOpen = useCallback((open: boolean) => {\n setDrawerOpenState(open);\n // Small layouts render the drawer as a modal sheet. Remembering that\n // one would greet the next load with an overlay over the content.\n if (!largeLayout) return;\n writeStoredDrawerOpen(storageKey, open);\n }, [largeLayout, storageKey]);\n\n // The pointer has left, but a popover the drawer opened is still up, so the\n // collapse is owed rather than cancelled. See `setOnHoverFalse`.\n const collapseWhenPopoverCloses = React.useRef(false);\n\n const setOnHoverTrue = useCallback(() => {\n // Hover expansion is the default; `autoOpenDrawer={false}` opts out for\n // admins that want the rail to stay a rail until the toggle is clicked.\n if (!autoOpenDrawer) return;\n collapseWhenPopoverCloses.current = false;\n setOnHover(true);\n }, [autoOpenDrawer]);\n const setOnHoverFalse = useCallback(() => {\n // Don't collapse the drawer out from under an open popover/dropdown —\n // its content is portalled outside the drawer, so reaching for it reads\n // as a mouseleave. The collapse is owed until that popover closes.\n if (document.querySelector(\"[data-radix-popper-content-wrapper]\")) {\n collapseWhenPopoverCloses.current = true;\n return;\n }\n collapseWhenPopoverCloses.current = false;\n setOnHover(false);\n }, []);\n\n // Nothing fires a second mouseleave when the popover finally closes, so the\n // owed collapse has to be noticed rather than waited for. Only mounted\n // while the drawer is actually floating open.\n React.useEffect(() => {\n if (!onHover) return;\n const collapseIfOwed = () => {\n if (!collapseWhenPopoverCloses.current) return;\n if (document.querySelector(\"[data-radix-popper-content-wrapper]\")) return;\n collapseWhenPopoverCloses.current = false;\n setOnHover(false);\n };\n const observer = new MutationObserver(collapseIfOwed);\n observer.observe(document.body, {\n childList: true,\n subtree: true\n });\n return () => observer.disconnect();\n }, [onHover]);\n\n const handleDrawerOpen = useCallback(() => {\n setDrawerOpen(true);\n }, [setDrawerOpen]);\n\n const handleDrawerClose = useCallback(() => {\n setDrawerOpen(false);\n }, [setDrawerOpen]);\n\n const computedDrawerOpen: boolean = drawerOpen;\n const computedDrawerHovered = Boolean(largeLayout && onHover);\n\n const hasAppBar = Boolean(appBarChildren.length > 0);\n const appContextValue = useMemo(() => ({\n hasDrawer: Boolean(includeDrawer),\n drawerOpen: computedDrawerOpen,\n drawerHovered: computedDrawerHovered,\n openDrawer: handleDrawerOpen,\n closeDrawer: handleDrawerClose,\n closeHover: setOnHoverFalse,\n logo\n }), [includeDrawer, computedDrawerOpen, computedDrawerHovered, handleDrawerOpen, handleDrawerClose, setOnHoverFalse, logo]);\n\n return (\n <AppContext.Provider value={appContextValue}>\n <div\n className={cls(\"flex h-screen w-screen overflow-hidden\",\n \"bg-surface-frame\",\n \"text-surface-900 dark:text-white\", className)}\n style={{\n paddingTop: \"env(safe-area-inset-top)\",\n paddingLeft: \"env(safe-area-inset-left)\",\n paddingRight: \"env(safe-area-inset-right)\",\n paddingBottom: \"env(safe-area-inset-bottom)\",\n height: \"100dvh\",\n ...style\n }}>\n {appBarChildren}\n\n <DrawerWrapper\n displayed={includeDrawer}\n onMouseEnter={setOnHoverTrue}\n onMouseMove={setOnHoverTrue}\n onMouseLeave={setOnHoverFalse}\n open={drawerOpen}\n hovered={onHover}\n setDrawerOpen={setDrawerOpen}>\n {includeDrawer && drawerChildren}\n </DrawerWrapper>\n\n <main\n className=\"flex flex-col grow overflow-auto\">\n\n {hasAppBar && <DrawerHeader/>}\n\n {/* Above the sheet, so it is there on every screen: while\n the realtime connection is down, every live view is\n showing what it last received. */}\n <ConnectionLostBanner className={cls(\"px-2 pt-1\", {\n \"lg:pt-0 lg:pb-2\": padding,\n \"lg:pt-2\": !hasAppBar && padding\n })}/>\n\n {/* While access is simulated, every data view shows\n another identity's rows: say so on every screen. */}\n <RlsSimulationBanner className={cls(\"px-2 pt-1\", {\n \"lg:pt-0 lg:pb-2\": padding,\n \"lg:pt-2\": !hasAppBar && padding\n })}/>\n\n <div\n // The sheet is one lightness step above the frame AND carries a\n // plain hairline on its edge. The step alone (#090a0c to #111316,\n // #eff0f3 to #f8f9fa) is about 3 L* on both themes, under what a\n // dimmed screen renders, and the first pass of this system removed\n // the line on the theory that the step would do its work; the\n // frame and the sheet then read as one black. The reference's own\n // content sheet carries this line. Only in the inset `lg` layout:\n // edge-to-edge on small screens, a border draws at the viewport.\n className={cls(\"bg-surface-sheet\", \"grow overflow-auto m-0\", \"lg:border lg:border-hairline\", {\n \"mt-1 lg:m-0 lg:mx-2 lg:mb-2 lg:rounded-xl\": padding,\n // No app bar means no DrawerHeader spacer above, so inset the\n // panel by the same amount as its sides and bottom.\n // Must come after the padding classes, which reset lg margins.\n \"lg:mt-2\": !hasAppBar && padding,\n \"lg:mt-4\": !hasAppBar && !padding\n })}>\n\n <ErrorBoundary>\n {otherChildren}\n </ErrorBoundary>\n\n </div>\n </main>\n </div>\n </AppContext.Provider>\n );\n },\n equal\n)\n\nconst DrawerHeader = () => {\n return (\n <div className=\"flex flex-col min-h-14\"></div>\n );\n};\n\nfunction DrawerWrapper(props: {\n children: React.ReactNode,\n displayed: boolean,\n open: boolean,\n logo?: string,\n hovered: boolean,\n setDrawerOpen: (open: boolean) => void,\n onMouseEnter: () => void,\n onMouseMove: () => void,\n onMouseLeave: () => void\n}) {\n\n const layoutWidth = !props.displayed ? 0 : (props.open ? DRAWER_WIDTH : 72);\n const visualWidth = !props.displayed ? 0 : ((props.open || props.hovered) ? DRAWER_WIDTH : 72);\n\n const isFloating = props.hovered && !props.open;\n const { t } = useTranslation();\n\n // The drawer is part of the frame, on both themes. When it floats over the\n // sheet it needs an edge, because a frame-coloured panel over the sheet is\n // an object at that moment; docked, it is a region and gets none.\n const innerDrawer = <div\n className={cls(\"h-full overflow-hidden bg-surface-frame\", defaultBorderMixin,\n isFloating ? \"absolute top-0 left-0 bottom-0 z-50 shadow-lg border-r\" : \"relative\")}\n style={{\n width: visualWidth,\n transition: \"left 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, opacity 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, width 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms\"\n }}\n >\n\n <div className={\"flex flex-col h-full\"}>\n {props.children}\n </div>\n\n </div>;\n\n const largeLayout = useLargeLayout();\n if (!largeLayout) {\n if (!props.displayed)\n return null;\n return <>\n <IconButton\n aria-label={t(\"open_menu\")}\n onClick={() => props.setDrawerOpen(true)}\n className=\"absolute sm:top-2 sm:left-4 top-1 left-2\"\n >\n <MenuIcon/>\n </IconButton>\n <Sheet side={\"left\"}\n transparent={true}\n open={props.open}\n onOpenChange={props.setDrawerOpen}\n title={t(\"navigation_drawer\")}\n overlayClassName={\"bg-surface-scrim\"}\n >\n {innerDrawer}\n </Sheet>\n </>;\n }\n\n return (\n <div\n className=\"z-20 relative flex-shrink-0 overflow-visible\"\n onMouseEnter={props.onMouseEnter}\n onMouseMove={props.onMouseMove}\n onMouseLeave={props.onMouseLeave}\n style={{\n width: layoutWidth,\n minWidth: layoutWidth,\n transition: \"left 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, opacity 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms, width 75ms cubic-bezier(0.4, 0, 0.6, 1) 0ms\"\n }}>\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GACL;;CACY,CAAA;AAE7B,GACA,SACJ;AAEA,IAAM,qBAAqB;CACvB,OACI,oBAAC,OAAD,EAAK,WAAU,yBAA8B,CAAA;AAErD;AAEA,SAAS,cAAc,OAUpB;CAEC,MAAM,cAAc,CAAC,MAAM,YAAY,IAAK,MAAM,OAAA,MAAsB;CACxE,MAAM,cAAc,CAAC,MAAM,YAAY,IAAM,MAAM,QAAQ,MAAM,UAAA,MAA0B;CAE3F,MAAM,aAAa,MAAM,WAAW,CAAC,MAAM;CAC3C,MAAM,EAAE,MAAM,eAAe;CAK7B,MAAM,cAAc,oBAAC,OAAD;EAChB,WAAW,IAAI,2CAA2C,oBACtD,aAAa,2DAA2D,UAAU;EACtF,OAAO;GACH,OAAO;GACP,YAAY;EAChB;YAGA,oBAAC,OAAD;GAAK,WAAW;aACX,MAAM;EACN,CAAA;CAEJ,CAAA;CAGL,IAAI,CADgB,eACf,GAAa;EACd,IAAI,CAAC,MAAM,WACP,OAAO;EACX,OAAO,qBAAA,UAAA,EAAA,UAAA,CACH,oBAAC,YAAD;GACI,cAAY,EAAE,WAAW;GACzB,eAAe,MAAM,cAAc,IAAI;GACvC,WAAU;aAEV,oBAAC,UAAD,CAAU,CAAA;EACF,CAAA,GACZ,oBAAC,OAAD;GAAO,MAAM;GACT,aAAa;GACb,MAAM,MAAM;GACZ,cAAc,MAAM;GACpB,OAAO,EAAE,mBAAmB;GAC5B,kBAAkB;aAEjB;EACE,CAAA,CACT,EAAA,CAAA;CACN;CAEA,OACI,oBAAC,OAAD;EACI,WAAU;EACV,cAAc,MAAM;EACpB,aAAa,MAAM;EACnB,cAAc,MAAM;EACpB,OAAO;GACH,OAAO;GACP,UAAU;GACV,YAAY;EAChB;YAEC;CAEA,CAAA;AAEb"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getDefaultFieldId, getFieldId } from "./field_ids.js";
|
|
1
2
|
import { ArrayCustomShapedFieldBinding } from "../form/field_bindings/ArrayCustomShapedFieldBinding.js";
|
|
2
3
|
import { ArrayOfReferencesFieldBinding } from "../form/field_bindings/ArrayOfReferencesFieldBinding.js";
|
|
3
4
|
import { BlockFieldBinding } from "../form/field_bindings/BlockFieldBinding.js";
|
|
@@ -17,7 +18,6 @@ import { GeopointFieldBinding } from "../form/field_bindings/GeopointFieldBindin
|
|
|
17
18
|
import { BinaryFieldBinding } from "../form/field_bindings/BinaryFieldBinding.js";
|
|
18
19
|
import { RelationFieldBinding } from "../form/field_bindings/RelationFieldBinding.js";
|
|
19
20
|
import { UserSelectFieldBinding } from "../form/field_bindings/UserSelectFieldBinding.js";
|
|
20
|
-
import { getDefaultFieldId, getFieldId } from "./field_ids.js";
|
|
21
21
|
import { AlignLeftIcon, CalendarIcon, FlagIcon, FolderUpIcon, GlobeIcon, HashIcon, LinkIcon, ListIcon, ListOrderedIcon, MailIcon, QuoteIcon, RepeatIcon, Rows3Icon, TextIcon, UploadIcon, UserIcon, VoteIcon } from "@rebasepro/ui";
|
|
22
22
|
import { mergeDeep } from "@rebasepro/utils";
|
|
23
23
|
//#region src/components/field_configs.tsx
|
|
@@ -3,7 +3,7 @@ import { EntityHistoryEntry } from "./EntityHistoryEntry.js";
|
|
|
3
3
|
import { useEffect, useRef, useState } from "react";
|
|
4
4
|
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
5
5
|
import { ErrorBoundary, HistoryIcon, IconButton, Label, Tooltip, Typography, cls } from "@rebasepro/ui";
|
|
6
|
-
import { ConfirmationDialog,
|
|
6
|
+
import { ConfirmationDialog, usePermissions, useSnackbarController, useTranslation } from "@rebasepro/app";
|
|
7
7
|
//#region src/components/history/EntityHistoryView.tsx
|
|
8
8
|
/**
|
|
9
9
|
* Entity history tab view. Shows a paginated list of entity revisions
|
|
@@ -12,7 +12,7 @@ import { ConfirmationDialog, useAuthController, useSnackbarController, useTransl
|
|
|
12
12
|
function EntityHistoryView({ entity, collection, formContext, refreshToken }) {
|
|
13
13
|
const { t } = useTranslation();
|
|
14
14
|
const snackbarController = useSnackbarController();
|
|
15
|
-
|
|
15
|
+
const { canEdit } = usePermissions();
|
|
16
16
|
const dirty = formContext?.formex.dirty;
|
|
17
17
|
const slug = collection.slug;
|
|
18
18
|
const entityId = entity?.id;
|
|
@@ -50,6 +50,7 @@ function EntityHistoryView({ entity, collection, formContext, refreshToken }) {
|
|
|
50
50
|
className: "flex items-center justify-center h-full",
|
|
51
51
|
children: /* @__PURE__ */ jsx(Label, { children: t("history_new_entity") ?? "History is only available for existing records" })
|
|
52
52
|
});
|
|
53
|
+
const editable = canEdit(collection, entity.path ?? slug, entity);
|
|
53
54
|
async function doRevert(historyId) {
|
|
54
55
|
setIsReverting(true);
|
|
55
56
|
try {
|
|
@@ -66,8 +67,9 @@ function EntityHistoryView({ entity, collection, formContext, refreshToken }) {
|
|
|
66
67
|
});
|
|
67
68
|
} catch (error) {
|
|
68
69
|
console.error("Error reverting entity:", error);
|
|
70
|
+
const reason = error instanceof Error ? error.message : void 0;
|
|
69
71
|
snackbarController.open({
|
|
70
|
-
message: t("history_revert_error") ?? "Error reverting entity",
|
|
72
|
+
message: [t("history_revert_error") ?? "Error reverting entity", reason].filter(Boolean).join(": "),
|
|
71
73
|
type: "error"
|
|
72
74
|
});
|
|
73
75
|
} finally {
|
|
@@ -102,7 +104,7 @@ function EntityHistoryView({ entity, collection, formContext, refreshToken }) {
|
|
|
102
104
|
entry,
|
|
103
105
|
collection,
|
|
104
106
|
size: "medium",
|
|
105
|
-
actions: /* @__PURE__ */ jsx(Tooltip, {
|
|
107
|
+
actions: editable && /* @__PURE__ */ jsx(Tooltip, {
|
|
106
108
|
title: t("history_revert") ?? "Revert to this version",
|
|
107
109
|
className: "m-2 grow-0 self-start",
|
|
108
110
|
children: /* @__PURE__ */ jsx(IconButton, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EntityHistoryView.js","names":[],"sources":["../../../src/components/history/EntityHistoryView.tsx"],"sourcesContent":["\nimport type { EntityCustomViewParams } from \"@rebasepro/cms-types\";\nimport { useRef, useEffect } from \"react\";\nimport { cls, IconButton, Label, Tooltip, Typography } from \"@rebasepro/ui\";\nimport { ErrorBoundary, HistoryIcon } from \"@rebasepro/ui\";\nimport { EntityHistoryEntry } from \"./EntityHistoryEntry\";\nimport { useSnackbarController, useAuthController, useTranslation } from \"@rebasepro/app\";\nimport { ConfirmationDialog } from \"@rebasepro/app\";\nimport { useState } from \"react\";\nimport { useHistory } from \"../../hooks/useHistory\";\n\n/**\n * Entity history tab view. Shows a paginated list of entity revisions\n * fetched from the backend API. Supports infinite scroll and revert.\n */\nexport function EntityHistoryView<M extends Record<string, unknown>>({\n entity,\n collection,\n formContext,\n refreshToken\n}: EntityCustomViewParams<M> & {\n /** Bumped once per save, so the list picks up the revision it just made. */\n refreshToken?: number;\n}) {\n\n const { t } = useTranslation();\n const snackbarController = useSnackbarController();\n const authController = useAuthController();\n const dirty = formContext?.formex.dirty;\n\n const slug = collection.slug;\n const entityId = entity?.id;\n\n const {\n entries,\n isLoading,\n hasMore,\n loadMore,\n revert\n } = useHistory({\n slug,\n entityId,\n enabled: !!entityId,\n pageSize: 10,\n refreshToken\n });\n\n const [revertHistoryId, setRevertHistoryId] = useState<string | undefined>();\n const [isReverting, setIsReverting] = useState(false);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const loadMoreRef = useRef<HTMLDivElement>(null);\n\n // Intersection observer for infinite scroll\n useEffect(() => {\n const currentContainer = containerRef.current;\n const currentLoadMore = loadMoreRef.current;\n\n if (!currentContainer || !currentLoadMore || !hasMore || isLoading) return;\n\n const observer = new IntersectionObserver(\n (observerEntries) => {\n if (observerEntries[0].isIntersecting && hasMore && !isLoading) {\n loadMore();\n }\n },\n {\n root: currentContainer,\n rootMargin: \"0px 0px 200px 0px\",\n threshold: 0.01\n }\n );\n\n observer.observe(currentLoadMore);\n\n return () => observer.disconnect();\n }, [hasMore, isLoading, entries.length, loadMore]);\n\n if (!entity) {\n return <div className=\"flex items-center justify-center h-full\">\n <Label>{t(\"history_new_entity\") ?? \"History is only available for existing records\"}</Label>\n </div>;\n }\n\n async function doRevert(historyId: string) {\n setIsReverting(true);\n try {\n const revertedValues = await revert(historyId);\n setRevertHistoryId(undefined);\n\n // Reset the form with the reverted values so the UI updates\n // immediately without requiring a page refresh.\n if (formContext?.formex?.resetForm && revertedValues) {\n formContext.formex.resetForm({\n values: revertedValues as M,\n submitCount: 0,\n touched: {}\n });\n }\n\n snackbarController.open({\n message: t(\"history_reverted\") ?? \"Reverted to selected version\",\n type: \"info\"\n });\n } catch (error) {\n console.error(\"Error reverting entity:\", error);\n snackbarController.open({\n message: t(\"history_revert_error\") ?? \"Error reverting entity\",\n type: \"error\"\n });\n } finally {\n setIsReverting(false);\n }\n }\n\n const revertEntry = revertHistoryId\n ? entries.find(e => e.id === revertHistoryId)\n : undefined;\n\n // `p-8` plus a `mt-24` heading were sized for a full-width tab that no\n // longer exists. In the inspector panel that was 96px of nothing above the\n // first revision, and 32px of gutter on each side of a 448px column.\n return <div\n ref={containerRef}\n className={cls(\"relative flex-1 h-full overflow-auto w-full flex flex-col gap-4 p-4 sm:p-5\")}>\n <div className=\"flex flex-col gap-2 max-w-6xl mx-auto w-full\">\n\n {isLoading && entries.length === 0 && (\n <div className=\"flex flex-col gap-4\">\n {[1, 2, 3].map(i => (\n <div key={i} className=\"flex flex-col gap-2 animate-pulse\">\n <div className=\"h-4 w-48 bg-surface-raised rounded\"/>\n <div className=\"h-12 w-full bg-surface-raised rounded-lg border border-hairline-strong\"/>\n </div>\n ))}\n </div>\n )}\n\n {!isLoading && entries.length === 0 && <>\n <Label>\n {t(\"history_empty\") ?? \"No history available\"}\n </Label>\n <Typography variant={\"caption\"}>\n {t(\"history_empty_description\") ?? \"When you save a record, a new version is created and stored in the history.\"}\n </Typography>\n </>}\n\n {entries.map((entry) => (\n <div key={entry.id} className=\"flex flex-col gap-2 w-full\">\n <EntityHistoryEntry\n entry={entry}\n collection={collection}\n size={\"medium\"}\n actions={\n <Tooltip title={t(\"history_revert\") ?? \"Revert to this version\"}\n className={\"m-2 grow-0 self-start\"}>\n <IconButton aria-label={t(\"history_revert\") ?? \"Revert to this version\"}\n onClick={() => {\n if (dirty) {\n snackbarController.open({\n message: t(\"history_revert_dirty\") ?? \"Please save or discard your changes before reverting\",\n type: \"warning\"\n });\n } else {\n setRevertHistoryId(entry.id);\n }\n }}>\n <HistoryIcon/>\n </IconButton>\n </Tooltip>\n }\n />\n </div>\n ))}\n\n {/* Load more sentinel */}\n {entries.length > 0 && (\n <div ref={loadMoreRef} className=\"py-4 text-center\">\n {isLoading && <Label>{t(\"loading\")}</Label>}\n {!hasMore && entries.length > 10 && <Label>{t(\"history_no_more\") ?? \"No more history\"}</Label>}\n </div>\n )}\n </div>\n\n <ErrorBoundary>\n <ConfirmationDialog\n open={Boolean(revertHistoryId)}\n onAccept={() => {\n if (revertHistoryId) doRevert(revertHistoryId);\n }}\n onCancel={() => setRevertHistoryId(undefined)}\n title={<Typography variant={\"subtitle2\"}>{t(\"history_revert_title\") ?? \"Revert data to this version?\"}</Typography>}\n body={revertEntry\n ? <div className=\"p-4\">\n <Typography variant={\"caption\"} color={\"secondary\"}>\n This will save the entity with the values from{\" \"}\n {new Date(revertEntry.updated_at).toLocaleString()}.\n A new history entry will be created for the revert.\n </Typography>\n </div>\n : null\n }\n />\n </ErrorBoundary>\n </div>;\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,kBAAqD,EACjE,QACA,YACA,aACA,gBAID;CAEC,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,qBAAqB,sBAAsB;CAC1B,kBAAkB;CACzC,MAAM,QAAQ,aAAa,OAAO;CAElC,MAAM,OAAO,WAAW;CACxB,MAAM,WAAW,QAAQ;CAEzB,MAAM,EACF,SACA,WACA,SACA,UACA,WACA,WAAW;EACX;EACA;EACA,SAAS,CAAC,CAAC;EACX,UAAU;EACV;CACJ,CAAC;CAED,MAAM,CAAC,iBAAiB,sBAAsB,SAA6B;CAC3E,MA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D,EAAA,UACI,oBAAC,oBAAD;GACI,MAAM,QAAQ,eAAe;GAC7B,gBAAgB;IACZ,IAAI,iBAAiB,SAAS,eAAe;GACjD;GACA,gBAAgB,mBAAmB,KAAA,CAAS;GAC5C,OAAO,oBAAC,YAAD;IAAY,SAAS;cAAc,EAAE,sBAAsB,KAAK;GAA2C,CAAA;GAClH,MAAM,cACA,oBAAC,OAAD;IAAK,WAAU;cACb,qBAAC,YAAD;KAAY,SAAS;KAAW,OAAO;eAAvC;MAAoD;MACD;MAC9C,IAAI,KAAK,YAAY,UAAU,CAAC,CAAC,eAAe;MAAE;KAE3C;;GACX,CAAA,IACH;EAET,CAAA,EACU,CAAA,CACd;;AACT"}
|
|
1
|
+
{"version":3,"file":"EntityHistoryView.js","names":[],"sources":["../../../src/components/history/EntityHistoryView.tsx"],"sourcesContent":["\nimport type { EntityCustomViewParams } from \"@rebasepro/cms-types\";\nimport { useRef, useEffect } from \"react\";\nimport { cls, IconButton, Label, Tooltip, Typography } from \"@rebasepro/ui\";\nimport { ErrorBoundary, HistoryIcon } from \"@rebasepro/ui\";\nimport { EntityHistoryEntry } from \"./EntityHistoryEntry\";\nimport { usePermissions, useSnackbarController, useTranslation } from \"@rebasepro/app\";\nimport { ConfirmationDialog } from \"@rebasepro/app\";\nimport { useState } from \"react\";\nimport { useHistory } from \"../../hooks/useHistory\";\n\n/**\n * Entity history tab view. Shows a paginated list of entity revisions\n * fetched from the backend API. Supports infinite scroll and revert.\n */\nexport function EntityHistoryView<M extends Record<string, unknown>>({\n entity,\n collection,\n formContext,\n refreshToken\n}: EntityCustomViewParams<M> & {\n /** Bumped once per save, so the list picks up the revision it just made. */\n refreshToken?: number;\n}) {\n\n const { t } = useTranslation();\n const snackbarController = useSnackbarController();\n const { canEdit } = usePermissions();\n const dirty = formContext?.formex.dirty;\n\n const slug = collection.slug;\n const entityId = entity?.id;\n\n const {\n entries,\n isLoading,\n hasMore,\n loadMore,\n revert\n } = useHistory({\n slug,\n entityId,\n enabled: !!entityId,\n pageSize: 10,\n refreshToken\n });\n\n const [revertHistoryId, setRevertHistoryId] = useState<string | undefined>();\n const [isReverting, setIsReverting] = useState(false);\n\n const containerRef = useRef<HTMLDivElement>(null);\n const loadMoreRef = useRef<HTMLDivElement>(null);\n\n // Intersection observer for infinite scroll\n useEffect(() => {\n const currentContainer = containerRef.current;\n const currentLoadMore = loadMoreRef.current;\n\n if (!currentContainer || !currentLoadMore || !hasMore || isLoading) return;\n\n const observer = new IntersectionObserver(\n (observerEntries) => {\n if (observerEntries[0].isIntersecting && hasMore && !isLoading) {\n loadMore();\n }\n },\n {\n root: currentContainer,\n rootMargin: \"0px 0px 200px 0px\",\n threshold: 0.01\n }\n );\n\n observer.observe(currentLoadMore);\n\n return () => observer.disconnect();\n }, [hasMore, isLoading, entries.length, loadMore]);\n\n if (!entity) {\n return <div className=\"flex items-center justify-center h-full\">\n <Label>{t(\"history_new_entity\") ?? \"History is only available for existing records\"}</Label>\n </div>;\n }\n\n // A revert writes the record: offered only to someone who may edit it,\n // which no one may while access is simulated.\n const editable = canEdit(collection, entity.path ?? slug, entity);\n\n async function doRevert(historyId: string) {\n setIsReverting(true);\n try {\n const revertedValues = await revert(historyId);\n setRevertHistoryId(undefined);\n\n // Reset the form with the reverted values so the UI updates\n // immediately without requiring a page refresh.\n if (formContext?.formex?.resetForm && revertedValues) {\n formContext.formex.resetForm({\n values: revertedValues as M,\n submitCount: 0,\n touched: {}\n });\n }\n\n snackbarController.open({\n message: t(\"history_reverted\") ?? \"Reverted to selected version\",\n type: \"info\"\n });\n } catch (error) {\n console.error(\"Error reverting entity:\", error);\n const reason = error instanceof Error ? error.message : undefined;\n snackbarController.open({\n message: [t(\"history_revert_error\") ?? \"Error reverting entity\", reason].filter(Boolean).join(\": \"),\n type: \"error\"\n });\n } finally {\n setIsReverting(false);\n }\n }\n\n const revertEntry = revertHistoryId\n ? entries.find(e => e.id === revertHistoryId)\n : undefined;\n\n // `p-8` plus a `mt-24` heading were sized for a full-width tab that no\n // longer exists. In the inspector panel that was 96px of nothing above the\n // first revision, and 32px of gutter on each side of a 448px column.\n return <div\n ref={containerRef}\n className={cls(\"relative flex-1 h-full overflow-auto w-full flex flex-col gap-4 p-4 sm:p-5\")}>\n <div className=\"flex flex-col gap-2 max-w-6xl mx-auto w-full\">\n\n {isLoading && entries.length === 0 && (\n <div className=\"flex flex-col gap-4\">\n {[1, 2, 3].map(i => (\n <div key={i} className=\"flex flex-col gap-2 animate-pulse\">\n <div className=\"h-4 w-48 bg-surface-raised rounded\"/>\n <div className=\"h-12 w-full bg-surface-raised rounded-lg border border-hairline-strong\"/>\n </div>\n ))}\n </div>\n )}\n\n {!isLoading && entries.length === 0 && <>\n <Label>\n {t(\"history_empty\") ?? \"No history available\"}\n </Label>\n <Typography variant={\"caption\"}>\n {t(\"history_empty_description\") ?? \"When you save a record, a new version is created and stored in the history.\"}\n </Typography>\n </>}\n\n {entries.map((entry) => (\n <div key={entry.id} className=\"flex flex-col gap-2 w-full\">\n <EntityHistoryEntry\n entry={entry}\n collection={collection}\n size={\"medium\"}\n actions={editable &&\n <Tooltip title={t(\"history_revert\") ?? \"Revert to this version\"}\n className={\"m-2 grow-0 self-start\"}>\n <IconButton aria-label={t(\"history_revert\") ?? \"Revert to this version\"}\n onClick={() => {\n if (dirty) {\n snackbarController.open({\n message: t(\"history_revert_dirty\") ?? \"Please save or discard your changes before reverting\",\n type: \"warning\"\n });\n } else {\n setRevertHistoryId(entry.id);\n }\n }}>\n <HistoryIcon/>\n </IconButton>\n </Tooltip>\n }\n />\n </div>\n ))}\n\n {/* Load more sentinel */}\n {entries.length > 0 && (\n <div ref={loadMoreRef} className=\"py-4 text-center\">\n {isLoading && <Label>{t(\"loading\")}</Label>}\n {!hasMore && entries.length > 10 && <Label>{t(\"history_no_more\") ?? \"No more history\"}</Label>}\n </div>\n )}\n </div>\n\n <ErrorBoundary>\n <ConfirmationDialog\n open={Boolean(revertHistoryId)}\n onAccept={() => {\n if (revertHistoryId) doRevert(revertHistoryId);\n }}\n onCancel={() => setRevertHistoryId(undefined)}\n title={<Typography variant={\"subtitle2\"}>{t(\"history_revert_title\") ?? \"Revert data to this version?\"}</Typography>}\n body={revertEntry\n ? <div className=\"p-4\">\n <Typography variant={\"caption\"} color={\"secondary\"}>\n This will save the entity with the values from{\" \"}\n {new Date(revertEntry.updated_at).toLocaleString()}.\n A new history entry will be created for the revert.\n </Typography>\n </div>\n : null\n }\n />\n </ErrorBoundary>\n </div>;\n}\n"],"mappings":";;;;;;;;;;;AAeA,SAAgB,kBAAqD,EACjE,QACA,YACA,aACA,gBAID;CAEC,MAAM,EAAE,MAAM,eAAe;CAC7B,MAAM,qBAAqB,sBAAsB;CACjD,MAAM,EAAE,YAAY,eAAe;CACnC,MAAM,QAAQ,aAAa,OAAO;CAElC,MAAM,OAAO,WAAW;CACxB,MAAM,WAAW,QAAQ;CAEzB,MAAM,EACF,SACA,WACA,SACA,UACA,WACA,WAAW;EACX;EACA;EACA,SAAS,CAAC,CAAC;EACX,UAAU;EACV;CACJ,CAAC;CAED,MAAM,CAAC,iBAAiB,sBAAsB,SAA6B;CAC3E,MAAM,CAAC,aAAa,kBAAkB,SAAS,KAAK;CAEpD,MAAM,eAAe,OAAuB,IAAI;CAChD,MAAM,cAAc,OAAuB,IAAI;CAG/C,gBAAgB;EACZ,MAAM,mBAAmB,aAAa;EACtC,MAAM,kBAAkB,YAAY;EAEpC,IAAI,CAAC,oBAAoB,CAAC,mBAAmB,CAAC,WAAW,WAAW;EAEpE,MAAM,WAAW,IAAI,sBAChB,oBAAoB;GACjB,IAAI,gBAAgB,EAAE,CAAC,kBAAkB,WAAW,CAAC,WACjD,SAAS;EAEjB,GACA;GACI,MAAM;GACN,YAAY;GACZ,WAAW;EACf,CACJ;EAEA,SAAS,QAAQ,eAAe;EAEhC,aAAa,SAAS,WAAW;CACrC,GAAG;EAAC;EAAS;EAAW,QAAQ;EAAQ;CAAQ,CAAC;CAEjD,IAAI,CAAC,QACD,OAA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AY,UAAU,CAAC,CAAC,eAAe;MAAE;KAE3C;;GACX,CAAA,IACH;EAET,CAAA,EACU,CAAA,CACd;;AACT"}
|
|
@@ -2,7 +2,8 @@ import React from "react";
|
|
|
2
2
|
import type { AdminCollection } from "@rebasepro/cms-types";
|
|
3
3
|
/**
|
|
4
4
|
* Fetches the latest history entry from the backend API and displays
|
|
5
|
-
* who last edited the entity and when
|
|
5
|
+
* who last edited the entity and when — as the simulated identity while access
|
|
6
|
+
* is simulated, like the History tab.
|
|
6
7
|
*/
|
|
7
8
|
export declare function LastEditedByIndicator({ path, entityId, collection }: {
|
|
8
9
|
path: string;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Entity, Properties } from "@rebasepro/types";
|
|
2
|
+
import { escapeCsvFormula, unescapeCsvFormula } from "@rebasepro/utils";
|
|
2
3
|
interface Header {
|
|
3
4
|
key: string;
|
|
4
5
|
label: string;
|
|
@@ -52,19 +53,7 @@ export interface CsvExportWriter {
|
|
|
52
53
|
finish(): BlobPart[];
|
|
53
54
|
}
|
|
54
55
|
export declare function createCsvExportWriter({ properties, propertiesOrder, additionalHeaders, flattenArrays, dateExportType }: CsvExportWriterParams): CsvExportWriter;
|
|
55
|
-
|
|
56
|
-
* Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a
|
|
57
|
-
* single quote — the standard OWASP mitigation. The apostrophe is consumed by
|
|
58
|
-
* the spreadsheet as "treat the rest as text", so the value reads back intact.
|
|
59
|
-
*/
|
|
60
|
-
export declare function escapeCsvFormula(value: string): string;
|
|
61
|
-
/**
|
|
62
|
-
* The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that
|
|
63
|
-
* is an apostrophe followed by a formula trigger loses the apostrophe, as it
|
|
64
|
-
* does when a spreadsheet reads it. Any other apostrophe is text.
|
|
65
|
-
*/
|
|
66
|
-
export declare function unescapeCsvFormula(value: string): string;
|
|
56
|
+
export { escapeCsvFormula, unescapeCsvFormula };
|
|
67
57
|
export declare function entryToCSVRow(entry: unknown[]): string;
|
|
68
58
|
export declare function downloadBlob(content: BlobPart[], filename: string, contentType: string): void;
|
|
69
59
|
export declare function downloadDataAsCsv(data: object[], name: string): void;
|
|
70
|
-
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { EntityRelation } from "@rebasepro/types";
|
|
2
|
-
import { getArrayValuesCount, getValueInPath } from "@rebasepro/utils";
|
|
2
|
+
import { escapeCsvFormula, getArrayValuesCount, getValueInPath, unescapeCsvFormula } from "@rebasepro/utils";
|
|
3
3
|
//#region src/data_export/export/export.ts
|
|
4
4
|
function downloadEntitiesExport({ data, additionalData, properties, propertiesOrder, name, flattenArrays, additionalHeaders, exportType, dateExportType }) {
|
|
5
5
|
console.debug("Downloading export", {
|
|
@@ -336,41 +336,6 @@ function processValuesForExport(inputValues, properties, exportType, dateExportT
|
|
|
336
336
|
}
|
|
337
337
|
return result;
|
|
338
338
|
}
|
|
339
|
-
/**
|
|
340
|
-
* Characters that make a spreadsheet read a cell as a formula rather than text.
|
|
341
|
-
*
|
|
342
|
-
* Quoting is CSV *escaping* and is not enough: Excel, LibreOffice Calc and
|
|
343
|
-
* Sheets strip the CSV quoting at parse time and then evaluate a cell whose
|
|
344
|
-
* first character is one of these — `=HYPERLINK(…)` exfiltrates neighbouring
|
|
345
|
-
* cells on click, `=cmd|'…'!A0` is worse.
|
|
346
|
-
*/
|
|
347
|
-
var FORMULA_TRIGGERS = [
|
|
348
|
-
"=",
|
|
349
|
-
"+",
|
|
350
|
-
"-",
|
|
351
|
-
"@",
|
|
352
|
-
" ",
|
|
353
|
-
"\r"
|
|
354
|
-
];
|
|
355
|
-
/**
|
|
356
|
-
* Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a
|
|
357
|
-
* single quote — the standard OWASP mitigation. The apostrophe is consumed by
|
|
358
|
-
* the spreadsheet as "treat the rest as text", so the value reads back intact.
|
|
359
|
-
*/
|
|
360
|
-
function escapeCsvFormula(value) {
|
|
361
|
-
const first = value.charAt(0);
|
|
362
|
-
if (!FORMULA_TRIGGERS.includes(first)) return value;
|
|
363
|
-
if ((first === "-" || first === "+") && value.trim() !== "" && Number.isFinite(Number(value))) return value;
|
|
364
|
-
return "'" + value;
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that
|
|
368
|
-
* is an apostrophe followed by a formula trigger loses the apostrophe, as it
|
|
369
|
-
* does when a spreadsheet reads it. Any other apostrophe is text.
|
|
370
|
-
*/
|
|
371
|
-
function unescapeCsvFormula(value) {
|
|
372
|
-
return value.charAt(0) === "'" && FORMULA_TRIGGERS.includes(value.charAt(1)) ? value.slice(1) : value;
|
|
373
|
-
}
|
|
374
339
|
function toCSVCell(v) {
|
|
375
340
|
if (v === null || v === void 0) return "";
|
|
376
341
|
return "\"" + escapeCsvFormula(Array.isArray(v) || typeof v === "object" && !(v instanceof Date) ? JSON.stringify(v) : String(v)).replaceAll("\"", "\"\"") + "\"";
|