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
This commit is contained in:
committed by
Linus Flood
parent
667cab6fb6
commit
80100e7631
23
apps/scandic-web/hooks/booking/useAvailablePaymentOptions.ts
Normal file
23
apps/scandic-web/hooks/booking/useAvailablePaymentOptions.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
import { PaymentMethodEnum } from "@/constants/booking"
|
||||
|
||||
export function useAvailablePaymentOptions(
|
||||
otherPaymentOptions: PaymentMethodEnum[]
|
||||
) {
|
||||
const [availablePaymentOptions, setAvailablePaymentOptions] = useState(
|
||||
otherPaymentOptions.filter(
|
||||
(option) => option !== PaymentMethodEnum.applePay
|
||||
)
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
if (window.ApplePaySession) {
|
||||
setAvailablePaymentOptions(otherPaymentOptions)
|
||||
}
|
||||
}, [otherPaymentOptions, setAvailablePaymentOptions])
|
||||
|
||||
return availablePaymentOptions
|
||||
}
|
||||
52
apps/scandic-web/hooks/booking/useHandleBookingStatus.ts
Normal file
52
apps/scandic-web/hooks/booking/useHandleBookingStatus.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
"use client"
|
||||
|
||||
import { useRef } from "react"
|
||||
|
||||
import { trpc } from "@/lib/trpc/client"
|
||||
|
||||
import type { BookingStatusEnum } from "@/constants/booking"
|
||||
|
||||
export function useHandleBookingStatus({
|
||||
confirmationNumber,
|
||||
expectedStatus,
|
||||
maxRetries,
|
||||
retryInterval,
|
||||
enabled,
|
||||
}: {
|
||||
confirmationNumber: string | null
|
||||
expectedStatus: BookingStatusEnum
|
||||
maxRetries: number
|
||||
retryInterval: number
|
||||
enabled: boolean
|
||||
}) {
|
||||
const retries = useRef(0)
|
||||
|
||||
const query = trpc.booking.status.useQuery(
|
||||
{ confirmationNumber: confirmationNumber ?? "" },
|
||||
{
|
||||
enabled,
|
||||
refetchInterval: (query) => {
|
||||
retries.current = query.state.dataUpdateCount
|
||||
|
||||
if (query.state.error || query.state.dataUpdateCount >= maxRetries) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (query.state.data?.reservationStatus === expectedStatus) {
|
||||
return false
|
||||
}
|
||||
|
||||
return retryInterval
|
||||
},
|
||||
refetchIntervalInBackground: true,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnMount: false,
|
||||
retry: false,
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
...query,
|
||||
isTimeout: retries.current >= maxRetries,
|
||||
}
|
||||
}
|
||||
65
apps/scandic-web/hooks/booking/usePaymentFailedToast.ts
Normal file
65
apps/scandic-web/hooks/booking/usePaymentFailedToast.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
"use client"
|
||||
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation"
|
||||
import { useCallback, useEffect } from "react"
|
||||
import { useIntl } from "react-intl"
|
||||
|
||||
import { PaymentErrorCodeEnum } from "@/constants/booking"
|
||||
import { useEnterDetailsStore } from "@/stores/enter-details"
|
||||
|
||||
import { toast } from "@/components/TempDesignSystem/Toasts"
|
||||
|
||||
export function usePaymentFailedToast() {
|
||||
const updateSearchParams = useEnterDetailsStore(
|
||||
(state) => state.actions.updateSeachParamString
|
||||
)
|
||||
const intl = useIntl()
|
||||
const searchParams = useSearchParams()
|
||||
const pathname = usePathname()
|
||||
const router = useRouter()
|
||||
|
||||
const getErrorMessage = useCallback(
|
||||
(errorCode: PaymentErrorCodeEnum) => {
|
||||
switch (errorCode) {
|
||||
case PaymentErrorCodeEnum.Cancelled:
|
||||
return intl.formatMessage({
|
||||
id: "You have now cancelled your payment.",
|
||||
})
|
||||
default:
|
||||
return intl.formatMessage({
|
||||
id: "We had an issue processing your booking. Please try again. No charges have been made.",
|
||||
})
|
||||
}
|
||||
},
|
||||
[intl]
|
||||
)
|
||||
|
||||
const errorCodeString = searchParams.get("errorCode")
|
||||
const errorCode = Number(errorCodeString) as PaymentErrorCodeEnum
|
||||
const errorMessage = getErrorMessage(errorCode)
|
||||
|
||||
useEffect(() => {
|
||||
if (!errorCode) return
|
||||
|
||||
// setTimeout is needed to show toasts on page load: https://sonner.emilkowal.ski/toast#render-toast-on-page-load
|
||||
setTimeout(() => {
|
||||
const toastType =
|
||||
errorCode === PaymentErrorCodeEnum.Cancelled ? "warning" : "error"
|
||||
|
||||
toast[toastType](errorMessage)
|
||||
})
|
||||
|
||||
const queryParams = new URLSearchParams(searchParams.toString())
|
||||
queryParams.delete("errorCode")
|
||||
|
||||
updateSearchParams(queryParams.toString())
|
||||
router.push(`${pathname}?${queryParams.toString()}`)
|
||||
}, [
|
||||
searchParams,
|
||||
pathname,
|
||||
errorCode,
|
||||
errorMessage,
|
||||
router,
|
||||
updateSearchParams,
|
||||
])
|
||||
}
|
||||
62
apps/scandic-web/hooks/booking/useScrollToActiveSection.ts
Normal file
62
apps/scandic-web/hooks/booking/useScrollToActiveSection.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import { useCallback, useEffect } from "react"
|
||||
import { useMediaQuery } from "usehooks-ts"
|
||||
|
||||
import type { StepEnum } from "@/types/enums/step"
|
||||
|
||||
export default function useScrollToActiveSection(
|
||||
step: StepEnum,
|
||||
steps: StepEnum[],
|
||||
isActive: boolean
|
||||
) {
|
||||
const isMobile = useMediaQuery("(max-width: 768px)")
|
||||
|
||||
const handleScroll = useCallback(() => {
|
||||
if (!isMobile) {
|
||||
return
|
||||
}
|
||||
|
||||
const currentElement = document.querySelector<HTMLElement>(
|
||||
`[data-step="${step}"]`
|
||||
)
|
||||
const prevOpenElement =
|
||||
document.querySelector<HTMLElement>(`[data-open="true"]`)
|
||||
|
||||
const currentStepIndex = steps.indexOf(step)
|
||||
const prevStep = prevOpenElement
|
||||
? (Number(prevOpenElement?.dataset.step) as StepEnum)
|
||||
: null
|
||||
const prevStepIndex = prevStep ? steps.indexOf(prevStep) : null
|
||||
|
||||
if (currentElement) {
|
||||
const BOOKING_WIDGET_OFFSET = 71
|
||||
|
||||
const prevElementContent = prevOpenElement?.querySelector("header + div")
|
||||
|
||||
let collapsedSpace = 0
|
||||
if (
|
||||
prevElementContent &&
|
||||
prevStepIndex &&
|
||||
prevStepIndex < currentStepIndex
|
||||
) {
|
||||
collapsedSpace = prevElementContent.clientHeight
|
||||
}
|
||||
|
||||
const currentElementTop =
|
||||
currentElement.getBoundingClientRect().top + window.scrollY
|
||||
|
||||
const scrollTarget = Math.round(
|
||||
currentElementTop - BOOKING_WIDGET_OFFSET - collapsedSpace
|
||||
)
|
||||
|
||||
window.scrollTo({
|
||||
top: scrollTarget,
|
||||
behavior: "smooth",
|
||||
})
|
||||
}
|
||||
}, [step, steps, isMobile])
|
||||
|
||||
useEffect(() => {
|
||||
if (!isActive) return
|
||||
handleScroll()
|
||||
}, [isActive, handleScroll])
|
||||
}
|
||||
53
apps/scandic-web/hooks/maps/use-map-viewport.ts
Normal file
53
apps/scandic-web/hooks/maps/use-map-viewport.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
// Hook to use supercluster with @visgl/react-google-map.
|
||||
// Implemented according to https://github.com/visgl/react-google-maps/tree/main/examples/custom-marker-clustering
|
||||
|
||||
import { useMap } from "@vis.gl/react-google-maps"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
import type { BBox } from "geojson"
|
||||
|
||||
type MapViewportOptions = {
|
||||
padding?: number
|
||||
}
|
||||
|
||||
export function useMapViewport({ padding = 0 }: MapViewportOptions = {}) {
|
||||
const map = useMap()
|
||||
const [bbox, setBbox] = useState<BBox>([-180, -90, 180, 90])
|
||||
const [zoom, setZoom] = useState(0)
|
||||
|
||||
// observe the map to get current bounds
|
||||
useEffect(() => {
|
||||
if (!map) return
|
||||
|
||||
const listener = map.addListener("bounds_changed", () => {
|
||||
const bounds = map.getBounds()
|
||||
const zoom = map.getZoom()
|
||||
const projection = map.getProjection()
|
||||
|
||||
if (!bounds || !zoom || !projection) return
|
||||
|
||||
const sw = bounds.getSouthWest()
|
||||
const ne = bounds.getNorthEast()
|
||||
|
||||
const paddingDegrees = degreesPerPixel(zoom) * padding
|
||||
|
||||
const n = Math.min(90, ne.lat() + paddingDegrees)
|
||||
const s = Math.max(-90, sw.lat() - paddingDegrees)
|
||||
|
||||
const w = sw.lng() - paddingDegrees
|
||||
const e = ne.lng() + paddingDegrees
|
||||
|
||||
setBbox([w, s, e, n])
|
||||
setZoom(zoom)
|
||||
})
|
||||
|
||||
return () => listener.remove()
|
||||
}, [map, padding])
|
||||
|
||||
return { bbox, zoom }
|
||||
}
|
||||
|
||||
function degreesPerPixel(zoomLevel: number) {
|
||||
// 360° divided by the number of pixels at the zoom-level
|
||||
return 360 / (Math.pow(2, zoomLevel) * 256)
|
||||
}
|
||||
42
apps/scandic-web/hooks/maps/use-supercluster.ts
Normal file
42
apps/scandic-web/hooks/maps/use-supercluster.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { useEffect, useMemo, useReducer } from "react"
|
||||
import Supercluster, {type ClusterProperties } from "supercluster"
|
||||
|
||||
import { useMapViewport } from "./use-map-viewport"
|
||||
|
||||
import type { FeatureCollection, GeoJsonProperties, Point } from "geojson"
|
||||
|
||||
export function useSupercluster<T extends GeoJsonProperties>(
|
||||
geojson: FeatureCollection<Point, T>,
|
||||
superclusterOptions: Supercluster.Options<T, ClusterProperties>
|
||||
) {
|
||||
// create the clusterer and keep it
|
||||
const clusterer = useMemo(() => {
|
||||
return new Supercluster(superclusterOptions)
|
||||
}, [superclusterOptions])
|
||||
|
||||
// version-number for the data loaded into the clusterer
|
||||
// (this is needed to trigger updating the clusters when data was changed)
|
||||
const [version, dataWasUpdated] = useReducer((x: number) => x + 1, 0)
|
||||
|
||||
// when data changes, load it into the clusterer
|
||||
useEffect(() => {
|
||||
clusterer.load(geojson.features)
|
||||
dataWasUpdated()
|
||||
}, [clusterer, geojson])
|
||||
|
||||
// get bounding-box and zoomlevel from the map
|
||||
const { bbox, zoom } = useMapViewport({ padding: 100 })
|
||||
|
||||
// retrieve the clusters within the current viewport
|
||||
const clusters = useMemo(() => {
|
||||
// don't try to read clusters before data was loaded into the clusterer (version===0),
|
||||
// otherwise getClusters will crash
|
||||
if (!clusterer || version === 0) return []
|
||||
|
||||
return clusterer.getClusters(bbox, zoom)
|
||||
}, [version, clusterer, bbox, zoom])
|
||||
|
||||
return {
|
||||
clusters,
|
||||
}
|
||||
}
|
||||
21
apps/scandic-web/hooks/useCheckIfExternalLink.ts
Normal file
21
apps/scandic-web/hooks/useCheckIfExternalLink.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { useMemo } from "react"
|
||||
|
||||
export const useCheckIfExternalLink = (url: string) => {
|
||||
return useMemo(() => {
|
||||
if (typeof window !== "undefined" && url?.length) {
|
||||
try {
|
||||
const hostName = window.location.hostname
|
||||
const newURL = new URL(url)
|
||||
|
||||
const hostsMatch = hostName === newURL.hostname
|
||||
const langRouteRegex = /^\/[a-zA-Z]{2}\//
|
||||
|
||||
return !hostsMatch || !langRouteRegex.test(newURL.pathname)
|
||||
} catch {
|
||||
// Don't care. Expecting internal url (#, /my-pages/overview, etc)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}, [url])
|
||||
}
|
||||
24
apps/scandic-web/hooks/useClickOutside.ts
Normal file
24
apps/scandic-web/hooks/useClickOutside.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import { useEffect } from "react"
|
||||
|
||||
export default function useClickOutside(
|
||||
ref: React.RefObject<HTMLElement>,
|
||||
isOpen: boolean,
|
||||
callback: () => void
|
||||
) {
|
||||
useEffect(() => {
|
||||
function handleClickOutside(evt: Event) {
|
||||
const target = evt.target as HTMLElement
|
||||
if (ref.current && target && !ref.current.contains(target) && isOpen) {
|
||||
callback()
|
||||
}
|
||||
}
|
||||
|
||||
if (isOpen) {
|
||||
document.addEventListener("click", handleClickOutside)
|
||||
}
|
||||
|
||||
return () => {
|
||||
document.removeEventListener("click", handleClickOutside)
|
||||
}
|
||||
}, [ref, isOpen, callback])
|
||||
}
|
||||
11
apps/scandic-web/hooks/useHandleKeyPress.ts
Normal file
11
apps/scandic-web/hooks/useHandleKeyPress.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
"use client"
|
||||
import { useEffect } from "react"
|
||||
|
||||
export function useHandleKeyPress(callback: (event: KeyboardEvent) => void) {
|
||||
useEffect(() => {
|
||||
window.addEventListener("keydown", callback)
|
||||
return () => {
|
||||
window.removeEventListener("keydown", callback)
|
||||
}
|
||||
}, [callback])
|
||||
}
|
||||
12
apps/scandic-web/hooks/useHandleKeyUp.ts
Normal file
12
apps/scandic-web/hooks/useHandleKeyUp.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect } from "react"
|
||||
|
||||
export function useHandleKeyUp(callback: (event: KeyboardEvent) => void) {
|
||||
useEffect(() => {
|
||||
window.addEventListener("keyup", callback)
|
||||
return () => {
|
||||
window.removeEventListener("keyup", callback)
|
||||
}
|
||||
}, [callback])
|
||||
}
|
||||
15
apps/scandic-web/hooks/useHash.tsx
Normal file
15
apps/scandic-web/hooks/useHash.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
"use client"
|
||||
|
||||
import { useParams } from "next/navigation"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
export default function useHash() {
|
||||
const [hash, setHash] = useState<string | undefined>(undefined)
|
||||
const params = useParams()
|
||||
|
||||
useEffect(() => {
|
||||
setHash(window.location.hash)
|
||||
}, [params])
|
||||
|
||||
return hash?.slice(1)
|
||||
}
|
||||
18
apps/scandic-web/hooks/useInitializeFiltersFromUrl.ts
Normal file
18
apps/scandic-web/hooks/useInitializeFiltersFromUrl.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
import { useSearchParams } from "next/navigation"
|
||||
import { useEffect } from "react"
|
||||
|
||||
import { useHotelFilterStore } from "@/stores/hotel-filters"
|
||||
|
||||
export default function useInitializeFiltersFromUrl() {
|
||||
const searchParams = useSearchParams()
|
||||
const setFilters = useHotelFilterStore((state) => state.setFilters)
|
||||
|
||||
useEffect(() => {
|
||||
const filtersFromUrl = searchParams.get("filters")
|
||||
if (filtersFromUrl) {
|
||||
setFilters(filtersFromUrl.split(","))
|
||||
} else {
|
||||
setFilters([])
|
||||
}
|
||||
}, [searchParams, setFilters])
|
||||
}
|
||||
18
apps/scandic-web/hooks/useLang.ts
Normal file
18
apps/scandic-web/hooks/useLang.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
"use client"
|
||||
import { useParams } from "next/navigation"
|
||||
|
||||
import { Lang } from "@/constants/languages"
|
||||
|
||||
import { languageSchema } from "@/utils/languages"
|
||||
|
||||
import type { LangParams } from "@/types/params"
|
||||
|
||||
/**
|
||||
* A hook to get the current lang from the URL
|
||||
*/
|
||||
export default function useLang() {
|
||||
const { lang } = useParams<LangParams>()
|
||||
|
||||
const parsedLang = languageSchema.safeParse(lang)
|
||||
return parsedLang.success ? parsedLang.data : Lang.en
|
||||
}
|
||||
27
apps/scandic-web/hooks/useLazyPathname.ts
Normal file
27
apps/scandic-web/hooks/useLazyPathname.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
"use client"
|
||||
import { usePathname, useSearchParams } from "next/navigation"
|
||||
import { useEffect, useState } from "react"
|
||||
|
||||
/*** This hook is used to get the current pathname (as reflected in window.location.href) of the page. During ssr, the value from usePathname()
|
||||
* is the value return from NextResponse.rewrite() (e.g. the path from the app directory) instead of the actual pathname from the URL.
|
||||
*/
|
||||
export function useLazyPathname({ includeSearchParams = false } = {}) {
|
||||
const pathName = usePathname()
|
||||
const searchParams = useSearchParams()
|
||||
|
||||
const [updatedPathName, setUpdatedPathName] = useState<string | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!includeSearchParams) {
|
||||
setUpdatedPathName(pathName)
|
||||
} else {
|
||||
const updatedPathname = searchParams.size
|
||||
? `${pathName}?${searchParams.toString()}`
|
||||
: pathName
|
||||
|
||||
setUpdatedPathName(updatedPathname)
|
||||
}
|
||||
}, [pathName, searchParams, includeSearchParams])
|
||||
|
||||
return updatedPathName
|
||||
}
|
||||
34
apps/scandic-web/hooks/useScrollShadows.ts
Normal file
34
apps/scandic-web/hooks/useScrollShadows.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import { useEffect, useRef, useState } from "react"
|
||||
|
||||
export default function useScrollShadows<T extends HTMLElement>() {
|
||||
const containerRef = useRef<T>(null)
|
||||
const [showLeftShadow, setShowLeftShadow] = useState<boolean>(false)
|
||||
const [showRightShadow, setShowRightShadow] = useState<boolean>(false)
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
const container = containerRef.current
|
||||
if (!container) return
|
||||
|
||||
setShowLeftShadow(container.scrollLeft > 0)
|
||||
setShowRightShadow(
|
||||
container.scrollLeft < container.scrollWidth - container.clientWidth
|
||||
)
|
||||
}
|
||||
|
||||
const container = containerRef.current
|
||||
if (container) {
|
||||
container.addEventListener("scroll", handleScroll)
|
||||
}
|
||||
|
||||
handleScroll()
|
||||
|
||||
return () => {
|
||||
if (container) {
|
||||
container.removeEventListener("scroll", handleScroll)
|
||||
}
|
||||
}
|
||||
}, [])
|
||||
|
||||
return { containerRef, showLeftShadow, showRightShadow }
|
||||
}
|
||||
67
apps/scandic-web/hooks/useScrollSpy.ts
Normal file
67
apps/scandic-web/hooks/useScrollSpy.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
|
||||
|
||||
export default function useScrollSpy(
|
||||
sectionIds: string[],
|
||||
options: IntersectionObserverInit = {}
|
||||
): {
|
||||
activeSectionId: string
|
||||
pauseScrollSpy: () => void
|
||||
} {
|
||||
const [activeSectionId, setActiveSectionId] = useState("")
|
||||
const observerIsInactive = useRef(false)
|
||||
|
||||
const mergedOptions = useMemo(
|
||||
() => ({
|
||||
root: null,
|
||||
// Make sure only to activate the section when it reaches the top of the viewport.
|
||||
// A negative value for rootMargin shrinks the root bounding box inward,
|
||||
// meaning elements will only be considered intersecting when they are further inside the viewport.
|
||||
rootMargin: "-15% 0% -85% 0%",
|
||||
threshold: 0,
|
||||
...options,
|
||||
}),
|
||||
[options]
|
||||
)
|
||||
|
||||
const handleIntersection = useCallback(
|
||||
(entries: IntersectionObserverEntry[]) => {
|
||||
if (observerIsInactive.current) {
|
||||
return
|
||||
}
|
||||
|
||||
const intersectingEntries: IntersectionObserverEntry[] = []
|
||||
entries.forEach((e) => {
|
||||
if (e.isIntersecting) {
|
||||
intersectingEntries.push(e)
|
||||
}
|
||||
})
|
||||
if (intersectingEntries.length) {
|
||||
setActiveSectionId(intersectingEntries[0].target.id)
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(handleIntersection, mergedOptions)
|
||||
const elements = sectionIds
|
||||
.map((id) => document.getElementById(id))
|
||||
.filter((el): el is HTMLElement => !!el)
|
||||
|
||||
elements.forEach((element) => {
|
||||
observer.observe(element)
|
||||
})
|
||||
|
||||
return () => elements.forEach((el) => el && observer.unobserve(el))
|
||||
}, [sectionIds, mergedOptions, handleIntersection])
|
||||
|
||||
const pauseScrollSpy = () => {
|
||||
observerIsInactive.current = true
|
||||
|
||||
setTimeout(() => {
|
||||
observerIsInactive.current = false
|
||||
}, 500)
|
||||
}
|
||||
|
||||
return { activeSectionId, pauseScrollSpy }
|
||||
}
|
||||
46
apps/scandic-web/hooks/useScrollToTop.ts
Normal file
46
apps/scandic-web/hooks/useScrollToTop.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { type RefObject, useEffect, useState } from "react"
|
||||
|
||||
interface UseScrollToTopProps {
|
||||
threshold: number
|
||||
elementRef?: RefObject<HTMLElement>
|
||||
refScrollable?: boolean
|
||||
}
|
||||
|
||||
export function useScrollToTop({
|
||||
threshold,
|
||||
elementRef,
|
||||
refScrollable,
|
||||
}: UseScrollToTopProps) {
|
||||
const [showBackToTop, setShowBackToTop] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const element =
|
||||
refScrollable && elementRef?.current ? elementRef?.current : window
|
||||
|
||||
function handleScroll() {
|
||||
let position = window.scrollY
|
||||
if (elementRef?.current) {
|
||||
position = refScrollable
|
||||
? elementRef.current.scrollTop
|
||||
: elementRef.current.getBoundingClientRect().top * -1
|
||||
}
|
||||
setShowBackToTop(position > threshold)
|
||||
}
|
||||
|
||||
element.addEventListener("scroll", handleScroll, { passive: true })
|
||||
return () => element.removeEventListener("scroll", handleScroll)
|
||||
}, [threshold, elementRef, refScrollable])
|
||||
|
||||
function scrollToTop() {
|
||||
if (elementRef?.current) {
|
||||
if (refScrollable) {
|
||||
elementRef.current.scrollTo({ top: 0, behavior: "smooth" })
|
||||
}
|
||||
window.scrollTo({ top: elementRef.current.offsetTop, behavior: "smooth" })
|
||||
} else {
|
||||
window.scrollTo({ top: 0, behavior: "smooth" })
|
||||
}
|
||||
}
|
||||
|
||||
return { showBackToTop, scrollToTop }
|
||||
}
|
||||
22
apps/scandic-web/hooks/useSessionId.ts
Normal file
22
apps/scandic-web/hooks/useSessionId.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { nanoid } from "nanoid"
|
||||
import { useMemo } from "react"
|
||||
|
||||
const storageKey = "web_sessionId"
|
||||
|
||||
export function useSessionId(): string | null {
|
||||
const sessionId = useMemo(() => {
|
||||
if (typeof window === "undefined") {
|
||||
// Return null if running on the server
|
||||
return null
|
||||
}
|
||||
|
||||
let currentSessionId = sessionStorage.getItem(storageKey)
|
||||
if (!currentSessionId) {
|
||||
currentSessionId = nanoid()
|
||||
sessionStorage.setItem(storageKey, currentSessionId)
|
||||
}
|
||||
return currentSessionId
|
||||
}, [])
|
||||
|
||||
return sessionId
|
||||
}
|
||||
11
apps/scandic-web/hooks/useSetOverflowVisibleOnRA.ts
Normal file
11
apps/scandic-web/hooks/useSetOverflowVisibleOnRA.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export default function useSetOverflowVisibleOnRA(isNestedInModal?: boolean) {
|
||||
function setOverflowVisible(isOpen: boolean) {
|
||||
if (isOpen) {
|
||||
document.body.style.overflow = "visible"
|
||||
} else if (!isNestedInModal) {
|
||||
document.body.style.overflow = ""
|
||||
}
|
||||
}
|
||||
|
||||
return setOverflowVisible
|
||||
}
|
||||
152
apps/scandic-web/hooks/useStickyPosition.ts
Normal file
152
apps/scandic-web/hooks/useStickyPosition.ts
Normal file
@@ -0,0 +1,152 @@
|
||||
"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,
|
||||
}
|
||||
}
|
||||
83
apps/scandic-web/hooks/useTrapFocus.ts
Normal file
83
apps/scandic-web/hooks/useTrapFocus.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react"
|
||||
|
||||
import { useHandleKeyPress } from "@/hooks/useHandleKeyPress"
|
||||
import findTabbableDescendants from "@/utils/tabbable"
|
||||
|
||||
const TAB_KEY = "Tab"
|
||||
const optionsDefault = { focusOnRender: true, returnFocus: true }
|
||||
type OptionsType = {
|
||||
focusOnRender?: boolean
|
||||
returnFocus?: boolean
|
||||
}
|
||||
export function useTrapFocus(opts?: OptionsType) {
|
||||
const options = opts ? { ...optionsDefault, ...opts } : optionsDefault
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
const previouseFocusedElement = useRef<HTMLElement>(
|
||||
document.activeElement as HTMLElement
|
||||
)
|
||||
const [tabbableElements, setTabbableElements] = useState<HTMLElement[]>([])
|
||||
// Handle initial focus of the referenced element, and return focus to previously focused element on cleanup
|
||||
// and find all the tabbable elements in the referenced element
|
||||
|
||||
useEffect(() => {
|
||||
const { current } = ref
|
||||
if (current) {
|
||||
const focusableChildNodes = findTabbableDescendants(current)
|
||||
if (options.focusOnRender) {
|
||||
current.focus()
|
||||
}
|
||||
|
||||
setTabbableElements(focusableChildNodes)
|
||||
}
|
||||
return () => {
|
||||
const { current } = previouseFocusedElement
|
||||
if (current instanceof HTMLElement && options.returnFocus) {
|
||||
current.focus()
|
||||
}
|
||||
}
|
||||
}, [options.focusOnRender, options.returnFocus, ref, setTabbableElements])
|
||||
|
||||
const handleUserKeyPress = useCallback(
|
||||
(event: KeyboardEvent) => {
|
||||
const { code, shiftKey } = event
|
||||
const first = tabbableElements[0]
|
||||
const last = tabbableElements[tabbableElements.length - 1]
|
||||
|
||||
const currentActiveElement = document.activeElement
|
||||
// Scope current tabs to current root element
|
||||
if (isWithinCurrentElementScope([...tabbableElements, ref.current])) {
|
||||
if (code === TAB_KEY) {
|
||||
if (
|
||||
currentActiveElement === first ||
|
||||
currentActiveElement === ref.current
|
||||
) {
|
||||
// move focus to last element if shift+tab while currently focusing the first tabbable element
|
||||
if (shiftKey) {
|
||||
event.preventDefault()
|
||||
last.focus()
|
||||
}
|
||||
}
|
||||
if (currentActiveElement === last) {
|
||||
// move focus back to first if tabbing while currently focusing the last tabbable element
|
||||
if (!shiftKey) {
|
||||
event.preventDefault()
|
||||
first.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
[ref, tabbableElements]
|
||||
)
|
||||
useHandleKeyPress(handleUserKeyPress)
|
||||
|
||||
return ref
|
||||
}
|
||||
function isWithinCurrentElementScope(
|
||||
elementList: (HTMLInputElement | Element | null)[]
|
||||
) {
|
||||
const currentActiveElement = document.activeElement
|
||||
return elementList.includes(currentActiveElement)
|
||||
}
|
||||
Reference in New Issue
Block a user