1 import { useEffect, useState } from "react"
2
3 /**
4 * Hook to get the current document direction (ltr/rtl) and listen for changes
5 * @returns The current document direction as "ltr" | "rtl" | undefined
6 */
7 export const useDocumentDirection = (): "ltr" | "rtl" | undefined => {
8 const [direction, setDirection] = useState<"ltr" | "rtl" | undefined>(() => {
9 // Initialize with current value
10 if (typeof document !== "undefined") {
11 return (
12 (document.documentElement.getAttribute("dir") as "ltr" | "rtl") ||
13 undefined
14 )
15 }
16 return undefined
17 })
18
19 useEffect(() => {
20 // Only run on client side
21 if (typeof document === "undefined") {
22 return
23 }
24
25 // Create a MutationObserver to watch for changes to the dir attribute
26 const observer = new MutationObserver((mutations) => {
27 mutations.forEach((mutation) => {
28 if (
29 mutation.type === "attributes" &&
30 mutation.attributeName === "dir" &&
31 mutation.target === document.documentElement
32 ) {
33 const newDirection = document.documentElement.getAttribute("dir") as
34 | "ltr"
35 | "rtl"
36 setDirection(newDirection || undefined)
37 }
38 })
39 })
40
41 // Start observing the document element for attribute changes
42 observer.observe(document.documentElement, {
43 attributes: true,
44 attributeFilter: ["dir"],
45 })
46
47 // Cleanup observer on unmount
48 return () => {
49 observer.disconnect()
50 }
51 }, [])
52
53 return direction
54 }