From aca903feabcc320b68588aa39f9baa528403772a Mon Sep 17 00:00:00 2001 From: Joseph Garrone Date: Mon, 18 Sep 2023 16:30:45 +0200 Subject: [PATCH] #180: Support emotion prepend in Next App router --- src/next/appDir.tsx | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/src/next/appDir.tsx b/src/next/appDir.tsx index bcf3c7c..fa6f81c 100644 --- a/src/next/appDir.tsx +++ b/src/next/appDir.tsx @@ -11,7 +11,9 @@ import type { ReactNode } from "react"; export type NextAppDirEmotionCacheProviderProps = { /** This is the options passed to createCache() from 'import createCache from "@emotion/cache"' */ - options: Omit; + options: Omit & { + prepend?: boolean; + }; /** By default from 'import { CacheProvider } from "@emotion/react"' */ CacheProvider?: (props: { value: EmotionCache; @@ -23,7 +25,13 @@ export type NextAppDirEmotionCacheProviderProps = { export function NextAppDirEmotionCacheProvider( props: NextAppDirEmotionCacheProviderProps ) { - const { options, CacheProvider = DefaultCacheProvider, children } = props; + const { + options: optionsWithPrepend, + CacheProvider = DefaultCacheProvider, + children + } = props; + + const { prepend = false, ...options } = optionsWithPrepend; const [{ cache, flush }] = useState(() => { const cache = createCache(options); @@ -76,6 +84,9 @@ export function NextAppDirEmotionCacheProvider( } } + const get__Html = (style: string) => + prepend ? `@layer emotion {${style}}` : style; + return ( <> {globals.map(({ name, style }) => ( @@ -83,14 +94,16 @@ export function NextAppDirEmotionCacheProvider( nonce={options.nonce} key={name} data-emotion={`${cache.key}-global ${name}`} - dangerouslySetInnerHTML={{ "__html": style }} + dangerouslySetInnerHTML={{ "__html": get__Html(style) }} /> ))} {styles !== "" && (