Skip to content

feat(native): theme tokens, multiple themes and the React Native runtime - #1042

Open
owjs3901 wants to merge 3 commits into
feat/react-native-metrofrom
feat/react-native-themes
Open

owjs3901 wants to merge 3 commits into
feat/react-native-metrofrom
feat/react-native-themes

Conversation

@owjs3901

Copy link
Copy Markdown
Contributor

Part of #411, depends on #1041 (base: feat/react-native-metro). PR 3 of the React Native plan: theme tokens, multiple themes and a minimal runtime.

What it does

Tokens at build time. $ color, length and shadow tokens and typography resolve to the values React Native takes. The theme is parsed by libs/sheet as on the web (registerTheme), and binding-core converts it into a plain per-theme table for the native extractor, so the codeExtractNative ABI is unchanged. A relative typography lineHeight (unitless, %, em) or em letterSpacing becomes pixels of the typography's fontSize.

One theme: fully static, no runtime import.

// devup.json: colors.default.surface = #fff, length.default.radius = ["12px"]
<Box bg="$surface" borderRadius="$radius" p={4} />
const __s = StyleSheet.create({ a: { backgroundColor: "#fff", padding: 16, borderRadius: 12 } });
<Box style={__s.a} />

Several themes (R2): one precomputed object per theme, picked by index; theme-independent parts stay shared.

import { useThemeIndex as __useThemeIndex, defineThemes as __defineThemes } from "@devup-ui/react/native";
__defineThemes(["light", "dark"], 1);
const __s = StyleSheet.create({
  a: { padding: 16, borderRadius: 12 },
  b: { backgroundColor: "#fff" },
  c: { backgroundColor: "#000" },
});
export function Card() {
  const __t = __useThemeIndex();
  return <Box style={[__s.a, [__s.b, __s.c][__t]]} />;
}
  • The theme names are the color variants, default first (default > light > first), as the web orders them. A token a theme lacks falls back to the default variant, like the web's :root cascade.
  • The hook goes at the top of the enclosing component or hook: a capitalized function, use*, memo/forwardRef, or export default. An element outside one (module scope, class components, lowercase helpers) renders through the runtime's Themed wrapper instead, so the rules of hooks hold.
  • _themeDark, _themeSepia, … apply their styles only in that theme, including nested and conditional blocks. An unknown theme name is a build error.
  • useTheme, getTheme and setTheme imported from @devup-ui/react are rewritten to the runtime (they were build errors in feat: compile Devup UI elements to React Native styles (core, static subset) #1039).

Runtime: @devup-ui/react/native (RN-only subpath; web entries never import it). 628 B minified, 398 B min+gz.

  • A pure selector: a store read with useSyncExternalStore. No CSS parsing, no token resolution, no style computation.
  • The default follows the OS through Appearance. The dark theme is dark when devup.json renders it dark, else the first theme colorScheme makes dark.
  • setTheme(name) overrides the OS choice and supports any number of themes. An unknown name renders the default theme's styles, as on the web.
  • react-native is an optional peer; there are no other dependencies.
  • The compiler passes the theme list and the dark index with defineThemes.

runtime: false stays strict. Anything that needs the runtime is a build error: a value that differs by theme, _theme* with more than one theme, and useTheme/getTheme/setTheme. Single-theme tokens still compile.

Still build errors: responsive tokens or typography (a value at each breakpoint; PR 4), unknown $ tokens or typographies, tokens that reference each other in a loop, a relative typography without a pixel fontSize, and a typography chosen by a runtime value.

Metro plugin registers devup.json's theme (with extends) once per worker.

Expo example has light/dark themes, tokens, a typography and a setTheme toggle. The CI bundle check now:

  • allows only @devup-ui/react/dist/native from @devup-ui/react;
  • requires src/App.tsx to use the runtime;
  • requires the static-only src/Badge.tsx not to. The check maps each defineThemes/useThemeIndex occurrence back through the bundle's source map. It was verified locally to fail when Badge.tsx uses a token.

CI: adds feat/react-native-metro to the pull_request branches (it is removed when this is retargeted to main), and packages/react/src/native/ to the Expo job's path filter.

Tests

  • Rust (insta + rstest):
    • 1, 2 and 3 themes; mixed props and conditionals; hook placement in 17 component shapes; theme API imports; runtime: false; theme errors; the theme conversion in binding-core.
    • All extractor/sheet/css tests pass with no web snapshot changes.
    • clippy -D warnings is clean.
  • Runtime bun tests (mock.module('react-native')):
    • OS appearance changes;
    • setTheme overriding the OS;
    • an unknown theme name;
    • no themes;
    • the Themed wrapper.
    • Coverage is 100%.
  • Metro plugin: the theme is registered once before compiling, and the real-WASM transformer resolves a two-theme token.

#411의 일부이며 #1041에 의존합니다(base: feat/react-native-metro). React Native 계획의 PR 3으로, 테마 토큰, 다중 테마와 최소 런타임을 다룹니다.

변경 사항

빌드 타임 토큰. $ 색상·length·shadow 토큰과 typography를 React Native 값으로 바꿉니다. 테마는 웹과 같이 libs/sheet가 파싱하고(registerTheme), binding-core가 네이티브 추출기용 테마별 표로 변환하므로 codeExtractNative ABI는 그대로입니다. 상대 단위 lineHeight(단위 없음, %, em)와 em letterSpacing은 typography의 fontSize 기준 픽셀이 됩니다.

테마 1개: 모두 정적이며 런타임 import가 없습니다(위 예시).

테마 여러 개(R2): 테마마다 미리 계산한 객체를 인덱스로 고릅니다. 테마와 무관한 부분은 공유합니다(위 예시).

  • 테마 이름은 색상 variant이고, 기본 테마가 먼저 옵니다(default > light > 첫 번째). 테마에 없는 토큰은 웹의 :root처럼 기본 variant 값을 씁니다.
  • 훅은 둘러싼 컴포넌트나 훅의 맨 위에 삽입합니다. 그 밖(모듈 스코프, 클래스 컴포넌트, 소문자 헬퍼)에 있는 요소는 런타임의 Themed 래퍼로 렌더링하므로 hooks 규칙을 지킵니다.
  • _themeDark 같은 _theme*는 해당 테마에서만 적용됩니다. 알 수 없는 테마 이름은 빌드 에러입니다.
  • useTheme/getTheme/setTheme import는 런타임으로 다시 씁니다(#1039에서는 빌드 에러였습니다).

런타임 @devup-ui/react/native (RN 전용 서브패스이며 웹 엔트리는 import하지 않습니다). min 628B, min+gz 398B.

  • 순수 선택자입니다: useSyncExternalStore로 읽는 작은 스토어이며, CSS 파싱·토큰 해석·스타일 계산이 없습니다.
  • 기본값은 Appearance로 OS를 따릅니다.
  • setTheme(name)은 OS 선택을 덮어쓰고 테마 개수에 제한이 없습니다. 알 수 없는 이름은 웹과 같이 기본 테마 스타일로 렌더링합니다.
  • react-native는 optional peer이며, 다른 의존성은 없습니다.

**runtime: false**는 엄격 모드를 유지합니다. 런타임이 필요한 것은 모두 빌드 에러이고, 단일 테마 토큰은 그대로 컴파일됩니다.

여전히 빌드 에러: 반응형 토큰과 typography(PR 4), 정의되지 않은 토큰이나 typography, 순환 토큰, 픽셀 fontSize가 없는 상대 typography, 런타임 값으로 고르는 typography.

Metro 플러그인은 devup.json 테마(extends 포함)를 워커마다 한 번 등록합니다.

Expo 예제에는 light/dark 테마, 토큰, typography와 setTheme 토글을 추가했습니다. CI 번들 검사는 다음을 확인합니다:

  • @devup-ui/react 중에서는 dist/native만 허용합니다;
  • App.tsx가 런타임을 사용해야 합니다;
  • 정적인 Badge.tsx는 런타임을 사용하면 안 됩니다. 이 검사는 source map으로 확인하며, 로컬에서 실패하는 경우도 검증했습니다.

CI: pull_request 브랜치에 feat/react-native-metro를 추가했습니다(main으로 retarget할 때 제거합니다). Expo 잡의 경로 필터에는 packages/react/src/native/를 추가했습니다.

테스트

  • Rust 스냅샷: 테마 1/2/3개, 혼합 props와 조건, 훅 위치, 테마 API, runtime: false, 에러, 변환. 웹 스냅샷 변경은 없고 clippy도 깨끗합니다.
  • 런타임 bun 테스트: OS 변경, setTheme 우선, 알 수 없는 이름, Themed. 커버리지는 100%입니다.
  • Metro: 테마 등록과 실제 WASM 변환을 확인합니다.

🤖 Generated with Claude Code

owjs3901 and others added 3 commits November 20, 2026 19:11
Resolve `$` tokens and typography of devup.json at build time for React
Native. With one theme every value is a literal and no runtime is imported;
with more, each theme's styles are precomputed and picked by the index
`useThemeIndex()` of the new `@devup-ui/react/native` runtime gives, which
follows the OS appearance and `setTheme`. `_theme*` and the theme API
compile, and `runtime: false` keeps them build errors. The Metro plugin
registers devup.json's theme, and the Expo example gains a theme toggle and
a bundle check that static files do not use the runtime.

Part of #411.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
verify-dist loads every declared entry, and `@devup-ui/react/native`
imports react-native, which is Flow source Bun cannot parse. A virtual
module stands in for it so the entry still loads and exports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cover a typography whose token one theme does not define, a static style
merged into a themed one, and a later style checked against a choice that
applies in one theme. A merge that leaves every theme declaring the same
styles now collapses to one static style instead of picking between equal
objects.

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

codecov Bot commented Nov 20, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
libs/binding/src/lib.rs 100.00% <ø> (ø)
libs/binding/src/native_theme.rs 100.00% <100.00%> (ø)
libs/binding/src/output.rs 100.00% <ø> (ø)
libs/extractor/src/lib.rs 100.00% <ø> (ø)
libs/extractor/src/native/element.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/errors.rs 100.00% <ø> (ø)
libs/extractor/src/native/imports.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/mod.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/props.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/style.rs 100.00% <100.00%> (ø)
... and 6 more
🚀 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.

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