Skip to content

Commit d5dcee5

Browse files
committed
More robust style tag
1 parent d6c3dc7 commit d5dcee5

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

packages/mdx/src/remark/transform.ts

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,20 +96,47 @@ function getUsedCodeHikeComponentNames(
9696
return usage
9797
}
9898

99+
const styleCache = new Map<string, string>()
100+
101+
async function getStyle(
102+
theme: CodeHikeConfig["theme"],
103+
themeName: string
104+
) {
105+
if (styleCache.has(themeName)) {
106+
return styleCache.get(themeName)
107+
}
108+
const rules = await getCSSVariables(theme)
109+
const style = `[data-ch-theme="${themeName}"] \{ ${rules} \}`
110+
styleCache.set(themeName, style)
111+
return style
112+
}
113+
99114
async function getCSSVariables(
100115
theme: CodeHikeConfig["theme"]
101116
) {
102117
const themeColors = await getThemeColors(theme)
118+
119+
if (!themeColors || typeof themeColors !== "object") {
120+
throw new Error(
121+
"[Code Hike error] Unknown theme format"
122+
)
123+
}
103124
let rules = ""
104125
for (const [first, value] of Object.entries(
105126
themeColors
106127
)) {
128+
if (!value) {
129+
continue
130+
}
107131
if (typeof value === "string") {
108132
rules += `--ch-t-${first}: ${value};`
109133
} else {
110134
for (const [second, svalue] of Object.entries(
111135
value
112136
)) {
137+
if (!svalue) {
138+
continue
139+
}
113140
rules += `--ch-t-${first}-${second}: ${svalue};`
114141
}
115142
}
@@ -128,10 +155,9 @@ async function addConfig(
128155
config: CodeHikeConfig
129156
) {
130157
const { theme } = config
131-
const rules = await getCSSVariables(theme)
132158
const themeName =
133159
typeof theme === "string" ? theme : theme.name
134-
const style = `[data-ch-theme="${themeName}"] \{ ${rules} \}`
160+
const style = await getStyle(theme, themeName)
135161

136162
const codeConfig = {
137163
staticMediaQuery: config.staticMediaQuery,

0 commit comments

Comments
 (0)