|
| 1 | +import { bulkUserManagementStrings } from 'kolibri-common/strings/bulkUserManagementStrings'; |
| 2 | +import useSnackbar from 'kolibri/composables/useSnackbar'; |
| 3 | + |
| 4 | +/** |
| 5 | + * |
| 6 | + * @param {Object} options |
| 7 | + * @param {() => Promise<boolean>} options.action - Callback that executes the action to perform. |
| 8 | + * Should return a boolean promise indicating whether the action was successful. If the action |
| 9 | + * succeeds, the snackbar will display a success message and provide an undo option. |
| 10 | + * |
| 11 | + * @param {() => string} options.actionNotice$ - Function that returns the message to display on |
| 12 | + * the snackbar when the action is successful. |
| 13 | + * |
| 14 | + * @param {() => Promise<void>} options.undoAction - Callback that executes the undo action. |
| 15 | + * Be careful if this action is happening after the component that triggered the original action has |
| 16 | + * been unmounted (e.g. you cannot emit events from an unmounted component). If the undoAction fails |
| 17 | + * the function should throw an error, and a snackbar will be shown with a generic error message. |
| 18 | + * |
| 19 | + * @param {() => string} options.undoActionNotice$ - Function that returns the message to display on |
| 20 | + * the snackbar when the undo action is successful. |
| 21 | + * |
| 22 | + * @param {() => void} [options.onBlur] - Optional callback that executes when the undo button in |
| 23 | + * the snackbar loses focus. |
| 24 | + * |
| 25 | + * @typedef {Object} UseActionWithUndoObject |
| 26 | + * @property {() => Promise<void>} performAction - A method to manually trigger the main action |
| 27 | + * with all the undo machinery set up. |
| 28 | + * |
| 29 | + * @returns {UseActionWithUndoObject} |
| 30 | + */ |
| 31 | +export default function useActionWithUndo({ |
| 32 | + action, |
| 33 | + actionNotice$, |
| 34 | + undoAction, |
| 35 | + undoActionNotice$, |
| 36 | + onBlur, |
| 37 | +}) { |
| 38 | + const { undoAction$, defaultErrorMessage$ } = bulkUserManagementStrings; |
| 39 | + const { createSnackbar, clearSnackbar } = useSnackbar(); |
| 40 | + |
| 41 | + const performUndoAction = async () => { |
| 42 | + clearSnackbar(); |
| 43 | + try { |
| 44 | + await undoAction(); |
| 45 | + createSnackbar(undoActionNotice$()); |
| 46 | + } catch (error) { |
| 47 | + createSnackbar(defaultErrorMessage$()); |
| 48 | + } |
| 49 | + }; |
| 50 | + |
| 51 | + const performAction = async () => { |
| 52 | + const success = await action(); |
| 53 | + if (!success) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + createSnackbar({ |
| 58 | + text: actionNotice$(), |
| 59 | + autofocus: true, |
| 60 | + autoDismiss: true, |
| 61 | + duration: 6000, |
| 62 | + actionText: undoAction$(), |
| 63 | + onBlur, |
| 64 | + actionCallback: performUndoAction, |
| 65 | + }); |
| 66 | + }; |
| 67 | + |
| 68 | + return { |
| 69 | + performAction, |
| 70 | + }; |
| 71 | +} |
0 commit comments