Skip to content

Commit

Permalink
#180: Support emotion prepend in Next App router
Browse files Browse the repository at this point in the history
  • Loading branch information
garronej committed Sep 18, 2023
1 parent da6cc4e commit aca903f
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/next/appDir.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<OptionsOfCreateCache, "insertionPoint">;
options: Omit<OptionsOfCreateCache, "insertionPoint"> & {
prepend?: boolean;
};
/** By default <CacheProvider /> from 'import { CacheProvider } from "@emotion/react"' */
CacheProvider?: (props: {
value: EmotionCache;
Expand All @@ -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);
Expand Down Expand Up @@ -76,21 +84,26 @@ export function NextAppDirEmotionCacheProvider(
}
}

const get__Html = (style: string) =>
prepend ? `@layer emotion {${style}}` : style;

return (
<>
{globals.map(({ name, style }) => (
<style
nonce={options.nonce}
key={name}
data-emotion={`${cache.key}-global ${name}`}
dangerouslySetInnerHTML={{ "__html": style }}
dangerouslySetInnerHTML={{ "__html": get__Html(style) }}
/>
))}
{styles !== "" && (
<style
nonce={options.nonce}
data-emotion={dataEmotionAttribute}
dangerouslySetInnerHTML={{ "__html": styles }}
dangerouslySetInnerHTML={{
"__html": get__Html(styles)
}}
/>
)}
</>
Expand Down

0 comments on commit aca903f

Please sign in to comment.