Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions packages/@expressive-code/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,10 @@
},
"dependencies": {
"@ctrl/tinycolor": "^4.0.4",
"hast-util-select": "^6.0.2",
"@eslint/css-tree": "3.6.9",
"hast-util-to-html": "^9.0.1",
"hast-util-to-text": "^4.0.1",
"hastscript": "^9.0.0",
"postcss": "^8.4.38",
"postcss-nested": "^6.0.1",
"unist-util-visit": "^5.0.0",
"unist-util-visit-parents": "^6.0.1"
},
Expand All @@ -59,6 +57,7 @@
"@types/hast": "^3.0.4",
"culori": "^4.0.1",
"djb2a": "^2.0.0",
"hast-util-select": "^6.0.2",
"hast-util-sanitize": "^5.0.1",
"shiki": "^4.0.2",
"strip-json-comments": "^5.0.1"
Expand Down
10 changes: 6 additions & 4 deletions packages/@expressive-code/core/src/common/engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ export class ExpressiveCodeEngine implements ResolvedExpressiveCodeEngineConfig
})
}
// Process styles (scoping, minifying, etc.)
const processedStyles = await processPluginStyles(pluginStyles)
const processedStyles = processPluginStyles(pluginStyles)
return wrapInCascadeLayer([...processedStyles].join(''), this.cascadeLayer)
}

Expand All @@ -376,6 +376,8 @@ export class ExpressiveCodeEngine implements ResolvedExpressiveCodeEngineConfig
* Please note that these styles must be added to the page together with the base styles
* returned by {@link getBaseStyles}.
*/
// Keep the public Promise-returning API even though CSS processing is synchronous.
// eslint-disable-next-line @typescript-eslint/require-await
async getThemeStyles(): Promise<string> {
const themeStyles: string[] = []
const renderDeclarations = (declarations: Map<string, string>) => [...declarations].map(([varName, varValue]) => `${varName}:${varValue}`).join(';')
Expand Down Expand Up @@ -404,7 +406,7 @@ export class ExpressiveCodeEngine implements ResolvedExpressiveCodeEngineConfig
.filter((selector) => selector)
.join(',')
themeStyles.push(
await scopeAndMinifyNestedCss(`
scopeAndMinifyNestedCss(`
${baseVarSelectors} {
${renderDeclarations(baseVars)}
}
Expand Down Expand Up @@ -448,7 +450,7 @@ export class ExpressiveCodeEngine implements ResolvedExpressiveCodeEngineConfig
this.themes.map((theme) => `${theme.name} (${theme.type})`).join(', '),
].join(' ')
)
const darkModeMediaQuery = await scopeAndMinifyNestedCss(`
const darkModeMediaQuery = scopeAndMinifyNestedCss(`
@media (prefers-color-scheme: ${altType}) {
${this.themeCssRoot}${notBaseThemeSelector} {
${firstAltVariant.cssVars}
Expand All @@ -468,7 +470,7 @@ export class ExpressiveCodeEngine implements ResolvedExpressiveCodeEngineConfig
if (!themeSelector) continue

themeStyles.push(
await scopeAndMinifyNestedCss(`
scopeAndMinifyNestedCss(`
${this.themeCssRoot}${themeSelector} &${notBaseThemeSelector}, &${themeSelector} {
${cssVars};
${coreStyles}
Expand Down
40 changes: 18 additions & 22 deletions packages/@expressive-code/core/src/hast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@ import { matches, select, selectAll } from 'hast-util-select'
import { visit } from 'unist-util-visit'
import { visitParents, CONTINUE, EXIT, SKIP } from 'unist-util-visit-parents'
import { h, s } from 'hastscript'
import postcss, { Declaration } from 'postcss'
import type { DeclarationList } from '@eslint/css-tree'
import { generate, parse } from './internal/css-tree'
import { serializeCssStringValue } from './internal/escaping'
import { validateCssDelimiters } from './internal/css'

export { visit, visitParents, CONTINUE, EXIT, SKIP }
export { toHtml, toText, matches, select, selectAll, h, s }
Expand Down Expand Up @@ -72,19 +74,23 @@ export function getInlineStyles(node: Element): Map<string, string> {
const styleString = node.properties?.style?.toString().trim() || ''
if (!styleString) return styles

// @ts-expect-error PostCSS has incorrect types when using exactOptionalPropertyTypes
const postCssOptions: { from?: string } = { from: undefined }

// Attempt to parse the style string and extract its root-level declarations
try {
const root = postcss.parse(styleString, postCssOptions)

// Extract all root-level declarations into the styles map
root.each((node) => {
if (node.type === 'decl') styles.set(node.prop, node.value)
})
validateCssDelimiters(styleString)
const declarationList = parse(styleString, {
context: 'declarationList',
positions: true,
onParseError(error) {
throw error
},
}) as DeclarationList
for (const declaration of declarationList.children) {
if (declaration.type !== 'Declaration') throw new Error('Invalid inline style declaration')
const value = declaration.value.loc ? styleString.slice(declaration.value.loc.start.offset, declaration.value.loc.end.offset).trim() : generate(declaration.value)
styles.set(declaration.property, value)
}
} catch {
// Treat invalid inline styles as if they were empty
styles.clear()
}

return styles
Expand All @@ -96,17 +102,7 @@ export function getInlineStyles(node: Element): Map<string, string> {
* Any existing styles will be overwritten.
*/
export function setInlineStyles(node: Element, styles: Map<string, string>) {
const styleString = [...styles]
.map(([prop, value]) =>
new Declaration({
prop,
value,
raws: {
between: ':',
},
}).toString()
)
.join(';')
const styleString = [...styles].map(([prop, value]) => `${prop}:${value}`).join(';')
setProperty(node, 'style', styleString)
}

Expand Down
7 changes: 7 additions & 0 deletions packages/@expressive-code/core/src/internal/css-tree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import type * as CssTree from '@eslint/css-tree'
// @ts-expect-error The browser bundle is exported without a matching declaration file.
import * as browserRuntime from '@eslint/css-tree/dist/csstree.esm'

const cssTree = browserRuntime as Pick<typeof CssTree, 'fork' | 'generate' | 'parse' | 'walk'>

export const { fork, generate, parse, walk } = cssTree
Loading