Files
web/apps/scandic-web/hooks/useStickyPosition.ts
Anton Gunnarsson 80100e7631 Merged in monorepo-step-1 (pull request #1080)
Migrate to a monorepo setup - step 1

* Move web to subfolder /apps/scandic-web

* Yarn + transitive deps

- Move to yarn
- design-system package removed for now since yarn doesn't
support the parameter for token (ie project currently broken)
- Add missing transitive dependencies as Yarn otherwise
prevents these imports
- VS Code doesn't pick up TS path aliases unless you open
/apps/scandic-web instead of root (will be fixed with monorepo)

* Pin framer-motion to temporarily fix typing issue

https://github.com/adobe/react-spectrum/issues/7494

* Pin zod to avoid typ error

There seems to have been a breaking change in the types
returned by zod where error is now returned as undefined
instead of missing in the type. We should just handle this
but to avoid merge conflicts just pin the dependency for
now.

* Pin react-intl version

Pin version of react-intl to avoid tiny type issue where formatMessage
does not accept a generic any more. This will be fixed in a future
commit, but to avoid merge conflicts just pin for now.

* Pin typescript version

Temporarily pin version as newer versions as stricter and results in
a type error. Will be fixed in future commit after merge.

* Setup workspaces

* Add design-system as a monorepo package

* Remove unused env var DESIGN_SYSTEM_ACCESS_TOKEN

* Fix husky for monorepo setup

* Update netlify.toml

* Add lint script to root package.json

* Add stub readme

* Fix react-intl formatMessage types

* Test netlify.toml in root

* Remove root toml

* Update netlify.toml publish path

* Remove package-lock.json

* Update build for branch/preview builds


Approved-by: Linus Flood
2025-02-26 10:36:17 +00:00

153 lines
5.3 KiB
TypeScript

"use client"
import { useCallback, useEffect, useState } from "react"
import { env } from "@/env/client"
import useStickyPositionStore, {
type StickyElement,
type StickyElementNameEnum,
} from "@/stores/sticky-position"
import { debounce } from "@/utils/debounce"
interface UseStickyPositionProps {
ref?: React.RefObject<HTMLElement>
name?: StickyElementNameEnum
group?: string
}
// Global singleton ResizeObserver to observe the body only once
let resizeObserver: ResizeObserver | null = null
/**
* Custom hook to manage sticky positioning of elements within a page.
* This hook registers an element as sticky, calculates its top offset based on
* other registered sticky elements, and updates the element's position dynamically.
*
* @param {UseStickyPositionProps} props - The properties for configuring the hook.
* @param {React.RefObject<HTMLElement>} [props.ref] - A reference to the HTML element that should be sticky. Is optional to allow for other components to only get the height of the sticky elements.
* @param {StickyElementNameEnum} [props.name] - A unique name for the sticky element, used for tracking.
* @param {string} [props.group] - An optional group identifier to make multiple elements share the same top offset. Defaults to the name if not provided.
*
* @returns {Object} An object containing information about the sticky elements.
* @returns {number | null} [returns.currentHeight] - The current height of the registered sticky element, or `null` if not available.
* @returns {Array<StickyElement>} [returns.allElements] - An array containing the heights, names, and groups of all registered sticky elements.
*/
export default function useStickyPosition({
ref,
name,
group,
}: UseStickyPositionProps) {
const {
registerSticky,
unregisterSticky,
stickyElements,
updateHeights,
getAllElements,
} = useStickyPositionStore()
/* Used for Current mobile header since that doesn't use this hook.
*
* Instead, calculate if the mobile header is shown and add the height of
* that "manually" to all offsets using this hook.
*
* TODO: Remove this and just use 0 when the current header has been removed.
*/
const [baseTopOffset, setBaseTopOffset] = useState(0)
useEffect(() => {
if (ref && name) {
// Register the sticky element with the given ref, name, and group.
// If the group is not provided, it defaults to the value of the name.
// This registration keeps track of the sticky element and its height.
registerSticky(ref, name, group || name)
// Update the heights of all registered sticky elements.
// This ensures that the height information is accurate and up-to-date.
updateHeights()
return () => {
unregisterSticky(ref)
}
}
}, [ref, name, group, registerSticky, unregisterSticky, updateHeights])
/**
* Get the top position of element at index `index`
*
* Calculates the total height of all sticky elements _before_ the element
* at position `index`. If `index` is not provided all elements are included
* in the calculation. Takes grouping into consideration (only counts one
* element per group)
*/
const getTopOffset = useCallback(
(index?: number) => {
// Get the group name of the current sticky element.
// This will be used to only count one element per group.
const elementGroup = index ? stickyElements[index].group : undefined
return stickyElements
.slice(0, index)
.reduce<StickyElement[]>((acc, curr) => {
if (
(elementGroup && curr.group === elementGroup) ||
acc.some((elem: StickyElement) => elem.group === curr.group)
) {
return acc
}
return [...acc, curr]
}, [])
.reduce((acc, el) => acc + el.height, baseTopOffset)
},
[baseTopOffset, stickyElements]
)
useEffect(() => {
if (ref) {
// Find the index of the current sticky element in the array of stickyElements.
// This helps us determine its position relative to other sticky elements.
const index = stickyElements.findIndex((el) => el.ref === ref)
if (index !== -1 && ref.current) {
const topOffset = getTopOffset(index)
// Apply the calculated top offset to the current element's style.
// This positions the element at the correct location within the document.
ref.current.style.top = `${topOffset}px`
}
}
}, [baseTopOffset, stickyElements, ref, getTopOffset])
useEffect(() => {
if (!resizeObserver) {
const debouncedResizeHandler = debounce(() => {
updateHeights()
// Only do this special handling if we have the current header
if (env.NEXT_PUBLIC_HIDE_FOR_NEXT_RELEASE) {
if (document.body.clientWidth > 950) {
setBaseTopOffset(0)
} else {
setBaseTopOffset(52.41) // The height of current mobile header
}
}
}, 100)
resizeObserver = new ResizeObserver(debouncedResizeHandler)
}
resizeObserver.observe(document.body)
return () => {
if (resizeObserver) {
resizeObserver.unobserve(document.body)
}
}
}, [updateHeights])
return {
currentHeight: ref?.current?.offsetHeight || null,
allElements: getAllElements(),
getTopOffset,
}
}