@helsenorge/designsystem-react 2.6.1 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/FormGroup.js +1 -1
  3. package/FormGroup.js.map +1 -1
  4. package/Input.js +1 -1
  5. package/Input.js.map +1 -1
  6. package/Modal.js +1 -1
  7. package/Modal.js.map +1 -1
  8. package/components/FormExample/FormExample.d.ts +2 -1
  9. package/components/FormExample/FormExample.d.ts.map +1 -1
  10. package/components/FormExample/componentdata.json +1 -1
  11. package/components/FormExample/index.js +3 -3
  12. package/components/FormExample/index.js.map +1 -1
  13. package/components/FormExample/styles.module.scss +27 -0
  14. package/components/FormExample/styles.module.scss.d.ts +11 -0
  15. package/components/FormGroup/FormGroup.d.ts +4 -0
  16. package/components/FormGroup/FormGroup.d.ts.map +1 -1
  17. package/components/FormGroup/componentdata.json +1 -1
  18. package/components/Icons/AdditionalIconInformation.js +8 -1
  19. package/components/Icons/EmoticonAnnoyed.d.ts +5 -0
  20. package/components/Icons/EmoticonAnnoyed.d.ts.map +1 -0
  21. package/components/Icons/EmoticonAnnoyed.js +2 -0
  22. package/components/Icons/EmoticonAnnoyed.js.map +1 -0
  23. package/components/Icons/EmoticonDelighted.d.ts +5 -0
  24. package/components/Icons/EmoticonDelighted.d.ts.map +1 -0
  25. package/components/Icons/EmoticonDelighted.js +2 -0
  26. package/components/Icons/EmoticonDelighted.js.map +1 -0
  27. package/components/Icons/EmoticonDisappointed.d.ts +5 -0
  28. package/components/Icons/EmoticonDisappointed.d.ts.map +1 -0
  29. package/components/Icons/EmoticonDisappointed.js +2 -0
  30. package/components/Icons/EmoticonDisappointed.js.map +1 -0
  31. package/components/Icons/EmoticonHappy.d.ts +5 -0
  32. package/components/Icons/EmoticonHappy.d.ts.map +1 -0
  33. package/components/Icons/EmoticonHappy.js +2 -0
  34. package/components/Icons/EmoticonHappy.js.map +1 -0
  35. package/components/Icons/EmoticonMeh.d.ts +5 -0
  36. package/components/Icons/EmoticonMeh.d.ts.map +1 -0
  37. package/components/Icons/EmoticonMeh.js +2 -0
  38. package/components/Icons/EmoticonMeh.js.map +1 -0
  39. package/components/Icons/Filter.d.ts +5 -0
  40. package/components/Icons/Filter.d.ts.map +1 -0
  41. package/components/Icons/Filter.js +2 -0
  42. package/components/Icons/Filter.js.map +1 -0
  43. package/components/Icons/SortDown.d.ts +5 -0
  44. package/components/Icons/SortDown.d.ts.map +1 -0
  45. package/components/Icons/SortDown.js +2 -0
  46. package/components/Icons/SortDown.js.map +1 -0
  47. package/components/Icons/SortUp.d.ts +5 -0
  48. package/components/Icons/SortUp.d.ts.map +1 -0
  49. package/components/Icons/SortUp.js +2 -0
  50. package/components/Icons/SortUp.js.map +1 -0
  51. package/components/Input/Input.d.ts +10 -2
  52. package/components/Input/Input.d.ts.map +1 -1
  53. package/components/Input/componentdata.json +1 -1
  54. package/components/Input/styles.module.scss +5 -0
  55. package/components/Input/styles.module.scss.d.ts +1 -0
  56. package/components/Modal/Modal.d.ts.map +1 -1
  57. package/hooks/useFocusTrap.d.ts +1 -2
  58. package/hooks/useFocusTrap.d.ts.map +1 -1
  59. package/hooks/useFocusTrap.js +1 -1
  60. package/hooks/useFocusTrap.js.map +1 -1
  61. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,3 +1,17 @@
1
+ ## [2.6.2](https://dev.azure.com/nhnfelles/Helsenorge/_git/HN-Designsystem/branchCompare?baseVersion=GTv2.6.1&targetVersion=GTv2.6.2) (2022-11-17)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * modal setter fokus til seg selv kun én gang når den først vises ([a293206](https://dev.azure.com/nhnfelles/Helsenorge/_git/HN-Designsystem/commit/a293206cbd23a4524054198239eb00f2ee454a39)), closes [#289818](https://dev.azure.com/nhnfelles/Helsenorge/_git/HN-Designsystem/issues/289818)
7
+
8
+ ## [2.6.1](https://dev.azure.com/nhnfelles/Helsenorge/_git/HN-Designsystem/branchCompare?baseVersion=GTv2.6.0&targetVersion=GTv2.6.1) (2022-11-17)
9
+
10
+
11
+ ### Bug Fixes
12
+
13
+ * resizeobserver logger ikke feil om loop limit exceeded ([afece3a](https://dev.azure.com/nhnfelles/Helsenorge/_git/HN-Designsystem/commit/afece3a3f40763f6520e09c2398b5928eaf9fa82)), closes [#288871](https://dev.azure.com/nhnfelles/Helsenorge/_git/HN-Designsystem/issues/288871)
14
+
1
15
  ## [2.6.0](https://dev.azure.com/nhnfelles/Helsenorge/_git/HN-Designsystem/branchCompare?baseVersion=GTv2.5.0&targetVersion=GTv2.6.0) (2022-11-15)
2
16
 
3
17
 
package/FormGroup.js CHANGED
@@ -1,2 +1,2 @@
1
- import r from"react";import i from"classnames";import a from"./components/FormGroup/styles.module.scss";import{C as b}from"./Checkbox.js";import{FormMode as g,FormVariant as E,AnalyticsId as v}from"./constants.js";import{R as y}from"./RadioButton.js";import{I as G}from"./Input.js";import{T as I}from"./Title.js";import{F as x}from"./FormLayout.js";import{E as R}from"./ErrorWrapper.js";import{S as T}from"./Select.js";const z=r.forwardRef((t,_)=>{const{className:C,mode:n=g.onwhite,variant:l=E.normal,error:m,name:o,htmlMarkup:d="fieldset"}=t,f=n===g.ondark,c=l===E.bigform,N=i(a["form-group-wrapper"],{[a["form-group-wrapper--on-dark"]]:f,[a["form-group-wrapper--invalid"]]:m},C),k=i(a["form-group-wrapper__title"],{[a["form-group-wrapper__title--on-dark"]]:f&&!m,[a["form-group-wrapper__title--bigform"]]:c}),w=i(a["form-group"]),u=i(a["field-set__legend"],{[a["field-set__legend--on-dark"]]:f&&!m,[a["field-set__legend--bigform"]]:c}),s=(e,F)=>r.isValidElement(e)&&e.type===F,p=e=>s(e,x)?r.cloneElement(e,{variant:l,mapHelper:p}):s(e,b)?r.cloneElement(e,{name:o!=null?o:e.props.name,mode:n,variant:l,error:!!m}):s(e,y)?r.cloneElement(e,{name:o!=null?o:e.props.name,mode:n,variant:l,error:!!m}):s(e,G)?r.cloneElement(e,{name:o!=null?o:e.props.name,mode:n,variant:l,error:!!m}):s(e,T)?r.cloneElement(e,{name:o!=null?o:e.props.name,mode:n,error:!!m}):e;return r.createElement("div",{"data-testid":t.testId,"data-analyticsid":v.FormGroup,className:N,ref:_,tabIndex:-1},t.title&&r.createElement(I,{className:k,htmlMarkup:"h4",appearance:"title4",margin:{marginTop:0,marginBottom:m?1:2}},t.title),r.createElement(R,{errorText:m},r.createElement("div",{className:w},d==="div"&&r.createElement("div",{id:t.title,className:a["field-set"]},t.legend&&r.createElement("h5",{className:u},t.legend),r.Children.map(t.children,p)),d==="fieldset"&&r.createElement("fieldset",{name:t.title,className:a["field-set"]},t.legend&&r.createElement("legend",{className:u},t.legend),r.Children.map(t.children,p)))))});export{z as F};
1
+ import r from"react";import i from"classnames";import a from"./components/FormGroup/styles.module.scss";import{C as I}from"./Checkbox.js";import{FormMode as C,FormVariant as _,AnalyticsId as x}from"./constants.js";import{R}from"./RadioButton.js";import{I as T}from"./Input.js";import{T as M}from"./Title.js";import{F as S}from"./FormLayout.js";import{E as B}from"./ErrorWrapper.js";import{S as V}from"./Select.js";const W=r.forwardRef((t,N)=>{const{className:k,fieldsetClassName:w,mode:n=C.onwhite,variant:s=_.normal,error:m,name:o,htmlMarkup:d="fieldset",renderError:F=!0}=t,f=n===C.ondark,u=s===_.bigform,b=i(a["form-group-wrapper"],{[a["form-group-wrapper--on-dark"]]:f,[a["form-group-wrapper--invalid"]]:m},k),v=i(a["form-group-wrapper__title"],{[a["form-group-wrapper__title--on-dark"]]:f&&!m,[a["form-group-wrapper__title--bigform"]]:u}),G=i(a["form-group"]),c=i(a["field-set__legend"],{[a["field-set__legend--on-dark"]]:f&&!m,[a["field-set__legend--bigform"]]:u}),g=i(a["field-set"],w),l=(e,y)=>r.isValidElement(e)&&e.type===y,p=e=>l(e,S)?r.cloneElement(e,{variant:s,mapHelper:p}):l(e,W)?r.cloneElement(e,{mode:n,variant:s,error:m,renderError:!1}):l(e,I)?r.cloneElement(e,{name:o!=null?o:e.props.name,mode:n,variant:s,error:!!m}):l(e,R)?r.cloneElement(e,{name:o!=null?o:e.props.name,mode:n,variant:s,error:!!m}):l(e,T)?r.cloneElement(e,{name:o!=null?o:e.props.name,mode:n,variant:s,error:!!m}):l(e,V)?r.cloneElement(e,{name:o!=null?o:e.props.name,mode:n,error:!!m}):e,E=()=>r.createElement("div",{className:G},d==="div"&&r.createElement("div",{id:t.title,className:g},t.legend&&r.createElement("h5",{className:c},t.legend),r.Children.map(t.children,p)),d==="fieldset"&&r.createElement("fieldset",{name:t.title,className:g},t.legend&&r.createElement("legend",{className:c},t.legend),r.Children.map(t.children,p)));return r.createElement("div",{"data-testid":t.testId,"data-analyticsid":x.FormGroup,className:b,ref:N,tabIndex:-1},t.title&&r.createElement(M,{className:v,htmlMarkup:"h4",appearance:"title4",margin:{marginTop:0,marginBottom:m?1:2}},t.title),F?r.createElement(B,{errorText:m},E()):E())});export{W as F};
2
2
  //# sourceMappingURL=FormGroup.js.map
package/FormGroup.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"FormGroup.js","sources":["../src/components/FormGroup/FormGroup.tsx"],"sourcesContent":["import React from 'react';\n\nimport classNames from 'classnames';\n\nimport formGroupStyles from './styles.module.scss';\nimport Checkbox, { CheckboxProps } from '../Checkbox/Checkbox';\nimport { AnalyticsId, FormMode, FormVariant } from '../../constants';\nimport RadioButton, { RadioButtonProps } from '../RadioButton/RadioButton';\nimport Input, { InputProps } from '../Input/Input';\nimport Title from '../Title';\nimport FormLayout, { FormLayoutProps } from '../FormLayout';\nimport ErrorWrapper from '../ErrorWrapper';\nimport Select, { SelectProps } from '../Select';\n\nexport type FormGroupTags = 'fieldset' | 'div';\n\nexport interface FormGroupProps {\n /** title for the the fieldset */\n title?: string;\n /** text placed in the legend tag of the fieldset */\n legend?: string;\n /** Items in the FormGroup component */\n children?: React.ReactNode;\n /** Adds custom classes to the element. */\n className?: string;\n /** Changes the visuals of the formgroup */\n mode?: keyof typeof FormMode;\n /** Changes the visuals of the formgroup */\n variant?: keyof typeof FormVariant;\n /** Error message */\n error?: string;\n /** Sets the data-testid attribute. */\n testId?: string;\n /** Unique identifyer for the child input tags */\n name?: string;\n /** Sets div instead of fieldset tag */\n htmlMarkup?: FormGroupTags;\n}\n\nexport const FormGroup = React.forwardRef((props: FormGroupProps, ref: React.ForwardedRef<HTMLDivElement>) => {\n const { className, mode = FormMode.onwhite, variant = FormVariant.normal, error, name, htmlMarkup = 'fieldset' } = props;\n const onDark = mode === FormMode.ondark;\n const bigform = variant === FormVariant.bigform;\n const formGroupWrapperClasses = classNames(\n formGroupStyles['form-group-wrapper'],\n {\n [formGroupStyles['form-group-wrapper--on-dark']]: onDark,\n [formGroupStyles['form-group-wrapper--invalid']]: error,\n },\n className\n );\n const titleClasses = classNames(formGroupStyles['form-group-wrapper__title'], {\n [formGroupStyles['form-group-wrapper__title--on-dark']]: onDark && !error,\n [formGroupStyles['form-group-wrapper__title--bigform']]: bigform,\n });\n const formGroupClasses = classNames(formGroupStyles['form-group']);\n\n const legendClasses = classNames(formGroupStyles['field-set__legend'], {\n [formGroupStyles['field-set__legend--on-dark']]: onDark && !error,\n [formGroupStyles['field-set__legend--bigform']]: bigform,\n });\n\n const isComponent = <T,>(element: {} | null | undefined, type: React.ForwardRefExoticComponent<T>): element is React.ReactElement<T> =>\n React.isValidElement<T>(element) && (element as React.ReactElement).type === type;\n\n const mapFormComponent = (child: React.ReactNode): React.ReactNode => {\n if (isComponent<FormGroupProps>(child, FormLayout)) {\n return React.cloneElement(child as React.ReactElement<FormLayoutProps>, {\n variant,\n mapHelper: mapFormComponent,\n });\n } else if (isComponent<CheckboxProps>(child, Checkbox)) {\n return React.cloneElement(child as React.ReactElement<CheckboxProps>, {\n name: name ?? child.props.name,\n mode,\n variant,\n error: !!error,\n });\n } else if (isComponent<RadioButtonProps>(child, RadioButton)) {\n return React.cloneElement(child as React.ReactElement<RadioButtonProps>, {\n name: name ?? child.props.name,\n mode,\n variant,\n error: !!error,\n });\n } else if (isComponent<InputProps>(child, Input)) {\n return React.cloneElement(child as React.ReactElement<InputProps>, {\n name: name ?? child.props.name,\n mode,\n variant,\n error: !!error,\n });\n } else if (isComponent<SelectProps>(child, Select)) {\n return React.cloneElement(child as React.ReactElement<SelectProps>, {\n name: name ?? child.props.name,\n mode,\n error: !!error,\n });\n }\n return child;\n };\n\n return (\n <div data-testid={props.testId} data-analyticsid={AnalyticsId.FormGroup} className={formGroupWrapperClasses} ref={ref} tabIndex={-1}>\n {props.title && (\n <Title className={titleClasses} htmlMarkup={'h4'} appearance={'title4'} margin={{ marginTop: 0, marginBottom: error ? 1 : 2 }}>\n {props.title}\n </Title>\n )}\n <ErrorWrapper errorText={error}>\n <div className={formGroupClasses}>\n {htmlMarkup === 'div' && (\n <div id={props.title} className={formGroupStyles['field-set']}>\n {props.legend && <h5 className={legendClasses}>{props.legend}</h5>}\n {React.Children.map(props.children, mapFormComponent)}\n </div>\n )}\n {htmlMarkup === 'fieldset' && (\n <fieldset name={props.title} className={formGroupStyles['field-set']}>\n {props.legend && <legend className={legendClasses}>{props.legend}</legend>}\n {React.Children.map(props.children, mapFormComponent)}\n </fieldset>\n )}\n </div>\n </ErrorWrapper>\n </div>\n );\n});\n\nexport default FormGroup;\n"],"names":["FormGroup","React","props","ref","className","mode","FormMode","variant","FormVariant","error","name","htmlMarkup","onDark","bigform","formGroupWrapperClasses","classNames","formGroupStyles","titleClasses","formGroupClasses","legendClasses","isComponent","element","type","mapFormComponent","child","FormLayout","Checkbox","RadioButton","Input","Select","AnalyticsId","Title","ErrorWrapper"],"mappings":"maAuCO,MAAMA,EAAYC,EAAM,WAAW,CAACC,EAAuBC,IAA4C,CAC5G,KAAM,CAAE,UAAAC,EAAW,KAAAC,EAAOC,EAAS,QAAS,QAAAC,EAAUC,EAAY,OAAQ,MAAAC,EAAO,KAAAC,EAAM,WAAAC,EAAa,UAAA,EAAeT,EAC7GU,EAASP,IAASC,EAAS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,EACA,MAAO,CAAC,CAACI,CAAA,CACV,EAEIe,EAGT,OACGvB,EAAA,cAAA,MAAA,CAAI,cAAaC,EAAM,OAAQ,mBAAkB4B,EAAY,UAAW,UAAWhB,EAAyB,IAAAX,EAAU,SAAU,EAC9H,EAAAD,EAAM,OACJD,EAAA,cAAA8B,EAAA,CAAM,UAAWd,EAAc,WAAY,KAAM,WAAY,SAAU,OAAQ,CAAE,UAAW,EAAG,aAAcR,EAAQ,EAAI,CAAE,CACzH,EAAAP,EAAM,KACT,EAEDD,EAAA,cAAA+B,EAAA,CAAa,UAAWvB,CAAA,EACtBR,EAAA,cAAA,MAAA,CAAI,UAAWiB,CACb,EAAAP,IAAe,OACbV,EAAA,cAAA,MAAA,CAAI,GAAIC,EAAM,MAAO,UAAWc,EAAgB,YAC9C,EAAAd,EAAM,QAAWD,EAAA,cAAA,KAAA,CAAG,UAAWkB,CAAA,EAAgBjB,EAAM,MAAO,EAC5DD,EAAM,SAAS,IAAIC,EAAM,SAAUqB,CAAgB,CACtD,EAEDZ,IAAe,YACbV,EAAA,cAAA,WAAA,CAAS,KAAMC,EAAM,MAAO,UAAWc,EAAgB,YACrD,EAAAd,EAAM,QAAWD,EAAA,cAAA,SAAA,CAAO,UAAWkB,CAAA,EAAgBjB,EAAM,MAAO,EAChED,EAAM,SAAS,IAAIC,EAAM,SAAUqB,CAAgB,CACtD,CAEJ,CACF,CACF,CAEJ,CAAC"}
1
+ {"version":3,"file":"FormGroup.js","sources":["../src/components/FormGroup/FormGroup.tsx"],"sourcesContent":["import React from 'react';\n\nimport classNames from 'classnames';\n\nimport formGroupStyles from './styles.module.scss';\nimport Checkbox, { CheckboxProps } from '../Checkbox/Checkbox';\nimport { AnalyticsId, FormMode, FormVariant } from '../../constants';\nimport RadioButton, { RadioButtonProps } from '../RadioButton/RadioButton';\nimport Input, { InputProps } from '../Input/Input';\nimport Title from '../Title';\nimport FormLayout, { FormLayoutProps } from '../FormLayout';\nimport ErrorWrapper from '../ErrorWrapper';\nimport Select, { SelectProps } from '../Select';\n\nexport type FormGroupTags = 'fieldset' | 'div';\n\nexport interface FormGroupProps {\n /** title for the the fieldset */\n title?: string;\n /** text placed in the legend tag of the fieldset */\n legend?: string;\n /** Items in the FormGroup component */\n children?: React.ReactNode;\n /** Adds custom classes to the element. */\n className?: string;\n /** Adds custom classes to the fieldset element. */\n fieldsetClassName?: string;\n /** Changes the visuals of the formgroup */\n mode?: keyof typeof FormMode;\n /** Changes the visuals of the formgroup */\n variant?: keyof typeof FormVariant;\n /** Error message */\n error?: string;\n /** Sets the data-testid attribute. */\n testId?: string;\n /** Unique identifyer for the child input tags */\n name?: string;\n /** Sets div instead of fieldset tag */\n htmlMarkup?: FormGroupTags;\n /** Renders the error component (Default: true) */\n renderError?: boolean;\n}\n\nexport const FormGroup = React.forwardRef((props: FormGroupProps, ref: React.ForwardedRef<HTMLDivElement>) => {\n const {\n className,\n fieldsetClassName,\n mode = FormMode.onwhite,\n variant = FormVariant.normal,\n error,\n name,\n htmlMarkup = 'fieldset',\n renderError = true,\n } = props;\n const onDark = mode === FormMode.ondark;\n const bigform = variant === FormVariant.bigform;\n const formGroupWrapperClasses = classNames(\n formGroupStyles['form-group-wrapper'],\n {\n [formGroupStyles['form-group-wrapper--on-dark']]: onDark,\n [formGroupStyles['form-group-wrapper--invalid']]: error,\n },\n className\n );\n const titleClasses = classNames(formGroupStyles['form-group-wrapper__title'], {\n [formGroupStyles['form-group-wrapper__title--on-dark']]: onDark && !error,\n [formGroupStyles['form-group-wrapper__title--bigform']]: bigform,\n });\n const formGroupClasses = classNames(formGroupStyles['form-group']);\n\n const legendClasses = classNames(formGroupStyles['field-set__legend'], {\n [formGroupStyles['field-set__legend--on-dark']]: onDark && !error,\n [formGroupStyles['field-set__legend--bigform']]: bigform,\n });\n\n const fieldsetClasses = classNames(formGroupStyles['field-set'], fieldsetClassName);\n\n const isComponent = <T,>(element: {} | null | undefined, type: React.ForwardRefExoticComponent<T>): element is React.ReactElement<T> =>\n React.isValidElement<T>(element) && (element as React.ReactElement).type === type;\n\n const mapFormComponent = (child: React.ReactNode): React.ReactNode => {\n if (isComponent<FormGroupProps>(child, FormLayout)) {\n return React.cloneElement(child as React.ReactElement<FormLayoutProps>, {\n variant,\n mapHelper: mapFormComponent,\n });\n } else if (isComponent<FormGroupProps>(child, FormGroup)) {\n return React.cloneElement(child, {\n mode,\n variant,\n error,\n renderError: false,\n });\n } else if (isComponent<CheckboxProps>(child, Checkbox)) {\n return React.cloneElement(child as React.ReactElement<CheckboxProps>, {\n name: name ?? child.props.name,\n mode,\n variant,\n error: !!error,\n });\n } else if (isComponent<RadioButtonProps>(child, RadioButton)) {\n return React.cloneElement(child as React.ReactElement<RadioButtonProps>, {\n name: name ?? child.props.name,\n mode,\n variant,\n error: !!error,\n });\n } else if (isComponent<InputProps>(child, Input)) {\n return React.cloneElement(child as React.ReactElement<InputProps>, {\n name: name ?? child.props.name,\n mode,\n variant,\n error: !!error,\n });\n } else if (isComponent<SelectProps>(child, Select)) {\n return React.cloneElement(child as React.ReactElement<SelectProps>, {\n name: name ?? child.props.name,\n mode,\n error: !!error,\n });\n }\n return child;\n };\n\n const formGroupContent = () => {\n return (\n <div className={formGroupClasses}>\n {htmlMarkup === 'div' && (\n <div id={props.title} className={fieldsetClasses}>\n {props.legend && <h5 className={legendClasses}>{props.legend}</h5>}\n {React.Children.map(props.children, mapFormComponent)}\n </div>\n )}\n {htmlMarkup === 'fieldset' && (\n <fieldset name={props.title} className={fieldsetClasses}>\n {props.legend && <legend className={legendClasses}>{props.legend}</legend>}\n {React.Children.map(props.children, mapFormComponent)}\n </fieldset>\n )}\n </div>\n );\n };\n\n return (\n <div data-testid={props.testId} data-analyticsid={AnalyticsId.FormGroup} className={formGroupWrapperClasses} ref={ref} tabIndex={-1}>\n {props.title && (\n <Title className={titleClasses} htmlMarkup={'h4'} appearance={'title4'} margin={{ marginTop: 0, marginBottom: error ? 1 : 2 }}>\n {props.title}\n </Title>\n )}\n {renderError ? <ErrorWrapper errorText={error}>{formGroupContent()}</ErrorWrapper> : formGroupContent()}\n </div>\n );\n});\n\nexport default FormGroup;\n"],"names":["FormGroup","React","props","ref","className","fieldsetClassName","mode","FormMode","variant","FormVariant","error","name","htmlMarkup","renderError","onDark","bigform","formGroupWrapperClasses","classNames","formGroupStyles","titleClasses","formGroupClasses","legendClasses","fieldsetClasses","isComponent","element","type","mapFormComponent","child","FormLayout","Checkbox","RadioButton","Input","Select","formGroupContent","AnalyticsId","Title","ErrorWrapper"],"mappings":"8ZA2CO,MAAMA,EAAYC,EAAM,WAAW,CAACC,EAAuBC,IAA4C,CACtG,KAAA,CACJ,UAAAC,EACA,kBAAAC,EACA,KAAAC,EAAOC,EAAS,QAChB,QAAAC,EAAUC,EAAY,OACtB,MAAAC,EACA,KAAAC,EACA,WAAAC,EAAa,WACb,YAAAC,EAAc,EACZ,EAAAX,EACEY,EAASR,IAASC,EAAS,OAC3BQ,EAAUP,IAAYC,EAAY,QAClCO,EAA0BC,EAC9BC,EAAgB,sBAChB,CACE,CAACA,EAAgB,gCAAiCJ,EAClD,CAACI,EAAgB,gCAAiCR,CACpD,EACAN,CAAA,EAEIe,EAAeF,EAAWC,EAAgB,6BAA8B,CAC5E,CAACA,EAAgB,uCAAwCJ,GAAU,CAACJ,EACpE,CAACQ,EAAgB,uCAAwCH,CAAA,CAC1D,EACKK,EAAmBH,EAAWC,EAAgB,aAAa,EAE3DG,EAAgBJ,EAAWC,EAAgB,qBAAsB,CACrE,CAACA,EAAgB,+BAAgCJ,GAAU,CAACJ,EAC5D,CAACQ,EAAgB,+BAAgCH,CAAA,CAClD,EAEKO,EAAkBL,EAAWC,EAAgB,aAAcb,CAAiB,EAE5EkB,EAAc,CAAKC,EAAgCC,IACvDxB,EAAM,eAAkBuB,CAAO,GAAMA,EAA+B,OAASC,EAEzEC,EAAoBC,GACpBJ,EAA4BI,EAAOC,CAAU,EACxC3B,EAAM,aAAa0B,EAA8C,CACtE,QAAAnB,EACA,UAAWk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ED,EAAM,SAAS,IAAIC,EAAM,SAAUwB,CAAgB,CACtD,CAEJ,EAIJ,OACGzB,EAAA,cAAA,MAAA,CAAI,cAAaC,EAAM,OAAQ,mBAAkBgC,EAAY,UAAW,UAAWlB,EAAyB,IAAAb,EAAU,SAAU,EAC9H,EAAAD,EAAM,OACJD,EAAA,cAAAkC,EAAA,CAAM,UAAWhB,EAAc,WAAY,KAAM,WAAY,SAAU,OAAQ,CAAE,UAAW,EAAG,aAAcT,EAAQ,EAAI,CAAE,CAAA,EACzHR,EAAM,KACT,EAEDW,EAAeZ,EAAA,cAAAmC,EAAA,CAAa,UAAW1B,CAAA,EAAQuB,EAAmB,CAAA,EAAkBA,EAAA,CACvF,CAEJ,CAAC"}
package/Input.js CHANGED
@@ -1,2 +1,2 @@
1
- import t,{useRef as J}from"react";import c from"classnames";import{FormMode as s,FormVariant as K,IconSize as g,AnalyticsId as Q,AVERAGE_CHARACTER_WIDTH_PX as U}from"./constants.js";import{a as Y}from"./uuid.js";import{Icon as Z}from"./components/Icons/Icon.js";import{getColor as R}from"./theme/currys/color.js";import{useBreakpoint as T,Breakpoint as ee}from"./hooks/useBreakpoint.js";import{E as re}from"./ErrorWrapper.js";import e from"./components/Input/styles.module.scss";var te=(r=>(r.text="text",r.number="number",r.email="email",r.password="password",r.search="search",r.tel="tel",r.url="url",r))(te||{});const ne=(r,o,d)=>{const m=o?"1.5rem":"2rem",u=o?`${d}px`:"0px",l="4px";return`calc(${r*U}px + ${m} + ${u} + ${l})`},be=t.forwardRef((r,o)=>{const{defaultValue:d,placeholder:m,type:u="text",inputId:l=Y(),name:N,transparent:A=!1,icon:n,iconRight:b,mode:i,variant:I,label:h,error:$,errorText:_,testId:F,disabled:a,readOnly:S,autoComplete:y,afterLabelChildren:C,belowLabelChildren:E,width:v,required:z,...B}=r,V=T(),p=J(null),x=i===s.ondark,D=i===s.onblueberry,f=i===s.oninvalid||_||$,w=I===K.bigform,H=A&&i!==s.ondark&&!f,L=c(e["input-wrapper"]),M=c(e["input-wrapper__label-wrapper"],{[e["input-wrapper__label-wrapper--on-dark"]]:x,[e["input-wrapper__label-wrapper--disabled"]]:a}),X=c(e["content-wrapper"],{[e["content-wrapper--transparent"]]:H,[e["content-wrapper--on-blueberry"]]:D,[e["content-wrapper--on-dark"]]:x,[e["content-wrapper--invalid"]]:f,[e["content-wrapper--bigform"]]:w,[e["content-wrapper--disabled"]]:a,[e["content-wrapper--with-icon"]]:n}),q=c(e["content-wrapper__input"],{[e["content-wrapper__input--bigform"]]:w,[e["content-wrapper__input--disabled"]]:a}),G=a?R("neutral",500):R("black"),k=V===ee.xs||!w?g.XSmall:g.Small,W=()=>n!==void 0?t.createElement(Z,{color:G,size:k,svgIcon:n}):null,O=()=>{if(p&&p.current&&n){const j=b?0:1;p.current.children[j].focus()}},P=v?ne(v,!!n,k):void 0;return t.createElement(re,{errorText:_},t.createElement("div",{"data-testid":F,"data-analyticsid":Q.Input,className:L},h&&t.createElement("div",{className:M},t.createElement("label",{htmlFor:l},h),C&&t.createElement("div",{className:e["input-wrapper__after-label-children"]},C)),E&&t.createElement("div",null,E),t.createElement("div",{onClick:O,ref:p,className:X,style:{maxWidth:P}},!b&&W(),t.createElement("input",{name:N,type:u,defaultValue:d,id:l,className:q,ref:o,"aria-invalid":!!f,disabled:a,placeholder:m,readOnly:S,autoComplete:y||"off",required:z,...B}),b&&W())))});export{be as I,te as a};
1
+ import t,{useRef as Y}from"react";import c from"classnames";import{FormMode as p,FormVariant as Z,IconSize as A,AnalyticsId as T,AVERAGE_CHARACTER_WIDTH_PX as ee}from"./constants.js";import{a as re}from"./uuid.js";import{Icon as te}from"./components/Icons/Icon.js";import{getColor as $}from"./theme/currys/color.js";import{useBreakpoint as ae,Breakpoint as ne}from"./hooks/useBreakpoint.js";import{E as oe}from"./ErrorWrapper.js";import e from"./components/Input/styles.module.scss";var le=(r=>(r.text="text",r.number="number",r.email="email",r.password="password",r.search="search",r.tel="tel",r.url="url",r.date="date",r.time="time",r))(le||{});const ie=(r,o,s)=>{const d=o?"1.5rem":"2rem",m=o?`${s}px`:"0px",u="4px";return`calc(${r*ee}px + ${d} + ${m} + ${u})`},he=t.forwardRef((r,o)=>{var R;const{className:s,defaultValue:d,placeholder:m,type:u="text",inputId:h=re(),labelId:b,name:F,transparent:S=!1,icon:a,iconRight:f,mode:l,variant:y,label:v,error:z,errorText:C,testId:B,disabled:n,readOnly:I,autoComplete:V,afterLabelChildren:E,afterInputChildren:D,belowLabelChildren:x,width:k,required:H,...L}=r,M=ae(),i=Y(null),W=l===p.ondark,X=l===p.onblueberry,w=l===p.oninvalid||C||z,_=y===Z.bigform,q=S&&l!==p.ondark&&!w,G=c(e["input-wrapper"],s),O=c(e["input-wrapper__label-wrapper"],{[e["input-wrapper__label-wrapper--on-dark"]]:W,[e["input-wrapper__label-wrapper--disabled"]]:n}),P=c(e["content-wrapper"],{[e["content-wrapper--transparent"]]:q,[e["content-wrapper--on-blueberry"]]:X,[e["content-wrapper--on-dark"]]:W,[e["content-wrapper--invalid"]]:w,[e["content-wrapper--bigform"]]:_,[e["content-wrapper--disabled"]]:n,[e["content-wrapper--with-icon"]]:a}),j=c(e["content-wrapper__input"],{[e["content-wrapper__input--bigform"]]:_,[e["content-wrapper__input--disabled"]]:n}),J=n?$("neutral",500):$("black"),g=M===ne.xs||!_?A.XSmall:A.Small,N=()=>a!==void 0?t.createElement(te,{color:J,size:g,svgIcon:a}):null,K=()=>{if(i&&i.current&&a){const U=f?0:1;i.current.children[U].focus()}},Q=k?ie(k,!!a,g):void 0;return t.createElement(oe,{errorText:C},t.createElement("div",{"data-testid":B,"data-analyticsid":T.Input,className:G},v&&t.createElement("div",{className:O},t.createElement("label",{id:b!=null?b:void 0,htmlFor:h},v),E&&t.createElement("div",{className:e["input-wrapper__after-label-children"]},E)),x&&t.createElement("div",null,x),t.createElement("div",{className:e["input-wrapper__after-content-wrapper"]},t.createElement("div",{onClick:K,ref:i,className:P,style:{maxWidth:Q}},!f&&N(),t.createElement("input",{name:F,type:u,defaultValue:d,id:h,className:j,ref:o,"aria-labelledby":(R=r["aria-labelledby"])!=null?R:void 0,"aria-invalid":!!w,disabled:n,placeholder:m,readOnly:I,autoComplete:V||"off",required:H,...L}),f&&N()),D)))});export{he as I,le as a};
2
2
  //# sourceMappingURL=Input.js.map
package/Input.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Input.js","sources":["../src/components/Input/Input.tsx"],"sourcesContent":["import React, { useRef } from 'react';\nimport cn from 'classnames';\n\nimport { FormMode, FormVariant, AnalyticsId, AVERAGE_CHARACTER_WIDTH_PX } from '../../constants';\nimport { uuid } from '../../utils/uuid';\nimport Icon, { IconSize, SvgIcon } from '../Icons';\nimport { getColor } from '../../theme/currys';\nimport { Breakpoint, useBreakpoint } from '../../hooks/useBreakpoint';\n\nimport ErrorWrapper from '../ErrorWrapper';\n\nimport styles from './styles.module.scss';\n\nexport interface InputProps\n extends Pick<\n React.InputHTMLAttributes<HTMLInputElement>,\n 'disabled' | 'readOnly' | 'autoComplete' | 'name' | 'placeholder' | 'defaultValue' | 'required'\n > {\n /** HMTL Input type */\n type?: keyof typeof InputTypes;\n /** input id */\n inputId?: string;\n /** Width of input field in characters (approximate) */\n width?: number;\n /** If true, the component will be transparent. */\n transparent?: boolean;\n /** Icon to be displayed next to the input field */\n icon?: SvgIcon;\n /** Places the icon to the right */\n iconRight?: boolean;\n /** Changes the color profile of the input */\n mode?: keyof typeof FormMode;\n /** Changes the visuals of the input */\n variant?: keyof typeof FormVariant;\n /** Label of the input */\n label?: string;\n /** Activates Error style for the input */\n error?: boolean;\n /** Error text to show above the component */\n errorText?: string;\n /** Sets the data-testid attribute. */\n testId?: string;\n /** Component shown after label */\n afterLabelChildren?: React.ReactNode;\n /** Component shown under label */\n belowLabelChildren?: React.ReactNode;\n}\n\nexport enum InputTypes {\n text = 'text',\n number = 'number',\n email = 'email',\n password = 'password',\n search = 'search',\n tel = 'tel',\n url = 'url',\n}\n\nconst getInputMaxWidth = (characters: number, hasIcon: boolean, iconSize: number): string => {\n const paddingWidth = hasIcon ? '1.5rem' : '2rem';\n const iconWidth = hasIcon ? `${iconSize}px` : '0px';\n const borderWidth = '4px';\n\n return `calc(${characters * AVERAGE_CHARACTER_WIDTH_PX}px + ${paddingWidth} + ${iconWidth} + ${borderWidth})`;\n};\n\nconst Input = React.forwardRef((props: InputProps, ref: React.Ref<HTMLInputElement>) => {\n const {\n defaultValue,\n placeholder,\n type = InputTypes.text,\n inputId = uuid(),\n name,\n transparent = false,\n icon,\n iconRight,\n mode,\n variant,\n label,\n error,\n errorText,\n testId,\n disabled,\n readOnly,\n autoComplete,\n afterLabelChildren,\n belowLabelChildren,\n width,\n required,\n ...rest\n } = props;\n const breakpoint = useBreakpoint();\n const contentWrapperRef = useRef<HTMLDivElement>(null);\n\n const onDark = mode === FormMode.ondark;\n const onBlueberry = mode === FormMode.onblueberry;\n const onError = mode === FormMode.oninvalid || errorText || error;\n const bigForm = variant === FormVariant.bigform;\n const isTransparent = transparent && mode !== FormMode.ondark && !onError;\n\n const inputWrapperClass = cn(styles['input-wrapper']);\n\n const labelWrapperClass = cn(styles['input-wrapper__label-wrapper'], {\n [styles['input-wrapper__label-wrapper--on-dark']]: onDark,\n [styles['input-wrapper__label-wrapper--disabled']]: disabled,\n });\n\n const contentWrapperClass = cn(styles['content-wrapper'], {\n [styles['content-wrapper--transparent']]: isTransparent,\n [styles['content-wrapper--on-blueberry']]: onBlueberry,\n [styles['content-wrapper--on-dark']]: onDark,\n [styles['content-wrapper--invalid']]: onError,\n [styles['content-wrapper--bigform']]: bigForm,\n [styles['content-wrapper--disabled']]: disabled,\n [styles['content-wrapper--with-icon']]: icon,\n });\n\n const inputClass = cn(styles['content-wrapper__input'], {\n [styles['content-wrapper__input--bigform']]: bigForm,\n [styles['content-wrapper__input--disabled']]: disabled,\n });\n\n const iconColor = disabled ? getColor('neutral', 500) : getColor('black');\n const iconSize = breakpoint === Breakpoint.xs || !bigForm ? IconSize.XSmall : IconSize.Small;\n\n const renderIcon = () => {\n return icon !== undefined ? <Icon color={iconColor} size={iconSize} svgIcon={icon} /> : null;\n };\n\n const handleClick = (): void => {\n if (contentWrapperRef && contentWrapperRef.current && icon) {\n const selectedChild = iconRight ? 0 : 1;\n const input = contentWrapperRef.current.children[selectedChild] as HTMLInputElement;\n input.focus();\n }\n };\n\n const maxWidth = width ? getInputMaxWidth(width, !!icon, iconSize) : undefined;\n\n return (\n <ErrorWrapper errorText={errorText}>\n <div data-testid={testId} data-analyticsid={AnalyticsId.Input} className={inputWrapperClass}>\n {label && (\n <div className={labelWrapperClass}>\n <label htmlFor={inputId}>{label}</label>\n {afterLabelChildren && <div className={styles['input-wrapper__after-label-children']}>{afterLabelChildren}</div>}\n </div>\n )}\n {belowLabelChildren && <div>{belowLabelChildren}</div>}\n <div onClick={handleClick} ref={contentWrapperRef} className={contentWrapperClass} style={{ maxWidth }}>\n {!iconRight && renderIcon()}\n <input\n name={name}\n type={type}\n defaultValue={defaultValue}\n id={inputId}\n className={inputClass}\n ref={ref}\n aria-invalid={!!onError}\n disabled={disabled}\n placeholder={placeholder}\n readOnly={readOnly}\n autoComplete={autoComplete || 'off'}\n required={required}\n {...rest}\n />\n {iconRight && renderIcon()}\n </div>\n </div>\n </ErrorWrapper>\n );\n});\n\nexport default Input;\n"],"names":["InputTypes","getInputMaxWidth","characters","hasIcon","iconSize","paddingWidth","iconWidth","borderWidth","AVERAGE_CHARACTER_WIDTH_PX","Input","React","props","ref","defaultValue","placeholder","type","inputId","uuid","name","transparent","icon","iconRight","mode","variant","label","error","errorText","testId","disabled","readOnly","autoComplete","afterLabelChildren","belowLabelChildren","width","required","rest","breakpoint","useBreakpoint","contentWrapperRef","useRef","onDark","FormMode","onBlueberry","onError","bigForm","FormVariant","isTransparent","inputWrapperClass","cn","styles","labelWrapperClass","contentWrapperClass","inputClass","iconColor","getColor","Breakpoint","IconSize","renderIcon","Icon","handleClick","selectedChild","maxWidth","ErrorWrapper","AnalyticsId"],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AAA,QAAA,CACC,KAAAQ,EACA,KAAAH,EACA,aAAAF,EACA,GAAIG,EACJ,UAAWoC,EACX,IAAAxC,EACA,eAAc,CAAC,CAAC+B,EAChB,SAAAf,EACA,YAAAd,EACA,SAAAe,EACA,aAAcC,GAAgB,MAC9B,SAAAI,EACC,GAAGC,CACN,CAAA,EACCd,GAAaoC,EAChB,CAAA,CACF,CACF,CAEJ,CAAC"}
1
+ {"version":3,"file":"Input.js","sources":["../src/components/Input/Input.tsx"],"sourcesContent":["import React, { useRef } from 'react';\nimport cn from 'classnames';\n\nimport { FormMode, FormVariant, AnalyticsId, AVERAGE_CHARACTER_WIDTH_PX } from '../../constants';\nimport { uuid } from '../../utils/uuid';\nimport Icon, { IconSize, SvgIcon } from '../Icons';\nimport { getColor } from '../../theme/currys';\nimport { Breakpoint, useBreakpoint } from '../../hooks/useBreakpoint';\n\nimport ErrorWrapper from '../ErrorWrapper';\n\nimport styles from './styles.module.scss';\n\nexport interface InputProps\n extends Pick<\n React.InputHTMLAttributes<HTMLInputElement>,\n | 'disabled'\n | 'readOnly'\n | 'autoComplete'\n | 'name'\n | 'placeholder'\n | 'defaultValue'\n | 'required'\n | 'value'\n | 'min'\n | 'max'\n | 'aria-labelledby'\n > {\n /** Adds custom classes to the element. */\n className?: string;\n /** HMTL Input type */\n type?: keyof typeof InputTypes;\n /** input id */\n inputId?: string;\n /** label id */\n labelId?: string;\n /** Width of input field in characters (approximate) */\n width?: number;\n /** If true, the component will be transparent. */\n transparent?: boolean;\n /** Icon to be displayed next to the input field */\n icon?: SvgIcon;\n /** Places the icon to the right */\n iconRight?: boolean;\n /** Changes the color profile of the input */\n mode?: keyof typeof FormMode;\n /** Changes the visuals of the input */\n variant?: keyof typeof FormVariant;\n /** Label of the input */\n label?: string;\n /** Activates Error style for the input */\n error?: boolean;\n /** Error text to show above the component */\n errorText?: string;\n /** Sets the data-testid attribute. */\n testId?: string;\n /** Component shown after label */\n afterLabelChildren?: React.ReactNode;\n /** Component shown after input */\n afterInputChildren?: React.ReactNode;\n /** Component shown under label */\n belowLabelChildren?: React.ReactNode;\n}\n\nexport enum InputTypes {\n text = 'text',\n number = 'number',\n email = 'email',\n password = 'password',\n search = 'search',\n tel = 'tel',\n url = 'url',\n date = 'date',\n time = 'time',\n}\n\nconst getInputMaxWidth = (characters: number, hasIcon: boolean, iconSize: number): string => {\n const paddingWidth = hasIcon ? '1.5rem' : '2rem';\n const iconWidth = hasIcon ? `${iconSize}px` : '0px';\n const borderWidth = '4px';\n\n return `calc(${characters * AVERAGE_CHARACTER_WIDTH_PX}px + ${paddingWidth} + ${iconWidth} + ${borderWidth})`;\n};\n\nconst Input = React.forwardRef((props: InputProps, ref: React.Ref<HTMLInputElement>) => {\n const {\n className,\n defaultValue,\n placeholder,\n type = InputTypes.text,\n inputId = uuid(),\n labelId,\n name,\n transparent = false,\n icon,\n iconRight,\n mode,\n variant,\n label,\n error,\n errorText,\n testId,\n disabled,\n readOnly,\n autoComplete,\n afterLabelChildren,\n afterInputChildren,\n belowLabelChildren,\n width,\n required,\n ...rest\n } = props;\n const breakpoint = useBreakpoint();\n const contentWrapperRef = useRef<HTMLDivElement>(null);\n\n const onDark = mode === FormMode.ondark;\n const onBlueberry = mode === FormMode.onblueberry;\n const onError = mode === FormMode.oninvalid || errorText || error;\n const bigForm = variant === FormVariant.bigform;\n const isTransparent = transparent && mode !== FormMode.ondark && !onError;\n\n const inputWrapperClass = cn(styles['input-wrapper'], className);\n\n const labelWrapperClass = cn(styles['input-wrapper__label-wrapper'], {\n [styles['input-wrapper__label-wrapper--on-dark']]: onDark,\n [styles['input-wrapper__label-wrapper--disabled']]: disabled,\n });\n\n const contentWrapperClass = cn(styles['content-wrapper'], {\n [styles['content-wrapper--transparent']]: isTransparent,\n [styles['content-wrapper--on-blueberry']]: onBlueberry,\n [styles['content-wrapper--on-dark']]: onDark,\n [styles['content-wrapper--invalid']]: onError,\n [styles['content-wrapper--bigform']]: bigForm,\n [styles['content-wrapper--disabled']]: disabled,\n [styles['content-wrapper--with-icon']]: icon,\n });\n\n const inputClass = cn(styles['content-wrapper__input'], {\n [styles['content-wrapper__input--bigform']]: bigForm,\n [styles['content-wrapper__input--disabled']]: disabled,\n });\n\n const iconColor = disabled ? getColor('neutral', 500) : getColor('black');\n const iconSize = breakpoint === Breakpoint.xs || !bigForm ? IconSize.XSmall : IconSize.Small;\n\n const renderIcon = () => {\n return icon !== undefined ? <Icon color={iconColor} size={iconSize} svgIcon={icon} /> : null;\n };\n\n const handleClick = (): void => {\n if (contentWrapperRef && contentWrapperRef.current && icon) {\n const selectedChild = iconRight ? 0 : 1;\n const input = contentWrapperRef.current.children[selectedChild] as HTMLInputElement;\n input.focus();\n }\n };\n\n const maxWidth = width ? getInputMaxWidth(width, !!icon, iconSize) : undefined;\n\n return (\n <ErrorWrapper errorText={errorText}>\n <div data-testid={testId} data-analyticsid={AnalyticsId.Input} className={inputWrapperClass}>\n {label && (\n <div className={labelWrapperClass}>\n <label id={labelId ?? undefined} htmlFor={inputId}>\n {label}\n </label>\n {afterLabelChildren && <div className={styles['input-wrapper__after-label-children']}>{afterLabelChildren}</div>}\n </div>\n )}\n {belowLabelChildren && <div>{belowLabelChildren}</div>}\n <div className={styles['input-wrapper__after-content-wrapper']}>\n <div onClick={handleClick} ref={contentWrapperRef} className={contentWrapperClass} style={{ maxWidth }}>\n {!iconRight && renderIcon()}\n <input\n name={name}\n type={type}\n defaultValue={defaultValue}\n id={inputId}\n className={inputClass}\n ref={ref}\n aria-labelledby={props['aria-labelledby'] ?? undefined}\n aria-invalid={!!onError}\n disabled={disabled}\n placeholder={placeholder}\n readOnly={readOnly}\n autoComplete={autoComplete || 'off'}\n required={required}\n {...rest}\n />\n {iconRight && renderIcon()}\n </div>\n {afterInputChildren}\n </div>\n </div>\n </ErrorWrapper>\n );\n});\n\nexport default Input;\n"],"names":["InputTypes","getInputMaxWidth","characters","hasIcon","iconSize","paddingWidth","iconWidth","borderWidth","AVERAGE_CHARACTER_WIDTH_PX","Input","React","props","ref","className","defaultValue","placeholder","type","inputId","uuid","labelId","name","transparent","icon","iconRight","mode","variant","label","error","errorText","testId","disabled","readOnly","autoComplete","afterLabelChildren","afterInputChildren","belowLabelChildren","width","required","rest","breakpoint","useBreakpoint","contentWrapperRef","useRef","onDark","FormMode","onBlueberry","onError","bigForm","FormVariant","isTransparent","inputWrapperClass","cn","styles","labelWrapperClass","contentWrapperClass","inputClass","iconColor","getColor","Breakpoint","IconSize","renderIcon","Icon","handleClick","selectedChild","maxWidth","ErrorWrapper","AnalyticsId","_a"],"mappings":"meAgEY,IAAAA,IAAAA,IACVA,EAAA,KAAO,OACPA,EAAA,OAAS,SACTA,EAAA,MAAQ,QACRA,EAAA,SAAW,WACXA,EAAA,OAAS,SACTA,EAAA,IAAM,MACNA,EAAA,IAAM,MACNA,EAAA,KAAO,OACPA,EAAA,KAAO,OATGA,IAAAA,IAAA,CAAA,CAAA,EAYZ,MAAMC,GAAmB,CAACC,EAAoBC,EAAkBC,IAA6B,CACrF,MAAAC,EAAeF,EAAU,SAAW,OACpCG,EAAYH,EAAU,GAAGC,MAAe,MACxCG,EAAc,MAEpB,MAAO,QAAQL,EAAaM,UAAkCH,OAAkBC,OAAeC,IACjG,EAEME,GAAQC,EAAM,WAAW,CAACC,EAAmBC,IAAqC,OAChF,KAAA,CACJ,UAAAC,EACA,aAAAC,EACA,YAAAC,EACA,KAAAC,EAAO,OACP,QAAAC,EAAUC,GAAK,EACf,QAAAC,EACA,KAAAC,EACA,YAAAC,EAAc,GACd,KAAAC,EACA,UAAAC,EACA,KAAAC,EACA,QAAAC,EACA,MAAAC,EACA,MAAAC,EACA,UAAAC,EACA,OAAAC,EACA,SAAAC,EACA,SAAAC,EACA,aAAAC,EACA,mBAAAC,EACA,mBAAAC,EACA,mBAAAC,EACA,MAAAC,EACA,SAAAC,KACGC,CACD,EAAA3B,EACE4B,EAAaC,KACbC,EAAoBC,EAAuB,IAAI,EAE/CC,EAASnB,IAASoB,EAAS,OAC3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Q,mBAAkBqC,EAAY,MAAO,UAAWhB,CAAA,EACvExB,GACEhB,EAAA,cAAA,MAAA,CAAI,UAAW2C,CAAA,EACb3C,EAAA,cAAA,QAAA,CAAM,GAAIS,GAAA,KAAAA,EAAW,OAAW,QAASF,CACvC,EAAAS,CACH,EACCO,GAAuBvB,EAAA,cAAA,MAAA,CAAI,UAAW0C,EAAO,sCAAyC,EAAAnB,CAAmB,CAC5G,EAEDE,mBAAuB,MAAK,KAAAA,CAAmB,EAC/CzB,EAAA,cAAA,MAAA,CAAI,UAAW0C,EAAO,uCAAA,EACpB1C,EAAA,cAAA,MAAA,CAAI,QAASoD,EAAa,IAAKrB,EAAmB,UAAWa,EAAqB,MAAO,CAAE,SAAAU,CAAS,CAAA,EAClG,CAACzC,GAAaqC,EAAW,EACzBlD,EAAA,cAAA,QAAA,CACC,KAAAU,EACA,KAAAJ,EACA,aAAAF,EACA,GAAIG,EACJ,UAAWsC,EACX,IAAA3C,EACA,mBAAiBuD,EAAAxD,EAAM,qBAAN,KAAAwD,EAA4B,OAC7C,eAAc,CAAC,CAACrB,EAChB,SAAAhB,EACA,YAAAf,EACA,SAAAgB,EACA,aAAcC,GAAgB,MAC9B,SAAAK,EACC,GAAGC,CAAA,CACN,EACCf,GAAaqC,EAAA,CAChB,EACC1B,CACH,CACF,CACF,CAEJ,CAAC"}
package/Modal.js CHANGED
@@ -1,2 +1,2 @@
1
- import t,{useEffect as W}from"react";import n from"classnames";import{palette as d}from"./theme/palette.js";import{B as N}from"./Button.js";import{Icon as u}from"./components/Icons/Icon.js";import{ZIndex as z,AnalyticsId as R,IconSize as c}from"./constants.js";import a from"./components/Modal/styles.module.scss";import P from"./components/Icons/AlertSignStroke.js";import $ from"./components/Icons/AlertSignFill.js";import{useFocusTrap as A}from"./hooks/useFocusTrap.js";import{useIsVisible as I}from"./hooks/useIsVisible.js";import{T as F}from"./Title.js";import{a as H}from"./uuid.js";import{C as K}from"./Close.js";import O from"./components/Icons/CheckOutline.js";import D from"./components/Portal/index.js";var M=(e=>(e.normal="normal",e.warning="warning",e.error="error",e.success="success",e.image="image",e))(M||{}),V=(e=>(e.large="large",e.medium="medium",e))(V||{});const Z={variant:"normal",primaryButtonText:"OK",titleId:H(),className:"",size:"large",zIndex:z.Modal},j=e=>e==="error"?t.createElement(u,{size:c.Small,svgIcon:$,color:d.cherry500}):e==="warning"?t.createElement(u,{size:c.Small,svgIcon:P,color:d.black}):e==="success"?t.createElement(u,{size:c.Small,svgIcon:O,color:d.kiwi900}):null,q=(e,r)=>{const o=j(e);return o?t.createElement("div",{className:a.modal__iconWrapper},o):r?t.createElement("div",{className:a.modal__iconWrapper},t.cloneElement(r,{size:c.Small})):null},G=e=>{var C,h;const r=t.useRef(null),o=t.useRef(null),_=t.useRef(null);A(_,!0,!0);const w=I(r),f=t.useRef(null),B=I(f),m=o.current&&o.current.scrollHeight>o.current.clientHeight;function v(l){l.key==="Escape"&&e.onClose&&(l.stopPropagation(),e.onClose())}function E(l){l.target&&s.current===l.target&&e.onClose&&(l.stopPropagation(),e.onClose())}function k(){document.body.style.overflow="hidden"}function L(){document.body.style.removeProperty("overflow")}const i=e.variant==="image",s=t.useRef(null),g=e.secondaryButtonText&&((C=e.secondaryButtonText)==null?void 0:C.length)>0||e.onSuccess,S=e.ariaLabelledBy?void 0:e.ariaLabel,y=e.ariaLabelledBy?e.ariaLabelledBy:e.ariaLabel?void 0:e.titleId;W(()=>{const l=s.current;return k(),!e.disableCloseEvents&&l&&(l.addEventListener("keydown",v),l.addEventListener("click",E)),()=>{L(),!e.disableCloseEvents&&l&&(l.removeEventListener("keydown",v),l.removeEventListener("click",E))}},[e.disableCloseEvents]);const T=n(e.className,a.modal,a[`modal--${e.variant}`],a[`modal--${e.size}`],m&&!g&&a["modal--no-actions"]),x=n({[a["modal__title--error"]]:e.variant==="error",[a["modal__title--success"]]:e.variant==="success"}),b=t.createElement("div",{"data-testid":"dialog-container"},t.createElement("div",{ref:s,className:a["modal-overlay"],"data-testid":e.testId,"data-analyticsid":R.Modal,style:{zIndex:e.zIndex}},t.createElement("div",{className:a.align},t.createElement("div",{className:T,role:"dialog","aria-label":S,"aria-labelledby":y,ref:_},t.createElement("div",{className:n(a.modal__shadow,a["modal__shadow--top"],{[a["modal__shadow--show"]]:!w&&m})}),t.createElement("div",{className:n(a.modal__contentWrapper,{[a["modal__contentWrapper--image"]]:i}),ref:o},!e.noCloseButton&&t.createElement("div",{className:a.modal__closeWrapper},t.createElement("div",{className:n(a.modal__closeWrapper__close)},t.createElement(K,{onClick:e.onClose,ariaLabel:e.ariaLabelCloseBtn}))),t.createElement("div",{className:n(a[`modal__contentWrapper__scroll--${e.size}`],{[a["modal__contentWrapper__scroll--image"]]:i})},t.createElement("div",{ref:r}),t.createElement("div",{className:a.modal__contentWrapper__title},q(e.variant,e.icon),t.createElement(F,{id:y,htmlMarkup:"h3",appearance:"title3",className:x},e.title),e.afterTitleChildren&&t.createElement("div",{className:a.modal__afterTitleChildren},e.afterTitleChildren)),i&&t.createElement("div",null,t.createElement("div",{className:a.modal__contentWrapper__imageWrapper},e.children),t.createElement("span",{className:a.modal__contentWrapper__imageDescription},e.description)),!i&&e.children&&t.createElement("div",null,e.children),!i&&!e.children&&t.createElement("p",{className:a.modal__description},e.description),t.createElement("div",{ref:f}))),t.createElement("div",{className:n(a.modal__shadow,a["modal__shadow--bottom"],{[a["modal__shadow--show"]]:!B&&m})}),g&&t.createElement("div",{className:n(a["modal__call-to-action"],a[`modal__call-to-action--${e.size}`])},e.onSuccess&&t.createElement(N,{onClick:e.onSuccess},e.primaryButtonText),e.secondaryButtonText&&((h=e.secondaryButtonText)==null?void 0:h.length)>0&&t.createElement(N,{variant:"borderless",onClick:e.onClose},e.secondaryButtonText))))));if(e.printable){const l="print-modal";return t.createElement(D,{className:l,testId:"print-modal"},t.createElement("style",{media:"print"},`body > *:not(.${l}) {display: none;}`),b)}return b};G.defaultProps=Z;export{G as M,M as a,V as b};
1
+ import t,{useEffect as N}from"react";import n from"classnames";import{palette as u}from"./theme/palette.js";import{B as I}from"./Button.js";import{Icon as _}from"./components/Icons/Icon.js";import{ZIndex as z,AnalyticsId as R,IconSize as c}from"./constants.js";import a from"./components/Modal/styles.module.scss";import P from"./components/Icons/AlertSignStroke.js";import $ from"./components/Icons/AlertSignFill.js";import{useFocusTrap as A}from"./hooks/useFocusTrap.js";import{useIsVisible as w}from"./hooks/useIsVisible.js";import{T as F}from"./Title.js";import{a as H}from"./uuid.js";import{C as K}from"./Close.js";import O from"./components/Icons/CheckOutline.js";import D from"./components/Portal/index.js";var M=(e=>(e.normal="normal",e.warning="warning",e.error="error",e.success="success",e.image="image",e))(M||{}),V=(e=>(e.large="large",e.medium="medium",e))(V||{});const Z={variant:"normal",primaryButtonText:"OK",titleId:H(),className:"",size:"large",zIndex:z.Modal},j=e=>e==="error"?t.createElement(_,{size:c.Small,svgIcon:$,color:u.cherry500}):e==="warning"?t.createElement(_,{size:c.Small,svgIcon:P,color:u.black}):e==="success"?t.createElement(_,{size:c.Small,svgIcon:O,color:u.kiwi900}):null,q=(e,r)=>{const o=j(e);return o?t.createElement("div",{className:a.modal__iconWrapper},o):r?t.createElement("div",{className:a.modal__iconWrapper},t.cloneElement(r,{size:c.Small})):null},G=e=>{var C,h;const r=t.useRef(null),o=t.useRef(null),m=t.useRef(null);A(m,!0);const B=w(r),f=t.useRef(null),k=w(f),s=o.current&&o.current.scrollHeight>o.current.clientHeight;function v(l){l.key==="Escape"&&e.onClose&&(l.stopPropagation(),e.onClose())}function E(l){l.target&&d.current===l.target&&e.onClose&&(l.stopPropagation(),e.onClose())}function x(){document.body.style.overflow="hidden"}function L(){document.body.style.removeProperty("overflow")}const i=e.variant==="image",d=t.useRef(null),g=e.secondaryButtonText&&((C=e.secondaryButtonText)==null?void 0:C.length)>0||e.onSuccess,S=e.ariaLabelledBy?void 0:e.ariaLabel,y=e.ariaLabelledBy?e.ariaLabelledBy:e.ariaLabel?void 0:e.titleId;N(()=>{const l=d.current;return x(),!e.disableCloseEvents&&l&&(l.addEventListener("keydown",v),l.addEventListener("click",E)),()=>{L(),!e.disableCloseEvents&&l&&(l.removeEventListener("keydown",v),l.removeEventListener("click",E))}},[e.disableCloseEvents]),N(()=>{var l;(l=m.current)==null||l.focus()},[]);const T=n(e.className,a.modal,a[`modal--${e.variant}`],a[`modal--${e.size}`],s&&!g&&a["modal--no-actions"]),W=n({[a["modal__title--error"]]:e.variant==="error",[a["modal__title--success"]]:e.variant==="success"}),b=t.createElement("div",{"data-testid":"dialog-container"},t.createElement("div",{ref:d,className:a["modal-overlay"],"data-testid":e.testId,"data-analyticsid":R.Modal,style:{zIndex:e.zIndex}},t.createElement("div",{className:a.align},t.createElement("div",{className:T,role:"dialog","aria-modal":"true",tabIndex:-1,"aria-label":S,"aria-labelledby":y,ref:m},t.createElement("div",{className:n(a.modal__shadow,a["modal__shadow--top"],{[a["modal__shadow--show"]]:!B&&s})}),t.createElement("div",{className:n(a.modal__contentWrapper,{[a["modal__contentWrapper--image"]]:i}),ref:o},!e.noCloseButton&&t.createElement("div",{className:a.modal__closeWrapper},t.createElement("div",{className:n(a.modal__closeWrapper__close)},t.createElement(K,{onClick:e.onClose,ariaLabel:e.ariaLabelCloseBtn}))),t.createElement("div",{className:n(a[`modal__contentWrapper__scroll--${e.size}`],{[a["modal__contentWrapper__scroll--image"]]:i})},t.createElement("div",{ref:r}),t.createElement("div",{className:a.modal__contentWrapper__title},q(e.variant,e.icon),t.createElement(F,{id:y,htmlMarkup:"h3",appearance:"title3",className:W},e.title),e.afterTitleChildren&&t.createElement("div",{className:a.modal__afterTitleChildren},e.afterTitleChildren)),i&&t.createElement("div",null,t.createElement("div",{className:a.modal__contentWrapper__imageWrapper},e.children),t.createElement("span",{className:a.modal__contentWrapper__imageDescription},e.description)),!i&&e.children&&t.createElement("div",null,e.children),!i&&!e.children&&t.createElement("p",{className:a.modal__description},e.description),t.createElement("div",{ref:f}))),t.createElement("div",{className:n(a.modal__shadow,a["modal__shadow--bottom"],{[a["modal__shadow--show"]]:!k&&s})}),g&&t.createElement("div",{className:n(a["modal__call-to-action"],a[`modal__call-to-action--${e.size}`])},e.onSuccess&&t.createElement(I,{onClick:e.onSuccess},e.primaryButtonText),e.secondaryButtonText&&((h=e.secondaryButtonText)==null?void 0:h.length)>0&&t.createElement(I,{variant:"borderless",onClick:e.onClose},e.secondaryButtonText))))));if(e.printable){const l="print-modal";return t.createElement(D,{className:l,testId:"print-modal"},t.createElement("style",{media:"print"},`body > *:not(.${l}) {display: none;}`),b)}return b};G.defaultProps=Z;export{G as M,M as a,V as b};
2
2
  //# sourceMappingURL=Modal.js.map
package/Modal.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Modal.js","sources":["../src/components/Modal/Modal.tsx"],"sourcesContent":["import React, { useEffect } from 'react';\nimport cn from 'classnames';\n\nimport { palette } from '../../theme/palette';\nimport Button from '../Button';\nimport Icon, { IconSize } from '../Icons';\n\nimport styles from './styles.module.scss';\nimport AlertSignStroke from '../Icons/AlertSignStroke';\nimport AlertSignFill from '../Icons/AlertSignFill';\nimport useFocusTrap from '../../hooks/useFocusTrap';\nimport { useIsVisible } from '../../hooks/useIsVisible';\nimport Title from '../Title/Title';\nimport { uuid } from '../../utils/uuid';\nimport Close from '../Close';\nimport CheckOutline from '../Icons/CheckOutline';\nimport Portal from '../Portal';\nimport { AnalyticsId, ZIndex } from '../../constants';\n\nexport enum ModalVariants {\n normal = 'normal',\n warning = 'warning',\n error = 'error',\n success = 'success',\n image = 'image',\n}\n\nexport enum ModalSize {\n large = 'large',\n medium = 'medium',\n}\n\nexport interface ModalProps {\n /** Title of the modal */\n title: string;\n /** id of the modal title */\n titleId?: string;\n /** Description of the modal. Will not render if the modal has children. */\n description?: string;\n /** Changes the visual representation of the modal */\n variant?: keyof typeof ModalVariants;\n /** Change width of the modal (default: large) */\n size?: keyof typeof ModalSize;\n /** Icon displayed in title */\n icon?: React.ReactElement;\n /** Hides the close button */\n noCloseButton?: boolean;\n /** Sets the data-testid attribute. */\n testId?: string;\n /** Primary button text */\n primaryButtonText?: string;\n /** Secondary button text */\n secondaryButtonText?: string;\n /** Sets the aria-label of the modal */\n ariaLabel?: string;\n /** Sets the aria-labelledby of the modal */\n ariaLabelledBy?: string;\n /** Close button aria-label */\n ariaLabelCloseBtn?: string;\n /** Alternative component to modal */\n children?: React.ReactNode;\n /** Component shown after title */\n afterTitleChildren?: React.ReactNode;\n /** Adds custom classes to the element. */\n className?: string;\n /** Customize the z-index of the modal */\n zIndex?: number;\n /** Function is called when user clicks primary button */\n onSuccess?: () => void;\n /** Function is called when user clicks secondary button, clicks escape or outside the modal */\n onClose?: () => void;\n /** When enabled the component will be rendered in the bottom of document.body */\n printable?: boolean;\n /** If disabled, clicking escape or outside the modal will not close it */\n disableCloseEvents?: boolean;\n}\n\nconst defaultProps = {\n variant: ModalVariants.normal,\n primaryButtonText: 'OK',\n titleId: uuid(),\n className: '',\n size: ModalSize.large,\n zIndex: ZIndex.Modal,\n};\n\nconst getVariantIcon = (variant?: ModalProps['variant']): JSX.Element | null => {\n if (variant === ModalVariants.error) {\n return <Icon size={IconSize.Small} svgIcon={AlertSignFill} color={palette.cherry500} />;\n } else if (variant === ModalVariants.warning) {\n return <Icon size={IconSize.Small} svgIcon={AlertSignStroke} color={palette.black} />;\n } else if (variant === ModalVariants.success) {\n return <Icon size={IconSize.Small} svgIcon={CheckOutline} color={palette.kiwi900} />;\n }\n return null;\n};\n\nconst getIcon = (variant?: ModalProps['variant'], icon?: ModalProps['icon']): JSX.Element | null => {\n const variantIcon = getVariantIcon(variant);\n if (variantIcon) {\n return <div className={styles.modal__iconWrapper}>{variantIcon}</div>;\n }\n if (icon) {\n return (\n <div className={styles.modal__iconWrapper}>\n {React.cloneElement(icon, {\n size: IconSize.Small,\n })}\n </div>\n );\n }\n return null;\n};\n\nconst Modal = (props: ModalProps): JSX.Element => {\n const topContent = React.useRef<HTMLDivElement>(null);\n const modalContentRef = React.useRef<HTMLDivElement>(null);\n const dialogRef = React.useRef<HTMLDivElement>(null);\n useFocusTrap(dialogRef, true, true);\n const topContentVisible = useIsVisible(topContent);\n const bottomContent = React.useRef<HTMLDivElement>(null);\n const bottomContentVisible = useIsVisible(bottomContent);\n const contentIsScrollable = modalContentRef.current && modalContentRef.current.scrollHeight > modalContentRef.current.clientHeight;\n\n function handleKeyboardEvent(e: KeyboardEvent): void {\n if (e.key === 'Escape' && props.onClose) {\n e.stopPropagation();\n props.onClose();\n }\n }\n\n function handleClickEvent(event: MouseEvent): void {\n if (event.target && overlayRef.current === event.target && props.onClose) {\n event.stopPropagation();\n props.onClose();\n }\n }\n\n function disableBodyScroll(): void {\n document.body.style.overflow = 'hidden';\n }\n\n function enableBodyScroll(): void {\n document.body.style.removeProperty('overflow');\n }\n\n /* Displays a full window size modal with image */\n const imageView = props.variant === ModalVariants.image;\n\n const overlayRef = React.useRef<HTMLDivElement>(null);\n\n const showActions = (props.secondaryButtonText && props.secondaryButtonText?.length > 0) || props.onSuccess;\n\n // ariaLabelledBy prioriteres over ariaLabel, men dersom ariaLabel brukes trengs ikke ariaLabelledBy\n const ariaLabel = !props.ariaLabelledBy ? props.ariaLabel : undefined;\n const ariaLabelledBy = props.ariaLabelledBy ? props.ariaLabelledBy : !props.ariaLabel ? props.titleId : undefined;\n\n useEffect(() => {\n const overlayElement = overlayRef.current;\n disableBodyScroll();\n if (!props.disableCloseEvents && overlayElement) {\n overlayElement.addEventListener('keydown', handleKeyboardEvent);\n overlayElement.addEventListener('click', handleClickEvent);\n }\n return (): void => {\n enableBodyScroll();\n if (!props.disableCloseEvents && overlayElement) {\n overlayElement.removeEventListener('keydown', handleKeyboardEvent);\n overlayElement.removeEventListener('click', handleClickEvent);\n }\n };\n }, [props.disableCloseEvents]);\n\n const dialogClasses = cn(\n props.className,\n styles.modal,\n styles[`modal--${props.variant}`],\n styles[`modal--${props.size}`],\n contentIsScrollable && !showActions && styles['modal--no-actions']\n );\n\n const titleClasses = cn({\n [styles['modal__title--error']]: props.variant === ModalVariants.error,\n [styles['modal__title--success']]: props.variant === ModalVariants.success,\n });\n\n const Component = (\n <div data-testid=\"dialog-container\">\n <div\n ref={overlayRef}\n className={styles['modal-overlay']}\n data-testid={props.testId}\n data-analyticsid={AnalyticsId.Modal}\n style={{ zIndex: props.zIndex }}\n >\n <div className={styles.align}>\n <div className={dialogClasses} role=\"dialog\" aria-label={ariaLabel} aria-labelledby={ariaLabelledBy} ref={dialogRef}>\n <div\n className={cn(styles['modal__shadow'], styles['modal__shadow--top'], {\n [styles['modal__shadow--show']]: !topContentVisible && contentIsScrollable,\n })}\n />\n <div\n className={cn(styles.modal__contentWrapper, {\n [styles['modal__contentWrapper--image']]: imageView,\n })}\n ref={modalContentRef}\n >\n {!props.noCloseButton && (\n <div className={styles.modal__closeWrapper}>\n <div className={cn(styles.modal__closeWrapper__close)}>\n <Close onClick={props.onClose} ariaLabel={props.ariaLabelCloseBtn} />\n </div>\n </div>\n )}\n <div\n className={cn(styles[`modal__contentWrapper__scroll--${props.size}`], {\n [styles['modal__contentWrapper__scroll--image']]: imageView,\n })}\n >\n <div ref={topContent} />\n <div className={styles.modal__contentWrapper__title}>\n {getIcon(props.variant, props.icon)}\n <Title id={ariaLabelledBy} htmlMarkup=\"h3\" appearance=\"title3\" className={titleClasses}>\n {props.title}\n </Title>\n {props.afterTitleChildren && <div className={styles['modal__afterTitleChildren']}>{props.afterTitleChildren}</div>}\n </div>\n {imageView && (\n <div>\n <div className={styles['modal__contentWrapper__imageWrapper']}>{props.children}</div>\n <span className={styles['modal__contentWrapper__imageDescription']}>{props.description}</span>\n </div>\n )}\n {!imageView && props.children && <div>{props.children}</div>}\n {!imageView && !props.children && <p className={styles.modal__description}>{props.description}</p>}\n <div ref={bottomContent} />\n </div>\n </div>\n <div\n className={cn(styles['modal__shadow'], styles['modal__shadow--bottom'], {\n [styles['modal__shadow--show']]: !bottomContentVisible && contentIsScrollable,\n })}\n />\n {showActions && (\n <div className={cn(styles['modal__call-to-action'], styles[`modal__call-to-action--${props.size}`])}>\n {props.onSuccess && <Button onClick={props.onSuccess}>{props.primaryButtonText}</Button>}\n {props.secondaryButtonText && props.secondaryButtonText?.length > 0 && (\n <Button variant=\"borderless\" onClick={props.onClose}>\n {props.secondaryButtonText}\n </Button>\n )}\n </div>\n )}\n </div>\n </div>\n </div>\n </div>\n );\n\n if (props.printable) {\n const printModal = 'print-modal';\n return (\n <Portal className={printModal} testId=\"print-modal\">\n <style media=\"print\">{`body > *:not(.${printModal}) {display: none;}`}</style>\n {Component}\n </Portal>\n );\n }\n\n return Component;\n};\n\nModal.defaultProps = defaultProps;\n\nexport default Modal;\n"],"names":["ModalVariants","ModalSize","defaultProps","uuid","ZIndex","getVariantIcon","variant","React","Icon","IconSize","AlertSignFill","palette","AlertSignStroke","CheckOutline","getIcon","icon","variantIcon","styles","Modal","props","topContent","modalContentRef","dialogRef","useFocusTrap","topContentVisible","useIsVisible","bottomContent","bottomContentVisible","contentIsScrollable","handleKeyboardEvent","e","handleClickEvent","event","overlayRef","disableBodyScroll","enableBodyScroll","imageView","showActions","_a","ariaLabel","ariaLabelledBy","useEffect","overlayElement","dialogClasses","cn","titleClasses","Component","AnalyticsId","Close","Title","Button","_b","printModal","Portal"],"mappings":"0sBAmBY,IAAAA,GAAAA,IACVA,EAAA,OAAS,SACTA,EAAA,QAAU,UACVA,EAAA,MAAQ,QACRA,EAAA,QAAU,UACVA,EAAA,MAAQ,QALEA,IAAAA,GAAA,CAAA,CAAA,EAQAC,GAAAA,IACVA,EAAA,MAAQ,QACRA,EAAA,OAAS,SAFCA,IAAAA,GAAA,CAAA,CAAA,EAkDZ,MAAMC,EAAe,CACnB,QAAS,SACT,kBAAmB,KACnB,QAASC,EAAK,EACd,UAAW,GACX,KAAM,QACN,OAAQC,EAAO,KACjB,EAEMC,EAAkBC,GAClBA,IAAY,QACNC,EAAA,cAAAC,EAAA,CAAK,KAAMC,EAAS,MAAO,QAASC,EAAe,MAAOC,EAAQ,SAAA,CAAW,EAC5EL,IA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AO,kBAAqB,EAAAE,EAAM,WAAY,EAC7FZ,EAAA,cAAA,MAAA,CAAI,IAAKmB,CAAe,CAAA,CAC3B,CACF,EACCnB,EAAA,cAAA,MAAA,CACC,UAAWqC,EAAG3B,EAAO,cAAkBA,EAAO,yBAA0B,CACtE,CAACA,EAAO,wBAAyB,CAACU,GAAwBC,CAAA,CAC3D,CACH,CAAA,EACCS,GACE9B,EAAA,cAAA,MAAA,CAAI,UAAWqC,EAAG3B,EAAO,yBAA0BA,EAAO,0BAA0BE,EAAM,OAAO,CAC/F,EAAAA,EAAM,WAAcZ,EAAA,cAAA2C,EAAA,CAAO,QAAS/B,EAAM,SAAY,EAAAA,EAAM,iBAAkB,EAC9EA,EAAM,uBAAuBgC,EAAAhC,EAAM,sBAAN,YAAAgC,EAA2B,QAAS,GAC/D5C,EAAA,cAAA2C,EAAA,CAAO,QAAQ,aAAa,QAAS/B,EAAM,OAAA,EACzCA,EAAM,mBACT,CAEJ,CAEJ,CACF,CACF,CACF,EAGF,GAAIA,EAAM,UAAW,CACnB,MAAMiC,EAAa,cACnB,OACG7C,EAAA,cAAA8C,EAAA,CAAO,UAAWD,EAAY,OAAO,aAAA,EACnC7C,EAAA,cAAA,QAAA,CAAM,MAAM,OAAA,EAAS,iBAAiB6C,qBAA+B,EACrEN,CACH,CAEJ,CAEO,OAAAA,CACT,EAEA5B,EAAM,aAAehB"}
1
+ {"version":3,"file":"Modal.js","sources":["../src/components/Modal/Modal.tsx"],"sourcesContent":["import React, { useEffect } from 'react';\nimport cn from 'classnames';\n\nimport { palette } from '../../theme/palette';\nimport Button from '../Button';\nimport Icon, { IconSize } from '../Icons';\n\nimport styles from './styles.module.scss';\nimport AlertSignStroke from '../Icons/AlertSignStroke';\nimport AlertSignFill from '../Icons/AlertSignFill';\nimport useFocusTrap from '../../hooks/useFocusTrap';\nimport { useIsVisible } from '../../hooks/useIsVisible';\nimport Title from '../Title/Title';\nimport { uuid } from '../../utils/uuid';\nimport Close from '../Close';\nimport CheckOutline from '../Icons/CheckOutline';\nimport Portal from '../Portal';\nimport { AnalyticsId, ZIndex } from '../../constants';\n\nexport enum ModalVariants {\n normal = 'normal',\n warning = 'warning',\n error = 'error',\n success = 'success',\n image = 'image',\n}\n\nexport enum ModalSize {\n large = 'large',\n medium = 'medium',\n}\n\nexport interface ModalProps {\n /** Title of the modal */\n title: string;\n /** id of the modal title */\n titleId?: string;\n /** Description of the modal. Will not render if the modal has children. */\n description?: string;\n /** Changes the visual representation of the modal */\n variant?: keyof typeof ModalVariants;\n /** Change width of the modal (default: large) */\n size?: keyof typeof ModalSize;\n /** Icon displayed in title */\n icon?: React.ReactElement;\n /** Hides the close button */\n noCloseButton?: boolean;\n /** Sets the data-testid attribute. */\n testId?: string;\n /** Primary button text */\n primaryButtonText?: string;\n /** Secondary button text */\n secondaryButtonText?: string;\n /** Sets the aria-label of the modal */\n ariaLabel?: string;\n /** Sets the aria-labelledby of the modal */\n ariaLabelledBy?: string;\n /** Close button aria-label */\n ariaLabelCloseBtn?: string;\n /** Alternative component to modal */\n children?: React.ReactNode;\n /** Component shown after title */\n afterTitleChildren?: React.ReactNode;\n /** Adds custom classes to the element. */\n className?: string;\n /** Customize the z-index of the modal */\n zIndex?: number;\n /** Function is called when user clicks primary button */\n onSuccess?: () => void;\n /** Function is called when user clicks secondary button, clicks escape or outside the modal */\n onClose?: () => void;\n /** When enabled the component will be rendered in the bottom of document.body */\n printable?: boolean;\n /** If disabled, clicking escape or outside the modal will not close it */\n disableCloseEvents?: boolean;\n}\n\nconst defaultProps = {\n variant: ModalVariants.normal,\n primaryButtonText: 'OK',\n titleId: uuid(),\n className: '',\n size: ModalSize.large,\n zIndex: ZIndex.Modal,\n};\n\nconst getVariantIcon = (variant?: ModalProps['variant']): JSX.Element | null => {\n if (variant === ModalVariants.error) {\n return <Icon size={IconSize.Small} svgIcon={AlertSignFill} color={palette.cherry500} />;\n } else if (variant === ModalVariants.warning) {\n return <Icon size={IconSize.Small} svgIcon={AlertSignStroke} color={palette.black} />;\n } else if (variant === ModalVariants.success) {\n return <Icon size={IconSize.Small} svgIcon={CheckOutline} color={palette.kiwi900} />;\n }\n return null;\n};\n\nconst getIcon = (variant?: ModalProps['variant'], icon?: ModalProps['icon']): JSX.Element | null => {\n const variantIcon = getVariantIcon(variant);\n if (variantIcon) {\n return <div className={styles.modal__iconWrapper}>{variantIcon}</div>;\n }\n if (icon) {\n return (\n <div className={styles.modal__iconWrapper}>\n {React.cloneElement(icon, {\n size: IconSize.Small,\n })}\n </div>\n );\n }\n return null;\n};\n\nconst Modal = (props: ModalProps): JSX.Element => {\n const topContent = React.useRef<HTMLDivElement>(null);\n const modalContentRef = React.useRef<HTMLDivElement>(null);\n const dialogRef = React.useRef<HTMLDivElement>(null);\n useFocusTrap(dialogRef, true);\n const topContentVisible = useIsVisible(topContent);\n const bottomContent = React.useRef<HTMLDivElement>(null);\n const bottomContentVisible = useIsVisible(bottomContent);\n const contentIsScrollable = modalContentRef.current && modalContentRef.current.scrollHeight > modalContentRef.current.clientHeight;\n\n function handleKeyboardEvent(e: KeyboardEvent): void {\n if (e.key === 'Escape' && props.onClose) {\n e.stopPropagation();\n props.onClose();\n }\n }\n\n function handleClickEvent(event: MouseEvent): void {\n if (event.target && overlayRef.current === event.target && props.onClose) {\n event.stopPropagation();\n props.onClose();\n }\n }\n\n function disableBodyScroll(): void {\n document.body.style.overflow = 'hidden';\n }\n\n function enableBodyScroll(): void {\n document.body.style.removeProperty('overflow');\n }\n\n /* Displays a full window size modal with image */\n const imageView = props.variant === ModalVariants.image;\n\n const overlayRef = React.useRef<HTMLDivElement>(null);\n\n const showActions = (props.secondaryButtonText && props.secondaryButtonText?.length > 0) || props.onSuccess;\n\n // ariaLabelledBy prioriteres over ariaLabel, men dersom ariaLabel brukes trengs ikke ariaLabelledBy\n const ariaLabel = !props.ariaLabelledBy ? props.ariaLabel : undefined;\n const ariaLabelledBy = props.ariaLabelledBy ? props.ariaLabelledBy : !props.ariaLabel ? props.titleId : undefined;\n\n useEffect(() => {\n const overlayElement = overlayRef.current;\n disableBodyScroll();\n if (!props.disableCloseEvents && overlayElement) {\n overlayElement.addEventListener('keydown', handleKeyboardEvent);\n overlayElement.addEventListener('click', handleClickEvent);\n }\n return (): void => {\n enableBodyScroll();\n if (!props.disableCloseEvents && overlayElement) {\n overlayElement.removeEventListener('keydown', handleKeyboardEvent);\n overlayElement.removeEventListener('click', handleClickEvent);\n }\n };\n }, [props.disableCloseEvents]);\n\n useEffect(() => {\n dialogRef.current?.focus();\n }, []);\n\n const dialogClasses = cn(\n props.className,\n styles.modal,\n styles[`modal--${props.variant}`],\n styles[`modal--${props.size}`],\n contentIsScrollable && !showActions && styles['modal--no-actions']\n );\n\n const titleClasses = cn({\n [styles['modal__title--error']]: props.variant === ModalVariants.error,\n [styles['modal__title--success']]: props.variant === ModalVariants.success,\n });\n\n const Component = (\n <div data-testid=\"dialog-container\">\n <div\n ref={overlayRef}\n className={styles['modal-overlay']}\n data-testid={props.testId}\n data-analyticsid={AnalyticsId.Modal}\n style={{ zIndex: props.zIndex }}\n >\n <div className={styles.align}>\n <div\n className={dialogClasses}\n role=\"dialog\"\n aria-modal=\"true\"\n tabIndex={-1}\n aria-label={ariaLabel}\n aria-labelledby={ariaLabelledBy}\n ref={dialogRef}\n >\n <div\n className={cn(styles['modal__shadow'], styles['modal__shadow--top'], {\n [styles['modal__shadow--show']]: !topContentVisible && contentIsScrollable,\n })}\n />\n <div\n className={cn(styles.modal__contentWrapper, {\n [styles['modal__contentWrapper--image']]: imageView,\n })}\n ref={modalContentRef}\n >\n {!props.noCloseButton && (\n <div className={styles.modal__closeWrapper}>\n <div className={cn(styles.modal__closeWrapper__close)}>\n <Close onClick={props.onClose} ariaLabel={props.ariaLabelCloseBtn} />\n </div>\n </div>\n )}\n <div\n className={cn(styles[`modal__contentWrapper__scroll--${props.size}`], {\n [styles['modal__contentWrapper__scroll--image']]: imageView,\n })}\n >\n <div ref={topContent} />\n <div className={styles.modal__contentWrapper__title}>\n {getIcon(props.variant, props.icon)}\n <Title id={ariaLabelledBy} htmlMarkup=\"h3\" appearance=\"title3\" className={titleClasses}>\n {props.title}\n </Title>\n {props.afterTitleChildren && <div className={styles['modal__afterTitleChildren']}>{props.afterTitleChildren}</div>}\n </div>\n {imageView && (\n <div>\n <div className={styles['modal__contentWrapper__imageWrapper']}>{props.children}</div>\n <span className={styles['modal__contentWrapper__imageDescription']}>{props.description}</span>\n </div>\n )}\n {!imageView && props.children && <div>{props.children}</div>}\n {!imageView && !props.children && <p className={styles.modal__description}>{props.description}</p>}\n <div ref={bottomContent} />\n </div>\n </div>\n <div\n className={cn(styles['modal__shadow'], styles['modal__shadow--bottom'], {\n [styles['modal__shadow--show']]: !bottomContentVisible && contentIsScrollable,\n })}\n />\n {showActions && (\n <div className={cn(styles['modal__call-to-action'], styles[`modal__call-to-action--${props.size}`])}>\n {props.onSuccess && <Button onClick={props.onSuccess}>{props.primaryButtonText}</Button>}\n {props.secondaryButtonText && props.secondaryButtonText?.length > 0 && (\n <Button variant=\"borderless\" onClick={props.onClose}>\n {props.secondaryButtonText}\n </Button>\n )}\n </div>\n )}\n </div>\n </div>\n </div>\n </div>\n );\n\n if (props.printable) {\n const printModal = 'print-modal';\n return (\n <Portal className={printModal} testId=\"print-modal\">\n <style media=\"print\">{`body > *:not(.${printModal}) {display: none;}`}</style>\n {Component}\n </Portal>\n );\n }\n\n return Component;\n};\n\nModal.defaultProps = defaultProps;\n\nexport default Modal;\n"],"names":["ModalVariants","ModalSize","defaultProps","uuid","ZIndex","getVariantIcon","variant","React","Icon","IconSize","AlertSignFill","palette","AlertSignStroke","CheckOutline","getIcon","icon","variantIcon","styles","Modal","props","topContent","modalContentRef","dialogRef","useFocusTrap","topContentVisible","useIsVisible","bottomContent","bottomContentVisible","contentIsScrollable","handleKeyboardEvent","e","handleClickEvent","event","overlayRef","disableBodyScroll","enableBodyScroll","imageView","showActions","_a","ariaLabel","ariaLabelledBy","useEffect","overlayElement","dialogClasses","cn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ACF,CACF,EAGF,GAAIA,EAAM,UAAW,CACnB,MAAMiC,EAAa,cACnB,OACG7C,EAAA,cAAA8C,EAAA,CAAO,UAAWD,EAAY,OAAO,aAAA,EACnC7C,EAAA,cAAA,QAAA,CAAM,MAAM,OAAA,EAAS,iBAAiB6C,qBAA+B,EACrEN,CACH,CAEJ,CAEO,OAAAA,CACT,EAEA5B,EAAM,aAAehB"}
@@ -10,7 +10,8 @@ export declare enum FormExampleVariants {
10
10
  radiobutton = "radiobutton",
11
11
  textarea = "textarea",
12
12
  input = "input",
13
- select = "select"
13
+ select = "select",
14
+ date = "date"
14
15
  }
15
16
  export declare const FormExample: (props: FormExampleProps) => JSX.Element;
16
17
  export default FormExample;
@@ -1 +1 @@
1
- {"version":3,"file":"FormExample.d.ts","sourceRoot":"","sources":["../../../src/components/FormExample/FormExample.tsx"],"names":[],"mappings":";AASA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAO9C,UAAU,gBAAgB;IACxB,WAAW,EAAE,mBAAmB,CAAC;IACjC,OAAO,CAAC,EAAE,MAAM,OAAO,WAAW,CAAC;CACpC;AAED,oBAAY,mBAAmB;IAC7B,SAAS,cAAc;IACvB,QAAQ,aAAa;IACrB,WAAW,gBAAgB;IAC3B,QAAQ,aAAa;IACrB,KAAK,UAAU;IACf,MAAM,WAAW;CAClB;AAED,eAAO,MAAM,WAAW,UAAW,gBAAgB,KAAG,WAmKrD,CAAC;AAEF,eAAe,WAAW,CAAC"}
1
+ {"version":3,"file":"FormExample.d.ts","sourceRoot":"","sources":["../../../src/components/FormExample/FormExample.tsx"],"names":[],"mappings":";AASA,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAS9C,UAAU,gBAAgB;IACxB,WAAW,EAAE,mBAAmB,CAAC;IACjC,OAAO,CAAC,EAAE,MAAM,OAAO,WAAW,CAAC;CACpC;AAED,oBAAY,mBAAmB;IAC7B,SAAS,cAAc;IACvB,QAAQ,aAAa;IACrB,WAAW,gBAAgB;IAC3B,QAAQ,aAAa;IACrB,KAAK,UAAU;IACf,MAAM,WAAW;IACjB,IAAI,SAAS;CACd;AAED,eAAO,MAAM,WAAW,UAAW,gBAAgB,KAAG,WAyQrD,CAAC;AAEF,eAAe,WAAW,CAAC"}
@@ -1 +1 @@
1
- {"props":{"exampleType":{"defaultValue":null,"description":"","name":"exampleType","parent":{"fileName":"src/components/FormExample/FormExample.tsx","name":"FormExampleProps"},"declarations":[{"fileName":"src/components/FormExample/FormExample.tsx","name":"FormExampleProps"}],"required":true,"type":{"name":"enum","raw":"FormExampleVariants","value":[{"value":"\"formgroup\"","description":"","fullComment":"","tags":{}},{"value":"\"checkbox\"","description":"","fullComment":"","tags":{}},{"value":"\"radiobutton\"","description":"","fullComment":"","tags":{}},{"value":"\"textarea\"","description":"","fullComment":"","tags":{}},{"value":"\"input\"","description":"","fullComment":"","tags":{}},{"value":"\"select\"","description":"","fullComment":"","tags":{}}]}},"variant":{"defaultValue":null,"description":"","name":"variant","parent":{"fileName":"src/components/FormExample/FormExample.tsx","name":"FormExampleProps"},"declarations":[{"fileName":"src/components/FormExample/FormExample.tsx","name":"FormExampleProps"}],"required":false,"type":{"name":"enum","raw":"\"normal\" | \"bigform\"","value":[{"value":"\"normal\""},{"value":"\"bigform\""}]}}}}
1
+ {"props":{"exampleType":{"defaultValue":null,"description":"","name":"exampleType","parent":{"fileName":"src/components/FormExample/FormExample.tsx","name":"FormExampleProps"},"declarations":[{"fileName":"src/components/FormExample/FormExample.tsx","name":"FormExampleProps"}],"required":true,"type":{"name":"enum","raw":"FormExampleVariants","value":[{"value":"\"formgroup\"","description":"","fullComment":"","tags":{}},{"value":"\"checkbox\"","description":"","fullComment":"","tags":{}},{"value":"\"radiobutton\"","description":"","fullComment":"","tags":{}},{"value":"\"textarea\"","description":"","fullComment":"","tags":{}},{"value":"\"input\"","description":"","fullComment":"","tags":{}},{"value":"\"select\"","description":"","fullComment":"","tags":{}},{"value":"\"date\"","description":"","fullComment":"","tags":{}}]}},"variant":{"defaultValue":null,"description":"","name":"variant","parent":{"fileName":"src/components/FormExample/FormExample.tsx","name":"FormExampleProps"},"declarations":[{"fileName":"src/components/FormExample/FormExample.tsx","name":"FormExampleProps"}],"required":false,"type":{"name":"enum","raw":"\"normal\" | \"bigform\"","value":[{"value":"\"normal\""},{"value":"\"bigform\""}]}}}}
@@ -1,12 +1,12 @@
1
- import v from"react";import{V as dt}from"../../Validation.js";import{F as Z}from"../../FormGroup.js";import{C as J}from"../../Checkbox.js";import{B as yt}from"../../Button.js";import{R as ye}from"../../RadioButton.js";import{T as Be}from"../../Textarea.js";import{I as Ue}from"../../Input.js";import qe from"../Icons/Hospital.js";import{F as gt,a as ht}from"../../FormLayout.js";import{isTest as mt}from"../../utils/environment.js";import{S as Ne}from"../../Select.js";import"classnames";import"../Validation/styles.module.scss";import"../../constants.js";import"../FormGroup/styles.module.scss";import"../../Title.js";import"../Title/styles.module.scss";import"../../ErrorWrapper.js";import"../ErrorWrapper/styles.module.scss";import"../../uuid.js";import"../Icons/Check.js";import"../Icons/Icon.js";import"../../hooks/useUuid.js";import"../../theme/currys/color.js";import"../../theme/index.js";import"../../theme/palette.js";import"../../theme/spacers.js";import"../../theme/grid.js";import"../Checkbox/styles.module.scss";import"../../hooks/useHover.js";import"../../hooks/useIcons.js";import"../../hooks/useBreakpoint.js";import"../Button/styles.module.scss";import"../Icons/ArrowRight.js";import"../../hooks/useSize.js";import"../../utils/debounce.js";import"../RadioButton/styles.module.scss";import"../Textarea/styles.module.scss";import"../Input/styles.module.scss";import"../FormLayout/styles.module.scss";import"../Select/styles.module.scss";import"../Icons/ChevronDown.js";var le=e=>e.type==="checkbox",te=e=>e instanceof Date,T=e=>e==null;const Qe=e=>typeof e=="object";var D=e=>!T(e)&&!Array.isArray(e)&&Qe(e)&&!te(e),vt=e=>D(e)&&e.target?le(e.target)?e.target.checked:e.target.value:e,bt=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,xt=(e,s)=>e.has(bt(s)),ae=e=>Array.isArray(e)?e.filter(Boolean):[],F=e=>e===void 0,d=(e,s,t)=>{if(!s||!D(e))return t;const l=ae(s.split(/[,[\].]+?/)).reduce((i,a)=>T(i)?i:i[a],e);return F(l)||l===e?F(e[s])?t:e[s]:l};const Pe={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},H={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},G={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"};v.createContext(null);var kt=(e,s,t,l=!0)=>{const i={defaultValues:s._defaultValues};for(const a in e)Object.defineProperty(i,a,{get:()=>{const g=a;return s._proxyFormState[g]!==H.all&&(s._proxyFormState[g]=!l||H.all),t&&(t[g]=!0),e[g]}});return i},B=e=>D(e)&&!Object.keys(e).length,pt=(e,s,t)=>{const{name:l,...i}=e;return B(i)||Object.keys(i).length>=Object.keys(s).length||Object.keys(i).find(a=>s[a]===(!t||H.all))},Ae=e=>Array.isArray(e)?e:[e];function At(e){const s=v.useRef(e);s.current=e,v.useEffect(()=>{const t=!e.disabled&&s.current.subject.subscribe({next:s.current.callback});return()=>{t&&t.unsubscribe()}},[e.disabled])}var W=e=>typeof e=="string",Et=(e,s,t,l)=>{const i=Array.isArray(e);return W(e)?(l&&s.watch.add(e),d(t,e)):i?e.map(a=>(l&&s.watch.add(a),d(t,a))):(l&&(s.watchAll=!0),t)},he=e=>typeof e=="function",Xe=e=>{for(const s in e)if(he(e[s]))return!0;return!1},_t=(e,s,t,l,i)=>s?{...t[e],types:{...t[e]&&t[e].types?t[e].types:{},[l]:i||!0}}:{},Ce=e=>/^\w*$/.test(e),Ye=e=>ae(e.replace(/["|']|\]/g,"").split(/\.|\[/));function A(e,s,t){let l=-1;const i=Ce(s)?[s]:Ye(s),a=i.length,g=a-1;for(;++l<a;){const h=i[l];let E=t;if(l!==g){const S=e[h];E=D(S)||Array.isArray(S)?S:isNaN(+i[l+1])?{}:[]}e[h]=E,e=e[h]}return e}const Se=(e,s,t)=>{for(const l of t||Object.keys(e)){const i=d(e,l);if(i){const{_f:a,...g}=i;if(a&&s(a.name)){if(a.ref.focus){a.ref.focus();break}else if(a.refs&&a.refs[0].focus){a.refs[0].focus();break}}else D(g)&&Se(g,s)}}};var He=(e,s,t)=>!t&&(s.watchAll||s.watch.has(e)||[...s.watch].some(l=>e.startsWith(l)&&/^\.\w+/.test(e.slice(l.length)))),wt=(e,s,t)=>{const l=ae(d(e,t));return A(l,"root",s[t]),A(e,t,l),e},oe=e=>typeof e=="boolean",Oe=e=>e.type==="file",ge=e=>W(e)||v.isValidElement(e),Te=e=>e.type==="radio",me=e=>e instanceof RegExp;const We={value:!1,isValid:!1},$e={value:!0,isValid:!0};var Ze=e=>{if(Array.isArray(e)){if(e.length>1){const s=e.filter(t=>t&&t.checked&&!t.disabled).map(t=>t.value);return{value:s,isValid:!!s.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!F(e[0].attributes.value)?F(e[0].value)||e[0].value===""?$e:{value:e[0].value,isValid:!0}:$e:We}return We};const Ge={isValid:!1,value:null};var et=e=>Array.isArray(e)?e.reduce((s,t)=>t&&t.checked&&!t.disabled?{isValid:!0,value:t.value}:s,Ge):Ge;function Ke(e,s,t="validate"){if(ge(e)||Array.isArray(e)&&e.every(ge)||oe(e)&&!e)return{type:t,message:ge(e)?e:"",ref:s}}var ee=e=>D(e)&&!me(e)?e:{value:e,message:""},je=async(e,s,t,l,i)=>{const{ref:a,refs:g,required:h,maxLength:E,minLength:S,min:R,max:p,pattern:m,validate:$,name:L,valueAsNumber:K,mount:se,disabled:I}=e._f;if(!se||I)return{};const U=g?g[0]:a,q=b=>{l&&W(b)&&(U.setCustomValidity(b),U.reportValidity())},k={},j=Te(a),ue=le(a),z=j||ue,X=(K||Oe(a))&&!a.value||s===""||Array.isArray(s)&&!s.length,N=_t.bind(null,L,t,k),ce=(b,x,w,V=G.maxLength,P=G.minLength)=>{const M=b?x:w;k[L]={type:b?V:P,message:M,ref:a,...N(b?V:P,M)}};if(i?!Array.isArray(s)||!s.length:h&&(!z&&(X||T(s))||oe(s)&&!s||ue&&!Ze(g).isValid||j&&!et(g).isValid)){const{value:b,message:x}=ge(h)?{value:!!h,message:h}:ee(h);if(b&&(k[L]={type:G.required,message:x,ref:U,...N(G.required,x)},!t))return q(x),k}if(!X&&(!T(R)||!T(p))){let b,x;const w=ee(p),V=ee(R);if(!T(s)&&!isNaN(s)){const P=a.valueAsNumber||s&&+s;T(w.value)||(b=P>w.value),T(V.value)||(x=P<V.value)}else{const P=a.valueAsDate||new Date(s),M=fe=>new Date(new Date().toDateString()+" "+fe),ie=a.type=="time",Y=a.type=="week";W(w.value)&&s&&(b=ie?M(s)>M(w.value):Y?s>w.value:P>new Date(w.value)),W(V.value)&&s&&(x=ie?M(s)<M(V.value):Y?s<V.value:P<new Date(V.value))}if((b||x)&&(ce(!!b,w.message,V.message,G.max,G.min),!t))return q(k[L].message),k}if((E||S)&&!X&&(W(s)||i&&Array.isArray(s))){const b=ee(E),x=ee(S),w=!T(b.value)&&s.length>b.value,V=!T(x.value)&&s.length<x.value;if((w||V)&&(ce(w,b.message,x.message),!t))return q(k[L].message),k}if(m&&!X&&W(s)){const{value:b,message:x}=ee(m);if(me(b)&&!s.match(b)&&(k[L]={type:G.pattern,message:x,ref:a,...N(G.pattern,x)},!t))return q(x),k}if($){if(he($)){const b=await $(s),x=Ke(b,U);if(x&&(k[L]={...x,...N(G.validate,x.message)},!t))return q(x.message),k}else if(D($)){let b={};for(const x in $){if(!B(b)&&!t)break;const w=Ke(await $[x](s),U,x);w&&(b={...w,...N(x,w.message)},q(w.message),t&&(k[L]=b))}if(!B(b)&&(k[L]={ref:U,...b},!t))return k}}return q(!0),k},Ft=e=>{const s=e.constructor&&e.constructor.prototype;return D(s)&&s.hasOwnProperty("isPrototypeOf")},De=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Q(e){let s;const t=Array.isArray(e);if(e instanceof Date)s=new Date(e);else if(e instanceof Set)s=new Set(e);else if(!(De&&(e instanceof Blob||e instanceof FileList))&&(t||D(e)))if(s=t?[]:{},!Array.isArray(e)&&!Ft(e))s=e;else for(const l in e)s[l]=Q(e[l]);else return e;return s}var ze=e=>({isOnSubmit:!e||e===H.onSubmit,isOnBlur:e===H.onBlur,isOnChange:e===H.onChange,isOnAll:e===H.all,isOnTouch:e===H.onTouched});function St(e,s){const t=s.slice(0,-1).length;let l=0;for(;l<t;)e=F(e)?l++:e[s[l++]];return e}function Dt(e){for(const s in e)if(!F(e[s]))return!1;return!0}function O(e,s){const t=Ce(s)?[s]:Ye(s),l=t.length==1?e:St(e,t),i=t[t.length-1];let a;l&&delete l[i];for(let g=0;g<t.slice(0,-1).length;g++){let h=-1,E;const S=t.slice(0,-(g+1)),R=S.length-1;for(g>0&&(a=e);++h<S.length;){const p=S[h];E=E?E[p]:e[p],R===h&&(D(E)&&B(E)||Array.isArray(E)&&Dt(E))&&(a?delete a[p]:delete e[p]),a=E}}return e}function Ee(){let e=[];return{get observers(){return e},next:i=>{for(const a of e)a.next(i)},subscribe:i=>(e.push(i),{unsubscribe:()=>{e=e.filter(a=>a!==i)}}),unsubscribe:()=>{e=[]}}}var ve=e=>T(e)||!Qe(e);function re(e,s){if(ve(e)||ve(s))return e===s;if(te(e)&&te(s))return e.getTime()===s.getTime();const t=Object.keys(e),l=Object.keys(s);if(t.length!==l.length)return!1;for(const i of t){const a=e[i];if(!l.includes(i))return!1;if(i!=="ref"){const g=s[i];if(te(a)&&te(g)||D(a)&&D(g)||Array.isArray(a)&&Array.isArray(g)?!re(a,g):a!==g)return!1}}return!0}var Ve=e=>{const s=e?e.ownerDocument:0,t=s&&s.defaultView?s.defaultView.HTMLElement:HTMLElement;return e instanceof t},tt=e=>e.type==="select-multiple",Vt=e=>Te(e)||le(e),_e=e=>Ve(e)&&e.isConnected;function be(e,s={}){const t=Array.isArray(e);if(D(e)||t)for(const l in e)Array.isArray(e[l])||D(e[l])&&!Xe(e[l])?(s[l]=Array.isArray(e[l])?[]:{},be(e[l],s[l])):T(e[l])||(s[l]=!0);return s}function rt(e,s,t){const l=Array.isArray(e);if(D(e)||l)for(const i in e)Array.isArray(e[i])||D(e[i])&&!Xe(e[i])?F(s)||ve(t[i])?t[i]=Array.isArray(e[i])?be(e[i],[]):{...be(e[i])}:rt(e[i],T(s)?{}:s[i],t[i]):re(e[i],s[i])?delete t[i]:t[i]=!0;return t}var we=(e,s)=>rt(e,s,be(s)),st=(e,{valueAsNumber:s,valueAsDate:t,setValueAs:l})=>F(e)?e:s?e===""?NaN:e&&+e:t&&W(e)?new Date(e):l?l(e):e;function Fe(e){const s=e.ref;if(!(e.refs?e.refs.every(t=>t.disabled):s.disabled))return Oe(s)?s.files:Te(s)?et(e.refs).value:tt(s)?[...s.selectedOptions].map(({value:t})=>t):le(s)?Ze(e.refs).value:st(F(s.value)?e.ref.value:s.value,e)}var Ct=(e,s,t,l)=>{const i={};for(const a of e){const g=d(s,a);g&&A(i,a,g._f)}return{criteriaMode:t,names:[...e],fields:i,shouldUseNativeValidation:l}},ne=e=>F(e)?void 0:me(e)?e.source:D(e)?me(e.value)?e.value.source:e.value:e,Ot=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function Je(e,s,t){const l=d(e,t);if(l||Ce(t))return{error:l,name:t};const i=t.split(".");for(;i.length;){const a=i.join("."),g=d(s,a),h=d(e,a);if(g&&!Array.isArray(g)&&t!==a)return{name:t};if(h&&h.type)return{name:a,error:h};i.pop()}return{name:t}}var Tt=(e,s,t,l,i)=>i.isOnAll?!1:!t&&i.isOnTouch?!(s||e):(t?l.isOnBlur:i.isOnBlur)?!e:(t?l.isOnChange:i.isOnChange)?e:!0,Rt=(e,s)=>!ae(d(e,s)).length&&O(e,s);const Lt={mode:H.onSubmit,reValidateMode:H.onChange,shouldFocusError:!0};function It(e={}){let s={...Lt,...e},t={submitCount:0,isDirty:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{}},l={},i=Q(s.defaultValues)||{},a=s.shouldUnregister?{}:Q(i),g={action:!1,mount:!1,watch:!1},h={mount:new Set,unMount:new Set,array:new Set,watch:new Set},E,S=0,R={};const p={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},m={watch:Ee(),array:Ee(),state:Ee()},$=ze(s.mode),L=ze(s.reValidateMode),K=s.criteriaMode===H.all,se=r=>n=>{clearTimeout(S),S=window.setTimeout(r,n)},I=async()=>{let r=!1;return p.isValid&&(r=s.resolver?B((await z()).errors):await N(l,!0),r!==t.isValid&&(t.isValid=r,m.state.next({isValid:r}))),r},U=(r,n=[],o,c,f=!0,u=!0)=>{if(c&&o){if(g.action=!0,u&&Array.isArray(d(l,r))){const y=o(d(l,r),c.argA,c.argB);f&&A(l,r,y)}if(p.errors&&u&&Array.isArray(d(t.errors,r))){const y=o(d(t.errors,r),c.argA,c.argB);f&&A(t.errors,r,y),Rt(t.errors,r)}if(p.touchedFields&&u&&Array.isArray(d(t.touchedFields,r))){const y=o(d(t.touchedFields,r),c.argA,c.argB);f&&A(t.touchedFields,r,y)}p.dirtyFields&&(t.dirtyFields=we(i,a)),m.state.next({isDirty:b(r,n),dirtyFields:t.dirtyFields,errors:t.errors,isValid:t.isValid})}else A(a,r,n)},q=(r,n)=>{A(t.errors,r,n),m.state.next({errors:t.errors})},k=(r,n,o,c)=>{const f=d(l,r);if(f){const u=d(a,r,F(o)?d(i,r):o);F(u)||c&&c.defaultChecked||n?A(a,r,n?u:Fe(f._f)):V(r,u),g.mount&&I()}},j=(r,n,o,c,f)=>{let u=!1;const y={name:r},_=d(t.touchedFields,r);if(p.isDirty){const C=t.isDirty;t.isDirty=y.isDirty=b(),u=C!==y.isDirty}if(p.dirtyFields&&(!o||c)){const C=d(t.dirtyFields,r);re(d(i,r),n)?O(t.dirtyFields,r):A(t.dirtyFields,r,!0),y.dirtyFields=t.dirtyFields,u=u||C!==d(t.dirtyFields,r)}return o&&!_&&(A(t.touchedFields,r,o),y.touchedFields=t.touchedFields,u=u||p.touchedFields&&_!==o),u&&f&&m.state.next(y),u?y:{}},ue=(r,n,o,c)=>{const f=d(t.errors,r),u=p.isValid&&oe(n)&&t.isValid!==n;if(e.delayError&&o?(E=se(()=>q(r,o)),E(e.delayError)):(clearTimeout(S),E=null,o?A(t.errors,r,o):O(t.errors,r)),(o?!re(f,o):f)||!B(c)||u){const y={...c,...u&&oe(n)?{isValid:n}:{},errors:t.errors,name:r};t={...t,...y},m.state.next(y)}R[r]--,p.isValidating&&!Object.values(R).some(y=>y)&&(m.state.next({isValidating:!1}),R={})},z=async r=>s.resolver?await s.resolver({...a},s.context,Ct(r||h.mount,l,s.criteriaMode,s.shouldUseNativeValidation)):{},X=async r=>{const{errors:n}=await z();if(r)for(const o of r){const c=d(n,o);c?A(t.errors,o,c):O(t.errors,o)}else t.errors=n;return n},N=async(r,n,o={valid:!0})=>{for(const c in r){const f=r[c];if(f){const{_f:u,...y}=f;if(u){const _=h.array.has(u.name),C=await je(f,d(a,u.name),K,s.shouldUseNativeValidation,_);if(C[u.name]&&(o.valid=!1,n))break;!n&&(d(C,u.name)?_?wt(t.errors,C,u.name):A(t.errors,u.name,C[u.name]):O(t.errors,u.name))}y&&await N(y,n,o)}}return o.valid},ce=()=>{for(const r of h.unMount){const n=d(l,r);n&&(n._f.refs?n._f.refs.every(o=>!_e(o)):!_e(n._f.ref))&&xe(r)}h.unMount=new Set},b=(r,n)=>(r&&n&&A(a,r,n),!re(fe(),i)),x=(r,n,o)=>{const c={...g.mount?a:F(n)?i:W(r)?{[r]:n}:n};return Et(r,h,c,o)},w=r=>ae(d(g.mount?a:i,r,e.shouldUnregister?d(i,r,[]):[])),V=(r,n,o={})=>{const c=d(l,r);let f=n;if(c){const u=c._f;u&&(!u.disabled&&A(a,r,st(n,u)),f=De&&Ve(u.ref)&&T(n)?"":n,tt(u.ref)?[...u.ref.options].forEach(y=>y.selected=f.includes(y.value)):u.refs?le(u.ref)?u.refs.length>1?u.refs.forEach(y=>(!y.defaultChecked||!y.disabled)&&(y.checked=Array.isArray(f)?!!f.find(_=>_===y.value):f===y.value)):u.refs[0]&&(u.refs[0].checked=!!f):u.refs.forEach(y=>y.checked=y.value===f):Oe(u.ref)?u.ref.value="":(u.ref.value=f,u.ref.type||m.watch.next({name:r})))}(o.shouldDirty||o.shouldTouch)&&j(r,f,o.shouldTouch,o.shouldDirty,!0),o.shouldValidate&&Y(r)},P=(r,n,o)=>{for(const c in n){const f=n[c],u=`${r}.${c}`,y=d(l,u);(h.array.has(r)||!ve(f)||y&&!y._f)&&!te(f)?P(u,f,o):V(u,f,o)}},M=(r,n,o={})=>{const c=d(l,r),f=h.array.has(r),u=Q(n);A(a,r,u),f?(m.array.next({name:r,values:a}),(p.isDirty||p.dirtyFields)&&o.shouldDirty&&(t.dirtyFields=we(i,a),m.state.next({name:r,dirtyFields:t.dirtyFields,isDirty:b(r,u)}))):c&&!c._f&&!T(u)?P(r,u,o):V(r,u,o),He(r,h)&&m.state.next({}),m.watch.next({name:r})},ie=async r=>{const n=r.target;let o=n.name;const c=d(l,o);if(c){let f,u;const y=n.type?Fe(c._f):vt(r),_=r.type===Pe.BLUR||r.type===Pe.FOCUS_OUT,C=!Ot(c._f)&&!s.resolver&&!d(t.errors,o)&&!c._f.deps||Tt(_,d(t.touchedFields,o),t.isSubmitted,L,$),de=He(o,h,_);A(a,o,y),_?(c._f.onBlur&&c._f.onBlur(r),E&&E(0)):c._f.onChange&&c._f.onChange(r);const pe=j(o,y,_,!1),ct=!B(pe)||de;if(!_&&m.watch.next({name:o,type:r.type}),C)return p.isValid&&I(),ct&&m.state.next({name:o,...de?{}:pe});if(!_&&de&&m.state.next({}),R[o]=R[o]?R[o]+1:1,m.state.next({isValidating:!0}),s.resolver){const{errors:Ie}=await z([o]),ft=Je(t.errors,l,o),Me=Je(Ie,l,ft.name||o);f=Me.error,o=Me.name,u=B(Ie)}else f=(await je(c,d(a,o),K,s.shouldUseNativeValidation))[o],I();c._f.deps&&Y(c._f.deps),ue(o,u,f,pe)}},Y=async(r,n={})=>{let o,c;const f=Ae(r);if(m.state.next({isValidating:!0}),s.resolver){const u=await X(F(r)?r:f);o=B(u),c=r?!f.some(y=>d(u,y)):o}else r?(c=(await Promise.all(f.map(async u=>{const y=d(l,u);return await N(y&&y._f?{[u]:y}:y)}))).every(Boolean),!(!c&&!t.isValid)&&I()):c=o=await N(l);return m.state.next({...!W(r)||p.isValid&&o!==t.isValid?{}:{name:r},...s.resolver||!r?{isValid:o}:{},errors:t.errors,isValidating:!1}),n.shouldFocus&&!c&&Se(l,u=>u&&d(t.errors,u),r?f:h.mount),c},fe=r=>{const n={...i,...g.mount?a:{}};return F(r)?n:W(r)?d(n,r):r.map(o=>d(n,o))},Re=(r,n)=>({invalid:!!d((n||t).errors,r),isDirty:!!d((n||t).dirtyFields,r),isTouched:!!d((n||t).touchedFields,r),error:d((n||t).errors,r)}),it=r=>{r?Ae(r).forEach(n=>O(t.errors,n)):t.errors={},m.state.next({errors:t.errors})},nt=(r,n,o)=>{const c=(d(l,r,{_f:{}})._f||{}).ref;A(t.errors,r,{...n,ref:c}),m.state.next({name:r,errors:t.errors,isValid:!1}),o&&o.shouldFocus&&c&&c.focus&&c.focus()},ot=(r,n)=>he(r)?m.watch.subscribe({next:o=>r(x(void 0,n),o)}):x(r,n,!0),xe=(r,n={})=>{for(const o of r?Ae(r):h.mount)h.mount.delete(o),h.array.delete(o),d(l,o)&&(n.keepValue||(O(l,o),O(a,o)),!n.keepError&&O(t.errors,o),!n.keepDirty&&O(t.dirtyFields,o),!n.keepTouched&&O(t.touchedFields,o),!s.shouldUnregister&&!n.keepDefaultValue&&O(i,o));m.watch.next({}),m.state.next({...t,...n.keepDirty?{isDirty:b()}:{}}),!n.keepIsValid&&I()},ke=(r,n={})=>{let o=d(l,r);const c=oe(n.disabled);return A(l,r,{...o||{},_f:{...o&&o._f?o._f:{ref:{name:r}},name:r,mount:!0,...n}}),h.mount.add(r),o?c&&A(a,r,n.disabled?void 0:d(a,r,Fe(o._f))):k(r,!0,n.value),{...c?{disabled:n.disabled}:{},...s.shouldUseNativeValidation?{required:!!n.required,min:ne(n.min),max:ne(n.max),minLength:ne(n.minLength),maxLength:ne(n.maxLength),pattern:ne(n.pattern)}:{},name:r,onChange:ie,onBlur:ie,ref:f=>{if(f){ke(r,n),o=d(l,r);const u=F(f.value)&&f.querySelectorAll&&f.querySelectorAll("input,select,textarea")[0]||f,y=Vt(u),_=o._f.refs||[];if(y?_.find(C=>C===u):u===o._f.ref)return;A(l,r,{_f:{...o._f,...y?{refs:[..._.filter(_e),u,...Array.isArray(d(i,r))?[{}]:[]],ref:{type:u.type,name:r}}:{ref:u}}}),k(r,!1,void 0,u)}else o=d(l,r,{}),o._f&&(o._f.mount=!1),(s.shouldUnregister||n.shouldUnregister)&&!(xt(h.array,r)&&g.action)&&h.unMount.add(r)}}},Le=()=>s.shouldFocusError&&Se(l,r=>r&&d(t.errors,r),h.mount),lt=(r,n)=>async o=>{o&&(o.preventDefault&&o.preventDefault(),o.persist&&o.persist());let c=!0,f=Q(a);m.state.next({isSubmitting:!0});try{if(s.resolver){const{errors:u,values:y}=await z();t.errors=u,f=y}else await N(l);B(t.errors)?(m.state.next({errors:{},isSubmitting:!0}),await r(f,o)):(n&&await n({...t.errors},o),Le())}catch(u){throw c=!1,u}finally{t.isSubmitted=!0,m.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:B(t.errors)&&c,submitCount:t.submitCount+1,errors:t.errors})}},at=(r,n={})=>{d(l,r)&&(F(n.defaultValue)?M(r,d(i,r)):(M(r,n.defaultValue),A(i,r,n.defaultValue)),n.keepTouched||O(t.touchedFields,r),n.keepDirty||(O(t.dirtyFields,r),t.isDirty=n.defaultValue?b(r,d(i,r)):b()),n.keepError||(O(t.errors,r),p.isValid&&I()),m.state.next({...t}))},ut=(r,n={})=>{const o=r||i,c=Q(o),f=r&&!B(r)?c:i;if(n.keepDefaultValues||(i=o),!n.keepValues){if(n.keepDirtyValues)for(const u of h.mount)d(t.dirtyFields,u)?A(f,u,d(a,u)):M(u,d(f,u));else{if(De&&F(r))for(const u of h.mount){const y=d(l,u);if(y&&y._f){const _=Array.isArray(y._f.refs)?y._f.refs[0]:y._f.ref;if(Ve(_)){const C=_.closest("form");if(C){C.reset();break}}}}l={}}a=e.shouldUnregister?n.keepDefaultValues?Q(i):{}:c,m.array.next({values:f}),m.watch.next({values:f})}h={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},g.mount=!p.isValid||!!n.keepIsValid,g.watch=!!e.shouldUnregister,m.state.next({submitCount:n.keepSubmitCount?t.submitCount:0,isDirty:n.keepDirty||n.keepDirtyValues?t.isDirty:!!(n.keepDefaultValues&&!re(r,i)),isSubmitted:n.keepIsSubmitted?t.isSubmitted:!1,dirtyFields:n.keepDirty||n.keepDirtyValues?t.dirtyFields:n.keepDefaultValues&&r?we(i,r):{},touchedFields:n.keepTouched?t.touchedFields:{},errors:n.keepErrors?t.errors:{},isSubmitting:!1,isSubmitSuccessful:!1})};return{control:{register:ke,unregister:xe,getFieldState:Re,_executeSchema:z,_focusError:Le,_getWatch:x,_getDirty:b,_updateValid:I,_removeUnmounted:ce,_updateFieldArray:U,_getFieldArray:w,_subjects:m,_proxyFormState:p,get _fields(){return l},get _formValues(){return a},get _stateFlags(){return g},set _stateFlags(r){g=r},get _defaultValues(){return i},get _names(){return h},set _names(r){h=r},get _formState(){return t},set _formState(r){t=r},get _options(){return s},set _options(r){s={...s,...r}}},trigger:Y,register:ke,handleSubmit:lt,watch:ot,setValue:M,getValues:fe,reset:(r,n)=>ut(he(r)?r(a):r,n),resetField:at,clearErrors:it,unregister:xe,setError:nt,setFocus:(r,n={})=>{const o=d(l,r),c=o&&o._f;if(c){const f=c.refs?c.refs[0]:c.ref;f.focus&&(f.focus(),n.shouldSelect&&f.select())}},getFieldState:Re}}function Mt(e={}){const s=v.useRef(),[t,l]=v.useState({isDirty:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},defaultValues:e.defaultValues});s.current||(s.current={...It(e),formState:t});const i=s.current.control;return i._options=e,At({subject:i._subjects.state,callback:v.useCallback(a=>{pt(a,i._proxyFormState,!0)&&(i._formState={...i._formState,...a},l({...i._formState}))},[i])}),v.useEffect(()=>{i._stateFlags.mount||(i._proxyFormState.isValid&&i._updateValid(),i._stateFlags.mount=!0),i._stateFlags.watch&&(i._stateFlags.watch=!1,i._subjects.state.next({})),i._removeUnmounted()}),v.useEffect(()=>{t.submitCount&&i._focusError()},[i,t.submitCount]),s.current.formState=kt(t,i),s.current}var Bt=(e=>(e.formgroup="formgroup",e.checkbox="checkbox",e.radiobutton="radiobutton",e.textarea="textarea",e.input="input",e.select="select",e))(Bt||{});const Vr=e=>{const{exampleType:s="formgroup"}=e,{register:t,handleSubmit:l,formState:{errors:i}}=Mt(),a="field1",g="field2",h="field3",E="field4",S="field5",R="field6",p=i.field1||i.field2||i.field3||i.field4||i.field5||i.field6,m="Du m\xE5 velge et alternativ",$="Du m\xE5 velge to alternativ",L="Det kan ikke legges inn mer enn 40 tegn",K="Du m\xE5 skrive noe her",se='Du m\xE5 velge "Option 2"',I=k=>k.length>=2||$,U=k=>k.toString()==="Option 2"||se,q=()=>{if(s==="formgroup"){const k=[v.createElement(J,{key:0,inputId:"checkbox1",label:"Checkbox 1",...t(a,{required:m})}),v.createElement(J,{key:1,inputId:"checkbox2",label:"Checkbox 2",...t(a,{required:m})}),v.createElement(J,{key:2,inputId:"checkbox3",label:"Checkbox 3",...t(a,{required:m})})];return[v.createElement(Z,{key:0,title:"Gruppe tittel",legend:"Velg minst en",error:i.field1?i.field1.message:void 0,variant:e.variant},v.createElement(gt,{maxColumns:ht.two},k.map(j=>j))),v.createElement(Z,{key:1,legend:"Velg minst to",error:i.field2?i.field2.message:void 0,variant:e.variant},v.createElement(J,{inputId:"checkbox4",label:"Checkbox 4",...t(g,{validate:I})}),v.createElement(J,{inputId:"checkbox5",label:"Checkbox 5",...t(g,{validate:I})}),v.createElement(J,{inputId:"checkbox6",label:"Checkbox 6",...t(g,{validate:I})})),v.createElement(Z,{key:2,legend:"Velg en",error:i.field3?i.field3.message:void 0,variant:e.variant},v.createElement(ye,{inputId:"radiobutton1",label:"Radiobutton 1",...t(h,{required:m})}),v.createElement(ye,{inputId:"radiobutton2",label:"Radiobutton 2",...t(h,{required:m})}),v.createElement(ye,{inputId:"radiobutton3",label:"Radiobutton 3",...t(h,{required:m})})),v.createElement(Z,{key:3,error:i.field4?i.field4.message:void 0},v.createElement(Be,{defaultValue:`Dette er en test
1
+ import h from"react";import{V as yt}from"../../Validation.js";import{F as Y}from"../../FormGroup.js";import{C as ee}from"../../Checkbox.js";import{B as mt}from"../../Button.js";import{R as me}from"../../RadioButton.js";import{T as Be}from"../../Textarea.js";import{I as ae}from"../../Input.js";import Ue from"../Icons/Hospital.js";import{F as gt,a as ht}from"../../FormLayout.js";import{isTest as vt}from"../../utils/environment.js";import{S as Pe}from"../../Select.js";import we from"./styles.module.scss";import"classnames";import"../Validation/styles.module.scss";import"../../constants.js";import"../FormGroup/styles.module.scss";import"../../Title.js";import"../Title/styles.module.scss";import"../../ErrorWrapper.js";import"../ErrorWrapper/styles.module.scss";import"../../uuid.js";import"../Icons/Check.js";import"../Icons/Icon.js";import"../../hooks/useUuid.js";import"../../theme/currys/color.js";import"../../theme/index.js";import"../../theme/palette.js";import"../../theme/spacers.js";import"../../theme/grid.js";import"../Checkbox/styles.module.scss";import"../../hooks/useHover.js";import"../../hooks/useIcons.js";import"../../hooks/useBreakpoint.js";import"../Button/styles.module.scss";import"../Icons/ArrowRight.js";import"../../hooks/useSize.js";import"../../utils/debounce.js";import"../RadioButton/styles.module.scss";import"../Textarea/styles.module.scss";import"../Input/styles.module.scss";import"../FormLayout/styles.module.scss";import"../Select/styles.module.scss";import"../Icons/ChevronDown.js";var de=e=>e.type==="checkbox",ne=e=>e instanceof Date,N=e=>e==null;const Xe=e=>typeof e=="object";var L=e=>!N(e)&&!Array.isArray(e)&&Xe(e)&&!ne(e),bt=e=>L(e)&&e.target?de(e.target)?e.target.checked:e.target.value:e,xt=e=>e.substring(0,e.search(/\.\d+(\.|$)/))||e,kt=(e,i)=>e.has(xt(i)),fe=e=>Array.isArray(e)?e.filter(Boolean):[],T=e=>e===void 0,f=(e,i,t)=>{if(!i||!L(e))return t;const l=fe(i.split(/[,[\].]+?/)).reduce((s,a)=>N(s)?s:s[a],e);return T(l)||l===e?T(e[i])?t:e[i]:l};const He={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},$={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},j={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"};h.createContext(null);var pt=(e,i,t,l=!0)=>{const s={defaultValues:i._defaultValues};for(const a in e)Object.defineProperty(s,a,{get:()=>{const m=a;return i._proxyFormState[m]!==$.all&&(i._proxyFormState[m]=!l||$.all),t&&(t[m]=!0),e[m]}});return s},B=e=>L(e)&&!Object.keys(e).length,Et=(e,i,t)=>{const{name:l,...s}=e;return B(s)||Object.keys(s).length>=Object.keys(i).length||Object.keys(s).find(a=>i[a]===(!t||$.all))},Ae=e=>Array.isArray(e)?e:[e];function wt(e){const i=h.useRef(e);i.current=e,h.useEffect(()=>{const t=!e.disabled&&i.current.subject.subscribe({next:i.current.callback});return()=>{t&&t.unsubscribe()}},[e.disabled])}var W=e=>typeof e=="string",At=(e,i,t,l)=>{const s=Array.isArray(e);return W(e)?(l&&i.watch.add(e),f(t,e)):s?e.map(a=>(l&&i.watch.add(a),f(t,a))):(l&&(i.watchAll=!0),t)},he=e=>typeof e=="function",Ye=e=>{for(const i in e)if(he(e[i]))return!0;return!1},Dt=(e,i,t,l,s)=>i?{...t[e],types:{...t[e]&&t[e].types?t[e].types:{},[l]:s||!0}}:{},Le=e=>/^\w*$/.test(e),Ze=e=>fe(e.replace(/["|']|\]/g,"").split(/\.|\[/));function A(e,i,t){let l=-1;const s=Le(i)?[i]:Ze(i),a=s.length,m=a-1;for(;++l<a;){const g=s[l];let E=t;if(l!==m){const V=e[g];E=L(V)||Array.isArray(V)?V:isNaN(+s[l+1])?{}:[]}e[g]=E,e=e[g]}return e}const Ve=(e,i,t)=>{for(const l of t||Object.keys(e)){const s=f(e,l);if(s){const{_f:a,...m}=s;if(a&&i(a.name)){if(a.ref.focus){a.ref.focus();break}else if(a.refs&&a.refs[0].focus){a.refs[0].focus();break}}else L(m)&&Ve(m,i)}}};var $e=(e,i,t)=>!t&&(i.watchAll||i.watch.has(e)||[...i.watch].some(l=>e.startsWith(l)&&/^\.\w+/.test(e.slice(l.length)))),St=(e,i,t)=>{const l=fe(f(e,t));return A(l,"root",i[t]),A(e,t,l),e},ce=e=>typeof e=="boolean",Oe=e=>e.type==="file",ge=e=>W(e)||h.isValidElement(e),Re=e=>e.type==="radio",ve=e=>e instanceof RegExp;const We={value:!1,isValid:!1},Ge={value:!0,isValid:!0};var et=e=>{if(Array.isArray(e)){if(e.length>1){const i=e.filter(t=>t&&t.checked&&!t.disabled).map(t=>t.value);return{value:i,isValid:!!i.length}}return e[0].checked&&!e[0].disabled?e[0].attributes&&!T(e[0].attributes.value)?T(e[0].value)||e[0].value===""?Ge:{value:e[0].value,isValid:!0}:Ge:We}return We};const Ke={isValid:!1,value:null};var tt=e=>Array.isArray(e)?e.reduce((i,t)=>t&&t.checked&&!t.disabled?{isValid:!0,value:t.value}:i,Ke):Ke;function je(e,i,t="validate"){if(ge(e)||Array.isArray(e)&&e.every(ge)||ce(e)&&!e)return{type:t,message:ge(e)?e:"",ref:i}}var se=e=>L(e)&&!ve(e)?e:{value:e,message:""},ze=async(e,i,t,l,s)=>{const{ref:a,refs:m,required:g,maxLength:E,minLength:V,min:O,max:p,pattern:b,validate:U,name:q,valueAsNumber:re,mount:le,disabled:P}=e._f;if(!le||P)return{};const C=m?m[0]:a,H=v=>{l&&W(v)&&(C.setCustomValidity(v),C.reportValidity())},D={},z=Re(a),ie=de(a),K=z||ie,J=(re||Oe(a))&&!a.value||i===""||Array.isArray(i)&&!i.length,R=Dt.bind(null,q,t,D),Z=(v,x,S,k=j.maxLength,w=j.minLength)=>{const _=v?x:S;D[q]={type:v?k:w,message:_,ref:a,...R(v?k:w,_)}};if(s?!Array.isArray(i)||!i.length:g&&(!K&&(J||N(i))||ce(i)&&!i||ie&&!et(m).isValid||z&&!tt(m).isValid)){const{value:v,message:x}=ge(g)?{value:!!g,message:g}:se(g);if(v&&(D[q]={type:j.required,message:x,ref:C,...R(j.required,x)},!t))return H(x),D}if(!J&&(!N(O)||!N(p))){let v,x;const S=se(p),k=se(O);if(!N(i)&&!isNaN(i)){const w=a.valueAsNumber||i&&+i;N(S.value)||(v=w>S.value),N(k.value)||(x=w<k.value)}else{const w=a.valueAsDate||new Date(i),_=X=>new Date(new Date().toDateString()+" "+X),G=a.type=="time",Q=a.type=="week";W(S.value)&&i&&(v=G?_(i)>_(S.value):Q?i>S.value:w>new Date(S.value)),W(k.value)&&i&&(x=G?_(i)<_(k.value):Q?i<k.value:w<new Date(k.value))}if((v||x)&&(Z(!!v,S.message,k.message,j.max,j.min),!t))return H(D[q].message),D}if((E||V)&&!J&&(W(i)||s&&Array.isArray(i))){const v=se(E),x=se(V),S=!N(v.value)&&i.length>v.value,k=!N(x.value)&&i.length<x.value;if((S||k)&&(Z(S,v.message,x.message),!t))return H(D[q].message),D}if(b&&!J&&W(i)){const{value:v,message:x}=se(b);if(ve(v)&&!i.match(v)&&(D[q]={type:j.pattern,message:x,ref:a,...R(j.pattern,x)},!t))return H(x),D}if(U){if(he(U)){const v=await U(i),x=je(v,C);if(x&&(D[q]={...x,...R(j.validate,x.message)},!t))return H(x.message),D}else if(L(U)){let v={};for(const x in U){if(!B(v)&&!t)break;const S=je(await U[x](i),C,x);S&&(v={...S,...R(x,S.message)},H(S.message),t&&(D[q]=v))}if(!B(v)&&(D[q]={ref:C,...v},!t))return D}}return H(!0),D},_t=e=>{const i=e.constructor&&e.constructor.prototype;return L(i)&&i.hasOwnProperty("isPrototypeOf")},Te=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function te(e){let i;const t=Array.isArray(e);if(e instanceof Date)i=new Date(e);else if(e instanceof Set)i=new Set(e);else if(!(Te&&(e instanceof Blob||e instanceof FileList))&&(t||L(e)))if(i=t?[]:{},!Array.isArray(e)&&!_t(e))i=e;else for(const l in e)i[l]=te(e[l]);else return e;return i}var Je=e=>({isOnSubmit:!e||e===$.onSubmit,isOnBlur:e===$.onBlur,isOnChange:e===$.onChange,isOnAll:e===$.all,isOnTouch:e===$.onTouched});function Ft(e,i){const t=i.slice(0,-1).length;let l=0;for(;l<t;)e=T(e)?l++:e[i[l++]];return e}function Vt(e){for(const i in e)if(!T(e[i]))return!1;return!0}function I(e,i){const t=Le(i)?[i]:Ze(i),l=t.length==1?e:Ft(e,t),s=t[t.length-1];let a;l&&delete l[s];for(let m=0;m<t.slice(0,-1).length;m++){let g=-1,E;const V=t.slice(0,-(m+1)),O=V.length-1;for(m>0&&(a=e);++g<V.length;){const p=V[g];E=E?E[p]:e[p],O===g&&(L(E)&&B(E)||Array.isArray(E)&&Vt(E))&&(a?delete a[p]:delete e[p]),a=E}}return e}function De(){let e=[];return{get observers(){return e},next:s=>{for(const a of e)a.next(s)},subscribe:s=>(e.push(s),{unsubscribe:()=>{e=e.filter(a=>a!==s)}}),unsubscribe:()=>{e=[]}}}var be=e=>N(e)||!Xe(e);function oe(e,i){if(be(e)||be(i))return e===i;if(ne(e)&&ne(i))return e.getTime()===i.getTime();const t=Object.keys(e),l=Object.keys(i);if(t.length!==l.length)return!1;for(const s of t){const a=e[s];if(!l.includes(s))return!1;if(s!=="ref"){const m=i[s];if(ne(a)&&ne(m)||L(a)&&L(m)||Array.isArray(a)&&Array.isArray(m)?!oe(a,m):a!==m)return!1}}return!0}var Ce=e=>{const i=e?e.ownerDocument:0,t=i&&i.defaultView?i.defaultView.HTMLElement:HTMLElement;return e instanceof t},rt=e=>e.type==="select-multiple",Tt=e=>Re(e)||de(e),Se=e=>Ce(e)&&e.isConnected;function xe(e,i={}){const t=Array.isArray(e);if(L(e)||t)for(const l in e)Array.isArray(e[l])||L(e[l])&&!Ye(e[l])?(i[l]=Array.isArray(e[l])?[]:{},xe(e[l],i[l])):N(e[l])||(i[l]=!0);return i}function it(e,i,t){const l=Array.isArray(e);if(L(e)||l)for(const s in e)Array.isArray(e[s])||L(e[s])&&!Ye(e[s])?T(i)||be(t[s])?t[s]=Array.isArray(e[s])?xe(e[s],[]):{...xe(e[s])}:it(e[s],N(i)?{}:i[s],t[s]):oe(e[s],i[s])?delete t[s]:t[s]=!0;return t}var _e=(e,i)=>it(e,i,xe(i)),st=(e,{valueAsNumber:i,valueAsDate:t,setValueAs:l})=>T(e)?e:i?e===""?NaN:e&&+e:t&&W(e)?new Date(e):l?l(e):e;function Fe(e){const i=e.ref;if(!(e.refs?e.refs.every(t=>t.disabled):i.disabled))return Oe(i)?i.files:Re(i)?tt(e.refs).value:rt(i)?[...i.selectedOptions].map(({value:t})=>t):de(i)?et(e.refs).value:st(T(i.value)?e.ref.value:i.value,e)}var Ct=(e,i,t,l)=>{const s={};for(const a of e){const m=f(i,a);m&&A(s,a,m._f)}return{criteriaMode:t,names:[...e],fields:s,shouldUseNativeValidation:l}},ue=e=>T(e)?void 0:ve(e)?e.source:L(e)?ve(e.value)?e.value.source:e.value:e,Lt=e=>e.mount&&(e.required||e.min||e.max||e.maxLength||e.minLength||e.pattern||e.validate);function Qe(e,i,t){const l=f(e,t);if(l||Le(t))return{error:l,name:t};const s=t.split(".");for(;s.length;){const a=s.join("."),m=f(i,a),g=f(e,a);if(m&&!Array.isArray(m)&&t!==a)return{name:t};if(g&&g.type)return{name:a,error:g};s.pop()}return{name:t}}var Ot=(e,i,t,l,s)=>s.isOnAll?!1:!t&&s.isOnTouch?!(i||e):(t?l.isOnBlur:s.isOnBlur)?!e:(t?l.isOnChange:s.isOnChange)?e:!0,Rt=(e,i)=>!fe(f(e,i)).length&&I(e,i);const Mt={mode:$.onSubmit,reValidateMode:$.onChange,shouldFocusError:!0};function It(e={}){let i={...Mt,...e},t={submitCount:0,isDirty:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},errors:{}},l={},s=te(i.defaultValues)||{},a=i.shouldUnregister?{}:te(s),m={action:!1,mount:!1,watch:!1},g={mount:new Set,unMount:new Set,array:new Set,watch:new Set},E,V=0,O={};const p={isDirty:!1,dirtyFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},b={watch:De(),array:De(),state:De()},U=Je(i.mode),q=Je(i.reValidateMode),re=i.criteriaMode===$.all,le=r=>n=>{clearTimeout(V),V=window.setTimeout(r,n)},P=async()=>{let r=!1;return p.isValid&&(r=i.resolver?B((await K()).errors):await R(l,!0),r!==t.isValid&&(t.isValid=r,b.state.next({isValid:r}))),r},C=(r,n=[],o,c,d=!0,u=!0)=>{if(c&&o){if(m.action=!0,u&&Array.isArray(f(l,r))){const y=o(f(l,r),c.argA,c.argB);d&&A(l,r,y)}if(p.errors&&u&&Array.isArray(f(t.errors,r))){const y=o(f(t.errors,r),c.argA,c.argB);d&&A(t.errors,r,y),Rt(t.errors,r)}if(p.touchedFields&&u&&Array.isArray(f(t.touchedFields,r))){const y=o(f(t.touchedFields,r),c.argA,c.argB);d&&A(t.touchedFields,r,y)}p.dirtyFields&&(t.dirtyFields=_e(s,a)),b.state.next({isDirty:v(r,n),dirtyFields:t.dirtyFields,errors:t.errors,isValid:t.isValid})}else A(a,r,n)},H=(r,n)=>{A(t.errors,r,n),b.state.next({errors:t.errors})},D=(r,n,o,c)=>{const d=f(l,r);if(d){const u=f(a,r,T(o)?f(s,r):o);T(u)||c&&c.defaultChecked||n?A(a,r,n?u:Fe(d._f)):k(r,u),m.mount&&P()}},z=(r,n,o,c,d)=>{let u=!1;const y={name:r},F=f(t.touchedFields,r);if(p.isDirty){const M=t.isDirty;t.isDirty=y.isDirty=v(),u=M!==y.isDirty}if(p.dirtyFields&&(!o||c)){const M=f(t.dirtyFields,r);oe(f(s,r),n)?I(t.dirtyFields,r):A(t.dirtyFields,r,!0),y.dirtyFields=t.dirtyFields,u=u||M!==f(t.dirtyFields,r)}return o&&!F&&(A(t.touchedFields,r,o),y.touchedFields=t.touchedFields,u=u||p.touchedFields&&F!==o),u&&d&&b.state.next(y),u?y:{}},ie=(r,n,o,c)=>{const d=f(t.errors,r),u=p.isValid&&ce(n)&&t.isValid!==n;if(e.delayError&&o?(E=le(()=>H(r,o)),E(e.delayError)):(clearTimeout(V),E=null,o?A(t.errors,r,o):I(t.errors,r)),(o?!oe(d,o):d)||!B(c)||u){const y={...c,...u&&ce(n)?{isValid:n}:{},errors:t.errors,name:r};t={...t,...y},b.state.next(y)}O[r]--,p.isValidating&&!Object.values(O).some(y=>y)&&(b.state.next({isValidating:!1}),O={})},K=async r=>i.resolver?await i.resolver({...a},i.context,Ct(r||g.mount,l,i.criteriaMode,i.shouldUseNativeValidation)):{},J=async r=>{const{errors:n}=await K();if(r)for(const o of r){const c=f(n,o);c?A(t.errors,o,c):I(t.errors,o)}else t.errors=n;return n},R=async(r,n,o={valid:!0})=>{for(const c in r){const d=r[c];if(d){const{_f:u,...y}=d;if(u){const F=g.array.has(u.name),M=await ze(d,f(a,u.name),re,i.shouldUseNativeValidation,F);if(M[u.name]&&(o.valid=!1,n))break;!n&&(f(M,u.name)?F?St(t.errors,M,u.name):A(t.errors,u.name,M[u.name]):I(t.errors,u.name))}y&&await R(y,n,o)}}return o.valid},Z=()=>{for(const r of g.unMount){const n=f(l,r);n&&(n._f.refs?n._f.refs.every(o=>!Se(o)):!Se(n._f.ref))&&ke(r)}g.unMount=new Set},v=(r,n)=>(r&&n&&A(a,r,n),!oe(X(),s)),x=(r,n,o)=>{const c={...m.mount?a:T(n)?s:W(r)?{[r]:n}:n};return At(r,g,c,o)},S=r=>fe(f(m.mount?a:s,r,e.shouldUnregister?f(s,r,[]):[])),k=(r,n,o={})=>{const c=f(l,r);let d=n;if(c){const u=c._f;u&&(!u.disabled&&A(a,r,st(n,u)),d=Te&&Ce(u.ref)&&N(n)?"":n,rt(u.ref)?[...u.ref.options].forEach(y=>y.selected=d.includes(y.value)):u.refs?de(u.ref)?u.refs.length>1?u.refs.forEach(y=>(!y.defaultChecked||!y.disabled)&&(y.checked=Array.isArray(d)?!!d.find(F=>F===y.value):d===y.value)):u.refs[0]&&(u.refs[0].checked=!!d):u.refs.forEach(y=>y.checked=y.value===d):Oe(u.ref)?u.ref.value="":(u.ref.value=d,u.ref.type||b.watch.next({name:r})))}(o.shouldDirty||o.shouldTouch)&&z(r,d,o.shouldTouch,o.shouldDirty,!0),o.shouldValidate&&Q(r)},w=(r,n,o)=>{for(const c in n){const d=n[c],u=`${r}.${c}`,y=f(l,u);(g.array.has(r)||!be(d)||y&&!y._f)&&!ne(d)?w(u,d,o):k(u,d,o)}},_=(r,n,o={})=>{const c=f(l,r),d=g.array.has(r),u=te(n);A(a,r,u),d?(b.array.next({name:r,values:a}),(p.isDirty||p.dirtyFields)&&o.shouldDirty&&(t.dirtyFields=_e(s,a),b.state.next({name:r,dirtyFields:t.dirtyFields,isDirty:v(r,u)}))):c&&!c._f&&!N(u)?w(r,u,o):k(r,u,o),$e(r,g)&&b.state.next({}),b.watch.next({name:r})},G=async r=>{const n=r.target;let o=n.name;const c=f(l,o);if(c){let d,u;const y=n.type?Fe(c._f):bt(r),F=r.type===He.BLUR||r.type===He.FOCUS_OUT,M=!Lt(c._f)&&!i.resolver&&!f(t.errors,o)&&!c._f.deps||Ot(F,f(t.touchedFields,o),t.isSubmitted,q,U),ye=$e(o,g,F);A(a,o,y),F?(c._f.onBlur&&c._f.onBlur(r),E&&E(0)):c._f.onChange&&c._f.onChange(r);const Ee=z(o,y,F,!1),dt=!B(Ee)||ye;if(!F&&b.watch.next({name:o,type:r.type}),M)return p.isValid&&P(),dt&&b.state.next({name:o,...ye?{}:Ee});if(!F&&ye&&b.state.next({}),O[o]=O[o]?O[o]+1:1,b.state.next({isValidating:!0}),i.resolver){const{errors:Ne}=await K([o]),ft=Qe(t.errors,l,o),qe=Qe(Ne,l,ft.name||o);d=qe.error,o=qe.name,u=B(Ne)}else d=(await ze(c,f(a,o),re,i.shouldUseNativeValidation))[o],P();c._f.deps&&Q(c._f.deps),ie(o,u,d,Ee)}},Q=async(r,n={})=>{let o,c;const d=Ae(r);if(b.state.next({isValidating:!0}),i.resolver){const u=await J(T(r)?r:d);o=B(u),c=r?!d.some(y=>f(u,y)):o}else r?(c=(await Promise.all(d.map(async u=>{const y=f(l,u);return await R(y&&y._f?{[u]:y}:y)}))).every(Boolean),!(!c&&!t.isValid)&&P()):c=o=await R(l);return b.state.next({...!W(r)||p.isValid&&o!==t.isValid?{}:{name:r},...i.resolver||!r?{isValid:o}:{},errors:t.errors,isValidating:!1}),n.shouldFocus&&!c&&Ve(l,u=>u&&f(t.errors,u),r?d:g.mount),c},X=r=>{const n={...s,...m.mount?a:{}};return T(r)?n:W(r)?f(n,r):r.map(o=>f(n,o))},Me=(r,n)=>({invalid:!!f((n||t).errors,r),isDirty:!!f((n||t).dirtyFields,r),isTouched:!!f((n||t).touchedFields,r),error:f((n||t).errors,r)}),nt=r=>{r?Ae(r).forEach(n=>I(t.errors,n)):t.errors={},b.state.next({errors:t.errors})},ot=(r,n,o)=>{const c=(f(l,r,{_f:{}})._f||{}).ref;A(t.errors,r,{...n,ref:c}),b.state.next({name:r,errors:t.errors,isValid:!1}),o&&o.shouldFocus&&c&&c.focus&&c.focus()},lt=(r,n)=>he(r)?b.watch.subscribe({next:o=>r(x(void 0,n),o)}):x(r,n,!0),ke=(r,n={})=>{for(const o of r?Ae(r):g.mount)g.mount.delete(o),g.array.delete(o),f(l,o)&&(n.keepValue||(I(l,o),I(a,o)),!n.keepError&&I(t.errors,o),!n.keepDirty&&I(t.dirtyFields,o),!n.keepTouched&&I(t.touchedFields,o),!i.shouldUnregister&&!n.keepDefaultValue&&I(s,o));b.watch.next({}),b.state.next({...t,...n.keepDirty?{isDirty:v()}:{}}),!n.keepIsValid&&P()},pe=(r,n={})=>{let o=f(l,r);const c=ce(n.disabled);return A(l,r,{...o||{},_f:{...o&&o._f?o._f:{ref:{name:r}},name:r,mount:!0,...n}}),g.mount.add(r),o?c&&A(a,r,n.disabled?void 0:f(a,r,Fe(o._f))):D(r,!0,n.value),{...c?{disabled:n.disabled}:{},...i.shouldUseNativeValidation?{required:!!n.required,min:ue(n.min),max:ue(n.max),minLength:ue(n.minLength),maxLength:ue(n.maxLength),pattern:ue(n.pattern)}:{},name:r,onChange:G,onBlur:G,ref:d=>{if(d){pe(r,n),o=f(l,r);const u=T(d.value)&&d.querySelectorAll&&d.querySelectorAll("input,select,textarea")[0]||d,y=Tt(u),F=o._f.refs||[];if(y?F.find(M=>M===u):u===o._f.ref)return;A(l,r,{_f:{...o._f,...y?{refs:[...F.filter(Se),u,...Array.isArray(f(s,r))?[{}]:[]],ref:{type:u.type,name:r}}:{ref:u}}}),D(r,!1,void 0,u)}else o=f(l,r,{}),o._f&&(o._f.mount=!1),(i.shouldUnregister||n.shouldUnregister)&&!(kt(g.array,r)&&m.action)&&g.unMount.add(r)}}},Ie=()=>i.shouldFocusError&&Ve(l,r=>r&&f(t.errors,r),g.mount),at=(r,n)=>async o=>{o&&(o.preventDefault&&o.preventDefault(),o.persist&&o.persist());let c=!0,d=te(a);b.state.next({isSubmitting:!0});try{if(i.resolver){const{errors:u,values:y}=await K();t.errors=u,d=y}else await R(l);B(t.errors)?(b.state.next({errors:{},isSubmitting:!0}),await r(d,o)):(n&&await n({...t.errors},o),Ie())}catch(u){throw c=!1,u}finally{t.isSubmitted=!0,b.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:B(t.errors)&&c,submitCount:t.submitCount+1,errors:t.errors})}},ut=(r,n={})=>{f(l,r)&&(T(n.defaultValue)?_(r,f(s,r)):(_(r,n.defaultValue),A(s,r,n.defaultValue)),n.keepTouched||I(t.touchedFields,r),n.keepDirty||(I(t.dirtyFields,r),t.isDirty=n.defaultValue?v(r,f(s,r)):v()),n.keepError||(I(t.errors,r),p.isValid&&P()),b.state.next({...t}))},ct=(r,n={})=>{const o=r||s,c=te(o),d=r&&!B(r)?c:s;if(n.keepDefaultValues||(s=o),!n.keepValues){if(n.keepDirtyValues)for(const u of g.mount)f(t.dirtyFields,u)?A(d,u,f(a,u)):_(u,f(d,u));else{if(Te&&T(r))for(const u of g.mount){const y=f(l,u);if(y&&y._f){const F=Array.isArray(y._f.refs)?y._f.refs[0]:y._f.ref;if(Ce(F)){const M=F.closest("form");if(M){M.reset();break}}}}l={}}a=e.shouldUnregister?n.keepDefaultValues?te(s):{}:c,b.array.next({values:d}),b.watch.next({values:d})}g={mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},m.mount=!p.isValid||!!n.keepIsValid,m.watch=!!e.shouldUnregister,b.state.next({submitCount:n.keepSubmitCount?t.submitCount:0,isDirty:n.keepDirty||n.keepDirtyValues?t.isDirty:!!(n.keepDefaultValues&&!oe(r,s)),isSubmitted:n.keepIsSubmitted?t.isSubmitted:!1,dirtyFields:n.keepDirty||n.keepDirtyValues?t.dirtyFields:n.keepDefaultValues&&r?_e(s,r):{},touchedFields:n.keepTouched?t.touchedFields:{},errors:n.keepErrors?t.errors:{},isSubmitting:!1,isSubmitSuccessful:!1})};return{control:{register:pe,unregister:ke,getFieldState:Me,_executeSchema:K,_focusError:Ie,_getWatch:x,_getDirty:v,_updateValid:P,_removeUnmounted:Z,_updateFieldArray:C,_getFieldArray:S,_subjects:b,_proxyFormState:p,get _fields(){return l},get _formValues(){return a},get _stateFlags(){return m},set _stateFlags(r){m=r},get _defaultValues(){return s},get _names(){return g},set _names(r){g=r},get _formState(){return t},set _formState(r){t=r},get _options(){return i},set _options(r){i={...i,...r}}},trigger:Q,register:pe,handleSubmit:at,watch:lt,setValue:_,getValues:X,reset:(r,n)=>ct(he(r)?r(a):r,n),resetField:ut,clearErrors:nt,unregister:ke,setError:ot,setFocus:(r,n={})=>{const o=f(l,r),c=o&&o._f;if(c){const d=c.refs?c.refs[0]:c.ref;d.focus&&(d.focus(),n.shouldSelect&&d.select())}},getFieldState:Me}}function Nt(e={}){const i=h.useRef(),[t,l]=h.useState({isDirty:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},errors:{},defaultValues:e.defaultValues});i.current||(i.current={...It(e),formState:t});const s=i.current.control;return s._options=e,wt({subject:s._subjects.state,callback:h.useCallback(a=>{Et(a,s._proxyFormState,!0)&&(s._formState={...s._formState,...a},l({...s._formState}))},[s])}),h.useEffect(()=>{s._stateFlags.mount||(s._proxyFormState.isValid&&s._updateValid(),s._stateFlags.mount=!0),s._stateFlags.watch&&(s._stateFlags.watch=!1,s._subjects.state.next({})),s._removeUnmounted()}),h.useEffect(()=>{t.submitCount&&s._focusError()},[s,t.submitCount]),i.current.formState=pt(t,s),i.current}var qt=(e=>(e.formgroup="formgroup",e.checkbox="checkbox",e.radiobutton="radiobutton",e.textarea="textarea",e.input="input",e.select="select",e.date="date",e))(qt||{});const Cr=e=>{const{exampleType:i="formgroup"}=e,{register:t,handleSubmit:l,formState:{errors:s}}=Nt(),a=new Date;a.setHours(0),a.setMinutes(0),a.setSeconds(0);const m=new Date;m.setDate(a.getDate()-5),m.setHours(6),m.setMinutes(10),m.setSeconds(0);const g=new Date;g.setDate(a.getDate()+5),g.setHours(22),g.setMinutes(0),g.setSeconds(0);const E="field1",V="field2",O="field3",p="field4",b="field5",U="field6",q="field7",re="field8",le="field9",P=s.field1||s.field2||s.field3||s.field4||s.field5||s.field6||s.field7||s.field8||s.field9,C="Du m\xE5 velge et alternativ",H="Du m\xE5 velge to alternativ",D="Det kan ikke legges inn mer enn 40 tegn",z="Du m\xE5 skrive noe her",ie='Du m\xE5 velge "Option 2"',K=`Du m\xE5 velge dato mellom ${m.toLocaleDateString("nb")} og ${g.toLocaleDateString("nb")}`,J=`Du m\xE5 skrive inn tidspunkt mellom ${m.toLocaleTimeString("nb",{hour:"2-digit",minute:"2-digit"})} og ${g.toLocaleTimeString("nb",{hour:"2-digit",minute:"2-digit"})}`,R=k=>k.length>=2||H,Z=k=>k.toString()==="Option 2"||ie,v=(k,w,_)=>{const G=new Date(k);return!!k&&G.getTime()>=w.getTime()&&G.getTime()<=_.getTime()||K},x=(k,w)=>{const _=new Date;_.setHours(k),_.setMinutes(w),_.setSeconds(0);const G=m.toLocaleTimeString("nb"),Q=g.toLocaleTimeString("nb"),X=_.toLocaleTimeString("nb");return console.log("value",X),!!_&&X>=G&&X<=Q||J},S=()=>{if(i==="formgroup"){const k=[h.createElement(ee,{key:0,inputId:"checkbox1",label:"Checkbox 1",...t(E,{required:C})}),h.createElement(ee,{key:1,inputId:"checkbox2",label:"Checkbox 2",...t(E,{required:C})}),h.createElement(ee,{key:2,inputId:"checkbox3",label:"Checkbox 3",...t(E,{required:C})})];return[h.createElement(Y,{key:0,title:"Gruppe tittel",legend:"Velg minst en",error:s.field1?s.field1.message:void 0,variant:e.variant},h.createElement(gt,{maxColumns:ht.two},k.map(w=>w))),h.createElement(Y,{key:1,legend:"Velg minst to",error:s.field2?s.field2.message:void 0,variant:e.variant},h.createElement(ee,{inputId:"checkbox4",label:"Checkbox 4",...t(V,{validate:R})}),h.createElement(ee,{inputId:"checkbox5",label:"Checkbox 5",...t(V,{validate:R})}),h.createElement(ee,{inputId:"checkbox6",label:"Checkbox 6",...t(V,{validate:R})})),h.createElement(Y,{key:2,legend:"Velg en",error:s.field3?s.field3.message:void 0,variant:e.variant},h.createElement(me,{inputId:"radiobutton1",label:"Radiobutton 1",...t(O,{required:C})}),h.createElement(me,{inputId:"radiobutton2",label:"Radiobutton 2",...t(O,{required:C})}),h.createElement(me,{inputId:"radiobutton3",label:"Radiobutton 3",...t(O,{required:C})})),h.createElement(Y,{key:3,error:s.field4?s.field4.message:void 0},h.createElement(Be,{defaultValue:`Dette er en test
2
2
 
3
3
  Hello
4
4
 
5
5
  test
6
6
 
7
- test test`,grow:!0,maxCharacters:40,minRows:5,label:"Skriv din historie her",textareaId:"textarea1",...t(E,{maxLength:{value:40,message:L}})})),v.createElement(Z,{key:4,variant:e.variant,error:i.field5?i.field5.message:void 0},v.createElement(Ue,{label:"Skriv inn din tekst",placeholder:"Skriv noe!",icon:qe,...t(S,{required:K})})),v.createElement(Z,{key:5,variant:e.variant,error:i.field6?i.field6.message:void 0},v.createElement(Ne,{label:"Skriv inn din tekst",...t(R,{validate:U})},v.createElement("option",{value:"Option 1"},"Option 1"),v.createElement("option",{value:"Option 2"},"Option 2"),v.createElement("option",{value:"Option 3"},"Option 3")))]}else{if(s==="checkbox")return v.createElement(J,{inputId:"checkbox1",label:"Checkbox 1",errorText:i.field1?i.field1.message:void 0,variant:e.variant,...t(a,{required:m})});if(s==="radiobutton")return v.createElement(ye,{inputId:"radiobutton1",label:"Radiobutton 1",errorText:i.field3?i.field3.message:void 0,variant:e.variant,...t(h,{required:m})});if(s==="textarea")return v.createElement(Be,{defaultValue:`Dette er min historie
7
+ test test`,grow:!0,maxCharacters:40,minRows:5,label:"Skriv din historie her",textareaId:"textarea1",...t(p,{maxLength:{value:40,message:D}})})),h.createElement(Y,{key:4,variant:e.variant,error:s.field5?s.field5.message:void 0},h.createElement(ae,{label:"Skriv inn din tekst",placeholder:"Skriv noe!",icon:Ue,...t(b,{required:z})})),h.createElement(Y,{key:5,variant:e.variant,error:s.field6?s.field6.message:void 0},h.createElement(Pe,{label:"Skriv inn din tekst",...t(U,{validate:Z})},h.createElement("option",{value:"Option 1"},"Option 1"),h.createElement("option",{value:"Option 2"},"Option 2"),h.createElement("option",{value:"Option 3"},"Option 3")))]}else{if(i==="checkbox")return h.createElement(ee,{inputId:"checkbox1",label:"Checkbox 1",errorText:s.field1?s.field1.message:void 0,variant:e.variant,...t(E,{required:C})});if(i==="radiobutton")return h.createElement(me,{inputId:"radiobutton1",label:"Radiobutton 1",errorText:s.field3?s.field3.message:void 0,variant:e.variant,...t(O,{required:C})});if(i==="textarea")return h.createElement(Be,{defaultValue:`Dette er min historie
8
8
 
9
9
  Hello
10
10
 
11
- test`,grow:!0,maxCharacters:40,minRows:5,errorText:i.field4?i.field4.message:void 0,label:"Skriv din historie her",textareaId:"textarea1",...t(E,{maxLength:{value:40,message:L}})});if(s==="input")return v.createElement(Ue,{inputId:"input1",label:"Skriv inn din tekst",placeholder:"Skriv noe!",errorText:i.field5?i.field5.message:void 0,icon:qe,...t(S,{required:K})});if(s==="select")return v.createElement(Ne,{errorText:i.field6?i.field6.message:void 0,label:"Skriv inn din tekst",...t(R,{validate:U})},v.createElement("option",{value:"Option 1"},"Option 1"),v.createElement("option",{value:"Option 2"},"Option 2"),v.createElement("option",{value:"Option 3"},"Option 3"))}};return v.createElement("form",{onSubmit:l(k=>{!mt()&&console.log(k)})},v.createElement(dt,{variant:e.variant,errorSummary:p?"Sjekk at alt er riktig utfylt":void 0},q()),v.createElement(yt,{type:"submit"},"Send inn"))};export{Vr as FormExample,Bt as FormExampleVariants,Vr as default};
11
+ test`,grow:!0,maxCharacters:40,minRows:5,errorText:s.field4?s.field4.message:void 0,label:"Skriv din historie her",textareaId:"textarea1",...t(p,{maxLength:{value:40,message:D}})});if(i==="input")return h.createElement(ae,{inputId:"input1",label:"Skriv inn din tekst",placeholder:"Skriv noe!",errorText:s.field5?s.field5.message:void 0,icon:Ue,...t(b,{required:z})});if(i==="select")return h.createElement(Pe,{errorText:s.field6?s.field6.message:void 0,label:"Skriv inn din tekst",...t(U,{validate:Z})},h.createElement("option",{value:"Option 1"},"Option 1"),h.createElement("option",{value:"Option 2"},"Option 2"),h.createElement("option",{value:"Option 3"},"Option 3"));if(i==="date"){const k=s.field7||s.field8||s.field9;return h.createElement(h.Fragment,null,h.createElement(Y,{legend:"Velg en dato og et klokkeslett",fieldsetClassName:we["fieldset--flex"],error:k?k.message:void 0},h.createElement(ae,{className:we["date-picker--spacing"],label:"dato",width:20,type:"date",defaultValue:a.toLocaleDateString("en-CA"),min:m.toLocaleDateString("en-CA"),max:g.toLocaleDateString("en-CA"),...t(q,{validate:w=>v(w,m,g)})}),h.createElement(Y,{htmlMarkup:"div",fieldsetClassName:we["fieldset--flex-time"]},h.createElement(ae,{labelId:"time-label-id",afterInputChildren:h.createElement("span",{style:{padding:"0 1rem"}},":"),label:"klokke",width:4,type:"number",defaultValue:a.toLocaleTimeString("nb",{hour:"2-digit"}),max:23,min:0,...t(re,{validate:w=>x(w,w)})}),h.createElement(ae,{"aria-labelledby":"time-label-id",width:4,type:"number",defaultValue:a.toLocaleTimeString("nb",{minute:"2-digit"}),max:59,min:0,...t(le,{validate:w=>x(7,w)})}))))}}};return h.createElement("form",{noValidate:!0,onSubmit:l(k=>{!vt()&&console.log(k)})},h.createElement(yt,{variant:e.variant,errorSummary:P?"Sjekk at alt er riktig utfylt":void 0},S()),h.createElement(mt,{type:"submit"},"Send inn"))};export{Cr as FormExample,qt as FormExampleVariants,Cr as default};
12
12
  //# sourceMappingURL=index.js.map