@wordpress/components
Version:
UI components for WordPress.
1 lines • 7.8 kB
Source Map (JSON)
{"version":3,"file":"element-rect.mjs","names":[],"sources":["../../src/utils/element-rect.ts"],"sourcesContent":["/* eslint-disable jsdoc/require-param */\nimport { useLayoutEffect, useRef, useState } from '@wordpress/element';\nimport { useEvent, useResizeObserver } from '@wordpress/compose';\n\n/**\n * The position and dimensions of an element, relative to its offset parent.\n */\nexport type ElementOffsetRect = {\n\t/**\n\t * The element the rect belongs to.\n\t */\n\telement: HTMLElement | undefined;\n\t/**\n\t * The distance from the top edge of the offset parent to the top edge of\n\t * the element.\n\t */\n\ttop: number;\n\t/**\n\t * The distance from the right edge of the offset parent to the right edge\n\t * of the element.\n\t */\n\tright: number;\n\t/**\n\t * The distance from the bottom edge of the offset parent to the bottom edge\n\t * of the element.\n\t */\n\tbottom: number;\n\t/**\n\t * The distance from the left edge of the offset parent to the left edge of\n\t * the element.\n\t */\n\tleft: number;\n\t/**\n\t * The width of the element.\n\t */\n\twidth: number;\n\t/**\n\t * The height of the element.\n\t */\n\theight: number;\n};\n\n/**\n * An `ElementOffsetRect` object with all values set to zero.\n */\nexport const NULL_ELEMENT_OFFSET_RECT = {\n\telement: undefined,\n\ttop: 0,\n\tright: 0,\n\tbottom: 0,\n\tleft: 0,\n\twidth: 0,\n\theight: 0,\n} satisfies ElementOffsetRect;\n\n/**\n * Returns the position and dimensions of an element, relative to its offset\n * parent, with subpixel precision. Values reflect the real measures before any\n * potential scaling distortions along the X and Y axes.\n *\n * Useful in contexts where plain `getBoundingClientRect` calls or `ResizeObserver`\n * entries are not suitable, such as when the element is transformed, and when\n * `element.offset<Top|Left|Width|Height>` methods are not precise enough.\n *\n * **Note:** in some contexts, like when the scale is 0, this method will fail\n * because it's impossible to calculate a scaling ratio. When that happens, it\n * will return `undefined`.\n */\nexport function getElementOffsetRect(\n\telement: HTMLElement\n): ElementOffsetRect | undefined {\n\t// Position and dimension values computed with `getBoundingClientRect` have\n\t// subpixel precision, but are affected by distortions since they represent\n\t// the \"real\" measures, or in other words, the actual final values as rendered\n\t// by the browser.\n\tconst rect = element.getBoundingClientRect();\n\tif ( rect.width === 0 || rect.height === 0 ) {\n\t\treturn;\n\t}\n\tconst offsetParent = element.offsetParent;\n\tconst offsetParentRect =\n\t\toffsetParent?.getBoundingClientRect() ?? NULL_ELEMENT_OFFSET_RECT;\n\tconst offsetParentScrollX = offsetParent?.scrollLeft ?? 0;\n\tconst offsetParentScrollY = offsetParent?.scrollTop ?? 0;\n\n\t// Computed widths and heights have subpixel precision, and are not affected\n\t// by distortions.\n\tconst computedWidth = parseFloat( getComputedStyle( element ).width );\n\tconst computedHeight = parseFloat( getComputedStyle( element ).height );\n\n\t// We can obtain the current scale factor for the element by comparing \"computed\"\n\t// dimensions with the \"real\" ones.\n\tconst scaleX = computedWidth / rect.width;\n\tconst scaleY = computedHeight / rect.height;\n\n\treturn {\n\t\telement,\n\t\t// To obtain the adjusted values for the position:\n\t\t// 1. Compute the element's position relative to the offset parent.\n\t\t// 2. Correct for the scale factor.\n\t\t// 3. Adjust for the scroll position of the offset parent.\n\t\ttop:\n\t\t\t( rect.top - offsetParentRect?.top ) * scaleY + offsetParentScrollY,\n\t\tright:\n\t\t\t( offsetParentRect?.right - rect.right ) * scaleX -\n\t\t\toffsetParentScrollX,\n\t\tbottom:\n\t\t\t( offsetParentRect?.bottom - rect.bottom ) * scaleY -\n\t\t\toffsetParentScrollY,\n\t\tleft:\n\t\t\t( rect.left - offsetParentRect?.left ) * scaleX +\n\t\t\toffsetParentScrollX,\n\t\t// Computed dimensions don't need any adjustments.\n\t\twidth: computedWidth,\n\t\theight: computedHeight,\n\t};\n}\n\nconst POLL_RATE = 100;\n\n/**\n * Tracks the position and dimensions of an element, relative to its offset\n * parent. The element can be changed dynamically.\n *\n * When no element is provided (`null` or `undefined`), the hook will return\n * a \"null\" rect, in which all values are `0` and `element` is `undefined`.\n *\n * **Note:** sometimes, the measurement will fail (see `getElementOffsetRect`'s\n * documentation for more details). When that happens, this hook will attempt\n * to measure again after a frame, and if that fails, it will poll every 100\n * milliseconds until it succeeds.\n */\nexport function useTrackElementOffsetRect(\n\ttargetElement: HTMLElement | undefined | null,\n\tdeps: unknown[] = []\n) {\n\tconst [ indicatorPosition, setIndicatorPosition ] =\n\t\tuseState< ElementOffsetRect >( NULL_ELEMENT_OFFSET_RECT );\n\tconst intervalRef = useRef< ReturnType< typeof setInterval > >( undefined );\n\n\tconst measure = useEvent( () => {\n\t\t// Check that the targetElement is still attached to the DOM, in case\n\t\t// it was removed since the last `measure` call.\n\t\tif ( targetElement && targetElement.isConnected ) {\n\t\t\tconst elementOffsetRect = getElementOffsetRect( targetElement );\n\t\t\tif ( elementOffsetRect ) {\n\t\t\t\tsetIndicatorPosition( elementOffsetRect );\n\t\t\t\tclearInterval( intervalRef.current );\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} else {\n\t\t\tclearInterval( intervalRef.current );\n\t\t}\n\t\treturn false;\n\t} );\n\n\tconst setElement = useResizeObserver( () => {\n\t\tif ( ! measure() ) {\n\t\t\trequestAnimationFrame( () => {\n\t\t\t\tif ( ! measure() ) {\n\t\t\t\t\tintervalRef.current = setInterval( measure, POLL_RATE );\n\t\t\t\t}\n\t\t\t} );\n\t\t}\n\t} );\n\n\tuseLayoutEffect( () => {\n\t\tsetElement( targetElement );\n\t\tif ( ! targetElement ) {\n\t\t\tsetIndicatorPosition( NULL_ELEMENT_OFFSET_RECT );\n\t\t}\n\t}, [ setElement, targetElement ] );\n\n\t// Escape hatch to force a remeasurement when something else changes rather\n\t// than the target elements' ref or size (for example, the target element\n\t// can change its position within the tablist).\n\tuseLayoutEffect( () => {\n\t\tmeasure();\n\t\t// `measure` is a stable function, so it's safe to omit it from the deps array.\n\t\t// deps can't be statically analyzed by ESLint\n\t}, deps );\n\n\treturn indicatorPosition;\n}\n\n/* eslint-enable jsdoc/require-param */\n"],"mappings":";;;;;;AA6CA,MAAa,2BAA2B;CACvC,SAAS,KAAA;CACT,KAAK;C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