@helsenorge/designsystem-react 2.4.0 → 2.6.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.
- package/Button.js +1 -1
- package/Button.js.map +1 -1
- package/CHANGELOG.md +27 -0
- package/Checkbox.js +1 -1
- package/Checkbox.js.map +1 -1
- package/FormGroup.js +1 -1
- package/FormGroup.js.map +1 -1
- package/HelpBubble.js +1 -1
- package/HelpBubble.js.map +1 -1
- package/Input.js +1 -1
- package/Input.js.map +1 -1
- package/Panel.js +1 -1
- package/Panel.js.map +1 -1
- package/RadioButton.js +1 -1
- package/RadioButton.js.map +1 -1
- package/Select.js +2 -0
- package/Select.js.map +1 -0
- package/Textarea.js +1 -1
- package/Textarea.js.map +1 -1
- package/Tooltip.js +1 -1
- package/Tooltip.js.map +1 -1
- package/TooltipWord.js +2 -0
- package/TooltipWord.js.map +1 -0
- package/__mocks__/uuid.js +1 -1
- package/__mocks__/uuid.js.map +1 -1
- package/components/AnchorLink/index.js +1 -1
- package/components/Avatar/index.js +1 -1
- package/components/Avatar/index.js.map +1 -1
- package/components/Button/index.js +1 -1
- package/components/ButtonWithModal/index.js +1 -1
- package/components/ButtonWithModal/index.js.map +1 -1
- package/components/Checkbox/Checkbox.d.ts +1 -1
- package/components/Checkbox/Checkbox.d.ts.map +1 -1
- package/components/Checkbox/componentdata.json +1 -1
- package/components/Checkbox/index.js +1 -1
- package/components/Close/index.js +1 -1
- package/components/Dropdown/Dropdown.d.ts.map +1 -1
- package/components/Dropdown/index.js +1 -1
- package/components/Dropdown/index.js.map +1 -1
- package/components/Duolist/Duolist.d.ts +6 -4
- package/components/Duolist/Duolist.d.ts.map +1 -1
- package/components/Duolist/componentdata.json +1 -1
- package/components/Duolist/index.js +1 -1
- package/components/Duolist/index.js.map +1 -1
- package/components/Duolist/styles.module.scss +0 -1
- package/components/Expander/index.js +1 -1
- package/components/Expander/index.js.map +1 -1
- package/components/ExpanderList/index.js +1 -1
- package/components/ExpanderList/index.js.map +1 -1
- package/components/FormExample/FormExample.d.ts +2 -1
- package/components/FormExample/FormExample.d.ts.map +1 -1
- package/components/FormExample/componentdata.json +1 -1
- package/components/FormExample/index.js +3 -3
- package/components/FormExample/index.js.map +1 -1
- package/components/FormGroup/FormGroup.d.ts.map +1 -1
- package/components/FormGroup/index.js +1 -1
- package/components/HelpBubble/HelpBubble.d.ts +7 -4
- package/components/HelpBubble/HelpBubble.d.ts.map +1 -1
- package/components/HelpBubble/componentdata.json +1 -1
- package/components/HelpBubble/index.js +1 -1
- package/components/HelpBubble/styles.module.scss +12 -6
- package/components/HelpBubble/styles.module.scss.d.ts +0 -1
- package/components/HelpBubbleExample/componentdata.json +1 -1
- package/components/HelpBubbleExample/index.js +1 -1
- package/components/HelpBubbleExample/index.js.map +1 -1
- package/components/HighlightBox/index.js +1 -1
- package/components/HighlightBox/index.js.map +1 -1
- package/components/HorizontalScroll/index.js +1 -1
- package/components/Icons/AcupunctureBack.js +1 -1
- package/components/Icons/AcupunctureBack.js.map +1 -1
- package/components/Icons/AlarmClock.js +1 -1
- package/components/Icons/AlarmClock.js.map +1 -1
- package/components/Icons/AlertSignFill.js +1 -1
- package/components/Icons/AlertSignFill.js.map +1 -1
- package/components/Icons/AlertSignStroke.js +1 -1
- package/components/Icons/AlertSignStroke.js.map +1 -1
- package/components/Icons/Archive.js +1 -1
- package/components/Icons/Archive.js.map +1 -1
- package/components/Icons/ArrowDown.js +1 -1
- package/components/Icons/ArrowDown.js.map +1 -1
- package/components/Icons/ArrowLeft.js +1 -1
- package/components/Icons/ArrowLeft.js.map +1 -1
- package/components/Icons/ArrowRight.js +1 -1
- package/components/Icons/ArrowRight.js.map +1 -1
- package/components/Icons/ArrowUp.js +1 -1
- package/components/Icons/ArrowUp.js.map +1 -1
- package/components/Icons/ArrowUpRight.js +1 -1
- package/components/Icons/ArrowUpRight.js.map +1 -1
- package/components/Icons/Attachment.js +1 -1
- package/components/Icons/Attachment.js.map +1 -1
- package/components/Icons/Avatar.js +1 -1
- package/components/Icons/Avatar.js.map +1 -1
- package/components/Icons/Bus.js +1 -1
- package/components/Icons/Bus.js.map +1 -1
- package/components/Icons/Calendar.js +1 -1
- package/components/Icons/Calendar.js.map +1 -1
- package/components/Icons/CalendarChange.js +1 -1
- package/components/Icons/CalendarChange.js.map +1 -1
- package/components/Icons/CalendarCheck.js +1 -1
- package/components/Icons/CalendarCheck.js.map +1 -1
- package/components/Icons/CalendarSave.js +1 -1
- package/components/Icons/CalendarSave.js.map +1 -1
- package/components/Icons/Change.js +1 -1
- package/components/Icons/Change.js.map +1 -1
- package/components/Icons/Check.js +1 -1
- package/components/Icons/Check.js.map +1 -1
- package/components/Icons/CheckFill.js +1 -1
- package/components/Icons/CheckFill.js.map +1 -1
- package/components/Icons/ChevronDown.js +1 -1
- package/components/Icons/ChevronDown.js.map +1 -1
- package/components/Icons/ChevronLeft.js +1 -1
- package/components/Icons/ChevronLeft.js.map +1 -1
- package/components/Icons/ChevronRight.js +1 -1
- package/components/Icons/ChevronRight.js.map +1 -1
- package/components/Icons/ChevronUp.js +1 -1
- package/components/Icons/ChevronUp.js.map +1 -1
- package/components/Icons/ChevronsDown.js +1 -1
- package/components/Icons/ChevronsDown.js.map +1 -1
- package/components/Icons/ChevronsUp.js +1 -1
- package/components/Icons/ChevronsUp.js.map +1 -1
- package/components/Icons/Contacts.js +1 -1
- package/components/Icons/Contacts.js.map +1 -1
- package/components/Icons/Copy.js +1 -1
- package/components/Icons/Copy.js.map +1 -1
- package/components/Icons/Download.js +1 -1
- package/components/Icons/Download.js.map +1 -1
- package/components/Icons/EChat.js +1 -1
- package/components/Icons/EChat.js.map +1 -1
- package/components/Icons/EnterFullScreen.js +1 -1
- package/components/Icons/EnterFullScreen.js.map +1 -1
- package/components/Icons/Envelope.js +1 -1
- package/components/Icons/Envelope.js.map +1 -1
- package/components/Icons/Eraser.js +1 -1
- package/components/Icons/Eraser.js.map +1 -1
- package/components/Icons/ErrorSignFill.js +1 -1
- package/components/Icons/ErrorSignFill.js.map +1 -1
- package/components/Icons/ErrorSignStroke.js +1 -1
- package/components/Icons/ErrorSignStroke.js.map +1 -1
- package/components/Icons/ExitFullScreen.js +1 -1
- package/components/Icons/ExitFullScreen.js.map +1 -1
- package/components/Icons/Eye.js +1 -1
- package/components/Icons/Eye.js.map +1 -1
- package/components/Icons/Form.js +1 -1
- package/components/Icons/Form.js.map +1 -1
- package/components/Icons/Forward.js +1 -1
- package/components/Icons/Forward.js.map +1 -1
- package/components/Icons/Gallery.js +1 -1
- package/components/Icons/Gallery.js.map +1 -1
- package/components/Icons/Globe.js +1 -1
- package/components/Icons/Globe.js.map +1 -1
- package/components/Icons/Group.js +1 -1
- package/components/Icons/Group.js.map +1 -1
- package/components/Icons/Heart.js +1 -1
- package/components/Icons/Heart.js.map +1 -1
- package/components/Icons/HelpSign.js +1 -1
- package/components/Icons/HelpSign.js.map +1 -1
- package/components/Icons/History.js +1 -1
- package/components/Icons/History.js.map +1 -1
- package/components/Icons/Home.js +1 -1
- package/components/Icons/Home.js.map +1 -1
- package/components/Icons/Hospital.js +1 -1
- package/components/Icons/Hospital.js.map +1 -1
- package/components/Icons/Hourglass.js +1 -1
- package/components/Icons/Hourglass.js.map +1 -1
- package/components/Icons/Icon.js +1 -1
- package/components/Icons/Icon.js.map +1 -1
- package/components/Icons/InfoSignFill.js +1 -1
- package/components/Icons/InfoSignFill.js.map +1 -1
- package/components/Icons/InfoSignStroke.js +1 -1
- package/components/Icons/InfoSignStroke.js.map +1 -1
- package/components/Icons/Journal.js +1 -1
- package/components/Icons/Journal.js.map +1 -1
- package/components/Icons/List.js +1 -1
- package/components/Icons/List.js.map +1 -1
- package/components/Icons/Location.js +1 -1
- package/components/Icons/Location.js.map +1 -1
- package/components/Icons/Lock.js +1 -1
- package/components/Icons/Lock.js.map +1 -1
- package/components/Icons/Medicine.js +1 -1
- package/components/Icons/Medicine.js.map +1 -1
- package/components/Icons/Menu.js +1 -1
- package/components/Icons/Menu.js.map +1 -1
- package/components/Icons/Minus.js +1 -1
- package/components/Icons/Minus.js.map +1 -1
- package/components/Icons/MobilePhone.js +1 -1
- package/components/Icons/MobilePhone.js.map +1 -1
- package/components/Icons/NoAccess.js +1 -1
- package/components/Icons/NoAccess.js.map +1 -1
- package/components/Icons/NoEye.js +1 -1
- package/components/Icons/NoEye.js.map +1 -1
- package/components/Icons/NoFilter.js +1 -1
- package/components/Icons/NoFilter.js.map +1 -1
- package/components/Icons/PaperPlane.js +1 -1
- package/components/Icons/PaperPlane.js.map +1 -1
- package/components/Icons/Pause.js +1 -1
- package/components/Icons/Pause.js.map +1 -1
- package/components/Icons/Pencil.js +1 -1
- package/components/Icons/Pencil.js.map +1 -1
- package/components/Icons/PersonalPlan.js +1 -1
- package/components/Icons/PersonalPlan.js.map +1 -1
- package/components/Icons/Play.js +1 -1
- package/components/Icons/Play.js.map +1 -1
- package/components/Icons/PlusLarge.js +1 -1
- package/components/Icons/PlusLarge.js.map +1 -1
- package/components/Icons/PlusSmall.js +1 -1
- package/components/Icons/PlusSmall.js.map +1 -1
- package/components/Icons/Printer.js +1 -1
- package/components/Icons/Printer.js.map +1 -1
- package/components/Icons/QrCode.js +1 -1
- package/components/Icons/QrCode.js.map +1 -1
- package/components/Icons/Receptionist.js +1 -1
- package/components/Icons/Receptionist.js.map +1 -1
- package/components/Icons/Referral.js +1 -1
- package/components/Icons/Referral.js.map +1 -1
- package/components/Icons/Refresh.js +1 -1
- package/components/Icons/Refresh.js.map +1 -1
- package/components/Icons/Reply.js +1 -1
- package/components/Icons/Reply.js.map +1 -1
- package/components/Icons/Save.js +1 -1
- package/components/Icons/Save.js.map +1 -1
- package/components/Icons/Search.js +1 -1
- package/components/Icons/Search.js.map +1 -1
- package/components/Icons/SectionSign.js +1 -1
- package/components/Icons/SectionSign.js.map +1 -1
- package/components/Icons/Settings.js +1 -1
- package/components/Icons/Settings.js.map +1 -1
- package/components/Icons/Share.js +1 -1
- package/components/Icons/Share.js.map +1 -1
- package/components/Icons/SpeechBubble.js +1 -1
- package/components/Icons/SpeechBubble.js.map +1 -1
- package/components/Icons/Stopwatch.js +1 -1
- package/components/Icons/Stopwatch.js.map +1 -1
- package/components/Icons/SupportingPerson.js +1 -1
- package/components/Icons/SupportingPerson.js.map +1 -1
- package/components/Icons/Syringe.js +1 -1
- package/components/Icons/Syringe.js.map +1 -1
- package/components/Icons/TimePassing.js +1 -1
- package/components/Icons/TimePassing.js.map +1 -1
- package/components/Icons/Toolbox.js +1 -1
- package/components/Icons/Toolbox.js.map +1 -1
- package/components/Icons/TrashCan.js +1 -1
- package/components/Icons/TrashCan.js.map +1 -1
- package/components/Icons/Undo.js +1 -1
- package/components/Icons/Undo.js.map +1 -1
- package/components/Icons/Upload.js +1 -1
- package/components/Icons/Upload.js.map +1 -1
- package/components/Icons/Vaccine.js +1 -1
- package/components/Icons/Vaccine.js.map +1 -1
- package/components/Icons/VerticalDots.js +1 -1
- package/components/Icons/VerticalDots.js.map +1 -1
- package/components/Icons/VideoCamera.js +1 -1
- package/components/Icons/VideoCamera.js.map +1 -1
- package/components/Icons/VideoChat.js +1 -1
- package/components/Icons/VideoChat.js.map +1 -1
- package/components/Icons/Wallet.js +1 -1
- package/components/Icons/Wallet.js.map +1 -1
- package/components/Icons/Watch.js +1 -1
- package/components/Icons/Watch.js.map +1 -1
- package/components/Icons/X.js +1 -1
- package/components/Icons/X.js.map +1 -1
- package/components/Icons/Zoom.js +1 -1
- package/components/Icons/Zoom.js.map +1 -1
- package/components/Icons/index.js +1 -1
- package/components/Input/Input.d.ts +0 -1
- package/components/Input/Input.d.ts.map +1 -1
- package/components/Input/index.js +1 -1
- package/components/LinkList/index.js +1 -1
- package/components/LinkList/index.js.map +1 -1
- package/components/Loader/index.js +1 -1
- package/components/Loader/index.js.map +1 -1
- package/components/Modal/index.js +1 -1
- package/components/NotificationPanel/index.js +1 -1
- package/components/NotificationPanel/index.js.map +1 -1
- package/components/Panel/index.js +1 -1
- package/components/PanelList/index.js +1 -1
- package/components/PanelList/index.js.map +1 -1
- package/components/Progressbar/index.js +1 -1
- package/components/Progressbar/index.js.map +1 -1
- package/components/RadioButton/RadioButton.d.ts.map +1 -1
- package/components/RadioButton/index.js +1 -1
- package/components/Select/Select.d.ts +30 -0
- package/components/Select/Select.d.ts.map +1 -0
- package/components/Select/componentdata.json +1 -0
- package/components/Select/index.d.ts +4 -0
- package/components/Select/index.d.ts.map +1 -0
- package/components/Select/index.js +2 -0
- package/components/Select/index.js.map +1 -0
- package/components/Select/styles.module.scss +125 -0
- package/components/Select/styles.module.scss.d.ts +21 -0
- package/components/Slider/index.js +1 -1
- package/components/Slider/index.js.map +1 -1
- package/components/StatusDot/index.js +1 -1
- package/components/StatusDot/index.js.map +1 -1
- package/components/Table/TableExpandedRow/index.js +1 -1
- package/components/Table/TableExpanderCell/index.js +1 -1
- package/components/Table/TableHeadCell/index.js +1 -1
- package/components/Table/TableRow/index.js +1 -1
- package/components/Table/index.js +1 -1
- package/components/Table/index.js.map +1 -1
- package/components/Tag/index.js +1 -1
- package/components/Tag/index.js.map +1 -1
- package/components/Textarea/Textarea.d.ts +1 -1
- package/components/Textarea/Textarea.d.ts.map +1 -1
- package/components/Textarea/componentdata.json +1 -1
- package/components/Textarea/index.js +1 -1
- package/components/Tile/index.js +1 -1
- package/components/Tile/index.js.map +1 -1
- package/components/Tooltip/Tooltip.d.ts +11 -12
- package/components/Tooltip/Tooltip.d.ts.map +1 -1
- package/components/Tooltip/TooltipWord/TooltipWord.d.ts +20 -0
- package/components/Tooltip/TooltipWord/TooltipWord.d.ts.map +1 -0
- package/components/Tooltip/TooltipWord/componentdata.json +1 -0
- package/components/Tooltip/TooltipWord/index.d.ts +4 -0
- package/components/Tooltip/TooltipWord/index.d.ts.map +1 -0
- package/components/Tooltip/TooltipWord/index.js +2 -0
- package/components/Tooltip/TooltipWord/index.js.map +1 -0
- package/components/Tooltip/{styles.module.scss → TooltipWord/styles.module.scss} +3 -6
- package/components/Tooltip/{styles.module.scss.d.ts → TooltipWord/styles.module.scss.d.ts} +0 -0
- package/components/Tooltip/componentdata.json +1 -1
- package/components/Tooltip/index.js +1 -1
- package/components/TooltipExample/TooltipExample.d.ts.map +1 -1
- package/components/TooltipExample/componentdata.json +1 -1
- package/components/TooltipExample/index.js +1 -1
- package/components/TooltipExample/index.js.map +1 -1
- package/components/Validation/index.js +1 -1
- package/constants.d.ts +2 -0
- package/constants.d.ts.map +1 -1
- package/constants.js +1 -1
- package/constants.js.map +1 -1
- package/hooks/useDelayedState.d.ts +9 -0
- package/hooks/useDelayedState.d.ts.map +1 -0
- package/hooks/useDelayedState.js +2 -0
- package/hooks/useDelayedState.js.map +1 -0
- package/hooks/useElementList.d.ts +9 -0
- package/hooks/useElementList.d.ts.map +1 -0
- package/hooks/useElementList.js +2 -0
- package/hooks/useElementList.js.map +1 -0
- package/hooks/useFocusToggle.d.ts.map +1 -1
- package/hooks/useFocusToggle.js +1 -1
- package/hooks/useFocusToggle.js.map +1 -1
- package/hooks/useFocusTrap.js +1 -1
- package/hooks/useFocusTrap.js.map +1 -1
- package/hooks/useFocusableElements.d.ts.map +1 -1
- package/hooks/useFocusableElements.js +1 -1
- package/hooks/useFocusableElements.js.map +1 -1
- package/hooks/useHover.d.ts +5 -6
- package/hooks/useHover.d.ts.map +1 -1
- package/hooks/useHover.js +1 -1
- package/hooks/useHover.js.map +1 -1
- package/hooks/useKeyboardEvent.d.ts +10 -1
- package/hooks/useKeyboardEvent.d.ts.map +1 -1
- package/hooks/useKeyboardEvent.js +1 -1
- package/hooks/useKeyboardEvent.js.map +1 -1
- package/hooks/useLayoutEvent.js +1 -1
- package/hooks/useLayoutEvent.js.map +1 -1
- package/hooks/useOutsideEvent.d.ts +1 -4
- package/hooks/useOutsideEvent.d.ts.map +1 -1
- package/hooks/useOutsideEvent.js +1 -1
- package/hooks/useOutsideEvent.js.map +1 -1
- package/hooks/useSize.js +1 -1
- package/hooks/useSize.js.map +1 -1
- package/hooks/useSticky.js +1 -1
- package/hooks/useSticky.js.map +1 -1
- package/hooks/useUuid.js +1 -1
- package/hooks/useUuid.js.map +1 -1
- package/index.js +1 -1
- package/package.json +1 -1
- package/utils/accessibility.js +2 -0
- package/utils/accessibility.js.map +1 -0
- package/utils/debounce.js +2 -0
- package/utils/debounce.js.map +1 -0
- package/utils/environment.js +2 -0
- package/utils/environment.js.map +1 -0
- package/{hooks/focus-utils.d.ts → utils/focus.d.ts} +1 -1
- package/utils/focus.d.ts.map +1 -0
- package/{hooks/focus-utils.js → utils/focus.js} +1 -1
- package/utils/focus.js.map +1 -0
- package/utils/loremtext.js +2 -0
- package/utils/loremtext.js.map +1 -0
- package/utils/refs.js +2 -0
- package/utils/refs.js.map +1 -0
- package/utils/uuid.js +2 -0
- package/utils/uuid.js.map +1 -0
- package/utils/viewport.js +2 -0
- package/utils/viewport.js.map +1 -0
- package/uuid.js +1 -1
- package/uuid.js.map +1 -1
- package/accessibility.js +0 -2
- package/accessibility.js.map +0 -1
- package/debounce.js +0 -2
- package/debounce.js.map +0 -1
- package/hooks/focus-utils.d.ts.map +0 -1
- package/hooks/focus-utils.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/components/Dropdown/Dropdown.tsx"],"sourcesContent":["import React, { useRef, useState } from 'react';\n\nimport classNames from 'classnames';\n\nimport Icon from '../Icons';\n\nimport {\n AnalyticsId,\n IconSize,\n KeyboardEventKey,\n theme,\n useHover,\n useKeyboardEvent,\n useOutsideEvent,\n useResizeObserver,\n useToggle,\n useUuid,\n} from '../..';\n\nimport styles from './styles.module.scss';\nimport PlusSmall from '../Icons/PlusSmall';\nimport Button from '../Button';\n\nexport enum DropdownMode {\n onwhite = 'onwhite',\n ongrey = 'ongrey',\n onblueberry = 'onblueberry',\n oncherry = 'oncherry',\n}\n\nexport interface DropdownProps {\n /** Label for dropdown. Synlig for skjermlesere. */\n label: string;\n /** Tekst på knappen som åpner dropdownen */\n placeholder: string;\n /** Sets the dropdown content */\n children: React.ReactNode;\n /** Close button text */\n closeText?: string;\n /** No close button */\n noCloseButton?: boolean;\n /** Called when dropdown is open/closed. */\n onToggle?: (isOpen: boolean) => void;\n /** Om dropdown er åpen */\n open?: boolean;\n /** Changes the visuals of the dropdown */\n mode?: keyof typeof DropdownMode;\n /** Makes the background transparent */\n transparent?: boolean;\n /** Makes the background transparent */\n fluid?: boolean;\n /** Makes the dropdown disabled */\n disabled?: boolean;\n /** Sets the data-testid attribute on the dropdown button. */\n testId?: string;\n}\n\nconst Dropdown: React.FC<DropdownProps> = props => {\n const {\n label,\n placeholder,\n closeText = 'Lukk',\n noCloseButton = false,\n onToggle,\n open = false,\n children,\n mode = DropdownMode.onwhite,\n transparent = false,\n fluid = false,\n testId,\n disabled,\n } = props;\n const dropdownRef = useRef<HTMLDivElement>(null);\n const optionsRef = useRef<HTMLUListElement>(null);\n const { hoverRef: buttonRef, isHovered } = useHover<HTMLButtonElement>();\n const { value: isOpen, toggleValue: toggleIsOpen } = useToggle(!disabled && open, onToggle);\n const inputRefList = useRef(React.Children.map(children, () => React.createRef<HTMLElement>()));\n const [currentIndex, setCurrentIndex] = useState<number>();\n const { width: buttonWidth } = useResizeObserver(buttonRef) || {};\n const labelId = useUuid();\n const toggleLabelId = useUuid();\n const optionIdPrefix = useUuid();\n\n const handleOpen = () => {\n toggleIsOpen();\n optionsRef.current?.focus();\n };\n\n const handleClose = () => {\n toggleIsOpen();\n buttonRef.current?.focus();\n };\n\n const handleKeyboardNavigation = (event: KeyboardEvent) => {\n event.preventDefault();\n\n if (!inputRefList.current) {\n return;\n }\n\n if (!isOpen) {\n handleOpen();\n return;\n } else if (event.key === KeyboardEventKey.Escape && isOpen) {\n handleClose();\n return;\n }\n\n const index = inputRefList.current.findIndex(x => x.current === event.target);\n let nextIndex = index;\n\n if (event.key === KeyboardEventKey.Home) {\n nextIndex = 0;\n } else if (event.key === KeyboardEventKey.End) {\n nextIndex = inputRefList.current.length - 1;\n } else if (event.key === KeyboardEventKey.ArrowDown && index < inputRefList.current.length - 1) {\n nextIndex = index + 1;\n } else if (event.key === KeyboardEventKey.ArrowUp && index > 0) {\n nextIndex = index - 1;\n } else if (event.key === KeyboardEventKey.Enter && index !== -1) {\n nextIndex = index;\n }\n if (nextIndex !== -1) {\n inputRefList.current[nextIndex].current?.focus();\n setCurrentIndex(nextIndex);\n }\n };\n\n useKeyboardEvent(\n 'keydown',\n dropdownRef,\n [\n KeyboardEventKey.ArrowDown,\n KeyboardEventKey.ArrowUp,\n KeyboardEventKey.End,\n KeyboardEventKey.Enter,\n KeyboardEventKey.Escape,\n KeyboardEventKey.Home,\n ],\n handleKeyboardNavigation\n );\n\n useOutsideEvent(dropdownRef, () => isOpen && handleClose());\n\n const toggleClasses = classNames(\n styles.dropdown__toggle,\n !disabled && {\n [styles['dropdown__toggle--on-white']]: mode === DropdownMode.onwhite,\n [styles['dropdown__toggle--on-grey']]: mode === DropdownMode.ongrey,\n [styles['dropdown__toggle--on-blueberry']]: mode === DropdownMode.onblueberry,\n [styles['dropdown__toggle--on-cherry']]: mode === DropdownMode.oncherry,\n [styles['dropdown__toggle--transparent']]: transparent,\n [styles['dropdown__toggle--fluid']]: fluid,\n [styles['dropdown__toggle--open']]: isOpen,\n }\n );\n\n const contentClasses = classNames(styles.dropdown__content, isOpen && styles['dropdown__content--open']);\n\n return (\n <div className={styles.dropdown} ref={dropdownRef}>\n <span id={labelId} className={styles.dropdown__label}>\n {label}\n </span>\n <button\n type=\"button\"\n onClick={() => !isOpen && handleOpen()}\n className={toggleClasses}\n ref={buttonRef}\n data-testid={testId}\n data-analyticsid={AnalyticsId.Dropdown}\n disabled={disabled}\n aria-labelledby={toggleLabelId}\n aria-haspopup=\"listbox\"\n aria-expanded={isOpen}\n >\n <span id={toggleLabelId} className={styles.dropdown__toggle__label}>\n {placeholder}\n </span>\n <Icon\n color={disabled ? theme.palette.neutral500 : theme.palette.blueberry600}\n svgIcon={PlusSmall}\n className={styles.dropdown__icon}\n isHovered={isHovered}\n size={IconSize.XSmall}\n />\n </button>\n <div className={contentClasses} style={{ width: fluid ? '100%' : `${buttonWidth}px` }}>\n <ul\n className={styles.dropdown__options}\n role=\"listbox\"\n aria-labelledby={labelId}\n tabIndex={-1}\n aria-activedescendant={typeof currentIndex !== 'undefined' ? `${optionIdPrefix}-${currentIndex}` : undefined}\n ref={optionsRef}\n >\n {React.Children.map(children, (child, index) => (\n <li className={styles.dropdown__input} role=\"option\" id={`${optionIdPrefix}-${index}`}>\n {React.cloneElement(child as React.ReactElement, { ref: inputRefList.current?.[index] })}\n </li>\n ))}\n </ul>\n {!noCloseButton && (\n <div className={styles.dropdown__close}>\n <Button onClick={handleClose} fluid aria-expanded={isOpen}>\n {closeText}\n </Button>\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default Dropdown;\n"],"names":["DropdownMode","Dropdown","props","label","placeholder","closeText","noCloseButton","onToggle","open","children","mode","transparent","fluid","testId","disabled","dropdownRef","useRef","optionsRef","buttonRef","isHovered","useHover","isOpen","toggleIsOpen","useToggle","inputRefList","React","currentIndex","setCurrentIndex","useState","buttonWidth","useResizeObserver","labelId","useUuid","toggleLabelId","optionIdPrefix","handleOpen","_a","handleClose","handleKeyboardNavigation","event","KeyboardEventKey","index","x","nextIndex","useKeyboardEvent","useOutsideEvent","toggleClasses","classNames","styles","contentClasses","AnalyticsId","Icon","theme","PlusSmall","IconSize","child","Button"],"mappings":"4jCAuBY,IAAAA,IAAAA,IACVA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,YAAc,cACdA,EAAA,SAAW,WAJDA,IAAAA,IAAA,CAAA,CAAA,EAkCZ,MAAMC,GAA6CC,GAAA,CAC3C,KAAA,CACJ,MAAAC,EACA,YAAAC,EACA,UAAAC,EAAY,OACZ,cAAAC,EAAgB,GAChB,SAAAC,EACA,KAAAC,EAAO,GACP,SAAAC,EACA,KAAAC,EAAO,UACP,YAAAC,EAAc,GACd,MAAAC,EAAQ,GACR,OAAAC,EACA,SAAA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AS,GAAGiB,KAAgB,CAAA,EACjFJ,EAAA,cAAA,KAAA,CACC,UAAWuB,EAAO,kBAClB,KAAK,UACL,kBAAiBjB,EACjB,SAAU,GACV,wBAAuB,OAAOL,EAAiB,IAAc,GAAGQ,KAAkBR,IAAiB,OACnG,IAAKT,CAAA,EAEJQ,EAAM,SAAS,IAAIhB,EAAU,CAAC8C,EAAOd,IACnC,OAAA,OAAAhB,EAAA,cAAA,KAAA,CAAG,UAAWuB,EAAO,gBAAiB,KAAK,SAAS,GAAI,GAAGd,KAAkBO,GAAA,EAC3EhB,EAAM,aAAa8B,EAA6B,CAAE,KAAKnB,EAAAZ,EAAa,UAAb,YAAAY,EAAuBK,EAAO,CAAC,CACzF,EACD,CACH,EACC,CAACnC,GACCmB,EAAA,cAAA,MAAA,CAAI,UAAWuB,EAAO,eAAA,EACpBvB,EAAA,cAAA+B,EAAA,CAAO,QAASnB,EAAa,MAAK,GAAC,gBAAehB,CAAA,EAChDhB,CACH,CACF,CAEJ,CACF,CAEJ"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/components/Dropdown/Dropdown.tsx"],"sourcesContent":["import React, { useRef, useState } from 'react';\n\nimport classNames from 'classnames';\n\nimport Icon from '../Icons';\n\nimport {\n AnalyticsId,\n IconSize,\n KeyboardEventKey,\n theme,\n useHover,\n useKeyboardEvent,\n useOutsideEvent,\n useResizeObserver,\n useToggle,\n useUuid,\n} from '../..';\n\nimport styles from './styles.module.scss';\nimport PlusSmall from '../Icons/PlusSmall';\nimport Button from '../Button';\n\nexport enum DropdownMode {\n onwhite = 'onwhite',\n ongrey = 'ongrey',\n onblueberry = 'onblueberry',\n oncherry = 'oncherry',\n}\n\nexport interface DropdownProps {\n /** Label for dropdown. Synlig for skjermlesere. */\n label: string;\n /** Tekst på knappen som åpner dropdownen */\n placeholder: string;\n /** Sets the dropdown content */\n children: React.ReactNode;\n /** Close button text */\n closeText?: string;\n /** No close button */\n noCloseButton?: boolean;\n /** Called when dropdown is open/closed. */\n onToggle?: (isOpen: boolean) => void;\n /** Om dropdown er åpen */\n open?: boolean;\n /** Changes the visuals of the dropdown */\n mode?: keyof typeof DropdownMode;\n /** Makes the background transparent */\n transparent?: boolean;\n /** Makes the background transparent */\n fluid?: boolean;\n /** Makes the dropdown disabled */\n disabled?: boolean;\n /** Sets the data-testid attribute on the dropdown button. */\n testId?: string;\n}\n\nconst Dropdown: React.FC<DropdownProps> = props => {\n const {\n label,\n placeholder,\n closeText = 'Lukk',\n noCloseButton = false,\n onToggle,\n open = false,\n children,\n mode = DropdownMode.onwhite,\n transparent = false,\n fluid = false,\n testId,\n disabled,\n } = props;\n const dropdownRef = useRef<HTMLDivElement>(null);\n const optionsRef = useRef<HTMLUListElement>(null);\n const { hoverRef: buttonRef, isHovered } = useHover<HTMLButtonElement>();\n const { value: isOpen, toggleValue: toggleIsOpen } = useToggle(!disabled && open, onToggle);\n const inputRefList = useRef(React.Children.map(children, () => React.createRef<HTMLElement>()));\n const [currentIndex, setCurrentIndex] = useState<number>();\n const { width: buttonWidth } = useResizeObserver(buttonRef) || {};\n const labelId = useUuid();\n const toggleLabelId = useUuid();\n const optionIdPrefix = useUuid();\n\n const handleOpen = () => {\n toggleIsOpen();\n optionsRef.current?.focus();\n };\n\n const handleClose = () => {\n toggleIsOpen();\n buttonRef.current?.focus();\n };\n\n const handleKeyboardNavigation = (event: KeyboardEvent) => {\n event.preventDefault();\n\n if (!inputRefList.current) {\n return;\n }\n\n if (!isOpen) {\n handleOpen();\n return;\n } else if (event.key === KeyboardEventKey.Escape && isOpen) {\n handleClose();\n return;\n }\n\n const index = inputRefList.current.findIndex(x => x.current === event.target);\n let nextIndex = index;\n\n if (event.key === KeyboardEventKey.Home) {\n nextIndex = 0;\n } else if (event.key === KeyboardEventKey.End) {\n nextIndex = inputRefList.current.length - 1;\n } else if (event.key === KeyboardEventKey.ArrowDown && index < inputRefList.current.length - 1) {\n nextIndex = index + 1;\n } else if (event.key === KeyboardEventKey.ArrowUp && index > 0) {\n nextIndex = index - 1;\n } else if (event.key === KeyboardEventKey.Enter && index !== -1) {\n nextIndex = index;\n }\n if (nextIndex !== -1) {\n inputRefList.current[nextIndex].current?.focus();\n setCurrentIndex(nextIndex);\n }\n };\n\n useKeyboardEvent(dropdownRef, handleKeyboardNavigation, [\n KeyboardEventKey.ArrowDown,\n KeyboardEventKey.ArrowUp,\n KeyboardEventKey.End,\n KeyboardEventKey.Enter,\n KeyboardEventKey.Escape,\n KeyboardEventKey.Home,\n ]);\n\n useOutsideEvent(dropdownRef, () => isOpen && handleClose());\n\n const toggleClasses = classNames(\n styles.dropdown__toggle,\n !disabled && {\n [styles['dropdown__toggle--on-white']]: mode === DropdownMode.onwhite,\n [styles['dropdown__toggle--on-grey']]: mode === DropdownMode.ongrey,\n [styles['dropdown__toggle--on-blueberry']]: mode === DropdownMode.onblueberry,\n [styles['dropdown__toggle--on-cherry']]: mode === DropdownMode.oncherry,\n [styles['dropdown__toggle--transparent']]: transparent,\n [styles['dropdown__toggle--fluid']]: fluid,\n [styles['dropdown__toggle--open']]: isOpen,\n }\n );\n\n const contentClasses = classNames(styles.dropdown__content, isOpen && styles['dropdown__content--open']);\n\n return (\n <div className={styles.dropdown} ref={dropdownRef}>\n <span id={labelId} className={styles.dropdown__label}>\n {label}\n </span>\n <button\n type=\"button\"\n onClick={() => !isOpen && handleOpen()}\n className={toggleClasses}\n ref={buttonRef}\n data-testid={testId}\n data-analyticsid={AnalyticsId.Dropdown}\n disabled={disabled}\n aria-labelledby={toggleLabelId}\n aria-haspopup=\"listbox\"\n aria-expanded={isOpen}\n >\n <span id={toggleLabelId} className={styles.dropdown__toggle__label}>\n {placeholder}\n </span>\n <Icon\n color={disabled ? theme.palette.neutral500 : theme.palette.blueberry600}\n svgIcon={PlusSmall}\n className={styles.dropdown__icon}\n isHovered={isHovered}\n size={IconSize.XSmall}\n />\n </button>\n <div className={contentClasses} style={{ width: fluid ? '100%' : `${buttonWidth}px` }}>\n <ul\n className={styles.dropdown__options}\n role=\"listbox\"\n aria-labelledby={labelId}\n tabIndex={-1}\n aria-activedescendant={typeof currentIndex !== 'undefined' ? `${optionIdPrefix}-${currentIndex}` : undefined}\n ref={optionsRef}\n >\n {React.Children.map(children, (child, index) => (\n <li className={styles.dropdown__input} role=\"option\" id={`${optionIdPrefix}-${index}`}>\n {React.cloneElement(child as React.ReactElement, { ref: inputRefList.current?.[index] })}\n </li>\n ))}\n </ul>\n {!noCloseButton && (\n <div className={styles.dropdown__close}>\n <Button onClick={handleClose} fluid aria-expanded={isOpen}>\n {closeText}\n </Button>\n </div>\n )}\n </div>\n </div>\n );\n};\n\nexport default Dropdown;\n"],"names":["DropdownMode","Dropdown","props","label","placeholder","closeText","noCloseButton","onToggle","open","children","mode","transparent","fluid","testId","disabled","dropdownRef","useRef","optionsRef","buttonRef","isHovered","useHover","isOpen","toggleIsOpen","useToggle","inputRefList","React","currentIndex","setCurrentIndex","useState","buttonWidth","useResizeObserver","labelId","useUuid","toggleLabelId","optionIdPrefix","handleOpen","_a","handleClose","useKeyboardEvent","event","KeyboardEventKey","index","x","nextIndex","useOutsideEvent","toggleClasses","classNames","styles","contentClasses","AnalyticsId","Icon","theme","PlusSmall","IconSize","child","Button"],"mappings":"qmCAuBY,IAAAA,GAAAA,IACVA,EAAA,QAAU,UACVA,EAAA,OAAS,SACTA,EAAA,YAAc,cACdA,EAAA,SAAW,WAJDA,IAAAA,GAAA,CAAA,CAAA,EAkCZ,MAAMC,GAA6CC,GAAA,CAC3C,KAAA,CACJ,MAAAC,EACA,YAAAC,EACA,UAAAC,EAAY,OACZ,cAAAC,EAAgB,GAChB,SAAAC,EACA,KAAAC,EAAO,GACP,SAAAC,EACA,KAAAC,EAAO,UACP,YAAAC,EAAc,GACd,MAAAC,EAAQ,GACR,OAAAC,EACA,SAAAC,CACE,EAAAZ,EACEa,EAAcC,EAAuB,IAAI,EACzCC,EAAaD,EAAyB,IAAI,EAC1C,CAAE,SAAUE,EAAW,UAAAC,GAAcC,E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AAuB,OAAOL,EAAiB,IAAc,GAAGQ,KAAkBR,IAAiB,OACnG,IAAKT,CAAA,EAEJQ,EAAM,SAAS,IAAIhB,EAAU,CAAC6C,EAAOb,IACnC,OAAA,OAAAhB,EAAA,cAAA,KAAA,CAAG,UAAWsB,EAAO,gBAAiB,KAAK,SAAS,GAAI,GAAGb,KAAkBO,GAAA,EAC3EhB,EAAM,aAAa6B,EAA6B,CAAE,KAAKlB,EAAAZ,EAAa,UAAb,YAAAY,EAAuBK,EAAO,CAAC,CACzF,EACD,CACH,EACC,CAACnC,GACCmB,EAAA,cAAA,MAAA,CAAI,UAAWsB,EAAO,eAAA,EACpBtB,EAAA,cAAA8B,EAAA,CAAO,QAASlB,EAAa,MAAK,GAAC,gBAAehB,CAAA,EAChDhB,CACH,CACF,CAEJ,CACF,CAEJ"}
|
|
@@ -18,14 +18,16 @@ interface DuolistProps {
|
|
|
18
18
|
className?: string;
|
|
19
19
|
/** Sets the data-testid attribute. */
|
|
20
20
|
testId?: string;
|
|
21
|
+
/** Width of the description column in percentage */
|
|
22
|
+
descriptionWidth?: number;
|
|
21
23
|
}
|
|
22
24
|
interface DuolistGroupProps {
|
|
23
25
|
/** Determines which column is bold */
|
|
24
26
|
boldColumn?: BoldColumn;
|
|
25
|
-
/** Sets
|
|
26
|
-
description:
|
|
27
|
-
/** Sets
|
|
28
|
-
term:
|
|
27
|
+
/** Sets content of the <dd> tag. */
|
|
28
|
+
description: React.ReactNode;
|
|
29
|
+
/** Sets content of the <dt> tag. */
|
|
30
|
+
term: React.ReactNode;
|
|
29
31
|
}
|
|
30
32
|
export declare const DuolistGroup: React.FC<DuolistGroupProps>;
|
|
31
33
|
export declare const Duolist: React.FC<DuolistProps>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Duolist.d.ts","sourceRoot":"","sources":["../../../src/components/Duolist/Duolist.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAK1B,OAAO,EAAE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AM,CAAC;IACnB,sCAAsC;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,oDAAoD;IACpD,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,UAAU,iBAAiB;IACzB,sCAAsC;IACtC,UAAU,CAAC,EAAE,UAAU,CAAC;IACxB,oCAAoC;IACpC,WAAW,EAAE,KAAK,CAAC,SAAS,CAAC;IAC7B,oCAAoC;IACpC,IAAI,EAAE,KAAK,CAAC,SAAS,CAAC;CACvB;AAED,eAAO,MAAM,YAAY,EAAE,KAAK,CAAC,EAAE,CAAC,iBAAiB,CAcpD,CAAC;AAEF,eAAO,MAAM,OAAO,EAAE,KAAK,CAAC,EAAE,CAAC,YAAY,CAyC1C,CAAC;AAEF,eAAe,OAAO,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"props":{"boldColumn":{"defaultValue":null,"description":"Determines which column is bold","name":"boldColumn","parent":{"fileName":"src/components/Duolist/Duolist.tsx","name":"DuolistGroupProps"},"declarations":[{"fileName":"src/components/Duolist/Duolist.tsx","name":"DuolistGroupProps"}],"required":false,"type":{"name":"enum","raw":"BoldColumn","value":[{"value":"\"first\""},{"value":"\"second\""}]}},"description":{"defaultValue":null,"description":"Sets
|
|
1
|
+
{"props":{"boldColumn":{"defaultValue":null,"description":"Determines which column is bold","name":"boldColumn","parent":{"fileName":"src/components/Duolist/Duolist.tsx","name":"DuolistGroupProps"},"declarations":[{"fileName":"src/components/Duolist/Duolist.tsx","name":"DuolistGroupProps"}],"required":false,"type":{"name":"enum","raw":"BoldColumn","value":[{"value":"\"first\""},{"value":"\"second\""}]}},"description":{"defaultValue":null,"description":"Sets content of the <dd> tag.","name":"description","parent":{"fileName":"src/components/Duolist/Duolist.tsx","name":"DuolistGroupProps"},"declarations":[{"fileName":"src/components/Duolist/Duolist.tsx","name":"DuolistGroupProps"}],"required":true,"type":{"name":"ReactNode"}},"term":{"defaultValue":null,"description":"Sets content of the <dt> tag.","name":"term","parent":{"fileName":"src/components/Duolist/Duolist.tsx","name":"DuolistGroupProps"},"declarations":[{"fileName":"src/components/Duolist/Duolist.tsx","name":"DuolistGroupProps"}],"required":true,"type":{"name":"ReactNode"}}}}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import t from"react";import
|
|
1
|
+
import t from"react";import l from"classnames";import e from"./styles.module.scss";import{AnalyticsId as g}from"../../constants.js";import{S as h}from"../../Spacer.js";import"../Spacer/styles.module.scss";const x=r=>{const{boldColumn:a="first",description:d,term:o}=r,s=a==="first",n=l(e.duolist__dt,{[e["duolist__dt--bold"]]:s}),i=l(e.duolist__dd,{[e["duolist__dd--bold"]]:!s});return t.createElement(t.Fragment,null,t.createElement("dt",{className:n},o),t.createElement("dd",{className:i},d))},G=r=>{const{boldColumn:a,border:d="no-border",descriptionWidth:o,label:s,variant:n="normal",children:i,className:f,testId:C}=r,m=d==="border",c=n==="line",E=m&&(s||c),N=l(e["duolist-wrapper"],{[e["duolist-wrapper--border"]]:m,[e["duolist-wrapper--extra-padding-top"]]:E},f),_=l(e.duolist,{[e["duolist--line"]]:c}),y=o?o+"%":"minmax(60%, 1fr)";return t.createElement("div",{className:N,"data-testid":C,"data-analyticsid":g.Duolist},s&&t.createElement(t.Fragment,null,s,t.createElement(h,null)),t.createElement("dl",{style:{gridTemplateColumns:`auto ${y}`},className:_},t.Children.map(i,u=>{var b;const p=u;if(p.type===x)return t.cloneElement(u,{boldColumn:(b=p.props.boldColumn)!=null?b:a})})))};export{G as Duolist,x as DuolistGroup,G as default};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/components/Duolist/Duolist.tsx"],"sourcesContent":["import React from 'react';\nimport classNames from 'classnames';\n\nimport duolistStyles from './styles.module.scss';\nimport { AnalyticsId } from '../../constants';\nimport { TitleProps } from '../Title';\nimport Spacer from '../Spacer';\n\nexport type DuolistVariants = 'normal' | 'line';\nexport type BoldColumn = 'first' | 'second';\nexport type Border = 'no-border' | 'border';\n\ninterface DuolistProps {\n /** Determines which column is bold */\n boldColumn?: BoldColumn;\n /** Label of the Duolist */\n border?: Border;\n /** Label of the Duolist */\n label?: TitleProps;\n /** Sets the visual variant of the Duolist. */\n variant?: DuolistVariants;\n /** Sets the content of the Duolist. */\n children: React.ReactNode;\n /** Adds custom classes to the element. */\n className?: string;\n /** Sets the data-testid attribute. */\n testId?: string;\n}\n\ninterface DuolistGroupProps {\n /** Determines which column is bold */\n boldColumn?: BoldColumn;\n /** Sets
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/components/Duolist/Duolist.tsx"],"sourcesContent":["import React from 'react';\nimport classNames from 'classnames';\n\nimport duolistStyles from './styles.module.scss';\nimport { AnalyticsId } from '../../constants';\nimport { TitleProps } from '../Title';\nimport Spacer from '../Spacer';\n\nexport type DuolistVariants = 'normal' | 'line';\nexport type BoldColumn = 'first' | 'second';\nexport type Border = 'no-border' | 'border';\n\ninterface DuolistProps {\n /** Determines which column is bold */\n boldColumn?: BoldColumn;\n /** Label of the Duolist */\n border?: Border;\n /** Label of the Duolist */\n label?: TitleProps;\n /** Sets the visual variant of the Duolist. */\n variant?: DuolistVariants;\n /** Sets the content of the Duolist. */\n children: React.ReactNode;\n /** Adds custom classes to the element. */\n className?: string;\n /** Sets the data-testid attribute. */\n testId?: string;\n /** Width of the description column in percentage */\n descriptionWidth?: number;\n}\n\ninterface DuolistGroupProps {\n /** Determines which column is bold */\n boldColumn?: BoldColumn;\n /** Sets content of the <dd> tag. */\n description: React.ReactNode;\n /** Sets content of the <dt> tag. */\n term: React.ReactNode;\n}\n\nexport const DuolistGroup: React.FC<DuolistGroupProps> = props => {\n const { boldColumn = 'first', description, term } = props;\n\n const firstBold = boldColumn === 'first';\n\n const dtClassNames = classNames(duolistStyles['duolist__dt'], { [duolistStyles['duolist__dt--bold']]: firstBold });\n const ddClassNames = classNames(duolistStyles['duolist__dd'], { [duolistStyles['duolist__dd--bold']]: !firstBold });\n\n return (\n <>\n <dt className={dtClassNames}>{term}</dt>\n <dd className={ddClassNames}>{description}</dd>\n </>\n );\n};\n\nexport const Duolist: React.FC<DuolistProps> = props => {\n const { boldColumn, border = 'no-border', descriptionWidth, label, variant = 'normal', children, className, testId } = props;\n\n const hasBorder = border === 'border';\n const hasLines = variant === 'line';\n const extraPaddingTop = hasBorder && (label || hasLines);\n\n const duolistWrapperClasses = classNames(\n duolistStyles['duolist-wrapper'],\n {\n [duolistStyles['duolist-wrapper--border']]: hasBorder,\n [duolistStyles['duolist-wrapper--extra-padding-top']]: extraPaddingTop,\n },\n className\n );\n\n const duolistClasses = classNames(duolistStyles.duolist, {\n [duolistStyles['duolist--line']]: hasLines,\n });\n const duolistColumnStyle = descriptionWidth ? descriptionWidth + '%' : 'minmax(60%, 1fr)';\n\n return (\n <div className={duolistWrapperClasses} data-testid={testId} data-analyticsid={AnalyticsId.Duolist}>\n {label && (\n <>\n {label}\n <Spacer />\n </>\n )}\n <dl style={{ gridTemplateColumns: `auto ${duolistColumnStyle}` }} className={duolistClasses}>\n {React.Children.map(children, (child: React.ReactNode | React.ReactElement<DuolistGroupProps>) => {\n const duolistGroup = child as React.ReactElement<DuolistGroupProps>;\n if (duolistGroup.type === DuolistGroup) {\n return React.cloneElement(child as React.ReactElement<DuolistGroupProps>, {\n boldColumn: duolistGroup.props.boldColumn ?? boldColumn,\n });\n }\n })}\n </dl>\n </div>\n );\n};\n\nexport default Duolist;\n"],"names":["DuolistGroup","props","boldColumn","description","term","firstBold","dtClassNames","classNames","duolistStyles","ddClassNames","React","Duolist","border","descriptionWidth","label","variant","children","className","testId","hasBorder","hasLines","extraPaddingTop","duolistWrapperClasses","duolistClasses","duolistColumnStyle","AnalyticsId","Spacer","child","duolistGroup","_a"],"mappings":"6MAwCO,MAAMA,EAAqDC,GAAA,CAChE,KAAM,CAAE,WAAAC,EAAa,QAAS,YAAAC,EAAa,KAAAC,GAASH,EAE9CI,EAAYH,IAAe,QAE3BI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|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import n,{useState as O,useRef as b,useEffect as h}from"react";import{Icon as g}from"../Icons/Icon.js";import{ZIndex as P,AnalyticsId as k,IconSize as f}from"../../constants.js";import{useHover as U}from"../../hooks/useHover.js";import{usePrevious as Z}from"../../hooks/usePrevious.js";import e from"./styles.module.scss";import s from"classnames";import $ from"../Icons/ChevronDown.js";import S from"../Icons/ChevronUp.js";import{B as j}from"../../Button.js";import{useSticky as q}from"../../hooks/useSticky.js";import"../../hooks/useUuid.js";import"../../uuid.js";import"../../theme/currys/color.js";import"../../theme/index.js";import"../../theme/palette.js";import"../../theme/spacers.js";import"../../theme/grid.js";import"../../hooks/useIcons.js";import"../../hooks/useBreakpoint.js";import"../Button/styles.module.scss";import"../Icons/ArrowRight.js";import"../../hooks/useSize.js";import"../../debounce.js";import"../../hooks/useLayoutEvent.js";var F=(o=>(o.small="small",o.large="large",o))(F||{});const
|
|
1
|
+
import n,{useState as O,useRef as b,useEffect as h}from"react";import{Icon as g}from"../Icons/Icon.js";import{ZIndex as P,AnalyticsId as k,IconSize as f}from"../../constants.js";import{useHover as U}from"../../hooks/useHover.js";import{usePrevious as Z}from"../../hooks/usePrevious.js";import e from"./styles.module.scss";import s from"classnames";import $ from"../Icons/ChevronDown.js";import S from"../Icons/ChevronUp.js";import{B as j}from"../../Button.js";import{useSticky as q}from"../../hooks/useSticky.js";import"../../hooks/useUuid.js";import"../../uuid.js";import"../../utils/environment.js";import"../../theme/currys/color.js";import"../../theme/index.js";import"../../theme/palette.js";import"../../theme/spacers.js";import"../../theme/grid.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"../../hooks/useLayoutEvent.js";var F=(o=>(o.small="small",o.large="large",o))(F||{});const Ee=o=>{const{title:u,children:z,size:r="small",color:v,svgIcon:i,expanded:d=!1,noNestedLine:w=!1,sticky:R=!1,testId:E,onExpand:c,renderChildrenWhenClosed:W=!1}=o,[t,m]=O(d),B=Z(t),y=b(null),l=b(null),{isHovered:_}=U(l),{isOutsideWindow:H,isLeavingWindow:p,offsetHeight:I,contentWidth:C}=q(y,l),a=R&&t&&H;h(()=>{d!==t&&m(d)},[d]),h(()=>{c&&t!==!!B&&c(t)},[t,c]);const N=x=>n.createElement("span",{className:s(e.expander__icon,e[`expander__icon--${x}`])},n.createElement(g,{svgIcon:t?S:$,size:f.XSmall,isHovered:_})),T=s(e.expander__trigger,e[`expander__trigger--${r}`],r==="large"&&e[`expander__trigger--${v||"neutral"}`],r==="large"&&i&&e["expander__trigger--icon"],t&&e["expander__trigger--expanded"],a&&!p&&e["expander__trigger--sticky"],a&&p&&e["expander__trigger--absolute"]),X=()=>n.createElement("button",{type:"button",className:T,style:{zIndex:_||a?P.ExpanderTrigger:void 0,width:a&&C?`${C}px`:void 0},"aria-expanded":t,ref:l,onClick:()=>m(!t),"data-testid":E,"data-analyticsid":k.Expander},r==="small"&&N("left"),i&&n.createElement("span",{className:s(e.expander__icon,e["expander__icon--left"])},n.createElement(g,{svgIcon:i,size:f.XSmall,isHovered:_})),u,r==="large"&&N("right")),L=s(e.expander__button,t&&e["expander__button--expanded"],a&&!p&&e["expander__button--sticky"],a&&p&&e["expander__button--absolute"]),A=()=>n.createElement(j,{variant:"borderless",className:L,"aria-expanded":t,ref:l,onClick:()=>m(!t),testId:E,"data-analyticsid":k.Expander},n.createElement(g,{svgIcon:t?S:$,size:f.XSmall}),u),D=()=>{if(!W&&!t)return null;const x=s(e.expander__content,e[`expander__content--${r}`],r==="large"&&e[`expander__content--${v||"neutral"}`],r==="large"&&i&&e["expander__content--icon"],t&&e["expander__content--expanded"],r==="small"&&!w&&e["expander__content--nested-line"]);return n.createElement("div",{className:x},z)};return n.createElement("div",{className:e.expander,ref:y,style:{paddingTop:a&&I?`${I}px`:void 0}},r==="large"?X():A(),D())};export{F as ExpanderSize,Ee as default};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/components/Expander/Expander.tsx"],"sourcesContent":["import React, { useState, useRef, useEffect } from 'react';\nimport Icon, { IconSize, SvgIcon } from '../Icons';\nimport { useHover } from '../../hooks/useHover';\nimport { usePrevious } from '../../hooks/usePrevious';\nimport { PaletteNames } from '../../theme/palette';\n\nimport styles from './styles.module.scss';\nimport classNames from 'classnames';\nimport ChevronDown from '../Icons/ChevronDown';\nimport ChevronUp from '../Icons/ChevronUp';\nimport Button from '../Button';\nimport { useSticky } from '../../hooks/useSticky';\nimport { AnalyticsId, ZIndex } from '../../constants';\n\nexport enum ExpanderSize {\n small = 'small',\n large = 'large',\n}\n\nexport type ExpanderColors = Extract<PaletteNames, 'banana' | 'blueberry' | 'cherry' | 'kiwi' | 'neutral' | 'plum' | 'white'>;\n\ninterface ExpanderProps {\n /** Sets the trigger title */\n title: string;\n /** Sets the expanded content */\n children?: React.ReactNode;\n /** Sets the size of the expander. Default: ExpanderSize.small */\n size?: ExpanderSize;\n /** Sets the background of the expander. Requires size=ExpanderSize.large. */\n color?: ExpanderColors;\n /** Adds an icon to the expander trigger. Requires size=ExpanderSize.large. */\n svgIcon?: SvgIcon;\n /** Opens or closes the expander */\n expanded?: boolean;\n /** Removes border to the left of the content. Requires size=ExpanderSize.small. */\n noNestedLine?: boolean;\n /** Stick expander trigger to top of screen while scrolling down */\n sticky?: boolean;\n /** Called when expander is open/closed. */\n onExpand?: (isExpanded: boolean) => void;\n /** Whether to render children when closed (in which case they are hidden with CSS). Default: false */\n renderChildrenWhenClosed?: boolean;\n /** Sets the data-testid attribute on the expander button. */\n testId?: string;\n}\n\nconst Expander: React.FC<ExpanderProps> = props => {\n const {\n title,\n children,\n size = ExpanderSize.small,\n color,\n svgIcon: icon,\n expanded = false,\n noNestedLine = false,\n sticky = false,\n testId,\n onExpand,\n renderChildrenWhenClosed = false,\n } = props;\n const [isExpanded, setIsExpanded] = useState<boolean>(expanded);\n const previousIsExpanded = usePrevious(isExpanded);\n const expanderRef = useRef<HTMLDivElement>(null);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const { isHovered } = useHover(triggerRef);\n const { isOutsideWindow, isLeavingWindow, offsetHeight, contentWidth } = useSticky(expanderRef, triggerRef);\n\n const isSticky = sticky && isExpanded && isOutsideWindow;\n\n useEffect(() => {\n if (expanded !== isExpanded) {\n setIsExpanded(expanded);\n }\n }, [expanded]);\n\n useEffect(() => {\n if (onExpand && isExpanded !== !!previousIsExpanded) {\n onExpand(isExpanded);\n }\n }, [isExpanded, onExpand]);\n\n const renderChevron = (align: 'left' | 'right') => (\n <span className={classNames(styles['expander__icon'], styles[`expander__icon--${align}`])}>\n <Icon svgIcon={isExpanded ? ChevronUp : ChevronDown} size={IconSize.XSmall} isHovered={isHovered} />\n </span>\n );\n\n const triggerClassName = classNames(\n styles['expander__trigger'],\n styles[`expander__trigger--${size}`],\n size === ExpanderSize.large && styles[`expander__trigger--${color || 'neutral'}`],\n size === ExpanderSize.large && icon && styles['expander__trigger--icon'],\n isExpanded && styles['expander__trigger--expanded'],\n isSticky && !isLeavingWindow && styles['expander__trigger--sticky'],\n isSticky && isLeavingWindow && styles['expander__trigger--absolute']\n );\n\n const renderTrigger = () => (\n <button\n type=\"button\"\n className={triggerClassName}\n style={{\n zIndex: isHovered || isSticky ? ZIndex.ExpanderTrigger : undefined,\n width: isSticky && contentWidth ? `${contentWidth}px` : undefined,\n }}\n aria-expanded={isExpanded}\n ref={triggerRef}\n onClick={() => setIsExpanded(!isExpanded)}\n data-testid={testId}\n data-analyticsid={AnalyticsId.Expander}\n >\n {size === ExpanderSize.small && renderChevron('left')}\n {icon && (\n <span className={classNames(styles['expander__icon'], styles['expander__icon--left'])}>\n <Icon svgIcon={icon} size={IconSize.XSmall} isHovered={isHovered} />\n </span>\n )}\n {title}\n {size === ExpanderSize.large && renderChevron('right')}\n </button>\n );\n\n const buttonClassName = classNames(\n styles['expander__button'],\n isExpanded && styles['expander__button--expanded'],\n isSticky && !isLeavingWindow && styles['expander__button--sticky'],\n isSticky && isLeavingWindow && styles['expander__button--absolute']\n );\n\n const renderButton = () => (\n <Button\n variant=\"borderless\"\n className={buttonClassName}\n aria-expanded={isExpanded}\n ref={triggerRef}\n onClick={() => setIsExpanded(!isExpanded)}\n testId={testId}\n data-analyticsid={AnalyticsId.Expander}\n >\n <Icon svgIcon={isExpanded ? ChevronUp : ChevronDown} size={IconSize.XSmall} />\n {title}\n </Button>\n );\n\n const renderContent = () => {\n if (!renderChildrenWhenClosed && !isExpanded) {\n return null;\n }\n\n const contentClassName = classNames(\n styles['expander__content'],\n styles[`expander__content--${size}`],\n size === ExpanderSize.large && styles[`expander__content--${color || 'neutral'}`],\n size === ExpanderSize.large && icon && styles['expander__content--icon'],\n isExpanded && styles['expander__content--expanded'],\n size === ExpanderSize.small && !noNestedLine && styles['expander__content--nested-line']\n );\n\n return <div className={contentClassName}>{children}</div>;\n };\n\n return (\n <div\n className={styles['expander']}\n ref={expanderRef}\n style={{ paddingTop: isSticky && offsetHeight ? `${offsetHeight}px` : undefined }}\n >\n {size === ExpanderSize.large ? renderTrigger() : renderButton()}\n {renderContent()}\n </div>\n );\n};\n\nexport default Expander;\n"],"names":["ExpanderSize","Expander","props","title","children","size","color","icon","expanded","noNestedLine","sticky","testId","onExpand","renderChildrenWhenClosed","isExpanded","setIsExpanded","useState","previousIsExpanded","usePrevious","expanderRef","useRef","triggerRef","isHovered","useHover","isOutsideWindow","isLeavingWindow","offsetHeight","contentWidth","useSticky","isSticky","useEffect","renderChevron","align","React","classNames","styles","Icon","ChevronUp","ChevronDown","IconSize","triggerClassName","renderTrigger","ZIndex","AnalyticsId","buttonClassName","renderButton","Button","renderContent","contentClassName"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/components/Expander/Expander.tsx"],"sourcesContent":["import React, { useState, useRef, useEffect } from 'react';\nimport Icon, { IconSize, SvgIcon } from '../Icons';\nimport { useHover } from '../../hooks/useHover';\nimport { usePrevious } from '../../hooks/usePrevious';\nimport { PaletteNames } from '../../theme/palette';\n\nimport styles from './styles.module.scss';\nimport classNames from 'classnames';\nimport ChevronDown from '../Icons/ChevronDown';\nimport ChevronUp from '../Icons/ChevronUp';\nimport Button from '../Button';\nimport { useSticky } from '../../hooks/useSticky';\nimport { AnalyticsId, ZIndex } from '../../constants';\n\nexport enum ExpanderSize {\n small = 'small',\n large = 'large',\n}\n\nexport type ExpanderColors = Extract<PaletteNames, 'banana' | 'blueberry' | 'cherry' | 'kiwi' | 'neutral' | 'plum' | 'white'>;\n\ninterface ExpanderProps {\n /** Sets the trigger title */\n title: string;\n /** Sets the expanded content */\n children?: React.ReactNode;\n /** Sets the size of the expander. Default: ExpanderSize.small */\n size?: ExpanderSize;\n /** Sets the background of the expander. Requires size=ExpanderSize.large. */\n color?: ExpanderColors;\n /** Adds an icon to the expander trigger. Requires size=ExpanderSize.large. */\n svgIcon?: SvgIcon;\n /** Opens or closes the expander */\n expanded?: boolean;\n /** Removes border to the left of the content. Requires size=ExpanderSize.small. */\n noNestedLine?: boolean;\n /** Stick expander trigger to top of screen while scrolling down */\n sticky?: boolean;\n /** Called when expander is open/closed. */\n onExpand?: (isExpanded: boolean) => void;\n /** Whether to render children when closed (in which case they are hidden with CSS). Default: false */\n renderChildrenWhenClosed?: boolean;\n /** Sets the data-testid attribute on the expander button. */\n testId?: string;\n}\n\nconst Expander: React.FC<ExpanderProps> = props => {\n const {\n title,\n children,\n size = ExpanderSize.small,\n color,\n svgIcon: icon,\n expanded = false,\n noNestedLine = false,\n sticky = false,\n testId,\n onExpand,\n renderChildrenWhenClosed = false,\n } = props;\n const [isExpanded, setIsExpanded] = useState<boolean>(expanded);\n const previousIsExpanded = usePrevious(isExpanded);\n const expanderRef = useRef<HTMLDivElement>(null);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const { isHovered } = useHover(triggerRef);\n const { isOutsideWindow, isLeavingWindow, offsetHeight, contentWidth } = useSticky(expanderRef, triggerRef);\n\n const isSticky = sticky && isExpanded && isOutsideWindow;\n\n useEffect(() => {\n if (expanded !== isExpanded) {\n setIsExpanded(expanded);\n }\n }, [expanded]);\n\n useEffect(() => {\n if (onExpand && isExpanded !== !!previousIsExpanded) {\n onExpand(isExpanded);\n }\n }, [isExpanded, onExpand]);\n\n const renderChevron = (align: 'left' | 'right') => (\n <span className={classNames(styles['expander__icon'], styles[`expander__icon--${align}`])}>\n <Icon svgIcon={isExpanded ? ChevronUp : ChevronDown} size={IconSize.XSmall} isHovered={isHovered} />\n </span>\n );\n\n const triggerClassName = classNames(\n styles['expander__trigger'],\n styles[`expander__trigger--${size}`],\n size === ExpanderSize.large && styles[`expander__trigger--${color || 'neutral'}`],\n size === ExpanderSize.large && icon && styles['expander__trigger--icon'],\n isExpanded && styles['expander__trigger--expanded'],\n isSticky && !isLeavingWindow && styles['expander__trigger--sticky'],\n isSticky && isLeavingWindow && styles['expander__trigger--absolute']\n );\n\n const renderTrigger = () => (\n <button\n type=\"button\"\n className={triggerClassName}\n style={{\n zIndex: isHovered || isSticky ? ZIndex.ExpanderTrigger : undefined,\n width: isSticky && contentWidth ? `${contentWidth}px` : undefined,\n }}\n aria-expanded={isExpanded}\n ref={triggerRef}\n onClick={() => setIsExpanded(!isExpanded)}\n data-testid={testId}\n data-analyticsid={AnalyticsId.Expander}\n >\n {size === ExpanderSize.small && renderChevron('left')}\n {icon && (\n <span className={classNames(styles['expander__icon'], styles['expander__icon--left'])}>\n <Icon svgIcon={icon} size={IconSize.XSmall} isHovered={isHovered} />\n </span>\n )}\n {title}\n {size === ExpanderSize.large && renderChevron('right')}\n </button>\n );\n\n const buttonClassName = classNames(\n styles['expander__button'],\n isExpanded && styles['expander__button--expanded'],\n isSticky && !isLeavingWindow && styles['expander__button--sticky'],\n isSticky && isLeavingWindow && styles['expander__button--absolute']\n );\n\n const renderButton = () => (\n <Button\n variant=\"borderless\"\n className={buttonClassName}\n aria-expanded={isExpanded}\n ref={triggerRef}\n onClick={() => setIsExpanded(!isExpanded)}\n testId={testId}\n data-analyticsid={AnalyticsId.Expander}\n >\n <Icon svgIcon={isExpanded ? ChevronUp : ChevronDown} size={IconSize.XSmall} />\n {title}\n </Button>\n );\n\n const renderContent = () => {\n if (!renderChildrenWhenClosed && !isExpanded) {\n return null;\n }\n\n const contentClassName = classNames(\n styles['expander__content'],\n styles[`expander__content--${size}`],\n size === ExpanderSize.large && styles[`expander__content--${color || 'neutral'}`],\n size === ExpanderSize.large && icon && styles['expander__content--icon'],\n isExpanded && styles['expander__content--expanded'],\n size === ExpanderSize.small && !noNestedLine && styles['expander__content--nested-line']\n );\n\n return <div className={contentClassName}>{children}</div>;\n };\n\n return (\n <div\n className={styles['expander']}\n ref={expanderRef}\n style={{ paddingTop: isSticky && offsetHeight ? `${offsetHeight}px` : undefined }}\n >\n {size === ExpanderSize.large ? renderTrigger() : renderButton()}\n {renderContent()}\n </div>\n );\n};\n\nexport default Expander;\n"],"names":["ExpanderSize","Expander","props","title","children","size","color","icon","expanded","noNestedLine","sticky","testId","onExpand","renderChildrenWhenClosed","isExpanded","setIsExpanded","useState","previousIsExpanded","usePrevious","expanderRef","useRef","triggerRef","isHovered","useHover","isOutsideWindow","isLeavingWindow","offsetHeight","contentWidth","useSticky","isSticky","useEffect","renderChevron","align","React","classNames","styles","Icon","ChevronUp","ChevronDown","IconSize","triggerClassName","renderTrigger","ZIndex","AnalyticsId","buttonClassName","renderButton","Button","renderContent","contentClassName"],"mappings":"k+BAcY,IAAAA,GAAAA,IACVA,EAAA,MAAQ,QACRA,EAAA,MAAQ,QAFEA,IAAAA,GAAA,CAAA,CAAA,EAgCZ,MAAMC,GAA6CC,GAAA,CAC3C,KAAA,CACJ,MAAAC,EACA,SAAAC,EACA,KAAAC,EAAO,QACP,MAAAC,EACA,QAASC,EACT,SAAAC,EAAW,GACX,aAAAC,EAAe,GACf,OAAAC,EAAS,GACT,OAAAC,EACA,SAAAC,EACA,yBAAAC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CAEJ"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import r,{useState as
|
|
1
|
+
import r,{useState as A,useRef as V,useEffect as _}from"react";import{Icon as Z}from"../Icons/Icon.js";import{AnalyticsId as P,ZIndex as q,IconSize as T}from"../../constants.js";import F from"../Icons/ChevronUp.js";import G from"../Icons/ChevronDown.js";import{useHover as K}from"../../hooks/useHover.js";import{usePrevious as M}from"../../hooks/usePrevious.js";import{useBreakpoint as Q,Breakpoint as Y}from"../../hooks/useBreakpoint.js";import{isElementInViewport as v}from"../../utils/viewport.js";import x from"classnames";import t from"./styles.module.scss";import{useUuid as S}from"../../hooks/useUuid.js";import{useSticky as ee}from"../../hooks/useSticky.js";import{mergeRefs as ne}from"../../utils/refs.js";import"../../uuid.js";import"../../utils/environment.js";import"../../theme/grid.js";import"../../hooks/useLayoutEvent.js";import"../../utils/debounce.js";const H=r.forwardRef((c,I)=>{const{id:p,children:N,padding:w=!0,color:f="neutral",className:L="",icon:g,large:b=!1,title:d,expanded:m=!1,sticky:R,testId:$,handleExpanderClick:W,onExpand:o,renderChildrenWhenClosed:u}=c,[i,j]=A(m),y=M(i),h=V(null),E=V(null),{isHovered:k}=K(E),z=Q(),{isOutsideWindow:C,isLeavingWindow:n,offsetHeight:e,contentWidth:s}=ee(h,E),a=R&&i&&C,l=typeof d=="object",B=x(L,{[t["expander-list__item--jsx"]]:l}),U=x(t["expander-list-link"],t[`expander-list-link--${f}`],{[t["expander-list-link--closed"]]:!i,[t["expander-list-link--large"]]:b,[t["expander-list-link--jsx"]]:l,[t["expander-list-link--sticky"]]:a&&!n,[t["expander-list-link--absolute"]]:a&&n}),X=x(t["expander-list-link__title"],{[t["expander-list-link__title--string"]]:!l,[t["expander-list-link__title--jsx"]]:l});_(()=>{m!==i&&j(m)},[m]),_(()=>{o&&i!==!!y&&o(i)},[i,o]);const D=()=>{if(!u&&!i)return null;const J=x(t["expander-list-link__main-content"],i&&t["expander-list-link__main-content--expanded"],w?t["expander-list-link__main-content--padding"]:"");return r.createElement("div",{className:J},N)};return r.createElement("li",{className:B,ref:ne([I,h]),style:{paddingTop:a&&e?`${e}px`:void 0}},r.createElement("button",{type:"button",id:p,onClick:W,"data-testid":$,"data-analyticsid":P.ExpanderListExpander,className:U,ref:E,"aria-expanded":i,style:{zIndex:k||a?q.ExpanderTrigger:void 0,width:a&&s?`${s}px`:void 0}},g&&r.createElement("span",{className:t["expander-list-link__icon"]},r.cloneElement(g,{size:z===Y.xs?T.XSmall:T.Small,isHovered:k})),r.createElement("span",{className:X},d),r.createElement("span",{className:t["expander-list-link__chevron"]},r.createElement(Z,{size:T.XSmall,svgIcon:i?F:G,isHovered:k}))),D())}),O=c=>r.isValidElement(c)&&c.type===H,te=r.forwardRef((c,I)=>{const{children:p,childPadding:N=!0,large:w,isOpen:f=!1,renderChildrenWhenClosed:L=!1,color:g,className:b="",accordion:d=!1,topBorder:m=!0,bottomBorder:R=!0,sticky:$=!1,testId:W}=c,[o,u]=A(),[i,j]=A(),y=S(),h=r.Children.count(p),E=x(t["expander-list"],b);function k(n,e){u(s=>d?{[e]:!(s!=null&&s[e])}:{...s,[e]:!(s!=null&&s[e])}),j(n.currentTarget)}const z=n=>x(t["expander-list__item"],{[t["expander-list__item--top"]]:n===0&&m,[t["expander-list__item--no-bottom"]]:n===h-1&&!R}),C=n=>`${y}-${n}`;return _(()=>{d&&i&&!v(i)&&i.scrollIntoView()},[d,i]),_(()=>{if(f){const n=C(0);u(e=>d?{[n]:!(e!=null&&e[n])}:{...e,[n]:!(e!=null&&e[n])})}},[f]),_(()=>{var n;if(!f){const e=(n=r.Children.map(p,s=>{if(O(s))return s}))==null?void 0:n.reduce((s,a,l)=>(typeof a.props.expanded<"u"&&(s[C(l)]=a.props.expanded),s),{});u({...o,...e})}},[p]),r.createElement("ul",{className:E,ref:I,"data-testid":W,"data-analyticsid":P.ExpanderList},r.Children.map(p,(n,e)=>{if(O(n)){const s=C(e),a=o==null?void 0:o[s],l=z(e);return r.cloneElement(n,{id:s,key:e,expanded:a,padding:N,color:g,large:w,sticky:$,"aria-expanded":a,className:l,handleExpanderClick:B=>k(B,`${y}-${e}`),renderChildrenWhenClosed:L})}return n}))});te.Expander=H;H.displayName="ExpanderList.Expander";export{te as ExpanderList,te as default};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../src/utils/viewport.ts","../../../src/utils/refs.ts","../../../src/components/ExpanderList/ExpanderList.tsx"],"sourcesContent":["export const isElementInViewport = (el: HTMLElement): boolean => {\n var { top, left, bottom, right } = el.getBoundingClientRect();\n\n return (\n top >= 0 &&\n left >= 0 &&\n bottom <= (window.innerHeight || document.documentElement.clientHeight) &&\n right <= (window.innerWidth || document.documentElement.clientWidth)\n );\n};\n","/**\n * Slår sammen refs fra forwardRef og useRef slik at begge deler kan brukes\n * Fra https://github.com/gregberge/react-merge-refs\n * @param refs array med refs som skal slås sammen\n * @returns refcallback som kan brukes på komponent\n */\nexport const mergeRefs = <T>(refs: Array<React.MutableRefObject<T> | React.LegacyRef<T>>): React.RefCallback<T> => {\n return value => {\n refs.forEach(ref => {\n if (typeof ref === 'function') {\n ref(value);\n } else if (ref != null) {\n (ref as React.MutableRefObject<T | null>).current = value;\n }\n });\n };\n};\n\n/**\n * Sjekker om ref er et objekt (og ikke en funksjon)\n * @param ref\n * @returns type predicate\n */\nexport const isMutableRefObject = <T>(ref: React.ForwardedRef<T>): ref is React.MutableRefObject<T> => {\n return typeof ref !== 'function' && ref !== null;\n};\n","import React, { useEffect, useRef, useState } from 'react';\n\nimport { PaletteNames } from '../../theme/palette';\nimport Icon, { IconSize } from '../Icons';\nimport ChevronUp from '../Icons/ChevronUp';\nimport ChevronDown from '../Icons/ChevronDown';\nimport { useHover } from '../../hooks/useHover';\nimport { usePrevious } from '../../hooks/usePrevious';\nimport { Breakpoint, useBreakpoint } from '../../hooks/useBreakpoint';\nimport { isElementInViewport } from '../../utils/viewport';\n\nimport classNames from 'classnames';\n\nimport expanderListStyles from './styles.module.scss';\nimport { AnalyticsId, ZIndex } from '../../constants';\nimport { useUuid } from '../../hooks/useUuid';\nimport { useSticky } from '../../hooks/useSticky';\n\nimport { mergeRefs } from '../../utils/refs';\n\nexport type ExpanderListColors = PaletteNames;\nexport type ExpanderType = React.ForwardRefExoticComponent<ExpanderProps & React.RefAttributes<HTMLLIElement>>;\n\nexport interface ExpanderListCompound extends React.ForwardRefExoticComponent<ExpanderListProps & React.RefAttributes<HTMLUListElement>> {\n Expander: ExpanderType;\n}\n\ninterface ExpanderListProps {\n /** Toggles accordion functionality for the expanders. */\n accordion?: boolean;\n /** Toggles the bottom border of the last child element. */\n bottomBorder?: boolean;\n /** Items in the ExpanderList */\n children: React.ReactNode;\n /** Toggles padding of child elements */\n childPadding?: boolean;\n /** Adds custom classes to the element. */\n className?: string;\n /** Changes the link list background color on hover. */\n color?: ExpanderListColors;\n /** Changes the font size. */\n large?: boolean;\n /** Opens the first item in the list. */\n /** @deprecated Skal fases ut til fordel for å bruke expanded-prop på første ExpanderList.Expander */\n isOpen?: boolean;\n /** Whether to render children when closed (in which case they are hidden with CSS). Default: false */\n renderChildrenWhenClosed?: boolean;\n /** Toggles the top border of the first child element. */\n topBorder?: boolean;\n /** Stick expander trigger to top of screen while scrolling down */\n sticky?: boolean;\n /** Sets the data-testid attribute. */\n testId?: string;\n}\n\ntype Modify<T, R> = Omit<T, keyof R> & R;\n\ntype ExpanderProps = Modify<\n React.HTMLAttributes<HTMLButtonElement>,\n {\n id?: string;\n title: JSX.Element | string;\n children: React.ReactNode;\n className?: string;\n color?: ExpanderListColors;\n icon?: React.ReactElement;\n padding?: boolean;\n expanded?: boolean;\n large?: boolean;\n testId?: string;\n handleExpanderClick?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;\n /** Called when expander is open/closed. */\n onExpand?: (isExpanded: boolean) => void;\n }\n> &\n Pick<ExpanderListProps, 'renderChildrenWhenClosed' | 'sticky'>;\n\nconst Expander: ExpanderType = React.forwardRef<HTMLLIElement, ExpanderProps>((props, ref) => {\n const {\n id,\n children,\n padding = true,\n color = 'neutral',\n className = '',\n icon,\n large = false,\n title,\n expanded = false,\n sticky,\n testId,\n handleExpanderClick,\n onExpand,\n renderChildrenWhenClosed,\n } = props;\n const [isExpanded, setIsExpanded] = useState<boolean>(expanded);\n const previousIsExpanded = usePrevious(isExpanded);\n const expanderRef = useRef<HTMLLIElement>(null);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const { isHovered } = useHover(triggerRef);\n const breakpoint = useBreakpoint();\n\n const { isOutsideWindow, isLeavingWindow, offsetHeight, contentWidth } = useSticky(expanderRef, triggerRef);\n\n const isSticky = sticky && isExpanded && isOutsideWindow;\n\n const isJsxTitle = typeof title === 'object';\n\n const itemClasses = classNames(className, { [expanderListStyles['expander-list__item--jsx']]: isJsxTitle });\n\n const expanderClasses = classNames(expanderListStyles['expander-list-link'], expanderListStyles[`expander-list-link--${color}`], {\n [expanderListStyles['expander-list-link--closed']]: !isExpanded,\n [expanderListStyles['expander-list-link--large']]: large,\n [expanderListStyles['expander-list-link--jsx']]: isJsxTitle,\n [expanderListStyles['expander-list-link--sticky']]: isSticky && !isLeavingWindow,\n [expanderListStyles['expander-list-link--absolute']]: isSticky && isLeavingWindow,\n });\n\n const titleClasses = classNames(expanderListStyles['expander-list-link__title'], {\n [expanderListStyles['expander-list-link__title--string']]: !isJsxTitle,\n [expanderListStyles['expander-list-link__title--jsx']]: isJsxTitle,\n });\n\n useEffect(() => {\n if (expanded !== isExpanded) {\n setIsExpanded(expanded);\n }\n }, [expanded]);\n\n useEffect(() => {\n if (onExpand && isExpanded !== !!previousIsExpanded) {\n onExpand(isExpanded);\n }\n }, [isExpanded, onExpand]);\n\n const renderContent = () => {\n if (!renderChildrenWhenClosed && !isExpanded) {\n return null;\n }\n\n const mainContentClasses = classNames(\n expanderListStyles['expander-list-link__main-content'],\n isExpanded && expanderListStyles['expander-list-link__main-content--expanded'],\n padding ? expanderListStyles['expander-list-link__main-content--padding'] : ''\n );\n\n return <div className={mainContentClasses}>{children}</div>;\n };\n\n return (\n <li\n className={itemClasses}\n ref={mergeRefs([ref, expanderRef])}\n style={{ paddingTop: isSticky && offsetHeight ? `${offsetHeight}px` : undefined }}\n >\n <button\n type=\"button\"\n id={id}\n onClick={handleExpanderClick}\n data-testid={testId}\n data-analyticsid={AnalyticsId.ExpanderListExpander}\n className={expanderClasses}\n ref={triggerRef}\n aria-expanded={isExpanded}\n style={{\n zIndex: isHovered || isSticky ? ZIndex.ExpanderTrigger : undefined,\n width: isSticky && contentWidth ? `${contentWidth}px` : undefined,\n }}\n >\n {icon && (\n <span className={expanderListStyles['expander-list-link__icon']}>\n {React.cloneElement(icon, {\n size: breakpoint === Breakpoint.xs ? IconSize.XSmall : IconSize.Small,\n isHovered,\n })}\n </span>\n )}\n <span className={titleClasses}>{title}</span>\n <span className={expanderListStyles['expander-list-link__chevron']}>\n <Icon size={IconSize.XSmall} svgIcon={isExpanded ? ChevronUp : ChevronDown} isHovered={isHovered} />\n </span>\n </button>\n {renderContent()}\n </li>\n );\n});\n\ntype ActiveExpander = Record<string, boolean>;\n\nconst isExpanderComponent = (element: {} | null | undefined): element is React.ReactElement<ExpanderProps> =>\n React.isValidElement<ExpanderProps>(element) && (element as React.ReactElement).type === Expander;\n\nexport const ExpanderList = React.forwardRef((props: ExpanderListProps, ref: React.Ref<HTMLUListElement>) => {\n const {\n children,\n childPadding = true,\n large,\n isOpen = false,\n renderChildrenWhenClosed = false,\n color,\n className = '',\n accordion = false,\n topBorder = true,\n bottomBorder = true,\n sticky = false,\n testId,\n } = props;\n const [activeExpander, setActiveExpander] = useState<ActiveExpander>();\n const [latestExpander, setLatestExpander] = useState<HTMLElement>();\n const uuid = useUuid();\n const childCount = React.Children.count(children);\n const expanderListClasses = classNames(expanderListStyles['expander-list'], className);\n\n function handleExpanderClick(event: React.MouseEvent<HTMLElement, MouseEvent>, id: string): void {\n setActiveExpander(prevState => (accordion ? { [id]: !prevState?.[id] } : { ...prevState, [id]: !prevState?.[id] }));\n setLatestExpander(event.currentTarget);\n }\n\n /** Returns the class modifier top when we want to show the top border and no-bottom when we don't want to show the bottom border */\n const getExpanderItemClass = (index: number) => {\n return classNames(expanderListStyles['expander-list__item'], {\n [expanderListStyles['expander-list__item--top']]: index === 0 && topBorder,\n [expanderListStyles['expander-list__item--no-bottom']]: index === childCount - 1 && !bottomBorder,\n });\n };\n\n const getExpanderId = (index: number) => `${uuid}-${index}`;\n\n useEffect(() => {\n if (accordion && latestExpander && !isElementInViewport(latestExpander)) {\n latestExpander.scrollIntoView();\n }\n }, [accordion, latestExpander]);\n\n useEffect(() => {\n if (isOpen) {\n const id = getExpanderId(0);\n setActiveExpander(prevState => (accordion ? { [id]: !prevState?.[id] } : { ...prevState, [id]: !prevState?.[id] }));\n }\n }, [isOpen]);\n\n useEffect(() => {\n if (!isOpen) {\n const newActiveExpander = React.Children.map(children, child => {\n if (isExpanderComponent(child)) {\n return child;\n }\n })?.reduce((acc, child, index) => {\n // Expanded-status skal bare settes dersom prop er satt av den som bruker komponenten\n if (typeof child.props.expanded !== 'undefined') {\n acc[getExpanderId(index)] = child.props.expanded;\n }\n return acc;\n }, {} as ActiveExpander);\n\n setActiveExpander({ ...activeExpander, ...newActiveExpander });\n }\n }, [children]);\n\n return (\n <ul className={expanderListClasses} ref={ref} data-testid={testId} data-analyticsid={AnalyticsId.ExpanderList}>\n {React.Children.map(children, (child, index) => {\n if (isExpanderComponent(child)) {\n const id = getExpanderId(index);\n const expanded = activeExpander?.[id];\n const expanderItemClass = getExpanderItemClass(index);\n\n return React.cloneElement(child as React.ReactElement<ExpanderProps>, {\n id,\n key: index,\n expanded,\n padding: childPadding,\n color,\n large,\n sticky,\n 'aria-expanded': expanded,\n className: expanderItemClass,\n handleExpanderClick: (event: React.MouseEvent<HTMLElement>) => handleExpanderClick(event, `${uuid}-${index}`),\n renderChildrenWhenClosed,\n });\n }\n return child;\n })}\n </ul>\n );\n}) as ExpanderListCompound;\n\nExpanderList.Expander = Expander;\nExpander.displayName = 'ExpanderList.Expander';\n\nexport default ExpanderList;\n"],"names":["isElementInViewport","el","top","left","bottom","right","mergeRefs","refs","value","ref","Expander","React","props","id","children","padding","color","className","icon","large","title","expanded","sticky","testId","handleExpanderClick","onExpand","renderChildrenWhenClosed","isExpanded","setIsExpanded","useState","previousIsExpanded","usePrevious","expanderRef","useRef","triggerRef","isHovered","useHover","breakpoint","useBreakpoint","isOutsideWindow","isLeavingWindow","offsetHeight","contentWidth","useSticky","isSticky","isJsxTitle","itemClasses","classNames","expanderListStyles","expanderClasses","titleClasses","useEffect","renderContent","mainContentClasses","AnalyticsId","ZIndex","Breakpoint","IconSize","Icon","ChevronUp","ChevronDown","isExpanderComponent","element","ExpanderList","childPadding","isOpen","accordion","topBorder","bottomBorder","activeExpander","setActiveExpander","latestExpander","setLatestExpander","uuid","useUuid","childCount","expanderListClasses","event","prevState","getExpanderItemClass","index","getExpanderId","newActiveExpander","_a","child","acc","expanderItemClass"],"mappings":"6sBAAa,MAAAA,GAAuBC,GAA6B,CAC/D,GAAI,CAAE,IAAAC,EAAK,KAAAC,EAAM,OAAAC,EAAQ,MAAAC,GAAUJ,EAAG,wBAEtC,OACEC,GAAO,GACPC,GAAQ,GACRC,IAAW,OAAO,aAAe,SAAS,gBAAgB,eAC1DC,IAAU,OAAO,YAAc,SAAS,gBAAgB,YAE5D,ECHaC,GAAgBC,GACXC,GAAA,CACdD,EAAK,QAAeE,GAAA,CACd,OAAOA,GAAQ,WACjBA,EAAID,CAAK,EACAC,GAAO,OACfA,EAAyC,QAAUD,EACtD,CACD,CAAA,EC+DCE,EAAyBC,EAAM,WAAyC,CAACC,EAAOH,IAAQ,CACtF,KAAA,CACJ,GAAAI,EACA,SAAAC,EACA,QAAAC,EAAU,GACV,MAAAC,EAAQ,UACR,UAAAC,EAAY,GACZ,KAAAC,EACA,MAAAC,EAAQ,GACR,MAAAC,EACA,SAAAC,E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YAAAD,EAItB,OAAO,CAACE,EAAKD,EAAOJ,KAElB,OAAOI,EAAM,MAAM,SAAa,MAClCC,EAAIJ,EAAcD,CAAK,GAAKI,EAAM,MAAM,UAEnCC,GACN,CAAoB,GAEvBf,EAAkB,CAAE,GAAGD,EAAgB,GAAGa,CAAmB,CAAA,CAC/D,CAAA,EACC,CAACpE,CAAQ,CAAC,EAGVH,EAAA,cAAA,KAAA,CAAG,UAAWiE,EAAqB,IAAAnE,EAAU,cAAac,EAAQ,mBAAkB+B,EAAY,YAAA,EAC9F3C,EAAM,SAAS,IAAIG,EAAU,CAACsE,EAAOJ,IAAU,CAC1C,GAAAnB,EAAoBuB,CAAK,EAAG,CACxB,MAAAvE,EAAKoE,EAAcD,CAAK,EACxB3D,EAAWgD,GAAA,YAAAA,EAAiBxD,GAC5ByE,EAAoBP,EAAqBC,CAAK,EAE7C,OAAArE,EAAM,aAAayE,EAA4C,CACpE,GAAAvE,EACA,IAAKmE,EACL,SAAA3D,EACA,QAAS2C,EACT,MAAAhD,EACA,MAAAG,EACA,OAAAG,EACA,gBAAiBD,EACjB,UAAWiE,EACX,oBAAsBT,GAAyCrD,EAAoBqD,EAAO,GAAGJ,KAAQO,GAAO,EAC5G,yBAAAtD,CAAA,CACD,CACH,CACO,OAAA0D,CACR,CAAA,CACH,CAEJ,CAAC,EAEDrB,GAAa,SAAWrD,EACxBA,EAAS,YAAc"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../src/components/ExpanderList/ExpanderList.tsx"],"sourcesContent":["import React, { useEffect, useRef, useState } from 'react';\n\nimport { PaletteNames } from '../../theme/palette';\nimport Icon, { IconSize } from '../Icons';\nimport ChevronUp from '../Icons/ChevronUp';\nimport ChevronDown from '../Icons/ChevronDown';\nimport { useHover } from '../../hooks/useHover';\nimport { usePrevious } from '../../hooks/usePrevious';\nimport { Breakpoint, useBreakpoint } from '../../hooks/useBreakpoint';\nimport { isElementInViewport } from '../../utils/viewport';\n\nimport classNames from 'classnames';\n\nimport expanderListStyles from './styles.module.scss';\nimport { AnalyticsId, ZIndex } from '../../constants';\nimport { useUuid } from '../../hooks/useUuid';\nimport { useSticky } from '../../hooks/useSticky';\n\nimport { mergeRefs } from '../../utils/refs';\n\nexport type ExpanderListColors = PaletteNames;\nexport type ExpanderType = React.ForwardRefExoticComponent<ExpanderProps & React.RefAttributes<HTMLLIElement>>;\n\nexport interface ExpanderListCompound extends React.ForwardRefExoticComponent<ExpanderListProps & React.RefAttributes<HTMLUListElement>> {\n Expander: ExpanderType;\n}\n\ninterface ExpanderListProps {\n /** Toggles accordion functionality for the expanders. */\n accordion?: boolean;\n /** Toggles the bottom border of the last child element. */\n bottomBorder?: boolean;\n /** Items in the ExpanderList */\n children: React.ReactNode;\n /** Toggles padding of child elements */\n childPadding?: boolean;\n /** Adds custom classes to the element. */\n className?: string;\n /** Changes the link list background color on hover. */\n color?: ExpanderListColors;\n /** Changes the font size. */\n large?: boolean;\n /** Opens the first item in the list. */\n /** @deprecated Skal fases ut til fordel for å bruke expanded-prop på første ExpanderList.Expander */\n isOpen?: boolean;\n /** Whether to render children when closed (in which case they are hidden with CSS). Default: false */\n renderChildrenWhenClosed?: boolean;\n /** Toggles the top border of the first child element. */\n topBorder?: boolean;\n /** Stick expander trigger to top of screen while scrolling down */\n sticky?: boolean;\n /** Sets the data-testid attribute. */\n testId?: string;\n}\n\ntype Modify<T, R> = Omit<T, keyof R> & R;\n\ntype ExpanderProps = Modify<\n React.HTMLAttributes<HTMLButtonElement>,\n {\n id?: string;\n title: JSX.Element | string;\n children: React.ReactNode;\n className?: string;\n color?: ExpanderListColors;\n icon?: React.ReactElement;\n padding?: boolean;\n expanded?: boolean;\n large?: boolean;\n testId?: string;\n handleExpanderClick?: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;\n /** Called when expander is open/closed. */\n onExpand?: (isExpanded: boolean) => void;\n }\n> &\n Pick<ExpanderListProps, 'renderChildrenWhenClosed' | 'sticky'>;\n\nconst Expander: ExpanderType = React.forwardRef<HTMLLIElement, ExpanderProps>((props, ref) => {\n const {\n id,\n children,\n padding = true,\n color = 'neutral',\n className = '',\n icon,\n large = false,\n title,\n expanded = false,\n sticky,\n testId,\n handleExpanderClick,\n onExpand,\n renderChildrenWhenClosed,\n } = props;\n const [isExpanded, setIsExpanded] = useState<boolean>(expanded);\n const previousIsExpanded = usePrevious(isExpanded);\n const expanderRef = useRef<HTMLLIElement>(null);\n const triggerRef = useRef<HTMLButtonElement>(null);\n const { isHovered } = useHover(triggerRef);\n const breakpoint = useBreakpoint();\n\n const { isOutsideWindow, isLeavingWindow, offsetHeight, contentWidth } = useSticky(expanderRef, triggerRef);\n\n const isSticky = sticky && isExpanded && isOutsideWindow;\n\n const isJsxTitle = typeof title === 'object';\n\n const itemClasses = classNames(className, { [expanderListStyles['expander-list__item--jsx']]: isJsxTitle });\n\n const expanderClasses = classNames(expanderListStyles['expander-list-link'], expanderListStyles[`expander-list-link--${color}`], {\n [expanderListStyles['expander-list-link--closed']]: !isExpanded,\n [expanderListStyles['expander-list-link--large']]: large,\n [expanderListStyles['expander-list-link--jsx']]: isJsxTitle,\n [expanderListStyles['expander-list-link--sticky']]: isSticky && !isLeavingWindow,\n [expanderListStyles['expander-list-link--absolute']]: isSticky && isLeavingWindow,\n });\n\n const titleClasses = classNames(expanderListStyles['expander-list-link__title'], {\n [expanderListStyles['expander-list-link__title--string']]: !isJsxTitle,\n [expanderListStyles['expander-list-link__title--jsx']]: isJsxTitle,\n });\n\n useEffect(() => {\n if (expanded !== isExpanded) {\n setIsExpanded(expanded);\n }\n }, [expanded]);\n\n useEffect(() => {\n if (onExpand && isExpanded !== !!previousIsExpanded) {\n onExpand(isExpanded);\n }\n }, [isExpanded, onExpand]);\n\n const renderContent = () => {\n if (!renderChildrenWhenClosed && !isExpanded) {\n return null;\n }\n\n const mainContentClasses = classNames(\n expanderListStyles['expander-list-link__main-content'],\n isExpanded && expanderListStyles['expander-list-link__main-content--expanded'],\n padding ? expanderListStyles['expander-list-link__main-content--padding'] : ''\n );\n\n return <div className={mainContentClasses}>{children}</div>;\n };\n\n return (\n <li\n className={itemClasses}\n ref={mergeRefs([ref, expanderRef])}\n style={{ paddingTop: isSticky && offsetHeight ? `${offsetHeight}px` : undefined }}\n >\n <button\n type=\"button\"\n id={id}\n onClick={handleExpanderClick}\n data-testid={testId}\n data-analyticsid={AnalyticsId.ExpanderListExpander}\n className={expanderClasses}\n ref={triggerRef}\n aria-expanded={isExpanded}\n style={{\n zIndex: isHovered || isSticky ? ZIndex.ExpanderTrigger : undefined,\n width: isSticky && contentWidth ? `${contentWidth}px` : undefined,\n }}\n >\n {icon && (\n <span className={expanderListStyles['expander-list-link__icon']}>\n {React.cloneElement(icon, {\n size: breakpoint === Breakpoint.xs ? IconSize.XSmall : IconSize.Small,\n isHovered,\n })}\n </span>\n )}\n <span className={titleClasses}>{title}</span>\n <span className={expanderListStyles['expander-list-link__chevron']}>\n <Icon size={IconSize.XSmall} svgIcon={isExpanded ? ChevronUp : ChevronDown} isHovered={isHovered} />\n </span>\n </button>\n {renderContent()}\n </li>\n );\n});\n\ntype ActiveExpander = Record<string, boolean>;\n\nconst isExpanderComponent = (element: {} | null | undefined): element is React.ReactElement<ExpanderProps> =>\n React.isValidElement<ExpanderProps>(element) && (element as React.ReactElement).type === Expander;\n\nexport const ExpanderList = React.forwardRef((props: ExpanderListProps, ref: React.Ref<HTMLUListElement>) => {\n const {\n children,\n childPadding = true,\n large,\n isOpen = false,\n renderChildrenWhenClosed = false,\n color,\n className = '',\n accordion = false,\n topBorder = true,\n bottomBorder = true,\n sticky = false,\n testId,\n } = props;\n const [activeExpander, setActiveExpander] = useState<ActiveExpander>();\n const [latestExpander, setLatestExpander] = useState<HTMLElement>();\n const uuid = useUuid();\n const childCount = React.Children.count(children);\n const expanderListClasses = classNames(expanderListStyles['expander-list'], className);\n\n function handleExpanderClick(event: React.MouseEvent<HTMLElement, MouseEvent>, id: string): void {\n setActiveExpander(prevState => (accordion ? { [id]: !prevState?.[id] } : { ...prevState, [id]: !prevState?.[id] }));\n setLatestExpander(event.currentTarget);\n }\n\n /** Returns the class modifier top when we want to show the top border and no-bottom when we don't want to show the bottom border */\n const getExpanderItemClass = (index: number) => {\n return classNames(expanderListStyles['expander-list__item'], {\n [expanderListStyles['expander-list__item--top']]: index === 0 && topBorder,\n [expanderListStyles['expander-list__item--no-bottom']]: index === childCount - 1 && !bottomBorder,\n });\n };\n\n const getExpanderId = (index: number) => `${uuid}-${index}`;\n\n useEffect(() => {\n if (accordion && latestExpander && !isElementInViewport(latestExpander)) {\n latestExpander.scrollIntoView();\n }\n }, [accordion, latestExpander]);\n\n useEffect(() => {\n if (isOpen) {\n const id = getExpanderId(0);\n setActiveExpander(prevState => (accordion ? { [id]: !prevState?.[id] } : { ...prevState, [id]: !prevState?.[id] }));\n }\n }, [isOpen]);\n\n useEffect(() => {\n if (!isOpen) {\n const newActiveExpander = React.Children.map(children, child => {\n if (isExpanderComponent(child)) {\n return child;\n }\n })?.reduce((acc, child, index) => {\n // Expanded-status skal bare settes dersom prop er satt av den som bruker komponenten\n if (typeof child.props.expanded !== 'undefined') {\n acc[getExpanderId(index)] = child.props.expanded;\n }\n return acc;\n }, {} as ActiveExpander);\n\n setActiveExpander({ ...activeExpander, ...newActiveExpander });\n }\n }, [children]);\n\n return (\n <ul className={expanderListClasses} ref={ref} data-testid={testId} data-analyticsid={AnalyticsId.ExpanderList}>\n {React.Children.map(children, (child, index) => {\n if (isExpanderComponent(child)) {\n const id = getExpanderId(index);\n const expanded = activeExpander?.[id];\n const expanderItemClass = getExpanderItemClass(index);\n\n return React.cloneElement(child as React.ReactElement<ExpanderProps>, {\n id,\n key: index,\n expanded,\n padding: childPadding,\n color,\n large,\n sticky,\n 'aria-expanded': expanded,\n className: expanderItemClass,\n handleExpanderClick: (event: React.MouseEvent<HTMLElement>) => handleExpanderClick(event, `${uuid}-${index}`),\n renderChildrenWhenClosed,\n });\n }\n return child;\n })}\n </ul>\n );\n}) as ExpanderListCompound;\n\nExpanderList.Expander = Expander;\nExpander.displayName = 'ExpanderList.Expander';\n\nexport default ExpanderList;\n"],"names":["Expander","React","props","ref","id","children","padding","color","className","icon","large","title","expanded","sticky","testId","handleExpanderClick","onExpand","renderChildrenWhenClosed","isExpanded","setIsExpanded","useState","previousIsExpanded","usePrevious","expanderRef","useRef","triggerRef","isHovered","useHover","breakpoint","useBreakpoint","isOutsideWindow","isLeavingWindow","offsetHeight","contentWidth","useSticky","isSticky","isJsxTitle","itemClasses","classNames","expanderListStyles","expanderClasses","titleClasses","useEffect","renderContent","mainContentClasses","mergeRefs","AnalyticsId","ZIndex","Breakpoint","IconSize","Icon","ChevronUp","ChevronDown","isExpanderComponent","element","ExpanderList","childPadding","isOpen","accordion","topBorder","bottomBorder","activeExpander","setActiveExpander","latestExpander","setLatestExpander","uuid","useUuid","childCount","expanderListClasses","event","prevState","getExpanderItemClass","index","getExpanderId","isElementInViewport","newActiveExpander","_a","child","acc","expanderItemClass"],"mappings":"s2BA6EA,MAAMA,EAAyBC,EAAM,WAAyC,CAACC,EAAOC,IAAQ,CACtF,KAAA,CACJ,GAAAC,EACA,SAAAC,EACA,QAAAC,EAAU,GACV,MAAAC,EAAQ,UACR,UAAAC,EAAY,GACZ,KAAAC,EACA,MAAAC,EAAQ,GACR,MAAAC,EACA,SAAAC,EAAW,GACX,OAAAC,EACA,OAAAC,EACA,oBAAAC,EACA,SAAAC,EACA,yBAAAC,CACE,EAAAf,EACE,CAACgB,EAAYC,CAAa,EAAIC,EAAkBR,CAAQ,EACxDS,EAAqBC,EAAYJ,CAAU,EAC3CK,EAAcC,EAAsB,IAAI,EACxCC,EAAaD,EAA0B,IAAI,EAC3C,CAAE,UAAAE,CAAA,EAAcC,EAASF,CAAU,EACnCG,EAAaC,IAEb,CAAE,gBAAAC,EAAiB,gBAAAC,EAAiB,aAAAC,EAAc,aAAAC,GAAiBC,GAAUX,EAAaE,CAAU,EAEpGU,EAAWtB,GAAUK,GAAcY,EAEnCM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AAAnB,EAAoBwB,CAAK,EAAG,CACxB,MAAAzE,EAAKqE,EAAcD,CAAK,EACxB5D,EAAWiD,GAAA,YAAAA,EAAiBzD,GAC5B2E,EAAoBR,EAAqBC,CAAK,EAE7C,OAAAvE,EAAM,aAAa4E,EAA4C,CACpE,GAAAzE,EACA,IAAKoE,EACL,SAAA5D,EACA,QAAS4C,EACT,MAAAjD,EACA,MAAAG,EACA,OAAAG,EACA,gBAAiBD,EACjB,UAAWmE,EACX,oBAAsBV,GAAyCtD,EAAoBsD,EAAO,GAAGJ,KAAQO,GAAO,EAC5G,yBAAAvD,CAAA,CACD,CACH,CACO,OAAA4D,CACR,CAAA,CACH,CAEJ,CAAC,EAEDtB,GAAa,SAAWvD,EACxBA,EAAS,YAAc"}
|
|
@@ -9,7 +9,8 @@ export declare enum FormExampleVariants {
|
|
|
9
9
|
checkbox = "checkbox",
|
|
10
10
|
radiobutton = "radiobutton",
|
|
11
11
|
textarea = "textarea",
|
|
12
|
-
input = "input"
|
|
12
|
+
input = "input",
|
|
13
|
+
select = "select"
|
|
13
14
|
}
|
|
14
15
|
export declare const FormExample: (props: FormExampleProps) => JSX.Element;
|
|
15
16
|
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;
|
|
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 +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":{}}]}},"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":{}}]}},"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 R,{createContext as Pr,useRef as F,useState as qr,useCallback as w,useEffect as ir,useMemo as Wr,isValidElement as pr}from"react";import{V as Hr}from"../../Validation.js";import{F as Se}from"../../FormGroup.js";import{C as ce}from"../../Checkbox.js";import{B as Gr}from"../../Button.js";import{R as Ce}from"../../RadioButton.js";import{T as sr}from"../../Textarea.js";import{I as cr}from"../../Input.js";import or from"../Icons/Hospital.js";import{F as _r,a as $r}from"../../FormLayout.js";import{i as zr}from"../../uuid.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"../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"../../debounce.js";import"../RadioButton/styles.module.scss";import"../Textarea/styles.module.scss";import"../Input/styles.module.scss";import"../FormLayout/styles.module.scss";var pe=e=>e instanceof HTMLElement;const ae={BLUR:"blur",CHANGE:"change",INPUT:"input"},ee={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},vr="select",Me="undefined",X={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"};function Kr({ref:e},n,t){pe(e)&&t&&(e.addEventListener(n?ae.CHANGE:ae.INPUT,t),e.addEventListener(ae.BLUR,t))}var K=e=>e==null;const hr=e=>typeof e=="object";var G=e=>!K(e)&&!Array.isArray(e)&&hr(e)&&!(e instanceof Date),Re=e=>/^\w*$/.test(e),le=e=>e.filter(Boolean),Er=e=>le(e.replace(/["|']/g,"").replace(/\[/g,".").replace(/\]/g,"").split("."));function j(e,n,t){let c=-1;const o=Re(n)?[n]:Er(n),u=o.length,a=u-1;for(;++c<u;){const y=o[c];let l=t;if(c!==a){const p=e[y];l=G(p)||Array.isArray(p)?p:isNaN(+o[c+1])?{}:[]}e[y]=l,e=e[y]}return e}var Ge=(e,n={})=>{for(const t in e)Re(t)?n[t]=e[t]:j(n,t,e[t]);return n},M=e=>e===void 0,h=(e={},n,t)=>{const c=le(n.split(/[,[\].]+?/)).reduce((o,u)=>K(o)?o:o[u],e);return M(c)||c===e?M(e[n])?t:e[n]:c},Jr=(e,n)=>{for(const t in e)if(h(n,t)){const c=e[t];if(c){if(c.ref.focus&&M(c.ref.focus()))break;if(c.options){c.options[0].ref.focus();break}}}},ur=(e,n)=>{pe(e)&&e.removeEventListener&&(e.removeEventListener(ae.INPUT,n),e.removeEventListener(ae.CHANGE,n),e.removeEventListener(ae.BLUR,n))};const ar={isValid:!1,value:null};var Or=e=>Array.isArray(e)?e.reduce((n,t)=>t&&t.ref.checked?{isValid:!0,value:t.ref.value}:n,ar):ar,Qr=e=>[...e].filter(({selected:n})=>n).map(({value:n})=>n),we=e=>e.type==="radio",kr=e=>e.type==="file",fe=e=>e.type==="checkbox",Vr=e=>e.type===`${vr}-multiple`;const lr={value:!1,isValid:!1},fr={value:!0,isValid:!0};var xr=e=>{if(Array.isArray(e)){if(e.length>1){const o=e.filter(u=>u&&u.ref.checked).map(({ref:{value:u}})=>u);return{value:o,isValid:!!o.length}}const{checked:n,value:t,attributes:c}=e[0].ref;return n?c&&!M(c.value)?M(t)||t===""?fr:{value:t,isValid:!0}:fr:lr}return lr};function ue(e,n,t,c,o){const u=e.current[n];if(u){const{ref:{value:a,disabled:y},ref:l,valueAsNumber:p,valueAsDate:W,setValueAs:E}=u;return y&&c?void 0:kr(l)?l.files:we(l)?Or(u.options).value:Vr(l)?Qr(l.options):fe(l)?xr(u.options).value:o?a:p?a===""?NaN:+a:W?l.valueAsDate:E?E(a):a}if(t)return h(t.current,n)}function De(e){return e?!(e instanceof HTMLElement)||e.nodeType===Node.DOCUMENT_NODE?!1:De(e.parentNode):!0}var x=e=>G(e)&&!Object.keys(e).length,ze=e=>typeof e=="boolean";function Xr(e,n){const t=n.slice(0,-1).length;let c=0;for(;c<t;)e=M(e)?c++:e[n[c++]];return e}function H(e,n){const t=Re(n)?[n]:Er(n),c=t.length==1?e:Xr(e,t),o=t[t.length-1];let u;c&&delete c[o];for(let a=0;a<t.slice(0,-1).length;a++){let y=-1,l;const p=t.slice(0,-(a+1)),W=p.length-1;for(a>0&&(u=e);++y<p.length;){const E=p[y];l=l?l[E]:e[E],W===y&&(G(l)&&x(l)||Array.isArray(l)&&!l.filter(N=>G(N)&&!x(N)||ze(N)).length)&&(u?delete u[E]:delete e[E]),u=l}}return e}const dr=(e,n)=>e&&e.ref===n;function Yr(e,n,t,c,o,u){const{ref:a,ref:{name:y}}=t,l=e.current[y];if(!o){const p=ue(e,y,c);!M(p)&&j(c.current,y,p)}if(!a.type||!l){delete e.current[y];return}we(a)||fe(a)?Array.isArray(l.options)&&l.options.length?(le(l.options).forEach((p={},W)=>{(De(p.ref)&&dr(p,p.ref)||u)&&(ur(p.ref,n),H(l.options,`[${W}]`))}),l.options&&!le(l.options).length&&delete e.current[y]):delete e.current[y]:(De(a)&&dr(l,a)||u)&&(ur(a,n),delete e.current[y])}var te=e=>K(e)||!hr(e);function Ke(e,n){if(te(e)||te(n))return n;for(const t in n){const c=e[t],o=n[t];try{e[t]=G(c)&&G(o)||Array.isArray(c)&&Array.isArray(o)?Ke(c,o):o}catch{}}return e}function re(e,n,t){if(te(e)||te(n)||e instanceof Date||n instanceof Date)return e===n;if(!pr(e)){const c=Object.keys(e),o=Object.keys(n);if(c.length!==o.length)return!1;for(const u of c){const a=e[u];if(!(t&&u==="ref")){const y=n[u];if((G(a)||Array.isArray(a))&&(G(y)||Array.isArray(y))?!re(a,y,t):a!==y)return!1}}}return!0}function _e(e,n,t,c,o){let u=-1;for(;++u<e.length;){for(const a in e[u])Array.isArray(e[u][a])?(!t[u]&&(t[u]={}),t[u][a]=[],_e(e[u][a],h(n[u]||{},a,[]),t[u][a],t[u],a)):re(h(n[u]||{},a),e[u][a])?j(t[u]||{},a):t[u]=Object.assign(Object.assign({},t[u]),{[a]:!0});c&&!t.length&&delete c[o]}return t}var Zr=(e,n,t)=>Ke(_e(e,n,t.slice(0,e.length)),_e(n,e,t.slice(0,e.length))),Q=e=>typeof e=="string",He=(e,n,t,c,o)=>{const u={};for(const a in e.current)(M(o)||(Q(o)?a.startsWith(o):Array.isArray(o)&&o.find(y=>a.startsWith(y))))&&(u[a]=ue(e,a,void 0,c));return t?Ge(u):Ke(n,Ge(u))},Ur=({errors:e,name:n,error:t,validFields:c,fieldsWithValidation:o})=>{const u=M(t),a=h(e,n);return u&&!!a||!u&&!re(a,t,!0)||u&&h(o,n)&&!h(c,n)},Ar=e=>e instanceof RegExp,ye=e=>G(e)&&!Ar(e)?e:{value:e,message:""},Sr=e=>typeof e=="function",$e=e=>Q(e)||pr(e);function mr(e,n,t="validate"){if($e(e)||ze(e)&&!e)return{type:t,message:$e(e)?e:"",ref:n}}var et=(e,n,t,c,o)=>n?Object.assign(Object.assign({},t[e]),{types:Object.assign(Object.assign({},t[e]&&t[e].types?t[e].types:{}),{[c]:o||!0})}):{},Le=async(e,n,{ref:t,ref:{value:c},options:o,required:u,maxLength:a,minLength:y,min:l,max:p,pattern:W,validate:E},N)=>{const B=t.name,O={},L=we(t),k=fe(t),ne=L||k,P=c==="",_=et.bind(null,B,n,O),A=(S,V,v,D=X.maxLength,q=X.minLength)=>{const Y=S?V:v;O[B]=Object.assign({type:S?D:q,message:Y,ref:t},_(S?D:q,Y))};if(u&&(!L&&!k&&(P||K(c))||ze(c)&&!c||k&&!xr(o).isValid||L&&!Or(o).isValid)){const{value:S,message:V}=$e(u)?{value:!!u,message:u}:ye(u);if(S&&(O[B]=Object.assign({type:X.required,message:V,ref:ne?((e.current[B].options||[])[0]||{}).ref:t},_(X.required,V)),!n))return O}if((!K(l)||!K(p))&&c!==""){let S,V;const v=ye(p),D=ye(l);if(isNaN(c)){const q=t.valueAsDate||new Date(c);Q(v.value)&&(S=q>new Date(v.value)),Q(D.value)&&(V=q<new Date(D.value))}else{const q=t.valueAsNumber||parseFloat(c);K(v.value)||(S=q>v.value),K(D.value)||(V=q<D.value)}if((S||V)&&(A(!!S,v.message,D.message,X.max,X.min),!n))return O}if(Q(c)&&!P&&(a||y)){const S=ye(a),V=ye(y),v=!K(S.value)&&c.length>S.value,D=!K(V.value)&&c.length<V.value;if((v||D)&&(A(v,S.message,V.message),!n))return O}if(Q(c)&&W&&!P){const{value:S,message:V}=ye(W);if(Ar(S)&&!S.test(c)&&(O[B]=Object.assign({type:X.pattern,message:V,ref:t},_(X.pattern,V)),!n))return O}if(E){const S=ue(e,B,N,!1,!0),V=ne&&o?o[0].ref:t;if(Sr(E)){const v=await E(S),D=mr(v,V);if(D&&(O[B]=Object.assign(Object.assign({},D),_(X.validate,D.message)),!n))return O}else if(G(E)){let v={};for(const[D,q]of Object.entries(E)){if(!x(v)&&!n)break;const Y=await q(S),ve=mr(Y,V,D);ve&&(v=Object.assign(Object.assign({},ve),_(D,ve.message)),n&&(O[B]=v))}if(!x(v)&&(O[B]=Object.assign({ref:V},v),!n))return O}}return O};const Je=(e,n,t=[])=>{for(const c in n){const o=e+(G(n)?`.${c}`:`[${c}]`);te(n[c])?t.push(o):Je(o,n[c],t)}return t};var gr=(e,n,t,c,o)=>{let u;return t.add(n),x(e)||(u=h(e,n),(G(u)||Array.isArray(u))&&Je(n,u).forEach(a=>t.add(a))),M(u)?o?c:h(c,n):u},rt=({isOnBlur:e,isOnChange:n,isOnTouch:t,isTouched:c,isReValidateOnBlur:o,isReValidateOnChange:u,isBlurEvent:a,isSubmitted:y,isOnAll:l})=>l?!1:!y&&t?!(c||a):(y?o:e)?!a:(y?u:n)?a:!0,Te=e=>e.substring(0,e.indexOf("["));const tt=(e,n)=>RegExp(`^${n}([|.)\\d+`.replace(/\[/g,"\\[").replace(/\]/g,"\\]")).test(e);var nt=(e,n)=>[...e].some(t=>tt(n,t)),it=e=>e.type===`${vr}-one`;function st(e,n){const t=new MutationObserver(()=>{for(const c of Object.values(e.current))if(c&&c.options)for(const o of c.options)o&&o.ref&&De(o.ref)&&n(c);else c&&De(c.ref)&&n(c)});return t.observe(window.document,{childList:!0,subtree:!0}),t}var be=typeof window!==Me&&typeof document!==Me;function U(e){var n;let t;if(te(e)||be&&(e instanceof File||pe(e))||!["Set","Map","Object","Date","Array"].includes((n=e.constructor)===null||n===void 0?void 0:n.name))return e;if(e instanceof Date)return t=new Date(e.getTime()),t;if(e instanceof Set){t=new Set;for(const c of e)t.add(c);return t}if(e instanceof Map){t=new Map;for(const c of e.keys())t.set(c,U(e.get(c)));return t}t=Array.isArray(e)?[]:{};for(const c in e)t[c]=U(e[c]);return t}var yr=e=>({isOnSubmit:!e||e===ee.onSubmit,isOnBlur:e===ee.onBlur,isOnChange:e===ee.onChange,isOnAll:e===ee.all,isOnTouch:e===ee.onTouched}),br=e=>we(e)||fe(e);const ct=typeof window===Me,oe=be?"Proxy"in window:typeof Proxy!==Me;function ot({mode:e=ee.onSubmit,reValidateMode:n=ee.onChange,resolver:t,context:c,defaultValues:o={},shouldFocusError:u=!0,shouldUnregister:a=!0,criteriaMode:y}={}){const l=F({}),p=F({}),W=F({}),E=F(new Set),N=F({}),B=F({}),O=F({}),L=F({}),k=F(o),ne=F(!1),P=F(!1),_=F(),A=F({}),S=F({}),V=F(c),v=F(t),D=F(new Set),q=F(yr(e)),{isOnSubmit:Y,isOnTouch:ve}=q.current,$=y===ee.all,[de,Rr]=qr({isDirty:!1,isValidating:!1,dirtyFields:{},isSubmitted:!1,submitCount:0,touched:{},isSubmitting:!1,isSubmitSuccessful:!1,isValid:!Y,errors:{}}),T=F({isDirty:!oe,dirtyFields:!oe,touched:!oe||ve,isValidating:!oe,isSubmitting:!oe,isValid:!oe}),f=F(de),he=F(),{isOnBlur:Qe,isOnChange:Xe}=F(yr(n)).current;V.current=c,v.current=t,f.current=de,A.current=a?{}:x(A.current)?U(o):A.current;const I=w((r={})=>{ne.current||(f.current=Object.assign(Object.assign({},f.current),r),Rr(f.current))},[]),Ye=()=>T.current.isValidating&&I({isValidating:!0}),Ee=w((r,s,i=!1,m={},g)=>{let d=i||Ur({errors:f.current.errors,error:s,name:r,validFields:L.current,fieldsWithValidation:O.current});const b=h(f.current.errors,r);s?(H(L.current,r),d=d||!b||!re(b,s,!0),j(f.current.errors,r,s)):((h(O.current,r)||v.current)&&(j(L.current,r,!0),d=d||b),H(f.current.errors,r)),(d&&!K(i)||!x(m)||T.current.isValidating)&&I(Object.assign(Object.assign(Object.assign({},m),v.current?{isValid:!!g}:{}),{isValidating:!1}))},[]),Oe=w((r,s)=>{const{ref:i,options:m}=l.current[r],g=be&&pe(i)&&K(s)?"":s;we(i)?(m||[]).forEach(({ref:d})=>d.checked=d.value===g):kr(i)&&!Q(g)?i.files=g:Vr(i)?[...i.options].forEach(d=>d.selected=g.includes(d.value)):fe(i)&&m?m.length>1?m.forEach(({ref:d})=>d.checked=Array.isArray(g)?!!g.find(b=>b===d.value):g===d.value):m[0].ref.checked=!!g:i.value=g},[]),Ne=w((r,s)=>{if(T.current.isDirty){const i=me();return r&&s&&j(i,r,s),!re(i,k.current)}return!1},[]),ke=w((r,s=!0)=>{if(T.current.isDirty||T.current.dirtyFields){const i=!re(h(k.current,r),ue(l,r,A)),m=h(f.current.dirtyFields,r),g=f.current.isDirty;i?j(f.current.dirtyFields,r,!0):H(f.current.dirtyFields,r);const d={isDirty:Ne(),dirtyFields:f.current.dirtyFields},b=T.current.isDirty&&g!==d.isDirty||T.current.dirtyFields&&m!==h(f.current.dirtyFields,r);return b&&s&&I(d),b?d:{}}return{}},[]),Be=w(async(r,s)=>{const i=(await Le(l,$,l.current[r],A))[r];return Ee(r,i,s),M(i)},[Ee,$]),Ze=w(async r=>{const{errors:s}=await v.current(me(),V.current,$),i=f.current.isValid;if(Array.isArray(r)){const m=r.map(g=>{const d=h(s,g);return d?j(f.current.errors,g,d):H(f.current.errors,g),!d}).every(Boolean);return I({isValid:x(s),isValidating:!1}),m}else{const m=h(s,r);return Ee(r,m,i!==x(s),{},x(s)),!m}},[Ee,$]),Ve=w(async r=>{const s=r||Object.keys(l.current);if(Ye(),v.current)return Ze(s);if(Array.isArray(s)){!r&&(f.current.errors={});const i=await Promise.all(s.map(async m=>await Be(m,null)));return I({isValidating:!1}),i.every(Boolean)}return await Be(s)},[Ze,Be]),Ue=w((r,s,{shouldDirty:i,shouldValidate:m})=>{const g={};j(g,r,s);for(const d of Je(r,s))l.current[d]&&(Oe(d,h(g,d)),i&&ke(d),m&&Ve(d))},[Ve,Oe,ke]),er=w((r,s,i)=>{if(!a&&!te(s)&&j(A.current,r,Array.isArray(s)?[...s]:Object.assign({},s)),l.current[r])Oe(r,s),i.shouldDirty&&ke(r),i.shouldValidate&&Ve(r);else if(!te(s)&&(Ue(r,s,i),D.current.has(r))){const m=Te(r)||r;j(p.current,r,s),S.current[m]({[m]:h(p.current,m)}),(T.current.isDirty||T.current.dirtyFields)&&i.shouldDirty&&(j(f.current.dirtyFields,r,Zr(s,h(k.current,r,[]),h(f.current.dirtyFields,r,[]))),I({isDirty:!re(Object.assign(Object.assign({},me()),{[r]:s}),k.current)}))}!a&&j(A.current,r,s)},[ke,Oe,Ue]),rr=r=>P.current||E.current.has(r)||E.current.has((r.match(/\w+/)||[])[0]),xe=r=>{let s=!0;if(!x(N.current))for(const i in N.current)(!r||!N.current[i].size||N.current[i].has(r)||N.current[i].has(Te(r)))&&(B.current[i](),s=!1);return s};function Dr(r,s,i){er(r,s,i||{}),rr(r)&&I(),xe(r)}_.current=_.current?_.current:async({type:r,target:s})=>{let i=s.name;const m=l.current[i];let g,d;if(m){const b=r===ae.BLUR,z=rt(Object.assign({isBlurEvent:b,isReValidateOnChange:Xe,isReValidateOnBlur:Qe,isTouched:!!h(f.current.touched,i),isSubmitted:f.current.isSubmitted},q.current));let J=ke(i,!1),ge=!x(J)||!b&&rr(i);if(b&&!h(f.current.touched,i)&&T.current.touched&&(j(f.current.touched,i,!0),J=Object.assign(Object.assign({},J),{touched:f.current.touched})),!a&&fe(s)&&j(A.current,i,ue(l,i)),z)return!b&&xe(i),(!x(J)||ge&&x(J))&&I(J);if(Ye(),v.current){const{errors:C}=await v.current(me(),V.current,$),Ae=f.current.isValid;if(g=h(C,i),fe(s)&&!g&&v.current){const Z=Te(i),ie=h(C,Z,{});ie.type&&ie.message&&(g=ie),Z&&(ie||h(f.current.errors,Z))&&(i=Z)}d=x(C),Ae!==d&&(ge=!0)}else g=(await Le(l,$,m,A))[i];!b&&xe(i),Ee(i,g,ge,J,d)}};function tr(r){if(!a){let s=U(r);for(const i of D.current)Re(i)&&!s[i]&&(s=Object.assign(Object.assign({},s),{[i]:[]}));return s}return r}function me(r){if(Q(r))return ue(l,r,A);if(Array.isArray(r)){const s={};for(const i of r)j(s,i,ue(l,i,A));return s}return tr(He(l,U(A.current),a))}const Fe=w(async(r={})=>{const s=x(l.current)?k.current:{},{errors:i}=await v.current(Object.assign(Object.assign(Object.assign({},s),me()),r),V.current,$)||{},m=x(i);f.current.isValid!==m&&I({isValid:m})},[$]),je=w((r,s)=>{Yr(l,_.current,r,A,a,s),a&&(H(L.current,r.ref.name),H(O.current,r.ref.name))},[a]),Pe=w(r=>{if(P.current)I();else{for(const s of E.current)if(s.startsWith(r)){I();break}xe(r)}},[]),Ie=w((r,s)=>{r&&(je(r,s),a&&!le(r.options||[]).length&&(H(f.current.errors,r.ref.name),j(f.current.dirtyFields,r.ref.name,!0),I({isDirty:Ne()}),T.current.isValid&&v.current&&Fe(),Pe(r.ref.name)))},[Fe,je]);function wr(r){r&&(Array.isArray(r)?r:[r]).forEach(s=>l.current[s]&&Re(s)?delete f.current.errors[s]:H(f.current.errors,s)),I({errors:r?f.current.errors:{}})}function Fr(r,s){const i=(l.current[r]||{}).ref;j(f.current.errors,r,Object.assign(Object.assign({},s),{ref:i})),I({isValid:!1}),s.shouldFocus&&i&&i.focus&&i.focus()}const qe=w((r,s,i)=>{const m=i?N.current[i]:E.current;let g=He(l,U(A.current),a,!1,r);if(Q(r)){const b=Te(r)||r;return D.current.has(b)&&(g=Object.assign(Object.assign({},W.current),g)),gr(g,r,m,M(h(k.current,r))?s:h(k.current,r),!0)}const d=M(s)?k.current:s;return Array.isArray(r)?r.reduce((b,z)=>Object.assign(Object.assign({},b),{[z]:gr(g,z,m,d)}),{}):(P.current=M(i),Ge(!x(g)&&g||d))},[]);function jr(r,s){return qe(r,s)}function Ir(r){for(const s of Array.isArray(r)?r:[r])Ie(l.current[s],!0)}function We(r,s={}){const{name:i,type:m,value:g}=r,d=Object.assign({ref:r},s),b=l.current,z=br(r),J=nt(D.current,i),ge=se=>be&&(!pe(r)||se===r);let C=b[i],Ae=!0,Z;if(C&&(z?Array.isArray(C.options)&&le(C.options).find(se=>g===se.ref.value&&ge(se.ref)):ge(C.ref))){b[i]=Object.assign(Object.assign({},C),s);return}m?C=z?Object.assign({options:[...le(C&&C.options||[]),{ref:r}],ref:{type:m,name:i}},s):Object.assign({},d):C=d,b[i]=C;const ie=M(h(A.current,i));(!x(k.current)||!ie)&&(Z=h(ie?k.current:A.current,i),Ae=M(Z),!Ae&&!J&&Oe(i,Z)),x(s)||(j(O.current,i,!0),!Y&&T.current.isValid&&Le(l,$,C,A).then(se=>{const Br=f.current.isValid;x(se)?j(L.current,i,!0):H(L.current,i),Br!==x(se)&&I()})),a&&!(J&&Ae)&&!J&&H(f.current.dirtyFields,i),m&&Kr(z&&C.options?C.options[C.options.length-1]:C,z||it(r),_.current)}function Cr(r,s){if(!ct)if(Q(r))We({name:r},s);else if(G(r)&&"name"in r)We(r,s);else return i=>i&&We(i,r)}const Lr=w((r,s)=>async i=>{i&&i.preventDefault&&(i.preventDefault(),i.persist());let m={},g=tr(He(l,U(A.current),a,!0));T.current.isSubmitting&&I({isSubmitting:!0});try{if(v.current){const{errors:d,values:b}=await v.current(g,V.current,$);f.current.errors=m=d,g=b}else for(const d of Object.values(l.current))if(d){const{name:b}=d.ref,z=await Le(l,$,d,A);z[b]?(j(m,b,z[b]),H(L.current,b)):h(O.current,b)&&(H(f.current.errors,b),j(L.current,b,!0))}x(m)&&Object.keys(f.current.errors).every(d=>d in l.current)?(I({errors:{},isSubmitting:!0}),await r(g,i)):(f.current.errors=Object.assign(Object.assign({},f.current.errors),m),s&&await s(f.current.errors,i),u&&Jr(l.current,f.current.errors))}finally{f.current.isSubmitting=!1,I({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:x(f.current.errors),submitCount:f.current.submitCount+1})}},[u,$]),Tr=({errors:r,isDirty:s,isSubmitted:i,touched:m,isValid:g,submitCount:d,dirtyFields:b})=>{g||(L.current={},O.current={}),p.current={},E.current=new Set,P.current=!1,I({submitCount:d?f.current.submitCount:0,isDirty:s?f.current.isDirty:!1,isSubmitted:i?f.current.isSubmitted:!1,isValid:g?f.current.isValid:!1,dirtyFields:b?f.current.dirtyFields:{},touched:m?f.current.touched:{},errors:r?f.current.errors:{},isSubmitting:!1,isSubmitSuccessful:!1})},Mr=(r,s={})=>{if(be){for(const i of Object.values(l.current))if(i){const{ref:m,options:g}=i,d=br(m)&&Array.isArray(g)?g[0].ref:m;if(pe(d))try{d.closest("form").reset();break}catch{}}}l.current={},k.current=Object.assign({},r||k.current),r&&xe(""),Object.values(S.current).forEach(i=>Sr(i)&&i()),A.current=a?{}:U(r||k.current),Tr(s)};ir(()=>{t&&T.current.isValid&&Fe(),he.current=he.current||!be?he.current:st(l,Ie)},[Ie,k.current]),ir(()=>()=>{he.current&&he.current.disconnect(),ne.current=!0,Object.values(l.current).forEach(r=>Ie(r,!0))},[]),!t&&T.current.isValid&&(de.isValid=re(L.current,O.current)&&x(f.current.errors));const nr={trigger:Ve,setValue:w(Dr,[er,Ve]),getValues:w(me,[]),register:w(Cr,[k.current]),unregister:w(Ir,[]),formState:oe?new Proxy(de,{get:(r,s)=>{if(s in r)return T.current[s]=!0,r[s]}}):de},Nr=Wr(()=>Object.assign({isFormDirty:Ne,updateWatchedValue:Pe,shouldUnregister:a,updateFormState:I,removeFieldEventListener:je,watchInternal:qe,mode:q.current,reValidateMode:{isReValidateOnBlur:Qe,isReValidateOnChange:Xe},validateResolver:t?Fe:void 0,fieldsRef:l,resetFieldArrayFunctionRef:S,useWatchFieldsRef:N,useWatchRenderFunctionsRef:B,fieldArrayDefaultValuesRef:p,validFieldsRef:L,fieldsWithValidationRef:O,fieldArrayNamesRef:D,readFormStateRef:T,formStateRef:f,defaultValuesRef:k,shallowFieldsStateRef:A,fieldArrayValuesRef:W},nr),[k.current,Pe,a,je,qe]);return Object.assign({watch:jr,control:Nr,handleSubmit:Lr,reset:w(Mr,[]),clearErrors:w(wr,[]),setError:w(Fr,[]),errors:de.errors},nr)}const ut=Pr(null);ut.displayName="RHFContext";var at=(e=>(e.formgroup="formgroup",e.checkbox="checkbox",e.radiobutton="radiobutton",e.textarea="textarea",e.input="input",e))(at||{});const Qt=e=>{const{exampleType:n="formgroup"}=e,{register:t,handleSubmit:c,errors:o}=ot(),u="field1",a="field2",y="field3",l="field4",p="field5",W=o[u]||o[a]||o[y]||o[l]||o[p],E="Du m\xE5 velge et alternativ",N="Du m\xE5 velge to alternativ",B="Det kan ikke legges inn mer enn 40 tegn",O="Du m\xE5 skrive noe her",L=[R.createElement(ce,{key:0,inputId:"checkbox1",label:"Checkbox 1",ref:t({required:E})}),R.createElement(ce,{key:1,inputId:"checkbox2",label:"Checkbox 2",ref:t({required:E})}),R.createElement(ce,{key:2,inputId:"checkbox3",label:"Checkbox 3",ref:t({required:E})})],k=P=>P.length>=2||N,ne=()=>{if(n==="formgroup")return[R.createElement(Se,{key:0,title:"Gruppe tittel",legend:"Velg minst en",error:o[u]?o[u].message:void 0,variant:e.variant,name:u},R.createElement(_r,{maxColumns:$r.two},L.map(P=>P))),R.createElement(Se,{key:1,legend:"Velg minst to",error:o[a]?o[a].message:void 0,variant:e.variant,name:a},R.createElement(ce,{inputId:"checkbox4",label:"Checkbox 4",ref:t({validate:k})}),R.createElement(ce,{inputId:"checkbox5",label:"Checkbox 5",ref:t({validate:k})}),R.createElement(ce,{inputId:"checkbox6",label:"Checkbox 6",ref:t({validate:k})})),R.createElement(Se,{key:2,legend:"Velg en",error:o[y]?o[y].message:void 0,variant:e.variant,name:y},R.createElement(Ce,{inputId:"radiobutton1",label:"Radiobutton 1",ref:t({required:E})}),R.createElement(Ce,{inputId:"radiobutton2",label:"Radiobutton 2",ref:t({required:E})}),R.createElement(Ce,{inputId:"radiobutton3",label:"Radiobutton 3",ref:t({required:E})})),R.createElement(Se,{key:3,error:o[l]?o[l].message:void 0},R.createElement(sr,{defaultValue:`Dette er en test
|
|
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
|
|
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"
|
|
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
|
|
8
8
|
|
|
9
9
|
Hello
|
|
10
10
|
|
|
11
|
-
test`,grow:!0,maxCharacters:40,minRows:5,errorText:
|
|
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};
|
|
12
12
|
//# sourceMappingURL=index.js.map
|