UNPKG

niceform-hook

Version:
1 lines 17.9 kB
{"version":3,"file":"index.esm.mjs","sources":["../../../src/utils/use-context-selector/createContext.tsx","../../../src/utils/dequalLite.ts","../../../src/utils/use-context-selector/useContextSelector.tsx","../../../src/contexts/niceform.tsx","../../../src/hooks/useForm/useForm.ts","../../../src/hooks/useForm/useController.ts","../../../src/hooks/useForm/useFieldState.ts","../../../src/hooks/useForm/useFormState.ts","../../../src/hooks/useForm/useWatch.ts"],"sourcesContent":["import React, {\n createContext as createContextOriginal,\n useEffect,\n useRef\n} from \"react\";\n\nimport { Listener } from \"./types\";\n\nfunction createProvider<T>(ProviderOriginal: React.Context<any>['Provider']) {\n return ({ value, children }) => {\n const valueRef = useRef<T>(value);\n const listenersRef = useRef(new Set<Listener>());\n const contextValue = useRef({\n value: valueRef,\n registerListener: (listener: Listener) => {\n listenersRef.current.add(listener);\n return () => listenersRef.current.delete(listener);\n }\n });\n\n useEffect(() => {\n valueRef.current = value;\n listenersRef.current.forEach((listener) => {\n listener(value);\n });\n }, [value]);\n\n return (\n <ProviderOriginal value={contextValue.current}>\n {children}\n </ProviderOriginal>\n );\n };\n}\n\nexport default function createContext<T>(defaultValue: T) {\n const context = createContextOriginal(defaultValue);\n\n delete (context as Partial<typeof context>).Consumer;\n\n context.Provider = createProvider<T>(context.Provider) as (typeof context)['Provider']\n\n return context;\n}\n","/*\n * This code is based on an implementation provided by Luke Edwards\n * [https://github.com/lukeed/dequal]\n * Copyright (c) Luke Edwards <luke.edwards05@gmail.com> (lukeed.com)\n * release v2.0.3\n */\n\n\nconst has = Object.prototype.hasOwnProperty;\n\nexport function dequalLite(foo, bar) {\n\tlet ctor, len;\n\tif (foo === bar) return true;\n\n\tif (foo && bar && (ctor=foo.constructor) === bar.constructor) {\n\t\tif (ctor === Date) return foo.getTime() === bar.getTime();\n\t\tif (ctor === RegExp) return foo.toString() === bar.toString();\n\n\t\tif (ctor === Array) {\n\t\t\tif ((len=foo.length) === bar.length) {\n\t\t\t\twhile (len-- && dequalLite(foo[len], bar[len]));\n\t\t\t}\n\t\t\treturn len === -1;\n\t\t}\n\n\t\tif (!ctor || typeof foo === 'object') {\n\t\t\tlen = 0;\n\t\t\tfor (ctor in foo) {\n\t\t\t\tif (has.call(foo, ctor) && ++len && !has.call(bar, ctor)) return false;\n\t\t\t\tif (!(ctor in bar) || !dequalLite(foo[ctor], bar[ctor])) return false;\n\t\t\t}\n\t\t\treturn Object.keys(bar).length === len;\n\t\t}\n\t}\n\n\treturn foo !== foo && bar !== bar;\n}","import { useContext, useEffect, useRef, useState } from \"react\";\nimport { dequalLite } from \"../dequalLite\";\n\nimport { ValueContext } from \"./types\";\n\nexport default function useContextSelector<Value, Selected>(\n context: React.Context<Value>, \n selector: (value: Value) => Selected, \n deepComparison = false\n): Selected {\n const { value, registerListener } = useContext(context) as ValueContext<Value, Selected>;\n const selectorRef = useRef(selector);\n const [selectedValue, setSelectedValue] = useState(() =>\n selector(value.current)\n );\n\n const _selectedValue = useRef(selectedValue)\n _selectedValue.current = selectedValue\n\n useEffect(() => {\n selectorRef.current = selector;\n });\n\n useEffect(() => {\n \n const updateValueIfNeeded = (newValue) => {\n const newSelectedValue = selectorRef.current(newValue);\n\n const compare = deepComparison ? dequalLite : Object.is\n if(!compare(_selectedValue.current, newSelectedValue)){\n setSelectedValue(() => newSelectedValue);\n }\n };\n\n const unregisterListener = registerListener(updateValueIfNeeded);\n\n return unregisterListener as () => void;\n }, [registerListener, value, deepComparison]);\n\n return selectedValue;\n}\n","\nimport { FormConfig} from '../types/FormConfig';\nimport { createContext, useContextSelector } from \"../utils/use-context-selector\";\n\n// ---------------------------------------------------------------------\ntype FormConfigWithDefinition = FormConfig<{fieldProps: Record<string, any>}, any>\n\nconst context = createContext<FormConfigWithDefinition | null>(null);\n\nexport function NiceformHookProvider({ children, ...props }: FormConfigWithDefinition & { children: any }) {\n return (\n <context.Provider value={props}>\n {children}\n </context.Provider>\n )\n}\n\nexport function useNiceformHookContext<Selected>(callback: (parameters: FormConfigWithDefinition) => Selected, deepComparison = false): Selected {\n return useContextSelector(context, callback as (parameters: FormConfigWithDefinition | null) => Selected, deepComparison)\n}","import type { FieldValues, UseFormReturn } from 'react-hook-form'\n\nimport {useNiceformHookContext} from '../../contexts/niceform'\nexport default function useForm<TFieldValues extends FieldValues = FieldValues>() {\n \n return useNiceformHookContext(state => state.form.methods as UseFormReturn<TFieldValues>)\n}","import { FieldValues, Path, UseControllerProps, useController as _useController } from 'react-hook-form'\n\nimport useForm from './useForm'\n\nexport default function useController<TFieldValues extends FieldValues = FieldValues>(props: UseControllerProps<TFieldValues, Path<TFieldValues>>) {\n\n const {control} = useForm<TFieldValues>()\n return _useController<TFieldValues>({control, ...props})\n}","import type { FieldValues, Path, UseFormReturn } from 'react-hook-form'\n\nimport {useNiceformHookContext} from '../../contexts/niceform'\nimport type { FormConfig } from '../../types/FormConfig'\n\nexport default function useFieldState<TFieldValues extends FieldValues>(name: keyof TFieldValues) {\n \n type UseForm = UseFormReturn<TFieldValues>\n\n const cb = (state: FormConfig['form']['methods']) => (state as UseForm).getFieldState(name as Path<TFieldValues>, (state as UseForm).formState)\n\n const result = useNiceformHookContext(state => {\n const fieldState = cb(state.form.methods)\n\n return {\n /**\n * field is not valid.\n * \n Condition: subscribe to errors.\n */\n invalid: fieldState.invalid,\n /**\n * field is modified.\n * \n * Condition: subscribe to dirtyFields.\n */\n isDirty: fieldState.isDirty,\n /**\n * \tfield has received a focus and blur event.\n * \n Condition: subscribe to touchedFields.\n */\n isTouched: fieldState.isTouched,\n /**\n * field error object.\n Condition: subscribe to errors.\n */\n error: {\n /**\n * Error type.\n */\n type: fieldState.error?.type,\n root: fieldState.error?.root,\n /**\n * Element reference\n */\n ref: fieldState.error?.ref,\n types: fieldState.error?.types,\n /**\n * Error message\n */\n message: fieldState.error?.message\n }\n }\n }, true)\n \n return result\n}\n\nexport function useContextSelectorFieldState<TFieldValues extends FieldValues, Selected>(\n name: keyof TFieldValues, \n callback: (parameters: ReturnType<FormConfig['form']['methods']['getFieldState']>) => Selected\n): Selected{\n\n type UseForm = UseFormReturn<TFieldValues>\n\n const cb = (state: FormConfig['form']['methods']) => (state as UseForm).getFieldState(name as Path<TFieldValues>, (state as UseForm).formState)\n\n return useNiceformHookContext(state => callback(cb(state.form.methods)))\n}","import { FieldValues, UseFormReturn, useFormState as _useFormState, UseFormStateProps } from 'react-hook-form'\n\nimport { useNiceformHookContext } from '../../contexts/niceform'\nimport type { FormConfig } from '../../types/FormConfig'\nimport useForm from './useForm'\n\nexport default function useFormState<TFieldValues extends FieldValues = FieldValues>(props?: UseFormStateProps<TFieldValues>) {\n\n const {control} = useForm<TFieldValues>()\n return _useFormState<TFieldValues>({control, ...props})\n \n}\n\nexport function useContextSelectorFormState<TFieldValues extends FieldValues, Selected>(\n callback: (parameters: FormConfig['form']['methods']['formState']) => Selected\n): Selected {\n\n type UseForm = UseFormReturn<TFieldValues>\n\n const cb = (state: FormConfig['form']['methods']) => (state as UseForm).formState\n\n return useNiceformHookContext(state => callback(cb(state.form.methods)))\n}","import { DeepPartialSkipArrayKey, FieldPath, FieldPathValue, FieldPathValues, FieldValues, UseWatchProps, useWatch as _useWatch } from 'react-hook-form';\n\nimport useForm from './useForm';\n\n/**\n * Subscribe to the entire form values change and re-render at the hook level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { watch } = useForm();\n * const values = useWatch({\n * defaultValue: {\n * name: \"data\"\n * },\n * exact: false,\n * })\n * ```\n */\nexport default function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n>(props: {\n defaultValue?: DeepPartialSkipArrayKey<TFieldValues>;\n disabled?: boolean;\n exact?: boolean;\n}): DeepPartialSkipArrayKey<TFieldValues>;\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { watch } = useForm();\n * const values = useWatch({\n * name: \"fieldA\",\n * defaultValue: \"default value\",\n * exact: false,\n * })\n * ```\n */\nexport default function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n TFieldName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n>(props: {\n name: TFieldName;\n defaultValue?: FieldPathValue<TFieldValues, TFieldName>;\n disabled?: boolean;\n exact?: boolean;\n}): FieldPathValue<TFieldValues, TFieldName>;\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @param props - defaultValue, disable subscription and match exact name.\n *\n * @example\n * ```tsx\n * const { watch } = useForm();\n * const values = useWatch({\n * name: [\"fieldA\", \"fieldB\"],\n * defaultValue: {\n * fieldA: \"data\",\n * fieldB: \"data\"\n * },\n * exact: false,\n * })\n * ```\n */\nexport default function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n TFieldNames extends readonly FieldPath<TFieldValues>[] = readonly FieldPath<TFieldValues>[],\n>(props: {\n name: readonly [...TFieldNames];\n defaultValue?: DeepPartialSkipArrayKey<TFieldValues>;\n disabled?: boolean;\n exact?: boolean;\n}): FieldPathValues<TFieldValues, TFieldNames>;\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @example\n * ```tsx\n * // can skip passing down the control into useWatch if the form is wrapped with the FormProvider\n * const values = useWatch()\n * ```\n */\nexport default function useWatch<\n TFieldValues extends FieldValues = FieldValues,\n>(): DeepPartialSkipArrayKey<TFieldValues>;\n/**\n * Custom hook to subscribe to field change and isolate re-rendering at the component level.\n *\n * @remarks\n *\n * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)\n *\n * @example\n * ```tsx\n * const { watch } = useForm();\n * const values = useWatch({\n * name: \"fieldName\"\n * })\n * ```\n */\nexport default function useWatch<TFieldValues extends FieldValues>(props?: Omit<UseWatchProps<TFieldValues>, 'control'>) {\n\n const {control} = useForm<TFieldValues>()\n return _useWatch<TFieldValues>({control, ...props as any})\n}"],"names":["_jsx","createContextOriginal","_useController","_useFormState","_useWatch"],"mappings":"mPAQA,SAAS,cAAc,CAAI,gBAAgD,EAAA;AACvE,IAAA,OAAO,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAI;AAC3B,QAAA,MAAM,QAAQ,GAAG,MAAM,CAAI,KAAK,CAAC,CAAC;QAClC,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,GAAG,EAAY,CAAC,CAAC;QACjD,MAAM,YAAY,GAAG,MAAM,CAAC;AACxB,YAAA,KAAK,EAAE,QAAQ;AACf,YAAA,gBAAgB,EAAE,CAAC,QAAkB,KAAI;AACrC,gBAAA,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACnC,OAAO,MAAM,YAAY,CAAC,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;aACtD;AACJ,SAAA,CAAC,CAAC;QAEH,SAAS,CAAC,MAAK;AACX,YAAA,QAAQ,CAAC,OAAO,GAAG,KAAK,CAAC;YACzB,YAAY,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,QAAQ,KAAI;gBACtC,QAAQ,CAAC,KAAK,CAAC,CAAC;AACpB,aAAC,CAAC,CAAC;AACP,SAAC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC;AAEZ,QAAA,QACIA,GAAA,CAAC,gBAAgB,EAAA,EAAC,KAAK,EAAE,YAAY,CAAC,OAAO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