Skip to content

feat(native): responsive values, responsive tokens and orientation on React Native - #1044

Open
owjs3901 wants to merge 2 commits into
feat/react-native-themesfrom
feat/react-native-responsive
Open

owjs3901 wants to merge 2 commits into
feat/react-native-themesfrom
feat/react-native-responsive

Conversation

@owjs3901

Copy link
Copy Markdown
Contributor

Part of #411, depends on #1042 (base: feat/react-native-themes). PR 4 of the React Native plan: responsive values (R1).

What it does

Responsive arrays. p={[1, null, 3]} uses the breakpoints of devup.json (the web's [0, 480, 768, 992, 1280, 1600] by default), measured against the window width in dp. As on the web, each value applies from its breakpoint on and null/undefined keep the one before. A value past the last breakpoint uses the last one, as the web's media queries do.

The build precomputes one style object for each run of breakpoints that share their styles, only for the styles that differ, and picks one by the breakpoint the runtime gives:

export function Layout() {
  return <Box p={[1, null, 3]} m={2} />
}
import { useBreakpoint as __useBreakpoint } from "@devup-ui/react/native";
const __s = StyleSheet.create({ a: { margin: 8 }, b: { padding: 4 }, c: { padding: 12 } });
export function Layout() {
  const __b = __useBreakpoint();
  return <Box style={[__s.a, __b < 2 ? __s.b : __s.c]} />;
}

I used a condition on runs of breakpoints rather than [a, b, c][__b]. It is shorter when null repeats a value, and it does not depend on how many breakpoints devup.json has. When the first run has no styles, it becomes __b >= 1 && __s.x.

Theme × breakpoint. The cross product is precomputed only for the styles that differ by both. Each style of one prop is split by what it differs by (nothing, theme, breakpoint, both):

// space: light ["4px", null, "8px"], dark ["6px", null, "12px"]
<Box bg={["$primary", "$text"]} p="$space" m="$gutter" borderColor="$primary" />
style={[
  [__s.a, __s.b][__t],                       // borderColor: theme only
  __b < 2 ? __s.c : __s.d,                   // margin ($gutter): breakpoint only
  __b < 1 ? [__s.e, __s.f][__t]              // bg + padding: both
    : __b < 2 ? [__s.g, __s.h][__t] : [__s.i, __s.j][__t],
]}

The same split applies to the theme styles from #1042. For example, border="1px solid $primary" now keeps borderWidth/borderStyle in one shared object and switches only borderColor by theme. That is the only change to #1042's snapshots.

Responsive tokens and typography. A length, shadow or color token, or a typography, with a value at each breakpoint is no longer a build error. Each value cascades like the web's media queries: a typography keeps the properties of narrower breakpoints, and a relative lineHeight is recomputed against the font size at that breakpoint. Responsive values also work inside _ios/_android/_web, _theme*, _portrait/_landscape and conditions (p={on ? [1, 2] : 3}).

A longer shorthand at a wider breakpoint replaces the longhands of a narrower one. For example, m={["1px 2px", "3px"]} drops marginVertical/marginHorizontal at the second breakpoint, because React Native would otherwise prefer them over margin, whatever their order.

Values read at runtime in an array (p={[x, 2]}, p={[on ? 1 : 2, null, 3]}) apply from their breakpoint on: [{ padding: __u(x, 4) }, __b >= 1 && __s.a].

Orientation. _portrait and _landscape apply their styles while the window is in that orientation: __l && __s.a.

Hooks. Each hook is inserted at the top of the enclosing component or hook, like __useThemeIndex, and only for what the component's styles read: __useThemeIndex(), __useBreakpoint(), __useLandscape(). An element outside a component still renders through Themed, which now passes (theme, breakpoint, landscape). The compiled $s takes the parameters up to the last one it reads.

Runtime: @devup-ui/react/native

  • The store from feat(native): theme tokens, multiple themes and the React Native runtime #1042 now also tells the breakpoint (useBreakpoint, getBreakpoint) and the orientation (useLandscape, internal).

  • There is one Dimensions listener for the whole app, added with the Appearance one on the first subscription. It notifies only when the window crosses a breakpoint or turns, not on every pixel. useSyncExternalStore then re-renders only components whose own value changed.

  • defineBreakpoints([...]) is emitted only when devup.json sets breakpoints other than the web's default. defineThemes is now emitted only by files that read the theme.

  • Size, measured with bun build --minify (react and react-native external) and then gzip -9:

    Minified Minified + gzip
    Before this PR 629 B 412 B
    After this PR 1,115 B 630 B
    Change +486 B +218 B

    This is still under the design's 1.5 KB target.

runtime: false

These stay build errors with a message naming the option: a value that differs by breakpoint (arrays, responsive tokens, responsive typography) and _portrait/_landscape. A single-value array (p={[1]}, m={[2, 2]}) is not responsive and still compiles.

Still build errors

  • _pressed/_active (PR 5) and other interaction states
  • css(), styled(), globalCss(), keyframes(), Grid
  • unknown $ tokens and typographies, and tokens that reference each other in a loop
  • a typography chosen by a runtime value
  • spreads ([...a]) and nested arrays inside a responsive array

Expo example and CI

  • apps/expo adds a responsive length token ($gutter), a responsive typography (title) and responsive padding/maxW. It also adds a button row that turns into a row in _landscape.
  • check-bundle.mjs now requires src/App.tsx to call each of useThemeIndex, useBreakpoint and useLandscape, mapped through the source map. src/Badge.tsx must still use none of them. Locally, expo export for iOS and Android passes the check.
  • CI: feat/react-native-themes is added to the pull_request branches of the workflow. It will be removed when this PR is retargeted.

Tests

  • Rust (insta + rstest):
    • responsive arrays (null/undefined/holes/booleans, past the last breakpoint, shorthands, dynamic and conditional items, platform blocks, merges);
    • orientation blocks, including nested ones;
    • hook placement and name collisions;
    • theme × breakpoint with responsive tokens and typographies;
    • custom and empty breakpoints;
    • runtime: false;
    • errors;
    • unit tests for the shorthand cascade and the selection code;
    • binding-core keeping the breakpoints.
  • cargo test --workspace passes, including all 13,448 extractor tests. There are no web snapshot changes.
  • clippy -D warnings and cargo fmt are clean.
  • Runtime bun tests (mock.module('react-native') for Dimensions and Appearance) cover:
    • breakpoint edges;
    • custom and empty breakpoints;
    • re-rendering only when a boundary is crossed (counted renders);
    • orientation changes;
    • one shared listener;
    • Themed with all three values.
    • Coverage is 100%. ESLint is clean.

#411의 일부이며 #1042에 의존합니다 (base: feat/react-native-themes). React Native 계획의 4번째 PR인 반응형(R1)입니다.

변경 내용

반응형 배열. p={[1, null, 3]}는 devup.json의 breakpoints(기본값은 웹과 같은 [0, 480, 768, 992, 1280, 1600])를 창 너비(dp)에 적용합니다. 웹처럼 각 값은 그 breakpoint부터 적용되고, null/undefined는 앞의 값을 유지합니다. 마지막 breakpoint보다 뒤에 있는 값은 웹의 media query처럼 마지막 breakpoint를 씁니다.

빌드는 스타일이 같은 breakpoint 구간마다 스타일 객체를 하나씩 미리 만듭니다. 이때 달라지는 스타일만 따로 만들고, 런타임이 알려 주는 breakpoint로 그중 하나를 고릅니다(위 예시 참고). 출력은 [a, b, c][__b] 대신 구간별 조건식입니다. null로 값이 반복될 때 더 짧고, devup.json의 breakpoint 개수와도 무관하기 때문입니다. 첫 구간에 스타일이 없으면 __b >= 1 && __s.x가 됩니다.

테마 × breakpoint. 둘 다에 따라 달라지는 스타일만 조합을 미리 계산합니다. 한 prop의 스타일은 달라지는 기준(없음, 테마, breakpoint, 둘 다)별로 나뉩니다. 이 분리는 #1042의 테마 스타일에도 적용됩니다. 예를 들어 border="1px solid $primary"는 borderWidth/borderStyle을 하나의 공유 객체에 두고 borderColor만 테마별로 바꿉니다. #1042 snapshot이 바뀐 곳은 이것뿐입니다.

반응형 토큰과 typography. breakpoint별 값이 있는 length/shadow/color 토큰과 typography는 이제 빌드 에러가 아닙니다. 각 값은 웹의 media query처럼 이어집니다. typography는 좁은 breakpoint의 속성을 유지하고, 상대 lineHeight는 그 breakpoint의 font size로 다시 계산합니다. _ios/_android/_web, _theme*, _portrait/_landscape, 조건식(p={on ? [1, 2] : 3}) 안에서도 동작합니다.

넓은 breakpoint의 shorthand는 좁은 breakpoint의 longhand를 대체합니다. 예를 들어 m={["1px 2px", "3px"]}는 두 번째 breakpoint에서 marginVertical/marginHorizontal을 지웁니다. 그렇지 않으면 React Native는 순서와 관계없이 이 longhand를 margin보다 우선합니다.

배열 안의 런타임 값(p={[x, 2]}, p={[on ? 1 : 2, null, 3]})은 그 breakpoint부터 적용됩니다.

방향. _portrait/_landscape는 창이 그 방향일 때만 적용됩니다(__l && __s.a).

Hook. __useThemeIndex처럼 감싸는 컴포넌트나 hook 맨 위에 넣습니다. 컴포넌트의 스타일이 읽는 것에 해당하는 hook만 넣습니다(__useThemeIndex(), __useBreakpoint(), __useLandscape()). 컴포넌트 밖의 요소는 계속 Themed로 렌더링하며, Themed는 이제 (theme, breakpoint, landscape)를 넘깁니다. 컴파일된 $s는 마지막으로 읽는 값까지만 매개변수로 받습니다.

런타임 @devup-ui/react/native

  • #1042의 store가 이제 breakpoint(useBreakpoint, getBreakpoint)와 방향(useLandscape, 내부용)도 알려 줍니다.

  • Dimensions 리스너는 앱 전체에 하나뿐이며, 첫 구독 때 Appearance 리스너와 함께 등록됩니다. 픽셀마다 알리지 않고, breakpoint 경계를 넘거나 회전할 때만 알립니다. 그러면 useSyncExternalStore가 자기 값이 바뀐 컴포넌트만 다시 렌더링합니다.

  • defineBreakpoints([...])는 devup.json이 웹 기본값과 다른 breakpoint를 줄 때만 출력합니다. defineThemes는 이제 테마를 읽는 파일에서만 출력합니다.

  • 크기는 bun build --minify(react와 react-native는 external)로 번들한 뒤 gzip -9로 측정했습니다.

    minified min+gz
    이 PR 이전 629 B 412 B
    이 PR 이후 1,115 B 630 B
    증가량 +486 B +218 B

    설계안의 목표인 1.5 KB보다 작습니다.

runtime: false

breakpoint별로 달라지는 값(배열, 반응형 토큰, 반응형 typography)과 _portrait/_landscape는 옵션 이름을 밝히는 메시지와 함께 계속 빌드 에러입니다. 값이 하나뿐인 배열(p={[1]}, m={[2, 2]})은 반응형이 아니므로 그대로 컴파일됩니다.

여전히 빌드 에러인 것

  • _pressed/_active(PR 5)와 그 밖의 상호작용 상태
  • css(), styled(), globalCss(), keyframes(), Grid
  • 정의되지 않은 $ 토큰과 typography, 서로를 순환 참조하는 토큰
  • 런타임 값으로 고르는 typography
  • 반응형 배열 안의 spread([...a])와 중첩 배열

Expo 예제와 CI

  • apps/expo에 반응형 length 토큰($gutter), 반응형 typography(title), 반응형 padding/maxW를 추가했습니다. _landscape에서 가로로 바뀌는 버튼 줄도 추가했습니다.
  • check-bundle.mjs는 이제 source map으로 위치를 찾아 src/App.tsx가 useThemeIndex, useBreakpoint, useLandscape를 각각 호출하는지 확인합니다. src/Badge.tsx는 여전히 아무것도 쓰지 않아야 합니다. 로컬에서 iOS·Android expo export가 이 검사를 통과했습니다.
  • CI: workflow의 pull_request branches에 feat/react-native-themes를 추가했습니다. 이 PR의 base를 바꿀 때 제거합니다.

테스트

  • Rust (insta + rstest):
    • 반응형 배열(null/undefined/빈 자리/boolean, 마지막 breakpoint 이후 값, shorthand, 동적·조건부 항목, 플랫폼 블록, 병합);
    • 중첩을 포함한 방향 블록;
    • hook 위치와 이름 충돌;
    • 반응형 토큰과 typography를 쓰는 테마 × breakpoint;
    • 사용자 지정 breakpoint와 빈 breakpoint;
    • runtime: false;
    • 에러;
    • shorthand cascade와 선택 코드 단위 테스트;
    • binding-core의 breakpoint 유지.
  • cargo test --workspace가 extractor 테스트 13,448개를 포함해 모두 통과합니다. 웹 snapshot 변경은 없습니다.
  • clippy -D warnings와 cargo fmt는 깨끗합니다.
  • 런타임 bun 테스트(Dimensions와 Appearance를 대신하는 mock.module('react-native'))가 다루는 것:
    • breakpoint 경계;
    • 사용자 지정 breakpoint와 빈 breakpoint;
    • 경계를 넘을 때만 다시 렌더링(렌더 횟수 확인);
    • 방향 변경;
    • 공유 리스너 하나;
    • 세 값을 모두 넘기는 Themed.
    • coverage는 100%입니다. ESLint는 깨끗합니다.

🤖 Generated with Claude Code

owjs3901 and others added 2 commits November 21, 2026 10:45
… React Native

Responsive arrays, length/shadow/typography tokens with a value at each
breakpoint, responsive values in platform, theme and orientation blocks and
conditions compile to one style object for each run of breakpoints that
share their styles (by breakpoint and theme where both differ). The runtime
store of @devup-ui/react/native also tells the breakpoint of devup.json the
window is at and its orientation through one Dimensions listener that
notifies only when a breakpoint is crossed or the window turns.
_portrait/_landscape apply by orientation. With runtime: false these stay
build errors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The React Native runtime now reads the window size through Dimensions.

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

codecov Bot commented Nov 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Files with missing lines Coverage Δ
libs/binding/src/native_theme.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/element.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/errors.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/mod.rs 100.00% <ø> (ø)
libs/extractor/src/native/props.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/style.rs 100.00% <100.00%> (ø)
libs/extractor/src/native/theme.rs 100.00% <100.00%> (ø)
packages/react/src/native/index.ts 100.00% <100.00%> (ø)
🚀 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