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(transformer-directives): Implemented @screen directive #1434

Merged
merged 3 commits into from Aug 21, 2022
Merged
Show file tree
Hide file tree
Changes from 2 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
38 changes: 36 additions & 2 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, Declaration, List, ListItem, Rule, Selector, SelectorList } from 'css-tree'
import type { Atrule, CssNode, Declaration, 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 @@ -37,6 +37,7 @@ export default function transformerDirectives(options: TransformerDirectivesOpti
}

const themeFnRE = /theme\((.*?)\)/g
const screenRuleRE = /(@screen) (.+) /g

export async function transformDirectives(
code: MagicString,
Expand All @@ -52,9 +53,10 @@ export async function transformDirectives(
} = options

const isApply = code.original.includes('@apply') || (varStyle !== false && code.original.includes(varStyle))
const isScreen = code.original.includes('@screen')
const hasThemeFn = code.original.match(themeFnRE)

if (!isApply && !hasThemeFn)
if (!isApply && !hasThemeFn && !isScreen)
return

const ast = parse(originalCode || code.original, {
Expand Down Expand Up @@ -187,9 +189,41 @@ export async function transformDirectives(
}
}

const handleScreen = (node: Atrule) => {
let breakpointName
if (node.name === 'screen' && node.prelude && node.prelude.type === 'Raw')
breakpointName = node.prelude.value.trim()

if (!breakpointName)
return

// @ts-expect-error breakpoints aren't always available
const breakpointPx = uno.config.theme.breakpoints ? uno.config.theme.breakpoints[breakpointName] : null
if (!breakpointPx)
throw new Error(`breakpoint ${breakpointName} not found`)

const offset = node.loc!.start.offset
const str = code.original.slice(offset, node.loc!.end.offset)
const matches = Array.from(str.matchAll(screenRuleRE))

if (!matches.length)
return

for (const match of matches) {
code.overwrite(
offset + match.index!,
offset + match.index! + match[0].length,
`@media (min-width: ${breakpointPx}) `,
)
}
}

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

const processNode = async (node: CssNode, _item: ListItem<CssNode>, _list: List<CssNode>) => {
if (isScreen && node.type === 'Atrule')
handleScreen(node)

if (hasThemeFn && node.type === 'Declaration')
handleThemeFn(node)

Expand Down
100 changes: 96 additions & 4 deletions test/transformer-directives.test.ts
Expand Up @@ -396,10 +396,102 @@ describe('transformer-directives', () => {
`)
})

test('basic', async () => {
const customUno = createGenerator({
presets: [
presetUno(),
],
theme: {
breakpoints: {
xs: '320px',
sm: '640px',
md: '768px',
lg: '1024px',
xl: '1280px',
xxl: '1536px',
},
},
})
const result = await transform(
`.grid {
@apply grid grid-cols-2;
}
@screen xs {
.grid {
@apply grid-cols-1;
}
}
@screen sm {
.grid {
@apply grid-cols-3;
}
}
@screen md {
.grid {
@apply grid-cols-4;
}
}
@screen lg {
.grid {
@apply grid-cols-5;
}
}
@screen xl {
.grid {
@apply grid-cols-6;
}
}
@screen xxl {
.grid {
@apply grid-cols-7;
}
}`,
customUno,
)
expect(result)
.toMatchInlineSnapshot(`
".grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
}
@media (min-width: 320px) {
.grid {
grid-template-columns: repeat(1, minmax(0, 1fr));
}
}
@media (min-width: 640px) {
.grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
@media (min-width: 768px) {
.grid {
grid-template-columns: repeat(4, minmax(0, 1fr));
}
}
@media (min-width: 1024px) {
.grid {
grid-template-columns: repeat(5, minmax(0, 1fr));
}
}
@media (min-width: 1280px) {
.grid {
grid-template-columns: repeat(6, minmax(0, 1fr));
}
}
@media (min-width: 1536px) {
.grid {
grid-template-columns: repeat(7, minmax(0, 1fr));
}
}
"
`)
})

describe('theme()', () => {
test('basic', async () => {
const result = await transform(
`.btn {
`.btn {
background-color: theme("colors.blue.500");
padding: theme("spacing.xs") theme("spacing.sm");
}
Expand All @@ -422,14 +514,14 @@ describe('transformer-directives', () => {

test('non-exist', async () => {
expect(async () => await transform(
`.btn {
`.btn {
color: theme("color.none.500");
}`,
)).rejects
.toMatchInlineSnapshot('[Error: theme of "color.none.500" did not found]')

expect(async () => await transform(
`.btn {
`.btn {
font-size: theme("size.lg");
}`,
)).rejects
Expand All @@ -438,7 +530,7 @@ describe('transformer-directives', () => {

test('args', async () => {
expect(async () => await transform(
`.btn {
`.btn {
color: theme();
}`,
)).rejects
Expand Down