@oneblink/apps-react 4.0.0-beta.6 → 4.0.0-beta.7
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/OneBlinkAutoSaveForm.d.ts +1 -0
- package/dist/OneBlinkAutoSaveForm.js +1 -0
- package/dist/OneBlinkAutoSaveForm.js.map +1 -1
- package/dist/OneBlinkForm.d.ts +2 -0
- package/dist/OneBlinkForm.js +2 -0
- package/dist/OneBlinkForm.js.map +1 -1
- package/dist/OneBlinkReadOnlyForm.d.ts +1 -0
- package/dist/OneBlinkReadOnlyForm.js +1 -0
- package/dist/OneBlinkReadOnlyForm.js.map +1 -1
- package/dist/PaymentReceipt.d.ts +4 -0
- package/dist/PaymentReceipt.js +4 -0
- package/dist/PaymentReceipt.js.map +1 -1
- package/dist/components/formStore/OneBlinkFormStoreClearFiltersButton.d.ts +5 -0
- package/dist/components/formStore/OneBlinkFormStoreClearFiltersButton.js +5 -0
- package/dist/components/formStore/OneBlinkFormStoreClearFiltersButton.js.map +1 -1
- package/dist/components/formStore/OneBlinkFormStoreColumnsButton.d.ts +5 -0
- package/dist/components/formStore/OneBlinkFormStoreColumnsButton.js +5 -0
- package/dist/components/formStore/OneBlinkFormStoreColumnsButton.js.map +1 -1
- package/dist/components/formStore/OneBlinkFormStoreDownloadButton.d.ts +5 -0
- package/dist/components/formStore/OneBlinkFormStoreDownloadButton.js +5 -0
- package/dist/components/formStore/OneBlinkFormStoreDownloadButton.js.map +1 -1
- package/dist/components/formStore/OneBlinkFormStoreProvider.d.ts +5 -0
- package/dist/components/formStore/OneBlinkFormStoreProvider.js +5 -0
- package/dist/components/formStore/OneBlinkFormStoreProvider.js.map +1 -1
- package/dist/components/formStore/OneBlinkFormStoreRefreshButton.d.ts +5 -0
- package/dist/components/formStore/OneBlinkFormStoreRefreshButton.js +5 -0
- package/dist/components/formStore/OneBlinkFormStoreRefreshButton.js.map +1 -1
- package/dist/components/formStore/OneBlinkFormStoreTable.d.ts +4 -0
- package/dist/components/formStore/OneBlinkFormStoreTable.js +4 -0
- package/dist/components/formStore/OneBlinkFormStoreTable.js.map +1 -1
- package/dist/components/pickers/V4CompatibleDatePicker.d.ts +5 -0
- package/dist/components/pickers/V4CompatibleDatePicker.js +5 -0
- package/dist/components/pickers/V4CompatibleDatePicker.js.map +1 -1
- package/dist/components/pickers/V4CompatibleDateTimePicker.d.ts +5 -0
- package/dist/components/pickers/V4CompatibleDateTimePicker.js +5 -0
- package/dist/components/pickers/V4CompatibleDateTimePicker.js.map +1 -1
- package/dist/components/pickers/V4CompatibleTimePicker.d.ts +5 -0
- package/dist/components/pickers/V4CompatibleTimePicker.js +5 -0
- package/dist/components/pickers/V4CompatibleTimePicker.js.map +1 -1
- package/dist/components/renderer/ProgressBar.d.ts +5 -0
- package/dist/components/renderer/ProgressBar.js +5 -0
- package/dist/components/renderer/ProgressBar.js.map +1 -1
- package/dist/hooks/useAuth.d.ts +3 -1
- package/dist/hooks/useAuth.js +3 -1
- package/dist/hooks/useAuth.js.map +1 -1
- package/dist/hooks/useBooleanState.d.ts +1 -0
- package/dist/hooks/useBooleanState.js +1 -0
- package/dist/hooks/useBooleanState.js.map +1 -1
- package/dist/hooks/useClickOutsideElement.d.ts +1 -0
- package/dist/hooks/useClickOutsideElement.js +1 -0
- package/dist/hooks/useClickOutsideElement.js.map +1 -1
- package/dist/hooks/useDrafts.d.ts +3 -1
- package/dist/hooks/useDrafts.js +3 -1
- package/dist/hooks/useDrafts.js.map +1 -1
- package/dist/hooks/useFormSubmissionAutoSaveState.d.ts +1 -0
- package/dist/hooks/useFormSubmissionAutoSaveState.js +1 -0
- package/dist/hooks/useFormSubmissionAutoSaveState.js.map +1 -1
- package/dist/hooks/useFormSubmissionState.d.ts +1 -0
- package/dist/hooks/useFormSubmissionState.js +1 -0
- package/dist/hooks/useFormSubmissionState.js.map +1 -1
- package/dist/hooks/useIsMounted.d.ts +1 -0
- package/dist/hooks/useIsMounted.js +1 -0
- package/dist/hooks/useIsMounted.js.map +1 -1
- package/dist/hooks/useIsOffline.d.ts +5 -0
- package/dist/hooks/useIsOffline.js +5 -0
- package/dist/hooks/useIsOffline.js.map +1 -1
- package/dist/hooks/useLoadDataState.d.ts +2 -0
- package/dist/hooks/useLoadDataState.js +2 -0
- package/dist/hooks/useLoadDataState.js.map +1 -1
- package/dist/hooks/useLogin.d.ts +4 -2
- package/dist/hooks/useLogin.js +1 -0
- package/dist/hooks/useLogin.js.map +1 -1
- package/dist/hooks/useNullableState.d.ts +2 -0
- package/dist/hooks/useNullableState.js +2 -0
- package/dist/hooks/useNullableState.js.map +1 -1
- package/dist/hooks/usePendingSubmissions.d.ts +9 -1
- package/dist/hooks/usePendingSubmissions.js +17 -14
- package/dist/hooks/usePendingSubmissions.js.map +1 -1
- package/dist/hooks/useSignUp.d.ts +5 -0
- package/dist/hooks/useSignUp.js +5 -0
- package/dist/hooks/useSignUp.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"useDrafts.js","sourceRoot":"","sources":["../../src/hooks/useDrafts.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAEhE,OAAO,OAAO,MAAM,WAAW,CAAA;AAC/B,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AA0BzC,MAAM,gBAAgB,GAAG;IACvB,SAAS,EAAE,KAAK;IAChB,SAAS,EAAE,IAAI;IACf,MAAM,EAAE,EAAE;CACX,CAAA;AAED,MAAM,gBAAgB,GAAG;IACvB,SAAS,EAAE,KAAK;IAChB,SAAS,EAAE,IAAI;CAChB,CAAA;AAED,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,CACvC,SAAS,CACV,CAAA;AAED;;;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,CAAC,YAAY,CAAC,CAAC,CAAA;IAElB,KAAK,CAAC,SAAS,CAAC,GAAG,EAAE;QACnB,IAAI,CAAC,SAAS,EAAE;YACd,UAAU,EAAE,CAAA;SACb;IACH,CAAC,EAAE,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAA;IAE3B,OAAO,CACL,oBAAC,aAAa,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,IAAG,QAAQ,CAA0B,CAC1E,CAAA;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,OAAO,UAAU,SAAS;IAC/B,MAAM,KAAK,GAAG,KAAK,CAAC,UAAU,CAAC,aAAa,CAAC,CAAA;IAC7C,IAAI,CAAC,KAAK,EAAE;QACV,MAAM,IAAI,KAAK,CACb,4FAA4F,CAC7F,CAAA;KACF;IACD,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import * as React from 'react'\nimport { draftService, submissionService } from '@oneblink/apps'\nimport { SubmissionTypes } from '@oneblink/types'\nimport useAuth from './useAuth'\nimport useIsMounted from './useIsMounted'\nimport useIsOffline from './useIsOffline'\n\n/** The value returned from `useDrafts()` hook */\nexport type DraftsContextValue = {\n /** `true` drafts are currently loading. */\n isLoading: boolean\n /** An Error object if loading drafts fails */\n loadError: Error | null\n /** The incomplete submissions that were saved for later */\n drafts: SubmissionTypes.FormsAppDraft[]\n /** A function to trigger loading of the drafts */\n reloadDrafts: () => unknown\n /** A function to clear Error object from loading drafts */\n clearLoadError: () => void\n /** `true` drafts are syncing with other devices */\n isSyncing: boolean\n /** A function to trigger syncing of the drafts */\n syncDrafts: () => unknown\n /** An Error object if syncing drafts fails */\n syncError: Error | null\n /** A function to clear Error object from syncing drafts */\n clearSyncError: () => void\n /** A function to remove a draft */\n deleteDraft: (draftId: string) => Promise<void>\n}\n\nconst defaultLoadState = {\n isLoading: false,\n loadError: null,\n drafts: [],\n}\n\nconst defaultSyncState = {\n isSyncing: false,\n syncError: null,\n}\n\nconst DraftsContext = React.createContext<DraftsContextValue | undefined>(\n undefined,\n)\n\n/**\n * React Component that provides the context for the `useDrafts()` hook to be\n * used by components further down your component tree. **It should only be\n * included in your component tree once and ideally at the root of the\n * application.**\n *\n * #### Example\n *\n * ```jsx\n * import * as React from 'react'\n * import { DraftsContextProvider } from '@oneblink/apps-react'\n *\n * function Component() {\n * const draftsContext = useDrafts()\n * // use drafts here\n * }\n *\n * function App() {\n * return (\n * <DraftsContextProvider>\n * <Component />\n * </DraftsContextProvider>\n * )\n * }\n *\n * const root = document.getElementById('root')\n * if (root) {\n * ReactDOM.render(<App />, root)\n * }\n * ```\n *\n * @param props\n * @returns\n */\nexport function DraftsContextProvider({\n /** The identifier for the forms app associated with the user's drafts */\n formsAppId,\n /**\n * `true` if drafts are enabled, otherwise `false`. Can be used for account\n * tier validation.\n */\n isDraftsEnabled,\n /** Your application components */\n children,\n}: {\n formsAppId: number\n isDraftsEnabled: boolean\n children: React.ReactNode\n}) {\n const isMounted = useIsMounted()\n const isOffline = useIsOffline()\n const { isLoggedIn, isUsingFormsKey } = useAuth()\n\n const [syncState, setSyncState] = React.useState<{\n isSyncing: boolean\n syncError: Error | null\n }>(defaultSyncState)\n const clearSyncError = React.useCallback(() => {\n setSyncState((currentState) => ({\n ...currentState,\n syncError: null,\n }))\n }, [])\n const syncDrafts = React.useCallback(async () => {\n if (!isDraftsEnabled || !isLoggedIn || isUsingFormsKey) {\n return\n }\n\n if (isMounted.current) {\n setSyncState({\n isSyncing: true,\n syncError: null,\n })\n }\n\n let newError = null\n\n try {\n await draftService.syncDrafts({\n formsAppId,\n throwError: false,\n })\n } catch (error) {\n newError = error as Error\n }\n\n if (isMounted.current) {\n setSyncState({\n isSyncing: false,\n syncError: newError,\n })\n }\n }, [formsAppId, isDraftsEnabled, isLoggedIn, isMounted, isUsingFormsKey])\n\n const [loadState, setLoadState] = React.useState<{\n isLoading: boolean\n loadError: Error | null\n drafts: SubmissionTypes.FormsAppDraft[]\n }>(defaultLoadState)\n const clearLoadError = React.useCallback(() => {\n setLoadState((currentState) => ({\n ...currentState,\n loadError: null,\n }))\n }, [])\n const reloadDrafts = React.useCallback(async () => {\n if (!isLoggedIn) {\n if (isMounted.current) {\n setLoadState({\n isLoading: false,\n loadError: null,\n drafts: [],\n })\n }\n return\n }\n\n if (isMounted.current) {\n setLoadState((currentState) => ({\n isLoading: true,\n loadError: null,\n drafts: currentState.drafts,\n }))\n }\n\n let newError = null\n let newDrafts: SubmissionTypes.FormsAppDraft[] = []\n\n try {\n newDrafts = await draftService.getDrafts()\n } catch (error) {\n newError = error as Error\n }\n\n if (isMounted.current) {\n setLoadState({\n isLoading: false,\n loadError: newError,\n drafts: newDrafts,\n })\n }\n }, [isMounted, isLoggedIn])\n\n const deleteDraft = React.useCallback(\n (draftId) => {\n return draftService.deleteDraft(draftId, formsAppId)\n },\n [formsAppId],\n )\n\n const value = React.useMemo(\n () => ({\n // Sync\n syncDrafts,\n isSyncing: syncState.isSyncing,\n syncError: syncState.syncError,\n clearSyncError,\n // Load\n reloadDrafts,\n isLoading: loadState.isLoading,\n drafts: loadState.drafts,\n loadError: loadState.loadError,\n clearLoadError,\n // Delete,\n deleteDraft,\n }),\n [\n clearLoadError,\n clearSyncError,\n loadState.drafts,\n loadState.isLoading,\n loadState.loadError,\n reloadDrafts,\n syncDrafts,\n syncState.isSyncing,\n syncState.syncError,\n deleteDraft,\n ],\n )\n\n React.useEffect(() => {\n reloadDrafts()\n const unregisterPendingQueueListener =\n submissionService.registerPendingQueueListener(reloadDrafts)\n const unregisterDraftsListener = draftService.registerDraftsListener(\n (drafts) => {\n setLoadState({\n isLoading: false,\n drafts,\n loadError: null,\n })\n },\n )\n return () => {\n unregisterPendingQueueListener()\n unregisterDraftsListener()\n }\n }, [reloadDrafts])\n\n React.useEffect(() => {\n if (!isOffline) {\n syncDrafts()\n }\n }, [isOffline, syncDrafts])\n\n return (\n <DraftsContext.Provider value={value}>{children}</DraftsContext.Provider>\n )\n}\n\n/**\n * React hook to get the context value for Drafts. Will throw an Error if used\n * outside of the `<DraftsContextProvider />` component.\n *\n * @returns\n */\nexport default function useDrafts(): DraftsContextValue {\n const value = React.useContext(DraftsContext)\n if (!value) {\n throw new Error(\n `\"useDrafts\" hook was used outside of the \"<DraftsContextProvider />\" component's children.`,\n )\n }\n return value\n}\n"]}
|
1
|
+
{"version":3,"file":"useDrafts.js","sourceRoot":"","sources":["../../src/hooks/useDrafts.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAE,MAAM,gBAAgB,CAAA;AAEhE,OAAO,OAAO,MAAM,WAAW,CAAA;AAC/B,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,YAAY,MAAM,gBAAgB,CAAA;AA0BzC,MAAM,gBAAgB,GAAG;IACvB,SAAS,EAAE,KAAK;IAChB,SAAS,EAAE,IAAI;IACf,MAAM,EAAE,EAAE;CACX,CAAA;AAED,MAAM,gBAAgB,GAAG;IACvB,SAAS,EAAE,KAAK;IAChB,SAAS,EAAE,IAAI;CAChB,CAAA;AAED,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,CACvC,SAAS,CACV,CAAA;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,MAAM,UAAU,qBAAqB,CAAC;AACpC,yEAAyE;AACzE,UAAU;AACV;;;GAGG;AACH,eAAe;AACf,kCAAkC;AAClC,QAAQ,GAKT;IACC,MAAM,SAAS,GAAG,YAAY,EAAE,CAAA;IAChC,MAAM,SAAS,GAAG,YAAY,EAAE,CAAA;IAChC,MAAM,EAAE,UAAU,EAAE,eAAe,EAAE,GAAG,OAAO,EAAE,CAAA;IAEjD,MAAM,CAAC,SAAS,EAAE,YAAY,CAAC,GAAG,KAAK,CAAC,QAAQ,CAG7C,gBAAgB,CAAC,CAAA;IACpB,MAAM,cAAc,GAAG,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE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M,IAAI,KAAK,CACb,4FAA4F,CAC7F,CAAA;KACF;IACD,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import * as React from 'react'\nimport { draftService, submissionService } from '@oneblink/apps'\nimport { SubmissionTypes } from '@oneblink/types'\nimport useAuth from './useAuth'\nimport useIsMounted from './useIsMounted'\nimport useIsOffline from './useIsOffline'\n\n/** The value returned from `useDrafts()` hook */\nexport type DraftsContextValue = {\n /** `true` drafts are currently loading. */\n isLoading: boolean\n /** An Error object if loading drafts fails */\n loadError: Error | null\n /** The incomplete submissions that were saved for later */\n drafts: SubmissionTypes.FormsAppDraft[]\n /** A function to trigger loading of the drafts */\n reloadDrafts: () => unknown\n /** A function to clear Error object from loading drafts */\n clearLoadError: () => void\n /** `true` drafts are syncing with other devices */\n isSyncing: boolean\n /** A function to trigger syncing of the drafts */\n syncDrafts: () => unknown\n /** An Error object if syncing drafts fails */\n syncError: Error | null\n /** A function to clear Error object from syncing drafts */\n clearSyncError: () => void\n /** A function to remove a draft */\n deleteDraft: (draftId: string) => Promise<void>\n}\n\nconst defaultLoadState = {\n isLoading: false,\n loadError: null,\n drafts: [],\n}\n\nconst defaultSyncState = {\n isSyncing: false,\n syncError: null,\n}\n\nconst DraftsContext = React.createContext<DraftsContextValue | undefined>(\n undefined,\n)\n\n/**\n * React Component that provides the context for the `useDrafts()` hook to be\n * used by components further down your component tree. **It should only be\n * included in your component tree once and ideally at the root of the\n * application.**\n *\n * #### Example\n *\n * ```jsx\n * import * as React from 'react'\n * import { DraftsContextProvider, useDrafts } from '@oneblink/apps-react'\n *\n * function Component() {\n * const draftsContext = useDrafts()\n * // use drafts here\n * }\n *\n * function App() {\n * return (\n * <DraftsContextProvider>\n * <Component />\n * </DraftsContextProvider>\n * )\n * }\n *\n * const root = document.getElementById('root')\n * if (root) {\n * ReactDOM.render(<App />, root)\n * }\n * ```\n *\n * @param props\n * @returns\n * @group Components\n */\nexport function DraftsContextProvider({\n /** The identifier for the forms app associated with the user's drafts */\n formsAppId,\n /**\n * `true` if drafts are enabled, otherwise `false`. Can be used for account\n * tier validation.\n */\n isDraftsEnabled,\n /** Your application components */\n children,\n}: {\n formsAppId: number\n isDraftsEnabled: boolean\n children: React.ReactNode\n}) {\n const isMounted = useIsMounted()\n const isOffline = useIsOffline()\n const { isLoggedIn, isUsingFormsKey } = useAuth()\n\n const [syncState, setSyncState] = React.useState<{\n isSyncing: boolean\n syncError: Error | null\n }>(defaultSyncState)\n const clearSyncError = React.useCallback(() => {\n setSyncState((currentState) => ({\n ...currentState,\n syncError: null,\n }))\n }, [])\n const syncDrafts = React.useCallback(async () => {\n if (!isDraftsEnabled || !isLoggedIn || isUsingFormsKey) {\n return\n }\n\n if (isMounted.current) {\n setSyncState({\n isSyncing: true,\n syncError: null,\n })\n }\n\n let newError = null\n\n try {\n await draftService.syncDrafts({\n formsAppId,\n throwError: false,\n })\n } catch (error) {\n newError = error as Error\n }\n\n if (isMounted.current) {\n setSyncState({\n isSyncing: false,\n syncError: newError,\n })\n }\n }, [formsAppId, isDraftsEnabled, isLoggedIn, isMounted, isUsingFormsKey])\n\n const [loadState, setLoadState] = React.useState<{\n isLoading: boolean\n loadError: Error | null\n drafts: SubmissionTypes.FormsAppDraft[]\n }>(defaultLoadState)\n const clearLoadError = React.useCallback(() => {\n setLoadState((currentState) => ({\n ...currentState,\n loadError: null,\n }))\n }, [])\n const reloadDrafts = React.useCallback(async () => {\n if (!isLoggedIn) {\n if (isMounted.current) {\n setLoadState({\n isLoading: false,\n loadError: null,\n drafts: [],\n })\n }\n return\n }\n\n if (isMounted.current) {\n setLoadState((currentState) => ({\n isLoading: true,\n loadError: null,\n drafts: currentState.drafts,\n }))\n }\n\n let newError = null\n let newDrafts: SubmissionTypes.FormsAppDraft[] = []\n\n try {\n newDrafts = await draftService.getDrafts()\n } catch (error) {\n newError = error as Error\n }\n\n if (isMounted.current) {\n setLoadState({\n isLoading: false,\n loadError: newError,\n drafts: newDrafts,\n })\n }\n }, [isMounted, isLoggedIn])\n\n const deleteDraft = React.useCallback(\n (draftId) => {\n return draftService.deleteDraft(draftId, formsAppId)\n },\n [formsAppId],\n )\n\n const value = React.useMemo(\n () => ({\n // Sync\n syncDrafts,\n isSyncing: syncState.isSyncing,\n syncError: syncState.syncError,\n clearSyncError,\n // Load\n reloadDrafts,\n isLoading: loadState.isLoading,\n drafts: loadState.drafts,\n loadError: loadState.loadError,\n clearLoadError,\n // Delete,\n deleteDraft,\n }),\n [\n clearLoadError,\n clearSyncError,\n loadState.drafts,\n loadState.isLoading,\n loadState.loadError,\n reloadDrafts,\n syncDrafts,\n syncState.isSyncing,\n syncState.syncError,\n deleteDraft,\n ],\n )\n\n React.useEffect(() => {\n reloadDrafts()\n const unregisterPendingQueueListener =\n submissionService.registerPendingQueueListener(reloadDrafts)\n const unregisterDraftsListener = draftService.registerDraftsListener(\n (drafts) => {\n setLoadState({\n isLoading: false,\n drafts,\n loadError: null,\n })\n },\n )\n return () => {\n unregisterPendingQueueListener()\n unregisterDraftsListener()\n }\n }, [reloadDrafts])\n\n React.useEffect(() => {\n if (!isOffline) {\n syncDrafts()\n }\n }, [isOffline, syncDrafts])\n\n return (\n <DraftsContext.Provider value={value}>{children}</DraftsContext.Provider>\n )\n}\n\n/**\n * React hook to get the context value for Drafts. Will throw an Error if used\n * outside of the `<DraftsContextProvider />` component.\n *\n * @returns\n * @group Hooks\n */\nexport default function useDrafts(): DraftsContextValue {\n const value = React.useContext(DraftsContext)\n if (!value) {\n throw new Error(\n `\"useDrafts\" hook was used outside of the \"<DraftsContextProvider />\" component's children.`,\n )\n }\n return value\n}\n"]}
|
@@ -9,6 +9,7 @@ import { FormTypes, SubmissionTypes } from '@oneblink/types';
|
|
9
9
|
*
|
10
10
|
* @param options
|
11
11
|
* @returns
|
12
|
+
* @group Hooks
|
12
13
|
*/
|
13
14
|
export default function useFormSubmissionAutoSaveState({ form, initialSubmission, resumeAtElement, removeAutoSaveDataBeforeSubmit, removeAutoSaveDataBeforeSaveDraft, autoSaveKey, onCancel, onSubmit, onSaveDraft, }: {
|
14
15
|
form: FormTypes.Form;
|
@@ -10,6 +10,7 @@ import useFormSubmissionState from './useFormSubmissionState';
|
|
10
10
|
*
|
11
11
|
* @param options
|
12
12
|
* @returns
|
13
|
+
* @group Hooks
|
13
14
|
*/
|
14
15
|
export default function useFormSubmissionAutoSaveState({ form, initialSubmission, resumeAtElement, removeAutoSaveDataBeforeSubmit, removeAutoSaveDataBeforeSaveDraft, autoSaveKey, onCancel, onSubmit, onSaveDraft, }) {
|
15
16
|
const [{ definition, submission, lastElementUpdated }, setFormSubmission] = useFormSubmissionState(form, initialSubmission, resumeAtElement);
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"useFormSubmissionAutoSaveState.js","sourceRoot":"","sources":["../../src/hooks/useFormSubmissionAutoSaveState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,SAAS,MAAM,iBAAiB,CAAA;AACvC,OAAO,EAAE,eAAe,EAAqB,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAE3E,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAG7D;;;;;;;;GAQG;AACH,MAAM,CAAC,OAAO,UAAU,8BAA8B,CAAC,EACrD,IAAI,EACJ,iBAAiB,EACjB,eAAe,EACf,8BAA8B,EAC9B,iCAAiC,EACjC,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,WAAW,GAaZ;IACC,MAAM,CAAC,EAAE,UAAU,EAAE,UAAU,EAAE,kBAAkB,EAAE,EAAE,iBAAiB,CAAC,GACvE,sBAAsB,CAAC,IAAI,EAAE,iBAAiB,EAAE,eAAe,CAAC,CAAA;IAElE,MAAM,CACJ,EAAE,2BAA2B,EAAE,kBAAkB,EAAE,eAAe,EAAE,EACpE,gBAAgB,EACjB,GAAG,KAAK,CAAC,QAAQ,CAIf;QACD,2BAA2B,EAAE,IAAI;QACjC,kBAAkB,EAAE,IAAI;QACxB,eAAe,EA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,KAAK,IAAI;QAC1D,kBAAkB;QAClB,0BAA0B;QAC1B,YAAY;QACZ,YAAY;QACZ,eAAe;QACf,kBAAkB;QAClB,iBAAiB,EAAE,yBAAyB;KAC7C,CAAA;AACH,CAAC","sourcesContent":["import * as React from 'react'\nimport _throttle from 'lodash.throttle'\nimport { autoSaveService, submissionService, Sentry } from '@oneblink/apps'\nimport { FormTypes, SubmissionTypes } from '@oneblink/types'\nimport useFormSubmissionState from './useFormSubmissionState'\nimport { FormElement } from '@oneblink/types/typescript/forms'\n\n/**\n * Use this if you want to implement a controlled auto saving form. See\n * {@link OneBlinkFormControlled} for a full example. If you do not need to\n * control the `submission` or `definition` properties, you can use the\n * {@link OneBlinkAutoSaveForm} component.\n *\n * @param options\n * @returns\n */\nexport default function useFormSubmissionAutoSaveState({\n form,\n initialSubmission,\n resumeAtElement,\n removeAutoSaveDataBeforeSubmit,\n removeAutoSaveDataBeforeSaveDraft,\n autoSaveKey,\n onCancel,\n onSubmit,\n onSaveDraft,\n}: {\n form: FormTypes.Form\n removeAutoSaveDataBeforeSubmit?: boolean\n removeAutoSaveDataBeforeSaveDraft?: boolean\n autoSaveKey: string\n onCancel: () => unknown\n onSubmit: (newFormSubmission: submissionService.NewFormSubmission) => unknown\n initialSubmission?: SubmissionTypes.S3SubmissionData['submission']\n resumeAtElement?: FormTypes.FormElement\n onSaveDraft?: (\n newDraftSubmission: submissionService.NewDraftSubmission,\n ) => unknown\n}) {\n const [{ definition, submission, lastElementUpdated }, setFormSubmission] =\n useFormSubmissionState(form, initialSubmission, resumeAtElement)\n\n const [\n { isLoadingAutoSaveSubmission, autoSaveSubmission, autoSaveElement },\n setAutoSaveState,\n ] = React.useState<{\n isLoadingAutoSaveSubmission: boolean\n autoSaveSubmission: SubmissionTypes.S3SubmissionData['submission'] | null\n autoSaveElement: FormElement | null\n }>({\n isLoadingAutoSaveSubmission: true,\n autoSaveSubmission: null,\n autoSaveElement: null,\n })\n\n const throttledAutoSave = React.useMemo(() => {\n return _throttle(\n (\n model: SubmissionTypes.S3SubmissionData['submission'],\n lastElementUpdated?: FormElement,\n ) => {\n console.log('Auto saving...')\n autoSaveService\n .upsertAutoSaveData(definition.id, autoSaveKey, model)\n .then(() => {\n if (lastElementUpdated) {\n return autoSaveService.upsertAutoSaveData<FormElement>(\n definition.id,\n `LAST_ELEMENT_UPDATED_${autoSaveKey}`,\n lastElementUpdated,\n )\n }\n })\n .catch((error) => {\n console.warn('Error while auto saving', error)\n Sentry.captureException(error)\n })\n },\n 9580, // https://en.wikipedia.org/wiki/100_metres\n { trailing: true, leading: false },\n )\n }, [autoSaveKey, definition.id])\n\n const cancelAutoSave = React.useCallback(() => {\n if (throttledAutoSave) {\n throttledAutoSave.cancel()\n }\n }, [throttledAutoSave])\n\n const deleteAutoSaveSubmission = React.useCallback(() => {\n return autoSaveService\n .deleteAutoSaveData(definition.id, autoSaveKey)\n .catch((error) => {\n console.warn('Error removing auto save data: ', error)\n Sentry.captureException(error)\n })\n }, [autoSaveKey, definition.id])\n\n const handleSubmit = React.useCallback(\n (submissionResult: submissionService.NewFormSubmission) => {\n cancelAutoSave()\n if (removeAutoSaveDataBeforeSubmit !== false) {\n deleteAutoSaveSubmission()\n }\n onSubmit(submissionResult)\n },\n [\n cancelAutoSave,\n deleteAutoSaveSubmission,\n onSubmit,\n removeAutoSaveDataBeforeSubmit,\n ],\n )\n\n const handleSaveDraft = React.useMemo(() => {\n if (onSaveDraft) {\n return (newDraftSubmission: submissionService.NewDraftSubmission) => {\n cancelAutoSave()\n if (removeAutoSaveDataBeforeSaveDraft !== false) {\n deleteAutoSaveSubmission()\n }\n if (onSaveDraft) {\n onSaveDraft(newDraftSubmission)\n }\n }\n }\n }, [\n cancelAutoSave,\n deleteAutoSaveSubmission,\n onSaveDraft,\n removeAutoSaveDataBeforeSaveDraft,\n ])\n\n const handleNavigateAway = React.useCallback(() => {\n cancelAutoSave()\n deleteAutoSaveSubmission()\n }, [cancelAutoSave, deleteAutoSaveSubmission])\n\n const handleCancel = React.useCallback(() => {\n cancelAutoSave()\n deleteAutoSaveSubmission()\n onCancel()\n }, [cancelAutoSave, deleteAutoSaveSubmission, onCancel])\n\n React.useEffect(() => {\n let ignore = false\n const loadAutoSaveData = async () => {\n try {\n const autoSaveSubmission = await autoSaveService.getAutoSaveData<\n SubmissionTypes.S3SubmissionData['submission']\n >(definition.id, autoSaveKey)\n const autoSaveElement =\n await autoSaveService.getAutoSaveData<FormElement>(\n definition.id,\n `LAST_ELEMENT_UPDATED_${autoSaveKey}`,\n )\n if (!ignore) {\n setAutoSaveState({\n isLoadingAutoSaveSubmission: false,\n autoSaveSubmission,\n autoSaveElement,\n })\n }\n } catch (error) {\n console.warn('Error loading auto save data', error)\n Sentry.captureException(error)\n if (!ignore) {\n setAutoSaveState({\n isLoadingAutoSaveSubmission: false,\n autoSaveSubmission: null,\n autoSaveElement: null,\n })\n }\n }\n }\n loadAutoSaveData()\n return () => {\n ignore = true\n }\n }, [autoSaveKey, definition.id])\n\n // Clean up throttle function on unmount\n React.useEffect(() => {\n return () => {\n cancelAutoSave()\n }\n }, [cancelAutoSave])\n\n const setFormSubmissionAutoSave: typeof setFormSubmission = React.useCallback(\n (formSubmission) => {\n setFormSubmission((currentFormSubmission) => {\n const newFormSubmission =\n typeof formSubmission === 'function'\n ? formSubmission(currentFormSubmission)\n : formSubmission\n\n throttledAutoSave(\n newFormSubmission.submission,\n newFormSubmission.lastElementUpdated,\n )\n\n return newFormSubmission\n })\n },\n [setFormSubmission, throttledAutoSave],\n )\n\n const startNewSubmission = React.useCallback(() => {\n deleteAutoSaveSubmission()\n setAutoSaveState({\n isLoadingAutoSaveSubmission: false,\n autoSaveSubmission: null,\n autoSaveElement: null,\n })\n }, [deleteAutoSaveSubmission])\n\n const continueAutoSaveSubmission = React.useCallback(() => {\n if (autoSaveSubmission) {\n setFormSubmission((currentFormSubmission) => ({\n ...currentFormSubmission,\n submission: autoSaveSubmission,\n lastElementUpdated: autoSaveElement ? autoSaveElement : undefined,\n }))\n }\n setAutoSaveState({\n isLoadingAutoSaveSubmission: false,\n autoSaveSubmission: null,\n autoSaveElement: null,\n })\n }, [autoSaveSubmission, setFormSubmission, autoSaveElement])\n\n return {\n definition,\n submission,\n lastElementUpdated,\n isLoadingAutoSaveSubmission,\n isAutoSaveSubmissionAvailable: autoSaveSubmission !== null,\n startNewSubmission,\n continueAutoSaveSubmission,\n handleSubmit,\n handleCancel,\n handleSaveDraft,\n handleNavigateAway,\n setFormSubmission: setFormSubmissionAutoSave,\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"useFormSubmissionAutoSaveState.js","sourceRoot":"","sources":["../../src/hooks/useFormSubmissionAutoSaveState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,SAAS,MAAM,iBAAiB,CAAA;AACvC,OAAO,EAAE,eAAe,EAAqB,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAE3E,OAAO,sBAAsB,MAAM,0BAA0B,CAAA;AAG7D;;;;;;;;;GASG;AACH,MAAM,CAAC,OAAO,UAAU,8BAA8B,CAAC,EACrD,IAAI,EACJ,iBAAiB,EACjB,eAAe,EACf,8BAA8B,EAC9B,iCAAiC,EACjC,WAAW,EACX,QAAQ,EACR,QAAQ,EACR,WAAW,GAaZ;IACC,MAAM,CAAC,EAAE,UAAU,EAAE,UAAU,EAAE,kBAAkB,EAAE,EAAE,iBAAiB,CAAC,GACvE,sBAAsB,CAAC,IAAI,EAAE,iBAAiB,EAAE,eAAe,CAAC,CAAA;IAElE,MAAM,CACJ,EAAE,2BAA2B,EAAE,kBAAkB,EAAE,eAAe,EAAE,EACpE,gBAAgB,EACjB,GAAG,KAAK,CAAC,QAAQ,CAIf;QACD,2BAA2B,EAAE,IAAI;QACjC,kBAAkB,EAAE,IAAI;QACxB,eAAe,EAAE,IAAI;KACtB,CAAC,CAAA;IAEF,MAAM,iBAAiB,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,EAA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AAkB;QAClB,iBAAiB,EAAE,yBAAyB;KAC7C,CAAA;AACH,CAAC","sourcesContent":["import * as React from 'react'\nimport _throttle from 'lodash.throttle'\nimport { autoSaveService, submissionService, Sentry } from '@oneblink/apps'\nimport { FormTypes, SubmissionTypes } from '@oneblink/types'\nimport useFormSubmissionState from './useFormSubmissionState'\nimport { FormElement } from '@oneblink/types/typescript/forms'\n\n/**\n * Use this if you want to implement a controlled auto saving form. See\n * {@link OneBlinkFormControlled} for a full example. If you do not need to\n * control the `submission` or `definition` properties, you can use the\n * {@link OneBlinkAutoSaveForm} component.\n *\n * @param options\n * @returns\n * @group Hooks\n */\nexport default function useFormSubmissionAutoSaveState({\n form,\n initialSubmission,\n resumeAtElement,\n removeAutoSaveDataBeforeSubmit,\n removeAutoSaveDataBeforeSaveDraft,\n autoSaveKey,\n onCancel,\n onSubmit,\n onSaveDraft,\n}: {\n form: FormTypes.Form\n removeAutoSaveDataBeforeSubmit?: boolean\n removeAutoSaveDataBeforeSaveDraft?: boolean\n autoSaveKey: string\n onCancel: () => unknown\n onSubmit: (newFormSubmission: submissionService.NewFormSubmission) => unknown\n initialSubmission?: SubmissionTypes.S3SubmissionData['submission']\n resumeAtElement?: FormTypes.FormElement\n onSaveDraft?: (\n newDraftSubmission: submissionService.NewDraftSubmission,\n ) => unknown\n}) {\n const [{ definition, submission, lastElementUpdated }, setFormSubmission] =\n useFormSubmissionState(form, initialSubmission, resumeAtElement)\n\n const [\n { isLoadingAutoSaveSubmission, autoSaveSubmission, autoSaveElement },\n setAutoSaveState,\n ] = React.useState<{\n isLoadingAutoSaveSubmission: boolean\n autoSaveSubmission: SubmissionTypes.S3SubmissionData['submission'] | null\n autoSaveElement: FormElement | null\n }>({\n isLoadingAutoSaveSubmission: true,\n autoSaveSubmission: null,\n autoSaveElement: null,\n })\n\n const throttledAutoSave = React.useMemo(() => {\n return _throttle(\n (\n model: SubmissionTypes.S3SubmissionData['submission'],\n lastElementUpdated?: FormElement,\n ) => {\n console.log('Auto saving...')\n autoSaveService\n .upsertAutoSaveData(definition.id, autoSaveKey, model)\n .then(() => {\n if (lastElementUpdated) {\n return autoSaveService.upsertAutoSaveData<FormElement>(\n definition.id,\n `LAST_ELEMENT_UPDATED_${autoSaveKey}`,\n lastElementUpdated,\n )\n }\n })\n .catch((error) => {\n console.warn('Error while auto saving', error)\n Sentry.captureException(error)\n })\n },\n 9580, // https://en.wikipedia.org/wiki/100_metres\n { trailing: true, leading: false },\n )\n }, [autoSaveKey, definition.id])\n\n const cancelAutoSave = React.useCallback(() => {\n if (throttledAutoSave) {\n throttledAutoSave.cancel()\n }\n }, [throttledAutoSave])\n\n const deleteAutoSaveSubmission = React.useCallback(() => {\n return autoSaveService\n .deleteAutoSaveData(definition.id, autoSaveKey)\n .catch((error) => {\n console.warn('Error removing auto save data: ', error)\n Sentry.captureException(error)\n })\n }, [autoSaveKey, definition.id])\n\n const handleSubmit = React.useCallback(\n (submissionResult: submissionService.NewFormSubmission) => {\n cancelAutoSave()\n if (removeAutoSaveDataBeforeSubmit !== false) {\n deleteAutoSaveSubmission()\n }\n onSubmit(submissionResult)\n },\n [\n cancelAutoSave,\n deleteAutoSaveSubmission,\n onSubmit,\n removeAutoSaveDataBeforeSubmit,\n ],\n )\n\n const handleSaveDraft = React.useMemo(() => {\n if (onSaveDraft) {\n return (newDraftSubmission: submissionService.NewDraftSubmission) => {\n cancelAutoSave()\n if (removeAutoSaveDataBeforeSaveDraft !== false) {\n deleteAutoSaveSubmission()\n }\n if (onSaveDraft) {\n onSaveDraft(newDraftSubmission)\n }\n }\n }\n }, [\n cancelAutoSave,\n deleteAutoSaveSubmission,\n onSaveDraft,\n removeAutoSaveDataBeforeSaveDraft,\n ])\n\n const handleNavigateAway = React.useCallback(() => {\n cancelAutoSave()\n deleteAutoSaveSubmission()\n }, [cancelAutoSave, deleteAutoSaveSubmission])\n\n const handleCancel = React.useCallback(() => {\n cancelAutoSave()\n deleteAutoSaveSubmission()\n onCancel()\n }, [cancelAutoSave, deleteAutoSaveSubmission, onCancel])\n\n React.useEffect(() => {\n let ignore = false\n const loadAutoSaveData = async () => {\n try {\n const autoSaveSubmission = await autoSaveService.getAutoSaveData<\n SubmissionTypes.S3SubmissionData['submission']\n >(definition.id, autoSaveKey)\n const autoSaveElement =\n await autoSaveService.getAutoSaveData<FormElement>(\n definition.id,\n `LAST_ELEMENT_UPDATED_${autoSaveKey}`,\n )\n if (!ignore) {\n setAutoSaveState({\n isLoadingAutoSaveSubmission: false,\n autoSaveSubmission,\n autoSaveElement,\n })\n }\n } catch (error) {\n console.warn('Error loading auto save data', error)\n Sentry.captureException(error)\n if (!ignore) {\n setAutoSaveState({\n isLoadingAutoSaveSubmission: false,\n autoSaveSubmission: null,\n autoSaveElement: null,\n })\n }\n }\n }\n loadAutoSaveData()\n return () => {\n ignore = true\n }\n }, [autoSaveKey, definition.id])\n\n // Clean up throttle function on unmount\n React.useEffect(() => {\n return () => {\n cancelAutoSave()\n }\n }, [cancelAutoSave])\n\n const setFormSubmissionAutoSave: typeof setFormSubmission = React.useCallback(\n (formSubmission) => {\n setFormSubmission((currentFormSubmission) => {\n const newFormSubmission =\n typeof formSubmission === 'function'\n ? formSubmission(currentFormSubmission)\n : formSubmission\n\n throttledAutoSave(\n newFormSubmission.submission,\n newFormSubmission.lastElementUpdated,\n )\n\n return newFormSubmission\n })\n },\n [setFormSubmission, throttledAutoSave],\n )\n\n const startNewSubmission = React.useCallback(() => {\n deleteAutoSaveSubmission()\n setAutoSaveState({\n isLoadingAutoSaveSubmission: false,\n autoSaveSubmission: null,\n autoSaveElement: null,\n })\n }, [deleteAutoSaveSubmission])\n\n const continueAutoSaveSubmission = React.useCallback(() => {\n if (autoSaveSubmission) {\n setFormSubmission((currentFormSubmission) => ({\n ...currentFormSubmission,\n submission: autoSaveSubmission,\n lastElementUpdated: autoSaveElement ? autoSaveElement : undefined,\n }))\n }\n setAutoSaveState({\n isLoadingAutoSaveSubmission: false,\n autoSaveSubmission: null,\n autoSaveElement: null,\n })\n }, [autoSaveSubmission, setFormSubmission, autoSaveElement])\n\n return {\n definition,\n submission,\n lastElementUpdated,\n isLoadingAutoSaveSubmission,\n isAutoSaveSubmissionAvailable: autoSaveSubmission !== null,\n startNewSubmission,\n continueAutoSaveSubmission,\n handleSubmit,\n handleCancel,\n handleSaveDraft,\n handleNavigateAway,\n setFormSubmission: setFormSubmissionAutoSave,\n }\n}\n"]}
|
@@ -35,6 +35,7 @@ import { FormTypes, SubmissionTypes } from '@oneblink/types';
|
|
35
35
|
* with
|
36
36
|
* @param lastElementUpdated
|
37
37
|
* @returns
|
38
|
+
* @group Hooks
|
38
39
|
*/
|
39
40
|
export default function useFormSubmissionState(form: FormTypes.Form, initialSubmission?: SubmissionTypes.S3SubmissionData['submission'], lastElementUpdated?: FormTypes.FormElement): [{
|
40
41
|
definition: FormTypes.Form;
|
@@ -36,6 +36,7 @@ import generateDefaultData from '../services/generate-default-data';
|
|
36
36
|
* with
|
37
37
|
* @param lastElementUpdated
|
38
38
|
* @returns
|
39
|
+
* @group Hooks
|
39
40
|
*/
|
40
41
|
export default function useFormSubmissionState(form, initialSubmission, lastElementUpdated) {
|
41
42
|
return React.useState(() => {
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"useFormSubmissionState.js","sourceRoot":"","sources":["../../src/hooks/useFormSubmissionState.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,UAAU,MAAM,kBAAkB,CAAA;AAEzC,OAAO,mBAAmB,MAAM,mCAAmC,CAAA;AACnE
|
1
|
+
{"version":3,"file":"useFormSubmissionState.js","sourceRoot":"","sources":["../../src/hooks/useFormSubmissionState.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,UAAU,MAAM,kBAAkB,CAAA;AAEzC,OAAO,mBAAmB,MAAM,mCAAmC,CAAA;AACnE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAM,CAAC,OAAO,UAAU,sBAAsB,CAC5C,IAAoB,EACpB,iBAAkE,EAClE,kBAA0C;IAE1C,OAAO,KAAK,CAAC,QAAQ,CAAC,GAAG,EAAE;QACzB,MAAM,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,CAAA;QACnC,MAAM,WAAW,GAAG,mBAAmB,CACrC,UAAU,CAAC,QAAQ,EACnB,iBAAiB,IAAI,EAAE,CACxB,CAAA;QACD,OAAO;YACL,UAAU;YACV,UAAU,EAAE,WAAW;YACvB,kBAAkB;SACnB,CAAA;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import * as React from 'react'\nimport _cloneDeep from 'lodash.clonedeep'\nimport { FormTypes, SubmissionTypes } from '@oneblink/types'\nimport generateDefaultData from '../services/generate-default-data'\n/**\n * This function is a simple wrapper around the react hook `useState()`. The\n * results can be passed to the [`<OneBlinkForm\n * />`](https://oneblink.github.io/apps-react/somewhere) //TODO: Fix link\n * component.\n *\n * ## Example\n *\n * ```js\n * import {\n * useFormSubmissionState,\n * OneBlinkFormControlled,\n * } from '@oneblink/apps-react'\n *\n * function Uncontrolled({ form, initialSubmission, ...props }) {\n * const [{ definition, submission }, setFormSubmission] =\n * useFormSubmissionState(form, initialSubmission)\n *\n * return (\n * <OneBlinkFormControlled\n * {...props}\n * definition={definition}\n * submission={submission}\n * setFormSubmission={setFormSubmission}\n * lastElementUpdated={lastElementUpdated}\n * />\n * )\n * }\n * ```\n *\n * @param form The OneBlink Form to render\n * @param initialSubmission The initial submission data to populate the form\n * with\n * @param lastElementUpdated\n * @returns\n * @group Hooks\n */\nexport default function useFormSubmissionState(\n form: FormTypes.Form,\n initialSubmission?: SubmissionTypes.S3SubmissionData['submission'],\n lastElementUpdated?: FormTypes.FormElement,\n) {\n return React.useState(() => {\n const definition = _cloneDeep(form)\n const defaultData = generateDefaultData(\n definition.elements,\n initialSubmission || {},\n )\n return {\n definition,\n submission: defaultData,\n lastElementUpdated,\n }\n })\n}\n"]}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"useIsMounted.js","sourceRoot":"","sources":["../../src/hooks/useIsMounted.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B
|
1
|
+
{"version":3,"file":"useIsMounted.js","sourceRoot":"","sources":["../../src/hooks/useIsMounted.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,OAAO,UAAU,YAAY;IAIlC,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;IACrC,KAAK,CAAC,SAAS,CAAC,GAAG,EAAE;QACnB,SAAS,CAAC,OAAO,GAAG,IAAI,CAAA;QACxB,OAAO,GAAG,EAAE;YACV,SAAS,CAAC,OAAO,GAAG,KAAK,CAAA;QAC3B,CAAC,CAAA;IACH,CAAC,EAAE,EAAE,CAAC,CAAA;IACN,OAAO,SAAS,CAAA;AAClB,CAAC","sourcesContent":["import * as React from 'react'\n\n/**\n * This function is a react hook for determining whether the consuming component\n * is currently mounted on the DOM.\n *\n * ## Example\n *\n * ```js\n * import { useIsMounted } from '@oneblink/apps-react'\n *\n * const isMounted = useIsMounted()\n *\n * if (isMounted.current) {\n * // DO SOMETHING HERE\n * }\n * ```\n *\n * @returns\n * @group Hooks\n */\nexport default function useIsMounted(): {\n /** Whether the current component is mounted. */\n current: boolean\n} {\n const isMounted = React.useRef(false)\n React.useEffect(() => {\n isMounted.current = true\n return () => {\n isMounted.current = false\n }\n }, [])\n return isMounted\n}\n"]}
|
@@ -2,6 +2,7 @@ import * as React from 'react';
|
|
2
2
|
/**
|
3
3
|
* @param type
|
4
4
|
* @param listener
|
5
|
+
* @group Hooks
|
5
6
|
*/
|
6
7
|
export declare const useNetworkChangeEffect: (type: 'online' | 'offline', listener: () => unknown) => void;
|
7
8
|
/**
|
@@ -32,6 +33,7 @@ export declare const useNetworkChangeEffect: (type: 'online' | 'offline', listen
|
|
32
33
|
*
|
33
34
|
* @param props
|
34
35
|
* @returns
|
36
|
+
* @group Components
|
35
37
|
*/
|
36
38
|
export declare function IsOfflineContextProvider({ children, }: {
|
37
39
|
children: React.ReactNode;
|
@@ -51,5 +53,8 @@ export declare function IsOfflineContextProvider({ children, }: {
|
|
51
53
|
*
|
52
54
|
* const isOffline = useIsOffline()
|
53
55
|
* ```
|
56
|
+
*
|
57
|
+
* @returns
|
58
|
+
* @group Hooks
|
54
59
|
*/
|
55
60
|
export default function useIsOffline(): boolean;
|
@@ -6,6 +6,7 @@ const IsOfflineContext = React.createContext(defaultValue);
|
|
6
6
|
/**
|
7
7
|
* @param type
|
8
8
|
* @param listener
|
9
|
+
* @group Hooks
|
9
10
|
*/
|
10
11
|
export const useNetworkChangeEffect = (type, listener) => {
|
11
12
|
React.useEffect(() => {
|
@@ -47,6 +48,7 @@ export const useNetworkChangeEffect = (type, listener) => {
|
|
47
48
|
*
|
48
49
|
* @param props
|
49
50
|
* @returns
|
51
|
+
* @group Components
|
50
52
|
*/
|
51
53
|
export function IsOfflineContextProvider({ children, }) {
|
52
54
|
const [isOffline, goOffline, goOnline] = useBooleanState(defaultValue);
|
@@ -69,6 +71,9 @@ export function IsOfflineContextProvider({ children, }) {
|
|
69
71
|
*
|
70
72
|
* const isOffline = useIsOffline()
|
71
73
|
* ```
|
74
|
+
*
|
75
|
+
* @returns
|
76
|
+
* @group Hooks
|
72
77
|
*/
|
73
78
|
export default function useIsOffline() {
|
74
79
|
return React.useContext(IsOfflineContext);
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"useIsOffline.js","sourceRoot":"","sources":["../../src/hooks/useIsOffline.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAA;AAC/C,OAAO,eAAe,MAAM,0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E,QAAQ,CAAC,CAAA;IAC1C,sBAAsB,CAAC,SAAS,EAAE,SAAS,CAAC,CAAA;IAE5C,OAAO,CACL,oBAAC,gBAAgB,CAAC,QAAQ,IAAC,KAAK,EAAE,SAAS,IACxC,QAAQ,CACiB,CAC7B,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,CAAC,OAAO,UAAU,YAAY;IAClC,OAAO,KAAK,CAAC,UAAU,CAAC,gBAAgB,CAAC,CAAA;AAC3C,CAAC","sourcesContent":["import * as React from 'react'\n\nimport { offlineService } from '@oneblink/apps'\nimport useBooleanState from '../hooks/useBooleanState'\n\nconst defaultValue = offlineService.isOffline()\n\nconst IsOfflineContext = React.createContext<boolean>(defaultValue)\n\n/**\n * @param type\n * @param listener\n * @group Hooks\n */\nexport const useNetworkChangeEffect = (\n type: 'online' | 'offline',\n listener: () => unknown,\n) => {\n React.useEffect(() => {\n // Stupid cordova seems to require that offline/online\n // listeners are set on the document and browsers seem\n // to require window.\n const element = window.cordova ? document : window\n element.addEventListener(type, listener)\n\n return () => {\n element.removeEventListener(type, listener)\n }\n }, [type, listener])\n}\n\n/**\n * IsOfflineContextProvider is a React Component that provides the `isOffline`\n * state for components further down your component tree to consume. It should\n * be used to wrap the components requiring the state.\n *\n * - **This component is required in your component tree to be able to consume the\n * [`useIsOffline`](./useIsOffline.html) hook.**\n *\n * ### Usage\n *\n * ```jsx\n * import { IsOfflineContextProvider } from '@oneblink/apps-react'\n *\n * const TopLevelComponent = () => {\n * return (\n * <IsOfflineContextProvider>\n * <div>\n * <ComponentThatRequiresOfflineState />\n * </div>\n * </IsOfflineContextProvider>\n * )\n * }\n *\n * export default TopLevelComponent\n * ```\n *\n * @param props\n * @returns\n * @group Components\n */\nexport function IsOfflineContextProvider({\n children,\n}: {\n children: React.ReactNode\n}) {\n const [isOffline, goOffline, goOnline] = useBooleanState(defaultValue)\n\n useNetworkChangeEffect('online', goOnline)\n useNetworkChangeEffect('offline', goOffline)\n\n return (\n <IsOfflineContext.Provider value={isOffline}>\n {children}\n </IsOfflineContext.Provider>\n )\n}\n\n/**\n * This function is a react hook for determining whether an application is in an\n * offline state.\n *\n * - **This component requires\n * [`<IsOfflineContextProvider/>`](./IsOfflineContextProvider.html) to be\n * present in your component tree.**\n *\n * ## Example\n *\n * ```js\n * import { useIsOffline } from '@oneblink/apps-react'\n *\n * const isOffline = useIsOffline()\n * ```\n *\n * @returns\n * @group Hooks\n */\nexport default function useIsOffline() {\n return React.useContext(IsOfflineContext)\n}\n"]}
|
@@ -45,9 +45,11 @@ export type LoadDataState<T> = {
|
|
45
45
|
* export default MyComponent
|
46
46
|
* ```
|
47
47
|
*
|
48
|
+
* @typeParam T The type of the data returned by your `onLoad` function
|
48
49
|
* @param onLoad The function that fetches your data. Should be a Promise that
|
49
50
|
* returns your data
|
50
51
|
* @returns
|
52
|
+
* @group Hooks
|
51
53
|
*/
|
52
54
|
export default function useLoadDataState<T>(onLoad: (abortSignal?: AbortSignal) => Promise<T>): [
|
53
55
|
state: LoadDataState<T>,
|
@@ -35,9 +35,11 @@ import useIsMounted from './useIsMounted';
|
|
35
35
|
* export default MyComponent
|
36
36
|
* ```
|
37
37
|
*
|
38
|
+
* @typeParam T The type of the data returned by your `onLoad` function
|
38
39
|
* @param onLoad The function that fetches your data. Should be a Promise that
|
39
40
|
* returns your data
|
40
41
|
* @returns
|
42
|
+
* @group Hooks
|
41
43
|
*/
|
42
44
|
export default function useLoadDataState(onLoad) {
|
43
45
|
const isMounted = useIsMounted();
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"useLoadDataState.js","sourceRoot":"","sources":["../../src/hooks/useLoadDataState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,YAAY,MAAM,gBAAgB,CAAA;AAiBzC
|
1
|
+
{"version":3,"file":"useLoadDataState.js","sourceRoot":"","sources":["../../src/hooks/useLoadDataState.ts"],"names":[],"mappings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,YAAY;oBACf,MAAM,EACJ,OAAO,MAAM,KAAK,UAAU;wBAC1B,CAAC,CAAC,oFAAoF;4BACpF,MAAM,CAAC,YAAY,CAAC,MAAM,CAAC;wBAC7B,CAAC,CAAC,MAAM;iBACb,CAAA;aACF;iBAAM;gBACL,OAAO,YAAY,CAAA;aACpB;QACH,CAAC,CAAC,CAAA;IACJ,CAAC,EACD,EAAE,CACH,CAAA;IAED,KAAK,CAAC,SAAS,CAAC,GAAG,EAAE;QACnB,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAA;QAC7C,UAAU,CAAC,eAAe,CAAC,MAAM,CAAC,CAAA;QAClC,OAAO,GAAG,EAAE;YACV,eAAe,CAAC,KAAK,EAAE,CAAA;QACzB,CAAC,CAAA;IACH,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAA;IAEhB,OAAO,CAAC,KAAK,EAAE,UAAU,EAAE,SAAS,CAAC,CAAA;AACvC,CAAC","sourcesContent":["import * as React from 'react'\nimport useIsMounted from './useIsMounted'\n\nexport type LoadDataState<T> =\n | {\n status: 'SUCCESS'\n /** Your data. */\n result: T\n }\n | {\n status: 'ERROR'\n /** A JavaScript `Error` object. */\n error: Error\n }\n | {\n status: 'LOADING'\n }\n\n/**\n * This function is a react hook for managing the state involved with loading\n * data.\n *\n * ## Example\n *\n * ```js\n * import { useLoadDataState } from '@oneblink/apps-react'\n * const fetchData = async () => {\n * const response = await fetch(`https://some-website.com/api?data=data`)\n *\n * if (!response.ok) {\n * const text = await response.text()\n * throw new Error(text)\n * }\n *\n * return await response.json()\n * }\n *\n * const MyComponent = () => {\n * const [state, refresh, setResult] = useLoadDataState(fetchData)\n *\n * switch (state.status) {\n * case 'LOADING':\n * return <Loading />\n * case 'ERROR':\n * return <Error message={state.error} />\n * case 'SUCCESS':\n * // RENDER UI\n * }\n * }\n *\n * export default MyComponent\n * ```\n *\n * @typeParam T The type of the data returned by your `onLoad` function\n * @param onLoad The function that fetches your data. Should be a Promise that\n * returns your data\n * @returns\n * @group Hooks\n */\nexport default function useLoadDataState<T>(\n onLoad: (abortSignal?: AbortSignal) => Promise<T>,\n): [\n state: LoadDataState<T>,\n handleLoad: (abortSignal?: AbortSignal) => void,\n setResult: React.Dispatch<React.SetStateAction<T>>,\n] {\n const isMounted = useIsMounted()\n const [state, setState] = React.useState<LoadDataState<T>>({\n status: 'LOADING',\n })\n\n const handleLoad = React.useCallback(\n async (abortSignal?: AbortSignal) => {\n setState({\n status: 'LOADING',\n })\n try {\n const result = await onLoad(abortSignal)\n if (isMounted.current && !abortSignal?.aborted) {\n setState({\n status: 'SUCCESS',\n result,\n })\n }\n } catch (err) {\n if (isMounted.current && !abortSignal?.aborted) {\n setState({\n status: 'ERROR',\n error: err as Error,\n })\n }\n }\n },\n [isMounted, onLoad],\n )\n\n const setResult: React.Dispatch<React.SetStateAction<T>> = React.useCallback(\n (setter) => {\n setState((currentState: LoadDataState<T>) => {\n if (currentState.status === 'SUCCESS') {\n return {\n ...currentState,\n result:\n typeof setter === 'function'\n ? // @ts-expect-error Typescript cannot tell between a generic type (T) and a function\n setter(currentState.result)\n : setter,\n }\n } else {\n return currentState\n }\n })\n },\n [],\n )\n\n React.useEffect(() => {\n const abortController = new AbortController()\n handleLoad(abortController.signal)\n return () => {\n abortController.abort()\n }\n }, [handleLoad])\n\n return [state, handleLoad, setResult]\n}\n"]}
|
package/dist/hooks/useLogin.d.ts
CHANGED
@@ -295,6 +295,7 @@
|
|
295
295
|
*
|
296
296
|
* @param options
|
297
297
|
* @returns
|
298
|
+
* @group Hooks
|
298
299
|
*/
|
299
300
|
export default function useLogin({ username, password, newPassword, newPasswordConfirmed, code, }: {
|
300
301
|
/** The email address entered by the user. */
|
@@ -313,7 +314,8 @@ export default function useLogin({ username, password, newPassword, newPasswordC
|
|
313
314
|
* "forgot password" process.
|
314
315
|
*/
|
315
316
|
code: string;
|
316
|
-
}):
|
317
|
+
}): UseLoginValue;
|
318
|
+
export interface UseLoginValue {
|
317
319
|
/** Open redirect user to the Google sign-in page. */
|
318
320
|
loginWithGoogle: () => void;
|
319
321
|
/**
|
@@ -431,4 +433,4 @@ export default function useLogin({ username, password, newPassword, newPasswordC
|
|
431
433
|
* Will call `onLogin()` if successful, otherwise will set `loginError`.
|
432
434
|
*/
|
433
435
|
submitMfaCode: () => void;
|
434
|
-
}
|
436
|
+
}
|
package/dist/hooks/useLogin.js
CHANGED
@@ -299,6 +299,7 @@ import useBooleanState from './useBooleanState';
|
|
299
299
|
*
|
300
300
|
* @param options
|
301
301
|
* @returns
|
302
|
+
* @group Hooks
|
302
303
|
*/
|
303
304
|
export default function useLogin({ username, password, newPassword, newPasswordConfirmed, code, }) {
|
304
305
|
const isMounted = useIsMounted();
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"useLogin.js","sourceRoot":"","sources":["../../src/hooks/useLogin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAEpD,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAySG;AACH,MAAM,CAAC,OAAO,UAAU,QAAQ,CAAC,EAC/B,QAAQ,EACR,QAAQ,EACR,WAAW,EACX,oBAAoB,EACpB,IAAI,GAkBL;IAuHC,MAAM,SAAS,G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["import * as React from 'react'\nimport { authService, Sentry } from '@oneblink/apps'\n\nimport useIsMounted from './useIsMounted'\nimport useBooleanState from './useBooleanState'\n\n/**\n * This function is a react hook to help writing your own login screen.\n *\n * ## Example\n *\n * ```jsx\n * import * as React from 'react'\n * import { useHistory } from 'react-router-dom'\n * import { useLogin } from '@oneblink/apps-react'\n *\n * function App() {\n * const history = useHistory()\n *\n * const [username, setUsername] = React.useState('')\n * const [password, setPassword] = React.useState('')\n * const [newPasswordConfirmed, setNewPasswordConfirmed] = React.useState('')\n * const [newPassword, setNewPassword] = React.useState('')\n * const [code, setCode] = React.useState('')\n *\n * const onLogin = React.useCallback(() => {\n * history.push('/')\n * }, [history])\n *\n * const {\n * // Login\n * loginWithGoogle,\n * loginWithUsernamePassword,\n * isLoggingIn,\n * // Reset Temp Password\n * isPasswordTemporary,\n * isResettingTemporaryPassword,\n * resetTemporaryPassword,\n * // MFA Password\n * isMfaCodeRequired,\n * isSubmittingMfaCode,\n * submitMfaCode,\n * // Login Errors\n * loginError,\n * clearLoginError,\n * // Showing Forgot Password\n * isShowingForgotPassword,\n * showForgotPassword,\n * hideForgotPassword,\n * // Sending Forgot Password Code\n * isSendingForgotPasswordCode,\n * sendForgotPasswordCode,\n * // Resetting Forgotten Password\n * hasSentForgotPasswordCode,\n * isResettingForgottenPassword,\n * resetForgottenPassword,\n * // Forgot Password Errors\n * forgotPasswordError,\n * clearForgotPasswordError,\n * // Validation\n * usernameValidation,\n * passwordValidation,\n * codeValidation,\n * newPasswordValidation,\n * newPasswordConfirmedValidation,\n * } = useLogin({\n * username,\n * password,\n * newPassword,\n * newPasswordConfirmed,\n * code,\n * onLogin,\n * })\n *\n * if (hasSentForgotPasswordCode) {\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * resetForgottenPassword()\n * }}\n * >\n * <p>We have sent you a password reset code via email. Enter it below to reset your password.</p>\n *\n * <input\n * type=\"password\"\n * placeholder=\"Code\"\n * value={code}\n * onChange={(e) => setCode(e.target.value)}\n * />\n *\n * <input\n * type=\"password\"\n * placeholder=\"New Password\"\n * value={newPassword}\n * onChange={(e) => setNewPassword(e.target.value)}\n * />\n *\n * <input\n * type=\"password\"\n * placeholder=\"Confirm Password\"\n * value={newPassword}\n * onChange={(e) => setNewPasswordConfirmed(e.target.value)}\n * />\n *\n * <button\n * type=\"submit\"\n * disabled={isResettingForgottenPassword || codeValidation.isInvalid || newPasswordValidation.isInvalid || newPasswordConfirmedValidation.isInvalid}\n * >\n * Change Password\n * </button>\n *\n * <p>Password Requirements</p>\n * <p>Contains a lowercase letter: {validation.hasLowercaseLetter ? 'Yes' : 'No'}</p>\n * <p>Contains an upper case letter: {validation.hasUpperCaseLetter ? 'Yes' : 'No'}</p>\n * <p>Contains a number: {validation.hasNumber ? 'Yes' : 'No'}</p>\n * <p>Contains a special character: {validation.hasSpecialCharacter ? 'Yes' : 'No'}</p>\n * <p>Contains at least 8 characters: {validation.hasMinLength ? 'Yes' : 'No'}</p>\n *\n * {forgotPasswordError && (\n * <p>{forgotPasswordError.message}</p>\n * <button type=\"button\" onClick={clearForgotPasswordError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * if (isShowingForgotPassword) {\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * sendForgotPasswordCode()\n * }}\n * >\n * <p>Enter your email address and we will send you a code to reset your password.</p>\n *\n * <input\n * type=\"email\"\n * placeholder=\"Email Address\"\n * value={username}\n * onChange={(e) => setUsername(e.target.value)}\n * />\n *\n * <p>\n * <a onClick={hideForgotPassword}>Remembered your password?</a>\n * </p>\n *\n * <button\n * type=\"submit\"\n * disabled={isSendingForgotPasswordCode || usernameValidation.isInvalid}\n * >\n * Reset Password\n * </button>\n *\n * {forgotPasswordError && (\n * <p>{forgotPasswordError.message}</p>\n * <button type=\"button\" onClick={clearForgotPasswordError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * if (isPasswordTemporary) {\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * resetTemporaryPassword()\n * }}\n * >\n * <p>The password you entered was only temporary and must be reset for security purposes. Please enter your new password below to continue.</p>\n *\n * <input\n * type=\"password\"\n * placeholder=\"New Password\"\n * value={newPassword}\n * onChange={(e) => setNewPassword(e.target.value)}\n * />\n *\n * <input\n * type=\"password\"\n * placeholder=\"Confirm Password\"\n * value={newPassword}\n * onChange={(e) => setNewPasswordConfirmed(e.target.value)}\n * />\n *\n * <button\n * type=\"submit\"\n * disabled={isResettingTemporaryPassword || newPasswordValidation.isInvalid || newPasswordConfirmedValidation.isInvalid}\n * >\n * Change Password & Sign In\n * </button>\n *\n * <p>Password Requirements</p>\n * <p>Contains a lowercase letter: {validation.hasLowercaseLetter ? 'Yes' : 'No'}</p>\n * <p>Contains an upper case letter: {validation.hasUpperCaseLetter ? 'Yes' : 'No'}</p>\n * <p>Contains a number: {validation.hasNumber ? 'Yes' : 'No'}</p>\n * <p>Contains a special character: {validation.hasSpecialCharacter ? 'Yes' : 'No'}</p>\n * <p>Contains at least 8 characters: {validation.hasMinLength ? 'Yes' : 'No'}</p>\n *\n * {loginError && (\n * <p>{loginError.message}</p>\n * <button type=\"button\" onClick={clearLoginError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * if (isMfaCodeRequired) {\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * submitMfaCode()\n * }}\n * >\n * <p>Enter the 6-digit code found in your authenticator app.</p>\n *\n * <input\n * type=\"password\"\n * placeholder=\"Code\"\n * value={code}\n * onChange={(e) => setCode(e.target.value)}\n * />\n *\n * <button\n * type=\"submit\"\n * disabled={isSubmittingMfaCode || codeValidation.isInvalid}\n * >\n * Sign In\n * </button>\n *\n * {loginError && (\n * <p>{loginError.message}</p>\n * <button type=\"button\" onClick={clearLoginError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * loginWithUsernamePassword()\n * }}\n * >\n * <p>Sign in with your email address and password.</p>\n * <input\n * type=\"email\"\n * placeholder=\"Email Address\"\n * value={username}\n * onChange={(e) => setUsername(e.target.value)}\n * />\n *\n * <input\n * type=\"password\"\n * placeholder=\"New Password\"\n * value={newPassword}\n * onChange={(e) => setNewPassword(e.target.value)}\n * />\n *\n * <p>\n * <a onClick={showForgotPassword}>Forgot your password?</a>\n * </p>\n *\n * <button\n * type=\"submit\"\n * disabled={isLoggingIn || usernameValidation.isInvalid || passwordValidation.isInvalid}\n * >\n * {children}\n * </button>\n *\n * <p>or</p>\n *\n * <button\n * type=\"button\"\n * onClick={loginWithGoogle}\n * >\n * <img\n * alt=\"Google\"\n * src=\"google-sign-in.png\"\n * />\n * <span>Sign in with Google</span>\n * </button>\n *\n * {loginError && (\n * <p>{loginError.message}</p>\n * <button type=\"button\" onClick={clearLoginError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * const root = document.getElementById('root')\n * if (root) {\n * ReactDOM.render(<App />, root)\n * }\n * ```\n *\n * @param options\n * @returns\n */\nexport default function useLogin({\n username,\n password,\n newPassword,\n newPasswordConfirmed,\n code,\n}: {\n /** The email address entered by the user. */\n username: string\n /** The password entered by the user. */\n password: string\n /** The new password entered by the user if changing their password. */\n newPassword: string\n /**\n * The new password repeated by the user if changing their password to ensure\n * they do type it in wrong.\n */\n newPasswordConfirmed: string\n /**\n * The code sent to the user after requesting a password reset by starting the\n * \"forgot password\" process.\n */\n code: string\n}): {\n /** Open redirect user to the Google sign-in page. */\n loginWithGoogle: () => void\n /**\n * Attempt to use the `username` and `password` arguments to create a session.\n * Will call `onLogin()` if successful, otherwise will set `loginError`.\n */\n loginWithUsernamePassword: () => void\n /** `true` while processing `loginWithUsernamePassword()`. */\n isLoggingIn: boolean\n /**\n * `true` if the user logged in using a temporary password. Prompt the user\n * for a new password and call `resetTemporaryPassword()`.\n */\n isPasswordTemporary: boolean\n /**\n * Attempt to use `newPassword` and `newPasswordConfirmed` arguments to reset\n * the user's password and create a session. Will call `onLogin()` if\n * successful, otherwise will set `loginError`.\n */\n resetTemporaryPassword: () => void\n /**\n * Set if an error occurs while processing `loginWithUsernamePassword()` or\n * `resetTemporaryPassword()`.\n */\n loginError: Error | null\n /** Set `loginError` back to `null`. */\n clearLoginError: () => void\n /** `true` while processing `resetTemporaryPassword()`. */\n isResettingTemporaryPassword: boolean\n /** `true` when showing the forgot password flow. */\n isShowingForgotPassword: boolean\n /** Set `isShowingForgotPassword` to `true`. */\n showForgotPassword: () => void\n /** Set `isShowingForgotPassword` to `false`. */\n hideForgotPassword: () => void\n /**\n * Attempt to use the `username` argument to start the forgot password\n * process. This will send the user an email with a code to enter. A failed\n * request will set `forgotPasswordError`.\n */\n sendForgotPasswordCode: () => void\n /** `true` while processing `sendForgotPasswordCode()`. */\n isSendingForgotPasswordCode: boolean\n /** `true` if the forgot password code has been successfully sent to the user. */\n hasSentForgotPasswordCode: boolean\n /**\n * Attempt to use the `code`, `newPassword`, and `newPasswordConfirmed`\n * arguments to reset the user's password. A failed request will set\n * `forgotPasswordError`.\n */\n resetForgottenPassword: () => void\n /** `true` while processing `resetForgottenPassword()`. */\n isResettingForgottenPassword: boolean\n /**\n * Set if an error occurs while processing `sendForgotPasswordCode()` or\n * `resetForgottenPassword()`.\n */\n forgotPasswordError: Error | null\n /** Set `forgotPasswordError` back to `null`. */\n clearForgotPasswordError: () => void\n usernameValidation: {\n /** `true` if the `username` argument is invalid. */\n isInvalid: boolean\n }\n passwordValidation: {\n /** `true` if the `password` argument is invalid. */\n isInvalid: boolean\n }\n codeValidation: {\n /** `true` if the `code` argument is invalid. */\n isInvalid: boolean\n }\n newPasswordValidation: {\n /** `true` if the `newPassword` argument is invalid. */\n isInvalid: boolean\n /**\n * `true` if the `newPassword` argument has a lowercase letter (required to\n * be valid).\n */\n hasLowercaseLetter: boolean\n /**\n * `true` if the `newPassword` argument has an uppercase letter (required to\n * be valid).\n */\n hasUpperCaseLetter: boolean\n /** `true` if the `newPassword` argument has a number (required to be valid). */\n hasNumber: boolean\n /**\n * `true` if the `newPassword` argument has a special character (required to\n * be valid).\n */\n hasSpecialCharacter: boolean\n /**\n * `true` if the `newPassword` argument has at least the minimum number of\n * characters (required to be valid).\n */\n hasMinLength: boolean\n }\n newPasswordConfirmedValidation: {\n /**\n * `true` if the `newPasswordConfirmed` argument is invalid (must match the\n * `newPassword` argument).\n */\n isInvalid: boolean\n }\n /**\n * `true` if the user logged in using MFA and a code is required to finish the\n * login attempt. Prompt the user for a code and call `submitMfaCode()`.\n */\n isMfaCodeRequired: boolean\n /** `true` while processing `submitMfaCode()`. */\n isSubmittingMfaCode: boolean\n /**\n * Attempt to use `code` argument to submit the MFA code and create a session.\n * Will call `onLogin()` if successful, otherwise will set `loginError`.\n */\n submitMfaCode: () => void\n} {\n const isMounted = useIsMounted()\n\n // Validation\n const usernameValidation = React.useMemo(() => {\n return {\n isInvalid: !username.trim(),\n }\n }, [username])\n\n const passwordValidation = React.useMemo(() => {\n return {\n isInvalid: !password.trim(),\n }\n }, [password])\n\n const codeValidation = React.useMemo(() => {\n return {\n isInvalid: !code.trim(),\n }\n }, [code])\n\n const newPasswordValidation = React.useMemo(() => {\n const validation = {\n hasLowercaseLetter: /[a-z]+/.test(newPassword),\n hasUpperCaseLetter: /[A-Z]+/.test(newPassword),\n hasNumber: /\\d+/.test(newPassword),\n hasSpecialCharacter: /[\\^$*.[\\]{}()?|\\-\"!@#%&/,><':;|_~`]+/.test(\n newPassword,\n ),\n hasMinLength: newPassword.length >= 8,\n isInvalid: true,\n }\n validation.isInvalid =\n !validation.hasLowercaseLetter ||\n !validation.hasUpperCaseLetter ||\n !validation.hasNumber ||\n !validation.hasSpecialCharacter ||\n !validation.hasMinLength\n return validation\n }, [newPassword])\n\n const newPasswordConfirmedValidation = React.useMemo(() => {\n return {\n isInvalid: newPassword !== newPasswordConfirmed,\n }\n }, [newPassword, newPasswordConfirmed])\n\n // Login, Reset Password, MFA\n const [\n {\n isResettingTemporaryPassword,\n isLoggingIn,\n loginError,\n loginAttemptResponse,\n isSubmittingMfaCode,\n },\n setLoginState,\n ] = React.useState<{\n isResettingTemporaryPassword: boolean\n isLoggingIn: boolean\n loginError: null | Error\n loginAttemptResponse: authService.LoginAttemptResponse | undefined\n isSubmittingMfaCode: boolean\n }>({\n isResettingTemporaryPassword: false,\n isLoggingIn: false,\n loginError: null,\n loginAttemptResponse: undefined,\n isSubmittingMfaCode: false,\n })\n const clearLoginError = React.useCallback(\n () =>\n setLoginState((current) => ({\n ...current,\n loginError: null,\n })),\n [],\n )\n const loginWithUsernamePassword = React.useCallback(async () => {\n if (usernameValidation.isInvalid) {\n setLoginState((current) => ({\n ...current,\n loginError: new Error('Please enter a valid email address'),\n }))\n return\n }\n if (passwordValidation.isInvalid) {\n setLoginState((current) => ({\n ...current,\n loginError: new Error('Please enter a valid password'),\n }))\n return\n }\n\n setLoginState((currentState) => ({\n ...currentState,\n isLoggingIn: true,\n loginError: null,\n }))\n\n try {\n const newLoginAttemptResponse = await authService.loginUsernamePassword(\n username,\n password,\n )\n if (isMounted.current) {\n setLoginState((currentState) => ({\n ...currentState,\n isLoggingIn: false,\n loginAttemptResponse: newLoginAttemptResponse,\n }))\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setLoginState((currentState) => ({\n ...currentState,\n isLoggingIn: false,\n loginError: error as Error,\n }))\n }\n }\n }, [\n isMounted,\n password,\n passwordValidation.isInvalid,\n username,\n usernameValidation.isInvalid,\n ])\n\n const resetTemporaryPassword = React.useCallback(async () => {\n const resetTemporaryPasswordCallback =\n loginAttemptResponse?.resetPasswordCallback\n if (!resetTemporaryPasswordCallback) {\n return\n }\n\n if (newPasswordValidation.isInvalid) {\n setLoginState((current) => ({\n ...current,\n loginError: new Error('Please enter a valid password'),\n }))\n return\n }\n\n if (newPasswordConfirmedValidation.isInvalid) {\n setLoginState((current) => ({\n ...current,\n loginError: new Error('Please confirm your new password'),\n }))\n return\n }\n\n setLoginState((current) => ({\n ...current,\n isResettingPassword: true,\n loginError: null,\n }))\n\n try {\n const resetPasswordResponse = await resetTemporaryPasswordCallback(\n newPassword,\n )\n if (isMounted.current) {\n setLoginState((currentState) => ({\n ...currentState,\n isResettingTemporaryPassword: false,\n loginAttemptResponse: resetPasswordResponse,\n }))\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setLoginState((current) => ({\n ...current,\n isResettingPassword: false,\n loginError: error as Error,\n }))\n }\n }\n }, [\n isMounted,\n loginAttemptResponse?.resetPasswordCallback,\n newPassword,\n newPasswordConfirmedValidation.isInvalid,\n newPasswordValidation.isInvalid,\n ])\n\n const submitMfaCode = React.useCallback(async () => {\n const mfaCodeCallback = loginAttemptResponse?.mfaCodeCallback\n if (!mfaCodeCallback) {\n return\n }\n\n setLoginState((current) => ({\n ...current,\n isSubmittingMfaCode: true,\n loginError: null,\n }))\n\n try {\n const mfaResponse = await mfaCodeCallback(code)\n if (isMounted.current) {\n setLoginState((currentState) => ({\n ...currentState,\n isSubmittingMfaCode: false,\n loginAttemptResponse: mfaResponse,\n }))\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setLoginState((current) => ({\n ...current,\n isSubmittingMfaCode: false,\n loginError: error as Error,\n }))\n }\n }\n }, [code, isMounted, loginAttemptResponse?.mfaCodeCallback])\n\n // Forgot Password\n const [isShowingForgotPassword, showForgotPassword, hideForgotPassword] =\n useBooleanState(false)\n const [\n {\n resetForgottenPasswordCallback,\n isSendingForgotPasswordCode,\n isResettingForgottenPassword,\n forgotPasswordError,\n },\n setForgotPasswordState,\n ] = React.useState<{\n isSendingForgotPasswordCode: boolean\n forgotPasswordError: null | Error\n resetForgottenPasswordCallback:\n | null\n | ((code: string, newPassword: string) => void)\n isResettingForgottenPassword: boolean\n }>({\n isSendingForgotPasswordCode: false,\n forgotPasswordError: null,\n resetForgottenPasswordCallback: null,\n isResettingForgottenPassword: false,\n })\n const clearForgotPasswordError = React.useCallback(\n () =>\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: null,\n })),\n [],\n )\n const sendForgotPasswordCode = React.useCallback(async () => {\n if (usernameValidation.isInvalid) {\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: new Error('Please enter a valid email address'),\n }))\n return\n }\n\n setForgotPasswordState({\n isSendingForgotPasswordCode: true,\n resetForgottenPasswordCallback: null,\n forgotPasswordError: null,\n isResettingForgottenPassword: false,\n })\n\n try {\n const newResetForgottenPasswordCallback =\n await authService.forgotPassword(username)\n if (isMounted.current) {\n setForgotPasswordState({\n isSendingForgotPasswordCode: false,\n resetForgottenPasswordCallback: newResetForgottenPasswordCallback,\n forgotPasswordError: null,\n isResettingForgottenPassword: false,\n })\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setForgotPasswordState({\n isSendingForgotPasswordCode: false,\n resetForgottenPasswordCallback: null,\n forgotPasswordError: error as Error,\n isResettingForgottenPassword: false,\n })\n }\n }\n }, [isMounted, username, usernameValidation.isInvalid])\n\n const resetForgottenPassword = React.useCallback(async () => {\n if (!resetForgottenPasswordCallback) {\n return\n }\n\n if (codeValidation.isInvalid) {\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: new Error(\n 'Please enter the code that was sent to your email address',\n ),\n }))\n }\n if (newPasswordValidation.isInvalid) {\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: new Error('Please enter a valid password'),\n }))\n return\n }\n if (newPasswordConfirmedValidation.isInvalid) {\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: new Error('Please confirm your new password'),\n }))\n return\n }\n\n setForgotPasswordState((current) => ({\n ...current,\n isChangingPassword: true,\n forgotPasswordError: null,\n }))\n\n try {\n await resetForgottenPasswordCallback(code, newPassword)\n if (isMounted.current) {\n setForgotPasswordState({\n isSendingForgotPasswordCode: false,\n resetForgottenPasswordCallback: null,\n forgotPasswordError: null,\n isResettingForgottenPassword: false,\n })\n hideForgotPassword()\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setForgotPasswordState((current) => ({\n ...current,\n isChangingPassword: false,\n forgotPasswordError: error as Error,\n }))\n }\n }\n }, [\n resetForgottenPasswordCallback,\n codeValidation.isInvalid,\n newPasswordValidation.isInvalid,\n newPasswordConfirmedValidation.isInvalid,\n code,\n newPassword,\n isMounted,\n hideForgotPassword,\n ])\n\n const loginWithGoogle = React.useCallback(() => {\n authService.loginHostedUI('Google')\n }, [])\n\n return {\n // Login\n /** Open redirect user to the Google sign in */\n loginWithGoogle,\n loginWithUsernamePassword,\n isLoggingIn,\n loginError,\n clearLoginError,\n // Reset Temp Password\n isPasswordTemporary: !!loginAttemptResponse?.resetPasswordCallback,\n isResettingTemporaryPassword,\n resetTemporaryPassword,\n // MFA Code\n isMfaCodeRequired: !!loginAttemptResponse?.mfaCodeCallback,\n isSubmittingMfaCode,\n submitMfaCode,\n // Showing Forgot Password\n isShowingForgotPassword,\n showForgotPassword,\n hideForgotPassword,\n forgotPasswordError,\n clearForgotPasswordError,\n // Sending Forgot Password Code\n isSendingForgotPasswordCode,\n sendForgotPasswordCode,\n // Resetting Forgotten Password\n hasSentForgotPasswordCode: !!resetForgottenPasswordCallback,\n isResettingForgottenPassword,\n resetForgottenPassword,\n // Validation\n usernameValidation,\n passwordValidation,\n codeValidation,\n newPasswordValidation,\n newPasswordConfirmedValidation,\n }\n}\n"]}
|
1
|
+
{"version":3,"file":"useLogin.js","sourceRoot":"","sources":["../../src/hooks/useLogin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAA;AAEpD,OAAO,YAAY,MAAM,gBAAgB,CAAA;AACzC,OAAO,eAAe,MAAM,mBAAmB,CAAA;AAE/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAE,eAAe,CAAA;QAC1D,mBAAmB;QACnB,aAAa;QACb,0BAA0B;QAC1B,uBAAuB;QACvB,kBAAkB;QAClB,kBAAkB;QAClB,mBAAmB;QACnB,wBAAwB;QACxB,+BAA+B;QAC/B,2BAA2B;QAC3B,sBAAsB;QACtB,+BAA+B;QAC/B,yBAAyB,EAAE,CAAC,CAAC,8BAA8B;QAC3D,4BAA4B;QAC5B,sBAAsB;QACtB,aAAa;QACb,kBAAkB;QAClB,kBAAkB;QAClB,cAAc;QACd,qBAAqB;QACrB,8BAA8B;KAC/B,CAAA;AACH,CAAC","sourcesContent":["import * as React from 'react'\nimport { authService, Sentry } from '@oneblink/apps'\n\nimport useIsMounted from './useIsMounted'\nimport useBooleanState from './useBooleanState'\n\n/**\n * This function is a react hook to help writing your own login screen.\n *\n * ## Example\n *\n * ```jsx\n * import * as React from 'react'\n * import { useHistory } from 'react-router-dom'\n * import { useLogin } from '@oneblink/apps-react'\n *\n * function App() {\n * const history = useHistory()\n *\n * const [username, setUsername] = React.useState('')\n * const [password, setPassword] = React.useState('')\n * const [newPasswordConfirmed, setNewPasswordConfirmed] = React.useState('')\n * const [newPassword, setNewPassword] = React.useState('')\n * const [code, setCode] = React.useState('')\n *\n * const onLogin = React.useCallback(() => {\n * history.push('/')\n * }, [history])\n *\n * const {\n * // Login\n * loginWithGoogle,\n * loginWithUsernamePassword,\n * isLoggingIn,\n * // Reset Temp Password\n * isPasswordTemporary,\n * isResettingTemporaryPassword,\n * resetTemporaryPassword,\n * // MFA Password\n * isMfaCodeRequired,\n * isSubmittingMfaCode,\n * submitMfaCode,\n * // Login Errors\n * loginError,\n * clearLoginError,\n * // Showing Forgot Password\n * isShowingForgotPassword,\n * showForgotPassword,\n * hideForgotPassword,\n * // Sending Forgot Password Code\n * isSendingForgotPasswordCode,\n * sendForgotPasswordCode,\n * // Resetting Forgotten Password\n * hasSentForgotPasswordCode,\n * isResettingForgottenPassword,\n * resetForgottenPassword,\n * // Forgot Password Errors\n * forgotPasswordError,\n * clearForgotPasswordError,\n * // Validation\n * usernameValidation,\n * passwordValidation,\n * codeValidation,\n * newPasswordValidation,\n * newPasswordConfirmedValidation,\n * } = useLogin({\n * username,\n * password,\n * newPassword,\n * newPasswordConfirmed,\n * code,\n * onLogin,\n * })\n *\n * if (hasSentForgotPasswordCode) {\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * resetForgottenPassword()\n * }}\n * >\n * <p>We have sent you a password reset code via email. Enter it below to reset your password.</p>\n *\n * <input\n * type=\"password\"\n * placeholder=\"Code\"\n * value={code}\n * onChange={(e) => setCode(e.target.value)}\n * />\n *\n * <input\n * type=\"password\"\n * placeholder=\"New Password\"\n * value={newPassword}\n * onChange={(e) => setNewPassword(e.target.value)}\n * />\n *\n * <input\n * type=\"password\"\n * placeholder=\"Confirm Password\"\n * value={newPassword}\n * onChange={(e) => setNewPasswordConfirmed(e.target.value)}\n * />\n *\n * <button\n * type=\"submit\"\n * disabled={isResettingForgottenPassword || codeValidation.isInvalid || newPasswordValidation.isInvalid || newPasswordConfirmedValidation.isInvalid}\n * >\n * Change Password\n * </button>\n *\n * <p>Password Requirements</p>\n * <p>Contains a lowercase letter: {validation.hasLowercaseLetter ? 'Yes' : 'No'}</p>\n * <p>Contains an upper case letter: {validation.hasUpperCaseLetter ? 'Yes' : 'No'}</p>\n * <p>Contains a number: {validation.hasNumber ? 'Yes' : 'No'}</p>\n * <p>Contains a special character: {validation.hasSpecialCharacter ? 'Yes' : 'No'}</p>\n * <p>Contains at least 8 characters: {validation.hasMinLength ? 'Yes' : 'No'}</p>\n *\n * {forgotPasswordError && (\n * <p>{forgotPasswordError.message}</p>\n * <button type=\"button\" onClick={clearForgotPasswordError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * if (isShowingForgotPassword) {\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * sendForgotPasswordCode()\n * }}\n * >\n * <p>Enter your email address and we will send you a code to reset your password.</p>\n *\n * <input\n * type=\"email\"\n * placeholder=\"Email Address\"\n * value={username}\n * onChange={(e) => setUsername(e.target.value)}\n * />\n *\n * <p>\n * <a onClick={hideForgotPassword}>Remembered your password?</a>\n * </p>\n *\n * <button\n * type=\"submit\"\n * disabled={isSendingForgotPasswordCode || usernameValidation.isInvalid}\n * >\n * Reset Password\n * </button>\n *\n * {forgotPasswordError && (\n * <p>{forgotPasswordError.message}</p>\n * <button type=\"button\" onClick={clearForgotPasswordError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * if (isPasswordTemporary) {\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * resetTemporaryPassword()\n * }}\n * >\n * <p>The password you entered was only temporary and must be reset for security purposes. Please enter your new password below to continue.</p>\n *\n * <input\n * type=\"password\"\n * placeholder=\"New Password\"\n * value={newPassword}\n * onChange={(e) => setNewPassword(e.target.value)}\n * />\n *\n * <input\n * type=\"password\"\n * placeholder=\"Confirm Password\"\n * value={newPassword}\n * onChange={(e) => setNewPasswordConfirmed(e.target.value)}\n * />\n *\n * <button\n * type=\"submit\"\n * disabled={isResettingTemporaryPassword || newPasswordValidation.isInvalid || newPasswordConfirmedValidation.isInvalid}\n * >\n * Change Password & Sign In\n * </button>\n *\n * <p>Password Requirements</p>\n * <p>Contains a lowercase letter: {validation.hasLowercaseLetter ? 'Yes' : 'No'}</p>\n * <p>Contains an upper case letter: {validation.hasUpperCaseLetter ? 'Yes' : 'No'}</p>\n * <p>Contains a number: {validation.hasNumber ? 'Yes' : 'No'}</p>\n * <p>Contains a special character: {validation.hasSpecialCharacter ? 'Yes' : 'No'}</p>\n * <p>Contains at least 8 characters: {validation.hasMinLength ? 'Yes' : 'No'}</p>\n *\n * {loginError && (\n * <p>{loginError.message}</p>\n * <button type=\"button\" onClick={clearLoginError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * if (isMfaCodeRequired) {\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * submitMfaCode()\n * }}\n * >\n * <p>Enter the 6-digit code found in your authenticator app.</p>\n *\n * <input\n * type=\"password\"\n * placeholder=\"Code\"\n * value={code}\n * onChange={(e) => setCode(e.target.value)}\n * />\n *\n * <button\n * type=\"submit\"\n * disabled={isSubmittingMfaCode || codeValidation.isInvalid}\n * >\n * Sign In\n * </button>\n *\n * {loginError && (\n * <p>{loginError.message}</p>\n * <button type=\"button\" onClick={clearLoginError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * return (\n * <form\n * onSubmit={(e) => {\n * e.preventDefault()\n * loginWithUsernamePassword()\n * }}\n * >\n * <p>Sign in with your email address and password.</p>\n * <input\n * type=\"email\"\n * placeholder=\"Email Address\"\n * value={username}\n * onChange={(e) => setUsername(e.target.value)}\n * />\n *\n * <input\n * type=\"password\"\n * placeholder=\"New Password\"\n * value={newPassword}\n * onChange={(e) => setNewPassword(e.target.value)}\n * />\n *\n * <p>\n * <a onClick={showForgotPassword}>Forgot your password?</a>\n * </p>\n *\n * <button\n * type=\"submit\"\n * disabled={isLoggingIn || usernameValidation.isInvalid || passwordValidation.isInvalid}\n * >\n * {children}\n * </button>\n *\n * <p>or</p>\n *\n * <button\n * type=\"button\"\n * onClick={loginWithGoogle}\n * >\n * <img\n * alt=\"Google\"\n * src=\"google-sign-in.png\"\n * />\n * <span>Sign in with Google</span>\n * </button>\n *\n * {loginError && (\n * <p>{loginError.message}</p>\n * <button type=\"button\" onClick={clearLoginError}>Clear Error</button>\n * )}\n * </form>\n * )\n * }\n *\n * const root = document.getElementById('root')\n * if (root) {\n * ReactDOM.render(<App />, root)\n * }\n * ```\n *\n * @param options\n * @returns\n * @group Hooks\n */\nexport default function useLogin({\n username,\n password,\n newPassword,\n newPasswordConfirmed,\n code,\n}: {\n /** The email address entered by the user. */\n username: string\n /** The password entered by the user. */\n password: string\n /** The new password entered by the user if changing their password. */\n newPassword: string\n /**\n * The new password repeated by the user if changing their password to ensure\n * they do type it in wrong.\n */\n newPasswordConfirmed: string\n /**\n * The code sent to the user after requesting a password reset by starting the\n * \"forgot password\" process.\n */\n code: string\n}): UseLoginValue {\n const isMounted = useIsMounted()\n\n // Validation\n const usernameValidation = React.useMemo(() => {\n return {\n isInvalid: !username.trim(),\n }\n }, [username])\n\n const passwordValidation = React.useMemo(() => {\n return {\n isInvalid: !password.trim(),\n }\n }, [password])\n\n const codeValidation = React.useMemo(() => {\n return {\n isInvalid: !code.trim(),\n }\n }, [code])\n\n const newPasswordValidation = React.useMemo(() => {\n const validation = {\n hasLowercaseLetter: /[a-z]+/.test(newPassword),\n hasUpperCaseLetter: /[A-Z]+/.test(newPassword),\n hasNumber: /\\d+/.test(newPassword),\n hasSpecialCharacter: /[\\^$*.[\\]{}()?|\\-\"!@#%&/,><':;|_~`]+/.test(\n newPassword,\n ),\n hasMinLength: newPassword.length >= 8,\n isInvalid: true,\n }\n validation.isInvalid =\n !validation.hasLowercaseLetter ||\n !validation.hasUpperCaseLetter ||\n !validation.hasNumber ||\n !validation.hasSpecialCharacter ||\n !validation.hasMinLength\n return validation\n }, [newPassword])\n\n const newPasswordConfirmedValidation = React.useMemo(() => {\n return {\n isInvalid: newPassword !== newPasswordConfirmed,\n }\n }, [newPassword, newPasswordConfirmed])\n\n // Login, Reset Password, MFA\n const [\n {\n isResettingTemporaryPassword,\n isLoggingIn,\n loginError,\n loginAttemptResponse,\n isSubmittingMfaCode,\n },\n setLoginState,\n ] = React.useState<{\n isResettingTemporaryPassword: boolean\n isLoggingIn: boolean\n loginError: null | Error\n loginAttemptResponse: authService.LoginAttemptResponse | undefined\n isSubmittingMfaCode: boolean\n }>({\n isResettingTemporaryPassword: false,\n isLoggingIn: false,\n loginError: null,\n loginAttemptResponse: undefined,\n isSubmittingMfaCode: false,\n })\n const clearLoginError = React.useCallback(\n () =>\n setLoginState((current) => ({\n ...current,\n loginError: null,\n })),\n [],\n )\n const loginWithUsernamePassword = React.useCallback(async () => {\n if (usernameValidation.isInvalid) {\n setLoginState((current) => ({\n ...current,\n loginError: new Error('Please enter a valid email address'),\n }))\n return\n }\n if (passwordValidation.isInvalid) {\n setLoginState((current) => ({\n ...current,\n loginError: new Error('Please enter a valid password'),\n }))\n return\n }\n\n setLoginState((currentState) => ({\n ...currentState,\n isLoggingIn: true,\n loginError: null,\n }))\n\n try {\n const newLoginAttemptResponse = await authService.loginUsernamePassword(\n username,\n password,\n )\n if (isMounted.current) {\n setLoginState((currentState) => ({\n ...currentState,\n isLoggingIn: false,\n loginAttemptResponse: newLoginAttemptResponse,\n }))\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setLoginState((currentState) => ({\n ...currentState,\n isLoggingIn: false,\n loginError: error as Error,\n }))\n }\n }\n }, [\n isMounted,\n password,\n passwordValidation.isInvalid,\n username,\n usernameValidation.isInvalid,\n ])\n\n const resetTemporaryPassword = React.useCallback(async () => {\n const resetTemporaryPasswordCallback =\n loginAttemptResponse?.resetPasswordCallback\n if (!resetTemporaryPasswordCallback) {\n return\n }\n\n if (newPasswordValidation.isInvalid) {\n setLoginState((current) => ({\n ...current,\n loginError: new Error('Please enter a valid password'),\n }))\n return\n }\n\n if (newPasswordConfirmedValidation.isInvalid) {\n setLoginState((current) => ({\n ...current,\n loginError: new Error('Please confirm your new password'),\n }))\n return\n }\n\n setLoginState((current) => ({\n ...current,\n isResettingPassword: true,\n loginError: null,\n }))\n\n try {\n const resetPasswordResponse = await resetTemporaryPasswordCallback(\n newPassword,\n )\n if (isMounted.current) {\n setLoginState((currentState) => ({\n ...currentState,\n isResettingTemporaryPassword: false,\n loginAttemptResponse: resetPasswordResponse,\n }))\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setLoginState((current) => ({\n ...current,\n isResettingPassword: false,\n loginError: error as Error,\n }))\n }\n }\n }, [\n isMounted,\n loginAttemptResponse?.resetPasswordCallback,\n newPassword,\n newPasswordConfirmedValidation.isInvalid,\n newPasswordValidation.isInvalid,\n ])\n\n const submitMfaCode = React.useCallback(async () => {\n const mfaCodeCallback = loginAttemptResponse?.mfaCodeCallback\n if (!mfaCodeCallback) {\n return\n }\n\n setLoginState((current) => ({\n ...current,\n isSubmittingMfaCode: true,\n loginError: null,\n }))\n\n try {\n const mfaResponse = await mfaCodeCallback(code)\n if (isMounted.current) {\n setLoginState((currentState) => ({\n ...currentState,\n isSubmittingMfaCode: false,\n loginAttemptResponse: mfaResponse,\n }))\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setLoginState((current) => ({\n ...current,\n isSubmittingMfaCode: false,\n loginError: error as Error,\n }))\n }\n }\n }, [code, isMounted, loginAttemptResponse?.mfaCodeCallback])\n\n // Forgot Password\n const [isShowingForgotPassword, showForgotPassword, hideForgotPassword] =\n useBooleanState(false)\n const [\n {\n resetForgottenPasswordCallback,\n isSendingForgotPasswordCode,\n isResettingForgottenPassword,\n forgotPasswordError,\n },\n setForgotPasswordState,\n ] = React.useState<{\n isSendingForgotPasswordCode: boolean\n forgotPasswordError: null | Error\n resetForgottenPasswordCallback:\n | null\n | ((code: string, newPassword: string) => void)\n isResettingForgottenPassword: boolean\n }>({\n isSendingForgotPasswordCode: false,\n forgotPasswordError: null,\n resetForgottenPasswordCallback: null,\n isResettingForgottenPassword: false,\n })\n const clearForgotPasswordError = React.useCallback(\n () =>\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: null,\n })),\n [],\n )\n const sendForgotPasswordCode = React.useCallback(async () => {\n if (usernameValidation.isInvalid) {\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: new Error('Please enter a valid email address'),\n }))\n return\n }\n\n setForgotPasswordState({\n isSendingForgotPasswordCode: true,\n resetForgottenPasswordCallback: null,\n forgotPasswordError: null,\n isResettingForgottenPassword: false,\n })\n\n try {\n const newResetForgottenPasswordCallback =\n await authService.forgotPassword(username)\n if (isMounted.current) {\n setForgotPasswordState({\n isSendingForgotPasswordCode: false,\n resetForgottenPasswordCallback: newResetForgottenPasswordCallback,\n forgotPasswordError: null,\n isResettingForgottenPassword: false,\n })\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setForgotPasswordState({\n isSendingForgotPasswordCode: false,\n resetForgottenPasswordCallback: null,\n forgotPasswordError: error as Error,\n isResettingForgottenPassword: false,\n })\n }\n }\n }, [isMounted, username, usernameValidation.isInvalid])\n\n const resetForgottenPassword = React.useCallback(async () => {\n if (!resetForgottenPasswordCallback) {\n return\n }\n\n if (codeValidation.isInvalid) {\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: new Error(\n 'Please enter the code that was sent to your email address',\n ),\n }))\n }\n if (newPasswordValidation.isInvalid) {\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: new Error('Please enter a valid password'),\n }))\n return\n }\n if (newPasswordConfirmedValidation.isInvalid) {\n setForgotPasswordState((current) => ({\n ...current,\n forgotPasswordError: new Error('Please confirm your new password'),\n }))\n return\n }\n\n setForgotPasswordState((current) => ({\n ...current,\n isChangingPassword: true,\n forgotPasswordError: null,\n }))\n\n try {\n await resetForgottenPasswordCallback(code, newPassword)\n if (isMounted.current) {\n setForgotPasswordState({\n isSendingForgotPasswordCode: false,\n resetForgottenPasswordCallback: null,\n forgotPasswordError: null,\n isResettingForgottenPassword: false,\n })\n hideForgotPassword()\n }\n } catch (error) {\n Sentry.captureException(error)\n if (isMounted.current) {\n setForgotPasswordState((current) => ({\n ...current,\n isChangingPassword: false,\n forgotPasswordError: error as Error,\n }))\n }\n }\n }, [\n resetForgottenPasswordCallback,\n codeValidation.isInvalid,\n newPasswordValidation.isInvalid,\n newPasswordConfirmedValidation.isInvalid,\n code,\n newPassword,\n isMounted,\n hideForgotPassword,\n ])\n\n const loginWithGoogle = React.useCallback(() => {\n authService.loginHostedUI('Google')\n }, [])\n\n return {\n // Login\n /** Open redirect user to the Google sign in */\n loginWithGoogle,\n loginWithUsernamePassword,\n isLoggingIn,\n loginError,\n clearLoginError,\n // Reset Temp Password\n isPasswordTemporary: !!loginAttemptResponse?.resetPasswordCallback,\n isResettingTemporaryPassword,\n resetTemporaryPassword,\n // MFA Code\n isMfaCodeRequired: !!loginAttemptResponse?.mfaCodeCallback,\n isSubmittingMfaCode,\n submitMfaCode,\n // Showing Forgot Password\n isShowingForgotPassword,\n showForgotPassword,\n hideForgotPassword,\n forgotPasswordError,\n clearForgotPasswordError,\n // Sending Forgot Password Code\n isSendingForgotPasswordCode,\n sendForgotPasswordCode,\n // Resetting Forgotten Password\n hasSentForgotPasswordCode: !!resetForgottenPasswordCallback,\n isResettingForgottenPassword,\n resetForgottenPassword,\n // Validation\n usernameValidation,\n passwordValidation,\n codeValidation,\n newPasswordValidation,\n newPasswordConfirmedValidation,\n }\n}\n\nexport interface UseLoginValue {\n /** Open redirect user to the Google sign-in page. */\n loginWithGoogle: () => void\n /**\n * Attempt to use the `username` and `password` arguments to create a session.\n * Will call `onLogin()` if successful, otherwise will set `loginError`.\n */\n loginWithUsernamePassword: () => void\n /** `true` while processing `loginWithUsernamePassword()`. */\n isLoggingIn: boolean\n /**\n * `true` if the user logged in using a temporary password. Prompt the user\n * for a new password and call `resetTemporaryPassword()`.\n */\n isPasswordTemporary: boolean\n /**\n * Attempt to use `newPassword` and `newPasswordConfirmed` arguments to reset\n * the user's password and create a session. Will call `onLogin()` if\n * successful, otherwise will set `loginError`.\n */\n resetTemporaryPassword: () => void\n /**\n * Set if an error occurs while processing `loginWithUsernamePassword()` or\n * `resetTemporaryPassword()`.\n */\n loginError: Error | null\n /** Set `loginError` back to `null`. */\n clearLoginError: () => void\n /** `true` while processing `resetTemporaryPassword()`. */\n isResettingTemporaryPassword: boolean\n /** `true` when showing the forgot password flow. */\n isShowingForgotPassword: boolean\n /** Set `isShowingForgotPassword` to `true`. */\n showForgotPassword: () => void\n /** Set `isShowingForgotPassword` to `false`. */\n hideForgotPassword: () => void\n /**\n * Attempt to use the `username` argument to start the forgot password\n * process. This will send the user an email with a code to enter. A failed\n * request will set `forgotPasswordError`.\n */\n sendForgotPasswordCode: () => void\n /** `true` while processing `sendForgotPasswordCode()`. */\n isSendingForgotPasswordCode: boolean\n /** `true` if the forgot password code has been successfully sent to the user. */\n hasSentForgotPasswordCode: boolean\n /**\n * Attempt to use the `code`, `newPassword`, and `newPasswordConfirmed`\n * arguments to reset the user's password. A failed request will set\n * `forgotPasswordError`.\n */\n resetForgottenPassword: () => void\n /** `true` while processing `resetForgottenPassword()`. */\n isResettingForgottenPassword: boolean\n /**\n * Set if an error occurs while processing `sendForgotPasswordCode()` or\n * `resetForgottenPassword()`.\n */\n forgotPasswordError: Error | null\n /** Set `forgotPasswordError` back to `null`. */\n clearForgotPasswordError: () => void\n usernameValidation: {\n /** `true` if the `username` argument is invalid. */\n isInvalid: boolean\n }\n passwordValidation: {\n /** `true` if the `password` argument is invalid. */\n isInvalid: boolean\n }\n codeValidation: {\n /** `true` if the `code` argument is invalid. */\n isInvalid: boolean\n }\n newPasswordValidation: {\n /** `true` if the `newPassword` argument is invalid. */\n isInvalid: boolean\n /**\n * `true` if the `newPassword` argument has a lowercase letter (required to\n * be valid).\n */\n hasLowercaseLetter: boolean\n /**\n * `true` if the `newPassword` argument has an uppercase letter (required to\n * be valid).\n */\n hasUpperCaseLetter: boolean\n /** `true` if the `newPassword` argument has a number (required to be valid). */\n hasNumber: boolean\n /**\n * `true` if the `newPassword` argument has a special character (required to\n * be valid).\n */\n hasSpecialCharacter: boolean\n /**\n * `true` if the `newPassword` argument has at least the minimum number of\n * characters (required to be valid).\n */\n hasMinLength: boolean\n }\n newPasswordConfirmedValidation: {\n /**\n * `true` if the `newPasswordConfirmed` argument is invalid (must match the\n * `newPassword` argument).\n */\n isInvalid: boolean\n }\n /**\n * `true` if the user logged in using MFA and a code is required to finish the\n * login attempt. Prompt the user for a code and call `submitMfaCode()`.\n */\n isMfaCodeRequired: boolean\n /** `true` while processing `submitMfaCode()`. */\n isSubmittingMfaCode: boolean\n /**\n * Attempt to use `code` argument to submit the MFA code and create a session.\n * Will call `onLogin()` if successful, otherwise will set `loginError`.\n */\n submitMfaCode: () => void\n}\n"]}
|
@@ -33,8 +33,10 @@ import * as React from 'react';
|
|
33
33
|
* unsetUserProfile()
|
34
34
|
* ```
|
35
35
|
*
|
36
|
+
* @typeParam T The type of the state
|
36
37
|
* @param defaultValue
|
37
38
|
* @returns
|
39
|
+
* @group Hooks
|
38
40
|
*/
|
39
41
|
export default function useNullableState<T>(
|
40
42
|
/** The starting state for the hook. */
|
@@ -33,8 +33,10 @@ import * as React from 'react';
|
|
33
33
|
* unsetUserProfile()
|
34
34
|
* ```
|
35
35
|
*
|
36
|
+
* @typeParam T The type of the state
|
36
37
|
* @param defaultValue
|
37
38
|
* @returns
|
39
|
+
* @group Hooks
|
38
40
|
*/
|
39
41
|
export default function useNullableState(
|
40
42
|
/** The starting state for the hook. */
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"useNullableState.js","sourceRoot":"","sources":["../../src/hooks/useNullableState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B
|
1
|
+
{"version":3,"file":"useNullableState.js","sourceRoot":"","sources":["../../src/hooks/useNullableState.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAE9B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,MAAM,CAAC,OAAO,UAAU,gBAAgB;AACtC,uCAAuC;AACvC,YAAsB;IAMtB,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAA;IACtD,MAAM,UAAU,GAAG,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,CAAA;IAC9D,OAAO,CAAC,KAAK,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAA;AACtC,CAAC","sourcesContent":["import * as React from 'react'\n\n/**\n * This function is a react hook for state of type of your choosing. It comes\n * with two memoized functions, one for setting state and one for clearing it.\n *\n * The items returned in the array can be destructured and named whatever you\n * like:\n *\n * ```js\n * import { useNullableState } from '@oneblink/apps-react'\n *\n * const startingProfile = {\n * name: 'Forest Gump',\n * profession: 'Military, Athlete, Other',\n * }\n *\n * const [userProfile, setUserProfile, unsetUserProfile] =\n * useBooleanState(startingProfile)\n * ```\n *\n * `setUserProfile` can then be called with an object of type `T` like:\n *\n * ```js\n * setUserProfile({\n * name: 'Walter White',\n * profession: 'Chemistry Teacher (Secondary School), Other',\n * })\n * ```\n *\n * And `unsetUserProfile` can be called like:\n *\n * ```js\n * unsetUserProfile()\n * ```\n *\n * @typeParam T The type of the state\n * @param defaultValue\n * @returns\n * @group Hooks\n */\nexport default function useNullableState<T>(\n /** The starting state for the hook. */\n defaultValue: T | null,\n): [\n state: T | null,\n setState: React.Dispatch<React.SetStateAction<T | null>>,\n clearState: () => void,\n] {\n const [state, setState] = React.useState(defaultValue)\n const unsetState = React.useCallback(() => setState(null), [])\n return [state, setState, unsetState]\n}\n"]}
|
@@ -28,6 +28,11 @@ export type PendingSubmissionsContextValue = {
|
|
28
28
|
hideFailedNotification: () => unknown;
|
29
29
|
/** `true` if a submission being processed completes successfully. */
|
30
30
|
isShowingSuccessNotification: boolean;
|
31
|
+
/**
|
32
|
+
* A function to hide the notification after a submission completed
|
33
|
+
* successfully
|
34
|
+
*/
|
35
|
+
hideSuccessNotification: () => unknown;
|
31
36
|
};
|
32
37
|
/**
|
33
38
|
* React Component that provides the context for the `usePendingSubmissions()`
|
@@ -39,7 +44,10 @@ export type PendingSubmissionsContextValue = {
|
|
39
44
|
*
|
40
45
|
* ```jsx
|
41
46
|
* import * as React from 'react'
|
42
|
-
* import {
|
47
|
+
* import {
|
48
|
+
* PendingSubmissionsContextProvider,
|
49
|
+
* usePendingSubmissions,
|
50
|
+
* } from '@oneblink/apps-react'
|
43
51
|
*
|
44
52
|
* function Component() {
|
45
53
|
* const pendingSubmissionsContext = usePendingSubmissions()
|