@aws-amplify/ui-react-core 0.0.0-react-v4-next-e3ffde5-20230811190323 → 0.0.0-react-18-c03bcb0-20231023181427

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.
Files changed (80) hide show
  1. package/dist/esm/Authenticator/context/AuthenticatorContext.mjs +2 -2
  2. package/dist/esm/Authenticator/context/AuthenticatorProvider.mjs +8 -8
  3. package/dist/esm/Authenticator/hooks/useAuthenticator/useAuthenticator.mjs +12 -7
  4. package/dist/esm/Authenticator/hooks/useAuthenticator/utils.mjs +6 -10
  5. package/dist/esm/Authenticator/hooks/useAuthenticatorInitMachine/useAuthenticatorInitMachine.mjs +3 -3
  6. package/dist/esm/Authenticator/hooks/useAuthenticatorRoute/constants.mjs +3 -0
  7. package/dist/esm/Authenticator/hooks/useAuthenticatorRoute/utils.mjs +45 -13
  8. package/dist/esm/Authenticator/hooks/utils.mjs +2 -2
  9. package/dist/esm/components/FormCore/FormProvider.mjs +16 -0
  10. package/dist/esm/components/FormCore/useField.mjs +20 -0
  11. package/dist/esm/components/FormCore/useForm.mjs +51 -0
  12. package/dist/esm/components/FormCore/withFormProvider.mjs +15 -0
  13. package/dist/esm/hooks/useDeprecationWarning.mjs +19 -0
  14. package/dist/esm/hooks/useHasValueUpdated.mjs +13 -0
  15. package/dist/esm/hooks/useTimeout.mjs +22 -0
  16. package/dist/esm/index.mjs +8 -2
  17. package/dist/esm/utils/createContextUtilities.mjs +81 -0
  18. package/dist/index.js +297 -71
  19. package/dist/types/Authenticator/hooks/types.d.ts +14 -13
  20. package/dist/types/components/FormCore/FormProvider.d.ts +4 -0
  21. package/dist/types/components/FormCore/index.d.ts +5 -0
  22. package/dist/types/components/FormCore/types.d.ts +217 -0
  23. package/dist/types/components/FormCore/useControlledField.d.ts +9 -0
  24. package/dist/types/components/FormCore/useField.d.ts +9 -0
  25. package/dist/types/components/FormCore/useForm.d.ts +12 -0
  26. package/dist/types/components/FormCore/withFormProvider.d.ts +8 -0
  27. package/dist/types/components/index.d.ts +1 -0
  28. package/dist/types/hooks/index.d.ts +3 -1
  29. package/dist/types/hooks/useDeprecationWarning.d.ts +13 -0
  30. package/dist/types/hooks/useHasValueUpdated.d.ts +13 -0
  31. package/dist/types/hooks/useTimeout.d.ts +4 -0
  32. package/dist/types/index.d.ts +4 -3
  33. package/dist/types/types/index.d.ts +1 -0
  34. package/dist/types/types/types.d.ts +3 -0
  35. package/dist/types/utils/createContextUtilities.d.ts +68 -0
  36. package/dist/types/utils/index.d.ts +1 -1
  37. package/package.json +11 -28
  38. package/src/Authenticator/context/AuthenticatorContext.tsx +17 -0
  39. package/src/Authenticator/context/AuthenticatorProvider.tsx +82 -0
  40. package/src/Authenticator/context/index.ts +2 -0
  41. package/src/Authenticator/hooks/constants.ts +30 -0
  42. package/src/Authenticator/hooks/index.ts +5 -0
  43. package/src/Authenticator/hooks/types.ts +215 -0
  44. package/src/Authenticator/hooks/useAuthenticator/__mock__/useAuthenticator.ts +68 -0
  45. package/src/Authenticator/hooks/useAuthenticator/constants.ts +2 -0
  46. package/src/Authenticator/hooks/useAuthenticator/index.ts +2 -0
  47. package/src/Authenticator/hooks/useAuthenticator/types.ts +51 -0
  48. package/src/Authenticator/hooks/useAuthenticator/useAuthenticator.ts +73 -0
  49. package/src/Authenticator/hooks/useAuthenticator/utils.ts +104 -0
  50. package/src/Authenticator/hooks/useAuthenticatorInitMachine/index.ts +1 -0
  51. package/src/Authenticator/hooks/useAuthenticatorInitMachine/useAuthenticatorInitMachine.tsx +25 -0
  52. package/src/Authenticator/hooks/useAuthenticatorRoute/constants.ts +104 -0
  53. package/src/Authenticator/hooks/useAuthenticatorRoute/index.ts +2 -0
  54. package/src/Authenticator/hooks/useAuthenticatorRoute/types.ts +113 -0
  55. package/src/Authenticator/hooks/useAuthenticatorRoute/useAuthenticatorRoute.ts +126 -0
  56. package/src/Authenticator/hooks/useAuthenticatorRoute/utils.ts +207 -0
  57. package/src/Authenticator/hooks/utils.ts +38 -0
  58. package/src/Authenticator/index.ts +23 -0
  59. package/src/components/FormCore/FormProvider.tsx +37 -0
  60. package/src/components/FormCore/index.ts +13 -0
  61. package/src/components/FormCore/types.ts +277 -0
  62. package/src/components/FormCore/useControlledField.ts +73 -0
  63. package/src/components/FormCore/useField.ts +25 -0
  64. package/src/components/FormCore/useForm.ts +84 -0
  65. package/src/components/FormCore/withFormProvider.tsx +31 -0
  66. package/src/components/RenderNothing/RenderNothing.tsx +6 -0
  67. package/src/components/RenderNothing/index.ts +1 -0
  68. package/src/components/index.ts +15 -0
  69. package/src/hooks/index.ts +7 -0
  70. package/src/hooks/useDeprecationWarning.ts +27 -0
  71. package/src/hooks/useHasValueUpdated.ts +28 -0
  72. package/src/hooks/usePreviousValue.ts +15 -0
  73. package/src/hooks/useTimeout.ts +30 -0
  74. package/src/index.ts +47 -0
  75. package/src/types/index.ts +1 -0
  76. package/src/types/types.ts +3 -0
  77. package/src/utils/createContextUtilities.tsx +131 -0
  78. package/src/utils/index.ts +1 -0
  79. package/dist/esm/node_modules/tslib/tslib.es6.mjs +0 -38
  80. package/dist/esm/utils/index.mjs +0 -7
@@ -1,10 +1,10 @@
1
- import React from 'react';
1
+ import React__default from 'react';
2
2
 
3
3
  /**
4
4
  * AuthenticatorContext serves static reference to the auth machine service.
5
5
  *
6
6
  * https://xstate.js.org/docs/recipes/react.html#context-provider
7
7
  */
8
- const AuthenticatorContext = React.createContext(null);
8
+ const AuthenticatorContext = React__default.createContext(null);
9
9
 
10
10
  export { AuthenticatorContext };
@@ -1,21 +1,21 @@
1
- import { __awaiter } from '../../node_modules/tslib/tslib.es6.mjs';
2
- import React, { useContext, useMemo, useEffect } from 'react';
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import React__default, { useContext, useMemo, useEffect } from 'react';
3
3
  import { useInterpret } from '@xstate/react';
4
4
  import { Auth } from 'aws-amplify';
5
5
  import { createAuthenticatorMachine, listenToAuthHub, defaultAuthHubHandler } from '@aws-amplify/ui';
6
6
  import { AuthenticatorContext } from './AuthenticatorContext.mjs';
7
7
 
8
- const createHubHandler = (options) => (data, service) => __awaiter(void 0, void 0, void 0, function* () {
9
- yield defaultAuthHubHandler(data, service, options);
10
- });
8
+ const createHubHandler = (options) => async (data, service) => {
9
+ await defaultAuthHubHandler(data, service, options);
10
+ };
11
11
  function AuthenticatorProvider({ children, }) {
12
12
  // `authStatus` is exposed by `useAuthenticator` but should not be derived directly from the
13
13
  // state machine as the machine only updates on `Authenticator` initiated events, which
14
14
  // leads to scenarios where the state machine `authStatus` gets "stuck". For exmample,
15
15
  // if a user was to sign in using `Auth.signIn` directly rather than using `Authenticator`
16
- const [authStatus, setAuthStatus] = React.useState('configuring');
16
+ const [authStatus, setAuthStatus] = React__default.useState('configuring');
17
17
  // only run on first render
18
- React.useEffect(() => {
18
+ React__default.useEffect(() => {
19
19
  Auth.currentAuthenticatedUser()
20
20
  .then(() => {
21
21
  setAuthStatus('authenticated');
@@ -45,7 +45,7 @@ function AuthenticatorProvider({ children, }) {
45
45
  const unsubscribe = listenToAuthHub(activeService, createHubHandler({ onSignIn, onSignOut }));
46
46
  return unsubscribe;
47
47
  }, [activeService]);
48
- return (React.createElement(AuthenticatorContext.Provider, { value: value }, children));
48
+ return (jsx(AuthenticatorContext.Provider, { value: value, children: children }));
49
49
  }
50
50
 
51
51
  export { AuthenticatorProvider as default };
@@ -1,7 +1,7 @@
1
- import { __rest } from '../../../node_modules/tslib/tslib.es6.mjs';
2
- import React, { useCallback } from 'react';
1
+ import React__default, { useCallback } from 'react';
3
2
  import { useSelector } from '@xstate/react';
4
3
  import { getServiceFacade } from '@aws-amplify/ui';
4
+ import 'react/jsx-runtime';
5
5
  import 'aws-amplify';
6
6
  import { AuthenticatorContext } from '../../context/AuthenticatorContext.mjs';
7
7
  import { USE_AUTHENTICATOR_ERROR } from './constants.mjs';
@@ -11,19 +11,19 @@ import { getQRFields, getMachineFields, getTotpSecretCodeCallback, getComparator
11
11
  * [📖 Docs](https://ui.docs.amplify.aws/react/connected-components/authenticator/headless#useauthenticator-hook)
12
12
  */
13
13
  function useAuthenticator(selector) {
14
- const context = React.useContext(AuthenticatorContext);
14
+ const context = React__default.useContext(AuthenticatorContext);
15
15
  if (!context) {
16
16
  throw new Error(USE_AUTHENTICATOR_ERROR);
17
17
  }
18
18
  const { service } = context;
19
19
  const { send } = service;
20
- const xstateSelector = useCallback((state) => (Object.assign({}, getServiceFacade({ send, state }))), [send]);
20
+ const xstateSelector = useCallback((state) => ({ ...getServiceFacade({ send, state }) }), [send]);
21
21
  const comparator = selector ? getComparator(selector) : defaultComparator;
22
22
  // the purpose of `context.authStatus`is to intentionally override `facade.authStatus`. `facade.authStatus` does
23
23
  // not update on external sign in events (for example when a user is not using the `Authenticator`).
24
24
  const { authStatus } = context;
25
25
  const facade = useSelector(service, xstateSelector, comparator);
26
- const { route, totpSecretCode, unverifiedContactMethods, user } = facade, rest = __rest(facade, ["route", "totpSecretCode", "unverifiedContactMethods", "user"]);
26
+ const { route, totpSecretCode, unverifiedContactMethods, user, ...rest } = facade;
27
27
  // do not memoize output. `service.getSnapshot` reference remains stable preventing
28
28
  // `fields` from updating with current form state on value changes
29
29
  const serviceSnapshot = service.getSnapshot();
@@ -31,13 +31,18 @@ function useAuthenticator(selector) {
31
31
  const QRFields = route === 'setupTOTP' ? getQRFields(serviceSnapshot) : null;
32
32
  // legacy `formFields` values required until form state is removed from state machine
33
33
  const fields = getMachineFields(route, serviceSnapshot, unverifiedContactMethods);
34
- return Object.assign(Object.assign({}, rest), { authStatus,
34
+ return {
35
+ ...rest,
36
+ authStatus,
35
37
  route,
36
38
  totpSecretCode,
37
39
  unverifiedContactMethods,
38
40
  user,
39
41
  /** @deprecated For internal use only */
40
- fields, getTotpSecretCode: getTotpSecretCodeCallback(user), QRFields });
42
+ fields,
43
+ getTotpSecretCode: getTotpSecretCodeCallback(user),
44
+ QRFields,
45
+ };
41
46
  }
42
47
 
43
48
  export { useAuthenticator as default };
@@ -1,4 +1,3 @@
1
- import { __awaiter } from '../../../node_modules/tslib/tslib.es6.mjs';
2
1
  import { Auth } from 'aws-amplify';
3
2
  import { getActorContext, getSortedFormFields, isString, areEmptyArrays, areEmptyObjects } from '@aws-amplify/ui';
4
3
  import { isComponentRouteKey } from '../utils.mjs';
@@ -27,16 +26,13 @@ const getComparator = (selector) => (currentFacade, nextFacade) => {
27
26
  // Shallow compare the array values
28
27
  return areSelectorDepsEqual(currentSelectorDeps, nextSelectorDeps);
29
28
  };
30
- const getQRFields = (state) => {
31
- var _a, _b, _c;
32
- return (Object.assign({}, (_c = (_b = (_a = getActorContext(state)) === null || _a === void 0 ? void 0 : _a.formFields) === null || _b === void 0 ? void 0 : _b.setupTOTP) === null || _c === void 0 ? void 0 : _c.QR));
29
+ const getQRFields = (state) => ({
30
+ ...getActorContext(state)?.formFields?.setupTOTP?.QR,
31
+ });
32
+ const getTotpSecretCodeCallback = (user) => async function getTotpSecretCode() {
33
+ return await Auth.setupTOTP(user);
33
34
  };
34
- const getTotpSecretCodeCallback = (user) => function getTotpSecretCode() {
35
- return __awaiter(this, void 0, void 0, function* () {
36
- return yield Auth.setupTOTP(user);
37
- });
38
- };
39
- const flattenFormFields = (fields) => fields.flatMap(([name, options]) => (Object.assign({ name }, options)));
35
+ const flattenFormFields = (fields) => fields.flatMap(([name, options]) => ({ name, ...options }));
40
36
  const convertContactMethodsToFields = (unverifiedContactMethods) => {
41
37
  return (unverifiedContactMethods &&
42
38
  Object.entries(unverifiedContactMethods).map(([name, value]) => {
@@ -1,12 +1,12 @@
1
- import React from 'react';
1
+ import React__default from 'react';
2
2
  import useAuthenticator from '../useAuthenticator/useAuthenticator.mjs';
3
3
 
4
4
  // only select `route` from machine context
5
5
  const routeSelector = ({ route }) => [route];
6
6
  function useAuthenticatorInitMachine(data) {
7
7
  const { route, initializeMachine } = useAuthenticator(routeSelector);
8
- const hasInitialized = React.useRef(false);
9
- React.useEffect(() => {
8
+ const hasInitialized = React__default.useRef(false);
9
+ React__default.useEffect(() => {
10
10
  if (!hasInitialized.current && route === 'setup') {
11
11
  initializeMachine(data);
12
12
  hasInitialized.current = true;
@@ -12,6 +12,7 @@ const COMMON_ROUTE_MACHINE_KEYS = [
12
12
  ];
13
13
  const CONFIRM_RESET_PASSWORD_MACHINE_KEYS = [
14
14
  ...COMMON_ROUTE_MACHINE_KEYS,
15
+ 'hasValidationErrors',
15
16
  'resendCode',
16
17
  'validationErrors',
17
18
  ];
@@ -31,6 +32,7 @@ const CONFIRM_VERIFY_USER_MACHINE_KEYS = [
31
32
  ];
32
33
  const FORCE_NEW_PASSWORD_MACHINE_KEYS = [
33
34
  ...COMMON_ROUTE_MACHINE_KEYS,
35
+ 'hasValidationErrors',
34
36
  'toSignIn',
35
37
  'validationErrors',
36
38
  ];
@@ -46,6 +48,7 @@ const SIGN_IN_MACHINE_KEYS = [
46
48
  ];
47
49
  const SIGN_UP_MACHINE_KEYS = [
48
50
  ...COMMON_ROUTE_MACHINE_KEYS,
51
+ 'hasValidationErrors',
49
52
  'toSignIn',
50
53
  'validationErrors',
51
54
  ];
@@ -1,4 +1,8 @@
1
- import { __rest } from '../../../node_modules/tslib/tslib.es6.mjs';
1
+ import 'react';
2
+ import 'react-hook-form';
3
+ import '@aws-amplify/ui';
4
+ import '../../../components/FormCore/FormProvider.mjs';
5
+ import 'react/jsx-runtime';
2
6
  import RenderNothing from '../../../components/RenderNothing/RenderNothing.mjs';
3
7
  import { isComponentRouteKey } from '../utils.mjs';
4
8
  import { MACHINE_PROP_KEYS, EVENT_HANDLER_KEY_MAP } from './constants.mjs';
@@ -15,47 +19,68 @@ const getRouteMachineSelector = (route) => isComponentRouteKey(route)
15
19
  : routeSelector;
16
20
  const isFormEventHandlerKey = (key) => ['updateBlur', 'updateForm', 'submitForm'].includes(key);
17
21
  const convertEventHandlerKey = (key) => EVENT_HANDLER_KEY_MAP[key];
18
- const getConvertedMachineProps = (route, context) => MACHINE_PROP_KEYS[route].reduce((acc, key) => (Object.assign(Object.assign({}, acc), { [isFormEventHandlerKey(key) ? convertEventHandlerKey(key) : key]: context[key] })), {});
22
+ const getConvertedMachineProps = (route, context) => MACHINE_PROP_KEYS[route].reduce((acc, key) => ({
23
+ ...acc,
24
+ [isFormEventHandlerKey(key) ? convertEventHandlerKey(key) : key]: context[key],
25
+ }), {});
19
26
  function resolveConfirmResetPasswordRoute(Component, props) {
20
27
  return {
21
28
  Component,
22
- props: Object.assign(Object.assign({}, Component), getConvertedMachineProps('confirmResetPassword', props)),
29
+ props: {
30
+ ...Component,
31
+ ...getConvertedMachineProps('confirmResetPassword', props),
32
+ },
23
33
  };
24
34
  }
25
35
  function resolveConfirmSignInRoute(Component, props) {
26
- const _a = getConvertedMachineProps('confirmSignIn', props), { user } = _a, machineProps = __rest(_a, ["user"]);
36
+ const { user, ...machineProps } = getConvertedMachineProps('confirmSignIn', props);
27
37
  // prior to the `confirmSignIn` route, `user.username` is populated
28
38
  const challengeName = user.challengeName;
29
- return { Component, props: Object.assign(Object.assign(Object.assign({}, Component), machineProps), { challengeName }) };
39
+ return { Component, props: { ...Component, ...machineProps, challengeName } };
30
40
  }
31
41
  function resolveConfirmSignUpRoute(Component, props) {
32
42
  return {
33
43
  Component,
34
- props: Object.assign(Object.assign({}, Component), getConvertedMachineProps('confirmSignUp', props)),
44
+ props: {
45
+ ...Component,
46
+ ...getConvertedMachineProps('confirmSignUp', props),
47
+ },
35
48
  };
36
49
  }
37
50
  function resolveConfirmVerifyUserRoute(Component, props) {
38
51
  return {
39
52
  Component,
40
- props: Object.assign(Object.assign({}, Component), getConvertedMachineProps('confirmVerifyUser', props)),
53
+ props: {
54
+ ...Component,
55
+ ...getConvertedMachineProps('confirmVerifyUser', props),
56
+ },
41
57
  };
42
58
  }
43
59
  function resolveForceNewPasswordRoute(Component, props) {
44
60
  return {
45
61
  Component,
46
- props: Object.assign(Object.assign({}, Component), getConvertedMachineProps('forceNewPassword', props)),
62
+ props: {
63
+ ...Component,
64
+ ...getConvertedMachineProps('forceNewPassword', props),
65
+ },
47
66
  };
48
67
  }
49
68
  function resolveResetPasswordRoute(Component, props) {
50
69
  return {
51
70
  Component,
52
- props: Object.assign(Object.assign({}, Component), getConvertedMachineProps('resetPassword', props)),
71
+ props: {
72
+ ...Component,
73
+ ...getConvertedMachineProps('resetPassword', props),
74
+ },
53
75
  };
54
76
  }
55
77
  function resolveSetupTOTPRoute(Component, props) {
56
78
  return {
57
79
  Component,
58
- props: Object.assign(Object.assign({}, Component), getConvertedMachineProps('setupTOTP', props)),
80
+ props: {
81
+ ...Component,
82
+ ...getConvertedMachineProps('setupTOTP', props),
83
+ },
59
84
  };
60
85
  }
61
86
  function resolveSignInRoute(Component, props) {
@@ -63,19 +88,26 @@ function resolveSignInRoute(Component, props) {
63
88
  const hideSignUp = false;
64
89
  return {
65
90
  Component,
66
- props: Object.assign(Object.assign(Object.assign({}, Component), getConvertedMachineProps('signIn', props)), { hideSignUp }),
91
+ props: {
92
+ ...Component,
93
+ ...getConvertedMachineProps('signIn', props),
94
+ hideSignUp,
95
+ },
67
96
  };
68
97
  }
69
98
  function resolveSignUpRoute(Component, props) {
70
99
  return {
71
100
  Component,
72
- props: Object.assign(Object.assign({}, Component), getConvertedMachineProps('signUp', props)),
101
+ props: { ...Component, ...getConvertedMachineProps('signUp', props) },
73
102
  };
74
103
  }
75
104
  function resolveVerifyUserRoute(Component, props) {
76
105
  return {
77
106
  Component,
78
- props: Object.assign(Object.assign({}, Component), getConvertedMachineProps('verifyUser', props)),
107
+ props: {
108
+ ...Component,
109
+ ...getConvertedMachineProps('verifyUser', props),
110
+ },
79
111
  };
80
112
  }
81
113
  function resolveDefault() {
@@ -9,7 +9,7 @@ function resolveAuthenticatorComponents(defaults, overrides) {
9
9
  const Default = defaults[route];
10
10
  const Override = overrides[route];
11
11
  if (typeof Override !== 'function') {
12
- return Object.assign(Object.assign({}, components), { [route]: Default });
12
+ return { ...components, [route]: Default };
13
13
  }
14
14
  const { Footer, FormFields, Header } = Default;
15
15
  // cast to allow assigning of component slots
@@ -17,7 +17,7 @@ function resolveAuthenticatorComponents(defaults, overrides) {
17
17
  Component.Footer = Footer;
18
18
  Component.FormFields = FormFields;
19
19
  Component.Header = Header;
20
- return Object.assign(Object.assign({}, components), { [route]: Component });
20
+ return { ...components, [route]: Component };
21
21
  }, {});
22
22
  }
23
23
 
@@ -0,0 +1,16 @@
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import React__default from 'react';
3
+ import { useForm, FormProvider as FormProvider$1 } from 'react-hook-form';
4
+
5
+ const DEFAULT_MODE = 'onTouched';
6
+ const FormProvider = React__default.forwardRef(function FormProvider({ children, defaultValues, mode = DEFAULT_MODE }, ref) {
7
+ const formProviderProps = useForm({
8
+ defaultValues,
9
+ mode,
10
+ });
11
+ const { getValues, reset } = formProviderProps;
12
+ React__default.useImperativeHandle(ref, () => ({ getValues, reset: () => reset(defaultValues) }), [defaultValues, getValues, reset]);
13
+ return (jsx(FormProvider$1, { ...formProviderProps, children: children }));
14
+ });
15
+
16
+ export { FormProvider as default };
@@ -0,0 +1,20 @@
1
+ import useForm from './useForm.mjs';
2
+
3
+ const DEFAULT_ERROR_MESSAGE = '`useField` must be used within a `FormProvider`';
4
+ /**
5
+ * `Field` integration hook for usage with React `Field` components.
6
+ *
7
+ * @param params Requires `name`, all additional params optional
8
+ * @returns `Form` aware `Field` event handlers and state values
9
+ */
10
+ function useField(params) {
11
+ const { getFieldState, registerField } = useForm({
12
+ errorMessage: DEFAULT_ERROR_MESSAGE,
13
+ });
14
+ return {
15
+ ...registerField(params),
16
+ ...getFieldState(params.name),
17
+ };
18
+ }
19
+
20
+ export { DEFAULT_ERROR_MESSAGE, useField as default };
@@ -0,0 +1,51 @@
1
+ import React__default from 'react';
2
+ import { useFormContext } from 'react-hook-form';
3
+ import { noop } from '@aws-amplify/ui';
4
+
5
+ const DEFAULT_ERROR_MESSAGE = '`useForm` must be called inside a `FormProvider`';
6
+ /**
7
+ * Utility hook corresponding to `FormProvider`, must be used within a `FormProvider`
8
+ *
9
+ * @internal Extend for public export. `useForm` and `UseForm` are an abstraction layer
10
+ * on top of `useFormContext` and `UseFormReturn`, imported from `react-hook-form`
11
+ *
12
+ * @param options optional parameters
13
+ * @returns `Form` utilities
14
+ */
15
+ function useForm(options = {}) {
16
+ const formContext = useFormContext();
17
+ const { errorMessage, onSubmit: _onSubmit } = options;
18
+ if (!formContext) {
19
+ throw new Error(errorMessage ?? DEFAULT_ERROR_MESSAGE);
20
+ }
21
+ const { formState, getFieldState: _getFieldState, getValues, handleSubmit, register, reset, setValue, } = formContext;
22
+ // Do not memoize, `formState` updates on all events
23
+ const getFieldState = (name) => {
24
+ const { error, ...fieldState } = _getFieldState(name, formState);
25
+ const { message: errorMessage } = error ?? {};
26
+ return { ...fieldState, errorMessage, hasError: !!errorMessage };
27
+ };
28
+ // memoize `registerField` and `setFormValue` together,
29
+ // `register` and `setValue` maintain stable references
30
+ const { registerField, setFormValue } = React__default.useMemo(() => {
31
+ return {
32
+ registerField: ({ name, ...options }) => register(name, options),
33
+ setFormValue: ({ name, value, ...options }) => setValue(name, value, options),
34
+ };
35
+ }, [register, setValue]);
36
+ const onSubmit = React__default.useCallback((event) => {
37
+ const handler = _onSubmit ? handleSubmit(_onSubmit) : noop;
38
+ handler(event);
39
+ }, [_onSubmit, handleSubmit]);
40
+ return {
41
+ getFieldState,
42
+ getValues,
43
+ isValid: formState.isValid,
44
+ onSubmit,
45
+ registerField,
46
+ reset,
47
+ setFormValue,
48
+ };
49
+ }
50
+
51
+ export { DEFAULT_ERROR_MESSAGE, useForm as default };
@@ -0,0 +1,15 @@
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import React__default from 'react';
3
+ import FormProvider from './FormProvider.mjs';
4
+
5
+ /**
6
+ * @param Child `Form` base component wrapped inside `FormProvider`
7
+ * @returns Composed `Form` component exposing `FormContext` values to descendents
8
+ */
9
+ function withFormProvider(Child) {
10
+ return React__default.forwardRef(function Form({ defaultValues, mode, ...props }, ref) {
11
+ return (jsx(FormProvider, { defaultValues: defaultValues, mode: mode, ref: ref, children: jsx(Child, { ...props }) }));
12
+ });
13
+ }
14
+
15
+ export { withFormProvider as default };
@@ -0,0 +1,19 @@
1
+ import * as React from 'react';
2
+
3
+ /**
4
+ * Logs a deprecation warning message.
5
+ *
6
+ * @important Please use the React/React Native specific platform implementations.
7
+ * This version of the hook is a base implementation that the others extend from due
8
+ * to env differences between running in RN or the browser
9
+ */
10
+ const useDeprecationWarning = ({ shouldWarn, message, }) => {
11
+ React.useEffect(() => {
12
+ if (shouldWarn) {
13
+ // eslint-disable-next-line no-console
14
+ console.warn(message);
15
+ }
16
+ }, [shouldWarn, message]);
17
+ };
18
+
19
+ export { useDeprecationWarning as default };
@@ -1,6 +1,19 @@
1
1
  import { isUndefined } from '@aws-amplify/ui';
2
2
  import usePreviousValue from './usePreviousValue.mjs';
3
3
 
4
+ /**
5
+ * @param value `value` to track for updates
6
+ * @param ignoreFirstRender whether to ignore initial render. defaults to `false`
7
+ * @returns a boolean representing whether the tracked `value` has updated between renders
8
+ *
9
+ * Returns `false`:
10
+ * - on initial render when ignoring first render
11
+ * - current and previous `value` are equal
12
+ *
13
+ * Returns `true`:
14
+ * - on initial render when not ignoring first render (default behavior)
15
+ * - current and previous `value` are not equal
16
+ */
4
17
  function useHasValueUpdated(value, ignoreFirstRender = false) {
5
18
  const previous = usePreviousValue(value);
6
19
  const shouldIgnoreChange = isUndefined(previous) && ignoreFirstRender;
@@ -0,0 +1,22 @@
1
+ import React__default from 'react';
2
+ import { isTypedFunction } from '@aws-amplify/ui';
3
+
4
+ function useTimeout({ callback, delay, }) {
5
+ const storedCallback = React__default.useRef(callback);
6
+ React__default.useLayoutEffect(() => {
7
+ storedCallback.current = callback;
8
+ }, [callback]);
9
+ React__default.useEffect(() => {
10
+ if (!isTypedFunction(storedCallback.current) || !delay) {
11
+ return;
12
+ }
13
+ const timeoutId = setTimeout(() => {
14
+ storedCallback.current?.();
15
+ }, delay);
16
+ return () => {
17
+ clearTimeout(timeoutId);
18
+ };
19
+ }, [delay]);
20
+ }
21
+
22
+ export { useTimeout as default };
@@ -4,7 +4,13 @@ export { default as useAuthenticator } from './Authenticator/hooks/useAuthentica
4
4
  export { default as useAuthenticatorRoute } from './Authenticator/hooks/useAuthenticatorRoute/useAuthenticatorRoute.mjs';
5
5
  export { default as useAuthenticatorInitMachine } from './Authenticator/hooks/useAuthenticatorInitMachine/useAuthenticatorInitMachine.mjs';
6
6
  export { isComponentRouteKey as isAuthenticatorComponentRouteKey, resolveAuthenticatorComponents } from './Authenticator/hooks/utils.mjs';
7
+ export { default as useField } from './components/FormCore/useField.mjs';
8
+ export { default as useForm } from './components/FormCore/useForm.mjs';
9
+ export { default as FormProvider } from './components/FormCore/FormProvider.mjs';
10
+ export { default as withFormProvider } from './components/FormCore/withFormProvider.mjs';
7
11
  export { default as RenderNothing } from './components/RenderNothing/RenderNothing.mjs';
8
- export { default as usePreviousValue } from './hooks/usePreviousValue.mjs';
12
+ export { default as useDeprecationWarning } from './hooks/useDeprecationWarning.mjs';
9
13
  export { default as useHasValueUpdated } from './hooks/useHasValueUpdated.mjs';
10
- export { templateJoin } from './utils/index.mjs';
14
+ export { default as usePreviousValue } from './hooks/usePreviousValue.mjs';
15
+ export { default as useTimeout } from './hooks/useTimeout.mjs';
16
+ export { default as createContextUtilities } from './utils/createContextUtilities.mjs';
@@ -0,0 +1,81 @@
1
+ import { jsx } from 'react/jsx-runtime';
2
+ import React__default from 'react';
3
+ import { isUndefined, isString } from '@aws-amplify/ui';
4
+
5
+ const INVALID_OPTIONS_MESSAGE = 'an `errorMessage` or a `defaultValue` must be provided in `options`';
6
+ /**
7
+ * Uses `ContextType`/`Name` generics and `options` to create:
8
+ * - `${Name}Context`: React Context of type `ContextType`
9
+ * - `Provider${Name}`: React Context `Provider` component exposing the `ContextType`
10
+ * as optional props
11
+ * - `use${Name}`: Utility Hook exposing the values of `ContextType`. Allows
12
+ * params with `errorMessage` for granular error messaging
13
+ *
14
+ * @template ContextType Type definition of the Context.
15
+ * > For most use cases the keys of `ContextType` should not be optional in
16
+ * preference of explicit `undefined` to avoid optional types on the
17
+ * Utility Hook return
18
+ *
19
+ * @param options Context utility options. Requires a `contextName`, and
20
+ * either a `defaultValue` of `ContextType` **or** an `errorMessage`
21
+ * allowing for differing behaviors of the Utility Hook when used outside a
22
+ * parent `Provider`:
23
+ *
24
+ * - `defaultValue`: Ensures the Utility Hook returns a default value for
25
+ * scenarios **where the missing context values should not impact usage**
26
+ * - `errorMessage`: Ensures the Utility Hook throws an error for
27
+ * scenarios **where the missing context values should prevent** usage
28
+ *
29
+ * @returns `Context`, `Provider` Component and `useContext` Utility Hook
30
+ *
31
+ * @usage
32
+ * ```ts
33
+ * interface StuffContextType {
34
+ * things: number;
35
+ * }
36
+ *
37
+ * // with `defaultValue`
38
+ * const defaultValue: StuffContextType = { things: 7 };
39
+ *
40
+ * const { StuffProvider, useStuff } = createContextUtilities({
41
+ * contextName: 'Stuff',
42
+ * defaultValue,
43
+ * });
44
+ *
45
+ * // with `errorMessage`
46
+ * const { StuffProvider, useStuff } = createContextUtilities<StuffContextType>({
47
+ * contextName: 'Stuff',
48
+ * errorMessage: '`useStuff` must be used in a `StuffProvider`'
49
+ * });
50
+ * ```
51
+ */
52
+ function createContextUtilities(options) {
53
+ const { contextName, defaultValue, errorMessage } = options ?? {};
54
+ if (isUndefined(defaultValue) && !isString(errorMessage)) {
55
+ throw new Error(INVALID_OPTIONS_MESSAGE);
56
+ }
57
+ const Context = React__default.createContext(defaultValue);
58
+ function Provider(props) {
59
+ const { children, ...context } = props;
60
+ const value = React__default.useMemo(() => context,
61
+ // Unpack `context` for the dep array; using `[context]` results in
62
+ // evaluation on every render
63
+ // eslint-disable-next-line react-hooks/exhaustive-deps
64
+ Object.values(context));
65
+ return jsx(Context.Provider, { value: value, children: children });
66
+ }
67
+ Provider.displayName = `${contextName}Provider`;
68
+ return {
69
+ [`use${contextName}`]: function (params) {
70
+ const context = React__default.useContext(Context);
71
+ if (isUndefined(context)) {
72
+ throw new Error(params?.errorMessage ?? errorMessage);
73
+ }
74
+ return context;
75
+ },
76
+ [`${contextName}Provider`]: Provider,
77
+ [`${contextName}Context`]: Context,
78
+ };
79
+ }
80
+
81
+ export { INVALID_OPTIONS_MESSAGE, createContextUtilities as default };