Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(directives): support theme() function #1005

Merged
merged 6 commits into from May 25, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
213 changes: 130 additions & 83 deletions packages/transformer-directives/src/index.ts
@@ -1,6 +1,6 @@
import { cssIdRE, expandVariantGroup, notNull, regexScopePlaceholder } from '@unocss/core'
import type { SourceCodeTransformer, StringifiedUtil, UnoGenerator } from '@unocss/core'
import type { CssNode, List, ListItem, Selector, SelectorList } from 'css-tree'
import type { CssNode, List, ListItem, Rule, Selector, SelectorList } from 'css-tree'
import { clone, generate, parse, walk } from 'css-tree'
import type MagicString from 'magic-string'

Expand Down Expand Up @@ -38,7 +38,12 @@ export async function transformDirectives(
offset?: number,
) {
const { varStyle = '--at-' } = options
if (!code.original.includes('@apply') && (varStyle === false || !code.original.includes(varStyle)))

const isApply = code.original.includes('@apply') || (varStyle !== false && code.original.includes(varStyle))

const isTheme = /theme\([^)]*\)/.test(code.original)

if (!isApply && !isTheme)
return

const ast = parse(originalCode || code.original, {
Expand All @@ -47,99 +52,141 @@ export async function transformDirectives(
filename,
})

const calcOffset = (pos: number) => offset ? pos + offset : pos

if (ast.type !== 'StyleSheet')
return

const stack: Promise<void>[] = []
const calcOffset = (pos: number) => offset ? pos + offset : pos

const processNode = async (node: CssNode, _item: ListItem<CssNode>, _list: List<CssNode>) => {
if (node.type !== 'Rule')
const handleApply = async (node: Rule, childNode: CssNode) => {
let body: string | undefined
if (childNode.type === 'Atrule' && childNode.name === 'apply' && childNode.prelude && childNode.prelude.type === 'Raw') {
body = childNode.prelude.value.trim()
}
else if (varStyle !== false && childNode.type === 'Declaration' && childNode.property === `${varStyle}apply` && childNode.value.type === 'Raw') {
body = childNode.value.value.trim()
// remove quotes
if (body.match(/^(['"]).*\1$/))
body = body.slice(1, -1)
}

if (!body)
return

await Promise.all(
node.block.children.map(async (childNode, _childItem) => {
if (childNode.type === 'Raw')
return transformDirectives(code, uno, options, filename, childNode.value, calcOffset(childNode.loc!.start.offset))
const classNames = expandVariantGroup(body).split(/\s+/g)
const utils = (
await Promise.all(
classNames.map(i => uno.parseToken(i, '-')),
))
.filter(notNull).flat()
.sort((a, b) => a[0] - b[0])
.sort((a, b) => (a[3] ? uno.parentOrders.get(a[3]) ?? 0 : 0) - (b[3] ? uno.parentOrders.get(b[3]) ?? 0 : 0))
.reduce((acc, item) => {
const target = acc.find(i => i[1] === item[1] && i[3] === item[3])
if (target)
target[2] += item[2]
else
// use spread operator to prevent reassign to uno internal cache
acc.push([...item] as Writeable<StringifiedUtil>)
return acc
}, [] as Writeable<StringifiedUtil>[])

if (!utils.length)
return

let body: string | undefined
if (childNode.type === 'Atrule' && childNode.name === 'apply' && childNode.prelude && childNode.prelude.type === 'Raw') {
body = childNode.prelude.value.trim()
}
else if (varStyle !== false && childNode.type === 'Declaration' && childNode.property === `${varStyle}apply` && childNode.value.type === 'Raw') {
body = childNode.value.value.trim()
// remove quotes
if (body.match(/^(['"]).*\1$/))
body = body.slice(1, -1)
for (const i of utils) {
const [, _selector, body, parent] = i
const selector = _selector?.replace(regexScopePlaceholder, ' ') || _selector

if (parent || (selector && selector !== '.\\-')) {
let newSelector = generate(node.prelude)
if (selector && selector !== '.\\-') {
const selectorAST = parse(selector, {
context: 'selector',
}) as Selector

const prelude = clone(node.prelude) as SelectorList

prelude.children.forEach((child) => {
const parentSelectorAst = clone(selectorAST) as Selector
parentSelectorAst.children.forEach((i) => {
if (i.type === 'ClassSelector' && i.name === '\\-')
Object.assign(i, clone(child))
})
Object.assign(child, parentSelectorAst)
})
newSelector = generate(prelude)
}

if (!body)
return

const classNames = expandVariantGroup(body).split(/\s+/g)
const utils = (
await Promise.all(
classNames.map(i => uno.parseToken(i, '-')),
))
.filter(notNull).flat()
.sort((a, b) => a[0] - b[0])
.sort((a, b) => (a[3] ? uno.parentOrders.get(a[3]) ?? 0 : 0) - (b[3] ? uno.parentOrders.get(b[3]) ?? 0 : 0))
.reduce((acc, item) => {
const target = acc.find(i => i[1] === item[1] && i[3] === item[3])
if (target)
target[2] += item[2]
else
// use spread operator to prevent reassign to uno internal cache
acc.push([...item] as Writeable<StringifiedUtil>)
return acc
}, [] as Writeable<StringifiedUtil>[])

if (!utils.length)
return

for (const i of utils) {
const [, _selector, body, parent] = i
const selector = _selector?.replace(regexScopePlaceholder, ' ') || _selector

if (parent || (selector && selector !== '.\\-')) {
let newSelector = generate(node.prelude)
if (selector && selector !== '.\\-') {
const selectorAST = parse(selector, {
context: 'selector',
}) as Selector

const prelude = clone(node.prelude) as SelectorList

prelude.children.forEach((child) => {
const parentSelectorAst = clone(selectorAST) as Selector
parentSelectorAst.children.forEach((i) => {
if (i.type === 'ClassSelector' && i.name === '\\-')
Object.assign(i, clone(child))
})
Object.assign(child, parentSelectorAst)
})
newSelector = generate(prelude)
}

let css = `${newSelector}{${body}}`
if (parent)
css = `${parent}{${css}}`

code.appendLeft(calcOffset(node.loc!.end.offset), css)
}
else {
code.appendRight(calcOffset(childNode.loc!.end.offset), body)
}
}
code.remove(
calcOffset(childNode.loc!.start.offset),
calcOffset(childNode.loc!.end.offset),
)
}).toArray(),
let css = `${newSelector}{${body}}`
if (parent)
css = `${parent}{${css}}`

code.appendLeft(calcOffset(node.loc!.end.offset), css)
}
else {
code.appendRight(calcOffset(childNode.loc!.end.offset), body)
}
}
code.remove(
calcOffset(childNode.loc!.start.offset),
calcOffset(childNode.loc!.end.offset),
)
}

const handleTheme = (node: CssNode) => {
if (node.type === 'Function' && node.name === 'theme' && node.children) {
const children = node.children.toArray().filter(n => n.type === 'String')
if (!children.length)
return

const matchedThemes = children.map((childNode) => {
if (childNode.type !== 'String')
return null

const keys = childNode.value.split('.')

let value: any = uno.config.theme

keys.every((key) => {
if (!Reflect.has(value, key)) {
value = null
return false
}
value = value[key]
return true
})

return typeof value === 'string' ? value : null
}).filter(Boolean)

if (matchedThemes.length !== children.length)
return

code.overwrite(
calcOffset(node.loc!.start.offset),
calcOffset(node.loc!.end.offset),
matchedThemes.join(' '))
}
}

const stack: Promise<void>[] = []

const processNode = async (node: CssNode, _item: ListItem<CssNode>, _list: List<CssNode>) => {
if (isTheme)
await handleTheme(node)

if (isApply && node.type === 'Rule') {
await Promise.all(
node.block.children.map(async (childNode, _childItem) => {
if (childNode.type === 'Raw')
return transformDirectives(code, uno, options, filename, childNode.value, calcOffset(childNode.loc!.start.offset))

await handleApply(node, childNode)
}).toArray(),
)
}
}

walk(ast, (...args) => stack.push(processNode(...args)))

await Promise.all(stack)
Expand Down
27 changes: 27 additions & 0 deletions test/transformer-directives.test.ts
Expand Up @@ -395,4 +395,31 @@ describe('transformer-directives', () => {
"
`)
})

describe('theme', () => {
test('basic', async () => {
const result = await transform(
`.btn {
background-color: theme("colors.blue.500");
padding: theme("spacing.xs", "spacing.sm");
margin: theme("spacing.xs", "spacing.sm", "spacing.xl", "spacing.lg");

color: theme("color.none.500");
font-size: theme("size.lg");
}`,
)
expect(result)
.toMatchInlineSnapshot(`
".btn {
background-color: #3b82f6;
padding: 0.75rem 0.875rem;
margin: 0.75rem 0.875rem 1.25rem 1.125rem;

color: theme(\\"color.none.500\\");
font-size: theme(\\"size.lg\\");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we throw on none-exist utils?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we throw on none-exist utils?

I think it would be better to keep the non-existent utils to better troubleshoot the problem.

}
"
`)
})
})
})