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: add css variable support #39

Closed
wants to merge 3 commits into from
Closed
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: 5 additions & 0 deletions fixtures/Foo.mist.css
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
@scope (.foo) {
div:scope {
--background: var(--color-black);
--padding: var(--spacing-0);
--border: 1;
--test: true;

font-size: 1rem;

&[data-foo-size='lg'] {
Expand Down
31 changes: 27 additions & 4 deletions fixtures/Foo.mist.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,28 @@ import type { JSX, ReactNode } from 'react'

type FooProps = {
children?: ReactNode
background?: string
padding?: string
border?: string
test?: string
fooSize?: 'lg' | 'sm'
x?: boolean
} & JSX.IntrinsicElements['div']

export function Foo({ children, fooSize, x, ...props }: FooProps) {
export function Foo({ children, background, padding, border, test, fooSize, x, ...props }: FooProps) {
return (
<div {...props} className="foo" data-fooSize={fooSize} data-x={x}>
<div
{...props}
className="foo"
data-fooSize={fooSize}
data-x={x}
style={{
["--background" as string]: `${background.includes("var(--") ? `${background}` : `--color-${background}`}`,
["--padding" as string]: `${padding.includes("var(--") ? `${padding}` : `--spacing-${padding}`}`,
["--border" as string]: `${border}`,
["--test" as string]: `${test}`
}}
>
{children}
</div>
)
Expand All @@ -25,7 +40,12 @@ type BarProps = {

export function Bar({ children, barSize, x, ...props }: BarProps) {
return (
<span {...props} className="bar" data-barSize={barSize} data-x={x}>
<span
{...props}
className="bar"
data-barSize={barSize}
data-x={x}
>
{children}
</span>
)
Expand All @@ -37,7 +57,10 @@ type BazProps = {

export function Baz({ children, ...props }: BazProps) {
return (
<p {...props} className="baz">
<p
{...props}
className="baz"
>
{children}
</p>
)
Expand Down
9 changes: 6 additions & 3 deletions src/parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import assert from 'node:assert'
import fs from 'node:fs'
import test from 'node:test'

import { camelCase, type Components, parseInput, pascalCase } from './parser.js'
import {camelCase, type Components, parseInput, pascalCase} from './parser.js'

// Fixtures
const mistCSS: string = fs.readFileSync('fixtures/Foo.mist.css', 'utf-8')
Expand All @@ -22,13 +22,16 @@ void test('toPascalCase', () => {
})

void test('parseInput', () => {
const input: string = mistCSS
const actual: Components = parseInput(input)
const actual: Components = parseInput(mistCSS)
const expected: Components = {
Foo: {
className: 'foo',
tag: 'div',
data: {
'--background': 'string:--color',
'--border': 'string',
'--padding': 'string:--spacing',
'--test': 'string',
fooSize: ['lg', 'sm'],
x: true,
},
Expand Down
36 changes: 32 additions & 4 deletions src/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ export type Components = Record<string, Component>

export interface Component {
tag: string
data: Record<string, string[] | boolean>
data: Record<string, string | string[] | boolean>
className: string
}

const enumDataAttributeRegex =
/\[data-(?<attribute>[a-z-]+)='(?<value>[^']*)'\]/g
/\[data-(?<attribute>[a-z-]+)=('|")(?<value>[^']*)('|")\]/g
const booleanDataAttributeRegex = /\[data-(?<attribute>[a-z-]+)(?=\])/g

const pascalCaseRegex = /(?:^|-)([a-z])/g
Expand All @@ -26,10 +26,15 @@ export function camelCase(str: string): string {
}

// Visit all nodes in the AST and return @scope and rule nodes
function visit(nodes: Element[]): { type: string; props: string[] }[] {
let result: { type: string; props: string[] }[] = []
function visit(nodes: Element[]): { type: string; props: string[], value?: string }[] {
let result: { type: string; props: string[], value?: string }[] = []

for (const node of nodes) {
if (node.type === 'decl' && node.value.startsWith('--')) {
result.push({ type: node.type, props: Array.isArray(node.props) ? node.props : [node.props], value: node.value })
continue
}

if (['@scope', 'rule'].includes(node.type) && Array.isArray(node.props)) {
result.push({ type: node.type, props: node.props })
}
Expand Down Expand Up @@ -61,6 +66,29 @@ export function parseInput(input: string): Components {
continue
}

if (node.type === 'decl') {
const prop = node.props[0]
const prefix = node.value?.split(':var(')[1]?.replace(');', '')

if (prop === undefined || name === undefined) {
continue
}

const component = components[name]

if (component === undefined) {
continue
}

component.data[prop] ||= "string"

if (prefix) {
component.data[prop] = `string:${prefix.split(/(?<!-)(?=-[a-zA-Z0-9])/g)[0]}`
}

continue
}

// Parse tag and data attributes
if (node.type === 'rule') {
const prop = node.props[0]
Expand Down
5 changes: 5 additions & 0 deletions src/renderer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ void test('render', () => {
assert.ok(actual.includes('className="foo"'))
assert.ok(actual.includes('data-fooSize={fooSize}'))
assert.ok(actual.includes('data-x={x}'))
assert.ok(actual.includes('style={{'))
assert.ok(actual.includes('["--background" as string]: `${background.includes("var(--") ? `${background}` : `--color-${background}`}`,'))
assert.ok(actual.includes('["--padding" as string]: `${padding.includes("var(--") ? `${padding}` : `--spacing-${padding}`}`,'))
assert.ok(actual.includes('["--border" as string]: `${border}`,'))
assert.ok(actual.includes('["--test" as string]: `${test}`'))
assert.ok(actual.includes('{children}'))
assert.ok(actual.includes('type BarProps'))
assert.ok(actual.includes('export function Bar'))
Expand Down
32 changes: 22 additions & 10 deletions src/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,15 @@ function renderProps(component: Component): string {
...component.data,
})
.map(([key, value]) => {
if (key === 'children') {
return `${key}?: ${value}`
}
if (Array.isArray(value)) {
return `${key}?: ${value.map((v) => `'${v}'`).join(' | ')}`
}

if (Array.isArray(value)) {
return `${key}?: ${value.map((v) => `'${v}'`).join(' | ')}`
}
if (typeof value === "string") {
return `${key.startsWith('--') ? key.replace('--', '') : key}?: ${value.split(':')[0]}`
}

return `${key}?: boolean`
return `${key}?: boolean`
})
.map((line) => ` ${line}`)
.join('\n')
Expand All @@ -25,22 +25,34 @@ function renderComponent(components: Components, name: string): string {
if (component === undefined) {
return ''
}

const variables = Object.keys(component.data).filter(key => key.startsWith('--'));
const hasVariables = variables.length > 0;

return `type ${name}Props = {
${renderProps(component)}
} & JSX.IntrinsicElements['${component.tag}']

export function ${name}({ ${[
'children',
...Object.keys(component.data),
...Object.keys(component.data).map(key => key.startsWith('--') ? key.replace('--', '') : key),
'...props',
].join(', ')} }: ${name}Props) {
return (
<${[
component.tag,
'{...props}',
`className="${component.className}"`,
...Object.keys(component.data).map((key) => `data-${key}={${key}}`),
].join(' ')}>
...Object.keys(component.data).filter(key => !key.startsWith('--')).map((key) => `data-${key}={${key}}`),
hasVariables ? `style={{
${variables.map(key =>
(component.data[key] as string)?.includes(':') ?
`["${key}" as string]: \`\${${key.replace('--', '')}.includes("var(--") ? \`\${${key.replace('--', '')}}\` : \`${(component.data[key] as string).split(':')[1]}-\${${key.replace('--', '')}}\`}\``
: `["${key}" as string]: \`\${${key.replace('--', '')}}\``)
.join(',\r\n\t\t\t')}
}}` : null,
].filter(item => item !== null).join("\r\n\t\t")}
>
{children}
</${component.tag}>
)
Expand Down
Loading