From bbd63400f94b43fde04449e0c71d14763d893e6a Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Thu, 19 May 2022 19:46:24 +0200
Subject: refactor: rewrite Prism hooks and providers

It avoid some hydratation errors on project pages (not in article
however) and the hooks are now reusable.
---
 src/utils/hooks/use-attributes.tsx | 35 +++++++++++++++++++++++++++--------
 1 file changed, 27 insertions(+), 8 deletions(-)

(limited to 'src/utils/hooks/use-attributes.tsx')

diff --git a/src/utils/hooks/use-attributes.tsx b/src/utils/hooks/use-attributes.tsx
index 97a7b43..6d18048 100644
--- a/src/utils/hooks/use-attributes.tsx
+++ b/src/utils/hooks/use-attributes.tsx
@@ -1,10 +1,15 @@
-import { useEffect } from 'react';
+import { fromKebabCaseToCamelCase } from '@utils/helpers/strings';
+import { useCallback, useEffect } from 'react';
 
 export type useAttributesProps = {
   /**
    * An HTML element.
    */
   element?: HTMLElement;
+  /**
+   * A node list of HTML Element.
+   */
+  elements?: NodeListOf<HTMLElement> | HTMLElement[];
   /**
    * The attribute name.
    */
@@ -20,14 +25,28 @@ export type useAttributesProps = {
  *
  * @param props - An object with element, attribute name and value.
  */
-const useAttributes = ({ element, attribute, value }: useAttributesProps) => {
+const useAttributes = ({
+  element,
+  elements,
+  attribute,
+  value,
+}: useAttributesProps) => {
+  const setAttribute = useCallback(
+    (el: HTMLElement) => {
+      if (attribute.startsWith('data')) {
+        el.setAttribute(attribute, value);
+      } else {
+        const camelCaseAttribute = fromKebabCaseToCamelCase(attribute);
+        el.dataset[camelCaseAttribute] = value;
+      }
+    },
+    [attribute, value]
+  );
+
   useEffect(() => {
-    if (element) {
-      element.dataset[attribute] = value;
-    } else {
-      document.documentElement.dataset[attribute] = value;
-    }
-  }, [attribute, element, value]);
+    if (element) setAttribute(element);
+    if (elements && elements.length > 0) elements.forEach(setAttribute);
+  }, [element, elements, setAttribute]);
 };
 
 export default useAttributes;
-- 
cgit v1.2.3

