File size: 1,375 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import { CacheProvider } from "@emotion/react"
import createEmotionServer from "@emotion/server/create-instance"
import { renderToString } from "react-dom/server"
import { ChakraProvider } from "../components/chakra-provider"
import { createEmotionCache } from "./emotion-cache"

export function createEmotion() {
  const cache = createEmotionCache()
  const server = createEmotionServer(cache)

  function injectStyles(html: string) {
    const { styles } = server.extractCriticalToChunks(html)

    let stylesHTML = ""

    styles.forEach(({ key, ids, css }) => {
      const emotionKey = `${key} ${ids.join(" ")}`
      const newStyleTag = `<style data-emotion="${emotionKey}">${css}</style>`
      stylesHTML = `${stylesHTML}${newStyleTag}`
    })

    // add the emotion style tags after the insertion point meta tag
    const markup = html.replace(
      /<meta(\s)*name="emotion-insertion-point"(\s)*content="emotion-insertion-point"(\s)*\/>/,
      `<meta name="emotion-insertion-point" content="emotion-insertion-point"/>${stylesHTML}`,
    )

    return markup
  }

  function _renderToString(element: React.ReactNode) {
    return renderToString(
      <CacheProvider value={cache}>
        <ChakraProvider>{element}</ChakraProvider>
      </CacheProvider>,
    )
  }

  return {
    server,
    cache,
    injectStyles,
    renderToString: _renderToString,
  }
}