Skip to content

Commit 4e7e7fd

Browse files
authored
feat(transformer-directives): support default value for theme function (#4787)
1 parent 0a8d10d commit 4e7e7fd

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

packages-presets/transformer-directives/src/functions.ts

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,25 @@ export async function handleFunction({ code, uno, options }: TransformerDirectiv
88

99
switch (node.name) {
1010
case 'theme': {
11-
if (node.children.size !== 1)
11+
if (!node.children.size)
1212
throw new Error('theme() expect exact one argument')
1313

1414
if (node.children.first!.type !== 'String')
1515
throw new Error('theme() expect a string argument')
1616

17+
let defaultValueLoc: [number, number] | undefined
18+
if (node.children.size > 1) {
19+
const remains = node.children.toArray().slice(1)
20+
if (!(remains[0].type === 'Operator' && remains[0].value === ','))
21+
throw new Error('theme() expect a comma between expression string and default value')
22+
if (remains.length > 1)
23+
defaultValueLoc = [remains[1].loc!.start.offset, node.children.last!.loc!.end.offset]
24+
}
25+
1726
const themeStr = node.children.first.value
18-
const value = transformThemeString(themeStr, uno.config.theme, throwOnMissing)
27+
let value = transformThemeString(themeStr, uno.config.theme, !defaultValueLoc && throwOnMissing)
28+
if (!value && defaultValueLoc)
29+
value = code.slice(defaultValueLoc[0], defaultValueLoc[1])
1930
if (value)
2031
code.overwrite(node.loc!.start.offset, node.loc!.end.offset, value)
2132

test/transformer-directives.test.ts

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1508,6 +1508,28 @@ describe('wind4', () => {
15081508
`)
15091509
})
15101510

1511+
it('theme() with defaults', async () => {
1512+
const result = await transform(
1513+
`.btn {
1514+
color: theme('not.exists.color', #fff);
1515+
font-family: theme('not.exists.font', 'ui-sans-serif', 'system-ui');
1516+
}`,
1517+
)
1518+
1519+
await expect(result)
1520+
.toMatchInlineSnapshot(`
1521+
".btn {
1522+
color: #fff;
1523+
font-family: "ui-sans-serif", "system-ui";
1524+
}
1525+
"
1526+
`)
1527+
1528+
await expect(transform(`.foo { color: theme('not.exists' ) }`)).rejects.toThrow()
1529+
await expect(transform(`.foo { color: theme('not.exists', ) }`)).rejects.toThrow()
1530+
await expect(transform(`.foo { color: theme('not.exists' #fff) }`)).rejects.toThrow('comma')
1531+
})
1532+
15111533
it('border opacity', async () => {
15121534
const result = await transform(
15131535
`.btn {

0 commit comments

Comments
 (0)