From 60c49f18389ff625177a57277ef8f292a31097bf Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Sat, 28 Oct 2023 17:12:58 +0200
Subject: refactor(providers,hooks): rewrite PrismThemeProvider & usePrismTheme

* reuse Theme provider logic
* move DOM mutation from provider to hook
* add a script to init theme before page load
---
 src/pages/_document.tsx | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)

(limited to 'src/pages/_document.tsx')

diff --git a/src/pages/_document.tsx b/src/pages/_document.tsx
index 7e3b5e6..6d065cd 100644
--- a/src/pages/_document.tsx
+++ b/src/pages/_document.tsx
@@ -1,6 +1,12 @@
 import { Html, Head, Main, NextScript } from 'next/document';
 import Script from 'next/script';
-import { STORAGE_KEY } from '../utils/constants';
+import {
+  PRISM_THEME_ATTRIBUTE,
+  STORAGE_KEY,
+  VALID_THEMES,
+} from '../utils/constants';
+
+const validPrismThemesStr = VALID_THEMES.map((t) => `"${t}"`);
 
 // eslint-disable-next-line @typescript-eslint/no-shadow -- Required by NextJs
 export default function Document() {
@@ -25,6 +31,15 @@ export default function Document() {
           // eslint-disable-next-line react/jsx-no-literals
           strategy="beforeInteractive"
         />
+        <Script
+          dangerouslySetInnerHTML={{
+            __html: `!function(){const t=localStorage.getItem("${STORAGE_KEY.PRISM}"),e="string"==typeof t?JSON.parse(t):void 0,s=e&&[${validPrismThemesStr}].includes(e)?e:"system";document.documentElement.setAttribute("${PRISM_THEME_ATTRIBUTE}",s)}();`,
+          }}
+          // eslint-disable-next-line react/jsx-no-literals
+          id="prism-theme-hydration"
+          // eslint-disable-next-line react/jsx-no-literals
+          strategy="beforeInteractive"
+        />
       </Head>
       <body>
         <Main />
-- 
cgit v1.2.3

