From 7e16f500cb7bc0cfd8bafbf6bb1555704f771231 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Fri, 29 Apr 2022 12:13:34 +0200
Subject: chore: remove old pages, components, helpers and types

Since I'm using new components, I will also rewrite the GraphQL queries
so it is easier to start from scratch.
---
 src/utils/providers/prism-theme.tsx | 2 ++
 1 file changed, 2 insertions(+)

(limited to 'src/utils/providers/prism-theme.tsx')

diff --git a/src/utils/providers/prism-theme.tsx b/src/utils/providers/prism-theme.tsx
index 2ed8454..62bcf56 100644
--- a/src/utils/providers/prism-theme.tsx
+++ b/src/utils/providers/prism-theme.tsx
@@ -2,6 +2,7 @@ import { LocalStorage } from '@services/local-storage';
 import {
   createContext,
   FC,
+  ReactNode,
   useCallback,
   useContext,
   useEffect,
@@ -22,6 +23,7 @@ export type UsePrismThemeProps = {
 
 export type PrismThemeProviderProps = {
   attribute?: string;
+  children: ReactNode;
   storageKey?: string;
   themes?: PrismTheme[];
 };
-- 
cgit v1.2.3


From 584bd42f871d2e1618ca414749f09c38f0143a44 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Wed, 18 May 2022 22:40:59 +0200
Subject: chore: handle settings change

---
 .../molecules/forms/ackee-select.stories.tsx       | 18 +++++-----
 .../molecules/forms/ackee-select.test.tsx          |  4 +--
 src/components/molecules/forms/ackee-select.tsx    | 26 +++++++++++----
 .../molecules/forms/motion-toggle.stories.tsx      | 18 +++++-----
 .../molecules/forms/motion-toggle.test.tsx         |  2 +-
 src/components/molecules/forms/motion-toggle.tsx   | 34 +++++++++++++++----
 .../molecules/forms/prism-theme-toggle.stories.tsx | 21 ------------
 .../molecules/forms/prism-theme-toggle.test.tsx    |  2 +-
 .../molecules/forms/prism-theme-toggle.tsx         | 34 ++++++++++++++-----
 .../molecules/forms/theme-toggle.stories.tsx       | 21 ------------
 .../molecules/forms/theme-toggle.test.tsx          |  2 +-
 src/components/molecules/forms/theme-toggle.tsx    | 20 +++++++++---
 .../organisms/forms/settings-form.test.tsx         | 38 +++++++++++++++++++---
 src/components/organisms/forms/settings-form.tsx   | 32 ++++++++++++++----
 src/components/organisms/layout/header.stories.tsx | 22 +++++++++++++
 src/components/organisms/layout/header.test.tsx    | 19 ++++++++---
 src/components/organisms/layout/header.tsx         | 22 +++++++++++--
 src/components/organisms/modals/search-modal.tsx   |  1 +
 .../organisms/modals/settings-modal.test.tsx       |  7 +++-
 src/components/organisms/modals/settings-modal.tsx |  6 +++-
 .../organisms/toolbar/settings.stories.tsx         | 24 ++++++++++++++
 src/components/organisms/toolbar/settings.test.tsx | 18 ++++++++--
 src/components/organisms/toolbar/settings.tsx      | 22 +++++++++----
 .../organisms/toolbar/toolbar-items.module.scss    |  2 +-
 .../organisms/toolbar/toolbar.stories.tsx          | 22 +++++++++++++
 src/components/organisms/toolbar/toolbar.test.tsx  |  9 ++++-
 src/components/organisms/toolbar/toolbar.tsx       | 37 +++++++++++++--------
 src/components/templates/layout/layout.tsx         | 10 +++---
 src/components/templates/page/page-layout.tsx      |  3 ++
 src/services/local-storage/index.ts                |  6 ++--
 src/utils/hooks/use-attributes.tsx                 | 33 +++++++++++++++++++
 src/utils/hooks/use-code-blocks-theme.tsx          | 22 +++++++++++++
 src/utils/hooks/use-local-storage.tsx              | 35 ++++++++++++++++++++
 src/utils/hooks/use-query-selector-all.tsx         | 16 +++++++++
 src/utils/hooks/use-update-ackee-options.tsx       | 19 +++++++++++
 src/utils/providers/prism-theme.tsx                |  2 +-
 36 files changed, 487 insertions(+), 142 deletions(-)
 create mode 100644 src/utils/hooks/use-attributes.tsx
 create mode 100644 src/utils/hooks/use-code-blocks-theme.tsx
 create mode 100644 src/utils/hooks/use-local-storage.tsx
 create mode 100644 src/utils/hooks/use-query-selector-all.tsx
 create mode 100644 src/utils/hooks/use-update-ackee-options.tsx

(limited to 'src/utils/providers/prism-theme.tsx')

diff --git a/src/components/molecules/forms/ackee-select.stories.tsx b/src/components/molecules/forms/ackee-select.stories.tsx
index 4e6adf1..6b42b71 100644
--- a/src/components/molecules/forms/ackee-select.stories.tsx
+++ b/src/components/molecules/forms/ackee-select.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import AckeeSelect from './ackee-select';
 
 /**
@@ -33,6 +32,16 @@ export default {
         required: false,
       },
     },
+    storageKey: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set Ackee settings local storage key.',
+      type: {
+        name: 'string',
+        required: true,
+      },
+    },
     tooltipClassName: {
       control: {
         type: 'text',
@@ -47,13 +56,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof AckeeSelect>;
 
 const Template: ComponentStory<typeof AckeeSelect> = (args) => (
diff --git a/src/components/molecules/forms/ackee-select.test.tsx b/src/components/molecules/forms/ackee-select.test.tsx
index ec27922..0089c06 100644
--- a/src/components/molecules/forms/ackee-select.test.tsx
+++ b/src/components/molecules/forms/ackee-select.test.tsx
@@ -4,13 +4,13 @@ import AckeeSelect from './ackee-select';
 
 describe('Select', () => {
   it('should correctly set default option', () => {
-    render(<AckeeSelect initialValue="full" />);
+    render(<AckeeSelect storageKey="ackee-tracking" initialValue="full" />);
     expect(screen.getByRole('combobox')).toHaveValue('full');
     expect(screen.queryByRole('combobox')).not.toHaveValue('partial');
   });
 
   it('should correctly change value when user choose another option', async () => {
-    render(<AckeeSelect initialValue="full" />);
+    render(<AckeeSelect storageKey="ackee-tracking" initialValue="full" />);
 
     await act(async () => {
       await user.selectOptions(
diff --git a/src/components/molecules/forms/ackee-select.tsx b/src/components/molecules/forms/ackee-select.tsx
index 101e5b5..34850fb 100644
--- a/src/components/molecules/forms/ackee-select.tsx
+++ b/src/components/molecules/forms/ackee-select.tsx
@@ -1,12 +1,14 @@
-import { SelectOptions } from '@components/atoms/forms/select';
-import { Dispatch, FC, SetStateAction, useState } from 'react';
+import { type SelectOptions } from '@components/atoms/forms/select';
+import useLocalStorage from '@utils/hooks/use-local-storage';
+import useUpdateAckeeOptions, {
+  type AckeeOptions,
+} from '@utils/hooks/use-update-ackee-options';
+import { Dispatch, FC, SetStateAction } from 'react';
 import { useIntl } from 'react-intl';
 import SelectWithTooltip, {
   type SelectWithTooltipProps,
 } from './select-with-tooltip';
 
-export type AckeeOptions = 'full' | 'partial';
-
 export type AckeeSelectProps = Pick<
   SelectWithTooltipProps,
   'labelClassName' | 'tooltipClassName'
@@ -15,6 +17,10 @@ export type AckeeSelectProps = Pick<
    * A default value for Ackee settings.
    */
   initialValue: AckeeOptions;
+  /**
+   * The local storage key to save preference.
+   */
+  storageKey: string;
 };
 
 /**
@@ -22,9 +28,17 @@ export type AckeeSelectProps = Pick<
  *
  * Render a select to set Ackee settings.
  */
-const AckeeSelect: FC<AckeeSelectProps> = ({ initialValue, ...props }) => {
+const AckeeSelect: FC<AckeeSelectProps> = ({
+  initialValue,
+  storageKey,
+  ...props
+}) => {
   const intl = useIntl();
-  const [value, setValue] = useState<AckeeOptions>(initialValue);
+  const { value, setValue } = useLocalStorage<AckeeOptions>(
+    storageKey,
+    initialValue
+  );
+  useUpdateAckeeOptions(value);
 
   const ackeeLabel = intl.formatMessage({
     defaultMessage: 'Tracking:',
diff --git a/src/components/molecules/forms/motion-toggle.stories.tsx b/src/components/molecules/forms/motion-toggle.stories.tsx
index dcfc68d..60430d5 100644
--- a/src/components/molecules/forms/motion-toggle.stories.tsx
+++ b/src/components/molecules/forms/motion-toggle.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import MotionToggleComponent from './motion-toggle';
 
 /**
@@ -22,6 +21,16 @@ export default {
         required: false,
       },
     },
+    storageKey: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set local storage key.',
+      type: {
+        name: 'string',
+        required: true,
+      },
+    },
     value: {
       control: {
         type: null,
@@ -33,13 +42,6 @@ export default {
       },
     },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof MotionToggleComponent>;
 
 const Template: ComponentStory<typeof MotionToggleComponent> = (args) => (
diff --git a/src/components/molecules/forms/motion-toggle.test.tsx b/src/components/molecules/forms/motion-toggle.test.tsx
index 77bc17c..4fd6b31 100644
--- a/src/components/molecules/forms/motion-toggle.test.tsx
+++ b/src/components/molecules/forms/motion-toggle.test.tsx
@@ -3,7 +3,7 @@ import MotionToggle from './motion-toggle';
 
 describe('MotionToggle', () => {
   it('renders a checked toggle (deactivate animations choice)', () => {
-    render(<MotionToggle value={true} />);
+    render(<MotionToggle storageKey="reduced-motion" value={true} />);
     expect(
       screen.getByRole('checkbox', {
         name: `Animations: On Off`,
diff --git a/src/components/molecules/forms/motion-toggle.tsx b/src/components/molecules/forms/motion-toggle.tsx
index 24b54ae..e3bb11a 100644
--- a/src/components/molecules/forms/motion-toggle.tsx
+++ b/src/components/molecules/forms/motion-toggle.tsx
@@ -2,19 +2,41 @@ import Toggle, {
   type ToggleChoices,
   type ToggleProps,
 } from '@components/molecules/forms/toggle';
-import { FC, useState } from 'react';
+import useAttributes from '@utils/hooks/use-attributes';
+import useLocalStorage from '@utils/hooks/use-local-storage';
+import { FC } from 'react';
 import { useIntl } from 'react-intl';
 
-export type MotionToggleProps = Pick<ToggleProps, 'labelClassName' | 'value'>;
+export type MotionToggleProps = Pick<
+  ToggleProps,
+  'labelClassName' | 'value'
+> & {
+  /**
+   * The local storage key to save preference.
+   */
+  storageKey: string;
+};
 
 /**
  * MotionToggle component
  *
  * Render a Toggle component to set reduce motion.
  */
-const MotionToggle: FC<MotionToggleProps> = ({ value, ...props }) => {
+const MotionToggle: FC<MotionToggleProps> = ({
+  storageKey,
+  value,
+  ...props
+}) => {
   const intl = useIntl();
-  const [isDeactivated, setIsDeactivated] = useState<boolean>(value);
+  const { value: isReduced, setValue: setIsReduced } = useLocalStorage<boolean>(
+    storageKey,
+    value
+  );
+  useAttributes({
+    attribute: 'reducedMotion',
+    value: `${isReduced}`,
+  });
+
   const reduceMotionLabel = intl.formatMessage({
     defaultMessage: 'Animations:',
     description: 'MotionToggle: reduce motion label',
@@ -42,8 +64,8 @@ const MotionToggle: FC<MotionToggleProps> = ({ value, ...props }) => {
       label={reduceMotionLabel}
       labelSize="medium"
       choices={reduceMotionChoices}
-      value={isDeactivated}
-      setValue={setIsDeactivated}
+      value={isReduced}
+      setValue={setIsReduced}
       {...props}
     />
   );
diff --git a/src/components/molecules/forms/prism-theme-toggle.stories.tsx b/src/components/molecules/forms/prism-theme-toggle.stories.tsx
index 513ebfc..ef4ed6e 100644
--- a/src/components/molecules/forms/prism-theme-toggle.stories.tsx
+++ b/src/components/molecules/forms/prism-theme-toggle.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import PrismThemeToggle from './prism-theme-toggle';
 
 /**
@@ -22,24 +21,7 @@ export default {
         required: false,
       },
     },
-    value: {
-      control: {
-        type: null,
-      },
-      description: 'The prism theme value.',
-      type: {
-        name: 'boolean',
-        required: true,
-      },
-    },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof PrismThemeToggle>;
 
 const Template: ComponentStory<typeof PrismThemeToggle> = (args) => (
@@ -50,6 +32,3 @@ const Template: ComponentStory<typeof PrismThemeToggle> = (args) => (
  * Toggle Stories - Prism theme
  */
 export const PrismTheme = Template.bind({});
-PrismTheme.args = {
-  value: false,
-};
diff --git a/src/components/molecules/forms/prism-theme-toggle.test.tsx b/src/components/molecules/forms/prism-theme-toggle.test.tsx
index 0dceb92..d831b82 100644
--- a/src/components/molecules/forms/prism-theme-toggle.test.tsx
+++ b/src/components/molecules/forms/prism-theme-toggle.test.tsx
@@ -3,7 +3,7 @@ import PrismThemeToggle from './prism-theme-toggle';
 
 describe('PrismThemeToggle', () => {
   it('renders a checked toggle (dark theme choice)', () => {
-    render(<PrismThemeToggle value={true} />);
+    render(<PrismThemeToggle />);
     expect(
       screen.getByRole('checkbox', {
         name: `Code blocks: Light theme Dark theme`,
diff --git a/src/components/molecules/forms/prism-theme-toggle.tsx b/src/components/molecules/forms/prism-theme-toggle.tsx
index 0b9c447..3320722 100644
--- a/src/components/molecules/forms/prism-theme-toggle.tsx
+++ b/src/components/molecules/forms/prism-theme-toggle.tsx
@@ -4,22 +4,38 @@ import Toggle, {
   type ToggleChoices,
   type ToggleProps,
 } from '@components/molecules/forms/toggle';
-import { FC, useState } from 'react';
+import { usePrismTheme } from '@utils/providers/prism-theme';
+import { FC } from 'react';
 import { useIntl } from 'react-intl';
 
-export type PrismThemeToggleProps = Pick<
-  ToggleProps,
-  'labelClassName' | 'value'
->;
+export type PrismThemeToggleProps = Pick<ToggleProps, 'labelClassName'>;
 
 /**
  * PrismThemeToggle component
  *
  * Render a Toggle component to set code blocks theme.
  */
-const PrismThemeToggle: FC<PrismThemeToggleProps> = ({ value, ...props }) => {
+const PrismThemeToggle: FC<PrismThemeToggleProps> = ({ ...props }) => {
   const intl = useIntl();
-  const [isDarkTheme, setIsDarkTheme] = useState<boolean>(value);
+  const { theme, setTheme, resolvedTheme } = usePrismTheme();
+
+  /**
+   * Check if the resolved or chosen theme is dark theme.
+   *
+   * @returns {boolean} True if it is dark theme.
+   */
+  const isDarkTheme = (): boolean => {
+    if (theme === 'system') return resolvedTheme === 'dark';
+    return theme === 'dark';
+  };
+
+  /**
+   * Update the theme.
+   */
+  const updateTheme = () => {
+    setTheme(isDarkTheme() ? 'light' : 'dark');
+  };
+
   const themeLabel = intl.formatMessage({
     defaultMessage: 'Code blocks:',
     description: 'PrismThemeToggle: theme label',
@@ -47,8 +63,8 @@ const PrismThemeToggle: FC<PrismThemeToggleProps> = ({ value, ...props }) => {
       label={themeLabel}
       labelSize="medium"
       choices={themeChoices}
-      value={isDarkTheme}
-      setValue={setIsDarkTheme}
+      value={isDarkTheme()}
+      setValue={updateTheme}
       {...props}
     />
   );
diff --git a/src/components/molecules/forms/theme-toggle.stories.tsx b/src/components/molecules/forms/theme-toggle.stories.tsx
index 05d94b9..5ebf5a2 100644
--- a/src/components/molecules/forms/theme-toggle.stories.tsx
+++ b/src/components/molecules/forms/theme-toggle.stories.tsx
@@ -1,5 +1,4 @@
 import { ComponentMeta, ComponentStory } from '@storybook/react';
-import { IntlProvider } from 'react-intl';
 import ThemeToggle from './theme-toggle';
 
 /**
@@ -22,24 +21,7 @@ export default {
         required: false,
       },
     },
-    value: {
-      control: {
-        type: null,
-      },
-      description: 'The theme value.',
-      type: {
-        name: 'boolean',
-        required: true,
-      },
-    },
   },
-  decorators: [
-    (Story) => (
-      <IntlProvider locale="en">
-        <Story />
-      </IntlProvider>
-    ),
-  ],
 } as ComponentMeta<typeof ThemeToggle>;
 
 const Template: ComponentStory<typeof ThemeToggle> = (args) => (
@@ -50,6 +32,3 @@ const Template: ComponentStory<typeof ThemeToggle> = (args) => (
  * Toggle Stories - Theme
  */
 export const Theme = Template.bind({});
-Theme.args = {
-  value: false,
-};
diff --git a/src/components/molecules/forms/theme-toggle.test.tsx b/src/components/molecules/forms/theme-toggle.test.tsx
index 5cd3209..89b4f6f 100644
--- a/src/components/molecules/forms/theme-toggle.test.tsx
+++ b/src/components/molecules/forms/theme-toggle.test.tsx
@@ -3,7 +3,7 @@ import ThemeToggle from './theme-toggle';
 
 describe('ThemeToggle', () => {
   it('renders a checked toggle (dark theme choice)', () => {
-    render(<ThemeToggle value={true} />);
+    render(<ThemeToggle />);
     expect(
       screen.getByRole('checkbox', {
         name: `Theme: Light theme Dark theme`,
diff --git a/src/components/molecules/forms/theme-toggle.tsx b/src/components/molecules/forms/theme-toggle.tsx
index 10c6c47..61ee4c6 100644
--- a/src/components/molecules/forms/theme-toggle.tsx
+++ b/src/components/molecules/forms/theme-toggle.tsx
@@ -4,19 +4,29 @@ import Toggle, {
   type ToggleChoices,
   type ToggleProps,
 } from '@components/molecules/forms/toggle';
-import { FC, useState } from 'react';
+import { useTheme } from 'next-themes';
+import { FC } from 'react';
 import { useIntl } from 'react-intl';
 
-export type ThemeToggleProps = Pick<ToggleProps, 'labelClassName' | 'value'>;
+export type ThemeToggleProps = Pick<ToggleProps, 'labelClassName'>;
 
 /**
  * ThemeToggle component
  *
  * Render a Toggle component to set theme.
  */
-const ThemeToggle: FC<ThemeToggleProps> = ({ value, ...props }) => {
+const ThemeToggle: FC<ThemeToggleProps> = ({ ...props }) => {
   const intl = useIntl();
-  const [isDarkTheme, setIsDarkTheme] = useState<boolean>(value);
+  const { resolvedTheme, setTheme } = useTheme();
+  const isDarkTheme = resolvedTheme === 'dark';
+
+  /**
+   * Update the theme.
+   */
+  const updateTheme = () => {
+    setTheme(isDarkTheme ? 'light' : 'dark');
+  };
+
   const themeLabel = intl.formatMessage({
     defaultMessage: 'Theme:',
     description: 'ThemeToggle: theme label',
@@ -45,7 +55,7 @@ const ThemeToggle: FC<ThemeToggleProps> = ({ value, ...props }) => {
       labelSize="medium"
       choices={themeChoices}
       value={isDarkTheme}
-      setValue={setIsDarkTheme}
+      setValue={updateTheme}
       {...props}
     />
   );
diff --git a/src/components/organisms/forms/settings-form.test.tsx b/src/components/organisms/forms/settings-form.test.tsx
index beb65ec..43d546e 100644
--- a/src/components/organisms/forms/settings-form.test.tsx
+++ b/src/components/organisms/forms/settings-form.test.tsx
@@ -1,37 +1,65 @@
 import { render, screen } from '@test-utils';
 import SettingsForm from './settings-form';
 
+const ackeeStorageKey = 'ackee-tracking';
+const motionStorageKey = 'reduce-motion';
+
 describe('SettingsForm', () => {
   it('renders a form', () => {
-    render(<SettingsForm />);
+    render(
+      <SettingsForm
+        ackeeStorageKey={ackeeStorageKey}
+        motionStorageKey={motionStorageKey}
+      />
+    );
     expect(
       screen.getByRole('form', { name: /^Settings form/i })
     ).toBeInTheDocument();
   });
 
   it('renders a theme toggle setting', () => {
-    render(<SettingsForm />);
+    render(
+      <SettingsForm
+        ackeeStorageKey={ackeeStorageKey}
+        motionStorageKey={motionStorageKey}
+      />
+    );
     expect(
       screen.getByRole('checkbox', { name: /^Theme:/i })
     ).toBeInTheDocument();
   });
 
   it('renders a code blocks toggle setting', () => {
-    render(<SettingsForm />);
+    render(
+      <SettingsForm
+        ackeeStorageKey={ackeeStorageKey}
+        motionStorageKey={motionStorageKey}
+      />
+    );
     expect(
       screen.getByRole('checkbox', { name: /^Code blocks:/i })
     ).toBeInTheDocument();
   });
 
   it('renders a motion setting', () => {
-    render(<SettingsForm />);
+    render(
+      <SettingsForm
+        ackeeStorageKey={ackeeStorageKey}
+        motionStorageKey={motionStorageKey}
+      />
+    );
     expect(
       screen.getByRole('checkbox', { name: /^Animations:/i })
     ).toBeInTheDocument();
   });
 
   it('renders a Ackee setting', () => {
-    render(<SettingsForm />);
+    render(
+      <SettingsForm
+        ackeeStorageKey={ackeeStorageKey}
+        motionStorageKey={motionStorageKey}
+      />
+    );
     expect(
       screen.getByRole('combobox', { name: /^Tracking:/i })
     ).toBeInTheDocument();
diff --git a/src/components/organisms/forms/settings-form.tsx b/src/components/organisms/forms/settings-form.tsx
index 0a34601..c897fa5 100644
--- a/src/components/organisms/forms/settings-form.tsx
+++ b/src/components/organisms/forms/settings-form.tsx
@@ -2,16 +2,31 @@ import Form from '@components/atoms/forms/form';
 import AckeeSelect, {
   type AckeeSelectProps,
 } from '@components/molecules/forms/ackee-select';
-import MotionToggle from '@components/molecules/forms/motion-toggle';
+import MotionToggle, {
+  MotionToggleProps,
+} from '@components/molecules/forms/motion-toggle';
 import PrismThemeToggle from '@components/molecules/forms/prism-theme-toggle';
 import ThemeToggle from '@components/molecules/forms/theme-toggle';
 import { FC } from 'react';
 import { useIntl } from 'react-intl';
 import styles from './settings-form.module.scss';
 
-export type SettingsFormProps = Pick<AckeeSelectProps, 'tooltipClassName'>;
+export type SettingsFormProps = Pick<AckeeSelectProps, 'tooltipClassName'> & {
+  /**
+   * The local storage key for Ackee settings.
+   */
+  ackeeStorageKey: AckeeSelectProps['storageKey'];
+  /**
+   * The local storage key for Reduce motion settings.
+   */
+  motionStorageKey: MotionToggleProps['storageKey'];
+};
 
-const SettingsForm: FC<SettingsFormProps> = ({ tooltipClassName }) => {
+const SettingsForm: FC<SettingsFormProps> = ({
+  ackeeStorageKey,
+  motionStorageKey,
+  tooltipClassName,
+}) => {
   const intl = useIntl();
   const ariaLabel = intl.formatMessage({
     defaultMessage: 'Settings form',
@@ -21,13 +36,18 @@ const SettingsForm: FC<SettingsFormProps> = ({ tooltipClassName }) => {
 
   return (
     <Form aria-label={ariaLabel} onSubmit={() => null}>
-      <ThemeToggle labelClassName={styles.label} value={false} />
-      <PrismThemeToggle labelClassName={styles.label} value={false} />
-      <MotionToggle labelClassName={styles.label} value={false} />
+      <ThemeToggle labelClassName={styles.label} />
+      <PrismThemeToggle labelClassName={styles.label} />
+      <MotionToggle
+        labelClassName={styles.label}
+        storageKey={motionStorageKey}
+        value={false}
+      />
       <AckeeSelect
         initialValue="full"
         labelClassName={styles.label}
         tooltipClassName={tooltipClassName}
+        storageKey={ackeeStorageKey}
       />
     </Form>
   );
diff --git a/src/components/organisms/layout/header.stories.tsx b/src/components/organisms/layout/header.stories.tsx
index 98d6377..3ceb337 100644
--- a/src/components/organisms/layout/header.stories.tsx
+++ b/src/components/organisms/layout/header.stories.tsx
@@ -8,11 +8,23 @@ export default {
   title: 'Organisms/Layout',
   component: HeaderComponent,
   args: {
+    ackeeStorageKey: 'ackee-tracking',
     isHome: false,
+    motionStorageKey: 'reduced-motion',
     searchPage: '#',
     withLink: false,
   },
   argTypes: {
+    ackeeStorageKey: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set Ackee settings local storage key.',
+      type: {
+        name: 'string',
+        required: true,
+      },
+    },
     baseline: {
       control: {
         type: 'text',
@@ -52,6 +64,16 @@ export default {
         required: false,
       },
     },
+    motionStorageKey: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set Reduced motion settings local storage key.',
+      type: {
+        name: 'string',
+        required: true,
+      },
+    },
     nav: {
       description: 'The main navigation items.',
       type: {
diff --git a/src/components/organisms/layout/header.test.tsx b/src/components/organisms/layout/header.test.tsx
index a9896f8..414d96f 100644
--- a/src/components/organisms/layout/header.test.tsx
+++ b/src/components/organisms/layout/header.test.tsx
@@ -16,11 +16,13 @@ describe('Header', () => {
   it('renders the website title', () => {
     render(
       <Header
+        ackeeStorageKey="ackee-tracking"
+        isHome={true}
+        motionStorageKey="reduced-motion"
+        nav={nav}
+        photo={photo}
         searchPage="#"
         title={title}
-        photo={photo}
-        nav={nav}
-        isHome={true}
       />
     );
     expect(
@@ -29,7 +31,16 @@ describe('Header', () => {
   });
 
   it('renders the main nav', () => {
-    render(<Header searchPage="#" title={title} photo={photo} nav={nav} />);
+    render(
+      <Header
+        ackeeStorageKey="ackee-tracking"
+        motionStorageKey="reduced-motion"
+        nav={nav}
+        photo={photo}
+        searchPage="#"
+        title={title}
+      />
+    );
     expect(screen.getByRole('navigation')).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/layout/header.tsx b/src/components/organisms/layout/header.tsx
index 18ebb31..f6212c3 100644
--- a/src/components/organisms/layout/header.tsx
+++ b/src/components/organisms/layout/header.tsx
@@ -6,7 +6,10 @@ import Toolbar, { type ToolbarProps } from '../toolbar/toolbar';
 import styles from './header.module.scss';
 
 export type HeaderProps = BrandingProps &
-  Pick<ToolbarProps, 'nav' | 'searchPage'> & {
+  Pick<
+    ToolbarProps,
+    'ackeeStorageKey' | 'motionStorageKey' | 'nav' | 'searchPage'
+  > & {
     /**
      * Set additional classnames to the header element.
      */
@@ -18,12 +21,25 @@ export type HeaderProps = BrandingProps &
  *
  * Render the website header.
  */
-const Header: FC<HeaderProps> = ({ className, nav, searchPage, ...props }) => {
+const Header: FC<HeaderProps> = ({
+  ackeeStorageKey,
+  className,
+  motionStorageKey,
+  nav,
+  searchPage,
+  ...props
+}) => {
   return (
     <header className={`${styles.wrapper} ${className}`}>
       <div className={styles.body}>
         <Branding {...props} />
-        <Toolbar nav={nav} searchPage={searchPage} className={styles.toolbar} />
+        <Toolbar
+          ackeeStorageKey={ackeeStorageKey}
+          className={styles.toolbar}
+          motionStorageKey={motionStorageKey}
+          nav={nav}
+          searchPage={searchPage}
+        />
       </div>
     </header>
   );
diff --git a/src/components/organisms/modals/search-modal.tsx b/src/components/organisms/modals/search-modal.tsx
index e92bf1b..c731048 100644
--- a/src/components/organisms/modals/search-modal.tsx
+++ b/src/components/organisms/modals/search-modal.tsx
@@ -10,6 +10,7 @@ const DynamicSearchForm = dynamic(
   () => import('@components/organisms/forms/search-form'),
   {
     loading: () => <Spinner />,
+    ssr: false,
   }
 );
 
diff --git a/src/components/organisms/modals/settings-modal.test.tsx b/src/components/organisms/modals/settings-modal.test.tsx
index acbf7d1..d6ed989 100644
--- a/src/components/organisms/modals/settings-modal.test.tsx
+++ b/src/components/organisms/modals/settings-modal.test.tsx
@@ -3,7 +3,12 @@ import SettingsModal from './settings-modal';
 
 describe('SettingsModal', () => {
   it('renders a fake heading', () => {
-    render(<SettingsModal />);
+    render(
+      <SettingsModal
+        ackeeStorageKey="ackee-tracking"
+        motionStorageKey="reduce-motion"
+      />
+    );
     expect(screen.getByText(/Settings/i)).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/modals/settings-modal.tsx b/src/components/organisms/modals/settings-modal.tsx
index e724076..5d14836 100644
--- a/src/components/organisms/modals/settings-modal.tsx
+++ b/src/components/organisms/modals/settings-modal.tsx
@@ -10,11 +10,15 @@ const DynamicSettingsForm = dynamic(
   () => import('@components/organisms/forms/settings-form'),
   {
     loading: () => <Spinner />,
+    ssr: false,
   }
 );
 
 export type SettingsModalProps = Pick<ModalProps, 'className'> &
-  Pick<SettingsFormProps, 'tooltipClassName'>;
+  Pick<
+    SettingsFormProps,
+    'ackeeStorageKey' | 'motionStorageKey' | 'tooltipClassName'
+  >;
 
 /**
  * SettingsModal component
diff --git a/src/components/organisms/toolbar/settings.stories.tsx b/src/components/organisms/toolbar/settings.stories.tsx
index aab4b9e..9d04932 100644
--- a/src/components/organisms/toolbar/settings.stories.tsx
+++ b/src/components/organisms/toolbar/settings.stories.tsx
@@ -8,7 +8,21 @@ import Settings from './settings';
 export default {
   title: 'Organisms/Toolbar/Settings',
   component: Settings,
+  args: {
+    ackeeStorageKey: 'ackee-tracking',
+    motionStorageKey: 'reduced-motion',
+  },
   argTypes: {
+    ackeeStorageKey: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set Ackee settings local storage key.',
+      type: {
+        name: 'string',
+        required: true,
+      },
+    },
     className: {
       control: {
         type: 'text',
@@ -32,6 +46,16 @@ export default {
         required: true,
       },
     },
+    motionStorageKey: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set Reduced motion settings local storage key.',
+      type: {
+        name: 'string',
+        required: true,
+      },
+    },
     setIsActive: {
       control: {
         type: null,
diff --git a/src/components/organisms/toolbar/settings.test.tsx b/src/components/organisms/toolbar/settings.test.tsx
index 96a32c9..7ccb234 100644
--- a/src/components/organisms/toolbar/settings.test.tsx
+++ b/src/components/organisms/toolbar/settings.test.tsx
@@ -3,14 +3,28 @@ import Settings from './settings';
 
 describe('Settings', () => {
   it('renders a button to open settings modal', () => {
-    render(<Settings isActive={false} setIsActive={() => null} />);
+    render(
+      <Settings
+        ackeeStorageKey="ackee-tracking"
+        motionStorageKey="reduced-motion"
+        isActive={false}
+        setIsActive={() => null}
+      />
+    );
     expect(
       screen.getByRole('checkbox', { name: 'Open settings' })
     ).toBeInTheDocument();
   });
 
   it('renders a button to close settings modal', () => {
-    render(<Settings isActive={true} setIsActive={() => null} />);
+    render(
+      <Settings
+        ackeeStorageKey="ackee-tracking"
+        motionStorageKey="reduced-motion"
+        isActive={true}
+        setIsActive={() => null}
+      />
+    );
     expect(
       screen.getByRole('checkbox', { name: 'Close settings' })
     ).toBeInTheDocument();
diff --git a/src/components/organisms/toolbar/settings.tsx b/src/components/organisms/toolbar/settings.tsx
index 43d3190..9985ba0 100644
--- a/src/components/organisms/toolbar/settings.tsx
+++ b/src/components/organisms/toolbar/settings.tsx
@@ -1,7 +1,7 @@
 import Checkbox, { type CheckboxProps } from '@components/atoms/forms/checkbox';
 import Label from '@components/atoms/forms/label';
 import Cog from '@components/atoms/icons/cog';
-import { FC, forwardRef, ForwardRefRenderFunction } from 'react';
+import { forwardRef, ForwardRefRenderFunction } from 'react';
 import { useIntl } from 'react-intl';
 import SettingsModal, {
   type SettingsModalProps,
@@ -9,7 +9,10 @@ import SettingsModal, {
 import settingsStyles from './settings.module.scss';
 import sharedStyles from './toolbar-items.module.scss';
 
-export type SettingsProps = {
+export type SettingsProps = Pick<
+  SettingsModalProps,
+  'ackeeStorageKey' | 'motionStorageKey' | 'tooltipClassName'
+> & {
   /**
    * Set additional classnames to the modal wrapper.
    */
@@ -22,14 +25,17 @@ export type SettingsProps = {
    * A callback function to handle button state.
    */
   setIsActive: CheckboxProps['setValue'];
-  /**
-   * Set additional classnames to the tooltip wrapper.
-   */
-  tooltipClassName?: SettingsModalProps['tooltipClassName'];
 };
 
 const Settings: ForwardRefRenderFunction<HTMLDivElement, SettingsProps> = (
-  { className = '', isActive, setIsActive, tooltipClassName = '' },
+  {
+    ackeeStorageKey,
+    className = '',
+    isActive,
+    motionStorageKey,
+    setIsActive,
+    tooltipClassName = '',
+  },
   ref
 ) => {
   const intl = useIntl();
@@ -62,7 +68,9 @@ const Settings: ForwardRefRenderFunction<HTMLDivElement, SettingsProps> = (
         <Cog />
       </Label>
       <SettingsModal
+        ackeeStorageKey={ackeeStorageKey}
         className={`${sharedStyles.modal} ${settingsStyles.modal} ${className}`}
+        motionStorageKey={motionStorageKey}
         tooltipClassName={tooltipClassName}
       />
     </div>
diff --git a/src/components/organisms/toolbar/toolbar-items.module.scss b/src/components/organisms/toolbar/toolbar-items.module.scss
index c970b71..20abe01 100644
--- a/src/components/organisms/toolbar/toolbar-items.module.scss
+++ b/src/components/organisms/toolbar/toolbar-items.module.scss
@@ -22,7 +22,7 @@
 .modal {
   position: absolute;
   top: var(--toolbar-size, calc(var(--btn-size) + var(--spacing-2xs)));
-  transition: all 0.8s ease-in-out 0s;
+  transition: all 0.8s ease-in-out 0s, background 0s;
 
   @include mix.media("screen") {
     @include mix.dimensions(null, "sm") {
diff --git a/src/components/organisms/toolbar/toolbar.stories.tsx b/src/components/organisms/toolbar/toolbar.stories.tsx
index 477cb55..1f07e79 100644
--- a/src/components/organisms/toolbar/toolbar.stories.tsx
+++ b/src/components/organisms/toolbar/toolbar.stories.tsx
@@ -8,9 +8,21 @@ export default {
   title: 'Organisms/Toolbar',
   component: ToolbarComponent,
   args: {
+    ackeeStorageKey: 'ackee-tracking',
+    motionStorageKey: 'reduced-motion',
     searchPage: '#',
   },
   argTypes: {
+    ackeeStorageKey: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set Ackee settings local storage key.',
+      type: {
+        name: 'string',
+        required: true,
+      },
+    },
     className: {
       control: {
         type: 'text',
@@ -24,6 +36,16 @@ export default {
         required: false,
       },
     },
+    motionStorageKey: {
+      control: {
+        type: 'text',
+      },
+      description: 'Set Reduced motion settings local storage key.',
+      type: {
+        name: 'string',
+        required: true,
+      },
+    },
     nav: {
       description: 'The main nav items.',
       type: {
diff --git a/src/components/organisms/toolbar/toolbar.test.tsx b/src/components/organisms/toolbar/toolbar.test.tsx
index 05e84ff..72965e8 100644
--- a/src/components/organisms/toolbar/toolbar.test.tsx
+++ b/src/components/organisms/toolbar/toolbar.test.tsx
@@ -10,7 +10,14 @@ const nav = [
 
 describe('Toolbar', () => {
   it('renders a navigation menu', () => {
-    render(<Toolbar nav={nav} searchPage="#" />);
+    render(
+      <Toolbar
+        ackeeStorageKey="ackee-tracking"
+        motionStorageKey="reduced-motion"
+        nav={nav}
+        searchPage="#"
+      />
+    );
     expect(screen.getByRole('navigation')).toBeInTheDocument();
   });
 });
diff --git a/src/components/organisms/toolbar/toolbar.tsx b/src/components/organisms/toolbar/toolbar.tsx
index e4188fe..e196c09 100644
--- a/src/components/organisms/toolbar/toolbar.tsx
+++ b/src/components/organisms/toolbar/toolbar.tsx
@@ -2,26 +2,33 @@ import useClickOutside from '@utils/hooks/use-click-outside';
 import { FC, useRef, useState } from 'react';
 import MainNav, { type MainNavProps } from '../toolbar/main-nav';
 import Search, { type SearchProps } from '../toolbar/search';
-import Settings from '../toolbar/settings';
+import Settings, { SettingsProps } from '../toolbar/settings';
 import styles from './toolbar.module.scss';
 
-export type ToolbarProps = Pick<SearchProps, 'searchPage'> & {
-  /**
-   * Set additional classnames to the toolbar wrapper.
-   */
-  className?: string;
-  /**
-   * The main nav items.
-   */
-  nav: MainNavProps['items'];
-};
+export type ToolbarProps = Pick<SearchProps, 'searchPage'> &
+  Pick<SettingsProps, 'ackeeStorageKey' | 'motionStorageKey'> & {
+    /**
+     * Set additional classnames to the toolbar wrapper.
+     */
+    className?: string;
+    /**
+     * The main nav items.
+     */
+    nav: MainNavProps['items'];
+  };
 
 /**
  * Toolbar component
  *
  * Render the website toolbar.
  */
-const Toolbar: FC<ToolbarProps> = ({ className = '', nav, searchPage }) => {
+const Toolbar: FC<ToolbarProps> = ({
+  ackeeStorageKey,
+  className = '',
+  motionStorageKey,
+  nav,
+  searchPage,
+}) => {
   const [isNavOpened, setIsNavOpened] = useState<boolean>(false);
   const [isSearchOpened, setIsSearchOpened] = useState<boolean>(false);
   const [isSettingsOpened, setIsSettingsOpened] = useState<boolean>(false);
@@ -53,11 +60,13 @@ const Toolbar: FC<ToolbarProps> = ({ className = '', nav, searchPage }) => {
         ref={searchRef}
       />
       <Settings
+        ackeeStorageKey={ackeeStorageKey}
+        className={`${styles.modal} ${styles['modal--settings']}`}
         isActive={isSettingsOpened}
+        motionStorageKey={motionStorageKey}
+        ref={settingsRef}
         setIsActive={setIsSettingsOpened}
-        className={`${styles.modal} ${styles['modal--settings']}`}
         tooltipClassName={styles.tooltip}
-        ref={settingsRef}
       />
     </div>
   );
diff --git a/src/components/templates/layout/layout.tsx b/src/components/templates/layout/layout.tsx
index 559eaed..8f0d4e7 100644
--- a/src/components/templates/layout/layout.tsx
+++ b/src/components/templates/layout/layout.tsx
@@ -193,14 +193,16 @@ const Layout: FC<LayoutProps> = ({
         {skipToContent}
       </ButtonLink>
       <Header
-        title={name}
+        ackeeStorageKey="ackee-tracking"
         baseline={baseline}
-        photo={picture}
+        className={styles.header}
+        isHome={isHome}
+        motionStorageKey="reduced-motion"
         nav={mainNav}
+        photo={picture}
         searchPage="/recherche"
-        isHome={isHome}
+        title={name}
         withLink={true}
-        className={styles.header}
       />
       <Main id="main" className={styles.main}>
         <article
diff --git a/src/components/templates/page/page-layout.tsx b/src/components/templates/page/page-layout.tsx
index d171944..54b8d6e 100644
--- a/src/components/templates/page/page-layout.tsx
+++ b/src/components/templates/page/page-layout.tsx
@@ -20,6 +20,7 @@ import CommentsList, {
 import TableOfContents from '@components/organisms/widgets/table-of-contents';
 import { type SendCommentVars } from '@services/graphql/api';
 import { sendComment } from '@services/graphql/comments';
+import useCodeBlocksTheme from '@utils/hooks/use-code-blocks-theme';
 import useIsMounted from '@utils/hooks/use-is-mounted';
 import Script from 'next/script';
 import { FC, HTMLAttributes, ReactNode, useRef, useState } from 'react';
@@ -183,6 +184,8 @@ const PageLayout: FC<PageLayoutProps> = ({
     return Object.values(meta).every((value) => value === null);
   };
 
+  useCodeBlocksTheme(bodyRef);
+
   return (
     <>
       <Script
diff --git a/src/services/local-storage/index.ts b/src/services/local-storage/index.ts
index 8ed9ebf..65235a7 100644
--- a/src/services/local-storage/index.ts
+++ b/src/services/local-storage/index.ts
@@ -1,15 +1,15 @@
 export const LocalStorage = {
-  get(key: string): string | null | undefined {
+  get<T>(key: string): T | undefined {
     try {
       const serialItem = localStorage.getItem(key);
       if (!serialItem) return undefined;
-      return JSON.parse(serialItem);
+      return JSON.parse(serialItem) as T;
     } catch (e) {
       console.log(e);
       return undefined;
     }
   },
-  set(key: string, value: string) {
+  set<T>(key: string, value: T) {
     try {
       const serialItem = JSON.stringify(value);
       localStorage.setItem(key, serialItem);
diff --git a/src/utils/hooks/use-attributes.tsx b/src/utils/hooks/use-attributes.tsx
new file mode 100644
index 0000000..97a7b43
--- /dev/null
+++ b/src/utils/hooks/use-attributes.tsx
@@ -0,0 +1,33 @@
+import { useEffect } from 'react';
+
+export type useAttributesProps = {
+  /**
+   * An HTML element.
+   */
+  element?: HTMLElement;
+  /**
+   * The attribute name.
+   */
+  attribute: string;
+  /**
+   * The attribute value.
+   */
+  value: string;
+};
+
+/**
+ * Set HTML attributes to the given element or to the HTML document.
+ *
+ * @param props - An object with element, attribute name and value.
+ */
+const useAttributes = ({ element, attribute, value }: useAttributesProps) => {
+  useEffect(() => {
+    if (element) {
+      element.dataset[attribute] = value;
+    } else {
+      document.documentElement.dataset[attribute] = value;
+    }
+  }, [attribute, element, value]);
+};
+
+export default useAttributes;
diff --git a/src/utils/hooks/use-code-blocks-theme.tsx b/src/utils/hooks/use-code-blocks-theme.tsx
new file mode 100644
index 0000000..beb7b29
--- /dev/null
+++ b/src/utils/hooks/use-code-blocks-theme.tsx
@@ -0,0 +1,22 @@
+import { usePrismTheme } from '@utils/providers/prism-theme';
+import { useRouter } from 'next/router';
+import { RefObject, useEffect, useState } from 'react';
+import useIsMounted from './use-is-mounted';
+
+const useCodeBlocksTheme = (el: RefObject<HTMLDivElement>) => {
+  const [preElements, setPreElements] = useState<NodeListOf<HTMLPreElement>>();
+  const isMounted = useIsMounted(el);
+  const { setCodeBlocks } = usePrismTheme();
+  const { asPath } = useRouter();
+
+  useEffect(() => {
+    const result = document.querySelectorAll<HTMLPreElement>('pre');
+    setPreElements(result);
+  }, [asPath]);
+
+  useEffect(() => {
+    isMounted && preElements && setCodeBlocks(preElements);
+  }, [isMounted, preElements, setCodeBlocks]);
+};
+
+export default useCodeBlocksTheme;
diff --git a/src/utils/hooks/use-local-storage.tsx b/src/utils/hooks/use-local-storage.tsx
new file mode 100644
index 0000000..da0292b
--- /dev/null
+++ b/src/utils/hooks/use-local-storage.tsx
@@ -0,0 +1,35 @@
+import { LocalStorage } from '@services/local-storage';
+import { Dispatch, SetStateAction, useEffect, useState } from 'react';
+
+export type UseLocalStorageReturn<T> = {
+  value: T;
+  setValue: Dispatch<SetStateAction<T>>;
+};
+
+/**
+ * Use the local storage.
+ *
+ * @param {string} key - The storage local key.
+ * @param {T} [fallbackValue] - A fallback value if local storage is empty.
+ * @returns {UseLocalStorageReturn<T>} An object with value and setValue.
+ */
+const useLocalStorage = <T extends unknown>(
+  key: string,
+  fallbackValue: T
+): UseLocalStorageReturn<T> => {
+  const getInitialValue = () => {
+    if (typeof window === 'undefined') return fallbackValue;
+    const storedValue = LocalStorage.get<T>(key);
+    return storedValue || fallbackValue;
+  };
+
+  const [value, setValue] = useState<T>(getInitialValue);
+
+  useEffect(() => {
+    LocalStorage.set(key, value);
+  }, [key, value]);
+
+  return { value, setValue };
+};
+
+export default useLocalStorage;
diff --git a/src/utils/hooks/use-query-selector-all.tsx b/src/utils/hooks/use-query-selector-all.tsx
new file mode 100644
index 0000000..dbeec90
--- /dev/null
+++ b/src/utils/hooks/use-query-selector-all.tsx
@@ -0,0 +1,16 @@
+import { useEffect, useState } from 'react';
+
+const useQuerySelectorAll = <T extends keyof HTMLElementTagNameMap>(
+  query: string
+) => {
+  const [elements, setElements] =
+    useState<NodeListOf<HTMLElementTagNameMap[T]>>();
+
+  useEffect(() => {
+    setElements(document.querySelectorAll(query));
+  }, [query]);
+
+  return elements;
+};
+
+export default useQuerySelectorAll;
diff --git a/src/utils/hooks/use-update-ackee-options.tsx b/src/utils/hooks/use-update-ackee-options.tsx
new file mode 100644
index 0000000..7c1d98a
--- /dev/null
+++ b/src/utils/hooks/use-update-ackee-options.tsx
@@ -0,0 +1,19 @@
+import { useAckeeTracker } from '@utils/providers/ackee';
+import { useEffect } from 'react';
+
+export type AckeeOptions = 'full' | 'partial';
+
+/**
+ * Update Ackee settings with the given choice.
+ *
+ * @param {AckeeOptions} value - Either `full` or `partial`.
+ */
+const useUpdateAckeeOptions = (value: AckeeOptions) => {
+  const { setDetailed } = useAckeeTracker();
+
+  useEffect(() => {
+    setDetailed(value === 'full');
+  }, [value, setDetailed]);
+};
+
+export default useUpdateAckeeOptions;
diff --git a/src/utils/providers/prism-theme.tsx b/src/utils/providers/prism-theme.tsx
index 62bcf56..23a2a36 100644
--- a/src/utils/providers/prism-theme.tsx
+++ b/src/utils/providers/prism-theme.tsx
@@ -55,7 +55,7 @@ const isValidTheme = (theme: string): boolean => {
 
 const getTheme = (key: string): PrismTheme | undefined => {
   if (typeof window === 'undefined') return undefined;
-  const storageValue = LocalStorage.get(key);
+  const storageValue = LocalStorage.get<string>(key);
 
   return storageValue && isValidTheme(storageValue)
     ? (storageValue as PrismTheme)
-- 
cgit v1.2.3


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/components/molecules/forms/motion-toggle.tsx |   3 +-
 src/components/molecules/layout/code.tsx         |  25 +---
 src/components/templates/page/page-layout.tsx    |   5 +-
 src/pages/article/[slug].tsx                     |  54 +++++--
 src/styles/pages/partials/_article-prism.scss    |   2 +-
 src/utils/helpers/strings.ts                     |  10 ++
 src/utils/hooks/use-add-classname.tsx            |  34 +++++
 src/utils/hooks/use-add-prism-class-attr.tsx     |  60 --------
 src/utils/hooks/use-attributes.tsx               |  35 ++++-
 src/utils/hooks/use-code-blocks-theme.tsx        |  22 ---
 src/utils/hooks/use-prism-plugins.tsx            | 115 --------------
 src/utils/hooks/use-prism.tsx                    | 182 +++++++++++++++++++++++
 src/utils/hooks/use-query-selector-all.tsx       |  12 +-
 src/utils/providers/prism-theme.tsx              |  78 ++++------
 14 files changed, 346 insertions(+), 291 deletions(-)
 create mode 100644 src/utils/hooks/use-add-classname.tsx
 delete mode 100644 src/utils/hooks/use-add-prism-class-attr.tsx
 delete mode 100644 src/utils/hooks/use-code-blocks-theme.tsx
 delete mode 100644 src/utils/hooks/use-prism-plugins.tsx
 create mode 100644 src/utils/hooks/use-prism.tsx

(limited to 'src/utils/providers/prism-theme.tsx')

diff --git a/src/components/molecules/forms/motion-toggle.tsx b/src/components/molecules/forms/motion-toggle.tsx
index e3bb11a..cbe38fe 100644
--- a/src/components/molecules/forms/motion-toggle.tsx
+++ b/src/components/molecules/forms/motion-toggle.tsx
@@ -33,7 +33,8 @@ const MotionToggle: FC<MotionToggleProps> = ({
     value
   );
   useAttributes({
-    attribute: 'reducedMotion',
+    element: document.documentElement || undefined,
+    attribute: 'reduced-motion',
     value: `${isReduced}`,
   });
 
diff --git a/src/components/molecules/layout/code.tsx b/src/components/molecules/layout/code.tsx
index 2959ae5..f5b60b9 100644
--- a/src/components/molecules/layout/code.tsx
+++ b/src/components/molecules/layout/code.tsx
@@ -1,7 +1,5 @@
-import usePrismPlugins, {
-  type PrismPlugin,
-} from '@utils/hooks/use-prism-plugins';
-import { FC } from 'react';
+import usePrism, { OptionalPrismPlugin } from '@utils/hooks/use-prism';
+import { FC, useRef } from 'react';
 import styles from './code.module.scss';
 
 export type PrismLanguage =
@@ -35,15 +33,6 @@ export type PrismLanguage =
   | 'twig'
   | 'yaml';
 
-export type OptionalPrismPlugin = Extract<
-  PrismPlugin,
-  | 'command-line'
-  | 'diff-highlight'
-  | 'inline-color'
-  | 'line-highlight'
-  | 'line-numbers'
->;
-
 export type CodeProps = {
   /**
    * The code to highlight.
@@ -79,17 +68,19 @@ const Code: FC<CodeProps> = ({
   plugins = [],
   outputPattern = '#output#',
 }) => {
-  const { pluginsAttribute, pluginsClassName } = usePrismPlugins(plugins);
+  const wrapperRef = useRef<HTMLDivElement>(null);
+  const { attributes, className } = usePrism({ language, plugins });
 
   const outputAttribute = filterOutput
     ? { 'data-filter-output': outputPattern }
     : {};
 
   return (
-    <div className={styles.wrapper}>
+    <div className={styles.wrapper} ref={wrapperRef}>
       <pre
-        className={`language-${language} ${pluginsClassName}`}
-        {...pluginsAttribute}
+        className={className}
+        tabIndex={0}
+        {...attributes}
         {...outputAttribute}
       >
         <code className={`language-${language}`}>{children}</code>
diff --git a/src/components/templates/page/page-layout.tsx b/src/components/templates/page/page-layout.tsx
index 54b8d6e..8ff44d5 100644
--- a/src/components/templates/page/page-layout.tsx
+++ b/src/components/templates/page/page-layout.tsx
@@ -20,7 +20,6 @@ import CommentsList, {
 import TableOfContents from '@components/organisms/widgets/table-of-contents';
 import { type SendCommentVars } from '@services/graphql/api';
 import { sendComment } from '@services/graphql/comments';
-import useCodeBlocksTheme from '@utils/hooks/use-code-blocks-theme';
 import useIsMounted from '@utils/hooks/use-is-mounted';
 import Script from 'next/script';
 import { FC, HTMLAttributes, ReactNode, useRef, useState } from 'react';
@@ -181,11 +180,9 @@ const PageLayout: FC<PageLayoutProps> = ({
    * @param {MetaData} meta - The metadata.
    */
   const hasMeta = (meta: MetaData) => {
-    return Object.values(meta).every((value) => value === null);
+    return Object.values(meta).every((value) => value);
   };
 
-  useCodeBlocksTheme(bodyRef);
-
   return (
     <>
       <Script
diff --git a/src/pages/article/[slug].tsx b/src/pages/article/[slug].tsx
index a3df43b..7abbabc 100644
--- a/src/pages/article/[slug].tsx
+++ b/src/pages/article/[slug].tsx
@@ -18,11 +18,11 @@ import {
   type NextPageWithLayout,
 } from '@ts/types/app';
 import { loadTranslation, type Messages } from '@utils/helpers/i18n';
-import useAddPrismClassAttr from '@utils/hooks/use-add-prism-class-attr';
+import useAddClassName from '@utils/hooks/use-add-classname';
+import useAttributes from '@utils/hooks/use-attributes';
 import useBreadcrumb from '@utils/hooks/use-breadcrumb';
-import usePrismPlugins, {
-  type PrismPlugin,
-} from '@utils/hooks/use-prism-plugins';
+import usePrism, { type OptionalPrismPlugin } from '@utils/hooks/use-prism';
+import useQuerySelectorAll from '@utils/hooks/use-query-selector-all';
 import useReadingTime from '@utils/hooks/use-reading-time';
 import useSettings from '@utils/hooks/use-settings';
 import { GetStaticPaths, GetStaticProps } from 'next';
@@ -199,14 +199,40 @@ const ArticlePage: NextPageWithLayout<ArticlePageProps> = ({
     });
   };
 
-  const prismPlugins: PrismPlugin[] = ['command-line', 'line-numbers'];
-  const { pluginsAttribute, pluginsClassName } = usePrismPlugins(prismPlugins);
-  useAddPrismClassAttr({
-    attributes: {
-      'data-filter-output': '#output#"',
-    },
-    classNames: pluginsClassName,
-  });
+  const prismPlugins: OptionalPrismPlugin[] = ['command-line', 'line-numbers'];
+  const { attributes, className } = usePrism({ plugins: prismPlugins });
+  const lineNumbersClassName = className
+    .replace('command-line', '')
+    .replace(/\s\s+/g, ' ');
+  const commandLineClassName = className
+    .replace('line-numbers', '')
+    .replace(/\s\s+/g, ' ');
+
+  /**
+   * Replace a string with Prism classnames and attributes.
+   *
+   * @param {string} str - The found string.
+   * @returns {string} The classes and attributes.
+   */
+  const prismClassNameReplacer = (str: string): string => {
+    const wpBlockClassName = 'wp-block-code';
+    const languageArray = str.match(/language-[^\s|"]+/);
+    const languageClassName = languageArray ? `${languageArray[0]}` : '';
+
+    if (
+      str.includes('command-line') ||
+      (!str.includes('command-line') && str.includes('language-bash'))
+    ) {
+      return `class="${wpBlockClassName} ${commandLineClassName}${languageClassName}" tabindex="0" data-filter-output="#output#`;
+    }
+
+    return `class="${wpBlockClassName} ${lineNumbersClassName}${languageClassName}" tabindex="0`;
+  };
+
+  const contentWithPrismClasses = content.replaceAll(
+    /class="wp-block-code[^"]+/gm,
+    prismClassNameReplacer
+  );
 
   return (
     <>
@@ -226,7 +252,7 @@ const ArticlePage: NextPageWithLayout<ArticlePageProps> = ({
       <PageLayout
         allowComments={true}
         bodyAttributes={{
-          ...(pluginsAttribute as HTMLAttributes<HTMLDivElement>),
+          ...(attributes as HTMLAttributes<HTMLDivElement>),
         }}
         bodyClassName={styles.body}
         breadcrumb={breadcrumbItems}
@@ -254,7 +280,7 @@ const ArticlePage: NextPageWithLayout<ArticlePageProps> = ({
           />,
         ]}
       >
-        {content}
+        {contentWithPrismClasses}
       </PageLayout>
     </>
   );
diff --git a/src/styles/pages/partials/_article-prism.scss b/src/styles/pages/partials/_article-prism.scss
index 025e0c0..5412bbd 100644
--- a/src/styles/pages/partials/_article-prism.scss
+++ b/src/styles/pages/partials/_article-prism.scss
@@ -238,7 +238,7 @@
       > span {
         &::before {
           display: block;
-          content: "";
+          content: " ";
         }
 
         &[data-user]::before {
diff --git a/src/utils/helpers/strings.ts b/src/utils/helpers/strings.ts
index 5d90161..1af0ca2 100644
--- a/src/utils/helpers/strings.ts
+++ b/src/utils/helpers/strings.ts
@@ -27,3 +27,13 @@ export const slugify = (text: string): string => {
 export const capitalize = (text: string): string => {
   return text.replace(/^\w/, (firstLetter) => firstLetter.toUpperCase());
 };
+
+/**
+ * Convert a text from kebab case (foo-bar) to camel case (fooBar).
+ *
+ * @param {string} text - A text to transform.
+ * @returns {string} The text in camel case.
+ */
+export const fromKebabCaseToCamelCase = (text: string): string => {
+  return text.replace(/-./g, (x) => x[1].toUpperCase());
+};
diff --git a/src/utils/hooks/use-add-classname.tsx b/src/utils/hooks/use-add-classname.tsx
new file mode 100644
index 0000000..0584084
--- /dev/null
+++ b/src/utils/hooks/use-add-classname.tsx
@@ -0,0 +1,34 @@
+import { useCallback, useEffect } from 'react';
+
+export type UseAddClassNameProps = {
+  className: string;
+  element?: HTMLElement;
+  elements?: NodeListOf<HTMLElement> | HTMLElement[];
+};
+
+/**
+ * Add className to the given element(s).
+ *
+ * @param {UseAddClassNameProps} props - An object with classnames and one or more elements.
+ */
+const useAddClassName = ({
+  className,
+  element,
+  elements,
+}: UseAddClassNameProps) => {
+  const classNames = className.split(' ').filter((string) => string !== '');
+
+  const setClassName = useCallback(
+    (el: HTMLElement) => {
+      el.classList.add(...classNames);
+    },
+    [classNames]
+  );
+
+  useEffect(() => {
+    if (element) setClassName(element);
+    if (elements && elements.length > 0) elements.forEach(setClassName);
+  }, [element, elements, setClassName]);
+};
+
+export default useAddClassName;
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;
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;
diff --git a/src/utils/hooks/use-code-blocks-theme.tsx b/src/utils/hooks/use-code-blocks-theme.tsx
deleted file mode 100644
index beb7b29..0000000
--- a/src/utils/hooks/use-code-blocks-theme.tsx
+++ /dev/null
@@ -1,22 +0,0 @@
-import { usePrismTheme } from '@utils/providers/prism-theme';
-import { useRouter } from 'next/router';
-import { RefObject, useEffect, useState } from 'react';
-import useIsMounted from './use-is-mounted';
-
-const useCodeBlocksTheme = (el: RefObject<HTMLDivElement>) => {
-  const [preElements, setPreElements] = useState<NodeListOf<HTMLPreElement>>();
-  const isMounted = useIsMounted(el);
-  const { setCodeBlocks } = usePrismTheme();
-  const { asPath } = useRouter();
-
-  useEffect(() => {
-    const result = document.querySelectorAll<HTMLPreElement>('pre');
-    setPreElements(result);
-  }, [asPath]);
-
-  useEffect(() => {
-    isMounted && preElements && setCodeBlocks(preElements);
-  }, [isMounted, preElements, setCodeBlocks]);
-};
-
-export default useCodeBlocksTheme;
diff --git a/src/utils/hooks/use-prism-plugins.tsx b/src/utils/hooks/use-prism-plugins.tsx
deleted file mode 100644
index c4959ac..0000000
--- a/src/utils/hooks/use-prism-plugins.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-import Prism from 'prismjs';
-import { useEffect, useMemo } from 'react';
-import { useIntl } from 'react-intl';
-
-export type PrismPlugin =
-  | 'autoloader'
-  | 'color-scheme'
-  | 'command-line'
-  | 'copy-to-clipboard'
-  | 'diff-highlight'
-  | 'inline-color'
-  | 'line-highlight'
-  | 'line-numbers'
-  | 'match-braces'
-  | 'normalize-whitespace'
-  | 'show-language'
-  | 'toolbar';
-
-/**
- * Import and configure all given Prism plugins.
- *
- * @param {PrismPlugin[]} prismPlugins - The Prism plugins to activate.
- */
-const loadPrismPlugins = async (prismPlugins: PrismPlugin[]) => {
-  for (const plugin of prismPlugins) {
-    try {
-      if (plugin === 'color-scheme') {
-        await import(`@utils/plugins/prism-${plugin}`);
-      } else {
-        await import(`prismjs/plugins/${plugin}/prism-${plugin}.min.js`);
-      }
-
-      if (plugin === 'autoloader') {
-        Prism.plugins.autoloader.languages_path = '/prism/';
-      }
-    } catch (error) {
-      console.error(
-        'usePrismPlugins: an error occurred while loading Prism plugins.'
-      );
-      console.error(error);
-    }
-  }
-};
-
-/**
- * Load both the given Prism plugins and the default plugins.
- *
- * @param {PrismPlugin[]} plugins - The Prism plugins to activate.
- */
-const usePrismPlugins = (plugins: PrismPlugin[]) => {
-  const intl = useIntl();
-
-  const copyText = intl.formatMessage({
-    defaultMessage: 'Copy',
-    description: 'usePrismPlugins: copy button text (not clicked)',
-    id: 'FIE/eC',
-  });
-  const copiedText = intl.formatMessage({
-    defaultMessage: 'Copied!',
-    description: 'usePrismPlugins: copy button text (clicked)',
-    id: 'MzLdEl',
-  });
-  const errorText = intl.formatMessage({
-    defaultMessage: 'Use Ctrl+c to copy',
-    description: 'usePrismPlugins: copy button error text',
-    id: '0XePFn',
-  });
-  const darkTheme = intl.formatMessage({
-    defaultMessage: 'Dark Theme 🌙',
-    description: 'usePrismPlugins: toggle dark theme button text',
-    id: 'jo9vr5',
-  });
-  const lightTheme = intl.formatMessage({
-    defaultMessage: 'Light Theme 🌞',
-    description: 'usePrismPlugins: toggle light theme button text',
-    id: '6EUEtH',
-  });
-
-  const attributes = {
-    'data-prismjs-copy': copyText,
-    'data-prismjs-copy-success': copiedText,
-    'data-prismjs-copy-error': errorText,
-    'data-prismjs-color-scheme-dark': darkTheme,
-    'data-prismjs-color-scheme-light': lightTheme,
-  };
-
-  const defaultPlugins: PrismPlugin[] = useMemo(
-    () => [
-      'toolbar',
-      'autoloader',
-      'show-language',
-      'copy-to-clipboard',
-      'color-scheme',
-      'match-braces',
-      'normalize-whitespace',
-    ],
-    []
-  );
-
-  useEffect(() => {
-    loadPrismPlugins([...defaultPlugins, ...plugins]).then(() => {
-      Prism.highlightAll();
-    });
-  }, [defaultPlugins, plugins]);
-
-  const defaultPluginsClasses = 'match-braces';
-  const pluginsClasses = plugins.join(' ');
-
-  return {
-    pluginsAttribute: attributes,
-    pluginsClassName: `${defaultPluginsClasses} ${pluginsClasses}`,
-  };
-};
-
-export default usePrismPlugins;
diff --git a/src/utils/hooks/use-prism.tsx b/src/utils/hooks/use-prism.tsx
new file mode 100644
index 0000000..ef1a4c8
--- /dev/null
+++ b/src/utils/hooks/use-prism.tsx
@@ -0,0 +1,182 @@
+import Prism from 'prismjs';
+import { useEffect, useMemo } from 'react';
+import { useIntl } from 'react-intl';
+
+const PRISM_PLUGINS = [
+  'autoloader',
+  'color-scheme',
+  'command-line',
+  'copy-to-clipboard',
+  'diff-highlight',
+  'inline-color',
+  'line-highlight',
+  'line-numbers',
+  'match-braces',
+  'normalize-whitespace',
+  'show-language',
+  'toolbar',
+] as const;
+
+export type PrismPlugin = typeof PRISM_PLUGINS[number];
+
+export type DefaultPrismPlugin = Extract<
+  PrismPlugin,
+  | 'autoloader'
+  | 'color-scheme'
+  | 'copy-to-clipboard'
+  | 'match-braces'
+  | 'normalize-whitespace'
+  | 'show-language'
+  | 'toolbar'
+>;
+
+export type OptionalPrismPlugin = Exclude<PrismPlugin, DefaultPrismPlugin>;
+
+export type PrismLanguage =
+  | 'apacheconf'
+  | 'bash'
+  | 'css'
+  | 'diff'
+  | 'docker'
+  | 'editorconfig'
+  | 'ejs'
+  | 'git'
+  | 'graphql'
+  | 'html'
+  | 'ignore'
+  | 'ini'
+  | 'javascript'
+  | 'jsdoc'
+  | 'json'
+  | 'jsx'
+  | 'makefile'
+  | 'markup'
+  | 'php'
+  | 'phpdoc'
+  | 'regex'
+  | 'scss'
+  | 'shell-session'
+  | 'smarty'
+  | 'tcl'
+  | 'toml'
+  | 'tsx'
+  | 'twig'
+  | 'yaml';
+
+export type PrismAttributes = {
+  'data-prismjs-copy': string;
+  'data-prismjs-copy-success': string;
+  'data-prismjs-copy-error': string;
+  'data-prismjs-color-scheme-dark': string;
+  'data-prismjs-color-scheme-light': string;
+};
+
+export type UsePrismProps = {
+  language?: PrismLanguage;
+  plugins: OptionalPrismPlugin[];
+};
+
+export type UsePrismReturn = {
+  attributes: PrismAttributes;
+  className: string;
+};
+
+/**
+ * Import and configure all given Prism plugins.
+ *
+ * @param {PrismPlugin[]} plugins - The Prism plugins to activate.
+ */
+const loadPrismPlugins = async (plugins: PrismPlugin[]) => {
+  for (const plugin of plugins) {
+    try {
+      if (plugin === 'color-scheme') {
+        await import(`@utils/plugins/prism-${plugin}`);
+      } else {
+        await import(`prismjs/plugins/${plugin}/prism-${plugin}.min.js`);
+      }
+
+      if (plugin === 'autoloader') {
+        Prism.plugins.autoloader.languages_path = '/prism/';
+      }
+    } catch (error) {
+      console.error('usePrism: an error occurred while loading Prism plugins.');
+      console.error(error);
+    }
+  }
+};
+
+/**
+ * Use Prism and its plugins.
+ *
+ * @param {UsePrismProps} props - An object of options.
+ * @returns {UsePrismReturn} An object of data.
+ */
+const usePrism = ({ language, plugins }: UsePrismProps): UsePrismReturn => {
+  /**
+   * The order matter. Toolbar must be loaded before some other plugins.
+   */
+  const defaultPlugins: DefaultPrismPlugin[] = useMemo(
+    () => [
+      'toolbar',
+      'autoloader',
+      'show-language',
+      'copy-to-clipboard',
+      'color-scheme',
+      'match-braces',
+      'normalize-whitespace',
+    ],
+    []
+  );
+
+  useEffect(() => {
+    loadPrismPlugins([...defaultPlugins, ...plugins]).then(() => {
+      Prism.highlightAll();
+    });
+  }, [defaultPlugins, plugins]);
+
+  const defaultClassName = 'match-braces';
+  const languageClassName = language ? `language-${language}` : '';
+  const pluginsClassName = plugins.join(' ');
+  const className = `${defaultClassName} ${pluginsClassName} ${languageClassName}`;
+
+  const intl = useIntl();
+  const copyText = intl.formatMessage({
+    defaultMessage: 'Copy',
+    description: 'usePrism: copy button text (not clicked)',
+    id: '6GySNl',
+  });
+  const copiedText = intl.formatMessage({
+    defaultMessage: 'Copied!',
+    description: 'usePrism: copy button text (clicked)',
+    id: 'nsw6Th',
+  });
+  const errorText = intl.formatMessage({
+    defaultMessage: 'Use Ctrl+c to copy',
+    description: 'usePrism: copy button error text',
+    id: 'lKhTGM',
+  });
+  const darkTheme = intl.formatMessage({
+    defaultMessage: 'Dark Theme 🌙',
+    description: 'usePrism: toggle dark theme button text',
+    id: 'QLisK6',
+  });
+  const lightTheme = intl.formatMessage({
+    defaultMessage: 'Light Theme 🌞',
+    description: 'usePrism: toggle light theme button text',
+    id: 'hHVgW3',
+  });
+  const attributes = {
+    'data-prismjs-copy': copyText,
+    'data-prismjs-copy-success': copiedText,
+    'data-prismjs-copy-error': errorText,
+    'data-prismjs-color-scheme-dark': darkTheme,
+    'data-prismjs-color-scheme-light': lightTheme,
+  };
+
+  return {
+    attributes,
+    className,
+  };
+};
+
+export default usePrism;
diff --git a/src/utils/hooks/use-query-selector-all.tsx b/src/utils/hooks/use-query-selector-all.tsx
index dbeec90..6ac8a08 100644
--- a/src/utils/hooks/use-query-selector-all.tsx
+++ b/src/utils/hooks/use-query-selector-all.tsx
@@ -1,14 +1,22 @@
+import { useRouter } from 'next/router';
 import { useEffect, useState } from 'react';
 
+/**
+ * Use `document.querySelectorAll`.
+ *
+ * @param {string} query - A query.
+ * @returns {NodeListOf<HTMLElementTagNameMap[T]|undefined>} - The node list.
+ */
 const useQuerySelectorAll = <T extends keyof HTMLElementTagNameMap>(
   query: string
-) => {
+): NodeListOf<HTMLElementTagNameMap[T]> | undefined => {
   const [elements, setElements] =
     useState<NodeListOf<HTMLElementTagNameMap[T]>>();
+  const { asPath } = useRouter();
 
   useEffect(() => {
     setElements(document.querySelectorAll(query));
-  }, [query]);
+  }, [asPath, query]);
 
   return elements;
 };
diff --git a/src/utils/providers/prism-theme.tsx b/src/utils/providers/prism-theme.tsx
index 23a2a36..dd8feb7 100644
--- a/src/utils/providers/prism-theme.tsx
+++ b/src/utils/providers/prism-theme.tsx
@@ -1,4 +1,6 @@
-import { LocalStorage } from '@services/local-storage';
+import useAttributes from '@utils/hooks/use-attributes';
+import useLocalStorage from '@utils/hooks/use-local-storage';
+import useQuerySelectorAll from '@utils/hooks/use-query-selector-all';
 import {
   createContext,
   FC,
@@ -10,7 +12,7 @@ import {
 } from 'react';
 
 export type PrismTheme = 'dark' | 'light' | 'system';
-export type ResolvedPrismTheme = 'dark' | 'light';
+export type ResolvedPrismTheme = Exclude<PrismTheme, 'system'>;
 
 export type UsePrismThemeProps = {
   themes: PrismTheme[];
@@ -18,7 +20,6 @@ export type UsePrismThemeProps = {
   setTheme: (theme: PrismTheme) => void;
   resolvedTheme?: ResolvedPrismTheme;
   codeBlocks?: NodeListOf<HTMLPreElement>;
-  setCodeBlocks: (codeBlocks: NodeListOf<HTMLPreElement>) => void;
 };
 
 export type PrismThemeProviderProps = {
@@ -33,14 +34,16 @@ export const PrismThemeContext = createContext<UsePrismThemeProps>({
   setTheme: (_) => {
     // This is intentional.
   },
-  setCodeBlocks: (_) => {
-    // This is intentional.
-  },
 });
 
 export const usePrismTheme = () => useContext(PrismThemeContext);
 
-const prefersDarkScheme = () => {
+/**
+ * Check if user prefers dark color scheme.
+ *
+ * @returns {boolean|undefined} True if `prefers-color-scheme` is set to `dark`.
+ */
+const prefersDarkScheme = (): boolean | undefined => {
   if (typeof window === 'undefined') return;
 
   return (
@@ -49,40 +52,35 @@ const prefersDarkScheme = () => {
   );
 };
 
+/**
+ * Check if a given string is a Prism theme name.
+ *
+ * @param {string} theme - A string.
+ * @returns {boolean} True if the given string match a Prism theme name.
+ */
 const isValidTheme = (theme: string): boolean => {
   return theme === 'dark' || theme === 'light' || theme === 'system';
 };
 
-const getTheme = (key: string): PrismTheme | undefined => {
-  if (typeof window === 'undefined') return undefined;
-  const storageValue = LocalStorage.get<string>(key);
-
-  return storageValue && isValidTheme(storageValue)
-    ? (storageValue as PrismTheme)
-    : undefined;
-};
-
 export const PrismThemeProvider: FC<PrismThemeProviderProps> = ({
   attribute = 'data-prismjs-color-scheme-current',
   storageKey = 'prismjs-color-scheme',
   themes = ['dark', 'light', 'system'],
   children,
 }) => {
+  /**
+   * Retrieve the theme to use depending on `prefers-color-scheme`.
+   */
   const getThemeFromSystem = useCallback(() => {
     return prefersDarkScheme() ? 'dark' : 'light';
   }, []);
 
-  const [prismTheme, setPrismTheme] = useState<PrismTheme>(
-    getTheme(storageKey) || 'system'
-  );
-
-  const updateTheme = (theme: PrismTheme) => {
-    setPrismTheme(theme);
-  };
+  const { value: prismTheme, setValue: setPrismTheme } =
+    useLocalStorage<PrismTheme>(storageKey, 'system');
 
   useEffect(() => {
-    LocalStorage.set(storageKey, prismTheme);
-  }, [prismTheme, storageKey]);
+    if (!isValidTheme(prismTheme)) setPrismTheme('system');
+  }, [prismTheme, setPrismTheme]);
 
   const [resolvedTheme, setResolvedTheme] = useState<ResolvedPrismTheme>();
 
@@ -109,22 +107,12 @@ export const PrismThemeProvider: FC<PrismThemeProviderProps> = ({
         .removeEventListener('change', updateResolvedTheme);
   }, [updateResolvedTheme]);
 
-  const [preTags, setPreTags] = useState<NodeListOf<HTMLPreElement>>();
-
-  const updatePreTags = useCallback((tags: NodeListOf<HTMLPreElement>) => {
-    setPreTags(tags);
-  }, []);
-
-  const updatePreTagsAttribute = useCallback(() => {
-    preTags?.forEach((pre) => {
-      pre.setAttribute(attribute, prismTheme);
-    });
-  }, [attribute, preTags, prismTheme]);
-
-  useEffect(() => {
-    updatePreTagsAttribute();
-  }, [updatePreTagsAttribute, prismTheme]);
+  const preTags = useQuerySelectorAll<'pre'>('pre');
+  useAttributes({ elements: preTags, attribute, value: prismTheme });
 
+  /**
+   * Listen for changes on pre attributes and update theme.
+   */
   const listenAttributeChange = useCallback(
     (pre: HTMLPreElement) => {
       var observer = new MutationObserver(function (mutations) {
@@ -139,15 +127,12 @@ export const PrismThemeProvider: FC<PrismThemeProviderProps> = ({
         attributeFilter: [attribute],
       });
     },
-    [attribute]
+    [attribute, setPrismTheme]
   );
 
   useEffect(() => {
     if (!preTags) return;
-
-    preTags.forEach((pre) => {
-      listenAttributeChange(pre);
-    });
+    preTags.forEach(listenAttributeChange);
   }, [preTags, listenAttributeChange]);
 
   return (
@@ -155,9 +140,8 @@ export const PrismThemeProvider: FC<PrismThemeProviderProps> = ({
       value={{
         themes,
         theme: prismTheme,
-        setTheme: updateTheme,
+        setTheme: setPrismTheme,
         codeBlocks: preTags,
-        setCodeBlocks: updatePreTags,
         resolvedTheme,
       }}
     >
-- 
cgit v1.2.3

