Skip to content
Merged
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
1 change: 1 addition & 0 deletions packages/preset/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"@proj-airi/chromatic": "workspace:^"
},
"devDependencies": {
"@csstools/css-calc": "catalog:",
"@unocss/core": "catalog:"
}
}
15 changes: 8 additions & 7 deletions packages/preset/src/shared.fitted.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Shade } from '@proj-airi/chromatic'

import { calc } from '@csstools/css-calc'
import { fittedOklch } from '@proj-airi/chromatic'
import { createGenerator, presetWind3, presetWind4 } from 'unocss'
import { describe, expect, it } from 'vitest'
Expand All @@ -21,8 +22,8 @@ function createUno(wind: 'wind3' | 'wind4' = 'wind3') {
}

/**
* Evaluates the custom properties of a preflight the way a browser would, for the subset of CSS it uses:
* `calc()`, `cos()`, `sin()`, `max()`, `var()` and plain arithmetic on numbers.
* Evaluates the custom properties of a preflight: `var()` references are replaced by their (already evaluated)
* values, and the math functions are solved by `@csstools/css-calc`, the CSS math engine of postcss-preset-env.
*/
function evaluateCustomProperties(css: string, overrides: Record<string, number>): (name: string) => number {
const declarations = new Map(
Expand All @@ -37,11 +38,11 @@ function evaluateCustomProperties(css: string, overrides: Record<string, number>
if (value == null)
throw new Error(`undefined custom property ${name}`)

const js = value
.replaceAll(/var\((--[\w-]+)\)/g, (_, ref: string) => `(${evaluate(ref)})`)
.replaceAll(/\b(calc|cos|sin|max)\(/g, (_, fn: string) => (fn === 'calc' ? '(' : `Math.${fn}(`))
// eslint-disable-next-line no-new-func
const result = Number(new Function(`return ${js}`)())
const substituted = value.replaceAll(/var\((--[\w-]+)\)/g, (_, ref: string) => String(evaluate(ref)))
const solved = calc(substituted)
const result = Number(solved)
if (!Number.isFinite(result))
throw new Error(`${name} did not resolve to a number: ${solved}`)
cache.set(name, result)
return result
}
Expand Down
34 changes: 34 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ packages:
- '!**/dist/**'

catalog:
'@csstools/css-calc': ^3.4.3
'@iconify-json/simple-icons': ^1.2.91
'@iconify-json/solar': ^1.2.5
'@moeru/eslint-config': ^0.1.0-beta.20
Expand Down
Loading