Skip to content

fix(extractor): give numbers read at runtime the units their literals take - #1040

Open
owjs3901 wants to merge 6 commits into
mainfrom
fix/web-dynamic-number-units
Open

owjs3901 wants to merge 6 commits into
mainfrom
fix/web-dynamic-number-units

Conversation

@owjs3901

@owjs3901 owjs3901 commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On the web target, a value only known at runtime reached its CSS variable as written. <Box p={m} /> with m = 2 set padding: 2, which is invalid CSS, while p={2} compiles to 8px. Each such value now goes through a conversion that turns a number into exactly what the static path makes of a literal of that property. The conversion lives in a new tiny subpath, @devup-ui/react/scale, and a file that needs it imports it once. Values the build can prove still fold at build time.

Rules (derived from ExtractStaticStyle::normalize_static_value, mirroring the RN runtime_scale in #1039)

Property Number / numeric string (2, '2') Other string ('2rem', 'auto') null / undefined / false
Spacing, sizes, other lengths (p, w, fontSize, bg...) ×4 + px (8px) unchanged unchanged (declaration dropped)
TIME_PROPERTIES (transitionDuration, animationDelay...) + ms (2ms) unchanged unchanged
MAINTAIN_VALUE_PROPERTIES (opacity, zIndex, lineHeight, flex, order...) not wrapped not wrapped not wrapped
Colors (*color), custom properties (--*) not wrapped not wrapped not wrapped

Rule coverage:

  • Covered: element props, responsive arrays, selectors (_hover), conditionals, and Devup UI's own styled() callbacks and templates.
  • Unchanged: css() stays build-time only, since a runtime value there is already a build error.
  • Not converted: Emotion, styled-components, vanilla-extract and Emotion css-prop files keep their own px conversion and get no import.
  • Skipped: a template that cannot end in a number (`${m}px`) is left as written.

Shared util: @devup-ui/react/scale

  • New subpath: packages/react/src/scale.ts is exported as ./scale (ESM + CJS + types). It is dependency-free, the package is already sideEffects: false, and the module imports no component code.
  • Exports:
  • Import form: the import comes from <package>/scale, so a custom package option resolves to its own re-export. It is added once per file, only when a call remains, after the leading imports, and under a collision-safe local name (__devupScale as __devupScale_ when the name is taken). A CommonJS file gets const __devupScale = require("<package>/scale").__devupScale;.
  • Bundlers: no plugin aliases or externalizes @devup-ui/react, so vite, webpack, rsbuild, Next (webpack and Turbopack) and bun resolve the subpath like any other package import.
  • Recompiling: compiling the output again keeps the import and its calls unchanged (tested).

Before / after

<Box p={m} opacity={o} />
+import { __devupScale } from "@devup-ui/react/scale";
-<div className="a c" style={{ "--b": m, "--d": o }} />
+<div className="a c" style={{ "--b": __devupScale(m), "--d": o }} />

Bundle impact

Before (per-file helper) Now (shared import)
Per file using it 163 B function body 54 B import line
Per wrapped value 14 B 14 B
Shared module — dist/scale.js 451 B / scale.cjs 432 B, once per bundle, both conversions
React Native, per file 226 B __u body one import line

Files with only static values, or only unitless or color values, are byte-identical and import nothing.

Intentional behavior change: styled() callbacks (owner-approved)

Inside Devup UI's own styled() callbacks and templates, a runtime number on a CSS name used to be read as px (3 → 3px) or passed through bare. Written statically, the same 3 gives 12px. Both now give 12px, matching the static path; the owner accepted this. Emotion and styled-components keep px.

The change is isolated in one branch in extractor/styled_scalar.rs. The tests pinning it are bound_callback_numeric_tests, the retained_render_assertions opaque case, known_mixin_regressions and tests/imported_styled_retained_edges. The changeset notes it.

Review notes

  • Snapshots:
    • Web: 70 insta snapshots changed. A script verified each one is byte-identical to main once the @devup-ui/react/scale import line is removed and __devupScale(...) is unwrapped, so no static output changed.
    • Native: 5 snapshots changed, each only swapping the inline __u body for import { __devupNativeScale as __u } from "@devup-ui/react/scale".
  • Capture handling: capture elision and the css-boundary capture check see through the call, so single-use captures still inline.
  • Tests:
    • The util has 30 unit tests in packages/react/src/__tests__/scale.test.ts, with 100% coverage.
    • The boa harnesses run the real scale.ts source and bind each imported local name to it.
    • Rust tests cover the import, an aliased local, a custom package, CommonJS require, no import when nothing is converted, and idempotent recompilation.
    • The e2e browser case asserts the emitted import and runs the WASM output in Chromium with the real util: p={m} with m = 2 computes padding: 8px, '2' gives 8px, '1rem' gives 16px, opacity stays raw and duration is in ms.
  • Docs: updated the Dynamic Values section to show the import, and fixed README examples that used bg with a color variable (now color).

Test plan

  • cargo test (workspace), cargo clippy --all-targets -- -D warnings, cargo fmt --check
  • bun test packages/react/src/__tests__/scale.test.ts (100% coverage)
  • bunx playwright test e2e/css-composition.spec.ts (27 passed)
  • CI

요약

웹 타깃에서 런타임에만 알 수 있는 값이 CSS 변수에 그대로 들어갔습니다. <Box p={m} />에 m = 2를 주면 padding: 2가 되는데, 이는 잘못된 CSS입니다. 반면 p={2}는 8px로 컴파일됩니다. 이제 이런 값은 변환 함수를 거칩니다. 이 함수는 정적 경로가 해당 속성의 리터럴을 변환하는 방식 그대로 숫자를 변환합니다. 함수는 새로 추가한 작은 서브패스 @devup-ui/react/scale에 있고, 필요한 파일이 한 번만 import합니다. 빌드 타임에 증명 가능한 값은 계속 빌드 타임에 접힙니다.

규칙 (ExtractStaticStyle::normalize_static_value에서 도출, #1039의 RN runtime_scale과 동일)

속성 숫자 / 숫자 문자열 (2, '2') 그 외 문자열 ('2rem', 'auto') null / undefined / false
간격, 크기, 기타 길이 (p, w, fontSize, bg...) ×4 + px (8px) 그대로 그대로 (선언 제거)
TIME_PROPERTIES (transitionDuration, animationDelay...) + ms (2ms) 그대로 그대로
MAINTAIN_VALUE_PROPERTIES (opacity, zIndex, lineHeight, flex, order...) 감싸지 않음 감싸지 않음 감싸지 않음
색상 (*color), 커스텀 속성 (--*) 감싸지 않음 감싸지 않음 감싸지 않음

규칙 적용 범위:

  • 적용: 요소 props, 반응형 배열, 셀렉터(_hover), 조건식, Devup UI 자체 styled() 콜백과 템플릿.
  • 변경 없음: css()는 여전히 빌드 타임 전용입니다. 런타임 값은 이미 빌드 에러입니다.
  • 변환 안 함: Emotion, styled-components, vanilla-extract, Emotion css prop 파일은 기존 px 변환을 유지하며 import도 추가되지 않습니다.
  • 건너뜀: 숫자로 끝날 수 없는 템플릿(`${m}px`)은 그대로 둡니다.

공유 유틸: @devup-ui/react/scale

  • 새 서브패스: packages/react/src/scale.ts를 ./scale로 export합니다(ESM + CJS + 타입). 의존성이 없고, 패키지는 이미 sideEffects: false이며, 컴포넌트 코드를 전혀 import하지 않습니다.
  • export:
  • import 형태: <package>/scale에서 import하므로 package 옵션을 바꾸면 그 패키지의 re-export로 해석됩니다. 호출이 남아 있는 파일에만, 파일당 한 번, 맨 앞 import들 뒤에 추가됩니다. 이름이 겹치면 __devupScale as __devupScale_처럼 충돌 없는 로컬 이름을 씁니다. CommonJS 파일에는 const __devupScale = require("<package>/scale").__devupScale;가 들어갑니다.
  • 번들러: 어떤 플러그인도 @devup-ui/react를 alias하거나 external로 빼지 않으므로 vite, webpack, rsbuild, Next(webpack·Turbopack), bun 모두 일반 패키지 import처럼 서브패스를 해석합니다.
  • 재컴파일: 출력을 다시 컴파일해도 import와 호출은 그대로 유지됩니다(테스트 있음).

전 / 후

영어 섹션의 diff를 참고하세요.

번들 영향

이전 (파일별 헬퍼) 현재 (공유 import)
사용하는 파일당 함수 본문 163 B import 한 줄 54 B
감싼 값당 14 B 14 B
공유 모듈 — dist/scale.js 451 B / scale.cjs 432 B, 번들당 한 번, 두 변환 포함
React Native 파일당 __u 본문 226 B import 한 줄

정적 값만 있거나 무단위·색상 값만 있는 파일은 바이트 단위로 동일하며 아무것도 import하지 않습니다.

의도된 동작 변경: styled() 콜백 (오너 승인)

Devup UI 자체 styled() 콜백과 템플릿에서 CSS 이름에 붙은 런타임 숫자는 px로 읽히거나(3 → 3px) 단위 없이 그대로 전달됐습니다. 같은 3을 정적으로 쓰면 12px입니다. 이제 둘 다 정적 경로와 같은 12px이며, 오너가 이 변경을 승인했습니다. Emotion과 styled-components는 px를 유지합니다.

이 변경은 extractor/styled_scalar.rs의 분기 하나에 격리되어 있습니다. 이를 고정하는 테스트는 bound_callback_numeric_tests, retained_render_assertions의 opaque 케이스, known_mixin_regressions, tests/imported_styled_retained_edges입니다. changeset에도 적었습니다.

리뷰 참고

  • 스냅샷:
    • 웹: insta 스냅샷 70개가 바뀌었습니다. 스크립트로 각 스냅샷에서 @devup-ui/react/scale import 줄을 지우고 __devupScale(...)를 벗기면 main과 바이트 단위로 같다는 것을 확인했습니다. 정적 출력은 바뀌지 않았습니다.
    • 네이티브: 스냅샷 5개가 바뀌었고, 각각 인라인 __u 본문이 import { __devupNativeScale as __u } from "@devup-ui/react/scale"로 바뀐 것뿐입니다.
  • 캡처 처리: capture elision과 css-boundary 캡처 검사가 호출을 투과해서 보므로, 한 번만 쓰이는 캡처는 계속 인라인됩니다.
  • 테스트:
    • 유틸은 packages/react/src/__tests__/scale.test.ts의 단위 테스트 30개로 커버리지 100%입니다.
    • boa 하니스는 실제 scale.ts 소스를 실행하고, import된 각 로컬 이름을 거기에 연결합니다.
    • Rust 테스트는 import, 별칭 로컬 이름, 커스텀 package, CommonJS require, 변환할 값이 없을 때 import 없음, 재컴파일 시 동일함을 다룹니다.
    • e2e 브라우저 케이스는 출력된 import를 확인한 뒤 실제 유틸과 함께 WASM 출력을 Chromium에서 실행합니다. p={m}에 m = 2이면 padding: 8px, '2'는 8px, '1rem'은 16px, opacity는 그대로, duration은 ms입니다.
  • 문서: Dynamic Values 섹션이 import를 보여주도록 갱신했고, bg에 색상 변수를 쓰던 README 예제를 color로 고쳤습니다.

🤖 Generated with Claude Code

owjs3901 and others added 3 commits November 20, 2026 06:55
… take

On the web target a value only known at runtime reached its CSS variable
as written, so <Box p={m} /> with m = 2 set padding: 2, which is no CSS
length, while p={2} compiles to 8px. Each such value is now passed
through a small helper the file declares once, which converts a number,
or a string holding only one, as the build converts a literal of that
property: spacing and sizes x4 in px, durations in ms, and unitless
properties, colors and custom properties unchanged. Other strings and
null, undefined or false pass through, so the latter still drop the
declaration. Responsive arrays, selectors, conditionals and Devup UI's
own styled() callbacks and templates follow the same rule; Emotion,
styled-components and vanilla-extract files keep their px numbers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…dependent build

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
libs/extractor/src/bound_callback_numeric_tests.rs 100.00% <ø> (ø)
libs/extractor/src/css_boundary.rs 100.00% <100.00%> (ø)
libs/extractor/src/css_utils/component_layers.rs 100.00% <ø> (ø)
...tractor/src/extract_style/extract_dynamic_style.rs 100.00% <100.00%> (ø)
libs/extractor/src/extract_style/style_property.rs 100.00% <ø> (ø)
...tor/src/extractor/extract_style_from_expression.rs 100.00% <ø> (ø)
...extractor/src/extractor/known_mixin_regressions.rs 100.00% <ø> (ø)
...bs/extractor/src/extractor/styled_mixin_context.rs 100.00% <ø> (ø)
libs/extractor/src/extractor/styled_scalar.rs 100.00% <ø> (ø)
libs/extractor/src/gen_style.rs 100.00% <100.00%> (ø)
... and 6 more

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

owjs3901 and others added 3 commits November 20, 2026 07:41
…scale

Files no longer declare their own __devupScale (web) or __u (React Native)
function. The conversions live in a dependency-free, side-effect-free
`scale` subpath of @devup-ui/react (ESM + CJS, no component code), and a
file that needs one imports it once, from `<package>/scale` so a custom
package option keeps working, under a collision-safe local name.
CommonJS output requires it instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant