@dr.pogodin/react-utils 1.53.1 → 1.54.1
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/build/development/client/index.js +2 -0
- package/build/development/client/index.js.map +1 -1
- package/build/development/index.js +2 -2
- package/build/development/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +149 -71
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +77 -24
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/GenericLink/index.js +133 -54
- package/build/development/shared/components/GenericLink/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +168 -45
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Link.js +23 -13
- package/build/development/shared/components/Link.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +203 -87
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/NavLink.js +16 -7
- package/build/development/shared/components/NavLink.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +77 -15
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +169 -68
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +51 -13
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +73 -34
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +19 -19
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +66 -23
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +104 -56
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +173 -75
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +86 -36
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/globalState.js +2 -2
- package/build/development/shared/utils/globalState.js.map +1 -1
- package/build/development/shared/utils/index.js +2 -2
- package/build/development/shared/utils/index.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +19 -7
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +125 -55
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/time.js +55 -20
- package/build/development/shared/utils/time.js.map +1 -1
- package/build/production/client/index.js +2 -2
- package/build/production/client/index.js.map +1 -1
- package/build/production/index.js +1 -1
- package/build/production/index.js.map +1 -1
- package/build/production/shared/components/Button/index.js +2 -13
- package/build/production/shared/components/Button/index.js.map +1 -1
- package/build/production/shared/components/Checkbox/index.js +1 -1
- package/build/production/shared/components/Checkbox/index.js.map +1 -1
- package/build/production/shared/components/GenericLink/index.js +2 -15
- package/build/production/shared/components/GenericLink/index.js.map +1 -1
- package/build/production/shared/components/Input/index.js +2 -11
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Link.js +2 -4
- package/build/production/shared/components/Link.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +2 -10
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/NavLink.js +1 -4
- package/build/production/shared/components/NavLink.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +2 -2
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +1 -21
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +2 -2
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +2 -7
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +3 -3
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +2 -5
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -6
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +1 -7
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/Switch/index.js +1 -1
- package/build/production/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/production/shared/utils/globalState.js +1 -1
- package/build/production/shared/utils/globalState.js.map +1 -1
- package/build/production/shared/utils/index.js +1 -1
- package/build/production/shared/utils/index.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +10 -3
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +3 -10
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/time.js +2 -2
- package/build/production/shared/utils/time.js.map +1 -1
- package/build/types-code/index.d.ts +2 -2
- package/build/types-code/shared/utils/globalState.d.ts +2 -2
- package/build/types-code/shared/utils/index.d.ts +2 -2
- package/build/types-code/shared/utils/splitComponent.d.ts +1 -0
- package/build/web/client/index.js +2 -2
- package/build/web/client/index.js.map +1 -1
- package/build/web/index.js +1 -1
- package/build/web/index.js.map +1 -1
- package/build/web/shared/components/Button/index.js +2 -13
- package/build/web/shared/components/Button/index.js.map +1 -1
- package/build/web/shared/components/Checkbox/index.js +1 -1
- package/build/web/shared/components/Checkbox/index.js.map +1 -1
- package/build/web/shared/components/GenericLink/index.js +2 -15
- package/build/web/shared/components/GenericLink/index.js.map +1 -1
- package/build/web/shared/components/Input/index.js +2 -11
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Link.js +2 -4
- package/build/web/shared/components/Link.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +2 -10
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/NavLink.js +1 -4
- package/build/web/shared/components/NavLink.js.map +1 -1
- package/build/web/shared/components/PageLayout/index.js +2 -2
- package/build/web/shared/components/PageLayout/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +1 -21
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/Throbber/index.js +2 -2
- package/build/web/shared/components/Throbber/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/Tooltip.js +2 -7
- package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +3 -3
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js +2 -5
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +1 -6
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -7
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +1 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/utils/globalState.js +1 -1
- package/build/web/shared/utils/globalState.js.map +1 -1
- package/build/web/shared/utils/index.js +1 -1
- package/build/web/shared/utils/index.js.map +1 -1
- package/build/web/shared/utils/jest/index.js +10 -3
- package/build/web/shared/utils/jest/index.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +3 -10
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/time.js +2 -2
- package/build/web/shared/utils/time.js.map +1 -1
- package/config/babel/webpack.d.ts +1 -0
- package/config/babel/webpack.js +10 -12
- package/package.json +6 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","useTheme","Tooltip","PLACEMENTS","defaultTheme","jsx","_jsx","jsxs","_jsxs","WithTooltip","children","className","classNameProp","onClick","onContextMenu","onMouseLeave","onMouseMove","onTouchStart","placement","ABOVE_CURSOR","ref","style","theme","tip","htmlAttributes","custom","heap","setHeap","lastCursorX","lastCursorY","timerId","undefined","triggeredByTouch","tooltipRef","wrapperRef","showTooltip","setShowTooltip","updatePortalPosition","cursorX","cursorY","wrapperRect","current","getBoundingClientRect","left","right","top","bottom","pointTo","window","scrollX","scrollY","prev","res","setTimeout","p","listener","addEventListener","removeEventListener","container","wrapper","clearTimeout","e","preventDefault","ignoreMouseMove","clientX","clientY","touch","targetTouches","item","node","role"],"sources":["../../../../../src/shared/components/WithTooltip/index.tsx"],"sourcesContent":["/* global window */\n\nimport {\n type FunctionComponent,\n type HTMLAttributes,\n type ReactNode,\n type RefObject,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Tooltip, {\n PLACEMENTS,\n type ThemeKeysT as TooltipThemeKeysT,\n} from './Tooltip';\n\nimport defaultTheme from './default-theme.scss';\n\ntype PropsT = HTMLAttributes<HTMLDivElement> & {\n children?: ReactNode;\n placement?: PLACEMENTS;\n ref?: RefObject<HTMLDivElement | null>;\n theme?: Theme<'wrapper' | TooltipThemeKeysT>;\n tip?: ReactNode;\n};\n\ntype TooltipRefT = {\n pointTo: (\n x: number,\n y: number,\n placement: PLACEMENTS,\n wrapperRef: HTMLDivElement,\n ) => void;\n};\n\ntype HeapT = {\n ignoreMouseMove?: boolean;\n lastCursorX: number;\n lastCursorY: number;\n timerId?: NodeJS.Timeout;\n triggeredByTouch: boolean;\n};\n\n/**\n * Implements a simple to use and themeable tooltip component, _e.g._\n * ```js\n * <WithTooltip tip=\"This is example tooltip.\">\n * <p>Hover to see the tooltip.</p>\n * </WithTooltip>\n * ```\n * **Children:** Children are rendered in the place of `<WithTooltip>`,\n * and when hovered the tooltip is shown. By default the wrapper itself is\n * `<div>` block with `display: inline-block`.\n * @param tip – Anything React is able to render,\n * _e.g._ a tooltip text. This will be the tooltip content.\n * @param {WithTooltipTheme} props.theme _Ad hoc_ theme.\n */\nconst WithTooltip: FunctionComponent<PropsT> = ({\n children,\n className: classNameProp,\n onClick,\n onContextMenu,\n onMouseLeave,\n onMouseMove,\n onTouchStart,\n placement = PLACEMENTS.ABOVE_CURSOR,\n ref,\n style,\n theme,\n tip,\n ...htmlAttributes\n}) => {\n const custom = useTheme('WithTooltip', defaultTheme, theme);\n\n const [heap, setHeap] = useState<HeapT>({\n lastCursorX: 0,\n lastCursorY: 0,\n timerId: undefined,\n triggeredByTouch: false,\n });\n\n const tooltipRef = useRef<TooltipRefT>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [showTooltip, setShowTooltip] = useState(false);\n\n const updatePortalPosition = (cursorX: number, cursorY: number) => {\n if (showTooltip) {\n const wrapperRect = wrapperRef.current!.getBoundingClientRect();\n if (\n cursorX < wrapperRect.left\n || cursorX > wrapperRect.right\n || cursorY < wrapperRect.top\n || cursorY > wrapperRect.bottom\n ) {\n setShowTooltip(false);\n } else if (tooltipRef.current) {\n tooltipRef.current.pointTo(\n cursorX + window.scrollX,\n cursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n }\n } else {\n setHeap((prev) => {\n const res: HeapT = {\n ...prev,\n lastCursorX: cursorX,\n lastCursorY: cursorY,\n };\n\n // If tooltip was triggered by a touch, we delay its opening by a bit,\n // to ensure it was not a touch-click - in the case of touch click we\n // want to do the click, rather than show the tooltip, and the delay\n // gives click handler a chance to abort the tooltip openning.\n if (res.triggeredByTouch) {\n res.timerId ??= setTimeout(() => {\n setHeap((p) => ({\n ...p,\n timerId: undefined,\n triggeredByTouch: false,\n }));\n\n setShowTooltip(true);\n }, 300);\n\n // Otherwise we can just open the tooltip right away.\n } else setShowTooltip(true);\n\n return res;\n });\n }\n };\n\n useEffect(() => {\n if (showTooltip && tip !== null) {\n // This is necessary to ensure that even when a single mouse event\n // arrives to a tool-tipped component, the tooltip is correctly positioned\n // once opened (because similar call above does not have effect until\n // the tooltip is fully mounted, and that is delayed to future rendering\n // cycle due to the implementation).\n if (tooltipRef.current) {\n setHeap((prev) => {\n tooltipRef.current?.pointTo(\n prev.lastCursorX + window.scrollX,\n prev.lastCursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n return prev;\n });\n }\n\n const listener = () => {\n setShowTooltip(false);\n };\n window.addEventListener('scroll', listener);\n return () => {\n window.removeEventListener('scroll', listener);\n };\n }\n return undefined;\n }, [\n placement,\n showTooltip,\n tip,\n ]);\n\n let container = custom.wrapper;\n if (classNameProp) container += ` ${classNameProp}`;\n\n useEffect(() => {\n const listener = () => {\n setShowTooltip(false);\n heap.triggeredByTouch = false;\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n heap.timerId = undefined;\n heap.triggeredByTouch = false;\n }\n };\n window.addEventListener('touchcancel', listener);\n window.addEventListener('touchend', listener);\n return () => {\n window.removeEventListener('touchcancel', listener);\n window.removeEventListener('touchend', listener);\n };\n }, [heap]);\n\n return (\n <div\n className={container}\n onClick={(e) => {\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n\n setHeap({\n ...heap,\n timerId: undefined,\n triggeredByTouch: false,\n });\n }\n onClick?.(e);\n }}\n onContextMenu={(e) => {\n e.preventDefault();\n onContextMenu?.(e);\n }}\n onMouseLeave={(e) => {\n setShowTooltip(false);\n onMouseLeave?.(e);\n }}\n onMouseMove={(e) => {\n // NOTE: Because on touch devices mouse move events are still fired\n // after touch is released, to emulate mouse clicks for old websites.\n // If we don't ignore it here, the tooltip will appear after the touch\n // is released.\n if (!heap.ignoreMouseMove) {\n updatePortalPosition(e.clientX, e.clientY);\n }\n onMouseMove?.(e);\n }}\n onTouchStart={(e) => {\n setHeap({\n ...heap,\n ignoreMouseMove: true,\n triggeredByTouch: true,\n });\n\n // TODO: I guess, it should be something more complex here,\n // to actually respond to the first / whatever touch we need.\n const touch = e.targetTouches.item(0);\n updatePortalPosition(touch.clientX, touch.clientY);\n\n onTouchStart?.(e);\n }}\n ref={(node) => {\n wrapperRef.current = node;\n\n // eslint-disable-next-line no-param-reassign\n if (ref) ref.current = node;\n }}\n role=\"presentation\"\n style={style}\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...htmlAttributes}\n >\n {\n showTooltip && tip !== null\n ? <Tooltip ref={tooltipRef} theme={custom}>{tip}</Tooltip>\n : null\n }\n {children}\n </div>\n );\n};\n\ntype ExportT = {\n PLACEMENTS: typeof PLACEMENTS;\n} & typeof WithTooltip;\n\nconst e: ExportT = WithTooltip as ExportT;\n\ne.PLACEMENTS = PLACEMENTS;\n\nexport default e;\n"],"mappings":"AAAA,mBAEA,OAKEA,SAAS,CACTC,MAAM,CACNC,QAAQ,KACH,OAAO,CAEd,OAAqBC,QAAQ,KAAQ,0BAA0B,CAE/D,MAAO,CAAAC,OAAO,EACZC,UAAU,iBAIZ,MAAO,CAAAC,YAAY,4BAA6B,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBA2BhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,WAAsC,CAAGA,CAAC,CAC9CC,QAAQ,CACRC,SAAS,CAAEC,aAAa,CACxBC,OAAO,CACPC,aAAa,CACbC,YAAY,CACZC,WAAW,CACXC,YAAY,CACZC,SAAS,CAAGf,UAAU,CAACgB,YAAY,CACnCC,GAAG,CACHC,KAAK,CACLC,KAAK,CACLC,GAAG,CACH,GAAGC,cACL,CAAC,GAAK,CACJ,KAAM,CAAAC,MAAM,CAAGxB,QAAQ,CAAC,aAAa,CAAEG,YAAY,CAAEkB,KAAK,CAAC,CAE3D,KAAM,CAACI,IAAI,CAAEC,OAAO,CAAC,CAAG3B,QAAQ,CAAQ,CACtC4B,WAAW,CAAE,CAAC,CACdC,WAAW,CAAE,CAAC,CACdC,OAAO,CAAEC,SAAS,CAClBC,gBAAgB,CAAE,KACpB,CAAC,CAAC,CAEF,KAAM,CAAAC,UAAU,CAAGlC,MAAM,CAAc,IAAI,CAAC,CAC5C,K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IACpB,CAAC,CAAC,CAEF;AACA;AACA,KAAM,CAAAkC,KAAK,CAAGL,CAAC,CAACM,aAAa,CAACC,IAAI,CAAC,CAAC,CAAC,CACrC/B,oBAAoB,CAAC6B,KAAK,CAACF,OAAO,CAAEE,KAAK,CAACD,OAAO,CAAC,CAElDhD,YAAY,GAAG4C,CAAC,CAAC,CACnB,CAAE,CACFzC,GAAG,CAAGiD,IAAI,EAAK,CACbnC,UAAU,CAACO,OAAO,CAAG4B,IAAI,CAEzB;AACA,GAAIjD,GAAG,CAAEA,GAAG,CAACqB,OAAO,CAAG4B,IAAI,CAC7B,CAAE,CACFC,IAAI,CAAC,cAAc,CACnBjD,KAAK,CAAEA,KAEP;AAAA,IACIG,cAAc,CAAAd,QAAA,EAGhByB,WAAW,EAAIZ,GAAG,GAAK,IAAI,cACvBjB,IAAA,CAACJ,OAAO,EAACkB,GAAG,CAAEa,UAAW,CAACX,KAAK,CAAEG,MAAO,CAAAf,QAAA,CAAEa,GAAG,CAAU,CAAC,CACxD,IAAI,CAETb,QAAQ,EACN,CAAC,CAEV,CAAC,CAMD,KAAM,CAAAmD,CAAU,CAAGpD,WAAsB,CAEzCoD,CAAC,CAAC1D,UAAU,CAAGA,UAAU,CAEzB,cAAe,CAAA0D,CAAC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","useTheme","Tooltip","PLACEMENTS","defaultTheme","jsx","_jsx","jsxs","_jsxs","WithTooltip","children","className","classNameProp","onClick","onContextMenu","onMouseLeave","onMouseMove","onTouchStart","placement","ABOVE_CURSOR","ref","style","theme","tip","htmlAttributes","custom","heap","setHeap","lastCursorX","lastCursorY","timerId","undefined","triggeredByTouch","tooltipRef","wrapperRef","showTooltip","setShowTooltip","updatePortalPosition","cursorX","cursorY","wrapperRect","current","getBoundingClientRect","left","right","top","bottom","pointTo","window","scrollX","scrollY","prev","res","setTimeout","p","listener","addEventListener","removeEventListener","container","wrapper","clearTimeout","e","preventDefault","ignoreMouseMove","clientX","clientY","touch","targetTouches","item","node","role"],"sources":["../../../../../src/shared/components/WithTooltip/index.tsx"],"sourcesContent":["/* global window */\n\nimport {\n type FunctionComponent,\n type HTMLAttributes,\n type ReactNode,\n type RefObject,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Tooltip, {\n PLACEMENTS,\n type ThemeKeysT as TooltipThemeKeysT,\n} from './Tooltip';\n\nimport defaultTheme from './default-theme.scss';\n\ntype PropsT = HTMLAttributes<HTMLDivElement> & {\n children?: ReactNode;\n placement?: PLACEMENTS;\n ref?: RefObject<HTMLDivElement | null>;\n theme?: Theme<'wrapper' | TooltipThemeKeysT>;\n tip?: ReactNode;\n};\n\ntype TooltipRefT = {\n pointTo: (\n x: number,\n y: number,\n placement: PLACEMENTS,\n wrapperRef: HTMLDivElement,\n ) => void;\n};\n\ntype HeapT = {\n ignoreMouseMove?: boolean;\n lastCursorX: number;\n lastCursorY: number;\n timerId?: NodeJS.Timeout;\n triggeredByTouch: boolean;\n};\n\n/**\n * Implements a simple to use and themeable tooltip component, _e.g._\n * ```js\n * <WithTooltip tip=\"This is example tooltip.\">\n * <p>Hover to see the tooltip.</p>\n * </WithTooltip>\n * ```\n * **Children:** Children are rendered in the place of `<WithTooltip>`,\n * and when hovered the tooltip is shown. By default the wrapper itself is\n * `<div>` block with `display: inline-block`.\n * @param tip – Anything React is able to render,\n * _e.g._ a tooltip text. This will be the tooltip content.\n * @param {WithTooltipTheme} props.theme _Ad hoc_ theme.\n */\nconst WithTooltip: FunctionComponent<PropsT> = ({\n children,\n className: classNameProp,\n onClick,\n onContextMenu,\n onMouseLeave,\n onMouseMove,\n onTouchStart,\n placement = PLACEMENTS.ABOVE_CURSOR,\n ref,\n style,\n theme,\n tip,\n ...htmlAttributes\n}) => {\n const custom = useTheme('WithTooltip', defaultTheme, theme);\n\n const [heap, setHeap] = useState<HeapT>({\n lastCursorX: 0,\n lastCursorY: 0,\n timerId: undefined,\n triggeredByTouch: false,\n });\n\n const tooltipRef = useRef<TooltipRefT>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [showTooltip, setShowTooltip] = useState(false);\n\n const updatePortalPosition = (cursorX: number, cursorY: number) => {\n if (showTooltip) {\n const wrapperRect = wrapperRef.current!.getBoundingClientRect();\n if (\n cursorX < wrapperRect.left\n || cursorX > wrapperRect.right\n || cursorY < wrapperRect.top\n || cursorY > wrapperRect.bottom\n ) {\n setShowTooltip(false);\n } else if (tooltipRef.current) {\n tooltipRef.current.pointTo(\n cursorX + window.scrollX,\n cursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n }\n } else {\n setHeap((prev) => {\n const res: HeapT = {\n ...prev,\n lastCursorX: cursorX,\n lastCursorY: cursorY,\n };\n\n // If tooltip was triggered by a touch, we delay its opening by a bit,\n // to ensure it was not a touch-click - in the case of touch click we\n // want to do the click, rather than show the tooltip, and the delay\n // gives click handler a chance to abort the tooltip openning.\n if (res.triggeredByTouch) {\n res.timerId ??= setTimeout(() => {\n setHeap((p) => ({\n ...p,\n timerId: undefined,\n triggeredByTouch: false,\n }));\n\n setShowTooltip(true);\n }, 300);\n\n // Otherwise we can just open the tooltip right away.\n } else setShowTooltip(true);\n\n return res;\n });\n }\n };\n\n useEffect(() => {\n if (showTooltip && tip !== null) {\n // This is necessary to ensure that even when a single mouse event\n // arrives to a tool-tipped component, the tooltip is correctly positioned\n // once opened (because similar call above does not have effect until\n // the tooltip is fully mounted, and that is delayed to future rendering\n // cycle due to the implementation).\n if (tooltipRef.current) {\n setHeap((prev) => {\n tooltipRef.current?.pointTo(\n prev.lastCursorX + window.scrollX,\n prev.lastCursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n return prev;\n });\n }\n\n const listener = () => {\n setShowTooltip(false);\n };\n window.addEventListener('scroll', listener);\n return () => {\n window.removeEventListener('scroll', listener);\n };\n }\n return undefined;\n }, [\n placement,\n showTooltip,\n tip,\n ]);\n\n let container = custom.wrapper;\n if (classNameProp) container += ` ${classNameProp}`;\n\n useEffect(() => {\n const listener = () => {\n setShowTooltip(false);\n heap.triggeredByTouch = false;\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n heap.timerId = undefined;\n heap.triggeredByTouch = false;\n }\n };\n window.addEventListener('touchcancel', listener);\n window.addEventListener('touchend', listener);\n return () => {\n window.removeEventListener('touchcancel', listener);\n window.removeEventListener('touchend', listener);\n };\n }, [heap]);\n\n return (\n <div\n className={container}\n onClick={(e) => {\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n\n setHeap({\n ...heap,\n timerId: undefined,\n triggeredByTouch: false,\n });\n }\n onClick?.(e);\n }}\n onContextMenu={(e) => {\n e.preventDefault();\n onContextMenu?.(e);\n }}\n onMouseLeave={(e) => {\n setShowTooltip(false);\n onMouseLeave?.(e);\n }}\n onMouseMove={(e) => {\n // NOTE: Because on touch devices mouse move events are still fired\n // after touch is released, to emulate mouse clicks for old websites.\n // If we don't ignore it here, the tooltip will appear after the touch\n // is released.\n if (!heap.ignoreMouseMove) {\n updatePortalPosition(e.clientX, e.clientY);\n }\n onMouseMove?.(e);\n }}\n onTouchStart={(e) => {\n setHeap({\n ...heap,\n ignoreMouseMove: true,\n triggeredByTouch: true,\n });\n\n // TODO: I guess, it should be something more complex here,\n // to actually respond to the first / whatever touch we need.\n const touch = e.targetTouches.item(0);\n updatePortalPosition(touch.clientX, touch.clientY);\n\n onTouchStart?.(e);\n }}\n ref={(node) => {\n wrapperRef.current = node;\n\n // eslint-disable-next-line no-param-reassign\n if (ref) ref.current = node;\n }}\n role=\"presentation\"\n style={style}\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...htmlAttributes}\n >\n {\n showTooltip && tip !== null\n ? <Tooltip ref={tooltipRef} theme={custom}>{tip}</Tooltip>\n : null\n }\n {children}\n </div>\n );\n};\n\ntype ExportT = {\n PLACEMENTS: typeof PLACEMENTS;\n} & typeof WithTooltip;\n\nconst e: ExportT = WithTooltip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ACO,OAAO,CAAG4B,IAAI,CAEzB;AACA,GAAIjD,GAAG,CAAEA,GAAG,CAACqB,OAAO,CAAG4B,IAAI,CAC7B,CAAE,CACFC,IAAI,CAAC,cAAc,CACnBjD,KAAK,CAAEA,KAEP;AAAA,IACIG,cAAc,CAAAd,QAAA,EAGhByB,WAAW,EAAIZ,GAAG,GAAK,IAAI,cACvBjB,IAAA,CAACJ,OAAO,EAACkB,GAAG,CAAEa,UAAW,CAACX,KAAK,CAAEG,MAAO,CAAAf,QAAA,CAAEa,GAAG,CAAU,CAAC,CACxD,IAAI,CAETb,QAAQ,EACN,CAAC,CAEV,CAAC,CAMD,KAAM,CAAAmD,CAAU,CAAGpD,WAAsB,CAEzCoD,CAAC,CAAC1D,UAAU,CAAGA,UAAU,CAEzB,cAAe,CAAA0D,CAAC","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import qs from"qs";import{useTheme}from"@dr.pogodin/react-themes";import Throbber from"../Throbber";import defaultTheme from"./base.scss";import throbberTheme from"./throbber.scss";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";/**
|
|
1
|
+
import{c as _c}from"react/compiler-runtime";import qs from"qs";import{useTheme}from"@dr.pogodin/react-themes";import Throbber from"../Throbber";import defaultTheme from"./base.scss";import throbberTheme from"./throbber.scss";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";/**
|
|
2
2
|
* A component for embeding a YouTube video.
|
|
3
3
|
* @param [props] Component properties.
|
|
4
4
|
* @param [props.autoplay] If `true` the video will start to play
|
|
@@ -12,8 +12,5 @@ import qs from"qs";import{useTheme}from"@dr.pogodin/react-themes";import Throbbe
|
|
|
12
12
|
* @param [props.theme] _Ad hoc_ theme.
|
|
13
13
|
* @param [props.title] The `title` attribute to add to the player
|
|
14
14
|
* IFrame.
|
|
15
|
-
*/const YouTubeVideo=({autoplay,src,theme,title}
|
|
16
|
-
// More query parameters can be exposed via the component props.
|
|
17
|
-
return/*#__PURE__*/_jsxs("div",{className:custom.container,children:[/*#__PURE__*/_jsx(Throbber,{theme:throbberTheme}),/*#__PURE__*/_jsx("iframe",{// eslint-disable-line react/iframe-missing-sandbox
|
|
18
|
-
allow:"autoplay",allowFullScreen:true,className:custom.video,src:url,title:title})]});};export default YouTubeVideo;
|
|
15
|
+
*/const YouTubeVideo=t0=>{const $=_c(13);const{autoplay,src,theme,title}=t0;const custom=useTheme("YouTubeVideo",defaultTheme,theme);let t1;let t2;let url;if($[0]!==autoplay||$[1]!==src){const srcParts=src.split("?");[url]=srcParts;const[,queryString]=srcParts;const query=queryString?qs.parse(queryString):{};const videoId=query.v??url?.match(/\/([a-zA-Z0-9-_]*)$/)?.[1];url=`https://www.youtube.com/embed/${videoId}`;delete query.v;query.autoplay=autoplay?"1":"0";t2=url;t1=qs.stringify(query);$[0]=autoplay;$[1]=src;$[2]=t1;$[3]=t2;$[4]=url}else{t1=$[2];t2=$[3];url=$[4]}url=t2+`?${t1}`;let t3;if($[5]===Symbol.for("react.memo_cache_sentinel")){t3=/*#__PURE__*/_jsx(Throbber,{theme:throbberTheme});$[5]=t3}else{t3=$[5]}let t4;if($[6]!==custom.video||$[7]!==title||$[8]!==url){t4=/*#__PURE__*/_jsx("iframe",{allow:"autoplay",allowFullScreen:true,className:custom.video,src:url,title:title});$[6]=custom.video;$[7]=title;$[8]=url;$[9]=t4}else{t4=$[9]}let t5;if($[10]!==custom.container||$[11]!==t4){t5=/*#__PURE__*/_jsxs("div",{className:custom.container,children:[t3,t4]});$[10]=custom.container;$[11]=t4;$[12]=t5}else{t5=$[12]}return t5};export default YouTubeVideo;
|
|
19
16
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["qs","useTheme","Throbber","defaultTheme","throbberTheme","jsx","_jsx","jsxs","_jsxs","YouTubeVideo","autoplay","src","theme","title","custom","
|
|
1
|
+
{"version":3,"file":"index.js","names":["qs","useTheme","Throbber","defaultTheme","throbberTheme","jsx","_jsx","jsxs","_jsxs","YouTubeVideo","t0","$","_c","autoplay","src","theme","title","custom","t1","t2","url","srcParts","split","queryString","query","parse","videoId","v","match","stringify","t3","Symbol","for","t4","video","allow","allowFullScreen","className","t5","container","children"],"sources":["../../../../../src/shared/components/YouTubeVideo/index.tsx"],"sourcesContent":["import qs from 'qs';\nimport type { FunctionComponent } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Throbber from 'components/Throbber';\n\nimport defaultTheme from './base.scss';\nimport throbberTheme from './throbber.scss';\n\ntype ThemeT = Theme<'container' | 'video'>;\n\ntype PropsT = {\n autoplay?: boolean;\n src: string;\n theme?: ThemeT;\n title?: string;\n};\n\n/**\n * A component for embeding a YouTube video.\n * @param [props] Component properties.\n * @param [props.autoplay] If `true` the video will start to play\n * automatically once loaded.\n * @param [props.src] URL of the video to play. Can be in any of\n * the following formats, and keeps any additional query parameters understood\n * by the YouTube IFrame player:\n * - `https://www.youtube.com/watch?v=NdF6Rmt6Ado`\n * - `https://youtu.be/NdF6Rmt6Ado`\n * - `https://www.youtube.com/embed/NdF6Rmt6Ado`\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.title] The `title` attribute to add to the player\n * IFrame.\n */\nconst YouTubeVideo: FunctionComponent<PropsT> = ({\n autoplay,\n src,\n theme,\n title,\n}) => {\n const custom = useTheme('YouTubeVideo', defaultTheme, theme);\n\n const srcParts = src.split('?');\n let [url] = srcParts;\n const [, queryString] = srcParts;\n const query = queryString ? qs.parse(queryString) : {};\n\n const videoId = query.v ?? url?.match(/\\/([a-zA-Z0-9-_]*)$/)?.[1];\n url = `https://www.youtube.com/embed/${videoId as string}`;\n\n delete query.v;\n query.autoplay = autoplay ? '1' : '0';\n url += `?${qs.stringify(query)}`;\n\n // TODO: https://developers.google.com/youtube/player_parameters\n // More query parameters can be exposed via the component props.\n\n return (\n <div className={custom.container}>\n <Throbber theme={throbberTheme} />\n {/* TODO: I guess, we better add the sanbox, but right now I don't have\n time to carefully explore which restrictions should be lifted to allow\n embed YouTube player to work... sometime later we'll take care of it */\n }\n <iframe // eslint-disable-line react/iframe-missing-sandbox\n allow=\"autoplay\"\n allowFullScreen\n className={custom.video}\n src={url}\n title={title}\n />\n </div>\n );\n};\n\nexport default YouTubeVideo;\n"],"mappings":"4CAAA,MAAO,CAAAA,EAAE,KAAM,IAAI,CAGnB,OAAqBC,QAAQ,KAAQ,0BAA0B,CAE/D,MAAO,CAAAC,QAAQ,mBAEf,MAAO,CAAAC,YAAY,mBACnB,MAAO,CAAAC,aAAa,uBAAwB,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAW5C;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,YAAuC,CAAGC,EAAA,SAAAC,CAAA,CAAAC,EAAA,KAAC,MAAAC,QAAA,CAAAC,GAAA,CAAAC,KAAA,CAAAC,KAAA,EAAAN,EAKhD,CACC,MAAAO,MAAA,CAAehB,QAAQ,CAAC,cAAc,CAAEE,YAAY,CAAEY,KAAK,CAAC,CAAC,IAAAG,EAAA,KAAAC,EAAA,KAAAC,GAAA,IAAAT,CAAA,MAAAE,QAAA,EAAAF,CAAA,MAAAG,GAAA,EAE7D,MAAAO,QAAA,CAAiBP,GAAG,CAAAQ,KAAM,CAAC,GAAG,CAAC,CAC/B,CAAAF,GAAA,EAAYC,QAAQ,CACpB,OAAAE,WAAA,EAAwBF,QAAQ,CAChC,MAAAG,KAAA,CAAcD,WAAW,CAAGvB,EAAE,CAAAyB,KAAM,CAACF,WAAgB,CAAC,CAAxC,CAAuC,CAAC,CAEtD,MAAAG,OAAA,CAAgBF,KAAK,CAAAG,CAA4C,EAAtCP,GAAG,EAAAQ,KAA8B,CAAtB,qBAA0B,CAAC,MACjER,IAAMA,iCAAiCM,OAAO,EAAY,CAE1D,MAAO,CAAAF,KAAK,CAAAG,CAAE,CACdH,KAAK,CA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AsB,SAAA5B,CAAA,MAAAsB,EAAAtB,CAAA,MAAA2B,EAAA,MAAAA,EAAA,CAAA3B,CAAA,WAbN,CAAA2B,EAaM,CAET,CAED,cAAe,CAAA7B,YAAY","ignoreList":[]}
|
|
@@ -1,7 +1,2 @@
|
|
|
1
|
-
import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import{useImperativeHandle,useRef}from"react";import{BaseModal}from"../../../Modal";import{optionValueName}from"../../common";import S from"./style.scss";import{jsx as _jsx}from"react/jsx-runtime";export function areEqual(a,b){return a?.left===b?.left&&a?.top===b?.top&&a?.width===b?.width;}const Options=({containerClass,containerStyle,filter,onCancel,onChange,optionClass,options,ref}
|
|
2
|
-
// This is the same native <select> elements do on scrolling, and at least for
|
|
3
|
-
// now we have no reason to deal with complications needed to support open
|
|
4
|
-
// dropdowns during the scrolling (that would need to re-position it in
|
|
5
|
-
// response to the position changes of the root dropdown element).
|
|
6
|
-
,{cancelOnScrolling:true,dontDisableScrolling:true,onCancel:onCancel,style:containerStyle,theme:{ad:"",container:containerClass,context:"",hoc:"",overlay:S.overlay},children:/*#__PURE__*/_jsx("div",{ref:opsRef,children:optionNodes})});};export default Options;
|
|
1
|
+
import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import{c as _c}from"react/compiler-runtime";import{useImperativeHandle,useRef}from"react";import{BaseModal}from"../../../Modal";import{optionValueName}from"../../common";import S from"./style.scss";import{jsx as _jsx}from"react/jsx-runtime";export function areEqual(a,b){return a?.left===b?.left&&a?.top===b?.top&&a?.width===b?.width;}const Options=t0=>{const $=_c(16);const{containerClass,containerStyle,filter,onCancel,onChange,optionClass,options,ref}=t0;const opsRef=useRef(null);let t1;let t2;if($[0]===Symbol.for("react.memo_cache_sentinel")){t1=()=>({measure:()=>{const e=opsRef.current?.parentElement;if(!e){return}const rect=opsRef.current.getBoundingClientRect();const style=window.getComputedStyle(e);const mBottom=parseFloat(style.marginBottom);const mTop=parseFloat(style.marginTop);rect.height=rect.height+(mBottom+mTop);return rect}});t2=[];$[0]=t1;$[1]=t2}else{t1=$[0];t2=$[1]}useImperativeHandle(ref,t1,t2);let optionNodes;if($[2]!==filter||$[3]!==onChange||$[4]!==optionClass||$[5]!==options){optionNodes=[];for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);optionNodes.push(/*#__PURE__*/_jsx("div",{className:optionClass,onClick:e_0=>{onChange(iValue);e_0.stopPropagation()},onKeyDown:e_1=>{if(e_1.key==="Enter"){onChange(iValue);e_1.stopPropagation()}},role:"button",tabIndex:0,children:iName},iValue))}}$[2]=filter;$[3]=onChange;$[4]=optionClass;$[5]=options;$[6]=optionNodes}else{optionNodes=$[6]}let t3;if($[7]!==containerClass){t3={ad:"",container:containerClass,context:"",hoc:"",overlay:S.overlay};$[7]=containerClass;$[8]=t3}else{t3=$[8]}let t4;if($[9]!==optionNodes){t4=/*#__PURE__*/_jsx("div",{ref:opsRef,children:optionNodes});$[9]=optionNodes;$[10]=t4}else{t4=$[10]}let t5;if($[11]!==containerStyle||$[12]!==onCancel||$[13]!==t3||$[14]!==t4){t5=/*#__PURE__*/_jsx(BaseModal,{cancelOnScrolling:true,dontDisableScrolling:true,onCancel:onCancel,style:containerStyle,theme:t3,children:t4});$[11]=containerStyle;$[12]=onCancel;$[13]=t3;$[14]=t4;$[15]=t5}else{t5=$[15]}return t5};export default Options;
|
|
7
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useImperativeHandle","useRef","BaseModal","optionValueName","S","jsx","_jsx","areEqual","a","b","left","top","width","Options","containerClass","containerStyle","filter","onCancel","onChange","optionClass","options","ref","opsRef","measure","e","current","parentElement","
|
|
1
|
+
{"version":3,"file":"index.js","names":["useImperativeHandle","useRef","BaseModal","optionValueName","S","jsx","_jsx","areEqual","a","b","left","top","width","Options","t0","$","_c","containerClass","containerStyle","filter","onCancel","onChange","optionClass","options","ref","opsRef","t1","t2","Symbol","for","measure","e","current","parentElement","rect","getBoundingClientRect","style","window","getComputedStyle","mBottom","parseFloat","marginBottom","mTop","marginTop","height","optionNodes","option","iValue","iName","push","onClick","e_0","stopPropagation","onKeyDown","e_1","key","role","tabIndex","children","t3","ad","container","context","hoc","overlay","t4","t5","cancelOnScrolling","dontDisableScrolling","theme"],"sources":["../../../../../../../src/shared/components/selectors/CustomDropdown/Options/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useImperativeHandle,\n useRef,\n} from 'react';\n\nimport { BaseModal } from 'components/Modal';\n\nimport {\n type OptionT,\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../../common';\n\nimport S from './style.scss';\n\nexport type ContainerPosT = {\n left: number;\n top: number;\n width: number;\n};\n\nexport function areEqual(a?: ContainerPosT, b?: ContainerPosT): boolean {\n return a?.left === b?.left && a?.top === b?.top && a?.width === b?.width;\n}\n\nexport type RefT = {\n measure: () => DOMRect | undefined;\n};\n\ntype PropsT = {\n containerClass: string;\n containerStyle?: ContainerPosT;\n filter?: (item: OptionT<ReactNode> | ValueT) => boolean;\n onCancel: () => void;\n onChange: (value: ValueT) => void;\n optionClass: string;\n options: Readonly<OptionsT<ReactNode>>;\n ref?: RefObject<RefT | null>;\n};\n\nconst Options: FunctionComponent<PropsT> = ({\n containerClass,\n containerStyle,\n filter,\n onCancel,\n onChange,\n optionClass,\n options,\n ref,\n}) => {\n const opsRef = useRef<HTMLDivElement>(null);\n\n useImperativeHandle(ref, () => ({\n measure: () => {\n const e = opsRef.current?.parentElement;\n if (!e) return undefined;\n\n const rect = opsRef.current!.getBoundingClientRect();\n const style = window.getComputedStyle(e);\n const mBottom = parseFloat(style.marginBottom);\n const mTop = parseFloat(style.marginTop);\n\n rect.height += mBottom + mTop;\n\n return rect;\n },\n }), []);\n\n const optionNodes: ReactNode[] = [];\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n optionNodes.push(\n <div\n className={optionClass}\n key={iValue}\n onClick={(e) => {\n onChange(iValue);\n e.stopPropagation();\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n onChange(iValue);\n e.stopPropagation();\n }\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>,\n );\n }\n }\n\n return (\n <BaseModal\n // Closes the dropdown (cancels the selection) on any page scrolling attempt.\n // This is the same native <select> elements do on scrolling, and at least for\n // now we have no reason to deal with complications needed to support open\n // dropdowns during the scrolling (that would need to re-position it in\n // response to the position changes of the root dropdown element).\n cancelOnScrolling\n dontDisableScrolling\n onCancel={onCancel}\n style={containerStyle}\n theme={{\n ad: '',\n container: containerClass,\n context: '',\n hoc: '',\n overlay: S.overlay,\n }}\n >\n <div ref={opsRef}>{optionNodes}</div>\n </BaseModal>\n );\n};\n\nexport default Options;\n"],"mappings":"sLAAA,OAIEA,mBAAmB,CACnBC,MAAM,KACD,OAAO,CAEd,OAASC,SAAS,sBAElB,OAIEC,eAAe,oBAGjB,MAAO,CAAAC,CAAC,oBAAqB,OAAAC,GAAA,IAAAC,IAAA,yBAQ7B,MAAO,SAAS,CAAAC,QAAQA,CAACC,CAAiB,CAAEC,CAAiB,CAAW,CACtE,MAAO,CAAAD,CAAC,EAAEE,IAAI,GAAKD,CAAC,EAAEC,IAAI,EAAIF,CAAC,EAAEG,GAAG,GAAKF,CAAC,EAAEE,GAAG,EAAIH,CAAC,EAAEI,KAAK,GAAKH,CAAC,EAAEG,KAAK,CAC1E,CAiBA,KAAM,CAAAC,OAAkC,CAAGC,EAAA,SAAAC,CAAA,CAAAC,EAAA,KAAC,MAAAC,cAAA,CAAAC,cAAA,CAAAC,MAAA,CAAAC,QAAA,CAAAC,QAAA,CAAAC,WAAA,CAAAC,OAAA,CAAAC,GAAA,EAAAV,EAS3C,CACC,MAAAW,MAAA,CAAexB,MAAM,CAAiB,IAAI,CAAC,CAAC,IAAAyB,EA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AdA,cAAc,CACdmD,KAMN,CANMV,EAMN,CAAAD,QAAA,CAEDO,EAAqC,CAC5B,CAAC,CAAAlD,CAAA,KAAAG,cAAAH,CAAA,MAAAK,QAAAL,CAAA,MAAA4C,EAAA5C,CAAA,MAAAkD,EAAAlD,CAAA,MAAAmD,EAAA,MAAAA,EAAA,CAAAnD,CAAA,WAnBZ,CAAAmD,EAmBY,CAEf,CAED,cAAe,CAAArD,OAAO","ignoreList":[]}
|
|
@@ -1,8 +1,2 @@
|
|
|
1
|
-
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import{useEffect,useRef,useState}from"react";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common";import Options,{areEqual}from"./Options";import defaultTheme from"./theme.scss";import{Fragment as _Fragment,jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const CustomDropdown=({filter,label,onChange,options,theme,value}
|
|
2
|
-
// by an effect declared above, and then positioned below, or above
|
|
3
|
-
// the original dropdown element, depending where it fits best
|
|
4
|
-
// (if we first open it downward, it would flick if we immediately
|
|
5
|
-
// move it above, at least with the current position update via local
|
|
6
|
-
// react state, and not imperatively).
|
|
7
|
-
setOpsPos({left:view?.width??0,top:view?.height??0,width:rect.width});e.stopPropagation();};let selected=/*#__PURE__*/_jsx(_Fragment,{children:"\u200C"});for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);if(iValue===value){selected=iName;break;}}}let containerClassName=custom.container;if(active)containerClassName+=` ${custom.active}`;let opsContainerClass=custom.select??"";if(upward){containerClassName+=` ${custom.upward}`;opsContainerClass+=` ${custom.upward}`;}return/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[label===undefined?null:/*#__PURE__*/_jsx("div",{className:custom.label,children:label}),/*#__PURE__*/_jsxs("div",{className:custom.dropdown,onClick:openList,onKeyDown:e=>{if(e.key==="Enter")openList(e);},ref:dropdownRef,role:"listbox",tabIndex:0,children:[selected,/*#__PURE__*/_jsx("div",{className:custom.arrow})]}),active?/*#__PURE__*/_jsx(Options,{containerClass:opsContainerClass,containerStyle:opsPos,onCancel:()=>{setActive(false);},onChange:newValue=>{setActive(false);if(onChange)onChange(newValue);},optionClass:custom.option??"",options:options,ref:opsRef}):null]});};export default CustomDropdown;
|
|
1
|
+
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import{c as _c}from"react/compiler-runtime";import{useEffect,useRef,useState}from"react";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common";import Options,{areEqual}from"./Options";import defaultTheme from"./theme.scss";import{Fragment as _Fragment,jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const CustomDropdown=t0=>{const $=_c(31);const{filter,label,onChange,options,theme,value}=t0;const custom=useTheme("CustomDropdown",defaultTheme,theme);const[active,setActive]=useState(false);const dropdownRef=useRef(null);const opsRef=useRef(null);const[opsPos,setOpsPos]=useState();const[upward,setUpward]=useState(false);let t1;let t2;if($[0]!==active){t1=()=>{if(!active){return}let id;const cb=()=>{const anchor=dropdownRef.current?.getBoundingClientRect();const opsRect=opsRef.current?.measure();if(anchor&&opsRect){const fitsDown=anchor.bottom+opsRect.height<(window.visualViewport?.height??0);const fitsUp=anchor.top-opsRect.height>0;const up=!fitsDown&&fitsUp;setUpward(up);const pos=up?{left:anchor.left,top:anchor.top-opsRect.height-1,width:anchor.width}:{left:anchor.left,top:anchor.bottom,width:anchor.width};setOpsPos(now=>areEqual(now,pos)?now:pos)}id=requestAnimationFrame(cb);};requestAnimationFrame(cb);return()=>{cancelAnimationFrame(id)}};t2=[active];$[0]=active;$[1]=t1;$[2]=t2}else{t1=$[1];t2=$[2]}useEffect(t1,t2);let t3;if($[3]===Symbol.for("react.memo_cache_sentinel")){t3=e=>{const view=window.visualViewport;const rect=dropdownRef.current.getBoundingClientRect();setActive(true);setOpsPos({left:view?.width??0,top:view?.height??0,width:rect.width});e.stopPropagation()};$[3]=t3}else{t3=$[3]}const openList=t3;let t4;if($[4]===Symbol.for("react.memo_cache_sentinel")){t4=/*#__PURE__*/_jsx(_Fragment,{children:"\u200C"});$[4]=t4}else{t4=$[4]}let selected=t4;if($[5]!==filter||$[6]!==options||$[7]!==value){for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);if(iValue===value){selected=iName;break;}}}$[5]=filter;$[6]=options;$[7]=value;$[8]=selected}else{selected=$[8]}let containerClassName=custom.container;if(active){containerClassName=containerClassName+` ${custom.active}`;}let opsContainerClass=custom.select??"";if(upward){containerClassName=containerClassName+` ${custom.upward}`;opsContainerClass=opsContainerClass+` ${custom.upward}`;}let t5;if($[9]!==custom.label||$[10]!==label){t5=label===undefined?null:/*#__PURE__*/_jsx("div",{className:custom.label,children:label});$[9]=custom.label;$[10]=label;$[11]=t5}else{t5=$[11]}let t6;if($[12]===Symbol.for("react.memo_cache_sentinel")){t6=e_0=>{if(e_0.key==="Enter"){openList(e_0)}};$[12]=t6}else{t6=$[12]}let t7;if($[13]!==custom.arrow){t7=/*#__PURE__*/_jsx("div",{className:custom.arrow});$[13]=custom.arrow;$[14]=t7}else{t7=$[14]}let t8;if($[15]!==custom.dropdown||$[16]!==selected||$[17]!==t7){t8=/*#__PURE__*/_jsxs("div",{className:custom.dropdown,onClick:openList,onKeyDown:t6,ref:dropdownRef,role:"listbox",tabIndex:0,children:[selected,t7]});$[15]=custom.dropdown;$[16]=selected;$[17]=t7;$[18]=t8}else{t8=$[18]}let t9;if($[19]!==active||$[20]!==custom.option||$[21]!==onChange||$[22]!==opsContainerClass||$[23]!==opsPos||$[24]!==options){t9=active?/*#__PURE__*/_jsx(Options,{containerClass:opsContainerClass,containerStyle:opsPos,onCancel:()=>{setActive(false)},onChange:newValue=>{setActive(false);if(onChange){onChange(newValue)}},optionClass:custom.option??"",options:options,ref:opsRef}):null;$[19]=active;$[20]=custom.option;$[21]=onChange;$[22]=opsContainerClass;$[23]=opsPos;$[24]=options;$[25]=t9}else{t9=$[25]}let t10;if($[26]!==containerClassName||$[27]!==t5||$[28]!==t8||$[29]!==t9){t10=/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[t5,t8,t9]});$[26]=containerClassName;$[27]=t5;$[28]=t8;$[29]=t9;$[30]=t10}else{t10=$[30]}return t10};export default CustomDropdown;
|
|
8
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","useTheme","optionValueName","Options","areEqual","defaultTheme","Fragment","_Fragment","jsx","_jsx","jsxs","_jsxs","CustomDropdown","filter","label","onChange","options","theme","value","custom","active","setActive","dropdownRef","opsRef","opsPos","setOpsPos","upward","setUpward","undefined","id","cb","anchor","current","getBoundingClientRect","opsRect","measure","fitsDown","bottom","height","window","visualViewport","fitsUp","top","up","pos","left","width","now","requestAnimationFrame","cancelAnimationFrame","openList","e","view","rect","stopPropagation","selected","children","option","iValue","iName","containerClassName","container","opsContainerClass","select","className","dropdown","onClick","onKeyDown","key","ref","role","tabIndex","arrow","containerClass","containerStyle","onCancel","newValue","optionClass"],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, type ValueT, optionValueName } from '../common';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nconst CustomDropdown: FunctionComponent<\n PropsT<ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const custom = useTheme('CustomDropdown', defaultTheme, theme);\n\n const [active, setActive] = useState(false);\n\n const dropdownRef = useRef<HTMLDivElement>(null);\n const opsRef = useRef<RefT>(null);\n\n const [opsPos, setOpsPos] = useState<ContainerPosT>();\n const [upward, setUpward] = useState(false);\n\n useEffect(() => {\n if (!active) return undefined;\n\n let id: number;\n const cb = () => {\n const anchor = dropdownRef.current?.getBoundingClientRect();\n const opsRect = opsRef.current?.measure();\n if (anchor && opsRect) {\n const fitsDown = anchor.bottom + opsRect.height\n < (window.visualViewport?.height ?? 0);\n const fitsUp = anchor.top - opsRect.height > 0;\n\n const up = !fitsDown && fitsUp;\n setUpward(up);\n\n const pos = up ? {\n left: anchor.left,\n top: anchor.top - opsRect.height - 1,\n width: anchor.width,\n } : {\n left: anchor.left,\n top: anchor.bottom,\n width: anchor.width,\n };\n\n setOpsPos((now) => (areEqual(now, pos) ? now : pos));\n }\n id = requestAnimationFrame(cb);\n };\n requestAnimationFrame(cb);\n\n return () => {\n cancelAnimationFrame(id);\n };\n }, [active]);\n\n const openList = (\n e: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>,\n ) => {\n const view = window.visualViewport;\n const rect = dropdownRef.current!.getBoundingClientRect();\n setActive(true);\n\n // NOTE: This first opens the dropdown off-screen, where it is measured\n // by an effect declared above, and then positioned below, or above\n // the original dropdown element, depending where it fits best\n // (if we first open it downward, it would flick if we immediately\n // move it above, at least with the current position update via local\n // react state, and not imperatively).\n setOpsPos({\n left: view?.width ?? 0,\n top: view?.height ?? 0,\n width: rect.width,\n });\n\n e.stopPropagation();\n };\n\n let selected: React.ReactNode = <>‌</>;\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n if (iValue === value) {\n selected = iName;\n break;\n }\n }\n }\n\n let containerClassName = custom.container;\n if (active) containerClassName += ` ${custom.active}`;\n\n let opsContainerClass = custom.select ?? '';\n if (upward) {\n containerClassName += ` ${custom.upward}`;\n opsContainerClass += ` ${custom.upward}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={custom.label}>{label}</div>}\n <div\n className={custom.dropdown}\n onClick={openList}\n onKeyDown={(e) => {\n if (e.key === 'Enter') openList(e);\n }}\n ref={dropdownRef}\n role=\"listbox\"\n tabIndex={0}\n >\n {selected}\n <div className={custom.arrow} />\n </div>\n {\n active ? (\n <Options\n containerClass={opsContainerClass}\n containerStyle={opsPos}\n onCancel={() => {\n setActive(false);\n }}\n onChange={(newValue) => {\n setActive(false);\n if (onChange) onChange(newValue);\n }}\n optionClass={custom.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default CustomDropdown;\n"],"mappings":"iGAAA,OAGEA,SAAS,CACTC,MAAM,CACNC,QAAQ,KACH,OAAO,CAEd,OAASC,QAAQ,KAAQ,0BAA0B,CAEnD,OAAmCC,eAAe,iBAElD,MAAO,CAAAC,OAAO,EAAmCC,QAAQ,iBAEzD,MAAO,CAAAC,YAAY,oBAAqB,OAAAC,QAAA,IAAAC,SAAA,CAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAExC,KAAM,CAAAC,cAEL,CAAGA,CAAC,CACHC,MAAM,CACNC,KAAK,CACLC,QAAQ,CACRC,OAAO,CACPC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,KAAM,CAAAC,MAAM,CAAGlB,QAAQ,CAAC,gBAAgB,CAAEI,YAAY,CAAEY,KAAK,CAAC,CAE9D,KAAM,CAACG,MAAM,CAAEC,SAAS,CAAC,CAAGrB,QAAQ,CAAC,KAAK,CAAC,CAE3C,KAAM,CAAAsB,WAAW,CAAGvB,MAAM,CAAiB,IAAI,CAAC,CAChD,KAAM,CAAAwB,MAAM,CAAGxB,MAAM,CAAO,IAAI,CAAC,CAEjC,KAAM,CAACyB,MAAM,CAAEC,SAAS,CAAC,CAAGzB,QAAQ,CAAgB,CAAC,CACrD,KAAM,CAAC0B,MAAM,CAAEC,SAAS,CAAC,CAAG3B,QAAQ,CAAC,KAAK,CAAC,CAE3CF,SAAS,CAAC,IAAM,CACd,GAAI,CAACsB,MAAM,CAAE,MAAO,CAAAQ,SAAS,CAE7B,GAAI,CAAAC,EAAU,CACd,KAAM,CAAAC,EAAE,CAAGA,CAAA,GAAM,CACf,KAAM,CAAAC,MAAM,CAAGT,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AAM,CAACL,KAAM,CAAA0C,QAAA,CAAE1C,KAAK,CAAM,CAAC,cAC/CH,KAAA,QACEqD,SAAS,CAAE7C,MAAM,CAAC8C,QAAS,CAC3BC,OAAO,CAAEhB,QAAS,CAClBiB,SAAS,CAAGhB,CAAC,EAAK,CAChB,GAAIA,CAAC,CAACiB,GAAG,GAAK,OAAO,CAAElB,QAAQ,CAACC,CAAC,CAAC,CACpC,CAAE,CACFkB,GAAG,CAAE/C,WAAY,CACjBgD,IAAI,CAAC,SAAS,CACdC,QAAQ,CAAE,CAAE,CAAAf,QAAA,EAEXD,QAAQ,cACT9C,IAAA,QAAKuD,SAAS,CAAE7C,MAAM,CAACqD,KAAM,CAAE,CAAC,EAC7B,CAAC,CAEJpD,MAAM,cACJX,IAAA,CAACN,OAAO,EACNsE,cAAc,CAAEX,iBAAkB,CAClCY,cAAc,CAAElD,MAAO,CACvBmD,QAAQ,CAAEA,CAAA,GAAM,CACdtD,SAAS,CAAC,KAAK,CAAC,CAClB,CAAE,CACFN,QAAQ,CAAG6D,QAAQ,EAAK,CACtBvD,SAAS,CAAC,KAAK,CAAC,CAChB,GAAIN,QAAQ,CAAEA,QAAQ,CAAC6D,QAAQ,CAAC,CAClC,CAAE,CACFC,WAAW,CAAE1D,MAAM,CAACsC,MAAM,EAAI,EAAG,CACjCzC,OAAO,CAAEA,OAAQ,CACjBqD,GAAG,CAAE9C,MAAO,CACb,CAAC,CACA,IAAI,EAEP,CAAC,CAEV,CAAC,CAED,cAAe,CAAAX,cAAc","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","useTheme","optionValueName","Options","areEqual","defaultTheme","Fragment","_Fragment","jsx","_jsx","jsxs","_jsxs","CustomDropdown","t0","$","_c","filter","label","onChange","options","theme","value","custom","active","setActive","dropdownRef","opsRef","opsPos","setOpsPos","upward","setUpward","t1","t2","id","cb","anchor","current","getBoundingClientRect","opsRect","measure","fitsDown","bottom","height","window","visualViewport","fitsUp","top","up","pos","left","width","now","requestAnimationFrame","cancelAnimationFrame","t3","Symbol","for","e","view","rect","stopPropagation","openList","t4","children","selected","option","iValue","iName","containerClassName","container","opsContainerClass","select","t5","undefined","className","t6","e_0","key","t7","arrow","t8","dropdown","onKeyDown","role","tabIndex","t9","onCancel","newValue","optionClass","t10"],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, type ValueT, optionValueName } from '../common';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nconst CustomDropdown: FunctionComponent<\n PropsT<ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const custom = useTheme('CustomDropdown', defaultTheme, theme);\n\n const [active, setActive] = useState(false);\n\n const dropdownRef = useRef<HTMLDivElement>(null);\n const opsRef = useRef<RefT>(null);\n\n const [opsPos, setOpsPos] = useState<ContainerPosT>();\n const [upward, setUpward] = useState(false);\n\n useEffect(() => {\n if (!active) return undefined;\n\n let id: number;\n const cb = () => {\n const anchor = dropdownRef.current?.getBoundingClientRect();\n const opsRect = opsRef.current?.measure();\n if (anchor && opsRect) {\n const fitsDown = anchor.bottom + opsRect.height\n < (window.visualViewport?.height ?? 0);\n const fitsUp = anchor.top - opsRect.height > 0;\n\n const up = !fitsDown && fitsUp;\n setUpward(up);\n\n const pos = up ? {\n left: anchor.left,\n top: anchor.top - opsRect.height - 1,\n width: anchor.width,\n } : {\n left: anchor.left,\n top: anchor.bottom,\n width: anchor.width,\n };\n\n setOpsPos((now) => (areEqual(now, pos) ? now : pos));\n }\n id = requestAnimationFrame(cb);\n };\n requestAnimationFrame(cb);\n\n return () => {\n cancelAnimationFrame(id);\n };\n }, [active]);\n\n const openList = (\n e: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>,\n ) => {\n const view = window.visualViewport;\n const rect = dropdownRef.current!.getBoundingClientRect();\n setActive(true);\n\n // NOTE: This first opens the dropdown off-screen, where it is measured\n // by an effect declared above, and then positioned below, or above\n // the original dropdown element, depending where it fits best\n // (if we first open it downward, it would flick if we immediately\n // move it above, at least with the current position update via local\n // react state, and not imperatively).\n setOpsPos({\n left: view?.width ?? 0,\n top: view?.height ?? 0,\n width: rect.width,\n });\n\n e.stopPropagation();\n };\n\n let selected: React.ReactNode = <>‌</>;\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n if (iValue === value) {\n selected = iName;\n break;\n }\n }\n }\n\n let containerClassName = custom.container;\n if (active) containerClassName += ` ${custom.active}`;\n\n let opsContainerClass = custom.select ?? '';\n if (upward) {\n containerClassName += ` ${custom.upward}`;\n opsContainerClass += ` ${custom.upward}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={custom.label}>{label}</div>}\n <div\n className={custom.dropdown}\n onClick={openList}\n onKeyDown={(e) => {\n if (e.key === 'Enter') openList(e);\n }}\n ref={dropdownRef}\n role=\"listbox\"\n tabIndex={0}\n >\n {selected}\n <div className={custom.arrow} />\n </div>\n {\n active ? (\n <Options\n containerClass={opsContainerClass}\n containerStyle={opsPos}\n onCancel={() => {\n setActive(false);\n }}\n onChange={(newValue) => {\n setActive(false);\n if (onChange) onChange(newValue);\n }}\n optionClass={custom.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default CustomDropdown;\n"],"mappings":"6IAAA,OAGEA,SAAS,CACTC,MAAM,CACNC,QAAQ,KACH,OAAO,CAEd,OAASC,QAAQ,KAAQ,0BAA0B,CAEnD,OAAmCC,eAAe,iBAElD,MAAO,CAAAC,OAAO,EAAmCC,QAAQ,iBAEzD,MAAO,CAAAC,YAAY,oBAAqB,OAAAC,QAAA,IAAAC,SAAA,CAAAC,GAAA,I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D,CAAA,MAAAkE,EAAAlE,CAAA,MAAAuE,EAAAvE,CAAA,MAAA2E,GAAA,MAAAA,GAAA,CAAA3E,CAAA,WAlCN,CAAA2E,GAkCM,CAET,CAED,cAAe,CAAA7E,cAAc","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"core-js/modules/es.array.push.js";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common";import defaultTheme from"./theme.scss";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export const Switch=({label,onChange,options,theme,value}
|
|
1
|
+
import"core-js/modules/es.array.push.js";import{c as _c}from"react/compiler-runtime";import{useTheme}from"@dr.pogodin/react-themes";import{optionValueName}from"../common";import defaultTheme from"./theme.scss";import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";export const Switch=t0=>{const $=_c(16);const{label,onChange,options,theme,value}=t0;const composed=useTheme("Switch",defaultTheme,theme);if(!options||!composed.option){throw Error("Internal error");}let optionNodes;if($[0]!==composed.option||$[1]!==composed.selected||$[2]!==onChange||$[3]!==options||$[4]!==value){optionNodes=[];for(const option of options){const[iValue,iName]=optionValueName(option);let className=composed.option;let onPress;if(iValue===value){className=className+` ${composed.selected}`;}else{if(onChange){onPress=()=>{onChange(iValue)};}}optionNodes.push(onPress?/*#__PURE__*/_jsx("div",{className:className,onClick:onPress,onKeyDown:e=>{if(e.key==="Enter"){onPress()}},role:"button",tabIndex:0,children:iName},iValue):/*#__PURE__*/_jsx("div",{className:className,children:iName},iValue))}$[0]=composed.option;$[1]=composed.selected;$[2]=onChange;$[3]=options;$[4]=value;$[5]=optionNodes}else{optionNodes=$[5]}let t1;if($[6]!==composed.label||$[7]!==label){t1=label?/*#__PURE__*/_jsx("div",{className:composed.label,children:label}):null;$[6]=composed.label;$[7]=label;$[8]=t1}else{t1=$[8]}let t2;if($[9]!==composed.options||$[10]!==optionNodes){t2=/*#__PURE__*/_jsx("div",{className:composed.options,children:optionNodes});$[9]=composed.options;$[10]=optionNodes;$[11]=t2}else{t2=$[11]}let t3;if($[12]!==composed.container||$[13]!==t1||$[14]!==t2){t3=/*#__PURE__*/_jsxs("div",{className:composed.container,children:[t1,t2]});$[12]=composed.container;$[13]=t1;$[14]=t2;$[15]=t3}else{t3=$[15]}return t3};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useTheme","optionValueName","defaultTheme","jsx","_jsx","jsxs","_jsxs","Switch","label","onChange","options","theme","value","composed","option","Error","optionNodes","iValue","iName","className","onPress","
|
|
1
|
+
{"version":3,"file":"index.js","names":["useTheme","optionValueName","defaultTheme","jsx","_jsx","jsxs","_jsxs","Switch","t0","$","_c","label","onChange","options","theme","value","composed","option","Error","optionNodes","selected","iValue","iName","className","onPress","push","onKeyDown","e","key","role","tabIndex","children","t1","t2","t3","container"],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import type { FunctionComponent, ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeT = Theme<'container' | 'label' | 'option' | 'options' | 'selected'>;\n\ntype PropsT = {\n label?: ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<ReactNode>>;\n theme?: ThemeT;\n value?: ValueT;\n};\n\nexport const Switch: FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const composed = useTheme('Switch', defaultTheme, theme);\n\n if (!options || !composed.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (const option of options) {\n const [iValue, iName] = optionValueName(option);\n\n let className: string = composed.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${composed.selected}`;\n else if (onChange) {\n onPress = () => {\n onChange(iValue);\n };\n }\n\n optionNodes.push(\n onPress\n ? (\n <div\n className={className}\n key={iValue}\n onClick={onPress}\n onKeyDown={(e) => {\n if (e.key === 'Enter') onPress();\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n )\n : <div className={className} key={iValue}>{iName}</div>,\n );\n }\n\n return (\n <div className={composed.container}>\n {label ? <div className={composed.label}>{label}</div> : null}\n\n <div className={composed.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n"],"mappings":"qFAEA,OAAqBA,QAAQ,KAAQ,0BAA0B,CAE/D,OAGEC,eAAe,iBAGjB,MAAO,CAAAC,YAAY,oBAAqB,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAYxC,MAAO,MAAM,CAAAC,MAAiC,CAAGC,EAAA,SAAAC,CAAA,CAAAC,EAAA,KAAC,MAAAC,KAAA,CAAAC,QAAA,CAAAC,OAAA,CAAAC,KAAA,CAAAC,KAAA,EAAAP,EAMjD,CACC,MAAAQ,QAAA,CAAiBhB,QAAQ,CAAC,QAAQ,CAAEE,YAAY,CAAEY,KAAK,CAAC,CAExD,GAAI,CAACD,OAA2B,EAA5B,CAAaG,QAAQ,CAAAC,MAAO,EAAE,KAAM,CAAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC,KAAAC,WAAA,IAAAV,CAAA,MAAAO,QAAA,CAAAC,MAAA,EAAAR,CAAA,MAAAO,QAAA,CAAAI,QAAA,EAAAX,CAAA,MAAAG,QAAA,EAAAH,CAAA,MAAAI,OAAA,EAAAJ,CAAA,MAAAM,KAAA,EAEhEI,WAAA,CAAuC,EAAE,CACzC,IAAK,MAAAF,MAAY,GAAI,CAAAJ,OAAO,EAC1B,MAAAQ,MAAA,CAAAC,KAAA,EAAwBrB,eAAe,CAACgB,MAAM,CAAC,CAE/C,IAAAM,SAAA,CAAwBP,QAAQ,CAAAC,MAAO,CACnCO,GAAA,CAAAA,OAAA,CACJ,GAAIH,MAAM,GAAKN,KAAK,EAAEQ,SAAA,CAAAA,SAAS,CAAI,IAAIP,QA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CAAAV,CAAA,IAAAO,QAAA,CAAAH,OAAAJ,CAAA,MAAAU,WAAAV,CAAA,MAAAwB,EAAA,MAAAA,EAAA,CAAAxB,CAAA,SAAAyB,EAAA,IAAAzB,CAAA,OAAAO,QAAA,CAAAmB,SAAA,EAAA1B,CAAA,OAAAuB,EAAA,EAAAvB,CAAA,OAAAwB,EAAA,EALRC,EAAA,cAAA5B,KAAA,QAAgBiB,SAAkB,CAAlBP,QAAQ,CAAAmB,SAAU,CAAAJ,QAAA,EAC/BC,EAA4D,CAE7DC,EAEM,EACH,CAAC,CAAAxB,CAAA,KAAAO,QAAA,CAAAmB,SAAA1B,CAAA,MAAAuB,EAAAvB,CAAA,MAAAwB,EAAAxB,CAAA,MAAAyB,EAAA,MAAAA,EAAA,CAAAzB,CAAA,WANN,CAAAyB,EAMM,CAET","ignoreList":[]}
|
|
@@ -2,5 +2,5 @@ import{withGlobalStateType}from"@dr.pogodin/react-global-state";/** Mapping "chu
|
|
|
2
2
|
// TODO: Not 100% sure now, whether it indeed can be replaced by type,
|
|
3
3
|
// or do we really need it to be an interface. Keeping the interface for now.
|
|
4
4
|
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
|
5
|
-
const{
|
|
5
|
+
const{useSsrContext}=withGlobalStateType();export{useSsrContext};
|
|
6
6
|
//# sourceMappingURL=globalState.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"globalState.js","names":["withGlobalStateType","
|
|
1
|
+
{"version":3,"file":"globalState.js","names":["withGlobalStateType","useSsrContext"],"sources":["../../../../src/shared/utils/globalState.ts"],"sourcesContent":["import type { Request } from 'express';\n\nimport { type SsrContext, withGlobalStateType } from '@dr.pogodin/react-global-state';\n\n/** Mapping \"chunkName\" > array of asset paths. */\nexport type ChunkGroupsT = Record<string, string[]>;\n\n// The type of data object injected by server into generated markup.\nexport type InjT = {\n CHUNK_GROUPS?: ChunkGroupsT;\n CONFIG?: Record<string, unknown>;\n ISTATE?: unknown;\n};\n\ndeclare global {\n // eslint-disable-next-line @typescript-eslint/consistent-type-definitions\n interface Window {\n REACT_UTILS_INJECTION?: InjT;\n }\n}\n\n// TODO: Not 100% sure now, whether it indeed can be replaced by type,\n// or do we really need it to be an interface. Keeping the interface for now.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\nexport interface SsrContextT<StateT> extends SsrContext<StateT> {\n chunkGroups: ChunkGroupsT;\n chunks: string[];\n\n /** If set at the end of SSR, the rendered will trigger\n * server-side redirect to this URL (and use the status\n * code). */\n redirectTo?: string;\n\n req: Request;\n status: number;\n}\n\nconst {\n useSsrContext,\n} = withGlobalStateType<unknown, SsrContextT<unknown>>();\n\nexport {\n useSsrContext,\n};\n"],"mappings":"AAEA,OAA0BA,mBAAmB,KAAQ,gCAAgC,CAErF,kDAGA;AAcA;AACA;AACA;AAcA,KAAM,CACJC,aACF,CAAC,CAAGD,mBAAmB,CAAgC,CAAC,CAExD,OACEC,aAAa","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{getConfig}from"./config";import time from"./time";import*as webpack from"./webpack";export*from"./isomorphy";export{Barrier,Cached,Emitter,Semaphore,assertEmptyObject,withRetries}from"@dr.pogodin/js-utils";export{COMPOSE as THEME_COMPOSE,PRIORITY as THEME_PRIORITY,ThemeProvider,useTheme}from"@dr.pogodin/react-themes";export{
|
|
1
|
+
import{getConfig}from"./config";import time from"./time";import*as webpack from"./webpack";export*from"./isomorphy";export{Barrier,Cached,Emitter,Semaphore,assertEmptyObject,withRetries}from"@dr.pogodin/js-utils";export{COMPOSE as THEME_COMPOSE,PRIORITY as THEME_PRIORITY,ThemeProvider,useTheme}from"@dr.pogodin/react-themes";export{useSsrContext}from"./globalState";export{setClientChunkGroups,default as splitComponent}from"./splitComponent";export{getConfig,time,webpack};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["getConfig","time","webpack","Barrier","Cached","Emitter","Semaphore","assertEmptyObject","withRetries","COMPOSE","THEME_COMPOSE","PRIORITY","THEME_PRIORITY","ThemeProvider","useTheme","
|
|
1
|
+
{"version":3,"file":"index.js","names":["getConfig","time","webpack","Barrier","Cached","Emitter","Semaphore","assertEmptyObject","withRetries","COMPOSE","THEME_COMPOSE","PRIORITY","THEME_PRIORITY","ThemeProvider","useTheme","useSsrContext","setClientChunkGroups","default","splitComponent"],"sources":["../../../../src/shared/utils/index.ts"],"sourcesContent":["import { getConfig } from './config';\nimport time from './time';\nimport * as webpack from './webpack';\n\nexport * from './isomorphy';\n\nexport {\n Barrier,\n Cached,\n Emitter,\n type Listener,\n type ObjectKey,\n Semaphore,\n assertEmptyObject,\n withRetries,\n} from '@dr.pogodin/js-utils';\n\nexport {\n COMPOSE as THEME_COMPOSE,\n PRIORITY as THEME_PRIORITY,\n type Theme,\n ThemeProvider,\n useTheme,\n} from '@dr.pogodin/react-themes';\n\nexport { useSsrContext } from './globalState';\n\nexport {\n setClientChunkGroups,\n default as splitComponent,\n} from './splitComponent';\n\nexport { getConfig, time, webpack };\n"],"mappings":"AAAA,OAASA,SAAS,gBAClB,MAAO,CAAAC,IAAI,cACX,MAAO,GAAK,CAAAC,OAAO,iBAEnB,yBAEA,OACEC,OAAO,CACPC,MAAM,CACNC,OAAO,CAGPC,SAAS,CACTC,iBAAiB,CACjBC,WAAW,KACN,sBAAsB,CAE7B,OACEC,OAAO,GAAI,CAAAC,aAAa,CACxBC,QAAQ,GAAI,CAAAC,cAAc,CAE1BC,aAAa,CACbC,QAAQ,KACH,0BAA0B,CAEjC,OAASC,aAAa,qBAEtB,OACEC,oBAAoB,CACpBC,OAAO,GAAI,CAAAC,cAAc,wBAG3B,OAASlB,SAAS,CAAEC,IAAI,CAAEC,OAAO","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"core-js/modules/es.json.stringify.js";/* global
|
|
1
|
+
import"core-js/modules/es.json.stringify.js";/* global document *//* eslint-disable import/no-extraneous-dependencies */import mockdate from"mockdate";import{act}from"react";import{createRoot}from"react-dom/client";import{expect,jest}from"@jest/globals";import{render}from"@testing-library/react";/**
|
|
2
2
|
* An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)
|
|
3
3
|
* from `react`.
|
|
4
4
|
*/export{act};export{default as getGlobal}from"./global";global.IS_REACT_ACT_ENVIRONMENT=true;const originalProcessVersions=process.versions;/**
|
|
@@ -41,7 +41,14 @@ const promise=act(()=>{res=render(element);return options?.await;});if(res===und
|
|
|
41
41
|
// it is not an instance of proper Promise class, and returning it directly
|
|
42
42
|
// breaks some async logic in Jest test or React test functions... thus, we
|
|
43
43
|
// wrap it into Promise instance here.
|
|
44
|
-
return new Promise(resolve
|
|
44
|
+
return new Promise((resolve,reject)=>{let rejected=false;// BEWARE: The "promise" returned by act() does not behave as a regular
|
|
45
|
+
// Promise instance:
|
|
46
|
+
// 1. In case of errors its .then() method both calls its "reject"
|
|
47
|
+
// callback (first), and then its "resolve" callback second.
|
|
48
|
+
// 2. It errors out if a rendering error happens, and there is no
|
|
49
|
+
// "reject" argument provided.
|
|
50
|
+
void promise.then(()=>{if(!rejected){// TODO: These lines are the same as the lines below for sync variant of
|
|
45
51
|
// the function. We should split and reuse them in both places.
|
|
46
|
-
const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();resolve(res);}
|
|
52
|
+
const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();resolve(res);}},error=>{rejected=true;// eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors
|
|
53
|
+
reject(error);});});}const nodes=res.asFragment().childNodes;expect(nodes.length>1?[...nodes]:nodes[0]).toMatchSnapshot();return res;}
|
|
47
54
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["mockdate","act","createRoot","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","jest","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","expect","toMatchSnapshot","options","promise","await","Error","Promise","resolve","then","nodes","asFragment","childNodes","length"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global jest, document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: React.ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve) => {\n void promise.then(() => {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"6CAAA,2BACA,sDASA,MAAO,CAAAA,QAAQ,KAAM,UAAU,CAC/B,OAA4CC,GAAG,KAAQ,OAAO,CAC9D,OAAoBC,UAAU,KAAQ,kBAAkB,C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,OAAO,CAAEC,OAAO,EAAK,CAC9B,IAAK,CAAAJ,OAAO,CAACK,IAAI,CAAC,IAAM,CACtB;AACA;AACA,KAAM,CAAAC,KAAK,CAAGrC,GAAG,CAAEsC,UAAU,CAAC,CAAC,CAACC,UAAU,CAC1CX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClEM,OAAO,CAACnC,GAAI,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,CAAAqC,KAAK,CAAGrC,GAAG,CAACsC,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCX,MAAM,CAACS,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACR,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA7B,GAAG,CACZ","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":["mockdate","act","createRoot","expect","jest","render","default","getGlobal","global","IS_REACT_ACT_ENVIRONMENT","originalProcessVersions","process","versions","mockClientSide","Object","defineProperty","value","undefined","unmockClientSide","writable","getMockUuid","seed","x","toString","padStart","slice","mockAxios","handlers","axios","requireActual","defaults","adapter","config","handler","res","data","headers","status","statusText","console","warn","JSON","stringify","e","mockTimer","time","set","Date","now","advanceTimersByTimeAsync","mount","scene","root","element","document","createElement","body","appendChild","destroy","unmount","remove","snapshot","toMatchSnapshot","options","promise","await","Error","Promise","resolve","reject","rejected","then","nodes","asFragment","childNodes","length","error"],"sources":["../../../../../src/shared/utils/jest/index.ts"],"sourcesContent":["/* global document */\n/* eslint-disable import/no-extraneous-dependencies */\n\nimport type {\n AxiosRequestConfig,\n AxiosResponse,\n AxiosStatic,\n InternalAxiosRequestConfig,\n} from 'axios';\n\nimport mockdate from 'mockdate';\nimport { type ReactElement, type ReactNode, act } from 'react';\nimport { type Root, createRoot } from 'react-dom/client';\n\nimport { expect, jest } from '@jest/globals';\nimport { type RenderResult, render } from '@testing-library/react';\n\n/**\n * An alias for [act(..)](https://reactjs.org/docs/test-utils.html#act)\n * from `react`.\n */\nexport { act };\n\nexport { default as getGlobal } from './global';\n\nglobal.IS_REACT_ACT_ENVIRONMENT = true;\n\nconst originalProcessVersions = process.versions;\n\n/**\n * Tricks **react-utils** into thinking the test is running within client-side\n * (browser) environment.\n */\nexport function mockClientSide(): void {\n Object.defineProperty(process, 'versions', { value: undefined });\n}\n\n/**\n * Reverts the effect of {@link module:JU.mockClientSide mockClientSide(..)}.\n */\nexport function unmockClientSide(): void {\n Object.defineProperty(process, 'versions', {\n value: originalProcessVersions,\n writable: false,\n });\n}\n\n/**\n * Generates a mock UUID, or better said it determenistically transforms given\n * `seed` number into a UUID-formatted string.\n * @param {number} seed\n * @return {string}\n */\nexport function getMockUuid(seed = 0): `${string}-${string}-${string}-${string}-${string}` {\n const x = seed.toString(16).padStart(32, '0');\n return `${x.slice(0, 8)}-${x.slice(8, 12)}-${x.slice(12, 16)}-${x.slice(16, 20)}-${x.slice(20)}`;\n}\n\nexport type AxiosRequestHandlerT = (\n config: AxiosRequestConfig,\n) => Partial<AxiosResponse> | null | undefined;\n\nexport function mockAxios(handlers: AxiosRequestHandlerT[]): AxiosStatic {\n const axios: AxiosStatic = jest.requireActual('axios');\n\n axios.defaults.adapter = async (\n config: AxiosRequestConfig,\n ): Promise<AxiosResponse> => {\n for (const handler of handlers) {\n const res = handler(config);\n if (res) {\n return {\n config: config as InternalAxiosRequestConfig,\n data: null,\n headers: {},\n status: 200,\n statusText: 'OK',\n ...res,\n };\n }\n }\n\n // Fallback to the regular network request.\n let res: AxiosResponse;\n try {\n res = await axios({ ...config, adapter: ['xhr', 'http', 'fetch'] });\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test.\\n\\nConfig:\\n',\n config,\n '\\n\\nResult:\\n',\n JSON.stringify(res, null, 2),\n );\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n 'Network request has not been mocked for a test, and failed.\\n\\nConfig:\\n',\n config,\n '\\n\\nError\\n',\n JSON.stringify(e, null, 2),\n );\n throw e;\n }\n\n return res;\n };\n\n return axios;\n}\n\n/**\n * Advances mock timers, and mock date by the specified time.\n * @param {number} time Time step [ms].\n * @returns {Promise} Wait for this to \"jump after\" any async code which should\n * be executed because of the mock time movement.\n */\nexport async function mockTimer(time: number): Promise<void> {\n mockdate.set(time + Date.now());\n await jest.advanceTimersByTimeAsync(time);\n}\n\nexport type MountedSceneT = HTMLElement & {\n destroy: () => void;\n snapshot: () => void;\n};\n\n/**\n * Mounts `scene` to the DOM, and returns the root scene element.\n * @param scene\n * @return Created container DOM element with destroy() function\n * attached.\n */\nexport function mount(scene: ReactNode): MountedSceneT {\n let root: Root;\n const element = document.createElement('div');\n document.body.appendChild(element);\n\n const res: MountedSceneT = (element as unknown) as MountedSceneT;\n res.destroy = () => {\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root.unmount();\n });\n res.remove();\n };\n\n res.snapshot = () => {\n expect(res).toMatchSnapshot();\n };\n\n // NOTE: As it seems @testing-library may reset this flag to false\n // when it is simulating user events.\n global.IS_REACT_ACT_ENVIRONMENT = true;\n\n act(() => {\n root = createRoot(res);\n root.render(scene);\n });\n return res;\n}\n\n// NOTE: If in future we have additional options here, they should be distributed\n// across two objects, depending whether they are applicable to the sync, or async\n// versions of snapshot(), or both.\ntype AsyncSnapshotOptionsT = {\n await?: Promise<void>;\n};\n\nexport function snapshot(element: ReactElement): RenderResult;\n\nexport async function snapshot(\n element: ReactElement,\n options: AsyncSnapshotOptionsT,\n): Promise<RenderResult>;\n\nexport function snapshot(\n element: ReactElement,\n options?: AsyncSnapshotOptionsT,\n): Promise<RenderResult> | RenderResult {\n let res: RenderResult | undefined;\n\n // TODO: Just adding async to the actor function breaks stuff, as it makes\n // act() asynchronous no matter the `options.await` value, thus breaking all\n // calls that do not await for snapshot() result... thus... perhaps we need\n // to have a more complex typing to ensure it all works as intended in all\n // cases, and while being correctly enforced by TypeScript.\n // eslint-disable-next-line @typescript-eslint/promise-function-async\n const promise = act(() => {\n res = render(element);\n return options?.await;\n });\n\n if (res === undefined) throw Error('Render failed');\n if (options?.await) {\n // BEWARE: Although `promise` is thenable (i.e. it has .then() method),\n // it is not an instance of proper Promise class, and returning it directly\n // breaks some async logic in Jest test or React test functions... thus, we\n // wrap it into Promise instance here.\n return new Promise((resolve, reject) => {\n let rejected = false;\n\n // BEWARE: The \"promise\" returned by act() does not behave as a regular\n // Promise instance:\n // 1. In case of errors its .then() method both calls its \"reject\"\n // callback (first), and then its \"resolve\" callback second.\n // 2. It errors out if a rendering error happens, and there is no\n // \"reject\" argument provided.\n void promise.then(() => {\n if (!rejected) {\n // TODO: These lines are the same as the lines below for sync variant of\n // the function. We should split and reuse them in both places.\n const nodes = res!.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n resolve(res!);\n }\n }, (error: unknown) => {\n rejected = true;\n\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n reject(error);\n });\n });\n }\n\n const nodes = res.asFragment().childNodes;\n expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();\n return res;\n}\n"],"mappings":"6CAAA,qBACA,sDASA,MAAO,CAAAA,QAAQ,KAAM,UAAU,CAC/B,OAA4CC,GAAG,KAAQ,OAAO,CAC9D,OAAoBC,UAAU,KAAQ,kBAAkB,CAExD,OAASC,MAAM,CAAEC,IAAI,KAAQ,eAAe,CAC5C,OAA4BC,MAAM,KAAQ,wBAAwB,CAElE;AACA;AACA;AACA,GACA,OAASJ,GAAG,EAEZ,OAASK,OAAO,GAAI,CAAAC,SAAS,gBAE7BC,MAAM,CAACC,wBAAwB,CAAG,IAAI,CAEtC,K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AAM,CACtB,GAAI,CAACD,QAAQ,CAAE,CACb;AACA;AACA,KAAM,CAAAE,KAAK,CAAGtC,GAAG,CAAEuC,UAAU,CAAC,CAAC,CAACC,UAAU,CAC1CvE,MAAM,CAACqE,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACV,eAAe,CAAC,CAAC,CAClEM,OAAO,CAAClC,GAAI,CAAC,CACf,CACF,CAAC,CAAG0C,KAAc,EAAK,CACrBN,QAAQ,CAAG,IAAI,CAEf;AACAD,MAAM,CAACO,KAAK,CAAC,CACf,CAAC,CAAC,CACJ,CAAC,CAAC,CACJ,CAEA,KAAM,CAAAJ,KAAK,CAAGtC,GAAG,CAACuC,UAAU,CAAC,CAAC,CAACC,UAAU,CACzCvE,MAAM,CAACqE,KAAK,CAACG,MAAM,CAAG,CAAC,CAAG,CAAC,GAAGH,KAAK,CAAC,CAAGA,KAAK,CAAC,CAAC,CAAC,CAAC,CAACV,eAAe,CAAC,CAAC,CAClE,MAAO,CAAA5B,GAAG,CACZ","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{
|
|
1
|
+
import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.set.difference.v2.js";import"core-js/modules/es.set.intersection.v2.js";import"core-js/modules/es.set.is-disjoint-from.v2.js";import"core-js/modules/es.set.is-subset-of.v2.js";import"core-js/modules/es.set.is-superset-of.v2.js";import"core-js/modules/es.set.symmetric-difference.v2.js";import"core-js/modules/es.set.union.v2.js";import{c as _c}from"react/compiler-runtime";/* global document */import{Suspense,lazy,useInsertionEffect}from"react";import{Barrier}from"@dr.pogodin/js-utils";import{useSsrContext}from"./globalState";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,assertClientSide,getBuildInfo}from"./isomorphy";import{jsx as _jsx}from"react/jsx-runtime";let clientChunkGroups;export function setClientChunkGroups(groups){assertClientSide();clientChunkGroups=groups;}const refCounts={};function getPublicPath(){return getBuildInfo().publicPath;}/**
|
|
2
2
|
* Client-side only! Ensures the specified CSS stylesheet is loaded into
|
|
3
3
|
* the document; loads if it is missing; and does simple reference counting
|
|
4
4
|
* to facilitate future clean-up.
|
|
@@ -51,15 +51,8 @@ import"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.cons
|
|
|
51
51
|
// ) {
|
|
52
52
|
// throw Error(`Repeated splitComponent() call for the chunk "${chunkName}"`);
|
|
53
53
|
// } else usedChunkNames.add(chunkName);
|
|
54
|
-
const LazyComponent=/*#__PURE__*/lazy(async()=>{const
|
|
55
|
-
if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");assertChunkName(chunkName,clientChunkGroups);}const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
|
|
54
|
+
const LazyComponent=/*#__PURE__*/lazy(async()=>{const resolved=await getComponent();const Component="default"in resolved?resolved.default:resolved;// This pre-loads necessary stylesheets prior to the first mount of
|
|
56
55
|
// the component (the lazy load function is executed by React one at
|
|
57
56
|
// the frist mount).
|
|
58
|
-
if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false);}const Wrapper=({children,ref,...rest})=>{
|
|
59
|
-
// and also push it to the SSR chunks array.
|
|
60
|
-
if(IS_SERVER_SIDE){const{chunkGroups,chunks}=getSsrContext();assertChunkName(chunkName,chunkGroups);if(!chunks.includes(chunkName))chunks.push(chunkName);}// This takes care about stylesheets management every time an instance of
|
|
61
|
-
// this component is mounted / unmounted.
|
|
62
|
-
useInsertionEffect(()=>{if(!clientChunkGroups)throw Error("Internal error");void bookStyleSheets(chunkName,clientChunkGroups,true);return()=>{freeStyleSheets(chunkName,clientChunkGroups);};},[]);return/*#__PURE__*/_jsx(Component// eslint-disable-next-line react/jsx-props-no-spreading
|
|
63
|
-
,{...rest,ref:ref,children:children});};return{default:Wrapper};});const CodeSplit=({children,...rest})=>/*#__PURE__*/_jsx(Suspense,{fallback:placeholder,children:/*#__PURE__*/_jsx(LazyComponent// eslint-disable-next-line react/jsx-props-no-spreading
|
|
64
|
-
,{...rest,children:children})});return CodeSplit;}
|
|
57
|
+
if(IS_CLIENT_SIDE){if(!clientChunkGroups)throw Error("Internal error");await bookStyleSheets(chunkName,clientChunkGroups,false);}const Wrapper=t0=>{const $=_c(12);let children;let chunkGroups;let ref;let rest;if($[0]!==t0){({children,chunkGroups,ref,...rest}=t0);$[0]=t0;$[1]=children;$[2]=chunkGroups;$[3]=ref;$[4]=rest}else{children=$[1];chunkGroups=$[2];ref=$[3];rest=$[4]}let t1;let t2;if($[5]!==chunkGroups){t1=()=>{if(!clientChunkGroups){throw Error("Internal error");}bookStyleSheets(chunkName,chunkGroups,true);return()=>{freeStyleSheets(chunkName,chunkGroups)}};t2=[chunkGroups];$[5]=chunkGroups;$[6]=t1;$[7]=t2}else{t1=$[6];t2=$[7]}useInsertionEffect(t1,t2);const t3=rest;let t4;if($[8]!==children||$[9]!==ref||$[10]!==t3){t4=/*#__PURE__*/_jsx(Component,{...t3,ref:ref,children:children});$[8]=children;$[9]=ref;$[10]=t3;$[11]=t4}else{t4=$[11]}return t4};return{default:Wrapper};});const CodeSplit=t0=>{const $=_c(7);let children;let rest;if($[0]!==t0){({children,...rest}=t0);$[0]=t0;$[1]=children;$[2]=rest}else{children=$[1];rest=$[2]}let chunkGroups;const ssrContext=useSsrContext(false);if(IS_SERVER_SIDE){if(!ssrContext){throw Error("Internal error");}({chunkGroups}=ssrContext);const{chunks}=ssrContext;if(!chunks.includes(chunkName)){chunks.push(chunkName)}}else{if(!clientChunkGroups){throw Error("Missing client-side chunk groups data");}chunkGroups=clientChunkGroups;}assertChunkName(chunkName,chunkGroups);const t1=rest;let t2;if($[3]!==children||$[4]!==chunkGroups||$[5]!==t1){t2=/*#__PURE__*/_jsx(Suspense,{fallback:placeholder,children:/*#__PURE__*/_jsx(LazyComponent,{...t1,chunkGroups:chunkGroups,children:children})});$[3]=children;$[4]=chunkGroups;$[5]=t1;$[6]=t2}else{t2=$[6]}return t2};return CodeSplit;}
|
|
65
58
|
//# sourceMappingURL=splitComponent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","getSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","getBuildInfo","jsx","_jsx","getClientChunkGroups","undefined","default","getInj","inj","CHUNK_GROUPS","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","splitComponent","getComponent","placeholder","LazyComponent","clientChunkGroups","resolved","Component","Wrapper","children","ref","rest","chunks","includes","CodeSplit","fallback"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, getSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n getBuildInfo,\n} from './isomorphy';\n\nfunction getClientChunkGroups(): Promise<ChunkGroupsT> | undefined {\n if (!IS_CLIENT_SIDE) return undefined;\n\n return (async () => {\n const { default: getInj } = await import(/* webpackChunkName: \"react-utils-client-side-code\" */ '../../client/getInj');\n\n const inj = await getInj();\n return inj.CHUNK_GROUPS ?? {};\n })();\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\n// const usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // TODO: For now I commented out this safeguard check, as I am not sure how\n // to easily make it work: it should not be triggered in HMR mode, but if I\n // add the code relying on import.meta, it fails in Jest environment, because\n // Jest does not support ES modules yet, and import.meta is not support in\n // CommonJS modules, and the \"babel-plugin-transform-import-meta\" plugin\n // we use to workaround this issue for import.meta.dirname, etc. does not\n // transform import.meta.webpackHot\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n // if (usedChunkNames.has(chunkName)\n\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n // && !import.meta.webpackHot\n // ) {\n // throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n // } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const clientChunkGroups = await getClientChunkGroups();\n\n // On the client side we can check right away if the chunk name is known.\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n assertChunkName(chunkName, clientChunkGroups);\n }\n\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT> = ({\n children,\n ref,\n ...rest\n }) => {\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n const { chunkGroups, chunks } = getSsrContext()!;\n assertChunkName(chunkName, chunkGroups);\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n }\n\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, clientChunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, clientChunkGroups);\n };\n }, []);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: React.FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n\n return CodeSplit;\n}\n"],"mappings":"+bAAA,qBAEA,OAKEA,QAAQ,CACRC,IAAI,CACJC,kBAAkB,KACb,OAAO,CAEd,OAASC,OAAO,KAAQ,sBAAsB,CAE9C,OAA4BC,aAAa,qBAEzC,OACEC,cAAc,CACdC,cAAc,CACdC,YAAY,mBACO,OAAAC,GAAA,IAAAC,IAAA,yBAErB,QAAS,CAAAC,oBAAoBA,CAAA,CAAsC,CACjE,GAAI,CAACL,cAAc,CAAE,MAAO,CAAAM,SAAS,CAErC,MAAO,CAAC,SAAY,CAClB,KAAM,CAAEC,OAAO,CAAEC,MAAO,CAAC,CAAG,KAAM,OAAM,CAAC,2EAA4E,CAAC,CAEtH,KAAM,CAAAC,GAAG,CAAG,KAAM,CAAAD,MAAM,CAAC,CAAC,CAC1B,MAAO,CAAAC,GAAG,CAACC,YAAY,EAAI,CAAC,CAAC,CAC/B,CAAC,EAAE,CAAC,CACN,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB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C/C,CAAC,CACH,CAAC,CAAE,EAAE,CAAC,CAEN,mBACEzD,IAAA,CAAC2D,SACC;AAAA,KACKI,IAAI,CACTD,GAAG,CAAEA,GAAI,CAAAD,QAAA,CAERA,QAAQ,CACA,CAAC,CAEhB,CAAC,CAED,MAAO,CAAE1D,OAAO,CAAEyD,OAAQ,CAAC,CAC7B,CAAC,CAAC,CAEF,KAAM,CAAAM,SAAmD,CAAGA,CAAC,CAC3DL,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChB/D,IAAA,CAACT,QAAQ,EAAC4E,QAAQ,CAAEZ,WAAY,CAAAM,QAAA,cAC9B7D,IAAA,CAACwD,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAK,SAAS,CAClB","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"splitComponent.js","names":["Suspense","lazy","useInsertionEffect","Barrier","useSsrContext","IS_CLIENT_SIDE","IS_SERVER_SIDE","assertClientSide","getBuildInfo","jsx","_jsx","clientChunkGroups","setClientChunkGroups","groups","refCounts","getPublicPath","publicPath","bookStyleSheet","name","loadedSheets","refCount","res","path","fullPath","document","location","origin","has","link","querySelector","createElement","setAttribute","head","appendChild","addEventListener","Error","resolve","current","getLoadedStyleSheets","Set","styleSheets","href","add","assertChunkName","chunkName","chunkGroups","bookStyleSheets","promises","assets","Promise","asset","endsWith","promise","push","length","allSettled","then","freeStyleSheets","pathRefCount","remove","splitComponent","getComponent","placeholder","LazyComponent","resolved","Component","default","Wrapper","t0","$","_c","children","ref","rest","t1","t2","t3","t4","CodeSplit","ssrContext","chunks","includes"],"sources":["../../../../src/shared/utils/splitComponent.tsx"],"sourcesContent":["/* global document */\n\nimport {\n type ComponentType,\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n Suspense,\n lazy,\n useInsertionEffect,\n} from 'react';\n\nimport { Barrier } from '@dr.pogodin/js-utils';\n\nimport { type ChunkGroupsT, useSsrContext } from './globalState';\n\nimport {\n IS_CLIENT_SIDE,\n IS_SERVER_SIDE,\n assertClientSide,\n getBuildInfo,\n} from './isomorphy';\n\nlet clientChunkGroups: ChunkGroupsT | undefined;\n\nexport function setClientChunkGroups(groups: ChunkGroupsT): void {\n assertClientSide();\n clientChunkGroups = groups;\n}\n\nconst refCounts: Record<string, number> = {};\n\nfunction getPublicPath() {\n return getBuildInfo().publicPath;\n}\n\n/**\n * Client-side only! Ensures the specified CSS stylesheet is loaded into\n * the document; loads if it is missing; and does simple reference counting\n * to facilitate future clean-up.\n * @param name\n * @param loadedSheets\n * @param refCount\n * @return\n */\nfunction bookStyleSheet(\n name: string,\n loadedSheets: Set<string>,\n refCount: boolean,\n): Promise<void> | undefined {\n let res: Barrier<void> | undefined;\n const path = `${getPublicPath()}/${name}`;\n const fullPath = `${document.location.origin}${path}`;\n\n if (!loadedSheets.has(fullPath)) {\n let link = document.querySelector(`link[href=\"${path}\"]`);\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('rel', 'stylesheet');\n link.setAttribute('href', path);\n document.head.appendChild(link);\n }\n\n res = new Barrier<void>();\n link.addEventListener('load', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n link.addEventListener('error', () => {\n if (!res) throw Error('Internal error');\n void res.resolve();\n });\n }\n\n if (refCount) {\n const current = refCounts[path] ?? 0;\n refCounts[path] = 1 + current;\n }\n\n return res;\n}\n\n/**\n * Generates the set of URLs for currently loaded, linked stylesheets.\n * @return\n */\nfunction getLoadedStyleSheets(): Set<string> {\n const res = new Set<string>();\n const { styleSheets } = document;\n for (const { href } of styleSheets) {\n if (href) res.add(href);\n }\n return res;\n}\n\nfunction assertChunkName(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n) {\n if (chunkGroups[chunkName]) return;\n throw Error(`Unknown chunk name \"${chunkName}\"`);\n}\n\n/**\n * Client-side only! Ensures all CSS stylesheets required for the specified\n * code chunk are loaded into the document; loads the missing ones; and does\n * simple reference counting to facilitate future clean-up.\n * @param chunkName Chunk name.\n * @param refCount\n * @return Resolves once all pending stylesheets, necessary for\n * the chunk, are either loaded, or failed to load.\n */\nexport async function bookStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n refCount: boolean,\n): Promise<void> {\n const promises = [];\n const assets = chunkGroups[chunkName];\n if (!assets) return Promise.resolve();\n\n const loadedSheets = getLoadedStyleSheets();\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const promise = bookStyleSheet(asset, loadedSheets, refCount);\n if (promise) promises.push(promise);\n }\n }\n\n return promises.length\n ? Promise.allSettled(promises).then()\n : Promise.resolve();\n}\n\n/**\n * Client-side only! Frees from the document all CSS stylesheets that are\n * required by the specified chunk, and have reference counter equal to one\n * (for chunks with larger reference counter values, it just decrements\n * the reference counter).\n * @param {string} chunkName\n */\nexport function freeStyleSheets(\n chunkName: string,\n chunkGroups: ChunkGroupsT,\n): void {\n const assets = chunkGroups[chunkName];\n if (!assets) return;\n\n for (const asset of assets) {\n if (asset.endsWith('.css')) {\n const path = `${getPublicPath()}/${asset}`;\n\n const pathRefCount = refCounts[path];\n if (pathRefCount) {\n if (pathRefCount <= 1) {\n document.head.querySelector(`link[href=\"${path}\"]`)!.remove();\n delete refCounts[path];\n } else refCounts[path] = pathRefCount - 1;\n }\n }\n }\n}\n\n// Holds the set of chunk names already used for splitComponent() calls.\n// const usedChunkNames = new Set();\n\ntype ComponentOrModule<PropsT> = ComponentType<PropsT> | {\n default: ComponentType<PropsT>;\n};\n\ntype GenericComponentPropsT = {\n children?: ReactNode;\n ref?: RefObject<unknown>;\n\n // NOTE: This is necessary, as without it this type (with only optional\n // fields) will be conisdered as \"weak\" by TypeScript, and it will be\n // a error to assign to it any type that does not use \"children\", or \"ref\".\n [propName: string]: unknown;\n};\n\n/**\n * Given an async component retrieval function `getComponent()` it creates\n * a special \"code split\" component, which uses <Suspense> to asynchronously\n * load on demand the code required by `getComponent()`.\n * @param options\n * @param options.chunkName\n * @param {function} options.getComponent\n * @param {React.Element} [options.placeholder]\n * @return {React.ElementType}\n */\nexport default function splitComponent<\n ComponentPropsT extends GenericComponentPropsT,\n>({\n chunkName,\n getComponent,\n placeholder,\n}: {\n chunkName: string;\n getComponent: () => Promise<ComponentOrModule<ComponentPropsT>>;\n placeholder?: ReactNode;\n}): FunctionComponent<ComponentPropsT> {\n // TODO: For now I commented out this safeguard check, as I am not sure how\n // to easily make it work: it should not be triggered in HMR mode, but if I\n // add the code relying on import.meta, it fails in Jest environment, because\n // Jest does not support ES modules yet, and import.meta is not support in\n // CommonJS modules, and the \"babel-plugin-transform-import-meta\" plugin\n // we use to workaround this issue for import.meta.dirname, etc. does not\n // transform import.meta.webpackHot\n\n // The correct usage of splitComponent() assumes a single call per chunk.\n // if (usedChunkNames.has(chunkName)\n\n // When HMR happens splitComponent() ends up getting called again for some\n // chunks, thus we should not throw this error. Not sure, if we need to do\n // some additional handling in that case, or just not throwing is all we\n // need.\n // && !import.meta.webpackHot\n // ) {\n // throw Error(`Repeated splitComponent() call for the chunk \"${chunkName}\"`);\n // } else usedChunkNames.add(chunkName);\n\n const LazyComponent = lazy(async () => {\n const resolved = await getComponent();\n const Component = 'default' in resolved ? resolved.default : resolved;\n\n // This pre-loads necessary stylesheets prior to the first mount of\n // the component (the lazy load function is executed by React one at\n // the frist mount).\n if (IS_CLIENT_SIDE) {\n if (!clientChunkGroups) throw Error('Internal error');\n await bookStyleSheets(chunkName, clientChunkGroups, false);\n }\n\n const Wrapper: FunctionComponent<ComponentPropsT & {\n chunkGroups: ChunkGroupsT;\n }> = ({\n children,\n chunkGroups,\n ref,\n ...rest\n }) => {\n // This takes care about stylesheets management every time an instance of\n // this component is mounted / unmounted.\n useInsertionEffect(() => {\n if (!clientChunkGroups) throw Error('Internal error');\n void bookStyleSheets(chunkName, chunkGroups, true);\n return () => {\n freeStyleSheets(chunkName, chunkGroups);\n };\n }, [chunkGroups]);\n\n return (\n <Component\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...(rest as unknown as ComponentPropsT)}\n ref={ref}\n >\n {children}\n </Component>\n );\n };\n\n return { default: Wrapper };\n });\n\n const CodeSplit: FunctionComponent<ComponentPropsT> = ({\n children,\n ...rest\n }: ComponentPropsT) => {\n let chunkGroups: ChunkGroupsT;\n\n const ssrContext = useSsrContext(false);\n\n // On the server side we'll assert the chunk name here,\n // and also push it to the SSR chunks array.\n if (IS_SERVER_SIDE) {\n if (!ssrContext) throw Error('Internal error');\n ({ chunkGroups } = ssrContext);\n const { chunks } = ssrContext;\n\n if (!chunks.includes(chunkName)) chunks.push(chunkName);\n } else {\n if (!clientChunkGroups) {\n throw Error('Missing client-side chunk groups data');\n }\n chunkGroups = clientChunkGroups;\n }\n\n assertChunkName(chunkName, chunkGroups);\n\n return (\n <Suspense fallback={placeholder}>\n <LazyComponent\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...rest as Parameters<typeof LazyComponent>[0]}\n\n chunkGroups={chunkGroups}\n >\n {children}\n </LazyComponent>\n </Suspense>\n );\n };\n\n return CodeSplit;\n}\n"],"mappings":"2eAAA,qBAEA,OAKEA,QAAQ,CACRC,IAAI,CACJC,kBAAkB,KACb,OAAO,CAEd,OAASC,OAAO,KAAQ,sBAAsB,CAE9C,OAA4BC,aAAa,qBAEzC,OACEC,cAAc,CACdC,cAAc,CACdC,gBAAgB,CAChBC,YAAY,mBACO,OAAAC,GAAA,IAAAC,IAAA,yBAErB,GAAI,CAAAC,iBAA2C,CAE/C,MAAO,SAAS,CAAAC,oBAAoBA,CAACC,MAAoB,CAAQ,CAC/DN,gBAAgB,CAAC,CAAC,CAClBI,iBAAiB,CAAGE,MAAM,CAC5B,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,CAAAP,YAAY,CAAC,CAAC,CAACQ,UAAU,CAClC,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,QAAS,CAAAC,cAAcA,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