diff options
| author | Armand Philippot <git@armandphilippot.com> | 2022-05-19 19:46:24 +0200 |
|---|---|---|
| committer | Armand Philippot <git@armandphilippot.com> | 2022-05-19 19:46:24 +0200 |
| commit | bbd63400f94b43fde04449e0c71d14763d893e6a (patch) | |
| tree | 057055dce19fc71c7c2e2fa05b691144224dfbd0 /src/utils/hooks/use-add-prism-class-attr.tsx | |
| parent | 806004ab79ac4e1cb49cef93ab3f35a08c5c82b5 (diff) | |
refactor: rewrite Prism hooks and providers
It avoid some hydratation errors on project pages (not in article
however) and the hooks are now reusable.
Diffstat (limited to 'src/utils/hooks/use-add-prism-class-attr.tsx')
| -rw-r--r-- | src/utils/hooks/use-add-prism-class-attr.tsx | 60 |
1 files changed, 0 insertions, 60 deletions
diff --git a/src/utils/hooks/use-add-prism-class-attr.tsx b/src/utils/hooks/use-add-prism-class-attr.tsx deleted file mode 100644 index 7d33cc2..0000000 --- a/src/utils/hooks/use-add-prism-class-attr.tsx +++ /dev/null @@ -1,60 +0,0 @@ -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; |
