@dr.pogodin/react-utils 1.57.1 → 1.58.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/development/client/getInj.js +17 -2
- package/build/development/client/getInj.js.map +1 -1
- package/build/development/server/Cache.js +42 -10
- package/build/development/server/Cache.js.map +1 -1
- package/build/development/server/index.js +6 -3
- package/build/development/server/index.js.map +1 -1
- package/build/development/server/renderer.js +67 -10
- package/build/development/server/renderer.js.map +1 -1
- package/build/development/server/server.js +17 -9
- package/build/development/server/server.js.map +1 -1
- package/build/development/server/utils/errors.js +11 -11
- package/build/development/server/utils/errors.js.map +1 -1
- package/build/development/server/utils/modules.js +35 -1
- package/build/development/server/utils/modules.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 +5 -5
- package/build/development/shared/components/Checkbox/index.js.map +1 -1
- package/build/development/shared/components/Input/index.js +3 -3
- package/build/development/shared/components/Input/index.js.map +1 -1
- package/build/development/shared/components/Modal/index.js +3 -0
- package/build/development/shared/components/Modal/index.js.map +1 -1
- package/build/development/shared/components/TextArea/index.js +3 -3
- package/build/development/shared/components/TextArea/index.js.map +1 -1
- package/build/development/shared/components/WithTooltip/Tooltip.js +2 -2
- package/build/development/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/development/shared/components/WithTooltip/index.js +3 -1
- package/build/development/shared/components/WithTooltip/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js +8 -2
- package/build/development/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/development/shared/components/selectors/CustomDropdown/index.js +10 -4
- package/build/development/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/NativeDropdown/index.js +7 -4
- package/build/development/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/development/shared/components/selectors/Switch/index.js +3 -3
- package/build/development/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/development/shared/utils/config.js.map +1 -1
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js +11 -10
- package/build/development/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/development/shared/utils/jest/index.js +4 -3
- package/build/development/shared/utils/jest/index.js.map +1 -1
- package/build/development/shared/utils/splitComponent.js +86 -10
- package/build/development/shared/utils/splitComponent.js.map +1 -1
- package/build/development/shared/utils/webpack.js +5 -2
- 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/server/Cache.js +4 -4
- package/build/production/server/Cache.js.map +1 -1
- package/build/production/server/index.js +1 -1
- package/build/production/server/index.js.map +1 -1
- package/build/production/server/renderer.js +12 -12
- package/build/production/server/renderer.js.map +1 -1
- package/build/production/server/server.js +7 -7
- package/build/production/server/server.js.map +1 -1
- package/build/production/server/utils/errors.js +2 -2
- package/build/production/server/utils/errors.js.map +1 -1
- package/build/production/server/utils/modules.js +1 -1
- package/build/production/server/utils/modules.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/TextArea/index.js +1 -1
- package/build/production/shared/components/TextArea/index.js.map +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js +1 -1
- package/build/production/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/production/shared/components/WithTooltip/index.js +2 -2
- package/build/production/shared/components/WithTooltip/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 +1 -1
- package/build/production/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/production/shared/components/selectors/NativeDropdown/index.js +3 -3
- 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/config.js.map +1 -1
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js +3 -3
- package/build/production/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/production/shared/utils/jest/index.js +4 -4
- package/build/production/shared/utils/jest/index.js.map +1 -1
- package/build/production/shared/utils/splitComponent.js +5 -5
- package/build/production/shared/utils/splitComponent.js.map +1 -1
- package/build/production/shared/utils/webpack.js +4 -3
- package/build/production/shared/utils/webpack.js.map +1 -1
- package/build/types-code/shared/utils/config.d.ts +1 -1
- package/build/web/client/getInj.js +1 -1
- package/build/web/client/getInj.js.map +1 -1
- package/build/web/server/Cache.js +4 -4
- package/build/web/server/Cache.js.map +1 -1
- package/build/web/server/index.js +1 -1
- package/build/web/server/index.js.map +1 -1
- package/build/web/server/renderer.js +12 -12
- package/build/web/server/renderer.js.map +1 -1
- package/build/web/server/server.js +7 -7
- package/build/web/server/server.js.map +1 -1
- package/build/web/server/utils/errors.js +2 -2
- package/build/web/server/utils/errors.js.map +1 -1
- package/build/web/server/utils/modules.js +1 -1
- package/build/web/server/utils/modules.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/TextArea/index.js +1 -1
- package/build/web/shared/components/TextArea/index.js.map +1 -1
- package/build/web/shared/components/WithTooltip/Tooltip.js +1 -1
- package/build/web/shared/components/WithTooltip/Tooltip.js.map +1 -1
- package/build/web/shared/components/WithTooltip/index.js +2 -2
- package/build/web/shared/components/WithTooltip/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/Options/index.js.map +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js +1 -1
- package/build/web/shared/components/selectors/CustomDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/NativeDropdown/index.js +3 -3
- package/build/web/shared/components/selectors/NativeDropdown/index.js.map +1 -1
- package/build/web/shared/components/selectors/Switch/index.js +1 -1
- package/build/web/shared/components/selectors/Switch/index.js.map +1 -1
- package/build/web/shared/utils/config.js.map +1 -1
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js +3 -3
- package/build/web/shared/utils/jest/E2eSsrEnv/index.js.map +1 -1
- package/build/web/shared/utils/jest/index.js +4 -4
- package/build/web/shared/utils/jest/index.js.map +1 -1
- package/build/web/shared/utils/splitComponent.js +5 -5
- package/build/web/shared/utils/splitComponent.js.map +1 -1
- package/build/web/shared/utils/webpack.js +4 -3
- package/build/web/shared/utils/webpack.js.map +1 -1
- package/config/babel/webpack.js +15 -1
- package/package.json +21 -21
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Tooltip.js","names":[],"sources":["../../../../../src/shared/components/WithTooltip/Tooltip.tsx"],"sourcesContent":["/**\n * The actual tooltip component. It is rendered outside the regular document\n * hierarchy, and with sub-components managed without React to achieve the best\n * performance during animation.\n */\n\nimport {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useImperativeHandle,\n useRef,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\n/**\n * Valid placements of the rendered tooltip. They will be overriden when\n * necessary to fit the tooltip within the viewport.\n */\nexport enum PLACEMENTS {\n ABOVE_CURSOR = 'ABOVE_CURSOR',\n ABOVE_ELEMENT = 'ABOVE_ELEMENT',\n BELOW_CURSOR = 'BELOW_CURSOR',\n BELOW_ELEMENT = 'BELOW_ELEMENT',\n}\n\nconst ARROW_STYLE_DOWN = [\n 'border-bottom-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\nconst ARROW_STYLE_UP = [\n 'border-top-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\ntype ComponentsT = {\n arrow: HTMLDivElement;\n container: HTMLDivElement;\n content: HTMLDivElement;\n};\n\nexport type ThemeKeysT = 'appearance' | 'arrow' | 'container' | 'content';\n\ntype TooltipThemeT = Theme<ThemeKeysT>;\n\ntype TooltipRectsT = {\n arrow: DOMRect;\n container: DOMRect;\n};\n\n/**\n * Generates bounding client rectangles for tooltip components.\n * @ignore\n * @param tooltip DOM references to the tooltip components.\n * @param tooltip.arrow\n * @param tooltip.container\n * @return Object holding tooltip rectangles in\n * two fields.\n */\nfunction calcTooltipRects(tooltip: ComponentsT): TooltipRectsT {\n return {\n arrow: tooltip.arrow.getBoundingClientRect(),\n container: tooltip.container.getBoundingClientRect(),\n };\n}\n\n/**\n * Calculates the document viewport size.\n * @ignore\n * @return {{x, y, width, height}}\n */\nfunction calcViewportRect() {\n const { scrollX, scrollY } = window;\n const { documentElement: { clientHeight, clientWidth } } = document;\n return {\n bottom: scrollY + clientHeight,\n left: scrollX,\n right: scrollX + clientWidth,\n top: scrollY,\n };\n}\n\n/**\n * Calculates tooltip and arrow positions for the placement just above\n * the cursor.\n * @ignore\n * @param {number} x Cursor page-x position.\n * @param {number} y Cursor page-y position.\n * @param {object} tooltipRects Bounding client rectangles of tooltip parts.\n * @param {object} tooltipRects.arrow\n * @param {object} tooltipRects.container\n * @return {object} Contains the following fields:\n * - {number} arrowX\n * - {number} arrowY\n * - {number} containerX\n * - {number} containerY\n * - {string} baseArrowStyle\n */\nfunction calcPositionAboveXY(\n x: number,\n y: number,\n tooltipRects: TooltipRectsT,\n) {\n const { arrow, container } = tooltipRects;\n return {\n arrowX: 0.5 * (container.width - arrow.width),\n arrowY: container.height,\n containerX: x - container.width / 2,\n containerY: y - container.height - arrow.height / 1.5,\n\n // TODO: Instead of already setting the base style here, we should\n // introduce a set of constants for arrow directions, which will help\n // to do checks dependant on the arrow direction.\n baseArrowStyle: ARROW_STYLE_DOWN,\n };\n}\n\n// const HIT = {\n// NONE: false,\n// LEFT: 'LEFT',\n// RIGHT: 'RIGHT',\n// TOP: 'TOP',\n// BOTTOM: 'BOTTOM',\n// };\n\n/**\n * Checks whether\n * @param {object} pos\n * @param {object} tooltipRects\n * @param {object} viewportRect\n * @return {HIT}\n */\n// function checkViewportFit(pos, tooltipRects, viewportRect) {\n// const { containerX, containerY } = pos;\n// if (containerX < viewportRect.left + 6) return HIT.LEFT;\n// if (containerX > viewportRect.right - 6) return HIT.RIGHT;\n// return HIT.NONE;\n// }\n\n/**\n * Shifts tooltip horizontally to fit into the viewport, while keeping\n * the arrow pointed to the XY point.\n * @param {number} x\n * @param {number} y\n * @param {object} pos\n * @param {number} pageXOffset\n * @param {number} pageXWidth\n */\n// function xPageFitCorrection(x, y, pos, pageXOffset, pageXWidth) {\n// if (pos.containerX < pageXOffset + 6) {\n// pos.containerX = pageXOffset + 6;\n// pos.arrowX = Math.max(6, pageX - containerX - arrowRect.width / 2);\n// } else {\n// const maxX = pageXOffset + docRect.width - containerRect.width - 6;\n// if (containerX > maxX) {\n// containerX = maxX;\n// arrowX = Math.min(\n// containerRect.width - 6,\n// pageX - containerX - arrowRect.width / 2,\n// );\n// }\n// }\n// }\n\n/**\n * Sets positions of tooltip components to point the tooltip to the specified\n * page point.\n * @ignore\n * @param pageX\n * @param pageY\n * @param placement\n * @param element DOM reference to the element wrapped by the tooltip.\n * @param tooltip\n * @param tooltip.arrow DOM reference to the tooltip arrow.\n * @param tooltip.container DOM reference to the tooltip container.\n */\nfunction setComponentPositions(\n pageX: number,\n pageY: number,\n placement: PLACEMENTS | undefined,\n element: HTMLElement | undefined,\n tooltip: ComponentsT,\n) {\n const tooltipRects = calcTooltipRects(tooltip);\n const viewportRect = calcViewportRect();\n\n /* Default container coords: tooltip at the top. */\n const pos = calcPositionAboveXY(pageX, pageY, tooltipRects);\n\n if (pos.containerX < viewportRect.left + 6) {\n pos.containerX = viewportRect.left + 6;\n pos.arrowX = Math.max(\n 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n } else {\n const maxX = viewportRect.right - 6 - tooltipRects.container.width;\n if (pos.containerX > maxX) {\n pos.containerX = maxX;\n pos.arrowX = Math.min(\n tooltipRects.container.width - 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n }\n }\n\n /* If tooltip has not enough space on top - make it bottom tooltip. */\n if (pos.containerY < viewportRect.top + 6) {\n pos.containerY += tooltipRects.container.height\n + 2 * tooltipRects.arrow.height;\n pos.arrowY -= tooltipRects.container.height\n + tooltipRects.arrow.height;\n pos.baseArrowStyle = ARROW_STYLE_UP;\n }\n\n const containerStyle = `left:${pos.containerX}px;top:${pos.containerY}px`;\n tooltip.container.setAttribute('style', containerStyle);\n\n const arrowStyle = `${pos.baseArrowStyle};left:${pos.arrowX}px;top:${pos.arrowY}px`;\n tooltip.arrow.setAttribute('style', arrowStyle);\n}\n\n/* The Tooltip component itself. */\nconst Tooltip: FunctionComponent<{\n children?: ReactNode;\n ref?: RefObject<unknown>;\n theme: TooltipThemeT;\n}> = ({ children, ref, theme }) => {\n // NOTE: The way it has to be implemented, for clean mounting and unmounting\n // at the client side, the <Tooltip> is fully mounted into DOM in the next\n // rendering cycles, and only then it can be correctly measured and positioned.\n // Thus, when we create the <Tooltip> we have to record its target positioning\n // details, and then apply them when it is created.\n\n const arrowRef = useRef<HTMLDivElement>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n const contentRef = useRef<HTMLDivElement>(null);\n\n const pointTo = (\n pageX: number,\n pageY: number,\n placement: PLACEMENTS,\n element: HTMLElement,\n ) => {\n if (!arrowRef.current || !containerRef.current || !contentRef.current) {\n throw Error('Internal error');\n }\n\n setComponentPositions(pageX, pageY, placement, element, {\n arrow: arrowRef.current,\n container: containerRef.current,\n content: contentRef.current,\n });\n };\n useImperativeHandle(ref, () => ({ pointTo }));\n\n return createPortal(\n (\n <div className={theme.container} ref={containerRef}>\n <div className={theme.arrow} ref={arrowRef} />\n <div className={theme.content} ref={contentRef}>{children}</div>\n </div>\n ),\n document.body,\n );\n};\n\nexport default Tooltip;\n"],"mappings":"iDAAA;AACA;AACA;AACA;AACA;AAEA,SAIE,mBAAmB,EACnB,MAAM,QACD,OAAO;AAEd,SAAS,YAAY,QAAQ,WAAW;AAAC,+DAIzC;AACA;AACA;AACA;AACA,WAAY,UAAU,0BAAV,UAAU;EAAV,UAAU;EAAV,UAAU;EAAV,UAAU;EAAV,UAAU;EAAA,OAAV,UAAU;AAAA;AAOtB,MAAM,gBAAgB,GAAG,CACvB,iCAAiC,EACjC,+BAA+B,EAC/B,gCAAgC,CACjC,CAAC,IAAI,CAAC,GAAG,CAAC;AAEX,MAAM,cAAc,GAAG,CACrB,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,CACjC,CAAC,IAAI,CAAC,GAAG,CAAC,CAiBX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,gBAAgB,CAAC,OAAoB,EAAiB;EAC7D,OAAO;IACL,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAC5C,SAAS,EAAE,OAAO,CAAC,SAAS,CAAC,qBAAqB,CAAC;EACrD,CAAC;AACH,CAEA;AACA;AACA;AACA;AACA;AACA,SAAS,gBAAgB,GAAG;EAC1B,MAAM;IAAE,OAAO;IAAE;EAAQ,CAAC,GAAG,MAAM;EACnC,MAAM;IAAE,eAAe,EAAE;MAAE,YAAY;MAAE;IAAY;EAAE,CAAC,GAAG,QAAQ;EACnE,OAAO;IACL,MAAM,EAAE,OA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|
|
1
|
+
{"version":3,"file":"Tooltip.js","names":[],"sources":["../../../../../src/shared/components/WithTooltip/Tooltip.tsx"],"sourcesContent":["/**\n * The actual tooltip component. It is rendered outside the regular document\n * hierarchy, and with sub-components managed without React to achieve the best\n * performance during animation.\n */\n\nimport {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useImperativeHandle,\n useRef,\n} from 'react';\n\nimport { createPortal } from 'react-dom';\n\nimport type { Theme } from '@dr.pogodin/react-themes';\n\n/**\n * Valid placements of the rendered tooltip. They will be overriden when\n * necessary to fit the tooltip within the viewport.\n */\nexport enum PLACEMENTS {\n ABOVE_CURSOR = 'ABOVE_CURSOR',\n ABOVE_ELEMENT = 'ABOVE_ELEMENT',\n BELOW_CURSOR = 'BELOW_CURSOR',\n BELOW_ELEMENT = 'BELOW_ELEMENT',\n}\n\nconst ARROW_STYLE_DOWN = [\n 'border-bottom-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\nconst ARROW_STYLE_UP = [\n 'border-top-color:transparent',\n 'border-left-color:transparent',\n 'border-right-color:transparent',\n].join(';');\n\ntype ComponentsT = {\n arrow: HTMLDivElement;\n container: HTMLDivElement;\n content: HTMLDivElement;\n};\n\nexport type ThemeKeysT = 'appearance' | 'arrow' | 'container' | 'content';\n\ntype TooltipThemeT = Theme<ThemeKeysT>;\n\ntype TooltipRectsT = {\n arrow: DOMRect;\n container: DOMRect;\n};\n\n/**\n * Generates bounding client rectangles for tooltip components.\n * @ignore\n * @param tooltip DOM references to the tooltip components.\n * @param tooltip.arrow\n * @param tooltip.container\n * @return Object holding tooltip rectangles in\n * two fields.\n */\nfunction calcTooltipRects(tooltip: ComponentsT): TooltipRectsT {\n return {\n arrow: tooltip.arrow.getBoundingClientRect(),\n container: tooltip.container.getBoundingClientRect(),\n };\n}\n\n/**\n * Calculates the document viewport size.\n * @ignore\n * @return {{x, y, width, height}}\n */\nfunction calcViewportRect() {\n const { scrollX, scrollY } = window;\n const { documentElement: { clientHeight, clientWidth } } = document;\n return {\n bottom: scrollY + clientHeight,\n left: scrollX,\n right: scrollX + clientWidth,\n top: scrollY,\n };\n}\n\n/**\n * Calculates tooltip and arrow positions for the placement just above\n * the cursor.\n * @ignore\n * @param {number} x Cursor page-x position.\n * @param {number} y Cursor page-y position.\n * @param {object} tooltipRects Bounding client rectangles of tooltip parts.\n * @param {object} tooltipRects.arrow\n * @param {object} tooltipRects.container\n * @return {object} Contains the following fields:\n * - {number} arrowX\n * - {number} arrowY\n * - {number} containerX\n * - {number} containerY\n * - {string} baseArrowStyle\n */\nfunction calcPositionAboveXY(\n x: number,\n y: number,\n tooltipRects: TooltipRectsT,\n) {\n const { arrow, container } = tooltipRects;\n return {\n arrowX: 0.5 * (container.width - arrow.width),\n arrowY: container.height,\n containerX: x - container.width / 2,\n containerY: y - container.height - arrow.height / 1.5,\n\n // TODO: Instead of already setting the base style here, we should\n // introduce a set of constants for arrow directions, which will help\n // to do checks dependant on the arrow direction.\n baseArrowStyle: ARROW_STYLE_DOWN,\n };\n}\n\n// const HIT = {\n// NONE: false,\n// LEFT: 'LEFT',\n// RIGHT: 'RIGHT',\n// TOP: 'TOP',\n// BOTTOM: 'BOTTOM',\n// };\n\n/**\n * Checks whether\n * @param {object} pos\n * @param {object} tooltipRects\n * @param {object} viewportRect\n * @return {HIT}\n */\n// function checkViewportFit(pos, tooltipRects, viewportRect) {\n// const { containerX, containerY } = pos;\n// if (containerX < viewportRect.left + 6) return HIT.LEFT;\n// if (containerX > viewportRect.right - 6) return HIT.RIGHT;\n// return HIT.NONE;\n// }\n\n/**\n * Shifts tooltip horizontally to fit into the viewport, while keeping\n * the arrow pointed to the XY point.\n * @param {number} x\n * @param {number} y\n * @param {object} pos\n * @param {number} pageXOffset\n * @param {number} pageXWidth\n */\n// function xPageFitCorrection(x, y, pos, pageXOffset, pageXWidth) {\n// if (pos.containerX < pageXOffset + 6) {\n// pos.containerX = pageXOffset + 6;\n// pos.arrowX = Math.max(6, pageX - containerX - arrowRect.width / 2);\n// } else {\n// const maxX = pageXOffset + docRect.width - containerRect.width - 6;\n// if (containerX > maxX) {\n// containerX = maxX;\n// arrowX = Math.min(\n// containerRect.width - 6,\n// pageX - containerX - arrowRect.width / 2,\n// );\n// }\n// }\n// }\n\n/**\n * Sets positions of tooltip components to point the tooltip to the specified\n * page point.\n * @ignore\n * @param pageX\n * @param pageY\n * @param placement\n * @param element DOM reference to the element wrapped by the tooltip.\n * @param tooltip\n * @param tooltip.arrow DOM reference to the tooltip arrow.\n * @param tooltip.container DOM reference to the tooltip container.\n */\nfunction setComponentPositions(\n pageX: number,\n pageY: number,\n placement: PLACEMENTS | undefined,\n element: HTMLElement | undefined,\n tooltip: ComponentsT,\n) {\n const tooltipRects = calcTooltipRects(tooltip);\n const viewportRect = calcViewportRect();\n\n /* Default container coords: tooltip at the top. */\n const pos = calcPositionAboveXY(pageX, pageY, tooltipRects);\n\n if (pos.containerX < viewportRect.left + 6) {\n pos.containerX = viewportRect.left + 6;\n pos.arrowX = Math.max(\n 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n } else {\n const maxX = viewportRect.right - 6 - tooltipRects.container.width;\n if (pos.containerX > maxX) {\n pos.containerX = maxX;\n pos.arrowX = Math.min(\n tooltipRects.container.width - 6,\n pageX - pos.containerX - tooltipRects.arrow.width / 2,\n );\n }\n }\n\n /* If tooltip has not enough space on top - make it bottom tooltip. */\n if (pos.containerY < viewportRect.top + 6) {\n pos.containerY += tooltipRects.container.height\n + 2 * tooltipRects.arrow.height;\n pos.arrowY -= tooltipRects.container.height\n + tooltipRects.arrow.height;\n pos.baseArrowStyle = ARROW_STYLE_UP;\n }\n\n const containerStyle = `left:${pos.containerX.toString()}px;top:${pos.containerY.toString()}px`;\n tooltip.container.setAttribute('style', containerStyle);\n\n const arrowStyle = `${pos.baseArrowStyle};left:${pos.arrowX.toString()}px;top:${pos.arrowY.toString()}px`;\n tooltip.arrow.setAttribute('style', arrowStyle);\n}\n\n/* The Tooltip component itself. */\nconst Tooltip: FunctionComponent<{\n children?: ReactNode;\n ref?: RefObject<unknown>;\n theme: TooltipThemeT;\n}> = ({ children, ref, theme }) => {\n // NOTE: The way it has to be implemented, for clean mounting and unmounting\n // at the client side, the <Tooltip> is fully mounted into DOM in the next\n // rendering cycles, and only then it can be correctly measured and positioned.\n // Thus, when we create the <Tooltip> we have to record its target positioning\n // details, and then apply them when it is created.\n\n const arrowRef = useRef<HTMLDivElement>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n const contentRef = useRef<HTMLDivElement>(null);\n\n const pointTo = (\n pageX: number,\n pageY: number,\n placement: PLACEMENTS,\n element: HTMLElement,\n ) => {\n if (!arrowRef.current || !containerRef.current || !contentRef.current) {\n throw Error('Internal error');\n }\n\n setComponentPositions(pageX, pageY, placement, element, {\n arrow: arrowRef.current,\n container: containerRef.current,\n content: contentRef.current,\n });\n };\n useImperativeHandle(ref, () => ({ pointTo }));\n\n return createPortal(\n (\n <div className={theme.container} ref={containerRef}>\n <div className={theme.arrow} ref={arrowRef} />\n <div className={theme.content} ref={contentRef}>{children}</div>\n </div>\n ),\n document.body,\n );\n};\n\nexport default Tooltip;\n"],"mappings":"iDAAA;AACA;AACA;AACA;AACA;AAEA,SAIE,mBAAmB,EACnB,MAAM,QACD,OAAO;AAEd,SAAS,YAAY,QAAQ,WAAW;AAAC,+DAIzC;AACA;AACA;AACA;AACA,WAAY,UAAU,0BAAV,UAAU;EAAV,UAAU;EAAV,UAAU;EAAV,UAAU;EAAV,UAAU;EAAA,OAAV,UAAU;AAAA;AAOtB,MAAM,gBAAgB,GAAG,CACvB,iCAAiC,EACjC,+BAA+B,EAC/B,gCAAgC,CACjC,CAAC,IAAI,CAAC,GAAG,CAAC;AAEX,MAAM,cAAc,GAAG,CACrB,8BAA8B,EAC9B,+BAA+B,EAC/B,gCAAgC,CACjC,CAAC,IAAI,CAAC,GAAG,CAAC,CAiBX;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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AgB,SAAW,EAAX,KAAK,MAAM;MAAO,GAAQ,EAAR;IAAQ,CAAG,CAAC;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IAC9C;MAAgB,SAAa,EAAb,KAAK,QAAQ;MAAO,GAAU,EAAV,UAAU;MAAA,UAAG;IAAQ,CAAM,CAAC;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IAJ/D,8BAAY,cAEf;MAAgB,SAAe,EAAf,KAAK,UAAU;MAAO,GAAY,EAAZ,YAAY;MAAA,WAChD,EAA8C,EAC9C,EAAgE;IAAA,CAC7D,CAAC,EAER,QAAQ,KACV,CAAC;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA,OARM,EAQN;AAAA,CACF;AAED,eAAe,OAAO","ignoreList":[]}
|
|
@@ -51,6 +51,7 @@ const WithTooltip = ({
|
|
|
51
51
|
const [showTooltip, setShowTooltip] = useState(false);
|
|
52
52
|
const updatePortalPosition = (cursorX, cursorY) => {
|
|
53
53
|
if (showTooltip) {
|
|
54
|
+
if (!wrapperRef.current) throw Error("Missing reference");
|
|
54
55
|
const wrapperRect = wrapperRef.current.getBoundingClientRect();
|
|
55
56
|
if (cursorX < wrapperRect.left || cursorX > wrapperRect.right || cursorY < wrapperRect.top || cursorY > wrapperRect.bottom) {
|
|
56
57
|
setShowTooltip(false);
|
|
@@ -90,6 +91,7 @@ const WithTooltip = ({
|
|
|
90
91
|
// cycle due to the implementation).
|
|
91
92
|
if (tooltipRef.current) {
|
|
92
93
|
setHeap(prev_0 => {
|
|
94
|
+
if (!wrapperRef.current) throw Error("Missing reference");
|
|
93
95
|
tooltipRef.current?.pointTo(prev_0.lastCursorX + window.scrollX, prev_0.lastCursorY + window.scrollY, placement, wrapperRef.current);
|
|
94
96
|
return prev_0;
|
|
95
97
|
});
|
|
@@ -104,7 +106,7 @@ const WithTooltip = ({
|
|
|
104
106
|
}
|
|
105
107
|
return undefined;
|
|
106
108
|
}, [placement, showTooltip, tip]);
|
|
107
|
-
let container = custom.wrapper;
|
|
109
|
+
let container = custom.wrapper ?? "";
|
|
108
110
|
if (classNameProp) container += ` ${classNameProp}`;
|
|
109
111
|
useEffect(() => {
|
|
110
112
|
const listener_0 = () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/components/WithTooltip/index.tsx"],"sourcesContent":["/* global window */\n\nimport {\n type FunctionComponent,\n type HTMLAttributes,\n type ReactNode,\n type RefObject,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Tooltip, {\n PLACEMENTS,\n type ThemeKeysT as TooltipThemeKeysT,\n} from './Tooltip';\n\nimport defaultTheme from './default-theme.scss';\n\ntype PropsT = HTMLAttributes<HTMLDivElement> & {\n children?: ReactNode;\n placement?: PLACEMENTS;\n ref?: RefObject<HTMLDivElement | null>;\n theme?: Theme<'wrapper' | TooltipThemeKeysT>;\n tip?: ReactNode;\n};\n\ntype TooltipRefT = {\n pointTo: (\n x: number,\n y: number,\n placement: PLACEMENTS,\n wrapperRef: HTMLDivElement,\n ) => void;\n};\n\ntype HeapT = {\n ignoreMouseMove?: boolean;\n lastCursorX: number;\n lastCursorY: number;\n timerId?: NodeJS.Timeout;\n triggeredByTouch: boolean;\n};\n\n/**\n * Implements a simple to use and themeable tooltip component, _e.g._\n * ```js\n * <WithTooltip tip=\"This is example tooltip.\">\n * <p>Hover to see the tooltip.</p>\n * </WithTooltip>\n * ```\n * **Children:** Children are rendered in the place of `<WithTooltip>`,\n * and when hovered the tooltip is shown. By default the wrapper itself is\n * `<div>` block with `display: inline-block`.\n * @param tip – Anything React is able to render,\n * _e.g._ a tooltip text. This will be the tooltip content.\n * @param {WithTooltipTheme} props.theme _Ad hoc_ theme.\n */\nconst WithTooltip: FunctionComponent<PropsT> = ({\n children,\n className: classNameProp,\n onClick,\n onContextMenu,\n onMouseLeave,\n onMouseMove,\n onTouchStart,\n placement = PLACEMENTS.ABOVE_CURSOR,\n ref,\n style,\n theme,\n tip,\n ...htmlAttributes\n}) => {\n const custom = useTheme('WithTooltip', defaultTheme, theme);\n\n const [heap, setHeap] = useState<HeapT>({\n lastCursorX: 0,\n lastCursorY: 0,\n timerId: undefined,\n triggeredByTouch: false,\n });\n\n const tooltipRef = useRef<TooltipRefT>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [showTooltip, setShowTooltip] = useState(false);\n\n const updatePortalPosition = (cursorX: number, cursorY: number) => {\n if (showTooltip) {\n const wrapperRect = wrapperRef.current!.getBoundingClientRect();\n if (\n cursorX < wrapperRect.left\n || cursorX > wrapperRect.right\n || cursorY < wrapperRect.top\n || cursorY > wrapperRect.bottom\n ) {\n setShowTooltip(false);\n } else if (tooltipRef.current) {\n tooltipRef.current.pointTo(\n cursorX + window.scrollX,\n cursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n }\n } else {\n setHeap((prev) => {\n const res: HeapT = {\n ...prev,\n lastCursorX: cursorX,\n lastCursorY: cursorY,\n };\n\n // If tooltip was triggered by a touch, we delay its opening by a bit,\n // to ensure it was not a touch-click - in the case of touch click we\n // want to do the click, rather than show the tooltip, and the delay\n // gives click handler a chance to abort the tooltip openning.\n if (res.triggeredByTouch) {\n res.timerId ??= setTimeout(() => {\n setHeap((p) => ({\n ...p,\n timerId: undefined,\n triggeredByTouch: false,\n }));\n\n setShowTooltip(true);\n }, 300);\n\n // Otherwise we can just open the tooltip right away.\n } else setShowTooltip(true);\n\n return res;\n });\n }\n };\n\n useEffect(() => {\n if (showTooltip && tip !== null) {\n // This is necessary to ensure that even when a single mouse event\n // arrives to a tool-tipped component, the tooltip is correctly positioned\n // once opened (because similar call above does not have effect until\n // the tooltip is fully mounted, and that is delayed to future rendering\n // cycle due to the implementation).\n if (tooltipRef.current) {\n setHeap((prev) => {\n tooltipRef.current?.pointTo(\n prev.lastCursorX + window.scrollX,\n prev.lastCursorY + window.scrollY,\n placement,\n wrapperRef.current!,\n );\n return prev;\n });\n }\n\n const listener = () => {\n setShowTooltip(false);\n };\n window.addEventListener('scroll', listener);\n return () => {\n window.removeEventListener('scroll', listener);\n };\n }\n return undefined;\n }, [\n placement,\n showTooltip,\n tip,\n ]);\n\n let container = custom.wrapper;\n if (classNameProp) container += ` ${classNameProp}`;\n\n useEffect(() => {\n const listener = () => {\n setShowTooltip(false);\n heap.triggeredByTouch = false;\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n heap.timerId = undefined;\n heap.triggeredByTouch = false;\n }\n };\n window.addEventListener('touchcancel', listener);\n window.addEventListener('touchend', listener);\n return () => {\n window.removeEventListener('touchcancel', listener);\n window.removeEventListener('touchend', listener);\n };\n }, [heap]);\n\n return (\n <div\n className={container}\n onClick={(e) => {\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n\n setHeap({\n ...heap,\n timerId: undefined,\n triggeredByTouch: false,\n });\n }\n onClick?.(e);\n }}\n onContextMenu={(e) => {\n e.preventDefault();\n onContextMenu?.(e);\n }}\n onMouseLeave={(e) => {\n setShowTooltip(false);\n onMouseLeave?.(e);\n }}\n onMouseMove={(e) => {\n // NOTE: Because on touch devices mouse move events are still fired\n // after touch is released, to emulate mouse clicks for old websites.\n // If we don't ignore it here, the tooltip will appear after the touch\n // is released.\n if (!heap.ignoreMouseMove) {\n updatePortalPosition(e.clientX, e.clientY);\n }\n onMouseMove?.(e);\n }}\n onTouchStart={(e) => {\n setHeap({\n ...heap,\n ignoreMouseMove: true,\n triggeredByTouch: true,\n });\n\n // TODO: I guess, it should be something more complex here,\n // to actually respond to the first / whatever touch we need.\n const touch = e.targetTouches.item(0);\n updatePortalPosition(touch.clientX, touch.clientY);\n\n onTouchStart?.(e);\n }}\n ref={(node) => {\n wrapperRef.current = node;\n\n // eslint-disable-next-line no-param-reassign\n if (ref) ref.current = node;\n }}\n role=\"presentation\"\n style={style}\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...htmlAttributes}\n >\n {\n showTooltip && tip !== null\n ? <Tooltip ref={tooltipRef} theme={custom}>{tip}</Tooltip>\n : null\n }\n {children}\n </div>\n );\n};\n\ntype ExportT = {\n PLACEMENTS: typeof PLACEMENTS;\n} & typeof WithTooltip;\n\nconst e: ExportT = WithTooltip as ExportT;\n\ne.PLACEMENTS = PLACEMENTS;\n\nexport default e;\n"],"mappings":"AAAA,mBAEA,SAKE,SAAS,EACT,MAAM,EACN,QAAQ,QACH,OAAO;AAEd,SAAqB,QAAQ,QAAQ,0BAA0B;AAAC,OAEzD,OAAO,IACZ,UAAU;AAIZ;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAAgD,+DA2BhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAsC,GAAG,CAAC;EAC9C,QAAQ;EACR,SAAS,EAAE,aAAa;EACxB,OAAO;EACP,aAAa;EACb,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS,GAAG,UAAU,CAAC,YAAY;EACnC,GAAG;EACH,KAAK;EACL,KAAK;EACL,GAAG;EACH,GAAG;AACL,CAAC,KAAK;EACJ,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,EAAE,YAAY,EAAE,KAAK,CAAC;EAE3D,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAQ;IACtC,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,CAAC;IACd,OAAO,EAAE,SAAS;IAClB,gBAAgB,EAAE;EACpB,CAAC,CAAC;EAEF,MAAM,UAAU,GAAG,MAAM,CAAc,IAAI,CAAC;EAC5C,MAAM,UAAU,GAAG,MAAM,CAAiB,IAAI,CAAC;EAC/C,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC;EAErD,MAAM,oBAAoB,GAAG,CAAC,OAAe,EAAE,OAAe,KAAK;IACjE,IAAI,WAAW,EAAE;MACf,M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G,CAAU,CAAC,GACxD,IAAI,EAET,QAAQ;EAAA,CACN,CAAC;AAEV,CAAC;AAMD,MAAM,CAAU,GAAG,WAAsB;AAEzC,CAAC,CAAC,UAAU,GAAG,UAAU;AAEzB,eAAe,CAAC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../src/shared/components/WithTooltip/index.tsx"],"sourcesContent":["/* global window */\n\nimport {\n type FunctionComponent,\n type HTMLAttributes,\n type ReactNode,\n type RefObject,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport Tooltip, {\n PLACEMENTS,\n type ThemeKeysT as TooltipThemeKeysT,\n} from './Tooltip';\n\nimport defaultTheme from './default-theme.scss';\n\ntype PropsT = HTMLAttributes<HTMLDivElement> & {\n children?: ReactNode;\n placement?: PLACEMENTS;\n ref?: RefObject<HTMLDivElement | null>;\n theme?: Theme<'wrapper' | TooltipThemeKeysT>;\n tip?: ReactNode;\n};\n\ntype TooltipRefT = {\n pointTo: (\n x: number,\n y: number,\n placement: PLACEMENTS,\n wrapperRef: HTMLDivElement,\n ) => void;\n};\n\ntype HeapT = {\n ignoreMouseMove?: boolean;\n lastCursorX: number;\n lastCursorY: number;\n timerId?: NodeJS.Timeout;\n triggeredByTouch: boolean;\n};\n\n/**\n * Implements a simple to use and themeable tooltip component, _e.g._\n * ```js\n * <WithTooltip tip=\"This is example tooltip.\">\n * <p>Hover to see the tooltip.</p>\n * </WithTooltip>\n * ```\n * **Children:** Children are rendered in the place of `<WithTooltip>`,\n * and when hovered the tooltip is shown. By default the wrapper itself is\n * `<div>` block with `display: inline-block`.\n * @param tip – Anything React is able to render,\n * _e.g._ a tooltip text. This will be the tooltip content.\n * @param {WithTooltipTheme} props.theme _Ad hoc_ theme.\n */\nconst WithTooltip: FunctionComponent<PropsT> = ({\n children,\n className: classNameProp,\n onClick,\n onContextMenu,\n onMouseLeave,\n onMouseMove,\n onTouchStart,\n placement = PLACEMENTS.ABOVE_CURSOR,\n ref,\n style,\n theme,\n tip,\n ...htmlAttributes\n}) => {\n const custom = useTheme('WithTooltip', defaultTheme, theme);\n\n const [heap, setHeap] = useState<HeapT>({\n lastCursorX: 0,\n lastCursorY: 0,\n timerId: undefined,\n triggeredByTouch: false,\n });\n\n const tooltipRef = useRef<TooltipRefT>(null);\n const wrapperRef = useRef<HTMLDivElement>(null);\n const [showTooltip, setShowTooltip] = useState(false);\n\n const updatePortalPosition = (cursorX: number, cursorY: number) => {\n if (showTooltip) {\n if (!wrapperRef.current) throw Error('Missing reference');\n const wrapperRect = wrapperRef.current.getBoundingClientRect();\n if (\n cursorX < wrapperRect.left\n || cursorX > wrapperRect.right\n || cursorY < wrapperRect.top\n || cursorY > wrapperRect.bottom\n ) {\n setShowTooltip(false);\n } else if (tooltipRef.current) {\n tooltipRef.current.pointTo(\n cursorX + window.scrollX,\n cursorY + window.scrollY,\n placement,\n wrapperRef.current,\n );\n }\n } else {\n setHeap((prev) => {\n const res: HeapT = {\n ...prev,\n lastCursorX: cursorX,\n lastCursorY: cursorY,\n };\n\n // If tooltip was triggered by a touch, we delay its opening by a bit,\n // to ensure it was not a touch-click - in the case of touch click we\n // want to do the click, rather than show the tooltip, and the delay\n // gives click handler a chance to abort the tooltip openning.\n if (res.triggeredByTouch) {\n res.timerId ??= setTimeout(() => {\n setHeap((p) => ({\n ...p,\n timerId: undefined,\n triggeredByTouch: false,\n }));\n\n setShowTooltip(true);\n }, 300);\n\n // Otherwise we can just open the tooltip right away.\n } else setShowTooltip(true);\n\n return res;\n });\n }\n };\n\n useEffect(() => {\n if (showTooltip && tip !== null) {\n // This is necessary to ensure that even when a single mouse event\n // arrives to a tool-tipped component, the tooltip is correctly positioned\n // once opened (because similar call above does not have effect until\n // the tooltip is fully mounted, and that is delayed to future rendering\n // cycle due to the implementation).\n if (tooltipRef.current) {\n setHeap((prev) => {\n if (!wrapperRef.current) throw Error('Missing reference');\n tooltipRef.current?.pointTo(\n prev.lastCursorX + window.scrollX,\n prev.lastCursorY + window.scrollY,\n placement,\n wrapperRef.current,\n );\n return prev;\n });\n }\n\n const listener = () => {\n setShowTooltip(false);\n };\n window.addEventListener('scroll', listener);\n return () => {\n window.removeEventListener('scroll', listener);\n };\n }\n return undefined;\n }, [\n placement,\n showTooltip,\n tip,\n ]);\n\n let container = custom.wrapper ?? '';\n if (classNameProp) container += ` ${classNameProp}`;\n\n useEffect(() => {\n const listener = () => {\n setShowTooltip(false);\n heap.triggeredByTouch = false;\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n heap.timerId = undefined;\n heap.triggeredByTouch = false;\n }\n };\n window.addEventListener('touchcancel', listener);\n window.addEventListener('touchend', listener);\n return () => {\n window.removeEventListener('touchcancel', listener);\n window.removeEventListener('touchend', listener);\n };\n }, [heap]);\n\n return (\n <div\n className={container}\n onClick={(e) => {\n if (heap.timerId) {\n clearTimeout(heap.timerId);\n\n setHeap({\n ...heap,\n timerId: undefined,\n triggeredByTouch: false,\n });\n }\n onClick?.(e);\n }}\n onContextMenu={(e) => {\n e.preventDefault();\n onContextMenu?.(e);\n }}\n onMouseLeave={(e) => {\n setShowTooltip(false);\n onMouseLeave?.(e);\n }}\n onMouseMove={(e) => {\n // NOTE: Because on touch devices mouse move events are still fired\n // after touch is released, to emulate mouse clicks for old websites.\n // If we don't ignore it here, the tooltip will appear after the touch\n // is released.\n if (!heap.ignoreMouseMove) {\n updatePortalPosition(e.clientX, e.clientY);\n }\n onMouseMove?.(e);\n }}\n onTouchStart={(e) => {\n setHeap({\n ...heap,\n ignoreMouseMove: true,\n triggeredByTouch: true,\n });\n\n // TODO: I guess, it should be something more complex here,\n // to actually respond to the first / whatever touch we need.\n const touch = e.targetTouches.item(0);\n updatePortalPosition(touch.clientX, touch.clientY);\n\n onTouchStart?.(e);\n }}\n ref={(node) => {\n wrapperRef.current = node;\n\n // eslint-disable-next-line no-param-reassign\n if (ref) ref.current = node;\n }}\n role=\"presentation\"\n style={style}\n\n // eslint-disable-next-line react/jsx-props-no-spreading\n {...htmlAttributes}\n >\n {\n showTooltip && tip !== null\n ? <Tooltip ref={tooltipRef} theme={custom}>{tip}</Tooltip>\n : null\n }\n {children}\n </div>\n );\n};\n\ntype ExportT = {\n PLACEMENTS: typeof PLACEMENTS;\n} & typeof WithTooltip;\n\nconst e: ExportT = WithTooltip as ExportT;\n\ne.PLACEMENTS = PLACEMENTS;\n\nexport default e;\n"],"mappings":"AAAA,mBAEA,SAKE,SAAS,EACT,MAAM,EACN,QAAQ,QACH,OAAO;AAEd,SAAqB,QAAQ,QAAQ,0BAA0B;AAAC,OAEzD,OAAO,IACZ,UAAU;AAIZ;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAAgD,+DA2BhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAM,WAAsC,GAAG,CAAC;EAC9C,QAAQ;EACR,SAAS,EAAE,aAAa;EACxB,OAAO;EACP,aAAa;EACb,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS,GAAG,UAAU,CAAC,YAAY;EACnC,GAAG;EACH,KAAK;EACL,KAAK;EACL,GAAG;EACH,GAAG;AACL,CAAC,KAAK;EACJ,MAAM,MAAM,GAAG,QAAQ,CAAC,aAAa,EAAE,YAAY,EAAE,KAAK,CAAC;EAE3D,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAQ;IACtC,WAAW,EAAE,CAAC;IACd,WAAW,EAAE,CAAC;IACd,OAAO,EAAE,SAAS;IAClB,gBAAgB,EAAE;EACpB,CAAC,CAAC;EAEF,MAAM,UAAU,GAAG,MAAM,CAAc,IAAI,CAAC;EAC5C,MAAM,UAAU,GAAG,MAAM,CAAiB,IAAI,CAAC;EAC/C,MAAM,CAAC,WAAW,EAAE,cAAc,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC;EAErD,MAAM,oBAAoB,GAAG,CAAC,OAA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;IAC7B,CAAE;IACF,IAAI,EAAC,cAAc;IACnB,KAAK,EAAE,KAEP;IAAA;IAAA,GACI,cAAc;IAAA,WAGhB,WAAW,IAAI,GAAG,KAAK,IAAI,gBACvB,KAAC,OAAO;MAAC,GAAG,EAAE,UAAW;MAAC,KAAK,EAAE,MAAO;MAAA,UAAE;IAAG,CAAU,CAAC,GACxD,IAAI,EAET,QAAQ;EAAA,CACN,CAAC;AAEV,CAAC;AAMD,MAAM,CAAU,GAAG,WAAsB;AAEzC,CAAC,CAAC,UAAU,GAAG,UAAU;AAEzB,eAAe,CAAC","ignoreList":[]}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "core-js/modules/es.iterator.filter.js";
|
|
2
|
+
import "core-js/modules/es.array.push.js";
|
|
3
|
+
import "core-js/modules/es.iterator.constructor.js";
|
|
4
|
+
import "core-js/modules/es.iterator.filter.js";
|
|
2
5
|
import { c as _c } from "react/compiler-runtime";
|
|
3
6
|
import { useImperativeHandle, useRef } from "react";
|
|
4
7
|
import { BaseModal } from "../../../Modal/index.js";
|
|
@@ -32,6 +35,9 @@ const Options = t0 => {
|
|
|
32
35
|
if (!e) {
|
|
33
36
|
return;
|
|
34
37
|
}
|
|
38
|
+
if (!opsRef.current) {
|
|
39
|
+
throw Error("Missing reference");
|
|
40
|
+
}
|
|
35
41
|
const rect = opsRef.current.getBoundingClientRect();
|
|
36
42
|
const style = window.getComputedStyle(e);
|
|
37
43
|
const mBottom = parseFloat(style.marginBottom);
|
|
@@ -54,7 +60,7 @@ const Options = t0 => {
|
|
|
54
60
|
for (const option of options) {
|
|
55
61
|
if (!filter || filter(option)) {
|
|
56
62
|
const [iValue, iName] = optionValueName(option);
|
|
57
|
-
|
|
63
|
+
optionNodes.push(/*#__PURE__*/_jsx("div", {
|
|
58
64
|
className: optionClass,
|
|
59
65
|
onClick: e_0 => {
|
|
60
66
|
onChange(iValue);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../../src/shared/components/selectors/CustomDropdown/Options/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useImperativeHandle,\n useRef,\n} from 'react';\n\nimport { BaseModal } from 'components/Modal';\n\nimport {\n type OptionT,\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../../common';\n\nimport S from './style.scss';\n\nexport type ContainerPosT = {\n left: number;\n top: number;\n width: number;\n};\n\nexport function areEqual(a?: ContainerPosT, b?: ContainerPosT): boolean {\n return a?.left === b?.left && a?.top === b?.top && a?.width === b?.width;\n}\n\nexport type RefT = {\n measure: () => DOMRect | undefined;\n};\n\ntype PropsT = {\n containerClass: string;\n containerStyle?: ContainerPosT;\n filter?: (item: OptionT<ReactNode> | ValueT) => boolean;\n onCancel: () => void;\n onChange: (value: ValueT) => void;\n optionClass: string;\n options: Readonly<OptionsT<ReactNode>>;\n ref?: RefObject<RefT | null>;\n};\n\nconst Options: FunctionComponent<PropsT> = ({\n containerClass,\n containerStyle,\n filter,\n onCancel,\n onChange,\n optionClass,\n options,\n ref,\n}) => {\n const opsRef = useRef<HTMLDivElement>(null);\n\n useImperativeHandle(ref, () => ({\n measure: () => {\n const e = opsRef.current?.parentElement;\n if (!e) return undefined;\n\n const rect = opsRef.current
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../../src/shared/components/selectors/CustomDropdown/Options/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n type RefObject,\n useImperativeHandle,\n useRef,\n} from 'react';\n\nimport { BaseModal } from 'components/Modal';\n\nimport {\n type OptionT,\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../../common';\n\nimport S from './style.scss';\n\nexport type ContainerPosT = {\n left: number;\n top: number;\n width: number;\n};\n\nexport function areEqual(a?: ContainerPosT, b?: ContainerPosT): boolean {\n return a?.left === b?.left && a?.top === b?.top && a?.width === b?.width;\n}\n\nexport type RefT = {\n measure: () => DOMRect | undefined;\n};\n\ntype PropsT = {\n containerClass: string;\n containerStyle?: ContainerPosT;\n filter?: (item: OptionT<ReactNode> | ValueT) => boolean;\n onCancel: () => void;\n onChange: (value: ValueT) => void;\n optionClass: string;\n options: Readonly<OptionsT<ReactNode>>;\n ref?: RefObject<RefT | null>;\n};\n\nconst Options: FunctionComponent<PropsT> = ({\n containerClass,\n containerStyle,\n filter,\n onCancel,\n onChange,\n optionClass,\n options,\n ref,\n}) => {\n const opsRef = useRef<HTMLDivElement>(null);\n\n useImperativeHandle(ref, () => ({\n measure: () => {\n const e = opsRef.current?.parentElement;\n if (!e) return undefined;\n\n if (!opsRef.current) throw Error('Missing reference');\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":";;;;;AAAA,SAIE,mBAAmB,EACnB,MAAM,QACD,OAAO;A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CAAC;YAChB,GAAC,gBAAgB,CAAC,CAAC;UAAA,CACpB;UACU,SAKV,EALU;YACT,IAAI,GAAC,IAAI,KAAK,OAAO;cACnB,QAAQ,CAAC,MAAM,CAAC;cAChB,GAAC,gBAAgB,CAAC,CAAC;YAAA;UACpB,CACF;UACI,IAAQ,EAAR,QAAQ;UACH,QAAC,EAAD,CAAC;UAAA,UAEV;QAAK,GAdD,MAeF,CACP,CAAC;MAAA;IACF;IACF;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IAaU;MAAA,IACD,EAAE;MAAA,WACK,cAAc;MAAA,SAChB,EAAE;MAAA,KACN,EAAE;MAAA,SACE,CAAC;IACZ,CAAC;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IAED;MAAU,GAAM,EAAN,MAAM;MAAA,UAAG;IAAW,CAAM,CAAC;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IAlBvC,uBAAC,SAAS;MAMR,iBAAiB,EAAjB,IAAiB;MACjB,oBAAoB,EAApB,IAAoB;MACV,QAAQ,EAAR,QAAQ;MACX,KAAc,EAAd,cAAc;MACd,KAMN,EANM,EAMN;MAAA,UAED;IAAqC,CAC5B,CAAC;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA,OAnBZ,EAmBY;AAAA,CAEf;AAED,eAAe,OAAO","ignoreList":[]}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import "core-js/modules/es.iterator.filter.js";
|
|
2
|
+
import "core-js/modules/es.iterator.constructor.js";
|
|
3
|
+
import "core-js/modules/es.iterator.filter.js";
|
|
1
4
|
import { c as _c } from "react/compiler-runtime";
|
|
2
5
|
import { useEffect, useRef, useState } from "react";
|
|
3
6
|
import { useTheme } from "@dr.pogodin/react-themes";
|
|
@@ -80,6 +83,9 @@ const CustomDropdown = t0 => {
|
|
|
80
83
|
if ($[3] === Symbol.for("react.memo_cache_sentinel")) {
|
|
81
84
|
t3 = e => {
|
|
82
85
|
const view = window.visualViewport;
|
|
86
|
+
if (!dropdownRef.current) {
|
|
87
|
+
throw Error("Missing dropdown reference");
|
|
88
|
+
}
|
|
83
89
|
const rect = dropdownRef.current.getBoundingClientRect();
|
|
84
90
|
setActive(true);
|
|
85
91
|
setOpsPos({
|
|
@@ -121,14 +127,14 @@ const CustomDropdown = t0 => {
|
|
|
121
127
|
} else {
|
|
122
128
|
selected = $[8];
|
|
123
129
|
}
|
|
124
|
-
let containerClassName = custom.container;
|
|
130
|
+
let containerClassName = custom.container ?? "";
|
|
125
131
|
if (active) {
|
|
126
|
-
containerClassName = containerClassName + ` ${custom.active}`;
|
|
132
|
+
containerClassName = containerClassName + ` ${custom.active ?? ""}`;
|
|
127
133
|
}
|
|
128
134
|
let opsContainerClass = custom.select ?? "";
|
|
129
135
|
if (upward) {
|
|
130
|
-
containerClassName = containerClassName + ` ${custom.upward}`;
|
|
131
|
-
opsContainerClass = opsContainerClass + ` ${custom.upward}`;
|
|
136
|
+
containerClassName = containerClassName + ` ${custom.upward ?? ""}`;
|
|
137
|
+
opsContainerClass = opsContainerClass + ` ${custom.upward ?? ""}`;
|
|
132
138
|
}
|
|
133
139
|
let t5;
|
|
134
140
|
if ($[9] !== custom.label || $[10] !== label) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, type ValueT, optionValueName } from '../common';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nconst CustomDropdown: FunctionComponent<\n PropsT<ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const custom = useTheme('CustomDropdown', defaultTheme, theme);\n\n const [active, setActive] = useState(false);\n\n const dropdownRef = useRef<HTMLDivElement>(null);\n const opsRef = useRef<RefT>(null);\n\n const [opsPos, setOpsPos] = useState<ContainerPosT>();\n const [upward, setUpward] = useState(false);\n\n useEffect(() => {\n if (!active) return undefined;\n\n let id: number;\n const cb = () => {\n const anchor = dropdownRef.current?.getBoundingClientRect();\n const opsRect = opsRef.current?.measure();\n if (anchor && opsRect) {\n const fitsDown = anchor.bottom + opsRect.height\n < (window.visualViewport?.height ?? 0);\n const fitsUp = anchor.top - opsRect.height > 0;\n\n const up = !fitsDown && fitsUp;\n setUpward(up);\n\n const pos = up ? {\n left: anchor.left,\n top: anchor.top - opsRect.height - 1,\n width: anchor.width,\n } : {\n left: anchor.left,\n top: anchor.bottom,\n width: anchor.width,\n };\n\n setOpsPos((now) => (areEqual(now, pos) ? now : pos));\n }\n id = requestAnimationFrame(cb);\n };\n requestAnimationFrame(cb);\n\n return () => {\n cancelAnimationFrame(id);\n };\n }, [active]);\n\n const openList = (\n e: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>,\n ) => {\n const view = window.visualViewport;\n const rect = dropdownRef.current
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/CustomDropdown/index.tsx"],"sourcesContent":["import {\n type FunctionComponent,\n type ReactNode,\n useEffect,\n useRef,\n useState,\n} from 'react';\n\nimport { useTheme } from '@dr.pogodin/react-themes';\n\nimport { type PropsT, type ValueT, optionValueName } from '../common';\n\nimport Options, { type ContainerPosT, type RefT, areEqual } from './Options';\n\nimport defaultTheme from './theme.scss';\n\nconst CustomDropdown: FunctionComponent<\n PropsT<ReactNode, (value: ValueT) => void>\n> = ({\n filter,\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const custom = useTheme('CustomDropdown', defaultTheme, theme);\n\n const [active, setActive] = useState(false);\n\n const dropdownRef = useRef<HTMLDivElement>(null);\n const opsRef = useRef<RefT>(null);\n\n const [opsPos, setOpsPos] = useState<ContainerPosT>();\n const [upward, setUpward] = useState(false);\n\n useEffect(() => {\n if (!active) return undefined;\n\n let id: number;\n const cb = () => {\n const anchor = dropdownRef.current?.getBoundingClientRect();\n const opsRect = opsRef.current?.measure();\n if (anchor && opsRect) {\n const fitsDown = anchor.bottom + opsRect.height\n < (window.visualViewport?.height ?? 0);\n const fitsUp = anchor.top - opsRect.height > 0;\n\n const up = !fitsDown && fitsUp;\n setUpward(up);\n\n const pos = up ? {\n left: anchor.left,\n top: anchor.top - opsRect.height - 1,\n width: anchor.width,\n } : {\n left: anchor.left,\n top: anchor.bottom,\n width: anchor.width,\n };\n\n setOpsPos((now) => (areEqual(now, pos) ? now : pos));\n }\n id = requestAnimationFrame(cb);\n };\n requestAnimationFrame(cb);\n\n return () => {\n cancelAnimationFrame(id);\n };\n }, [active]);\n\n const openList = (\n e: React.KeyboardEvent<HTMLDivElement> | React.MouseEvent<HTMLDivElement>,\n ) => {\n const view = window.visualViewport;\n if (!dropdownRef.current) throw Error('Missing dropdown reference');\n const rect = dropdownRef.current.getBoundingClientRect();\n setActive(true);\n\n // NOTE: This first opens the dropdown off-screen, where it is measured\n // by an effect declared above, and then positioned below, or above\n // the original dropdown element, depending where it fits best\n // (if we first open it downward, it would flick if we immediately\n // move it above, at least with the current position update via local\n // react state, and not imperatively).\n setOpsPos({\n left: view?.width ?? 0,\n top: view?.height ?? 0,\n width: rect.width,\n });\n\n e.stopPropagation();\n };\n\n let selected: React.ReactNode = <>‌</>;\n for (const option of options) {\n if (!filter || filter(option)) {\n const [iValue, iName] = optionValueName(option);\n if (iValue === value) {\n selected = iName;\n break;\n }\n }\n }\n\n let containerClassName = custom.container ?? '';\n if (active) containerClassName += ` ${custom.active ?? ''}`;\n\n let opsContainerClass = custom.select ?? '';\n if (upward) {\n containerClassName += ` ${custom.upward ?? ''}`;\n opsContainerClass += ` ${custom.upward ?? ''}`;\n }\n\n return (\n <div className={containerClassName}>\n {label === undefined ? null\n : <div className={custom.label}>{label}</div>}\n <div\n className={custom.dropdown}\n onClick={openList}\n onKeyDown={(e) => {\n if (e.key === 'Enter') openList(e);\n }}\n ref={dropdownRef}\n role=\"listbox\"\n tabIndex={0}\n >\n {selected}\n <div className={custom.arrow} />\n </div>\n {\n active ? (\n <Options\n containerClass={opsContainerClass}\n containerStyle={opsPos}\n onCancel={() => {\n setActive(false);\n }}\n onChange={(newValue) => {\n setActive(false);\n if (onChange) onChange(newValue);\n }}\n optionClass={custom.option ?? ''}\n options={options}\n ref={opsRef}\n />\n ) : null\n }\n </div>\n );\n};\n\nexport default CustomDropdown;\n"],"mappings":";;;;AAAA,SAGE,SAAS,EACT,MAAM,EACN,QAAQ,QACH,OAAO;AAEd,SAAS,QAAQ,QAAQ,0BAA0B;AAAC,SAEjB,eAAe;AAAA,OAE3C,OAAO,IAAmC,QAAQ;AAEzD;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAAwC;AAExC,MAAM,cAEL,GAAG;EAAA;EAAC;IAAA;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA,MAOJ;EACC,eAAe,QAAQ,CAAC,gBAAgB,EAAE,YAAY,EAAE,KAAK,CAAC;EAE9D,4BAA4B,QAAQ,CAAC,KAAK,CAAC;EAE3C,oBAAoB,MAAM,CAAiB,IAAI,CAAC;EAChD,eAAe,MAAM,CAAO,IAAI,CAAC;EAEjC,4BAA4B,QAAQ,CAAgB,CAAC;EACrD,4BAA4B,QAAQ,CAAC,KAAK,CAAC;EAAC;EAAA;EAAA;IAElC;MACR,IAAI,CAAC,MAAM;QAAA;MAAA;MAEP;MACJ,WAAW;QACT,eAAe,WAAW,QAA+B,uBAAE,CAAD,CAAC;QAC3D,gBAAgB,MAAM,QAAiB,SAAE,CAAD,CAAC;QACzC,IAAI,MAAiB,IAAjB,OAAiB;UACnB,iBAAiB,MAAM,OAAO,GAAG,OAAO,OAAO,IAC1C,MAAM,eAAuB,QAAK,IAAlC,CA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AiB,EAAjB,iBAAiB;MACjB,cAAM,EAAN,MAAM;MACZ,QAET,EAFS;QACR,SAAS,CAAC,KAAK,CAAC;MAAA,CACjB;MACS,QAGT,EAHS;QACR,SAAS,CAAC,KAAK,CAAC;QAChB,IAAI,QAAQ;UAAE,QAAQ,CAAC,QAAQ,CAAC;QAAA;MAAC,CAClC;MACY,WAAmB,EAAnB,MAAM,OAAa,IAAnB,EAAmB;MACvB,OAAO,EAAP,OAAO;MACX,GAAM,EAAN;IAAM,CAER,CAAC,GAfR,IAeQ;IAAA;IAAA;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IAhCZ;MAAgB,SAAkB,EAAlB,kBAAkB;MAAA,WAC/B,EAC8C,EAC/C,EAYM,EAEJ,EAeQ;IAAA,CAEP,CAAC;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA,OAlCN,GAkCM;AAAA,CAET;AAED,eAAe,cAAc","ignoreList":[]}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "core-js/modules/es.iterator.filter.js";
|
|
2
|
+
import "core-js/modules/es.array.push.js";
|
|
3
|
+
import "core-js/modules/es.iterator.constructor.js";
|
|
4
|
+
import "core-js/modules/es.iterator.filter.js"; // Implements dropdown based on the native HTML <select> element.
|
|
2
5
|
import { useTheme } from "@dr.pogodin/react-themes";
|
|
3
6
|
import { optionValueName } from "../common.js";
|
|
4
7
|
const defaultTheme = {
|
|
@@ -52,7 +55,7 @@ const Dropdown = ({
|
|
|
52
55
|
if (!filter || filter(option)) {
|
|
53
56
|
const [iValue, iName] = optionValueName(option);
|
|
54
57
|
isValidValue ||= iValue === value;
|
|
55
|
-
|
|
58
|
+
optionElements.push(/*#__PURE__*/_jsx("option", {
|
|
56
59
|
className: composed.option,
|
|
57
60
|
value: iValue,
|
|
58
61
|
children: iName
|
|
@@ -68,8 +71,8 @@ const Dropdown = ({
|
|
|
68
71
|
value: value,
|
|
69
72
|
children: value
|
|
70
73
|
}, "__reactUtilsHiddenOption");
|
|
71
|
-
let selectClassName = composed.select;
|
|
72
|
-
if (!isValidValue) selectClassName += ` ${composed.invalid}`;
|
|
74
|
+
let selectClassName = composed.select ?? "";
|
|
75
|
+
if (!isValidValue) selectClassName += ` ${composed.invalid ?? ""}`;
|
|
73
76
|
return /*#__PURE__*/_jsxs("div", {
|
|
74
77
|
className: composed.container,
|
|
75
78
|
children: [label === undefined ? null : /*#__PURE__*/_jsx("div", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/NativeDropdown/index.tsx"],"sourcesContent":["// Implements dropdown based on the native HTML <select> element.\n\nimport type { FunctionComponent } from 'react';\n\nimport { useTheme } 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: FunctionComponent<PropsT<string>> = ({\n filter,\n label,\n onChange,\n onClick,\n options,\n testId,\n theme,\n value,\n}) => {\n let isValidValue = false;\n const optionElements = [];\n\n const composed = useTheme('Dropdown', defaultTheme, theme);\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={composed.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={composed.hiddenOption}\n disabled\n key=\"__reactUtilsHiddenOption\"\n value={value}\n >\n {value}\n </option>\n );\n\n let selectClassName = composed.select;\n if (!isValidValue) selectClassName += ` ${composed.invalid}`;\n\n return (\n <div className={composed.container}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <div className={composed.dropdown}>\n <select\n className={selectClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onChange={onChange}\n onClick={onClick}\n value={value}\n >\n {hiddenOption}\n {optionElements}\n </select>\n <div className={composed.arrow} />\n </div>\n </div>\n );\n};\n\nexport default Dropdown;\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/NativeDropdown/index.tsx"],"sourcesContent":["// Implements dropdown based on the native HTML <select> element.\n\nimport type { FunctionComponent } from 'react';\n\nimport { useTheme } 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: FunctionComponent<PropsT<string>> = ({\n filter,\n label,\n onChange,\n onClick,\n options,\n testId,\n theme,\n value,\n}) => {\n let isValidValue = false;\n const optionElements = [];\n\n const composed = useTheme('Dropdown', defaultTheme, theme);\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={composed.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={composed.hiddenOption}\n disabled\n key=\"__reactUtilsHiddenOption\"\n value={value}\n >\n {value}\n </option>\n );\n\n let selectClassName = composed.select ?? '';\n if (!isValidValue) selectClassName += ` ${composed.invalid ?? ''}`;\n\n return (\n <div className={composed.container}>\n { label === undefined\n ? null : <div className={composed.label}>{label}</div> }\n <div className={composed.dropdown}>\n <select\n className={selectClassName}\n data-testid={process.env.NODE_ENV === 'production' ? undefined : testId}\n onChange={onChange}\n onClick={onClick}\n value={value}\n >\n {hiddenOption}\n {optionElements}\n </select>\n <div className={composed.arrow} />\n </div>\n </div>\n );\n};\n\nexport default Dropdown;\n"],"mappings":";;;+CAAA;AAIA,SAAS,QAAQ,QAAQ,0BAA0B;AAAC,SAE9B,eAAe;AAErC;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AAlBA;AAmBA,MAAM,QAA2C,GAAG,CAAC;EACnD,MAAM;EACN,KAAK;EACL,QAAQ;EACR,OAAO;EACP,OAAO;EACP,MAAM;EACN,KAAK;EACL;AACF,CAAC,KAAK;EACJ,IAAI,YAAY,GAAG,KAAK;EACxB,MAAM,cAAc,GAAG,EAAE;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AQ,CAAC;MAAM,CAAE,CAAC;IAAA,CAC/B,CAAC;EAAA,CACH,CAAC;AAEV,CAAC;AAED,eAAe,QAAQ","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "core-js/modules/es.array.push.js";
|
|
2
2
|
import { c as _c } from "react/compiler-runtime";
|
|
3
3
|
import { useTheme } from "@dr.pogodin/react-themes";
|
|
4
4
|
import { optionValueName } from "../common.js";
|
|
@@ -33,7 +33,7 @@ export const Switch = t0 => {
|
|
|
33
33
|
let className = composed.option;
|
|
34
34
|
let onPress;
|
|
35
35
|
if (iValue === value) {
|
|
36
|
-
className = className + ` ${composed.selected}`;
|
|
36
|
+
className = className + ` ${composed.selected ?? ""}`;
|
|
37
37
|
} else {
|
|
38
38
|
if (onChange) {
|
|
39
39
|
onPress = () => {
|
|
@@ -41,7 +41,7 @@ export const Switch = t0 => {
|
|
|
41
41
|
};
|
|
42
42
|
}
|
|
43
43
|
}
|
|
44
|
-
|
|
44
|
+
optionNodes.push(onPress ? /*#__PURE__*/_jsx("div", {
|
|
45
45
|
className: className,
|
|
46
46
|
onClick: onPress,
|
|
47
47
|
onKeyDown: e => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import type { FunctionComponent, ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeT = Theme<'container' | 'label' | 'option' | 'options' | 'selected'>;\n\ntype PropsT = {\n label?: ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<ReactNode>>;\n theme?: ThemeT;\n value?: ValueT;\n};\n\nexport const Switch: FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const composed = useTheme('Switch', defaultTheme, theme);\n\n if (!options || !composed.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (const option of options) {\n const [iValue, iName] = optionValueName(option);\n\n let className: string = composed.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${composed.selected}`;\n else if (onChange) {\n onPress = () => {\n onChange(iValue);\n };\n }\n\n optionNodes.push(\n onPress\n ? (\n <div\n className={className}\n key={iValue}\n onClick={onPress}\n onKeyDown={(e) => {\n if (e.key === 'Enter') onPress();\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n )\n : <div className={className} key={iValue}>{iName}</div>,\n );\n }\n\n return (\n <div className={composed.container}>\n {label ? <div className={composed.label}>{label}</div> : null}\n\n <div className={composed.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n"],"mappings":";;AAEA,SAAqB,QAAQ,QAAQ,0BAA0B;AAAC,SAK9D,eAAe;AAGjB;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAAwC;AAYxC,OAAO,MAAM,MAAiC,GAAG;EAAA;EAAC;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA,MAMjD;EACC,iBAAiB,QAAQ,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,CAAC;EAExD,IAAI,CAAC,OAA2B,IAA5B,CAAa,QAAQ,OAAO;IAAE,MAAM,KAAK,CAAC,gBAAgB,CAAC;EAAC;EAAA;EAAA;IAEhE,cAAuC,EAAE;IACzC,KAAK,YAAY,IAAI,OAAO;MAC1B,wBAAwB,eAAe,CAAC,MAAM,CAAC;MAE/C,gBAAwB,QAAQ,OAAO;MACnC;MACJ,IAAI,MAAM,KAAK,KAAK;QAAE,qBAAS,GAAI,IAAI,QAAQ,
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/components/selectors/Switch/index.tsx"],"sourcesContent":["import type { FunctionComponent, ReactNode } from 'react';\n\nimport { type Theme, useTheme } from '@dr.pogodin/react-themes';\n\nimport {\n type OptionsT,\n type ValueT,\n optionValueName,\n} from '../common';\n\nimport defaultTheme from './theme.scss';\n\ntype ThemeT = Theme<'container' | 'label' | 'option' | 'options' | 'selected'>;\n\ntype PropsT = {\n label?: ReactNode;\n onChange?: (value: ValueT) => void;\n options?: Readonly<OptionsT<ReactNode>>;\n theme?: ThemeT;\n value?: ValueT;\n};\n\nexport const Switch: FunctionComponent<PropsT> = ({\n label,\n onChange,\n options,\n theme,\n value,\n}) => {\n const composed = useTheme('Switch', defaultTheme, theme);\n\n if (!options || !composed.option) throw Error('Internal error');\n\n const optionNodes: React.ReactNode[] = [];\n for (const option of options) {\n const [iValue, iName] = optionValueName(option);\n\n let className: string = composed.option;\n let onPress: (() => void) | undefined;\n if (iValue === value) className += ` ${composed.selected ?? ''}`;\n else if (onChange) {\n onPress = () => {\n onChange(iValue);\n };\n }\n\n optionNodes.push(\n onPress\n ? (\n <div\n className={className}\n key={iValue}\n onClick={onPress}\n onKeyDown={(e) => {\n if (e.key === 'Enter') onPress();\n }}\n role=\"button\"\n tabIndex={0}\n >\n {iName}\n </div>\n )\n : <div className={className} key={iValue}>{iName}</div>,\n );\n }\n\n return (\n <div className={composed.container}>\n {label ? <div className={composed.label}>{label}</div> : null}\n\n <div className={composed.options}>\n {optionNodes}\n </div>\n </div>\n );\n};\n"],"mappings":";;AAEA,SAAqB,QAAQ,QAAQ,0BAA0B;AAAC,SAK9D,eAAe;AAGjB;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;EAAA;AAAA;AAAwC;AAYxC,OAAO,MAAM,MAAiC,GAAG;EAAA;EAAC;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA,MAMjD;EACC,iBAAiB,QAAQ,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,CAAC;EAExD,IAAI,CAAC,OAA2B,IAA5B,CAAa,QAAQ,OAAO;IAAE,MAAM,KAAK,CAAC,gBAAgB,CAAC;EAAC;EAAA;EAAA;IAEhE,cAAuC,EAAE;IACzC,KAAK,YAAY,IAAI,OAAO;MAC1B,wBAAwB,eAAe,CAAC,MAAM,CAAC;MAE/C,gBAAwB,QAAQ,OAAO;MACnC;MACJ,IAAI,MAAM,KAAK,KAAK;QAAE,qBAAS,GAAI,IAAI,QAAQ,SAAe,IAAvB,EAAuB,EAAE;MAAA;QAC3D,IAAI,QAAQ;UACf,UAAU;YACR,QAAQ,CAAC,MAAM,CAAC;UAAA,CACjB;QAFM;MAGR;MAED,WAAW,KAAK,CACd,OAAO,gBAAP;QAGiB,SAAS,EAAT,SAAS;QAEX,OAAO,EAAP,OAAO;QACL,SAEV,EAFU;UACT,IAAI,CAAC,IAAI,KAAK,OAAO;YAAE,OAAO,CAAC,CAAC;UAAA;QAAC,CAClC;QACI,IAAQ,EAAR,QAAQ;QACH,QAAC,EAAD,CAAC;QAAA,UAEV;MAAK,GARD,MAW6C,CAAC,gBAfzD;QAeoB,SAAS,EAAT,SAAS;QAAA,UAAgB;MAAK,GAAd,MAAoB,CAC1D,CAAC;IAAA;IACF;IAAA;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IAII,UAAK,gBAAL;MAAwB,SAAc,EAAd,QAAQ,MAAM;MAAA,UAAG;IAAK,CAAa,CAAC,GAA5D,IAA4D;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IAE7D;MAAgB,SAAgB,EAAhB,QAAQ,QAAQ;MAAA,UAC7B;IAAW,CACT,CAAC;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA;EAAA;IALR;MAAgB,SAAkB,EAAlB,QAAQ,UAAU;MAAA,WAC/B,EAA4D,EAE7D,EAEM;IAAA,CACH,CAAC;IAAA;IAAA;IAAA;IAAA;EAAA;IAAA;EAAA;EAAA,OANN,EAMM;AAAA,CAET","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.js","names":[],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parseCookie } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\ntype ConfigT = Record<string, unknown>;\n\nlet config: ConfigT | Promise<ConfigT> | undefined;\n\n/**\n * Injects CSRF token into config (on client-side only).\n *\n * BEWARE: It mutates the argument, and also returns it as the result,\n * for chaining.\n */\nfunction injectCsrfToken(cfg: ConfigT): ConfigT {\n // The safeguard for \"document\" is necessary because in non-Node environments,\n // like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n // of other browser-world features are not available.\n if (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line no-param-reassign\n cfg.CSRF = parseCookie(document.cookie).csrfToken;\n }\n\n return cfg;\n}\n\nexport function getConfig
|
|
1
|
+
{"version":3,"file":"config.js","names":[],"sources":["../../../../src/shared/utils/config.ts"],"sourcesContent":["/* global document */\n\nimport { parseCookie } from 'cookie';\n\nimport clientGetInj from '../../client/getInj';\n\nimport { IS_CLIENT_SIDE } from './isomorphy/environment-check';\nimport { requireWeak } from './webpack';\n\ntype ConfigT = Record<string, unknown>;\n\nlet config: ConfigT | Promise<ConfigT> | undefined;\n\n/**\n * Injects CSRF token into config (on client-side only).\n *\n * BEWARE: It mutates the argument, and also returns it as the result,\n * for chaining.\n */\nfunction injectCsrfToken(cfg: ConfigT): ConfigT {\n // The safeguard for \"document\" is necessary because in non-Node environments,\n // like React Native, IS_CLIENT_SIDE is \"true\", however \"document\" and a bunch\n // of other browser-world features are not available.\n if (IS_CLIENT_SIDE && typeof document !== 'undefined') {\n // eslint-disable-next-line no-param-reassign\n cfg.CSRF = parseCookie(document.cookie).csrfToken;\n }\n\n return cfg;\n}\n\nexport function getConfig(sync: true): ConfigT;\n\nexport function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T;\n\nexport function getConfig<T extends ConfigT>(sync?: boolean): Promise<T> | T {\n if (!config) {\n if (IS_CLIENT_SIDE) {\n const inj = clientGetInj();\n config = inj instanceof Promise\n ? inj.then((injection) => {\n const res = injectCsrfToken(injection.CONFIG ?? {});\n config = res;\n return res;\n })\n : injectCsrfToken(inj.CONFIG ?? {});\n } else {\n const weak = requireWeak<ConfigT>('config');\n if (!weak) throw Error('Internal error');\n config = weak;\n }\n }\n\n if (sync && (config instanceof Promise)) {\n throw Error('The config is not available yet');\n }\n\n return config as T;\n}\n"],"mappings":"AAAA,qBAEA,SAAS,WAAW,QAAQ,QAAQ;AAAC,OAE9B,YAAY;AAAA,SAEV,cAAc;AAAA,SACd,WAAW;AAIpB,IAAI,MAA8C,CAElD;AACA;AACA;AACA;AACA;AACA;AACA,SAAS,eAAe,CAAC,GAAY,EAAW;EAC9C;EACA;EACA;EACA,IAAI,cAAc,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;IACrD;IACA,GAAG,CAAC,IAAI,GAAG,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,SAAS;EACnD;EAEA,OAAO,GAAG;AACZ;AAMA,OAAO,SAAS,SAAS,CAAoB,IAAc,EAAkB;EAC3E,IAAI,CAAC,MAAM,EAAE;IACX,IAAI,cAAc,EAAE;MAClB,MAAM,GAAG,GAAG,YAAY,CAAC,CAAC;MAC1B,MAAM,GAAG,GAAG,YAAY,OAAO,GAC3B,GAAG,CAAC,IAAI,CAAE,SAAS,IAAK;QACxB,MAAM,GAAG,GAAG,eAAe,CAAC,SAAS,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC;QACnD,MAAM,GAAG,GAAG;QACZ,OAAO,GAAG;MACZ,CAAC,CAAC,GACA,eAAe,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,CAAC,CAAC;IACvC,CAAC,MAAM;MACL,MAAM,IAAI,GAAG,WAAW,CAAU,QAAQ,CAAC;MAC3C,IAAI,CAAC,IAAI,EAAE,MAAM,KAAK,CAAC,gBAAgB,CAAC;MACxC,MAAM,GAAG,IAAI;IACf;EACF;EAEA,IAAI,IAAI,IAAK,MAAM,YAAY,OAAQ,EAAE;IACvC,MAAM,KAAK,CAAC,iCAAiC,CAAC;EAChD;EAEA,OAAO,MAAM;AACf","ignoreList":[]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
import "core-js/modules/es.json.parse.js"; /**
|
|
2
|
+
* Jest environment for end-to-end SSR and client-side testing. It relies on
|
|
3
|
+
* the standard react-utils mechanics to execute SSR of given scene, and also
|
|
4
|
+
* Webpack build of the code for client-side execution, it further exposes
|
|
5
|
+
* Jsdom environment for the client-side testing of the outcomes.
|
|
6
|
+
*/ // BEWARE: The module is not imported into the JU module / the main assembly of
|
|
7
7
|
// the library, because doing so easily breaks stuff:
|
|
8
8
|
// 1) This module depends on Node-specific modules, which would make JU
|
|
9
9
|
// incompatible with JsDom if included into JU.
|
|
@@ -51,7 +51,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
51
51
|
*/
|
|
52
52
|
async loadWebpackConfig() {
|
|
53
53
|
const optionsString = this.pragmas["webpack-config-options"];
|
|
54
|
-
const options = optionsString ?
|
|
54
|
+
const options = optionsString ? JSON.parse(optionsString) : {};
|
|
55
55
|
defaults(options, {
|
|
56
56
|
context: this.testFolder,
|
|
57
57
|
fs: this.global.webpackOutputFs
|
|
@@ -61,10 +61,11 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
61
61
|
factory = "default" in factory ? factory.default : factory;
|
|
62
62
|
this.global.webpackConfig = factory(options);
|
|
63
63
|
const fs = this.global.webpackOutputFs;
|
|
64
|
+
if (!options.context) throw Error("Missing context");
|
|
64
65
|
let buildInfo = `${options.context}/.build-info`;
|
|
65
66
|
if (fs.existsSync(buildInfo)) {
|
|
66
67
|
buildInfo = fs.readFileSync(buildInfo, "utf8");
|
|
67
|
-
this.global.buildInfo =
|
|
68
|
+
this.global.buildInfo = JSON.parse(buildInfo);
|
|
68
69
|
}
|
|
69
70
|
} /**
|
|
70
71
|
* Executes Webpack build.
|
|
@@ -102,7 +103,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
102
103
|
const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);
|
|
103
104
|
const cp = fork(ssrModulePath);
|
|
104
105
|
const optionsString = this.pragmas["ssr-options"];
|
|
105
|
-
const options = optionsString ?
|
|
106
|
+
const options = optionsString ? JSON.parse(optionsString) : {};
|
|
106
107
|
options.buildInfo ??= this.global.buildInfo;
|
|
107
108
|
if (!this.webpackStats) throw Error("Missing Webpack stats");
|
|
108
109
|
options.chunkGroups = deduceChunkGroups(this.webpackStats);
|
|
@@ -130,7 +131,7 @@ export default class E2eSsrEnv extends JsdomEnv {
|
|
|
130
131
|
constructor(config, context) {
|
|
131
132
|
const pragmas = context.docblockPragmas;
|
|
132
133
|
const requestString = pragmas["ssr-request"];
|
|
133
|
-
const request = requestString ?
|
|
134
|
+
const request = requestString ? JSON.parse(requestString) : {};
|
|
134
135
|
request.url ??= "/"; // This ensures the initial JsDom URL matches the value we use for SSR.
|
|
135
136
|
set(config.projectConfig, "testEnvironmentOptions.url", `http://localhost${request.url}`);
|
|
136
137
|
super(config, context);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.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\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 */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\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?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async 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\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\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 await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\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 // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\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\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 // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\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 revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"4DAAA;AACA;AACA;AAC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AG,OAAO;IACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAEtB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,QAAQ,CAAC;MACP,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM;IACnD,CAAC,CAAC;EACJ;EAEA,MAAM,KAAK,GAAkB;IAC3B,MAAM,KAAK,CAAC,KAAK,CAAC,CAAC;IACnB,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;IACA,MAAM;MAAE;IAAa,CAAC,GAAG,MAAM,MAAM,gCAA6B;IAClE,YAAY,CAAC,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAAC,OAAO,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAM,QAAQ,GAAkB;IAC9B,OAAO,IAAI,CAAC,MAAM,CAAC,6BAA6B;IAEhD,MAAM,CAAC,CAAC;IAER,MAAM,KAAK,CAAC,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../../../../../src/shared/utils/jest/E2eSsrEnv/index.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\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 */\n\nimport { fork } from 'node:child_process';\nimport { access } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport JsdomEnv from 'jest-environment-jsdom';\nimport { defaults, set } from 'lodash-es';\nimport { Volume, createFsFromVolume } from 'memfs';\nimport webpack, { type Configuration, type Stats } from 'webpack';\n\nimport register, { revert } from '@babel/register';\n\nimport type {\n EnvironmentContext,\n JestEnvironmentConfig,\n} from '@jest/environment';\n\nimport { deduceChunkGroups } from 'server/renderer';\n\nimport type { LaunchT, ResultT } from './ssr';\n\nasync function findModule(module: string): Promise<string> {\n try {\n const res = `${module}.ts`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n try {\n const res = `${module}.js`;\n await access(res);\n return res;\n } catch {\n // NOOP\n }\n\n throw Error(`Module \"${module}\" was not found, neither as TS, nor as JS`);\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?: Stats;\n\n /**\n * Loads Webpack config, and exposes it to the environment via global\n * webpackConfig object.\n */\n private async 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\n let factory = await import(/* webpackChunkName: \"not-a-valid-chunk\" */\n path.resolve(this.rootDir, factoryPath)\n ) as (((ops: Configuration) => Configuration) | {\n default: (ops: Configuration) => Configuration;\n });\n\n factory = 'default' in factory ? factory.default : factory;\n\n this.global.webpackConfig = factory(options);\n\n const fs = this.global.webpackOutputFs;\n if (!options.context) throw Error('Missing context');\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 await this.loadWebpackConfig();\n\n if (!this.global.webpackConfig) throw Error('Failed to load Webpack config');\n const compiler = webpack(this.global.webpackConfig);\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 // NOTE: This is a TS module in the source code, and it turn into JS\n // module in the distributed code, after Babel compilation. As we rely\n // on it for the forked NodeJS process, we need to resolve the correct\n // extention ourselves (as NodeJS will hit the given path, without any\n // additional resolutions / transformations).\n const ssrModulePath = await findModule(`${import.meta.dirname}/ssr-preload`);\n\n const cp = fork(ssrModulePath);\n\n const optionsString = this.pragmas['ssr-options'] as string;\n const options = optionsString\n ? JSON.parse(optionsString) as Record<string, unknown>\n : {};\n\n options.buildInfo ??= this.global.buildInfo;\n\n if (!this.webpackStats) throw Error('Missing Webpack stats');\n\n options.chunkGroups = deduceChunkGroups(this.webpackStats);\n\n return new Promise((resolve, reject) => {\n cp.on('exit', (code) => {\n if (code) reject(Error('SSR process crashed'));\n });\n\n cp.on('message', (message: ResultT) => {\n this.global.ssrMarkup = message.markup;\n this.global.ssrOptions = options;\n this.global.ssrStatus = message.status;\n cp.kill();\n resolve();\n });\n\n if (!this.global.webpackConfig) throw Error('Missing Webpack config');\n\n cp.send({\n options,\n root: options.root === 'TEST' ? this.testFolder : process.cwd(),\n ssrRequest: this.ssrRequest,\n testFolder: this.testFolder,\n webpackConfig: this.global.webpackConfig,\n } satisfies LaunchT);\n });\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\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 // BEWARE: Anything imported prior to this register() call seems to be\n // transpiled again by Babel if loaded after this call. This causes very\n // confusing errors when testing the code dependent on some sort of contexts\n // (because loading a module again effectively creates a new context object,\n // which is not recognized by the code expecting another context instance).\n // That's why below we prefer dynamic imports for some React Utils methods.\n // BEWARE: Although we also do the registration inside SSR testing code,\n // we still need it here to correctly process imported Webpack configurations\n // (which are imported directly from this module).\n register({\n extensions: ['.js', '.jsx', '.ts', '.tsx', '.svg'],\n });\n }\n\n async setup(): Promise<void> {\n await super.setup();\n await this.runWebpack();\n\n // eslint-disable-next-line import/dynamic-import-chunkname\n const { setBuildInfo } = await import('../../isomorphy/buildInfo');\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 revert();\n\n await super.teardown();\n }\n}\n"],"mappings":"0CAAA;AACA;AACA;AACA;AACA;AACA,6CALA,CAOA;AACA;AACA;AACA;AACA;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C,QAAQ,CAAC;IAChD,IAAI,CAAC,OAAO,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC;IACjC,IAAI,CAAC,UAAU,GAAG,OAAO;IACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAEtB;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA;IACA,QAAQ,CAAC;MACP,UAAU,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM;IACnD,CAAC,CAAC;EACJ;EAEA,MAAM,KAAK,GAAkB;IAC3B,MAAM,KAAK,CAAC,KAAK,CAAC,CAAC;IACnB,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,CAEvB;IACA,MAAM;MAAE;IAAa,CAAC,GAAG,MAAM,MAAM,gCAA6B;IAClE,YAAY,CAAC,SAAS,EAAE,IAAI,CAAC;IAE7B,IAAI,IAAI,CAAC,OAAO,EAAE,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,CAAC,MAAM,CAAC,6BAA6B,GAAG,IAAI;EAClD;EAEA,MAAM,QAAQ,GAAkB;IAC9B,OAAO,IAAI,CAAC,MAAM,CAAC,6BAA6B;IAEhD,MAAM,CAAC,CAAC;IAER,MAAM,KAAK,CAAC,QAAQ,CAAC,CAAC;EACxB;AACF","ignoreList":[]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "core-js/modules/es.json.stringify.js"; /* global document */ /* eslint-disable import/no-extraneous-dependencies */
|
|
2
2
|
import mockdate from "mockdate";
|
|
3
3
|
import { act } from "react";
|
|
4
4
|
import { createRoot } from "react-dom/client";
|
|
@@ -58,10 +58,10 @@ export function mockAxios(handlers) {
|
|
|
58
58
|
...config,
|
|
59
59
|
adapter: ["xhr", "http", "fetch"]
|
|
60
60
|
}); // eslint-disable-next-line no-console
|
|
61
|
-
console.warn("Network request has not been mocked for a test.\n\nConfig:\n", config, "\n\nResult:\n",
|
|
61
|
+
console.warn("Network request has not been mocked for a test.\n\nConfig:\n", config, "\n\nResult:\n", JSON.stringify(res, null, 2));
|
|
62
62
|
} catch (e) {
|
|
63
63
|
// eslint-disable-next-line no-console
|
|
64
|
-
console.warn("Network request has not been mocked for a test, and failed.\n\nConfig:\n", config, "\n\nError\n",
|
|
64
|
+
console.warn("Network request has not been mocked for a test, and failed.\n\nConfig:\n", config, "\n\nError\n", JSON.stringify(e, null, 2));
|
|
65
65
|
throw e;
|
|
66
66
|
}
|
|
67
67
|
return res;
|
|
@@ -137,6 +137,7 @@ export function snapshot(element, options) {
|
|
|
137
137
|
if (!rejected) {
|
|
138
138
|
// TODO: These lines are the same as the lines below for sync variant of
|
|
139
139
|
// the function. We should split and reuse them in both places.
|
|
140
|
+
if (!res) throw Error("Missing render result");
|
|
140
141
|
const nodes = res.asFragment().childNodes;
|
|
141
142
|
expect(nodes.length > 1 ? [...nodes] : nodes[0]).toMatchSnapshot();
|
|
142
143
|
resolve(res);
|