aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/ActiveSectionProvider.tsx
blob: 022dbada8fd161c87eb8a057ecae64a4eb75e2a3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * SPDX-FileCopyrightText: 2023 Kristóf Marussy
 *
 * SPDX-License-Identifier: MIT
 */

import { useLocation } from '@docusaurus/router';
import {
  type ReactNode,
  createContext,
  useCallback,
  useContext,
  useRef,
  useState,
} from 'react';

export interface ActiveSection {
  hash: string | undefined;
  setHash: (hash: string | undefined) => void;
}

const ActiveSectionContext = createContext<ActiveSection | undefined>(
  undefined,
);

export function useActiveSection(): ActiveSection {
  const value = useContext(ActiveSectionContext);
  if (value === undefined) {
    throw new Error(
      'useActiveSection is only valid inside ActiveSectionProvider',
    );
  }
  return value;
}

export default function ActiveSectionProvider({
  children,
}: {
  children: ReactNode;
}) {
  const location = useLocation();
  const [hash, setHashState] = useState<string | undefined>();
  const lastHashRef = useRef<string | undefined>();
  const setHash = useCallback(
    (hash: string | undefined) => {
      if (hash === lastHashRef.current) {
        return;
      }
      // Passing `undefined` to `hash` will give contraol pack to react-router.
      const newURL = `${location.pathname}${location.search}${
        hash ?? location.hash
      }`;
      // Update the history entry without informing react-router so Docusaurus
      // doesn't scroll to the top of the element. See
      // https://github.com/facebook/docusaurus/blob/ca3dba5e5eab0f8b8a9b3388e2b2e637fe3a19a7/packages/docusaurus/src/client/ClientLifecyclesDispatcher.tsx#L30-L39
      window.history.replaceState(null, null, newURL);
      setHashState(hash);
      lastHashRef.current = hash;
    },
    [location, setHashState],
  );
  return (
    <ActiveSectionContext.Provider value={{ hash, setHash }}>
      {children}
    </ActiveSectionContext.Provider>
  );
}