nitrowind 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/LICENSE +21 -0
- package/README.md +44 -2
- package/css.d.ts +6 -0
- package/dist/color.d.ts +24 -0
- package/dist/color.d.ts.map +1 -0
- package/dist/color.js +158 -0
- package/dist/color.js.map +1 -0
- package/dist/core.d.ts +121 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +1026 -0
- package/dist/core.js.map +1 -0
- package/dist/css/compile.d.ts +18 -0
- package/dist/css/compile.d.ts.map +1 -0
- package/dist/css/compile.js +1018 -0
- package/dist/css/compile.js.map +1 -0
- package/dist/css/declarations.d.ts +18 -0
- package/dist/css/declarations.d.ts.map +1 -0
- package/dist/css/declarations.js +1173 -0
- package/dist/css/declarations.js.map +1 -0
- package/dist/css/index.d.ts +7 -0
- package/dist/css/index.d.ts.map +1 -0
- package/dist/css/index.js +7 -0
- package/dist/css/index.js.map +1 -0
- package/dist/css/parser.d.ts +9 -0
- package/dist/css/parser.d.ts.map +1 -0
- package/dist/css/parser.js +188 -0
- package/dist/css/parser.js.map +1 -0
- package/dist/css/tokenizer.d.ts +14 -0
- package/dist/css/tokenizer.d.ts.map +1 -0
- package/dist/css/tokenizer.js +200 -0
- package/dist/css/tokenizer.js.map +1 -0
- package/dist/css/types.d.ts +128 -0
- package/dist/css/types.d.ts.map +1 -0
- package/dist/css/types.js +19 -0
- package/dist/css/types.js.map +1 -0
- package/dist/css/values.d.ts +37 -0
- package/dist/css/values.d.ts.map +1 -0
- package/dist/css/values.js +343 -0
- package/dist/css/values.js.map +1 -0
- package/dist/environment.d.ts +5 -0
- package/dist/environment.d.ts.map +1 -0
- package/dist/environment.js +99 -0
- package/dist/environment.js.map +1 -0
- package/dist/hooks.d.ts +22 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +140 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/jsx-dev-runtime.d.ts +17 -0
- package/dist/jsx-dev-runtime.d.ts.map +1 -0
- package/dist/jsx-dev-runtime.js +12 -0
- package/dist/jsx-dev-runtime.js.map +1 -0
- package/dist/jsx-namespace.d.ts +29 -0
- package/dist/jsx-namespace.d.ts.map +1 -0
- package/dist/jsx-namespace.js +2 -0
- package/dist/jsx-namespace.js.map +1 -0
- package/dist/jsx-runtime.d.ts +22 -0
- package/dist/jsx-runtime.d.ts.map +1 -0
- package/dist/jsx-runtime.js +21 -0
- package/dist/jsx-runtime.js.map +1 -0
- package/dist/math.d.ts +50 -0
- package/dist/math.d.ts.map +1 -0
- package/dist/math.js +442 -0
- package/dist/math.js.map +1 -0
- package/dist/plugin.d.ts +45 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +172 -0
- package/dist/plugin.js.map +1 -0
- package/dist/props.d.ts +29 -0
- package/dist/props.d.ts.map +1 -0
- package/dist/props.js +163 -0
- package/dist/props.js.map +1 -0
- package/dist/scope.d.ts +99 -0
- package/dist/scope.d.ts.map +1 -0
- package/dist/scope.js +228 -0
- package/dist/scope.js.map +1 -0
- package/dist/store.d.ts +18 -0
- package/dist/store.d.ts.map +1 -0
- package/dist/store.js +244 -0
- package/dist/store.js.map +1 -0
- package/dist/tokens/index.d.ts +12 -0
- package/dist/tokens/index.d.ts.map +1 -0
- package/dist/tokens/index.js +237 -0
- package/dist/tokens/index.js.map +1 -0
- package/dist/tokens/tailwind.generated.d.ts +3 -0
- package/dist/tokens/tailwind.generated.d.ts.map +1 -0
- package/dist/tokens/tailwind.generated.js +610 -0
- package/dist/tokens/tailwind.generated.js.map +1 -0
- package/dist/tokens/types.d.ts +95 -0
- package/dist/tokens/types.d.ts.map +1 -0
- package/dist/tokens/types.js +2 -0
- package/dist/tokens/types.js.map +1 -0
- package/dist/transform.d.ts +22 -0
- package/dist/transform.d.ts.map +1 -0
- package/dist/transform.js +79 -0
- package/dist/transform.js.map +1 -0
- package/dist/transition.d.ts +7 -0
- package/dist/transition.d.ts.map +1 -0
- package/dist/transition.js +355 -0
- package/dist/transition.js.map +1 -0
- package/dist/types.d.ts +214 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utilities.d.ts +109 -0
- package/dist/utilities.d.ts.map +1 -0
- package/dist/utilities.js +2000 -0
- package/dist/utilities.js.map +1 -0
- package/dist/variables.d.ts +65 -0
- package/dist/variables.d.ts.map +1 -0
- package/dist/variables.js +408 -0
- package/dist/variables.js.map +1 -0
- package/dist/version.d.ts +3 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +3 -0
- package/dist/version.js.map +1 -0
- package/dist/withNitroWind.d.ts +11 -0
- package/dist/withNitroWind.d.ts.map +1 -0
- package/dist/withNitroWind.js +27 -0
- package/dist/withNitroWind.js.map +1 -0
- package/package.json +89 -4
- package/src/color.ts +164 -0
- package/src/core.ts +1248 -0
- package/src/css/compile.ts +1198 -0
- package/src/css/declarations.ts +1141 -0
- package/src/css/index.ts +22 -0
- package/src/css/parser.ts +196 -0
- package/src/css/tokenizer.ts +227 -0
- package/src/css/types.ts +178 -0
- package/src/css/values.ts +330 -0
- package/src/environment.ts +112 -0
- package/src/hooks.ts +190 -0
- package/src/index.ts +61 -0
- package/src/jsx-dev-runtime.ts +43 -0
- package/src/jsx-namespace.ts +23 -0
- package/src/jsx-runtime.ts +39 -0
- package/src/math.ts +488 -0
- package/src/plugin.ts +230 -0
- package/src/props.ts +173 -0
- package/src/scope.ts +331 -0
- package/src/store.ts +288 -0
- package/src/tokens/index.ts +252 -0
- package/src/tokens/tailwind.generated.ts +613 -0
- package/src/tokens/types.ts +99 -0
- package/src/transform.ts +115 -0
- package/src/transition.ts +414 -0
- package/src/types.ts +248 -0
- package/src/utilities.ts +1992 -0
- package/src/variables.ts +509 -0
- package/src/version.ts +2 -0
- package/src/withNitroWind.ts +36 -0
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** Development counterpart of `nitrowind/jsx-runtime`, used by the React Refresh transform. */
|
|
2
|
+
import { Fragment, jsxDEV as reactJsxDEV } from 'react/jsx-dev-runtime'
|
|
3
|
+
import { registerNitroUIEnvironment } from './environment'
|
|
4
|
+
import { createElementTransform } from './transform'
|
|
5
|
+
|
|
6
|
+
export type { JSX } from './jsx-namespace'
|
|
7
|
+
export { Fragment }
|
|
8
|
+
|
|
9
|
+
type JsxDevArgs = Parameters<typeof reactJsxDEV>
|
|
10
|
+
|
|
11
|
+
registerNitroUIEnvironment()
|
|
12
|
+
|
|
13
|
+
const transform = createElementTransform((type, props, isStatic) =>
|
|
14
|
+
reactJsxDEV(type as never, props, undefined, isStatic, undefined as never, undefined),
|
|
15
|
+
)
|
|
16
|
+
|
|
17
|
+
export function jsxDEV(
|
|
18
|
+
type: unknown,
|
|
19
|
+
props: Record<string, unknown>,
|
|
20
|
+
key: JsxDevArgs[2],
|
|
21
|
+
isStatic: boolean,
|
|
22
|
+
...rest: unknown[]
|
|
23
|
+
) {
|
|
24
|
+
const [nextType, nextProps] = transform(type, props, isStatic)
|
|
25
|
+
return (reactJsxDEV as (...args: unknown[]) => ReturnType<typeof reactJsxDEV>)(
|
|
26
|
+
nextType,
|
|
27
|
+
nextProps,
|
|
28
|
+
key,
|
|
29
|
+
isStatic,
|
|
30
|
+
...rest,
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
declare module 'nitro-ui-renderer' {
|
|
35
|
+
interface ViewPropsExtension {
|
|
36
|
+
/** Tailwind classes, compiled by NitroWind into `layout`, `style` and text props. */
|
|
37
|
+
className?: string
|
|
38
|
+
}
|
|
39
|
+
interface ListProps<Types> {
|
|
40
|
+
/** Tailwind padding classes (`p-*`, `px-*`, `py-*`, `pt-*`, `pr-*`, `pb-*`, `pl-*`), compiled by NitroWind into `contentPadding`. */
|
|
41
|
+
contentPaddingClassName?: string
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { JSX as ReactJSX } from 'react/jsx-runtime'
|
|
2
|
+
|
|
3
|
+
/** Props NitroWind adds to every element in files compiled with `jsxImportSource: "nitrowind"`. */
|
|
4
|
+
export interface NitroWindAttributes {
|
|
5
|
+
/** Tailwind classes, compiled by NitroWind into NitroUI `layout`, `style` and text props. */
|
|
6
|
+
className?: string
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* React's JSX types plus `className`. NitroUI releases before `ViewPropsExtension`
|
|
11
|
+
* have no other way to accept the prop on their components.
|
|
12
|
+
*/
|
|
13
|
+
export declare namespace JSX {
|
|
14
|
+
type ElementType = ReactJSX.ElementType
|
|
15
|
+
interface Element extends ReactJSX.Element {}
|
|
16
|
+
interface ElementClass extends ReactJSX.ElementClass {}
|
|
17
|
+
interface ElementAttributesProperty extends ReactJSX.ElementAttributesProperty {}
|
|
18
|
+
interface ElementChildrenAttribute extends ReactJSX.ElementChildrenAttribute {}
|
|
19
|
+
type LibraryManagedAttributes<C, P> = ReactJSX.LibraryManagedAttributes<C, P>
|
|
20
|
+
interface IntrinsicAttributes extends ReactJSX.IntrinsicAttributes, NitroWindAttributes {}
|
|
21
|
+
interface IntrinsicClassAttributes<T> extends ReactJSX.IntrinsicClassAttributes<T> {}
|
|
22
|
+
interface IntrinsicElements extends ReactJSX.IntrinsicElements {}
|
|
23
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A React JSX runtime that compiles `className` on NitroUI host elements.
|
|
3
|
+
*
|
|
4
|
+
* Point the JSX transform at it with `"jsxImportSource": "nitrowind"` in tsconfig.json,
|
|
5
|
+
* or a `/** @jsxImportSource nitrowind *\/` comment at the top of a file.
|
|
6
|
+
*/
|
|
7
|
+
import { Fragment, jsx as reactJsx, jsxs as reactJsxs } from 'react/jsx-runtime'
|
|
8
|
+
import { registerNitroUIEnvironment } from './environment'
|
|
9
|
+
import { createElementTransform } from './transform'
|
|
10
|
+
|
|
11
|
+
export type { JSX } from './jsx-namespace'
|
|
12
|
+
export { Fragment }
|
|
13
|
+
|
|
14
|
+
registerNitroUIEnvironment()
|
|
15
|
+
|
|
16
|
+
const transform = createElementTransform((type, props, isStatic) =>
|
|
17
|
+
isStatic ? reactJsxs(type as never, props) : reactJsx(type as never, props),
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
export function jsx(type: unknown, props: Record<string, unknown>, key?: string) {
|
|
21
|
+
const [nextType, nextProps] = transform(type, props, false)
|
|
22
|
+
return reactJsx(nextType as never, nextProps, key)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function jsxs(type: unknown, props: Record<string, unknown>, key?: string) {
|
|
26
|
+
const [nextType, nextProps] = transform(type, props, true)
|
|
27
|
+
return reactJsxs(nextType as never, nextProps, key)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
declare module 'nitro-ui-renderer' {
|
|
31
|
+
interface ViewPropsExtension {
|
|
32
|
+
/** Tailwind classes, compiled by NitroWind into `layout`, `style` and text props. */
|
|
33
|
+
className?: string
|
|
34
|
+
}
|
|
35
|
+
interface ListProps<Types> {
|
|
36
|
+
/** Tailwind padding classes (`p-*`, `px-*`, `py-*`, `pt-*`, `pr-*`, `pb-*`, `pl-*`), compiled by NitroWind into `contentPadding`. */
|
|
37
|
+
contentPaddingClassName?: string
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/math.ts
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Same-unit CSS math evaluator supporting `calc()`, `min()`, `max()`, and `clamp()`.
|
|
3
|
+
*
|
|
4
|
+
* Units:
|
|
5
|
+
* - `'pt'`: absolute lengths (`px`, `pt`, `rem`, `em`, `vw`, `vh`) converted to points.
|
|
6
|
+
* - `'%'`: percentages.
|
|
7
|
+
* - `'number'`: unitless numbers (also compatible with `'pt'` in addition/subtraction/min/max/clamp
|
|
8
|
+
* because NitroWind CSS variables frequently store point lengths as plain numbers).
|
|
9
|
+
*
|
|
10
|
+
* Unrepresentable mixed `%` and `'pt'`/`'number'` expressions are rejected with `reason: 'mixed-units'`.
|
|
11
|
+
*/
|
|
12
|
+
import type { ViewportSize } from './types'
|
|
13
|
+
|
|
14
|
+
export type MathUnit = 'pt' | '%' | 'number'
|
|
15
|
+
|
|
16
|
+
export interface MathValue {
|
|
17
|
+
readonly value: number
|
|
18
|
+
readonly unit: MathUnit
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type MathResult =
|
|
22
|
+
| { readonly ok: true; readonly value: number; readonly unit: MathUnit }
|
|
23
|
+
| {
|
|
24
|
+
readonly ok: false
|
|
25
|
+
readonly reason: 'mixed-units' | 'divide-by-zero' | 'missing-viewport' | 'syntax'
|
|
26
|
+
readonly message: string
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const MATH_FN_RE = /(?:^|[^A-Za-z0-9_-])(?:calc|min|max|clamp)\s*\(/i
|
|
30
|
+
const TOP_MATH_FN_RE = /^(?:calc|min|max|clamp)\s*\(/i
|
|
31
|
+
const VIEWPORT_UNIT_RE = /\d(?:vw|vh)(?![A-Za-z0-9])/i
|
|
32
|
+
|
|
33
|
+
const ROOT_FONT_SIZE = 16
|
|
34
|
+
|
|
35
|
+
/** Returns true if `value` contains a `calc()`, `min()`, `max()`, or `clamp()` call. */
|
|
36
|
+
export function hasMathFunction(value: string): boolean {
|
|
37
|
+
return MATH_FN_RE.test(value)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Returns true if `value` is a top-level `calc()`, `min()`, `max()`, or `clamp()` call. */
|
|
41
|
+
export function isMathExpression(value: string): boolean {
|
|
42
|
+
const trimmed = value.trim()
|
|
43
|
+
if (!TOP_MATH_FN_RE.test(trimmed) || !trimmed.endsWith(')')) return false
|
|
44
|
+
const open = trimmed.indexOf('(')
|
|
45
|
+
return findMatchingParen(trimmed, open) === trimmed.length - 1
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Returns true if `value` contains a `vw` or `vh` viewport length unit. */
|
|
49
|
+
export function hasViewportUnit(value: string): boolean {
|
|
50
|
+
return VIEWPORT_UNIT_RE.test(value)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function findMatchingParen(input: string, openIndex: number): number {
|
|
54
|
+
let depth = 0
|
|
55
|
+
for (let i = openIndex; i < input.length; i++) {
|
|
56
|
+
const ch = input[i]
|
|
57
|
+
if (ch === '(') depth++
|
|
58
|
+
else if (ch === ')') {
|
|
59
|
+
depth--
|
|
60
|
+
if (depth === 0) return i
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return -1
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
type Token =
|
|
67
|
+
| { readonly kind: 'value'; readonly value: number; readonly unit: MathUnit; readonly missingViewport?: boolean }
|
|
68
|
+
| { readonly kind: 'op'; readonly op: '+' | '-' | '*' | '/' }
|
|
69
|
+
| { readonly kind: 'fn'; readonly name: 'calc' | 'min' | 'max' | 'clamp' }
|
|
70
|
+
| { readonly kind: 'lparen' }
|
|
71
|
+
| { readonly kind: 'rparen' }
|
|
72
|
+
| { readonly kind: 'comma' }
|
|
73
|
+
|
|
74
|
+
type MathError = Extract<MathResult, { ok: false }>
|
|
75
|
+
|
|
76
|
+
function err(reason: MathError['reason'], message: string): MathError {
|
|
77
|
+
return { ok: false, reason, message }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function roundValue(n: number): number {
|
|
81
|
+
const rounded = Math.round(n * 1e4) / 1e4
|
|
82
|
+
return rounded === 0 ? 0 : rounded
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Formats a resolved math value back into a CSS string preserving unit semantics. */
|
|
86
|
+
export function formatMathResult(result: MathValue): string {
|
|
87
|
+
const rounded = roundValue(result.value)
|
|
88
|
+
switch (result.unit) {
|
|
89
|
+
case '%':
|
|
90
|
+
return `${rounded}%`
|
|
91
|
+
case 'pt':
|
|
92
|
+
return `${rounded}pt`
|
|
93
|
+
case 'number':
|
|
94
|
+
return String(rounded)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function tokenize(input: string, viewport?: ViewportSize): { ok: true; tokens: Token[] } | MathError {
|
|
99
|
+
const tokens: Token[] = []
|
|
100
|
+
let i = 0
|
|
101
|
+
const len = input.length
|
|
102
|
+
|
|
103
|
+
while (i < len) {
|
|
104
|
+
const ch = input[i]!
|
|
105
|
+
if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') {
|
|
106
|
+
i++
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
if (ch === '(') {
|
|
110
|
+
tokens.push({ kind: 'lparen' })
|
|
111
|
+
i++
|
|
112
|
+
continue
|
|
113
|
+
}
|
|
114
|
+
if (ch === ')') {
|
|
115
|
+
tokens.push({ kind: 'rparen' })
|
|
116
|
+
i++
|
|
117
|
+
continue
|
|
118
|
+
}
|
|
119
|
+
if (ch === ',') {
|
|
120
|
+
tokens.push({ kind: 'comma' })
|
|
121
|
+
i++
|
|
122
|
+
continue
|
|
123
|
+
}
|
|
124
|
+
if (ch === '+' || ch === '-' || ch === '*' || ch === '/') {
|
|
125
|
+
tokens.push({ kind: 'op', op: ch })
|
|
126
|
+
i++
|
|
127
|
+
continue
|
|
128
|
+
}
|
|
129
|
+
// Number (with optional unit)
|
|
130
|
+
if ((ch >= '0' && ch <= '9') || (ch === '.' && i + 1 < len && input[i + 1]! >= '0' && input[i + 1]! <= '9')) {
|
|
131
|
+
const start = i
|
|
132
|
+
let hasDot = false
|
|
133
|
+
while (i < len) {
|
|
134
|
+
const c = input[i]!
|
|
135
|
+
if (c >= '0' && c <= '9') {
|
|
136
|
+
i++
|
|
137
|
+
} else if (c === '.' && !hasDot) {
|
|
138
|
+
hasDot = true
|
|
139
|
+
i++
|
|
140
|
+
} else {
|
|
141
|
+
break
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
// Optional scientific notation: `e`/`E` followed by optional sign and digits (not `em`)
|
|
145
|
+
if (i < len && (input[i] === 'e' || input[i] === 'E')) {
|
|
146
|
+
let j = i + 1
|
|
147
|
+
if (j < len && (input[j] === '+' || input[j] === '-')) j++
|
|
148
|
+
if (j < len && input[j]! >= '0' && input[j]! <= '9') {
|
|
149
|
+
i = j + 1
|
|
150
|
+
while (i < len && input[i]! >= '0' && input[i]! <= '9') i++
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
const num = Number(input.slice(start, i))
|
|
154
|
+
if (!Number.isFinite(num)) {
|
|
155
|
+
return err('syntax', `invalid number "${input.slice(start, i)}"`)
|
|
156
|
+
}
|
|
157
|
+
// Optional unit: `%` or ASCII letters
|
|
158
|
+
if (i < len && input[i] === '%') {
|
|
159
|
+
i++
|
|
160
|
+
tokens.push({ kind: 'value', value: num, unit: '%' })
|
|
161
|
+
continue
|
|
162
|
+
}
|
|
163
|
+
const unitStart = i
|
|
164
|
+
while (i < len && ((input[i]! >= 'a' && input[i]! <= 'z') || (input[i]! >= 'A' && input[i]! <= 'Z'))) {
|
|
165
|
+
i++
|
|
166
|
+
}
|
|
167
|
+
const rawUnit = input.slice(unitStart, i).toLowerCase()
|
|
168
|
+
if (rawUnit === '') {
|
|
169
|
+
tokens.push({ kind: 'value', value: num, unit: 'number' })
|
|
170
|
+
} else if (rawUnit === 'px' || rawUnit === 'pt') {
|
|
171
|
+
tokens.push({ kind: 'value', value: num, unit: 'pt' })
|
|
172
|
+
} else if (rawUnit === 'rem' || rawUnit === 'em') {
|
|
173
|
+
tokens.push({ kind: 'value', value: num * ROOT_FONT_SIZE, unit: 'pt' })
|
|
174
|
+
} else if (rawUnit === 'vw') {
|
|
175
|
+
if (viewport === undefined) {
|
|
176
|
+
tokens.push({ kind: 'value', value: 0, unit: 'pt', missingViewport: true })
|
|
177
|
+
} else {
|
|
178
|
+
tokens.push({ kind: 'value', value: (num / 100) * viewport.width, unit: 'pt' })
|
|
179
|
+
}
|
|
180
|
+
} else if (rawUnit === 'vh') {
|
|
181
|
+
if (viewport === undefined) {
|
|
182
|
+
tokens.push({ kind: 'value', value: 0, unit: 'pt', missingViewport: true })
|
|
183
|
+
} else {
|
|
184
|
+
tokens.push({ kind: 'value', value: (num / 100) * viewport.height, unit: 'pt' })
|
|
185
|
+
}
|
|
186
|
+
} else {
|
|
187
|
+
return err('syntax', `unsupported unit "${rawUnit}"`)
|
|
188
|
+
}
|
|
189
|
+
continue
|
|
190
|
+
}
|
|
191
|
+
// Identifier: must be a supported math function followed by `(`
|
|
192
|
+
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
|
|
193
|
+
const start = i
|
|
194
|
+
while (
|
|
195
|
+
i < len &&
|
|
196
|
+
((input[i]! >= 'a' && input[i]! <= 'z') ||
|
|
197
|
+
(input[i]! >= 'A' && input[i]! <= 'Z') ||
|
|
198
|
+
(input[i]! >= '0' && input[i]! <= '9') ||
|
|
199
|
+
input[i] === '-' ||
|
|
200
|
+
input[i] === '_')
|
|
201
|
+
) {
|
|
202
|
+
i++
|
|
203
|
+
}
|
|
204
|
+
const ident = input.slice(start, i).toLowerCase()
|
|
205
|
+
while (i < len && (input[i] === ' ' || input[i] === '\t')) i++
|
|
206
|
+
if (
|
|
207
|
+
(ident === 'calc' || ident === 'min' || ident === 'max' || ident === 'clamp') &&
|
|
208
|
+
i < len &&
|
|
209
|
+
input[i] === '('
|
|
210
|
+
) {
|
|
211
|
+
tokens.push({ kind: 'fn', name: ident })
|
|
212
|
+
tokens.push({ kind: 'lparen' })
|
|
213
|
+
i++
|
|
214
|
+
continue
|
|
215
|
+
}
|
|
216
|
+
return err('syntax', `unexpected token "${ident}"`)
|
|
217
|
+
}
|
|
218
|
+
return err('syntax', `unexpected character "${ch}"`)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return { ok: true, tokens }
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
interface EvalValue {
|
|
225
|
+
readonly value: number
|
|
226
|
+
readonly unit: MathUnit
|
|
227
|
+
readonly missingViewport: boolean
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
type EvalOutcome = { readonly ok: true; readonly val: EvalValue } | MathError
|
|
231
|
+
|
|
232
|
+
function combineAdditiveUnits(a: MathUnit, b: MathUnit): MathUnit | null {
|
|
233
|
+
if (a === b) return a
|
|
234
|
+
if ((a === 'pt' && b === 'number') || (a === 'number' && b === 'pt')) return 'pt'
|
|
235
|
+
return null
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function unitLabel(u: MathUnit): string {
|
|
239
|
+
return u === 'number' ? 'unitless' : u
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
class Parser {
|
|
243
|
+
private pos = 0
|
|
244
|
+
|
|
245
|
+
constructor(private readonly tokens: readonly Token[]) {}
|
|
246
|
+
|
|
247
|
+
private peek(): Token | undefined {
|
|
248
|
+
return this.tokens[this.pos]
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
private consume(): Token | undefined {
|
|
252
|
+
return this.tokens[this.pos++]
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
parseRoot(): EvalOutcome {
|
|
256
|
+
const first = this.peek()
|
|
257
|
+
if (!first || first.kind !== 'fn') {
|
|
258
|
+
return err('syntax', 'expected calc(), min(), max(), or clamp()')
|
|
259
|
+
}
|
|
260
|
+
const result = this.parseFunction()
|
|
261
|
+
if (!result.ok) return result
|
|
262
|
+
if (this.pos !== this.tokens.length) {
|
|
263
|
+
return err('syntax', 'unexpected trailing tokens in math expression')
|
|
264
|
+
}
|
|
265
|
+
return result
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
private parseFunction(): EvalOutcome {
|
|
269
|
+
const fnToken = this.consume()
|
|
270
|
+
if (!fnToken || fnToken.kind !== 'fn') return err('syntax', 'expected math function')
|
|
271
|
+
const lparen = this.consume()
|
|
272
|
+
if (!lparen || lparen.kind !== 'lparen') return err('syntax', `expected "(" after ${fnToken.name}`)
|
|
273
|
+
|
|
274
|
+
const args: EvalValue[] = []
|
|
275
|
+
const first = this.parseAddSub()
|
|
276
|
+
if (!first.ok) return first
|
|
277
|
+
args.push(first.val)
|
|
278
|
+
|
|
279
|
+
while (this.peek()?.kind === 'comma') {
|
|
280
|
+
this.consume()
|
|
281
|
+
const next = this.parseAddSub()
|
|
282
|
+
if (!next.ok) return next
|
|
283
|
+
args.push(next.val)
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const rparen = this.consume()
|
|
287
|
+
if (!rparen || rparen.kind !== 'rparen') {
|
|
288
|
+
return err('syntax', `unclosed "${fnToken.name}("`)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (fnToken.name === 'calc') {
|
|
292
|
+
if (args.length !== 1) return err('syntax', 'calc() expects exactly 1 argument')
|
|
293
|
+
return { ok: true, val: args[0]! }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
if (fnToken.name === 'clamp') {
|
|
297
|
+
if (args.length !== 3) return err('syntax', 'clamp() expects exactly 3 arguments')
|
|
298
|
+
const [minVal, prefVal, maxVal] = args as [EvalValue, EvalValue, EvalValue]
|
|
299
|
+
const u1 = combineAdditiveUnits(minVal.unit, prefVal.unit)
|
|
300
|
+
if (u1 === null) {
|
|
301
|
+
return err('mixed-units', `cannot mix ${unitLabel(minVal.unit)} and ${unitLabel(prefVal.unit)} in clamp()`)
|
|
302
|
+
}
|
|
303
|
+
const u2 = combineAdditiveUnits(u1, maxVal.unit)
|
|
304
|
+
if (u2 === null) {
|
|
305
|
+
return err('mixed-units', `cannot mix ${unitLabel(u1)} and ${unitLabel(maxVal.unit)} in clamp()`)
|
|
306
|
+
}
|
|
307
|
+
const missingViewport = minVal.missingViewport || prefVal.missingViewport || maxVal.missingViewport
|
|
308
|
+
const clamped = Math.max(minVal.value, Math.min(prefVal.value, maxVal.value))
|
|
309
|
+
return { ok: true, val: { value: clamped, unit: u2, missingViewport } }
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// min() or max()
|
|
313
|
+
let unit: MathUnit = args[0]!.unit
|
|
314
|
+
let acc = args[0]!.value
|
|
315
|
+
let missingViewport = args[0]!.missingViewport
|
|
316
|
+
for (let i = 1; i < args.length; i++) {
|
|
317
|
+
const arg = args[i]!
|
|
318
|
+
const combined = combineAdditiveUnits(unit, arg.unit)
|
|
319
|
+
if (combined === null) {
|
|
320
|
+
return err('mixed-units', `cannot mix ${unitLabel(unit)} and ${unitLabel(arg.unit)} in ${fnToken.name}()`)
|
|
321
|
+
}
|
|
322
|
+
unit = combined
|
|
323
|
+
missingViewport = missingViewport || arg.missingViewport
|
|
324
|
+
acc = fnToken.name === 'min' ? Math.min(acc, arg.value) : Math.max(acc, arg.value)
|
|
325
|
+
}
|
|
326
|
+
return { ok: true, val: { value: acc, unit, missingViewport } }
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private parseAddSub(): EvalOutcome {
|
|
330
|
+
const left = this.parseMulDiv()
|
|
331
|
+
if (!left.ok) return left
|
|
332
|
+
let acc = left.val
|
|
333
|
+
|
|
334
|
+
while (true) {
|
|
335
|
+
const next = this.peek()
|
|
336
|
+
if (!next || next.kind !== 'op' || (next.op !== '+' && next.op !== '-')) break
|
|
337
|
+
this.consume()
|
|
338
|
+
const right = this.parseMulDiv()
|
|
339
|
+
if (!right.ok) return right
|
|
340
|
+
const combined = combineAdditiveUnits(acc.unit, right.val.unit)
|
|
341
|
+
if (combined === null) {
|
|
342
|
+
return err(
|
|
343
|
+
'mixed-units',
|
|
344
|
+
`cannot ${next.op === '+' ? 'add' : 'subtract'} ${unitLabel(acc.unit)} and ${unitLabel(right.val.unit)}`,
|
|
345
|
+
)
|
|
346
|
+
}
|
|
347
|
+
const value = next.op === '+' ? acc.value + right.val.value : acc.value - right.val.value
|
|
348
|
+
acc = {
|
|
349
|
+
value,
|
|
350
|
+
unit: combined,
|
|
351
|
+
missingViewport: acc.missingViewport || right.val.missingViewport,
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return { ok: true, val: acc }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
private parseMulDiv(): EvalOutcome {
|
|
359
|
+
const left = this.parseUnary()
|
|
360
|
+
if (!left.ok) return left
|
|
361
|
+
let acc = left.val
|
|
362
|
+
|
|
363
|
+
while (true) {
|
|
364
|
+
const next = this.peek()
|
|
365
|
+
if (!next || next.kind !== 'op' || (next.op !== '*' && next.op !== '/')) break
|
|
366
|
+
this.consume()
|
|
367
|
+
const right = this.parseUnary()
|
|
368
|
+
if (!right.ok) return right
|
|
369
|
+
const r = right.val
|
|
370
|
+
const missingViewport = acc.missingViewport || r.missingViewport
|
|
371
|
+
|
|
372
|
+
if (next.op === '*') {
|
|
373
|
+
if (acc.unit === 'number') {
|
|
374
|
+
acc = { value: acc.value * r.value, unit: r.unit, missingViewport }
|
|
375
|
+
} else if (r.unit === 'number') {
|
|
376
|
+
acc = { value: acc.value * r.value, unit: acc.unit, missingViewport }
|
|
377
|
+
} else {
|
|
378
|
+
return err('mixed-units', `cannot multiply ${unitLabel(acc.unit)} by ${unitLabel(r.unit)}`)
|
|
379
|
+
}
|
|
380
|
+
} else {
|
|
381
|
+
if (!r.missingViewport && r.value === 0) {
|
|
382
|
+
return err('divide-by-zero', 'division by zero')
|
|
383
|
+
}
|
|
384
|
+
if (r.unit === 'number') {
|
|
385
|
+
acc = { value: r.value === 0 ? 0 : acc.value / r.value, unit: acc.unit, missingViewport }
|
|
386
|
+
} else if (acc.unit === r.unit) {
|
|
387
|
+
acc = { value: r.value === 0 ? 0 : acc.value / r.value, unit: 'number', missingViewport }
|
|
388
|
+
} else {
|
|
389
|
+
return err('mixed-units', `cannot divide ${unitLabel(acc.unit)} by ${unitLabel(r.unit)}`)
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return { ok: true, val: acc }
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
private parseUnary(): EvalOutcome {
|
|
398
|
+
const next = this.peek()
|
|
399
|
+
if (next && next.kind === 'op' && (next.op === '+' || next.op === '-')) {
|
|
400
|
+
this.consume()
|
|
401
|
+
const inner = this.parseUnary()
|
|
402
|
+
if (!inner.ok) return inner
|
|
403
|
+
return {
|
|
404
|
+
ok: true,
|
|
405
|
+
val: {
|
|
406
|
+
value: next.op === '-' ? -inner.val.value : inner.val.value,
|
|
407
|
+
unit: inner.val.unit,
|
|
408
|
+
missingViewport: inner.val.missingViewport,
|
|
409
|
+
},
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
return this.parsePrimary()
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
private parsePrimary(): EvalOutcome {
|
|
416
|
+
const next = this.peek()
|
|
417
|
+
if (!next) return err('syntax', 'unexpected end of math expression')
|
|
418
|
+
|
|
419
|
+
if (next.kind === 'value') {
|
|
420
|
+
this.consume()
|
|
421
|
+
return {
|
|
422
|
+
ok: true,
|
|
423
|
+
val: { value: next.value, unit: next.unit, missingViewport: next.missingViewport === true },
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
if (next.kind === 'fn') {
|
|
427
|
+
return this.parseFunction()
|
|
428
|
+
}
|
|
429
|
+
if (next.kind === 'lparen') {
|
|
430
|
+
this.consume()
|
|
431
|
+
const inner = this.parseAddSub()
|
|
432
|
+
if (!inner.ok) return inner
|
|
433
|
+
const rparen = this.consume()
|
|
434
|
+
if (!rparen || rparen.kind !== 'rparen') {
|
|
435
|
+
return err('syntax', 'unclosed "(" in math expression')
|
|
436
|
+
}
|
|
437
|
+
return inner
|
|
438
|
+
}
|
|
439
|
+
return err('syntax', 'unexpected token in math expression')
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/** Evaluates a single top-level `calc()`, `min()`, `max()`, or `clamp()` expression. */
|
|
444
|
+
export function evaluateMath(expr: string, viewport?: ViewportSize): MathResult {
|
|
445
|
+
const tokenized = tokenize(expr.trim(), viewport)
|
|
446
|
+
if (!tokenized.ok) return tokenized
|
|
447
|
+
const parsed = new Parser(tokenized.tokens).parseRoot()
|
|
448
|
+
if (!parsed.ok) return parsed
|
|
449
|
+
if (parsed.val.missingViewport) {
|
|
450
|
+
return err('missing-viewport', 'viewport size is required for vw/vh units')
|
|
451
|
+
}
|
|
452
|
+
if (!Number.isFinite(parsed.val.value)) {
|
|
453
|
+
return err('syntax', 'math expression produced a non-finite result')
|
|
454
|
+
}
|
|
455
|
+
return { ok: true, value: roundValue(parsed.val.value), unit: parsed.val.unit }
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
export type EvaluateMathStringResult = { readonly ok: true; readonly value: string } | MathError
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* Evaluates all top-level `calc()`, `min()`, `max()`, and `clamp()` calls inside `input`,
|
|
462
|
+
* replacing each with its formatted result (e.g. `12pt`, `33.3333%`, or `1.5`).
|
|
463
|
+
*/
|
|
464
|
+
export function evaluateMathInString(input: string, viewport?: ViewportSize): EvaluateMathStringResult {
|
|
465
|
+
if (!hasMathFunction(input)) return { ok: true, value: input }
|
|
466
|
+
let out = ''
|
|
467
|
+
let i = 0
|
|
468
|
+
while (i < input.length) {
|
|
469
|
+
const slice = input.slice(i)
|
|
470
|
+
const match = /^(calc|min|max|clamp)\s*\(/i.exec(slice)
|
|
471
|
+
if (match && (i === 0 || !/[A-Za-z0-9_-]/.test(input[i - 1]!))) {
|
|
472
|
+
const openIndex = i + match[0].length - 1
|
|
473
|
+
const closeIndex = findMatchingParen(input, openIndex)
|
|
474
|
+
if (closeIndex === -1) {
|
|
475
|
+
return err('syntax', `unclosed "${match[1]}("`)
|
|
476
|
+
}
|
|
477
|
+
const call = input.slice(i, closeIndex + 1)
|
|
478
|
+
const evaluated = evaluateMath(call, viewport)
|
|
479
|
+
if (!evaluated.ok) return evaluated
|
|
480
|
+
out += formatMathResult(evaluated)
|
|
481
|
+
i = closeIndex + 1
|
|
482
|
+
continue
|
|
483
|
+
}
|
|
484
|
+
out += input[i]
|
|
485
|
+
i++
|
|
486
|
+
}
|
|
487
|
+
return { ok: true, value: out }
|
|
488
|
+
}
|