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

Feature/css theming #1613

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
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: 4 additions & 1 deletion .stylelintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,8 @@ module.exports = {
reportDescriptionlessDisables: true,
reportNeedlessDisables: true,
reportInvalidScopeDisables: true,
rules: {},
rules: {
// TODO reenable this
'no-descending-specificity': null,
},
}
11 changes: 4 additions & 7 deletions packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,14 @@
"import": "./dist/index.mjs"
}
},
"files": [
"dist",
"src",
"bin",
"bin.js"
],
"files": ["dist", "src", "bin", "bin.js"],
"engines": {
"node": ">=16"
},
"scripts": {
"build": "tsup src --format=esm,cjs --dts --no-splitting --shims"
"build": "tsup src --format=esm,cjs --dts --no-splitting --shims",
"dev": "tsup src --format=esm,cjs --dts --no-splitting --shims --watch",
"cli": "node ./bin.js"
},
"devDependencies": {
"@types/node": "20.4.5"
Expand Down
14 changes: 13 additions & 1 deletion packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Command } from 'commander'
import { css } from '@vtex/shoreline-css'
import { css, theme } from '@vtex/shoreline-css'

const program = new Command()

Expand All @@ -10,4 +10,16 @@ program
.description('Generate CSS Variables from tokens')
.action(css)

program
.command('theme')
.option('-f, --file <type>', 'file path', 'src/theme.css')
.option('-o, --out <type>', 'output file', 'src/theme-parsed.css')
.action((options) => {
// console.log(options)
theme({
filepath: options.file,
out: options.out,
})
})

program.parse()
13 changes: 8 additions & 5 deletions packages/css/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,30 @@
"import": "./dist/index.mjs"
}
},
"files": [
"dist"
],
"files": ["dist"],
"engines": {
"node": ">=18"
},
"scripts": {
"build": "tsup"
"build": "tsup",
"dev": "tsup --watch"
},
"devDependencies": {
"@types/cssesc": "3.0.0",
"@types/culori": "2.1.0",
"@types/fs-extra": "11.0.1",
"@types/node": "20.4.5"
},
"dependencies": {
"@vtex/shoreline-utils": "workspace:*",
"c12": "1.5.1",
"cssesc": "3.0.0",
"culori": "4.0.1",
"fs-extra": "11.1.1",
"postcss": "8.4.27",
"postcss-preset-env": "9.3.0",
"prettier": "3.0.0"
"prettier": "3.0.0",
"browserslist": "4.23.0",
"lightningcss": "1.24.1"
}
}
1 change: 1 addition & 0 deletions packages/css/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './css'
export * from './config'
export * from './token-collection'
export * from './types'
export * from './theme'
172 changes: 172 additions & 0 deletions packages/css/src/theme.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import browserslist from 'browserslist'
import {
transform,
browserslistToTargets,
type TokenOrValue,
} from 'lightningcss'
import path from 'node:path'
import fs from 'fs-extra'
import { kebabCase } from '@vtex/shoreline-utils'
import { format } from 'prettier'
import { formatHex } from 'culori'

const targets = browserslistToTargets(browserslist('>= 0.25%'))

interface Props {
filepath: string
out: string
}

const declared: Record<string, string> = {}

export async function theme(props: Props) {
const { filepath, out } = props

const { code } = transform({
filename: 'shoreline.css',
minify: false,
targets,
code: fs.readFileSync(`${path.dirname('')}/${filepath}`),
visitor: {
DeclarationExit: {
custom({ name, value }) {
// declared[(toJsProp(name), value)
declared[toJsProp(name)] = value.map(stringifyValue).join('')
},
},
Selector(selectors) {
const [themeSelector] = selectors

if (
themeSelector.type === 'attribute' &&
themeSelector.name === 'data-sl-theme' &&
themeSelector.operation?.operator === 'equal'
) {
return [
{
type: 'pseudo-class',
kind: 'root',
},
]
}

throw new Error('A new theme must be declared under [data-sl-theme]')
},
},
})

const unformatedTs = `export const theme = ${JSON.stringify(declared)};`

const formattedTs = await format(unformatedTs, {
parser: 'typescript',
semi: false,
singleQuote: true,
})

fs.outputFile(`${path.dirname('')}/${out}`, prefixCode(code), (err) => {
if (err) {
console.log(err)
} else {
console.log('✅ Styles')
}
})

fs.outputFile(
`${path.dirname('')}/${out.replace('.css', '.ts')}`,
formattedTs,
(err) => {
if (err) {
console.log(err)
} else {
console.log('✅ Ts')
}
}
)
}

function toJsProp(str: string) {
return kebabCase(String(str).replace(/--/gi, ''))
}

function stringifyValue(tkov: TokenOrValue) {
switch (tkov.type) {
case 'length':
return `${tkov.value.value}${tkov.value.unit}`
case 'token':
if (
tkov.value.type === 'ident' ||
tkov.value.type === 'number' ||
tkov.value.type === 'string' ||
tkov.value.type === 'delim' ||
tkov.value.type === 'white-space'
) {
// identifiers are passed through
return tkov.value.value
}
if (tkov.value.type === 'percentage') {
// css percentages
return `${Math.floor(Number(tkov.value.value) * 100)}%`
}
if (tkov.value.type === 'comma') {
return ','
}

return ''
case 'color': {
// @ts-ignore
const { type, ...rest } = tkov.value
console.log({
type,
...rest,
})
// all colors come as rgba
const raw = `rgba(${rest.r}, ${rest.g}, ${rest.b}, ${rest.alpha})`

return formatHex(raw)
}
case 'var': {
return `var(${tkov.value.name.ident.replace(/--/gi, '--sl-')})`
}
case 'function': {
return `${tkov.value.name}(${tkov.value.arguments
.map((argument) => {
if (argument.type === 'token') {
if (argument.value.type === 'ident') {
// identifiers are passed through
return argument.value.value
}
if (argument.value.type === 'percentage') {
// css percentages
return `${Math.floor(Number(argument.value.value) * 100)}%`
}
if (argument.value.type === 'white-space') {
return ' '
}
if (argument.value.type === 'comma') {
return ','
}

return ''
}

if (argument.type === 'var') {
return `var(${argument.value.name?.ident?.replace(
/--/gi,
'--sl-'
)})`
}

return ''
})
.join('')})`
}
default:
return ''
}
}

function prefixCode(code: Uint8Array, prefix = 'sl') {
const str = String(code.toString())
const replaced = str.replace(/--/gi, `--${prefix}-`)
return Buffer.from(replaced)
}
7 changes: 7 additions & 0 deletions packages/docs/components/tokens-grid/grid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import styles from './grid.module.css'

export function TokensGrid(props: TokensTableProps) {
const { foundation = 'color' } = props
console.log({
foundation,
})

return (
<div
Expand All @@ -26,7 +29,11 @@ export function TokensGrid(props: TokensTableProps) {
<Head>CSS Variable</Head>
<Head>Value</Head>
{foundation === 'breakpoint' ? null : <Head>Preview</Head>}

{getFoundationTokens(foundation).map((token) => {
console.log({
token,
})
const {
name,
variable,
Expand Down
16 changes: 12 additions & 4 deletions packages/docs/components/tokens-grid/theme-utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { theme } from '../../shoreline/theme'
import { presetSunrise } from '@vtex/shoreline'

const tokenPrefix = '--sl-'

export function getFoundationTokens(foundation: Foundation) {
const tokens = Object.keys(theme)
const tokens = Object.keys(presetSunrise)

const foundationTokens = tokens.filter((token) => {
if (foundation === 'border') {
Expand All @@ -16,6 +16,7 @@ export function getFoundationTokens(foundation: Foundation) {
})

if (foundation === 'typography') {
console.log(sanitizeTypographyTokens(foundationTokens))
return sanitizeTypographyTokens(foundationTokens)
}

Expand All @@ -42,7 +43,11 @@ function sanitizeTypographyTokens(tokens: string[]) {
}, [])
}

export function getTokenValues(token: string, foundation: Foundation) {
export function getTokenValues(
token: string,
foundation: Foundation,
theme = presetSunrise
) {
const resolvedFoundation = resolveFoundation(token, foundation)

const name = token.replace(tokenPrefix, '$')
Expand All @@ -58,7 +63,10 @@ export function getTokenValues(token: string, foundation: Foundation) {
}
}

function getTextValue(token: string) {
function getTextValue(token: string, theme = presetSunrise) {
console.log({
token,
})
const { font, letterSpacing } = {
font: theme[`${token}-font`],
letterSpacing: theme[`${token}-letter-spacing`],
Expand Down
1 change: 1 addition & 0 deletions packages/shoreline/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# Shoreline styles
__theme-sunrise__
__themes__
19 changes: 9 additions & 10 deletions packages/shoreline/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
"access": "public",
"registry": "https://registry.npmjs.org"
},
"files": [
"dist"
],
"files": ["dist"],
"exports": {
".": {
"require": "./dist/index.js",
Expand All @@ -26,14 +24,14 @@
"node": ">=16"
},
"scripts": {
"prebuild": "rm -rf dist && rm -rf __theme-sunrise__ && pnpm run theme",
"prebuild": "rm -rf dist && rm -rf __themes__ && pnpm run theme",
"dev": "concurrently \"tsup --watch\" \"pnpm run dev:css\" \"pnpm run dev:css-unlayered\"",
"dev:css": "pnpm run build:css -w",
"dev:css-unlayered": "pnpm run build:css-unlayered -w",
"dev:css": "lightningcss --bundle --watch --targets '>= 0.25%' ./src/themes/sunrise/index.css -o dist/themes/sunrise/styles.css",
"dev:css-unlayered": "lightningcss --bundle --watch --targets '>= 0.25%' ./src/themes/sunrise/index-unlayered.css -o dist/themes/sunrise/styles-unlayered.css",
"build": "pnpm run prebuild && concurrently \"tsup\" \"pnpm run build:css\" \"pnpm run build:css-unlayered\"",
"build:css": "postcss ./src/themes/sunrise/index.scss -o dist/themes/sunrise/styles.css",
"build:css-unlayered": "postcss ./src/themes/sunrise/index-unlayered.scss -o dist/themes/sunrise/styles-unlayered.css",
"theme": "shoreline css"
"build:css": "lightningcss --bundle --targets '>= 0.25%' ./src/themes/sunrise/index.css -o dist/themes/sunrise/styles.css",
"build:css-unlayered": "lightningcss --bundle --targets '>= 0.25%' ./src/themes/sunrise/index-unlayered.css -o dist/themes/sunrise/styles-unlayered.css",
"theme": "shoreline theme -f src/themes/sunrise/theme.css -o __themes__/sunrise.css"
},
"repository": {
"directory": "packages/shoreline",
Expand Down Expand Up @@ -63,7 +61,8 @@
"postcss-preset-env": "9.3.0",
"postcss-scss": "4.0.9",
"react-hook-form": "7.48.2",
"react-window": "1.8.10"
"react-window": "1.8.10",
"lightningcss-cli": "1.24.1"
},
"dependencies": {
"@ariakit/react": "0.4.5",
Expand Down
3 changes: 2 additions & 1 deletion packages/shoreline/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,8 @@ export {
today,
useCalendarContext,
} from './components'
export { presetSunrise } from './themes/sunrise/preset'
// export { presetSunrise } from './themes/sunrise/preset'
export { theme as presetSunrise } from '../__themes__/sunrise'
export type {
AccessibleIconProps,
AlertProps,
Expand Down
Loading