@dr.pogodin/react-utils 1.47.0-alpha.5 → 1.47.0-alpha.8
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/getInj.js +11 -0
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/client/index.js +1 -1
- package/build/development/client/index.js.map +1 -1
- package/build/development/index.js +1 -11
- package/build/development/index.js.map +1 -1
- package/build/development/server/index.js +3 -6
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +20 -0
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +6 -0
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/index.js +1 -1
- package/build/development/server/utils/index.js.map +1 -1
- package/build/development/shared/components/Button/index.js +1 -1
- package/build/development/shared/components/Button/index.js.map +1 -1
- package/build/development/shared/components/Checkbox/index.js +1 -1
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +1 -1
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +1 -1
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/PageLayout/index.js +1 -1
- package/build/development/shared/components/PageLayout/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +1 -1
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/Throbber/index.js +1 -1
- package/build/development/shared/components/Throbber/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +1 -1
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js +1 -1
- package/build/development/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +6 -0
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +5 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +7 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +3 -1
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv.js +4 -0
- package/build/development/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +18 -0
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/webpack.js +4 -0
- package/build/development/shared/utils/webpack.js.map +1 -1
- package/build/production/client/getInj.js +1 -1
- package/build/production/client/getInj.js.map +1 -1
- package/build/production/client/index.js +1 -1
- package/build/production/client/index.js.map +1 -1
- package/build/production/index.js +2 -6
- package/build/production/index.js.map +1 -1
- package/build/production/server/index.js +3 -3
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +1 -1
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +1 -1
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/index.js +1 -1
- package/build/production/server/utils/index.js.map +1 -1
- package/build/production/shared/components/Button/index.js +1 -1
- 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/Input/index.js +1 -1
- package/build/production/shared/components/Input/index.js.map +1 -1
- package/build/production/shared/components/Modal/index.js +1 -1
- package/build/production/shared/components/Modal/index.js.map +1 -1
- package/build/production/shared/components/PageLayout/index.js +1 -1
- package/build/production/shared/components/PageLayout/index.js.map +1 -1
- package/build/production/shared/components/TextArea/index.js +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/Throbber/index.js +1 -1
- package/build/production/shared/components/Throbber/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +1 -1
- package/build/production/shared/components/WithTooltip/index.js.map +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js +1 -1
- package/build/production/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +2 -2
- package/build/production/shared/components/selectors/NativeDropdown/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/jest/E2eSsrEnv.js +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +1 -1
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/webpack.js +1 -1
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/client/index.d.ts +1 -1
- package/build/types-code/index.d.ts +0 -5
- package/build/types-code/server/index.d.ts +4 -9
- package/build/types-code/server/utils/index.d.ts +1 -1
- package/build/web/client/getInj.js +7 -0
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/client/index.js +1 -1
- package/build/web/client/index.js.map +1 -1
- package/build/web/index.js +1 -11
- package/build/web/index.js.map +1 -1
- package/build/web/server/index.js +3 -6
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +10 -0
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +3 -0
- package/build/web/server/server.js.map +1 -1
- package/build/web/server/utils/index.js +1 -1
- package/build/web/server/utils/index.js.map +1 -1
- package/build/web/shared/components/Button/index.js +1 -1
- 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/Input/index.js +1 -1
- package/build/web/shared/components/Input/index.js.map +1 -1
- package/build/web/shared/components/Modal/index.js +1 -1
- package/build/web/shared/components/Modal/index.js.map +1 -1
- package/build/web/shared/components/PageLayout/index.js +1 -1
- package/build/web/shared/components/PageLayout/index.js.map +1 -1
- package/build/web/shared/components/TextArea/index.js +1 -1
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/Throbber/index.js +1 -1
- package/build/web/shared/components/Throbber/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +1 -1
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js +1 -1
- package/build/web/shared/components/YouTubeVideo/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +3 -0
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +3 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +4 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +2 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv.js +2 -0
- package/build/web/shared/utils/jest/E2eSsrEnv.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +9 -0
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +2 -0
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/node-ssr.js +7 -1
- package/config/babel/webpack.js +3 -1
- package/config/webpack/app-base.js +4 -7
- package/config/webpack/app-development.js +2 -3
- package/package.json +20 -9
- package/src/client/getInj.ts +0 -71
- package/src/client/index.tsx +0 -45
- package/src/client/init.ts +0 -52
- package/src/index.ts +0 -75
- package/src/server/Cache.ts +0 -61
- package/src/server/index.ts +0 -243
- package/src/server/renderer.tsx +0 -635
- package/src/server/server.ts +0 -330
- package/src/server/utils/errors.ts +0 -122
- package/src/server/utils/index.ts +0 -3
- package/src/shared/components/Button/index.tsx +0 -130
- package/src/shared/components/Button/style.scss +0 -54
- package/src/shared/components/Checkbox/index.tsx +0 -53
- package/src/shared/components/Checkbox/theme.scss +0 -63
- package/src/shared/components/GenericLink/index.tsx +0 -141
- package/src/shared/components/GenericLink/style.scss +0 -3
- package/src/shared/components/Input/index.tsx +0 -96
- package/src/shared/components/Input/theme.scss +0 -52
- package/src/shared/components/Link.tsx +0 -25
- package/src/shared/components/Modal/base-theme.scss +0 -38
- package/src/shared/components/Modal/index.tsx +0 -177
- package/src/shared/components/Modal/styles.scss +0 -3
- package/src/shared/components/NavLink.tsx +0 -18
- package/src/shared/components/PageLayout/base-theme.scss +0 -30
- package/src/shared/components/PageLayout/index.tsx +0 -51
- package/src/shared/components/TextArea/index.tsx +0 -139
- package/src/shared/components/TextArea/style.scss +0 -68
- package/src/shared/components/Throbber/index.tsx +0 -28
- package/src/shared/components/Throbber/theme.scss +0 -26
- package/src/shared/components/WithTooltip/Tooltip.tsx +0 -274
- package/src/shared/components/WithTooltip/default-theme.scss +0 -36
- package/src/shared/components/WithTooltip/index.tsx +0 -186
- package/src/shared/components/YouTubeVideo/base.scss +0 -15
- package/src/shared/components/YouTubeVideo/index.tsx +0 -73
- package/src/shared/components/YouTubeVideo/throbber.scss +0 -11
- package/src/shared/components/index.ts +0 -20
- package/src/shared/components/selectors/CustomDropdown/Options/index.tsx +0 -124
- package/src/shared/components/selectors/CustomDropdown/Options/style.scss +0 -6
- package/src/shared/components/selectors/CustomDropdown/index.tsx +0 -146
- package/src/shared/components/selectors/CustomDropdown/theme.scss +0 -118
- package/src/shared/components/selectors/NativeDropdown/index.tsx +0 -90
- package/src/shared/components/selectors/NativeDropdown/theme.scss +0 -81
- package/src/shared/components/selectors/Switch/index.tsx +0 -74
- package/src/shared/components/selectors/Switch/theme.scss +0 -39
- package/src/shared/components/selectors/common.ts +0 -57
- package/src/shared/components/selectors/index.ts +0 -8
- package/src/shared/utils/config.ts +0 -59
- package/src/shared/utils/globalState.ts +0 -44
- package/src/shared/utils/index.ts +0 -45
- package/src/shared/utils/isomorphy/buildInfo.ts +0 -50
- package/src/shared/utils/isomorphy/environment-check.ts +0 -18
- package/src/shared/utils/isomorphy/index.ts +0 -36
- package/src/shared/utils/jest/E2eSsrEnv.ts +0 -304
- package/src/shared/utils/jest/global.ts +0 -17
- package/src/shared/utils/jest/index.ts +0 -215
- package/src/shared/utils/splitComponent.tsx +0 -284
- package/src/shared/utils/time.ts +0 -101
- package/src/shared/utils/webpack.ts +0 -80
- package/src/styles/_global/reset.css +0 -52
- package/src/styles/_mixins/fonts.scss +0 -40
- package/src/styles/_mixins/media.scss +0 -150
- package/src/styles/_mixins/typography.scss +0 -83
- package/src/styles/global.scss +0 -11
- package/src/styles/mixins.scss +0 -6
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["themed","defaultTheme","jsx","_jsx","jsxs","_jsxs","Throbber","theme","className","container","children","circle"],"sources":["../../../../../src/shared/components/Throbber/index.tsx"],"sourcesContent":["import themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT = 'bouncing' | 'circle' | 'container';\n\ntype PropsT = {\n theme: Theme<ThemeKeyT>;\n};\n\n/**\n * Throbber is an \"action in progress\" indicator, which renders\n * three bouncing circles as a simple pending activity indicator,\n * and can be further themed to a certain degree.\n * @param {object} [props] Component properties.\n * @param {ThrobberTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Throbber: React.FunctionComponent<PropsT> = ({ theme }) => (\n <span className={theme.container}>\n <span className={theme.circle} />\n <span className={theme.circle} />\n <span className={theme.circle} />\n </span>\n);\n\nexport default themed(Throbber, 'Throbber', defaultTheme);\n"],"mappings":"AAAA,MAAO,CAAAA,MAAM,KAAsB,0BAA0B,OAAAC,YAAA,+GAErB,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAQxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,QAAyC,CAAGA,CAAC,CAAEC,KAAM,CAAC,gBAC1DF,KAAA,SAAMG,SAAS,CAAED,KAAK,CAACE,SAAU,CAAAC,QAAA,eAC/BP,IAAA,SAAMK,SAAS,CAAED,KAAK,CAACI,MAAO,CAAE,CAAC,cACjCR,IAAA,SAAMK,SAAS,CAAED,KAAK,CAACI,MAAO,CAAE,CAAC,cACjCR,IAAA,SAAMK,SAAS,CAAED,KAAK,CAACI,MAAO,CAAE,CAAC,EAC7B,CACP,CAED,cAAe,
|
|
1
|
+
{"version":3,"file":"index.js","names":["themed","defaultTheme","jsx","_jsx","jsxs","_jsxs","Throbber","theme","className","container","children","circle"],"sources":["../../../../../src/shared/components/Throbber/index.tsx"],"sourcesContent":["import themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeKeyT = 'bouncing' | 'circle' | 'container';\n\ntype PropsT = {\n theme: Theme<ThemeKeyT>;\n};\n\n/**\n * Throbber is an \"action in progress\" indicator, which renders\n * three bouncing circles as a simple pending activity indicator,\n * and can be further themed to a certain degree.\n * @param {object} [props] Component properties.\n * @param {ThrobberTheme} [props.theme] _Ad hoc_ theme.\n * @param {...any} [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Throbber: React.FunctionComponent<PropsT> = ({ theme }) => (\n <span className={theme.container}>\n <span className={theme.circle} />\n <span className={theme.circle} />\n <span className={theme.circle} />\n </span>\n);\n\nexport default /* #__PURE__ */ themed(Throbber, 'Throbber', defaultTheme);\n"],"mappings":"AAAA,MAAO,CAAAA,MAAM,KAAsB,0BAA0B,OAAAC,YAAA,+GAErB,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAQxC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,QAAyC,CAAGA,CAAC,CAAEC,KAAM,CAAC,gBAC1DF,KAAA,SAAMG,SAAS,CAAED,KAAK,CAACE,SAAU,CAAAC,QAAA,eAC/BP,IAAA,SAAMK,SAAS,CAAED,KAAK,CAACI,MAAO,CAAE,CAAC,cACjCR,IAAA,SAAMK,SAAS,CAAED,KAAK,CAACI,MAAO,CAAE,CAAC,cACjCR,IAAA,SAAMK,SAAS,CAAED,KAAK,CAACI,MAAO,CAAE,CAAC,EAC7B,CACP,CAED,cAAe,eAAgBX,MAAM,CAACM,QAAQ,CAAE,UAAU,CAAEL,YAAY,CAAC","ignoreList":[]}
|
|
@@ -21,5 +21,5 @@ if(heap.triggeredByTouch){heap.timerId??=setTimeout(()=>{heap.triggeredByTouch=f
|
|
|
21
21
|
// once opened (because similar call above does not have effect until
|
|
22
22
|
// the tooltip is fully mounted, and that is delayed to future rendering
|
|
23
23
|
// cycle due to the implementation).
|
|
24
|
-
if(tooltipRef.current){tooltipRef.current.pointTo(heap.lastCursorX+window.scrollX,heap.lastCursorY+window.scrollY,placement,wrapperRef.current)}const listener=()=>{setShowTooltip(false)};window.addEventListener("scroll",listener);return()=>{window.removeEventListener("scroll",listener)}}return undefined},[heap.lastCursorX,heap.lastCursorY,placement,showTooltip,tip]);return/*#__PURE__*/_jsxs("div",{className:theme.wrapper,onClick:()=>{if(heap.timerId){clearTimeout(heap.timerId);heap.timerId=undefined;heap.triggeredByTouch=false}},onMouseLeave:()=>{setShowTooltip(false)},onMouseMove:e=>{updatePortalPosition(e.clientX,e.clientY)},onTouchStart:()=>{heap.triggeredByTouch=true},ref:wrapperRef,role:"presentation",children:[showTooltip&&tip!==null?/*#__PURE__*/_jsx(Tooltip,{ref:tooltipRef,theme:theme,children:tip}):null,children]})};const ThemedWrapper
|
|
24
|
+
if(tooltipRef.current){tooltipRef.current.pointTo(heap.lastCursorX+window.scrollX,heap.lastCursorY+window.scrollY,placement,wrapperRef.current)}const listener=()=>{setShowTooltip(false)};window.addEventListener("scroll",listener);return()=>{window.removeEventListener("scroll",listener)}}return undefined},[heap.lastCursorX,heap.lastCursorY,placement,showTooltip,tip]);return/*#__PURE__*/_jsxs("div",{className:theme.wrapper,onClick:()=>{if(heap.timerId){clearTimeout(heap.timerId);heap.timerId=undefined;heap.triggeredByTouch=false}},onMouseLeave:()=>{setShowTooltip(false)},onMouseMove:e=>{updatePortalPosition(e.clientX,e.clientY)},onTouchStart:()=>{heap.triggeredByTouch=true},ref:wrapperRef,role:"presentation",children:[showTooltip&&tip!==null?/*#__PURE__*/_jsx(Tooltip,{ref:tooltipRef,theme:theme,children:tip}):null,children]})};const ThemedWrapper=/* #__PURE__ */themed(Wrapper,"WithTooltip",defaultTheme);const e=ThemedWrapper;e.PLACEMENTS=PLACEMENTS;export default e;
|
|
25
25
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","themed","Tooltip","PLACEMENTS","defaultTheme","jsx","_jsx","jsxs","_jsxs","Wrapper","children","placement","ABOVE_CURSOR","tip","theme","current","heap","lastCursorX","lastCursorY","timerId","undefined","triggeredByTouch","tooltipRef","wrapperRef","showTooltip","setShowTooltip","updatePortalPosition","cursorX","cursorY","wrapperRect","getBoundingClientRect","left","right","top","bottom","pointTo","window","scrollX","scrollY","setTimeout","listener","addEventListener","removeEventListener","className","wrapper","onClick","clearTimeout","onMouseLeave","onMouseMove","e","clientX","clientY","onTouchStart","ref","role","ThemedWrapper"],"sources":["../../../../../src/shared/components/WithTooltip/index.tsx"],"sourcesContent":["/* global window */\n\nimport {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport Tooltip, {\n type ThemeKeysT as TooltipThemeKeysT,\n PLACEMENTS,\n} from './Tooltip';\n\nimport defaultTheme from './default-theme.scss';\n\ntype PropsT = {\n children?: ReactNode;\n placement?: PLACEMENTS;\n tip?: ReactNode;\n theme: Theme<'wrapper' | TooltipThemeKeysT>;\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 lastCursorX: number;\n lastCursorY: number;\n triggeredByTouch: boolean;\n timerId?: NodeJS.Timeout;\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 Wrapper: FunctionComponent<PropsT> = ({\n children,\n placement = PLACEMENTS.ABOVE_CURSOR,\n tip,\n theme,\n}) => {\n const { current: heap } = useRef<HeapT>({\n lastCursorX: 0,\n lastCursorY: 0,\n timerId: undefined,\n triggeredByTouch: false,\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 heap.lastCursorX = cursorX;\n heap.lastCursorY = cursorY;\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 (heap.triggeredByTouch) {\n heap.timerId ??= setTimeout(() => {\n heap.triggeredByTouch = false;\n heap.timerId = undefined;\n setShowTooltip(true);\n }, 300);\n\n // Otherwise we can just open the tooltip right away.\n } else setShowTooltip(true);\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 tooltipRef.current.pointTo(\n heap.lastCursorX + window.scrollX,\n heap.lastCursorY + window.scrollY,\n placement,\n wrapperRef.current!,\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 heap.lastCursorX,\n heap.lastCursorY,\n placement,\n showTooltip,\n tip,\n ]);\n\n return (\n <div\n className={theme.wrapper}\n onClick={() => {\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n heap.timerId = undefined;\n heap.triggeredByTouch = false;\n }\n }}\n onMouseLeave={() => {\n setShowTooltip(false);\n }}\n onMouseMove={(e) => {\n updatePortalPosition(e.clientX, e.clientY);\n }}\n onTouchStart={() => {\n heap.triggeredByTouch = true;\n }}\n ref={wrapperRef}\n role=\"presentation\"\n >\n {\n showTooltip && tip !== null\n ? <Tooltip ref={tooltipRef} theme={theme}>{tip}</Tooltip>\n : null\n }\n {children}\n </div>\n );\n};\n\nconst ThemedWrapper = themed(Wrapper, 'WithTooltip', defaultTheme);\n\ntype ExportT = typeof ThemedWrapper & {\n PLACEMENTS: typeof PLACEMENTS;\n};\n\nconst e: ExportT = ThemedWrapper as ExportT;\n\ne.PLACEMENTS = PLACEMENTS;\n\nexport default e;\n"],"mappings":"AAAA,mBAEA,OAGEA,SAAS,CACTC,MAAM,CACNC,Q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,CAAC8B,OAAQ,CACzBC,OAAO,CAAEA,CAAA,GAAM,CACb,GAAI7B,IAAI,CAACG,OAAO,CAAE,CAChB2B,YAAY,CAAC9B,IAAI,CAACG,OAAO,CAAC,CAC1BH,IAAI,CAACG,OAAO,CAAGC,SAAS,CACxBJ,IAAI,CAACK,gBAAgB,CAAG,KAC1B,CACF,CAAE,CACF0B,YAAY,CAAEA,CAAA,GAAM,CAClBtB,cAAc,CAAC,KAAK,CACtB,CAAE,CACFuB,WAAW,CAAGC,CAAC,EAAK,CAClBvB,oBAAoB,CAACuB,CAAC,CAACC,OAAO,CAAED,CAAC,CAACE,OAAO,CAC3C,CAAE,CACFC,YAAY,CAAEA,CAAA,GAAM,CAClBpC,IAAI,CAACK,gBAAgB,CAAG,IAC1B,CAAE,CACFgC,GAAG,CAAE9B,UAAW,CAChB+B,IAAI,CAAC,cAAc,CAAA5C,QAAA,EAGjBc,WAAW,EAAIX,GAAG,GAAK,IAAI,cACvBP,IAAA,CAACJ,OAAO,EAACmD,GAAG,CAAE/B,UAAW,CAACR,KAAK,CAAEA,KAAM,CAAAJ,QAAA,CAAEG,GAAG,CAAU,CAAC,CACvD,IAAI,CAETH,QAAQ,EACN,CAET,CAAC,CAED,KAAM,CAAA6C,aAAa,
|
|
1
|
+
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","themed","Tooltip","PLACEMENTS","defaultTheme","jsx","_jsx","jsxs","_jsxs","Wrapper","children","placement","ABOVE_CURSOR","tip","theme","current","heap","lastCursorX","lastCursorY","timerId","undefined","triggeredByTouch","tooltipRef","wrapperRef","showTooltip","setShowTooltip","updatePortalPosition","cursorX","cursorY","wrapperRect","getBoundingClientRect","left","right","top","bottom","pointTo","window","scrollX","scrollY","setTimeout","listener","addEventListener","removeEventListener","className","wrapper","onClick","clearTimeout","onMouseLeave","onMouseMove","e","clientX","clientY","onTouchStart","ref","role","ThemedWrapper"],"sources":["../../../../../src/shared/components/WithTooltip/index.tsx"],"sourcesContent":["/* global window */\n\nimport {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport Tooltip, {\n type ThemeKeysT as TooltipThemeKeysT,\n PLACEMENTS,\n} from './Tooltip';\n\nimport defaultTheme from './default-theme.scss';\n\ntype PropsT = {\n children?: ReactNode;\n placement?: PLACEMENTS;\n tip?: ReactNode;\n theme: Theme<'wrapper' | TooltipThemeKeysT>;\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 lastCursorX: number;\n lastCursorY: number;\n triggeredByTouch: boolean;\n timerId?: NodeJS.Timeout;\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 Wrapper: FunctionComponent<PropsT> = ({\n children,\n placement = PLACEMENTS.ABOVE_CURSOR,\n tip,\n theme,\n}) => {\n const { current: heap } = useRef<HeapT>({\n lastCursorX: 0,\n lastCursorY: 0,\n timerId: undefined,\n triggeredByTouch: false,\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 heap.lastCursorX = cursorX;\n heap.lastCursorY = cursorY;\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 (heap.triggeredByTouch) {\n heap.timerId ??= setTimeout(() => {\n heap.triggeredByTouch = false;\n heap.timerId = undefined;\n setShowTooltip(true);\n }, 300);\n\n // Otherwise we can just open the tooltip right away.\n } else setShowTooltip(true);\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 tooltipRef.current.pointTo(\n heap.lastCursorX + window.scrollX,\n heap.lastCursorY + window.scrollY,\n placement,\n wrapperRef.current!,\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 heap.lastCursorX,\n heap.lastCursorY,\n placement,\n showTooltip,\n tip,\n ]);\n\n return (\n <div\n className={theme.wrapper}\n onClick={() => {\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n heap.timerId = undefined;\n heap.triggeredByTouch = false;\n }\n }}\n onMouseLeave={() => {\n setShowTooltip(false);\n }}\n onMouseMove={(e) => {\n updatePortalPosition(e.clientX, e.clientY);\n }}\n onTouchStart={() => {\n heap.triggeredByTouch = true;\n }}\n ref={wrapperRef}\n role=\"presentation\"\n >\n {\n showTooltip && tip !== null\n ? <Tooltip ref={tooltipRef} theme={theme}>{tip}</Tooltip>\n : null\n }\n {children}\n </div>\n );\n};\n\nconst ThemedWrapper = /* #__PURE__ */ themed(Wrapper, 'WithTooltip', defaultTheme);\n\ntype ExportT = typeof ThemedWrapper & {\n PLACEMENTS: typeof PLACEMENTS;\n};\n\nconst e: ExportT = ThemedWrapper as ExportT;\n\ne.PLACEMENTS = PLACEMENTS;\n\nexport default e;\n"],"mappings":"AAAA,mBAEA,OAGEA,SAAS,CACTC,MAAM,CACNC,QAAQ,KACH,OAAO,CAEd,MAAO,CAAAC,MAAM,KAAsB,0BAA0B,OAEtD,CAAAC,OAAO,EAEZC,UAAU,0BAAAC,YAAA,oIAGoC,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAyBhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,KAAM,CAAAC,OAAkC,CAAGA,CAAC,CAC1CC,QAAQ,CACRC,SAAS,CAAGR,UAAU,CAACS,YAAY,CACnCC,GAAG,CACHC,KACF,CAAC,GAAK,CACJ,KAAM,CAAEC,OAAO,CAAEC,IAAK,CAAC,CAAGjB,MAAM,CAAQ,CACtCkB,WAAW,CAAE,CAAC,CACdC,WAAW,CAAE,CAAC,CACdC,OAAO,CAAEC,SAAS,CAClBC,gBAAgB,CAAE,KACpB,CAAC,CAAC,CACF,KAAM,CAAAC,UAAU,CAAGvB,MAAM,CAAc,IAAI,CAAC,CAC5C,KAAM,CAAAwB,UAAU,CAAGxB,MAAM,CAAiB,IAAI,CAAC,CAC/C,KAAM,CAACyB,WAAW,CAAEC,cAAc,CAAC,CAAGzB,QAAQ,CAAC,KAAK,CAAC,CAErD,KAAM,CAAA0B,oBAAoB,CAAGA,CAACC,OAAe,CAAEC,OAAe,GAAK,CACjE,GAAIJ,WAAW,CAAE,CACf,KAAM,CAAAK,WAAW,CAAGN,UAAU,CAACR,OAAO,CAAEe,qBAAqB,CAAC,CAAC,CAC/D,GACEH,OAAO,CAAGE,WAAW,CAACE,IAAI,EACvBJ,OAAO,CAAGE,WAAW,CAACG,KAAK,EAC3B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themed from"@dr.pogodin/react-themes";import Throbber
|
|
|
15
15
|
*/const YouTubeVideo=({autoplay,src,theme,title})=>{const srcParts=src.split("?");let[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";url+=`?${qs.stringify(query)}`;// TODO: https://developers.google.com/youtube/player_parameters
|
|
16
16
|
// More query parameters can be exposed via the component props.
|
|
17
17
|
return/*#__PURE__*/_jsxs("div",{className:theme.container,children:[/*#__PURE__*/_jsx(Throbber,{theme:throbberTheme}),/*#__PURE__*/_jsx("iframe",{// eslint-disable-line react/iframe-missing-sandbox
|
|
18
|
-
allow:"autoplay",allowFullScreen:true,className:theme.video,src:url,title:title})]})};export default themed(YouTubeVideo,"YouTubeVideo",baseTheme);
|
|
18
|
+
allow:"autoplay",allowFullScreen:true,className:theme.video,src:url,title:title})]})};export default/* #__PURE__ */themed(YouTubeVideo,"YouTubeVideo",baseTheme);
|
|
19
19
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["qs","themed","Throbber","baseTheme","throbberTheme","jsx","_jsx","jsxs","_jsxs","YouTubeVideo","autoplay","src","theme","title","srcParts","split","url","queryString","query","parse","videoId","v","match","stringify","className","container","children","allow","allowFullScreen","video"],"sources":["../../../../../src/shared/components/YouTubeVideo/index.tsx"],"sourcesContent":["import qs from 'qs';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport Throbber from 'components/Throbber';\n\nimport baseTheme from './base.scss';\nimport throbberTheme from './throbber.scss';\n\ntype ComponentThemeT = Theme<'container' | 'video'>;\n\ntype PropsT = {\n autoplay?: boolean;\n src: string;\n theme: ComponentThemeT;\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: React.FunctionComponent<PropsT> = ({\n autoplay,\n src,\n theme,\n title,\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={theme.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={theme.video}\n src={url}\n title={title}\n />\n </div>\n );\n};\n\nexport default themed(YouTubeVideo, 'YouTubeVideo', baseTheme);\n"],"mappings":"AAAA,MAAO,CAAAA,EAAE,KAAM,IAAI,CAEnB,MAAO,CAAAC,MAAM,KAAsB,0BAA0B,OAEtD,CAAAC,QAAQ,kCAAAC,SAAA,+FAAAC,aAAA,yEAG6B,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,YAA6C,CAAGA,CAAC,CACrDC,QAAQ,CACRC,GAAG,CACHC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,KAAM,CAAAC,QAAQ,CAAGH,GAAG,CAACI,KAAK,CAAC,GAAG,CAAC,CAC/B,GAAI,CAACC,GAAG,CAAC,CAAGF,QAAQ,CACpB,KAAM,EAAGG,WAAW,CAAC,CAAGH,QAAQ,CAChC,KAAM,CAAAI,KAAK,CAAGD,WAAW,CAAGjB,EAAE,CAACmB,KAAK,CAACF,WAAW,CAAC,CAAG,CAAC,CAAC,CAEtD,KAAM,CAAAG,OAAO,CAAGF,KAAK,CAACG,CAAC,EAAIL,GAAG,EAAEM,KAAK,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC,CACjEN,GAAG,CAAG,iCAAiCI,OAAO,EAAY,CAE1D,MAAO,CAAAF,KAAK,CAACG,CAAC,CACdH,KAAK,CAACR,QAAQ,CAAGA,QAAQ,CAAG,GAAG,CAAG,GAAG,CACrCM,GAAG,EAAI,IAAIhB,EAAE,CAACuB,SAAS,CAACL,KAAK,CAAC,EAAE,CAEhC;AACA;AAEA,mBACEV,KAAA,QAAKgB,SAAS,CAAEZ,KAAK,CAACa,SAAU,CAAAC,QAAA,eAC9BpB,IAAA,CAACJ,QAAQ,EAACU,KAAK,CAAER,aAAc,CAAE,CAAC,cAKlCE,IAAA,WAAQ;AACNqB,KAAK,CAAC,UAAU,CAChBC,eAAe,MACfJ,SAAS,CAAEZ,KAAK,CAACiB,KAAM,CACvBlB,GAAG,CAAEK,GAAI,CACTH,KAAK,CAAEA,KAAM,CACd,CAAC,EACC,CAET,CAAC,CAED,cAAe,
|
|
1
|
+
{"version":3,"file":"index.js","names":["qs","themed","Throbber","baseTheme","throbberTheme","jsx","_jsx","jsxs","_jsxs","YouTubeVideo","autoplay","src","theme","title","srcParts","split","url","queryString","query","parse","videoId","v","match","stringify","className","container","children","allow","allowFullScreen","video"],"sources":["../../../../../src/shared/components/YouTubeVideo/index.tsx"],"sourcesContent":["import qs from 'qs';\n\nimport themed, { type Theme } from '@dr.pogodin/react-themes';\n\nimport Throbber from 'components/Throbber';\n\nimport baseTheme from './base.scss';\nimport throbberTheme from './throbber.scss';\n\ntype ComponentThemeT = Theme<'container' | 'video'>;\n\ntype PropsT = {\n autoplay?: boolean;\n src: string;\n theme: ComponentThemeT;\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: React.FunctionComponent<PropsT> = ({\n autoplay,\n src,\n theme,\n title,\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={theme.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={theme.video}\n src={url}\n title={title}\n />\n </div>\n );\n};\n\nexport default /* #__PURE__ */ themed(YouTubeVideo, 'YouTubeVideo', baseTheme);\n"],"mappings":"AAAA,MAAO,CAAAA,EAAE,KAAM,IAAI,CAEnB,MAAO,CAAAC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AAC,CAED,cAAe,eAAgBZ,MAAM,CAACQ,YAAY,CAAE,cAAc,CAAEN,SAAS,CAAC","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{useImperativeHandle,useRef}from"react";import{BaseModal}from"../../../Modal/index.js";import{optionValueName}from"../../common.js";const S={"overlay":"ntZ5My"};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})=>{const opsRef=useRef(null);useImperativeHandle(ref,()=>({measure:()=>{const e=opsRef.current?.parentElement;if(!e)return undefined;const rect=opsRef.current.getBoundingClientRect();const style=window.getComputedStyle(e);const mBottom=parseFloat(style.marginBottom);const mTop=parseFloat(style.marginTop);rect.height+=mBottom+mTop;return rect}}),[]);const optionNodes=[];for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);optionNodes.push(/*#__PURE__*/_jsx("div",{className:optionClass,onClick:e=>{onChange(iValue);e.stopPropagation()},onKeyDown:e=>{if(e.key==="Enter"){onChange(iValue);e.stopPropagation()}},role:"button",tabIndex:0,children:iName},iValue))}}return/*#__PURE__*/_jsx(BaseModal// Closes the dropdown (cancels the selection) on any page scrolling attempt.
|
|
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"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/index.js";import{optionValueName}from"../../common.js";const S={"overlay":"ntZ5My"};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})=>{const opsRef=useRef(null);useImperativeHandle(ref,()=>({measure:()=>{const e=opsRef.current?.parentElement;if(!e)return undefined;const rect=opsRef.current.getBoundingClientRect();const style=window.getComputedStyle(e);const mBottom=parseFloat(style.marginBottom);const mTop=parseFloat(style.marginTop);rect.height+=mBottom+mTop;return rect}}),[]);const optionNodes=[];for(const option of options){if(!filter||filter(option)){const[iValue,iName]=optionValueName(option);optionNodes.push(/*#__PURE__*/_jsx("div",{className:optionClass,onClick:e=>{onChange(iValue);e.stopPropagation()},onKeyDown:e=>{if(e.key==="Enter"){onChange(iValue);e.stopPropagation()}},role:"button",tabIndex:0,children:iName},iValue))}}return/*#__PURE__*/_jsx(BaseModal// Closes the dropdown (cancels the selection) on any page scrolling attempt.
|
|
2
2
|
// This is the same native <select> elements do on scrolling, and at least for
|
|
3
3
|
// now we have no reason to deal with complications needed to support open
|
|
4
4
|
// dropdowns during the scrolling (that would need to re-position it in
|
|
@@ -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","undefined","rect","getBoundingClientRect","style","window","getComputedStyle","mBottom","parseFloat","marginBottom","mTop","marginTop","height","optionNodes","option","iValue","iName","push","className","onClick","stopPropagation","onKeyDown","key","role","tabIndex","children","cancelOnScrolling","dontDisableScrolling","theme","ad","container","context","hoc","overlay"],"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 optionClass: string;\n options: Readonly<OptionsT<ReactNode>>;\n onCancel: () => void;\n onChange: (value: ValueT) => void;\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":"
|
|
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","undefined","rect","getBoundingClientRect","style","window","getComputedStyle","mBottom","parseFloat","marginBottom","mTop","marginTop","height","optionNodes","option","iValue","iName","push","className","onClick","stopPropagation","onKeyDown","key","role","tabIndex","children","cancelOnScrolling","dontDisableScrolling","theme","ad","container","context","hoc","overlay"],"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 optionClass: string;\n options: Readonly<OptionsT<ReactNode>>;\n onCancel: () => void;\n onChange: (value: ValueT) => void;\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":"oRAAA,OAIEA,mBAAmB,CACnBC,MAAM,KACD,OAAO,QAELC,SAAS,sCAMhBC,eAAe,6BAAAC,CAAA,sBAGY,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,KACrE,CAiBA,KAAM,CAAAC,OAAkC,CAAGA,CAAC,CAC1CC,cAAc,CACdC,cAAc,CACdC,MAAM,CACNC,QAAQ,CACRC,QAAQ,CACRC,WAAW,CACXC,OAAO,CACPC,GACF,CAAC,GAAK,CACJ,KAAM,CAAAC,MAAM,CAAGrB,MAAM,CAAiB,IAAI,CAAC,CAE3CD,mBAAmB,CAACqB,GAAG,CAAE,KAAO,CAC9BE,OAAO,CAAEA,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,IAAA,CAACJ,SACC;AACA;AACA;AACA;AACA;AAAA,EACAkD,iBAAiB,MACjBC,oBAAoB,MACpBpC,QAAQ,CAAEA,QAAS,CACnBa,KAAK,CAAEf,cAAe,CACtBuC,KAAK,CAAE,CACLC,EAAE,CAAE,EAAE,CACNC,SAAS,CAAE1C,cAAc,CACzB2C,OAAO,CAAE,EAAE,CACXC,GAAG,CAAE,EAAE,CACPC,OAAO,CAAEvD,CAAC,CAACuD,OACb,CAAE,CAAAR,QAAA,cAEF7C,IAAA,QAAKe,GAAG,CAAEC,MAAO,CAAA6B,QAAA,CAAEZ,WAAW,CAAM,CAAC,CAC5B,CAEf,CAAC,CAED,cAAe,CAAA1B,OAAO","ignoreList":[]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{useEffect,useRef,useState}from"react";import themed from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";import Options,{areEqual}from"./Options/index.js";const defaultTheme={"context":"SNj3wp","ad":"T6eOJ-","hoc":"KG-OKN","container":"SzHHPE","label":"KTG4ai","dropdown":"xdotm7","option":"y-WCDM","select":"PP5Siy","arrow":"_7-A7Lh","active":"RoOAZK","upward":"_--5Xpy"};import{Fragment as _Fragment,jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const BaseCustomDropdown=({filter,label,onChange,options,theme,value})=>{const[active,setActive]=useState(false);const dropdownRef=useRef(null);const opsRef=useRef(null);const[opsPos,setOpsPos]=useState();const[upward,setUpward]=useState(false);useEffect(()=>{if(!active)return undefined;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)}},[active]);const openList=e=>{const view=window.visualViewport;const rect=dropdownRef.current.getBoundingClientRect();setActive(true);// NOTE: This first opens the dropdown off-screen, where it is measured
|
|
1
|
+
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";import{useEffect,useRef,useState}from"react";import themed from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";import Options,{areEqual}from"./Options/index.js";const defaultTheme={"context":"SNj3wp","ad":"T6eOJ-","hoc":"KG-OKN","container":"SzHHPE","label":"KTG4ai","dropdown":"xdotm7","option":"y-WCDM","select":"PP5Siy","arrow":"_7-A7Lh","active":"RoOAZK","upward":"_--5Xpy"};import{Fragment as _Fragment,jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const BaseCustomDropdown=({filter,label,onChange,options,theme,value})=>{const[active,setActive]=useState(false);const dropdownRef=useRef(null);const opsRef=useRef(null);const[opsPos,setOpsPos]=useState();const[upward,setUpward]=useState(false);useEffect(()=>{if(!active)return undefined;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)}},[active]);const openList=e=>{const view=window.visualViewport;const rect=dropdownRef.current.getBoundingClientRect();setActive(true);// NOTE: This first opens the dropdown off-screen, where it is measured
|
|
2
2
|
// by an effect declared above, and then positioned below, or above
|
|
3
3
|
// the original dropdown element, depending where it fits best
|
|
4
4
|
// (if we first open it downward, it would flick if we immediately
|
|
5
5
|
// move it above, at least with the current position update via local
|
|
6
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=theme.container;if(active)containerClassName+=` ${theme.active}`;let opsContainerClass=theme.select??"";if(upward){containerClassName+=` ${theme.upward}`;opsContainerClass+=` ${theme.upward}`}return/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[label===undefined?null:/*#__PURE__*/_jsx("div",{className:theme.label,children:label}),/*#__PURE__*/_jsxs("div",{className:theme.dropdown,onClick:openList,onKeyDown:e=>{if(e.key==="Enter")openList(e)},ref:dropdownRef,role:"listbox",tabIndex:0,children:[selected,/*#__PURE__*/_jsx("div",{className:theme.arrow})]}),active?/*#__PURE__*/_jsx(Options,{containerClass:opsContainerClass,containerStyle:opsPos,onCancel:()=>{setActive(false)},onChange:newValue=>{setActive(false);if(onChange)onChange(newValue)},optionClass:theme.option??"",options:options,ref:opsRef}):null]})};export default themed(BaseCustomDropdown,"CustomDropdown",defaultTheme);
|
|
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=theme.container;if(active)containerClassName+=` ${theme.active}`;let opsContainerClass=theme.select??"";if(upward){containerClassName+=` ${theme.upward}`;opsContainerClass+=` ${theme.upward}`}return/*#__PURE__*/_jsxs("div",{className:containerClassName,children:[label===undefined?null:/*#__PURE__*/_jsx("div",{className:theme.label,children:label}),/*#__PURE__*/_jsxs("div",{className:theme.dropdown,onClick:openList,onKeyDown:e=>{if(e.key==="Enter")openList(e)},ref:dropdownRef,role:"listbox",tabIndex:0,children:[selected,/*#__PURE__*/_jsx("div",{className:theme.arrow})]}),active?/*#__PURE__*/_jsx(Options,{containerClass:opsContainerClass,containerStyle:opsPos,onCancel:()=>{setActive(false)},onChange:newValue=>{setActive(false);if(onChange)onChange(newValue)},optionClass:theme.option??"",options:options,ref:opsRef}):null]})};export default/* #__PURE__ */themed(BaseCustomDropdown,"CustomDropdown",defaultTheme);
|
|
8
8
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","themed","optionValueName","Options","areEqual","defaultTheme","Fragment","_Fragment","jsx","_jsx","jsxs","_jsxs","BaseCustomDropdown","filter","label","onChange","options","theme","value","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 { useEffect, useRef, useState } from 'react';\n\nimport themed 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 BaseCustomDropdown: React.FunctionComponent<\n PropsT<React.ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\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 = theme.container;\n if (active) containerClassName += ` ${theme.active}`;\n\n let opsContainerClass = theme.select ?? '';\n if (upward) {\n containerClassName += ` ${theme.upward}`;\n opsContainerClass += ` ${theme.upward}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={theme.label}>{label}</div>}\n <div\n className={theme.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={theme.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={theme.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default themed(BaseCustomDropdown, 'CustomDropdown', defaultTheme);\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["useEffect","useRef","useState","themed","optionValueName","Options","areEqual","defaultTheme","Fragment","_Fragment","jsx","_jsx","jsxs","_jsxs","BaseCustomDropdown","filter","label","onChange","options","theme","value","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 { useEffect, useRef, useState } from 'react';\n\nimport themed 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 BaseCustomDropdown: React.FunctionComponent<\n PropsT<React.ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\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 = theme.container;\n if (active) containerClassName += ` ${theme.active}`;\n\n let opsContainerClass = theme.select ?? '';\n if (upward) {\n containerClassName += ` ${theme.upward}`;\n opsContainerClass += ` ${theme.upward}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={theme.label}>{label}</div>}\n <div\n className={theme.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={theme.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={theme.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default /* #__PURE__ */ themed(BaseCustomDropdown, 'CustomDropdown', defaultTheme);\n"],"mappings":"kMAAA,OAASA,SAAS,CAAEC,MAAM,CAAEC,QAAQ,KAAQ,OAAO,CAEnD,MAAO,CAAAC,MAAM,KAAM,0BAA0B,QAEVC,eAAe,0BAE3C,CAAAC,OAAO,EAAmCC,QAAQ,gCAAAC,YAAA,wMAEjB,OAAAC,QAAA,IAAAC,SAAA,CAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAExC,KAAM,CAAAC,kBAEL,CAAGA,CAAC,CACHC,MAAM,CACNC,KAAK,CACLC,QAAQ,CACRC,OAAO,CACPC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,KAAM,CAACC,MAAM,CAAEC,SAAS,CAAC,CAAGpB,QAAQ,CAAC,KAAK,CAAC,CAE3C,KAAM,CAAAqB,WAAW,CAAGtB,MAAM,CAAiB,IAAI,CAAC,CAChD,KAAM,CAAAuB,MAAM,CAAGvB,MAAM,CAAO,IAAI,CAAC,CAEjC,KAAM,CAACwB,MAAM,CAAEC,SAAS,CAAC,CAAGxB,QAAQ,CAAgB,CAAC,CACrD,KAAM,CAACyB,MAAM,CAAEC,SAAS,CAAC,CAAG1B,QAAQ,CAAC,KAAK,CAAC,CAE3CF,SAAS,CAAC,IAAM,CACd,GAAI,CAACqB,MAAM,CAAE,MAAO,CAAAQ,SAAS,CAE7B,GAAI,CAAAC,EAAU,CACd,KAAM,CAAAC,EAAE,CAAGA,CAAA,GAAM,CACf,KAAM,CAAAC,MAAM,CAAGT,WAAW,CAACU,OAAO,EAAEC,qBAAqB,CAAC,CAAC,CAC3D,KAAM,CAAA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K,CAAC+C,QAAS,CAC1BC,OAAO,CAAEhB,QAAS,CAClBiB,SAAS,CAAGhB,CAAC,EAAK,CAChB,GAAIA,CAAC,CAACiB,GAAG,GAAK,OAAO,CAAElB,QAAQ,CAACC,CAAC,CACnC,CAAE,CACFkB,GAAG,CAAE/C,WAAY,CACjBgD,IAAI,CAAC,SAAS,CACdC,QAAQ,CAAE,CAAE,CAAAf,QAAA,EAEXD,QAAQ,cACT7C,IAAA,QAAKsD,SAAS,CAAE9C,KAAK,CAACsD,KAAM,CAAE,CAAC,EAC5B,CAAC,CAEJpD,MAAM,cACJV,IAAA,CAACN,OAAO,EACNqE,cAAc,CAAEX,iBAAkB,CAClCY,cAAc,CAAElD,MAAO,CACvBmD,QAAQ,CAAEA,CAAA,GAAM,CACdtD,SAAS,CAAC,KAAK,CACjB,CAAE,CACFL,QAAQ,CAAG4D,QAAQ,EAAK,CACtBvD,SAAS,CAAC,KAAK,CAAC,CAChB,GAAIL,QAAQ,CAAEA,QAAQ,CAAC4D,QAAQ,CACjC,CAAE,CACFC,WAAW,CAAE3D,KAAK,CAACuC,MAAM,EAAI,EAAG,CAChCxC,OAAO,CAAEA,OAAQ,CACjBoD,GAAG,CAAE9C,MAAO,CACb,CAAC,CACA,IAAI,EAEP,CAET,CAAC,CAED,cAAe,eAAgBrB,MAAM,CAACW,kBAAkB,CAAE,gBAAgB,CAAEP,YAAY,CAAC","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
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"core-js/modules/es.array.push.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.filter.js";// Implements dropdown based on the native HTML <select> element.
|
|
2
2
|
import themed from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";const defaultTheme={"context":"WbwY1Y","ad":"AP5hsY","hoc":"ODAJeW","dropdown":"wabw76","arrow":"WFSB9z","container":"vE9M8Z","active":"sfLSJA","label":"bQLBhS","option":"wgCtdC","hiddenOption":"ty19C2","select":"ntbzPR","invalid":"_3CzMM4"};/**
|
|
3
3
|
* Implements a themeable dropdown list. Internally it is rendered with help of
|
|
4
4
|
* the standard HTML `<select>` element, thus the styling support is somewhat
|
|
@@ -21,5 +21,5 @@ import themed from"@dr.pogodin/react-themes";import{optionValueName}from"../comm
|
|
|
21
21
|
// any valid option. In Chrome, and some other browsers, we are able to hide
|
|
22
22
|
// it from the opened dropdown; in others, e.g. Safari, the best we can do is
|
|
23
23
|
// to show it as disabled.
|
|
24
|
-
const hiddenOption=isValidValue?null:/*#__PURE__*/_jsx("option",{className:theme.hiddenOption,disabled:true,value:value,children:value},"__reactUtilsHiddenOption");let selectClassName=theme.select;if(!isValidValue)selectClassName+=` ${theme.invalid}`;return/*#__PURE__*/_jsxs("div",{className:theme.container,children:[label===undefined?null:/*#__PURE__*/_jsx("div",{className:theme.label,children:label}),/*#__PURE__*/_jsxs("div",{className:theme.dropdown,children:[/*#__PURE__*/_jsxs("select",{className:selectClassName,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,onChange:onChange,value:value,children:[hiddenOption,optionElements]}),/*#__PURE__*/_jsx("div",{className:theme.arrow})]})]})};export default themed(Dropdown,"Dropdown",defaultTheme);
|
|
24
|
+
const hiddenOption=isValidValue?null:/*#__PURE__*/_jsx("option",{className:theme.hiddenOption,disabled:true,value:value,children:value},"__reactUtilsHiddenOption");let selectClassName=theme.select;if(!isValidValue)selectClassName+=` ${theme.invalid}`;return/*#__PURE__*/_jsxs("div",{className:theme.container,children:[label===undefined?null:/*#__PURE__*/_jsx("div",{className:theme.label,children:label}),/*#__PURE__*/_jsxs("div",{className:theme.dropdown,children:[/*#__PURE__*/_jsxs("select",{className:selectClassName,"data-testid":process.env.NODE_ENV==="production"?undefined:testId,onChange:onChange,value:value,children:[hiddenOption,optionElements]}),/*#__PURE__*/_jsx("div",{className:theme.arrow})]})]})};export default/* #__PURE__ */themed(Dropdown,"Dropdown",defaultTheme);
|
|
25
25
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["themed","optionValueName","defaultTheme","jsx","_jsx","jsxs","_jsxs","Dropdown","filter","label","onChange","options","testId","theme","value","isValidValue","optionElements","option","iValue","iName","push","className","children","hiddenOption","disabled","selectClassName","select","invalid","container","undefined","dropdown","process","env","NODE_ENV","arrow"],"sources":["../../../../../../src/shared/components/selectors/NativeDropdown/index.tsx"],"sourcesContent":["// Implements dropdown based on the native HTML <select> element.\n\nimport themed from '@dr.pogodin/react-themes';\n\nimport { type PropsT, optionValueName } from '../common';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param [props] Component properties.\n * @param [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param [props.label] Dropdown label.\n * @param [props.onChange] Selection event handler.\n * @param [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.value] Currently selected value.\n * @param [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Dropdown: React.FunctionComponent<PropsT<string>> = ({\n filter,\n label,\n onChange,\n options,\n testId,\n theme,\n value,\n}) => {\n let isValidValue = false;\n const optionElements = [];\n\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n isValidValue ||= iValue === value;\n optionElements.push(\n <option className={theme.option} key={iValue} value={iValue}>\n {iName}\n </option>,\n );\n }\n }\n\n // NOTE: This element represents the current `value` when it does not match\n // any valid option. In Chrome, and some other browsers, we are able to hide\n // it from the opened dropdown; in others, e.g. Safari, the best we can do is\n // to show it as disabled.\n const hiddenOption = isValidValue ? null : (\n <option\n className={theme.hiddenOption}\n disabled\n key=\"__reactUtilsHiddenOption\"\n value={value}\n >\n {value}\n </option>\n );\n\n let selectClassName = theme.select;\n if (!isValidValue) selectClassName += ` ${theme.invalid}`;\n\n return (\n <div className={theme.container}>\n { label === undefined\n ? null : <div className={theme.label}>{label}</div> }\n <div className={theme.dropdown}>\n <select\n className={selectClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onChange={onChange}\n value={value}\n >\n {hiddenOption}\n {optionElements}\n </select>\n <div className={theme.arrow} />\n </div>\n </div>\n );\n};\n\nexport default themed(Dropdown, 'Dropdown', defaultTheme);\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["themed","optionValueName","defaultTheme","jsx","_jsx","jsxs","_jsxs","Dropdown","filter","label","onChange","options","testId","theme","value","isValidValue","optionElements","option","iValue","iName","push","className","children","hiddenOption","disabled","selectClassName","select","invalid","container","undefined","dropdown","process","env","NODE_ENV","arrow"],"sources":["../../../../../../src/shared/components/selectors/NativeDropdown/index.tsx"],"sourcesContent":["// Implements dropdown based on the native HTML <select> element.\n\nimport themed from '@dr.pogodin/react-themes';\n\nimport { type PropsT, optionValueName } from '../common';\n\nimport defaultTheme from './theme.scss';\n\n/**\n * Implements a themeable dropdown list. Internally it is rendered with help of\n * the standard HTML `<select>` element, thus the styling support is somewhat\n * limited.\n * @param [props] Component properties.\n * @param [props.filter] Options filter function. If provided, only\n * those elements of `options` list will be used by the dropdown, for which this\n * filter returns `true`.\n * @param [props.label] Dropdown label.\n * @param [props.onChange] Selection event handler.\n * @param [props.options=[]] Array of dropdown\n * options. For string elements the option value and name will be the same.\n * It is allowed to mix DropdownOption and string elements in the same option\n * list.\n * @param [props.theme] _Ad hoc_ theme.\n * @param [props.value] Currently selected value.\n * @param [props....]\n * [Other theming properties](https://www.npmjs.com/package/@dr.pogodin/react-themes#themed-component-properties)\n */\nconst Dropdown: React.FunctionComponent<PropsT<string>> = ({\n filter,\n label,\n onChange,\n options,\n testId,\n theme,\n value,\n}) => {\n let isValidValue = false;\n const optionElements = [];\n\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n isValidValue ||= iValue === value;\n optionElements.push(\n <option className={theme.option} key={iValue} value={iValue}>\n {iName}\n </option>,\n );\n }\n }\n\n // NOTE: This element represents the current `value` when it does not match\n // any valid option. In Chrome, and some other browsers, we are able to hide\n // it from the opened dropdown; in others, e.g. Safari, the best we can do is\n // to show it as disabled.\n const hiddenOption = isValidValue ? null : (\n <option\n className={theme.hiddenOption}\n disabled\n key=\"__reactUtilsHiddenOption\"\n value={value}\n >\n {value}\n </option>\n );\n\n let selectClassName = theme.select;\n if (!isValidValue) selectClassName += ` ${theme.invalid}`;\n\n return (\n <div className={theme.container}>\n { label === undefined\n ? null : <div className={theme.label}>{label}</div> }\n <div className={theme.dropdown}>\n <select\n className={selectClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onChange={onChange}\n value={value}\n >\n {hiddenOption}\n {optionElements}\n </select>\n <div className={theme.arrow} />\n </div>\n </div>\n );\n};\n\nexport default /* #__PURE__ */ themed(Dropdown, 'Dropdown', defaultTheme);\n"],"mappings":"oRAAA;AAEA,MAAO,CAAAA,MAAM,KAAM,0BAA0B,QAEvBC,eAAe,0BAAAC,YAAA,gOAIrC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GAlBA,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAmBA,KAAM,CAAAC,QAAiD,CAAGA,CAAC,CACzDC,MAAM,CACNC,KAAK,CACLC,QAAQ,CACRC,OAAO,CACPC,MAAM,CACNC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,GAAI,CAAAC,YAAY,CAAG,KAAK,CACxB,KAAM,CAAAC,cAAc,CAAG,EAAE,CAEzB,IAAK,KAAM,CAAAC,MAAM,GAAI,CAA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AAK,CAACqB,KAAM,CAAE,CAAC,EAC5B,CAAC,EACH,CAET,CAAC,CAED,cAAe,eAAgBlC,MAAM,CAACO,QAAQ,CAAE,UAAU,CAAEL,YAAY,CAAC","ignoreList":[]}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import themed from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";const defaultTheme={"context":"akD3dQ","ad":"xcXtdE","hoc":"N3iziJ","container":"BYeWyJ","option":"_7MFXEN","selected":"CDbWAd","options":"_9-eOZo"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const BaseSwitch=({label,onChange,options,theme,value})=>{if(!options||!theme.option)throw Error("Internal error");const optionNodes=[];for(const option of options){const[iValue,iName]=optionValueName(option);let className=theme.option;let onPress;if(iValue===value)className+=` ${theme.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))}return/*#__PURE__*/_jsxs("div",{className:theme.container,children:[label?/*#__PURE__*/_jsx("div",{className:theme.label,children:label}):null,/*#__PURE__*/_jsx("div",{className:theme.options,children:optionNodes})]})};export default themed(BaseSwitch,"Switch",defaultTheme);
|
|
1
|
+
import"core-js/modules/es.array.push.js";import"core-js/modules/es.array.push.js";import themed from"@dr.pogodin/react-themes";import{optionValueName}from"../common.js";const defaultTheme={"context":"akD3dQ","ad":"xcXtdE","hoc":"N3iziJ","container":"BYeWyJ","option":"_7MFXEN","selected":"CDbWAd","options":"_9-eOZo"};import{jsx as _jsx,jsxs as _jsxs}from"react/jsx-runtime";const BaseSwitch=({label,onChange,options,theme,value})=>{if(!options||!theme.option)throw Error("Internal error");const optionNodes=[];for(const option of options){const[iValue,iName]=optionValueName(option);let className=theme.option;let onPress;if(iValue===value)className+=` ${theme.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))}return/*#__PURE__*/_jsxs("div",{className:theme.container,children:[label?/*#__PURE__*/_jsx("div",{className:theme.label,children:label}):null,/*#__PURE__*/_jsx("div",{className:theme.options,children:optionNodes})]})};export default/* #__PURE__ */themed(BaseSwitch,"Switch",defaultTheme);
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["themed","optionValueName","defaultTheme","jsx","_jsx","jsxs","_jsxs","BaseSwitch","label","onChange","options","theme","value","option","Error","optionNodes","iValue","iName","className","onPress","selected","push","onClick","onKeyDown","e","key","role","tabIndex","children","container"],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import themed, { type Theme } 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 ThemeKeyT = 'container' | 'label' | 'option' | 'options' | 'selected';\n\ntype PropsT = {\n label?: React.ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<React.ReactNode>>;\n theme: Theme<ThemeKeyT>;\n value?: ValueT;\n};\n\nconst BaseSwitch: React.FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options || !theme.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 = theme.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${theme.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={theme.container}>\n {label ? <div className={theme.label}>{label}</div> : null}\n\n <div className={theme.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n\nexport default themed(BaseSwitch, 'Switch', defaultTheme);\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":["themed","optionValueName","defaultTheme","jsx","_jsx","jsxs","_jsxs","BaseSwitch","label","onChange","options","theme","value","option","Error","optionNodes","iValue","iName","className","onPress","selected","push","onClick","onKeyDown","e","key","role","tabIndex","children","container"],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import themed, { type Theme } 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 ThemeKeyT = 'container' | 'label' | 'option' | 'options' | 'selected';\n\ntype PropsT = {\n label?: React.ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<React.ReactNode>>;\n theme: Theme<ThemeKeyT>;\n value?: ValueT;\n};\n\nconst BaseSwitch: React.FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n if (!options || !theme.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 = theme.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${theme.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={theme.container}>\n {label ? <div className={theme.label}>{label}</div> : null}\n\n <div className={theme.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n\nexport default /* #__PURE__ */ themed(BaseSwitch, 'Switch', defaultTheme);\n"],"mappings":"kFAAA,MAAO,CAAAA,MAAM,KAAsB,0BAA0B,QAK3DC,eAAe,0BAAAC,YAAA,mIAGuB,OAAAC,GAAA,IAAAC,IAAA,CAAAC,IAAA,IAAAC,KAAA,yBAYxC,KAAM,CAAAC,UAA2C,CAAGA,CAAC,CACnDC,KAAK,CACLC,QAAQ,CACRC,OAAO,CACPC,KAAK,CACLC,KACF,CAAC,GAAK,CACJ,GAAI,CAACF,OAAO,EAAI,CAACC,KAAK,CAACE,MAAM,CAAE,KAAM,CAAAC,KAAK,CAAC,gBAAgB,CAAC,CAE5D,KAAM,CAAAC,WAA8B,CAAG,EAAE,CACzC,IAAK,KAAM,CAAAF,MAAM,GAAI,CAAAH,OAAO,CAAE,CAC5B,KAAM,CAACM,MAAM,CAAEC,KAAK,CAAC,CAAGhB,eAAe,CAACY,MAAM,CAAC,CAE/C,GAAI,CAAAK,SAAiB,CAAGP,KAAK,CAACE,MAAM,CACpC,GAAI,CAAAM,OAAiC,CACrC,GAAIH,MAAM,GAAKJ,KAAK,CAAEM,SAAS,EAAI,IAAIP,KAAK,CAACS,QAAQ,EAAE,CAAC,IACnD,IAAIX,QAAQ,CAAE,CACjBU,OAAO,CAAGA,CAAA,GAAM,CACdV,QAAQ,CAACO,MAAM,CACjB,CACF,CAEAD,WAAW,CAACM,IAAI,CACdF,OAAO,cAEHf,IAAA,QACEc,SAAS,CAAEA,SAAU,CAErBI,OAAO,CAAEH,OAAQ,CACjBI,SAAS,CAAGC,CAAC,EAAK,CAChB,GAAIA,CAAC,CAACC,GAAG,GAAK,OAAO,CAAEN,OAAO,CAAC,CACjC,CAAE,CACFO,IAAI,CAAC,QAAQ,CACbC,QAAQ,CAAE,CAAE,CAAAC,QAAA,CAEXX,KAAK,EARDD,MASF,CAAC,cAENZ,IAAA,QAAKc,SAAS,CAAEA,SAAU,CAAAU,QAAA,CAAeX,KAAK,EAAdD,MAAoB,CAC1D,CACF,CAEA,mBACEV,KAAA,QAAKY,SAAS,CAAEP,KAAK,CAACkB,SAAU,CAAAD,QAAA,EAC7BpB,KAAK,cAAGJ,IAAA,QAAKc,SAAS,CAAEP,KAAK,CAACH,KAAM,CAAAoB,QAAA,CAAEpB,KAAK,CAAM,CAAC,CAAG,IAAI,cAE1DJ,IAAA,QAAKc,SAAS,CAAEP,KAAK,CAACD,OAAQ,CAAAkB,QAAA,CAC3Bb,WAAW,CACT,CAAC,EACH,CAET,CAAC,CAED,cAAe,eAAgBf,MAAM,CAACO,UAAU,CAAE,QAAQ,CAAEL,YAAY,CAAC","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";/**
|
|
2
2
|
* Jest environment for end-to-end SSR and client-side testing. It relies on
|
|
3
3
|
* the standard react-utils mechanics to execute SSR of given scene, and also
|
|
4
4
|
* Webpack build of the code for client-side execution, it further exposes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","ssrFactory","setBuildInfo","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","require","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","cache","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n if (!compiler) throw Error('Failed to construct Webpack compiler');\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AAC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CAAC,CACrC,IAAI,CAAC5B,MAAM,CAAC0E,6BAA6B,CAAG,IAC9C,CAEA,KAAM,CAAAC,QAAQA,CAAA,CAAkB,CAC9B,MAAO,KAAI,CAAC3E,MAAM,CAAC0E,6BAA6B,CAEhD;AACA;AACA;AACA;AACA;AACA;AACAE,MAAM,CAACC,IAAI,CAACzE,OAAO,CAACoE,KAAK,CAAC,CAACM,OAAO,CAAEC,GAAG,EAAK,CAC1C,MAAO,CAAA3E,OAAO,CAACoE,KAAK,CAACO,GAAG,CAC1B,CAAC,CAAC,CACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC,CACjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CACvB,CACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"E2eSsrEnv.js","names":["path","defaults","set","register","JsdomEnv","Volume","createFsFromVolume","webpack","ssrFactory","setBuildInfo","noop","E2eSsrEnv","loadWebpackConfig","optionsString","pragmas","options","JSON","parse","context","testFolder","fs","global","webpackOutputFs","factoryPath","factory","require","resolve","rootDir","default","webpackConfig","buildInfo","existsSync","readFileSync","runWebpack","Error","compiler","outputFileSystem","Promise","done","fail","run","err","stats","hasErrors","console","error","toJson","errors","webpackStats","runSsr","logger","debug","info","log","warn","cleanup","entry","p","module","exportName","entryExportName","Application","renderer","status","markup","ssrRequest","cookie","send","value","locals","devMiddleware","ssrMarkup","ssrOptions","ssrStatus","constructor","config","docblockPragmas","requestString","request","url","csrfToken","projectConfig","dom","dirname","testPath","withSsr","root","process","cwd","envName","babelEnv","extensions","setup","cache","undefined","REACT_UTILS_FORCE_CLIENT_SIDE","teardown","Object","keys","forEach","key","revert"],"sources":["../../../../../src/shared/utils/jest/E2eSsrEnv.ts"],"sourcesContent":["/**\n * Jest environment for end-to-end SSR and client-side testing. It relies on\n * the standard react-utils mechanics to execute SSR of given scene, and also\n * Webpack build of the code for client-side execution, it further exposes\n * Jsdom environment for the client-side testing of the outcomes.\n */\n\n// BEWARE: The module is not imported into the JU module / the main assembly of\n// the library, because doing so easily breaks stuff:\n// 1) This module depends on Node-specific modules, which would make JU\n// incompatible with JsDom if included into JU.\n// 2) If this module is weakly imported from somewhere else in the lib,\n// it seems to randomly break tests using it for a different reason,\n// probably some sort of a require-loop, or some issues with weak\n// require in that scenario.\n\n// TODO: We need to add correct typing for environment options.\n\nimport path from 'node:path';\n\nimport type { Request, Response } from 'express';\n\nimport { defaults, set } from 'lodash-es';\n\nimport type { ReactNode } from 'react';\n\n// As this environment is a part of the Jest testing utils,\n// we assume development dependencies are available when it is used.\n/* eslint-disable import/no-extraneous-dependencies */\nimport register from '@babel/register/experimental-worker';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration } from 'webpack';\n/* eslint-enable import/no-extraneous-dependencies */\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport ssrFactory from 'server/renderer';\n\nimport { setBuildInfo } from '../isomorphy/buildInfo';\n\nfunction noop() {\n // NOOP\n}\n\nexport default class E2eSsrEnv extends JsdomEnv {\n pragmas: Record<string, string | string[]>;\n\n ssrRequest: object;\n\n rootDir: string;\n\n testFolder: string;\n\n withSsr: boolean;\n\n webpackStats?: webpack.StatsCompilation;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private loadWebpackConfig() {\n const optionsString = this.pragmas['webpack-config-options'] as string;\n\n const options = (optionsString ? JSON.parse(optionsString) : {}) as\n webpack.Configuration;\n\n defaults(options, {\n context: this.testFolder,\n fs: this.global.webpackOutputFs,\n });\n\n const factoryPath = this.pragmas['webpack-config-factory'] as string;\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n let factory = require(path.resolve(this.rootDir, factoryPath)) as\n (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n let buildInfo = `${options.context}/.build-info`;\n if (fs.existsSync(buildInfo)) {\n buildInfo = fs.readFileSync(buildInfo, 'utf8') as string;\n this.global.buildInfo = JSON.parse(buildInfo);\n }\n }\n\n /**\n * Executes Webpack build.\n * @return {Promise}\n */\n async runWebpack(): Promise<void> {\n this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\n if (!compiler) throw Error('Failed to construct Webpack compiler');\n\n // TODO: The \"as typeof compiler.outputFileSystem\" piece below is\n // a workaround for the Webpack regression:\n // https://github.com/webpack/webpack/issues/18242\n compiler.outputFileSystem = this.global.webpackOutputFs as\n typeof compiler.outputFileSystem;\n\n return new Promise<void>((done, fail) => {\n compiler.run((err, stats) => {\n if (err) fail(err);\n if (stats?.hasErrors()) {\n // eslint-disable-next-line no-console\n console.error(stats.toJson().errors);\n fail(Error('Webpack compilation failed'));\n }\n\n this.global.webpackStats = stats?.toJson();\n\n // Keeps reference to the raw Webpack stats object, which should be\n // explicitly passed to the server-side renderer alongside the request,\n // so that it can to pick up asset paths for different named chunks.\n this.webpackStats = stats;\n\n done();\n });\n });\n }\n\n async runSsr(): Promise<void> {\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n // TODO: This is temporary to shortcut the logging added to SSR.\n options.logger ??= {\n debug: noop,\n info: noop,\n log: noop,\n warn: noop,\n };\n\n options.buildInfo ??= this.global.buildInfo;\n\n let cleanup: (() => void) | undefined;\n\n if (options.entry) {\n const p = path.resolve(this.testFolder, options.entry as string);\n // TODO: This sure can be replaced by a dynamic import().\n // eslint-disable-next-line import/no-dynamic-require, @typescript-eslint/no-require-imports\n const module = require(p) as NodeJS.Module;\n if ('cleanup' in module) cleanup = module.cleanup as () => void;\n\n const exportName = (options.entryExportName as string) || 'default';\n if (exportName in module) {\n options.Application = (\n module as unknown as Record<string, unknown>\n )[exportName] as ReactNode;\n }\n }\n\n const renderer = ssrFactory(this.global.webpackConfig!, options);\n let status = 200; // OK\n const markup = await new Promise<string>((done, fail) => {\n void renderer(\n this.ssrRequest as Request,\n\n // TODO: This will do for now, with the current implementation of\n // the renderer, but it will require a rework once the renderer is\n // updated to do streaming.\n ({\n cookie: noop,\n send: done,\n set: noop,\n status: (value: number) => {\n status = value;\n },\n\n // This is how up-to-date Webpack stats are passed to the server in\n // development mode, and we use this here always, instead of having\n // to pass some information via filesystem.\n locals: {\n webpack: {\n devMiddleware: {\n stats: this.webpackStats,\n },\n },\n },\n } as unknown) as Response,\n\n (error) => {\n // TODO: Strictly speaking, that error as Error casting is not all\n // correct, but it works, so no need to spend time on it right now.\n if (error) fail(error as Error);\n else done('');\n },\n );\n });\n\n this.global.ssrMarkup = markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = status;\n\n if (cleanup) cleanup();\n }\n\n constructor(\n config: JestEnvironmentConfig,\n context: EnvironmentContext,\n ) {\n const pragmas = context.docblockPragmas;\n\n const requestString = pragmas['ssr-request'] as string;\n const request = requestString\n ? JSON.parse(requestString) as Record<string, unknown>\n : {};\n\n request.url ??= '/';\n request.csrfToken = noop;\n\n // This ensures the initial JsDom URL matches the value we use for SSR.\n set(\n config.projectConfig,\n 'testEnvironmentOptions.url',\n `http://localhost${request.url as string}`,\n );\n\n super(config, context);\n\n this.global.dom = this.dom;\n this.global.webpackOutputFs = createFsFromVolume(new Volume());\n\n // Extracts necessary settings from config and context.\n const { projectConfig } = config;\n this.rootDir = projectConfig.rootDir;\n this.testFolder = path.dirname(context.testPath);\n this.withSsr = !pragmas['no-ssr'];\n this.ssrRequest = request;\n this.pragmas = pragmas;\n\n // The usual \"babel-jest\" transformation setup does not apply to\n // the environment code and imports from it, this workaround enables it.\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n let root;\n switch (options.root) {\n case 'TEST':\n root = this.testFolder;\n break;\n default: root = process.cwd();\n }\n register({\n envName: options.babelEnv as string,\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n root,\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // NOTE: It is possible that the Webpack run above, and the SSR run below\n // load different versions of the same module (CommonJS, and ES), and it may\n // cause very confusing problems (e.g. see:\n // https://github.com/birdofpreyru/react-utils/issues/413).\n // It seems we can't reset the cache of ES modules, and Jest's module reset\n // does not reset modules loaded in this enviroment module, and also only\n // replacing entire cache object by and empty {} seems to help (in contrast\n // to deleting all entries by their keys, as it is done within .teardown()\n // method below). Thus, for now we do this as a hotfix, and we also reset\n // build info to undefined, because ES module version not beeing reset\n // triggers an error on the subsequent test using the environment.\n // TODO: Look for a cleaner solution.\n require.cache = {};\n setBuildInfo(undefined, true);\n\n if (this.withSsr) await this.runSsr();\n this.global.REACT_UTILS_FORCE_CLIENT_SIDE = true;\n }\n\n async teardown(): Promise<void> {\n delete this.global.REACT_UTILS_FORCE_CLIENT_SIDE;\n\n // Resets module cache and @babel/register. Effectively this ensures that\n // the next time an instance of this environment is set up, all modules are\n // transformed by Babel from scratch, thus taking into account the latest\n // Babel config (which may change between different environment instances,\n // which does not seem to be taken into account by Babel / Node caches\n // automatically).\n Object.keys(require.cache).forEach((key) => {\n delete require.cache[key];\n });\n register.revert();\n await super.teardown();\n }\n}\n"],"mappings":"sMAAA;AACA;AACA;AACA;AACA;AACA,GAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAEA;AAEA,MAAO,CAAAA,IAAI,KAAM,WAAW,CAI5B,OAASC,QAAQ,CAAEC,GAAG,KAAQ,WAAW,CAIzC;AACA;AACA,sDACA,MAAO,CAAAC,QAAQ,KAAM,qCAAqC,CAE1D,MAAO,CAAAC,QAAQ,KAAM,wBAAwB,CAC7C,OAASC,MAAM,CAAEC,kBAAkB,KAAQ,OAAO,CAClD,MAAO,CAAAC,OAAO,KAA8B,SAAS,CACrD,2DAOO,CAAAC,UA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AG,CAC1B,CAAC,CAAC,CACFjG,QAAQ,CAACkG,MAAM,CAAC,CAAC,CACjB,KAAM,MAAK,CAACL,QAAQ,CAAC,CACvB,CACF","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
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"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{getSsrContext}from"./globalState.js";import{IS_CLIENT_SIDE,IS_SERVER_SIDE,getBuildInfo}from"./isomorphy/index.js";import{jsx as _jsx}from"react/jsx-runtime";function getClientChunkGroups(){if(!IS_CLIENT_SIDE)return undefined;return(async()=>{const{default:getInj}=await import(/* webpackChunkName: "react-utils-client-side-code" */"../../client/getInj");const inj=await getInj();return inj.CHUNK_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.
|
|
@@ -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","usedChunkNames","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.\nconst 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 // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\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":"AAAA,qBAEA,OAKEA,QAAQ,CACRC,IAAI,CACJC,kBAAkB,KACb,OAAO,CAEd,OAASC,OAAO,KAAQ,sBAAsB,QAElBC,aAAa,+BAGvCC,cAAc,CACdC,cAAc,CACdC,YAAY,4BACO,OAAAC,GAAA,IAAAC,IAAA,yBAErB,QAAS,CAAAC,oBAAoBA,CAAA,CAAsC,CACjE,GAAI,CAACL,cAAc,CAAE,MAAO,CAAAM,SAAS,CAErC,MAAO,CAAC,SAAY,CAClB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2B,MAAM,CAACC,QAAQ,CAAC7B,SAAS,CAAC,CAAE4B,MAAM,CAACnB,IAAI,CAACT,SAAS,CACxD,CAEA;AACA;AACA5C,kBAAkB,CAAC,IAAM,CACvB,GAAI,CAACiE,iBAAiB,CAAE,KAAM,CAAA9B,KAAK,CAAC,gBAAgB,CAAC,CACrD,IAAK,CAAAW,eAAe,CAACF,SAAS,CAAEqB,iBAAiB,CAAE,IAAI,CAAC,CACxD,MAAO,IAAM,CACXR,eAAe,CAACb,SAAS,CAAEqB,iBAAiB,CAC9C,CACF,CAAC,CAAE,EAAE,CAAC,CAEN,mBACE1D,IAAA,CAAC4D,SACC;AAAA,KACKI,IAAI,CACTD,GAAG,CAAEA,GAAI,CAAAD,QAAA,CAERA,QAAQ,CACA,CAEf,CAAC,CAED,MAAO,CAAE3D,OAAO,CAAE0D,OAAQ,CAC5B,CAAC,CAAC,CAEF,KAAM,CAAAM,SAAmD,CAAGA,CAAC,CAC3DL,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChBhE,IAAA,CAACT,QAAQ,EAAC6E,QAAQ,CAAEZ,WAAY,CAAAM,QAAA,cAC9B9D,IAAA,CAACyD,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAK,SACT","ignoreList":[]}
|
|
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","usedChunkNames","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.\nconst 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 // The correct usage of splitComponent() assumes a single call per chunk.\n if (usedChunkNames.has(chunkName)) {\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":"83BAAA,qBAEA,OAKEA,QAAQ,CACRC,IAAI,CACJC,kBAAkB,KACb,OAAO,CAEd,OAASC,OAAO,KAAQ,sBAAsB,QAElBC,aAAa,+BAGvCC,cAAc,CACdC,cAAc,CACdC,YAAY,4BACO,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,CAC9B,CAAC,EAAE,CACL,CAEA,KAAM,CAAAC,SAAiC,CAAG,CAAC,CAAC,CAE5C,QAAS,CAAAC,aAAaA,CAAA,CAAG,CACvB,MAAO,CAA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CAAEqB,iBAAiB,CAC9C,CACF,CAAC,CAAE,EAAE,CAAC,CAEN,mBACE1D,IAAA,CAAC4D,SACC;AAAA,KACKI,IAAI,CACTD,GAAG,CAAEA,GAAI,CAAAD,QAAA,CAERA,QAAQ,CACA,CAEf,CAAC,CAED,MAAO,CAAE3D,OAAO,CAAE0D,OAAQ,CAC5B,CAAC,CAAC,CAEF,KAAM,CAAAM,SAAmD,CAAGA,CAAC,CAC3DL,QAAQ,CACR,GAAGE,IACY,CAAC,gBAChBhE,IAAA,CAACT,QAAQ,EAAC6E,QAAQ,CAAEZ,WAAY,CAAAM,QAAA,cAC9B9D,IAAA,CAACyD,aACC;AAAA,KACIO,IAAI,CAAAF,QAAA,CAEPA,QAAQ,CACI,CAAC,CACR,CACX,CAED,MAAO,CAAAK,SACT","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";import"core-js/modules/es.iterator.constructor.js";import"core-js/modules/es.iterator.for-each.js";// eslint-disable-next-line import/enforce-node-protocol-usage
|
|
2
2
|
import{createRequire}from"module";import{IS_CLIENT_SIDE,IS_SERVER_SIDE}from"./isomorphy/index.js";let require;if(IS_SERVER_SIDE)require=createRequire(import.meta.url);/**
|
|
3
3
|
* Requires the specified module without including it into the bundle during
|
|
4
4
|
* Webpack build.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"webpack.js","names":["createRequire","IS_CLIENT_SIDE","IS_SERVER_SIDE","require","import","meta","url","requireWeak","modulePath","basePathOrOptions","basePath","ops","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","undefined","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: string | RequireWeakOptionsT,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require!('node:path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n\n const module = require!(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned === undefined) {\n (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n } else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"webpack.js","names":["createRequire","IS_CLIENT_SIDE","IS_SERVER_SIDE","require","import","meta","url","requireWeak","modulePath","basePathOrOptions","basePath","ops","resolve","path","module","default","def","named","res","Object","entries","forEach","name","value","assigned","undefined","Error","resolveWeak"],"sources":["../../../../src/shared/utils/webpack.ts"],"sourcesContent":["import type PathNS from 'node:path';\n\n// eslint-disable-next-line import/enforce-node-protocol-usage\nimport { createRequire } from 'module';\n\nimport { IS_CLIENT_SIDE, IS_SERVER_SIDE } from './isomorphy';\n\ntype RequireWeakOptionsT = {\n basePath?: string;\n};\n\ntype RequireWeakResT<T> = T extends { default: infer D }\n ? (D extends null | undefined ? T : D & Omit<T, 'default'>)\n : T;\n\nlet require: ((url: string) => unknown) | undefined;\n\nif (IS_SERVER_SIDE) require = createRequire(import.meta.url);\n\n/**\n * Requires the specified module without including it into the bundle during\n * Webpack build.\n * @param modulePath\n * @param [basePath]\n * @return Required module.\n */\nexport function requireWeak<T extends object>(\n modulePath: string,\n\n // TODO: For now `basePath` can be provided directly as a string here,\n // for backward compatibility. Deprecate it in future, if any other\n // breaking changes are done for requireWeak().\n basePathOrOptions?: string | RequireWeakOptionsT,\n): RequireWeakResT<T> | null {\n if (IS_CLIENT_SIDE) return null;\n\n let basePath: string | undefined;\n let ops: RequireWeakOptionsT;\n if (typeof basePathOrOptions === 'string') {\n basePath = basePathOrOptions;\n } else {\n ops = basePathOrOptions ?? {};\n ({ basePath } = ops);\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n const { resolve } = require!('node:path') as typeof PathNS;\n\n const path = basePath ? resolve(basePath, modulePath) : modulePath;\n\n const module = require!(path) as T;\n\n if (!('default' in module) || !module.default) return module as RequireWeakResT<T>;\n\n const { default: def, ...named } = module;\n\n const res = def as RequireWeakResT<T>;\n\n Object.entries(named).forEach(([name, value]) => {\n const assigned = res[name as keyof RequireWeakResT<T>];\n if (assigned === undefined) {\n (res[name as keyof RequireWeakResT<T>] as unknown) = value;\n } else if (assigned !== value) {\n throw Error('Conflict between default and named exports');\n }\n });\n return res;\n}\n\n/**\n * Resolves specified module path with help of Babel's module resolver.\n * Yes, the function itself just returns its argument to the caller, but Babel\n * is configured to resolve the first argument of resolveWeak(..) function, thus\n * the result will be the resolved path.\n * @param {string} modulePath\n * @return {string} Absolute or relative path to the module.\n */\nexport function resolveWeak(modulePath: string): string {\n return modulePath;\n}\n"],"mappings":"sMAEA;AACA,OAASA,aAAa,KAAQ,QAAQ,QAE7BC,cAAc,CAAEC,cAAc,4BAUvC,GAAI,CAAAC,OAA+C,CAEnD,GAAID,cAAc,CAAEC,OAAO,CAAGH,aAAa,CAACI,MAAM,CAACC,IAAI,CAACC,GAAG,CAAC,CAE5D;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAC,WAAWA,CACzBC,UAAkB,CAElB;AACA;AACA;AACAC,iBAAgD,CACrB,CAC3B,GAAIR,cAAc,CAAE,MAAO,KAAI,CAE/B,GAAI,CAAAS,QAA4B,CAChC,GAAI,CAAAC,GAAwB,CAC5B,GAAI,MAAO,CAAAF,iBAAiB,GAAK,QAAQ,CAAE,CACzCC,QAAQ,CAAGD,iBACb,CAAC,IAAM,CACLE,GAAG,CAAGF,iBAAiB,EAAI,CAAC,CAAC,CAC7B,CAAC,CAAEC,QAAS,CAAC,CAAGC,GAAG,CACrB,CAEA;AACA,KAAM,CAAEC,OAAQ,CAAC,CAAGT,OAAO,CAAE,WAAW,CAAkB,CAE1D,KAAM,CAAAU,IAAI,CAAGH,QAAQ,CAAGE,OAAO,CAACF,QAAQ,CAAEF,UAAU,CAAC,CAAGA,UAAU,CAElE,KAAM,CAAAM,MAAM,CAAGX,OAAO,CAAEU,IAAI,CAAM,CAElC,GAAI,EAAE,SAAS,EAAI,CAAAC,MAAM,CAAC,EAAI,CAACA,MAAM,CAACC,OAAO,CAAE,MAAO,CAAAD,MAAM,CAE5D,KAAM,CAAEC,OAAO,CAAEC,GAAG,CAAE,GAAGC,KAAM,CAAC,CAAGH,MAAM,CAEzC,KAAM,CAAAI,GAAG,CAAGF,GAAyB,CAErCG,MAAM,CAACC,OAAO,CAACH,KAAK,CAAC,CAACI,OAAO,CAAC,CAAC,CAACC,IAAI,CAAEC,KAAK,CAAC,GAAK,CAC/C,KAAM,CAAAC,QAAQ,CAAGN,GAAG,CAACI,IAAI,CAA6B,CACtD,GAAIE,QAAQ,GAAKC,SAAS,CAAE,CACzBP,GAAG,CAACI,IAAI,CAA6B,CAAeC,KACvD,CAAC,IAAM,IAAIC,QAAQ,GAAKD,KAAK,CAAE,CAC7B,KAAM,CAAAG,KAAK,CAAC,4CAA4C,CAC1D,CACF,CAAC,CAAC,CACF,MAAO,CAAAR,GACT,CAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,GACA,MAAO,SAAS,CAAAS,WAAWA,CAACnB,UAAkB,CAAU,CACtD,MAAO,CAAAA,UACT","ignoreList":[]}
|
|
@@ -8,5 +8,5 @@ type OptionsT = {
|
|
|
8
8
|
* @param Application Root application component
|
|
9
9
|
* @param [options={}] Optional. Additional settings.
|
|
10
10
|
*/
|
|
11
|
-
export
|
|
11
|
+
export declare function launchClient(Application: ComponentType, options?: OptionsT): Promise<void>;
|
|
12
12
|
export {};
|
|
@@ -1,10 +1,5 @@
|
|
|
1
1
|
import 'styles/global.scss';
|
|
2
|
-
import clientModule from './client';
|
|
3
|
-
import type * as ServerFactoryM from './server';
|
|
4
|
-
declare const server: (typeof ServerFactoryM.default & Omit<typeof ServerFactoryM, "default">) | null;
|
|
5
|
-
declare const client: typeof clientModule | undefined;
|
|
6
2
|
export { type AsyncCollectionT, type AsyncCollectionLoaderT, type AsyncDataEnvelopeT, type AsyncDataLoaderT, type ForceT, type UseAsyncDataOptionsT, type UseAsyncDataResT, type UseGlobalStateResT, type ValueOrInitializerT, getGlobalState, GlobalStateProvider, newAsyncDataEnvelope, useAsyncCollection, useAsyncData, useGlobalState, withGlobalStateType, } from '@dr.pogodin/react-global-state';
|
|
7
3
|
export * from './shared/components';
|
|
8
4
|
export { type BeforeRenderResT, type BeforeRenderT, type ConfigT, type ServerSsrContext, type ServerT, } from './server';
|
|
9
5
|
export { assertEmptyObject, Barrier, Cached, Emitter, getConfig, isomorphy, getSsrContext, type Listener, type ObjectKey, Semaphore, splitComponent, type Theme, themed, ThemeProvider, time, webpack, withRetries, } from './shared/utils';
|
|
10
|
-
export { client, server };
|