aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-add-prism-class-attr.tsx
blob: 7d33cc23fcef2bb7d806fa6204b9082cf258ae20 (plain)
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
import { useCallback, useEffect, useState } from 'react';

export type AttributesMap = {
  [key: string]: string;
};

export type useAddPrismClassAttrProps = {
  attributes?: AttributesMap;
  classNames?: string;
};

/**
 * Add classnames and/or attributes to pre elements.
 *
 * @param props - An object of attributes and classnames.
 */
const useAddPrismClassAttr = ({
  attributes,
  classNames,
}: useAddPrismClassAttrProps) => {
  const [elements, setElements] = useState<HTMLPreElement[]>([]);

  useEffect(() => {
    const targetElements = document.querySelectorAll('pre');
    setElements(Array.from(targetElements));
  }, []);

  const setClassNameAndAttributes = useCallback(
    (array: HTMLElement[]) => {
      array.forEach((el) => {
        if (classNames) {
          const classNamesArray = classNames.split(' ');
          const isCommandLine = el.classList.contains('command-line');
          const removedClassName = isCommandLine
            ? 'line-numbers'
            : 'command-line';
          const filteredClassNames = classNamesArray.filter(
            (className) => className !== removedClassName
          );
          filteredClassNames.forEach((className) =>
            el.classList.add(className)
          );
        }

        if (attributes) {
          for (const [key, value] of Object.entries(attributes)) {
            el.setAttribute(key, value);
          }
        }
      });
    },
    [attributes, classNames]
  );

  useEffect(() => {
    if (elements.length > 0) setClassNameAndAttributes(elements);
  }, [elements, setClassNameAndAttributes]);
};

export default useAddPrismClassAttr;