From bba5fc4cdf34d3a13f8c23872772e1c386d60761 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 22 Nov 2026 03:07:09 +0900 Subject: [PATCH 1/2] feat(native): viewport lengths and reduced motion on React Native `vw`, `vh`, `vmin` and `vmax` (with their small, large and dynamic forms) compile to one multiplication of the window's width or height, which new runtime hooks give. Only components using a viewport length render again on a resize, and elements outside a function component render through the new `Sized` wrapper. `_motionReduce` and `_motionSafe` apply by the system's reduced-motion setting, which the runtime reads from AccessibilityInfo and follows. With `runtime: false`, both are build errors. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_metro_viewport_motion.json | 7 + ...pack_log_react_native_viewport_motion.json | 7 + .github/workflows/publish.yml | 1 + apps/expo/check-bundle.mjs | 23 +- apps/expo/check-web.mjs | 8 +- apps/expo/src/App.tsx | 8 +- .../app/(detail)/docs/react-native/page.mdx | 5 +- libs/extractor/src/native/element.rs | 230 +++++++++++++++--- .../extractor/src/native/element/animation.rs | 2 +- libs/extractor/src/native/element/css_call.rs | 2 +- libs/extractor/src/native/errors.rs | 7 +- libs/extractor/src/native/props.rs | 15 ++ ...ctor__native__tests__animation_errors.snap | 8 +- .../extractor__native__tests__css_errors.snap | 2 +- ...tractor__native__tests__motion_blocks.snap | 32 +++ ...or__native__tests__motion_runtime_off.snap | 6 + ...__native__tests__theme_viewport_token.snap | 5 + ...or__native__tests__unsupported_values.snap | 1 - ...ative__tests__viewport_css_and_styled.snap | 16 ++ ...native__tests__viewport_focused_input.snap | 5 + ...or__native__tests__viewport_keyframes.snap | 6 + ...ctor__native__tests__viewport_lengths.snap | 23 ++ ...ve__tests__viewport_outside_component.snap | 14 ++ ...r__native__tests__viewport_responsive.snap | 25 ++ ...__native__tests__viewport_runtime_off.snap | 5 + libs/extractor/src/native/style.rs | 103 +++++--- libs/extractor/src/native/tests.rs | 81 +++++- libs/extractor/src/native/values.rs | 64 ++++- packages/metro-plugin/README.md | 43 +++- .../native/__tests__/index.browser.test.tsx | 84 +++++++ packages/react/src/native/index.ts | 145 ++++++++--- 31 files changed, 852 insertions(+), 131 deletions(-) create mode 100644 .changepacks/changepack_log_metro_viewport_motion.json create mode 100644 .changepacks/changepack_log_react_native_viewport_motion.json create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__motion_blocks.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__motion_runtime_off.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__theme_viewport_token.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__viewport_css_and_styled.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__viewport_focused_input.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__viewport_keyframes.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__viewport_lengths.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__viewport_outside_component.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__viewport_responsive.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__viewport_runtime_off.snap diff --git a/.changepacks/changepack_log_metro_viewport_motion.json b/.changepacks/changepack_log_metro_viewport_motion.json new file mode 100644 index 000000000..67690a931 --- /dev/null +++ b/.changepacks/changepack_log_metro_viewport_motion.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/metro-plugin/package.json": "Patch" + }, + "note": "Compile `vw`/`vh`/`vmin`/`vmax` (and their small, large and dynamic forms) to one multiplication of the window size, and `_motionReduce`/`_motionSafe` to the system's reduced-motion setting, on React Native.", + "date": "2026-11-22T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_react_native_viewport_motion.json b/.changepacks/changepack_log_react_native_viewport_motion.json new file mode 100644 index 000000000..cd493d3e8 --- /dev/null +++ b/.changepacks/changepack_log_react_native_viewport_motion.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/react/package.json": "Patch" + }, + "note": "The React Native runtime adds `useReducedMotion` (from `AccessibilityInfo`), `useWindowWidth`, `useWindowHeight` and the `Sized` wrapper, for `_motionReduce`/`_motionSafe` and viewport lengths. Window changes now notify every hook, and React renders again only the components whose value changed. The runtime grows from 1,185 B to 1,302 B min+gzip.", + "date": "2026-11-22T00:00:00.000Z" +} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 0a3a8da91..0709ccc72 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -19,6 +19,7 @@ on: - feat/react-native-compat - feat/react-native-web - feat/react-native-types + - feat/react-native-docs # Pull requests and every job below run read-only. Only the `release` and # `deploy-pages` jobs get write permissions, and they run on pushes to main diff --git a/apps/expo/check-bundle.mjs b/apps/expo/check-bundle.mjs index 704d8d76f..cf2898846 100644 --- a/apps/expo/check-bundle.mjs +++ b/apps/expo/check-bundle.mjs @@ -15,9 +15,16 @@ import { join } from 'node:path' const PLACEHOLDER = 'Cannot run on the runtime' /** Names of the runtime that only code using it holds, as minified code keeps them */ const RUNTIME_NAMES = - /\b(?:defineThemes|useThemeIndex|useBreakpoint|useLandscape|Focused)\b/g + /\b(?:defineThemes|useThemeIndex|useBreakpoint|useLandscape|useReducedMotion|useWindowWidth|useWindowHeight|Focused)\b/g /** What src/App.tsx must use from the runtime */ -const APP_HOOKS = ['useThemeIndex', 'useBreakpoint', 'useLandscape', 'Focused'] +const APP_HOOKS = [ + 'useThemeIndex', + 'useBreakpoint', + 'useLandscape', + 'useReducedMotion', + 'useWindowHeight', + 'Focused', +] /** Modules of @devup-ui/react, by the path Metro resolves */ const REACT_PACKAGE = /(^|[\\/])(@devup-ui[\\/]react|packages[\\/]react)[\\/]/ /** @@ -99,13 +106,21 @@ function mapSources(map) { : map.sources } -/** Each name of the runtime, with the sources of the code that names it */ +/** + * Each name of the runtime, with the sources of the app that name it: a + * package may name its own hook the same (Reanimated's `useReducedMotion`) + */ function runtimeUsers(code, locate) { const users = new Map() code.split('\n').forEach((line, index) => { for (const match of line.matchAll(RUNTIME_NAMES)) { const source = locate(index, match.index) - if (source === null || NATIVE_RUNTIME.test(source)) continue + if ( + source === null || + NATIVE_RUNTIME.test(source) || + /[\\/]node_modules[\\/]/.test(source) + ) + continue const sources = users.get(match[0]) ?? new Set() sources.add(source) users.set(match[0], sources) diff --git a/apps/expo/check-web.mjs b/apps/expo/check-web.mjs index 2d28949c7..0aad26c65 100644 --- a/apps/expo/check-web.mjs +++ b/apps/expo/check-web.mjs @@ -1,6 +1,7 @@ // Opens the web export (`expo export --platform web` wrote dist/) in Chromium // and checks that react-native-web renders the styles Devup UI compiled: the -// card takes the theme's color and switches with the theme, the input takes +// card takes the theme's color and switches with the theme and is at least +// 30vh tall, the input takes // its focus style through the runtime's `Focused`, and the button, a // `Pressable`, counts a press. import { createReadStream, existsSync, statSync } from 'node:fs' @@ -66,6 +67,11 @@ try { 'rgb(255, 255, 255)', 'the card in the light theme', ) + expectEqual( + await style(card, 'minHeight'), + `${(await page.evaluate(() => window.innerHeight)) * 0.3}px`, + 'the card, at least 30vh tall', + ) expectEqual( await style(count, 'backgroundColor'), 'rgb(90, 68, 255)', diff --git a/apps/expo/src/App.tsx b/apps/expo/src/App.tsx index e6318fa87..475183f84 100644 --- a/apps/expo/src/App.tsx +++ b/apps/expo/src/App.tsx @@ -58,11 +58,17 @@ export function App() { borderRadius="$radius" boxShadow="$raised" maxW={[null, null, '480px']} + minH="30vh" p={[4, null, 6]} testID="card" w="100%" > - + Your name Self { + Self { + name: fresh_name(name, code), + used: false, + } + } + + /// The name, which the file now uses + fn use_name(&mut self) -> String { + self.used = true; + self.name.clone() + } +} + /// The runtime hooks, in the order they are called, by the name they are -/// exported under: they read the theme, the breakpoint and the orientation -const HOOKS: [&str; 3] = ["useThemeIndex", "useBreakpoint", "useLandscape"]; +/// exported under: they read what each `Read` names +const HOOKS: [&str; READS] = [ + "useThemeIndex", + "useBreakpoint", + "useLandscape", + "useReducedMotion", + "useWindowWidth", + "useWindowHeight", +]; impl Runtime { fn new(code: &str) -> Self { @@ -97,6 +134,9 @@ impl Runtime { index: fresh_name("__t", code), breakpoint: fresh_name("__b", code), landscape: fresh_name("__l", code), + motion: fresh_name("__m", code), + width: fresh_name("__vw", code), + height: fresh_name("__vh", code), pressed: fresh_name("__p", code), hovered: fresh_name("__h", code), focused: fresh_name("__f", code), @@ -106,8 +146,8 @@ impl Runtime { styled_theme_used: false, hooks: HOOKS.map(|hook| fresh_name(&format!("__{hook}"), code)), hooks_used: Reads::default(), - wrapper: fresh_name("__Themed", code), - wrapper_used: false, + wrapper: Import::new("__Themed", code), + sized_wrapper: Import::new("__Sized", code), wrapper_reads: Reads::default(), define: fresh_name("__defineThemes", code), define_breakpoints: fresh_name("__defineBreakpoints", code), @@ -120,6 +160,7 @@ impl Runtime { theme: &self.index, breakpoint: &self.breakpoint, landscape: &self.landscape, + motion: &self.motion, pressed: &self.pressed, hovered: &self.hovered, focused: &self.focused, @@ -129,18 +170,32 @@ impl Runtime { /// The variables of `reads`, in the order of the hooks fn variables(&self, reads: Reads) -> impl Iterator { - [&self.index, &self.breakpoint, &self.landscape] + self.runtime_variables() .into_iter() .enumerate() .filter(move |(at, _)| reads.flags()[*at]) .map(|(at, name)| (at, name.as_str())) } + /// The variables holding what the runtime tells, in the order of the + /// hooks + const fn runtime_variables(&self) -> [&String; READS] { + [ + &self.index, + &self.breakpoint, + &self.landscape, + &self.motion, + &self.width, + &self.height, + ] + } + /// The import of the runtime and the calls telling it the theme names /// and the breakpoints, when the file uses it fn prelude(&self, target: &NativeTarget, theme_api: bool) -> Option { if !(self.hooks_used.any() - || self.wrapper_used + || self.wrapper.used + || self.sized_wrapper.used || self.focused_used || self.styled_theme_used || theme_api) @@ -152,8 +207,10 @@ impl Runtime { .variables(self.hooks_used) .map(|(at, _)| format!("{} as {}", HOOKS[at], self.hooks[at])) .collect(); - if self.wrapper_used { - specifiers.push(format!("Themed as {}", self.wrapper)); + for (export, import) in [("Themed", &self.wrapper), ("Sized", &self.sized_wrapper)] { + if import.used { + specifiers.push(format!("{export} as {}", import.name)); + } } if self.styled_theme_used { specifiers.push(format!("useStyledTheme as {}", self.styled_theme)); @@ -163,7 +220,7 @@ impl Runtime { } let theme = &target.theme; let mut calls = String::new(); - if reads.theme || theme_api { + if reads.has(Read::Theme) || theme_api { specifiers.push(format!("defineThemes as {}", self.define)); let names = serde_json::Value::from(theme.names.clone()).to_string(); let dark = theme @@ -171,7 +228,7 @@ impl Runtime { .map_or_else(String::new, |dark| format!(", {dark}")); let _ = writeln!(calls, "{}({names}{dark});", self.define); } - if reads.breakpoint && theme.breakpoints != DEFAULT_BREAKPOINTS { + if reads.has(Read::Breakpoint) && theme.breakpoints != DEFAULT_BREAKPOINTS { specifiers.push(format!("defineBreakpoints as {}", self.define_breakpoints)); let breakpoints = serde_json::Value::from(theme.breakpoints.clone()).to_string(); let _ = writeln!(calls, "{}({breakpoints});", self.define_breakpoints); @@ -313,8 +370,9 @@ enum Prop { Platform(NativePlatform), /// `_themeDark` and the like: styles for the theme named Theme(String), - /// `_landscape`, `_portrait` and `_pressed`: styles applied while the - /// window is in that orientation or the element is pressed + /// `_landscape`, `_motionReduce`, `_pressed` and the like: styles + /// applied while the window is in that orientation, the system reduces + /// motion or the element is pressed When(State), /// What React Native has no equivalent of Unsupported(Problem), @@ -332,6 +390,8 @@ fn classify(name: &str) -> Prop { "_web" => Prop::Platform(NativePlatform::Web), "_portrait" => Prop::When(State::Landscape(false)), "_landscape" => Prop::When(State::Landscape(true)), + "_motionReduce" => Prop::When(State::ReducedMotion(true)), + "_motionSafe" => Prop::When(State::ReducedMotion(false)), "_pressed" | "_active" => Prop::When(State::Pressed), "_hover" => Prop::When(State::Hovered), "_focus" => Prop::When(State::Focused), @@ -705,6 +765,13 @@ impl<'a> Elements<'_> { } else { Cow::Borrowed(items) }; + if items + .iter() + .any(|(_, literal)| viewport_of(literal).is_some()) + && let Some(keys) = length_keys(name) + { + return self.viewport_choice(name, &keys, &items); + } let theme = &self.target.theme; let themes = match self.theme_scope { Some(index) => index..index + 1, @@ -739,14 +806,73 @@ impl<'a> Elements<'_> { Ok(choice) } + /// The styles of the literals of the style prop `name`, which sets + /// `keys`, where one at least is a viewport length: each from its + /// breakpoint on, a viewport length computed from the window's size + fn viewport_choice( + &self, + name: &str, + keys: &[&str], + items: &[(usize, Literal)], + ) -> Result { + if !self.target.runtime { + return Err(RuntimeFeature::Viewport.problem()); + } + let mut choices = Vec::with_capacity(items.len()); + for (level, literal) in items { + let choice = match viewport_of(literal) { + Some(length) => self.computed(keys, length), + None => self.static_choice(name, &[(0, literal.clone())])?, + }; + choices.push(if *level == 0 { + choice + } else { + when(State::AtLeast(*level), choice) + }); + } + Ok(if choices.len() == 1 { + choices.remove(0) + } else { + Choice::All(choices) + }) + } + + /// The styles `keys` take from a viewport length: the hundredths + /// `amount` of what `viewport` measures, one multiplication of the size + /// the runtime tells + fn computed(&self, keys: &[&str], (amount, viewport): (f64, Viewport)) -> Choice { + let (width, height) = (&self.runtime.width, &self.runtime.height); + let both = Reads::default() + .with(Read::Width, true) + .with(Read::Height, true); + let (side, reads) = match viewport { + Viewport::Width => (width.clone(), Reads::default().with(Read::Width, true)), + Viewport::Height => (height.clone(), Reads::default().with(Read::Height, true)), + Viewport::Min => (format!("Math.min({width}, {height})"), both), + Viewport::Max => (format!("Math.max({width}, {height})"), both), + }; + let factor = number_code(amount / 100.0); + let code = if factor == "1" { + side + } else { + format!("{side} * {factor}") + }; + Choice::Computed( + keys.iter() + .map(|key| ((*key).to_string(), code.clone())) + .collect(), + reads, + ) + } + /// Fail for a choice the runtime makes when it is turned off fn check_runtime(&self, choice: &Choice) -> Result<(), Problem> { let reads = choice.reads(); let feature = if self.target.runtime { None - } else if reads.breakpoint { + } else if reads.has(Read::Breakpoint) { Some(RuntimeFeature::Responsive) - } else if reads.theme { + } else if reads.has(Read::Theme) { Some(RuntimeFeature::Theme) } else { None @@ -1042,10 +1168,12 @@ impl<'a> Elements<'_> { if INTERACTIONS.contains(&state) { self.press.get_or_insert_with(|| (offset, name.to_string())); } else if !self.target.runtime && state != State::Disabled { - self.error( - offset, - RuntimeFeature::Orientation.problem().on(local, name), - ); + let feature = if matches!(state, State::ReducedMotion(_)) { + RuntimeFeature::Motion + } else { + RuntimeFeature::Orientation + }; + self.error(offset, feature.problem().on(local, name)); return Vec::new(); } self.block(value, name, offset, local) @@ -1369,15 +1497,17 @@ impl<'a> Elements<'_> { if !in_component { self.runtime.wrapper_reads = self.runtime.wrapper_reads.union(reads); } - let wrapper = if focus_wrapped { - self.runtime.focused_used = true; - Some(self.runtime.focused_wrapper.clone()) - } else if in_component { - None - } else { - self.runtime.wrapper_used = true; - Some(self.runtime.wrapper.clone()) - }; + if focus_wrapped && !in_component && reads.sized() { + self.error( + element.span.start, + Problem::new( + "an input with a focus style outside a function component cannot read the window's size, which a viewport length needs", + "render the input in a function component", + ) + .on(local, "_focus"), + ); + } + let wrapper = self.wrapper(focus_wrapped, in_component, reads); if let Some(name) = wrapper.as_ref().or(tag.as_ref()) { self.rename(element, name); } @@ -1393,11 +1523,7 @@ impl<'a> Elements<'_> { // up to the last it reads let focus = focus_wrapped.then_some(self.runtime.focused.as_str()); let read = self.runtime.variables(reads).last().map(|(at, _)| at); - let runtime = [ - &self.runtime.index, - &self.runtime.breakpoint, - &self.runtime.landscape, - ]; + let runtime = self.runtime.runtime_variables(); let parameters = focus .into_iter() .chain( @@ -1427,6 +1553,24 @@ impl<'a> Elements<'_> { .push((attributes_end as usize, attributes_end as usize, code)); } + /// The component rendering an element that reads `reads` from the + /// runtime for it: `Focused` for an input with a focus style, none in a + /// function component, else `Themed`, or `Sized` where it reads the + /// window's size + fn wrapper(&mut self, focus_wrapped: bool, in_component: bool, reads: Reads) -> Option { + let runtime = &mut self.runtime; + if focus_wrapped { + runtime.focused_used = true; + Some(runtime.focused_wrapper.clone()) + } else if in_component { + None + } else if reads.sized() { + Some(runtime.sized_wrapper.use_name()) + } else { + Some(runtime.wrapper.use_name()) + } + } + /// The component an element taking a press style renders: React Native's /// `Pressable` for a `View`, which only it can call the style of with /// whether it is pressed, or the `Pressable` it already renders @@ -1624,6 +1768,14 @@ pub(super) fn units_declaration(name: &str) -> String { ) + "\n" } +/// The viewport length `literal` writes, if it writes one +fn viewport_of(literal: &Literal) -> Option<(f64, Viewport)> { + match literal { + Literal::Text(text) => viewport_length(text), + Literal::Number(_) => None, + } +} + /// The span of a child writing text, if it writes any fn text_child(child: &JSXChild<'_>) -> Option { match child { diff --git a/libs/extractor/src/native/element/animation.rs b/libs/extractor/src/native/element/animation.rs index cff658c58..ba160abbc 100644 --- a/libs/extractor/src/native/element/animation.rs +++ b/libs/extractor/src/native/element/animation.rs @@ -244,7 +244,7 @@ impl<'a> Elements<'_> { self.error( property.span.start, Problem::new( - "react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition", + "react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size", "write one value for each style of the keyframe", ) .on(KEYFRAMES, &key), diff --git a/libs/extractor/src/native/element/css_call.rs b/libs/extractor/src/native/element/css_call.rs index 45ecf7bfc..57e5215b6 100644 --- a/libs/extractor/src/native/element/css_call.rs +++ b/libs/extractor/src/native/element/css_call.rs @@ -399,7 +399,7 @@ fn spread_problem() -> String { fn outside_component_problem() -> String { Problem::new( - "its styles differ by theme, breakpoint or orientation, which only a function component or a hook can read", + "its styles differ by theme, breakpoint, orientation, motion or the window's size, which only a function component or a hook can read", "call `css()` in the component that uses it", ) .call(CSS) diff --git a/libs/extractor/src/native/errors.rs b/libs/extractor/src/native/errors.rs index 3eb7df9fa..477020cc2 100644 --- a/libs/extractor/src/native/errors.rs +++ b/libs/extractor/src/native/errors.rs @@ -53,6 +53,8 @@ pub(super) enum RuntimeFeature { Responsive, Orientation, Theme, + Motion, + Viewport, } impl RuntimeFeature { @@ -61,14 +63,17 @@ impl RuntimeFeature { Self::Responsive => "a responsive value is chosen by the window width", Self::Orientation => "an orientation style is chosen by the orientation of the window", Self::Theme => "a theme variant is chosen by the theme the app shows", + Self::Motion => "a motion style is chosen by whether the system reduces motion", + Self::Viewport => "a viewport length is computed from the window's size", } } const fn fix(self) -> &'static str { match self { Self::Responsive => "give one value, or turn the runtime on", - Self::Orientation => "remove it, or turn the runtime on", + Self::Orientation | Self::Motion => "remove it, or turn the runtime on", Self::Theme => "give the value for one theme, or turn the runtime on", + Self::Viewport => "use a number of pixels or a percentage, or turn the runtime on", } } diff --git a/libs/extractor/src/native/props.rs b/libs/extractor/src/native/props.rs index 8bfe34acf..e1e3b41b8 100644 --- a/libs/extractor/src/native/props.rs +++ b/libs/extractor/src/native/props.rs @@ -570,6 +570,21 @@ pub(super) fn dynamic_keys(prop: &str) -> Result) .collect() } +/// The React Native keys a viewport length of the style prop `prop` sets, +/// when each takes a length +pub(super) fn length_keys(prop: &str) -> Option> { + css::disassemble_property(prop) + .map(|property| match property.as_ref() { + "margin" => Some("margin"), + "padding" => Some("padding"), + property => native_property(property) + .ok() + .filter(|(_, kind)| matches!(kind, Kind::Length | Kind::LineHeight)) + .map(|(key, _)| key), + }) + .collect() +} + /// The scale a number read at runtime for the CSS `property` of `kind` is /// multiplied by, as the web build scales a literal: four pixels a unit for a /// length, but for the properties taking a plain number diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__animation_errors.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__animation_errors.snap index 6f4ced5bf..8c305cf3a 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__animation_errors.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__animation_errors.snap @@ -2,10 +2,10 @@ source: libs/extractor/src/native/tests.rs expression: output --- -error: test.tsx:3:23: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition. Fix: write one value for each style of the keyframe -test.tsx:3:49: `keyframes()` cannot use `to` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition. Fix: write one value for each style of the keyframe -test.tsx:3:74: `keyframes()` cannot use `at` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition. Fix: write one value for each style of the keyframe -test.tsx:4:23: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition. Fix: write one value for each style of the keyframe +error: test.tsx:3:23: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe +test.tsx:3:49: `keyframes()` cannot use `to` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe +test.tsx:3:74: `keyframes()` cannot use `at` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe +test.tsx:4:23: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe test.tsx:4:62: `keyframes()` cannot use `to` on React Native: a keyframe holds style props. Fix: give it an object, such as `{ opacity: 0 }` test.tsx:4:65: `keyframes()` cannot compile here on React Native: the build reads only the keyframes written in the object. Fix: write each keyframe in it test.tsx:5:11: `keyframes()` cannot compile here on React Native: the build reads the keyframes written in the call. Fix: pass one object of keyframes, such as `keyframes({ from: { opacity: 0 }, to: { opacity: 1 } })` diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap index ba1792e28..b42166b23 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap @@ -2,7 +2,7 @@ source: libs/extractor/src/native/tests.rs expression: "compile_themed(two_themes(), runtime, code)" --- -error: test.tsx:3:18: `css()` cannot compile here on React Native: its styles differ by theme, breakpoint or orientation, which only a function component or a hook can read. Fix: call `css()` in the component that uses it +error: test.tsx:3:18: `css()` cannot compile here on React Native: its styles differ by theme, breakpoint, orientation, motion or the window's size, which only a function component or a hook can read. Fix: call `css()` in the component that uses it test.tsx:4:22: `css()` cannot compile here on React Native: the build reads only the parts written in the call. Fix: pass each part to `css()` itself test.tsx:5:22: `css()` cannot use `a part` on React Native: React Native has no class names. Fix: pass what `css()` gives, or write the styles as props test.tsx:5:30: `css()` cannot use `a part` on React Native: React Native has no class names. Fix: pass what `css()` gives, or write the styles as props diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__motion_blocks.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__motion_blocks.snap new file mode 100644 index 000000000..234749dbf --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__motion_blocks.snap @@ -0,0 +1,32 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useReducedMotion as __useReducedMotion, Themed as __Themed } from "@devup-ui/react/native"; +import __Animated from "react-native-reanimated"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { padding: 4 }, + b: { opacity: 1 }, + c: { opacity: .5 }, + d: { padding: 8 }, + e: { + transitionDuration: "300ms", + transitionProperty: "opacity" + }, + f: { transitionDuration: "0ms" } +}); +export function A() { + const __m = __useReducedMotion(); + return ; +} +export const b = <__Themed $c={Box} $s={(__t, __b, __l, __m) => __m && __s.d} />; +export function C() { + const __m = __useReducedMotion(); + return <__Animated.View style={[__s.e, __m && __s.f]} />; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__motion_runtime_off.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__motion_runtime_off.snap new file mode 100644 index 000000000..5e2cc389f --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__motion_runtime_off.snap @@ -0,0 +1,6 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:2:23: `` cannot use `_motionReduce` on React Native: a motion style is chosen by whether the system reduces motion, which needs the React Native runtime that `runtime: false` turns off. Fix: remove it, or turn the runtime on +test.tsx:2:48: `` cannot use `_motionSafe` on React Native: a motion style is chosen by whether the system reduces motion, which needs the React Native runtime that `runtime: false` turns off. Fix: remove it, or turn the runtime on diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__theme_viewport_token.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_viewport_token.snap new file mode 100644 index 000000000..4a00f3f14 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_viewport_token.snap @@ -0,0 +1,5 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, code)" +--- +error: test.tsx:2:6: `` cannot use `w` on React Native: `50vw` is a viewport length, which the build computes only where a style prop writes it. Fix: write the viewport length in the style prop, or use a number of pixels or a percentage diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__unsupported_values.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__unsupported_values.snap index 9e2cb108a..fc0afc561 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__unsupported_values.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__unsupported_values.snap @@ -4,7 +4,6 @@ expression: compile(code) --- error: test.tsx:2:6: `` cannot use `display` on React Native: React Native does not read `grid` here. Fix: use one of `none`, `flex` or `contents` test.tsx:2:21: `` cannot use `position` on React Native: React Native does not read `fixed` here. Fix: use one of `absolute`, `relative` or `static` -test.tsx:2:38: `` cannot use `w` on React Native: `10vw` needs the window size, which React Native knows only at runtime. Fix: use a number of pixels or a percentage test.tsx:2:47: `` cannot use `h` on React Native: React Native cannot compute `calc(100% - 4px)`. Fix: write the value itself test.tsx:2:68: `` cannot use `maxW` on React Native: React Native cannot compute `var(--w)`. Fix: write the value itself test.tsx:3:3: `` cannot use `minW` on React Native: React Native styles have no `!important`. Fix: remove `!important`; a later style already wins diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_css_and_styled.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_css_and_styled.snap new file mode 100644 index 000000000..07249b7ec --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_css_and_styled.snap @@ -0,0 +1,16 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useWindowWidth as __useWindowWidth, useWindowHeight as __useWindowHeight } from "@devup-ui/react/native"; +import { View as __View } from "react-native"; +export const Tall = (__props) => { + const __vh = __useWindowHeight(); + return <__View {...__props} style={[{ height: __vh * .5 }, __props.style]} />; +}; +export function A() { + const __vw = __useWindowWidth(); + const wide = { width: __vw * .5 }; + return ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_focused_input.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_focused_input.snap new file mode 100644 index 000000000..05f796a1b --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_focused_input.snap @@ -0,0 +1,5 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:2:18: `` cannot use `_focus` on React Native: an input with a focus style outside a function component cannot read the window's size, which a viewport length needs. Fix: render the input in a function component diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_keyframes.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_keyframes.snap new file mode 100644 index 000000000..c90153508 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_keyframes.snap @@ -0,0 +1,6 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:3:26: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe +test.tsx:3:46: `keyframes()` cannot use `to` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_lengths.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_lengths.snap new file mode 100644 index 000000000..915670c4c --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_lengths.snap @@ -0,0 +1,23 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useWindowWidth as __useWindowWidth, useWindowHeight as __useWindowHeight } from "@devup-ui/react/native"; +export function A() { + const __vw = __useWindowWidth(); + const __vh = __useWindowHeight(); + return ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_outside_component.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_outside_component.snap new file mode 100644 index 000000000..d0b3b7656 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_outside_component.snap @@ -0,0 +1,14 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { Themed as __Themed, Sized as __Sized, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { backgroundColor: "#5a44ff" }, + b: { backgroundColor: "#8c7bff" } +}); +export const a = <__Sized $c={Box} $s={(__t, __b, __l, __m, __vw) => [{ width: __vw * .5 }, [__s.a, __s.b][__t]]} />; +export const b = <__Themed $c={Box} $s={(__t) => [__s.a, __s.b][__t]} />; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_responsive.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_responsive.snap new file mode 100644 index 000000000..b114da2dc --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_responsive.snap @@ -0,0 +1,25 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useBreakpoint as __useBreakpoint, useWindowWidth as __useWindowWidth, useWindowHeight as __useWindowHeight } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { + height: 32, + backgroundColor: "10vw" + }, + b: { width: 16 } +}); +export function A() { + const __b = __useBreakpoint(); + const __vw = __useWindowWidth(); + const __vh = __useWindowHeight(); + return = 2 && __s.b, + __b >= 1 && { height: __vh * .5 } + ]} />; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_runtime_off.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_runtime_off.snap new file mode 100644 index 000000000..b9846a512 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_runtime_off.snap @@ -0,0 +1,5 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:3:15: `` cannot use `w` on React Native: a viewport length is computed from the window's size, which needs the React Native runtime that `runtime: false` turns off. Fix: use a number of pixels or a percentage, or turn the runtime on diff --git a/libs/extractor/src/native/style.rs b/libs/extractor/src/native/style.rs index 78c37db50..13fc8d6c6 100644 --- a/libs/extractor/src/native/style.rs +++ b/libs/extractor/src/native/style.rs @@ -18,6 +18,8 @@ pub(super) enum State { AtLeast(usize), /// The window is in landscape (`true`) or portrait (`false`) orientation Landscape(bool), + /// The system reduces motion (`true`) or does not (`false`) + ReducedMotion(bool), /// The element is pressed Pressed, /// The pointer is over the element @@ -53,34 +55,68 @@ pub(super) enum Choice { All(Vec), /// A style passed on whole, by its code, which may declare any style Given(String), + /// Styles whose values the element computes from what the runtime + /// tells, as a viewport length from the window's size: each key with the + /// code of its value + Computed(Vec<(String, String)>, Reads), } -/// What the runtime tells a style: which theme shows, which breakpoint the -/// window is at, and whether it is in landscape +/// What the runtime tells, by the hook telling it, in the order the hooks +/// are called and a wrapper gives them to a style +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Read { + /// Which theme shows + Theme, + /// Which breakpoint the window is at + Breakpoint, + /// Whether the window is in landscape + Landscape, + /// Whether the system reduces motion + Motion, + /// The window's width + Width, + /// The window's height + Height, +} + +/// How many things the runtime tells +pub(super) const READS: usize = 6; + +/// What a style reads from the runtime #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub(super) struct Reads { - pub theme: bool, - pub breakpoint: bool, - pub landscape: bool, -} +pub(super) struct Reads([bool; READS]); impl Reads { + /// Reading `read` too when `on` + pub(super) const fn with(mut self, read: Read, on: bool) -> Self { + if on { + self.0[read as usize] = true; + } + self + } + + /// Whether it reads `read` + pub(super) const fn has(self, read: Read) -> bool { + self.0[read as usize] + } + /// Whether it reads what a hook of the runtime gives - pub(super) const fn any(self) -> bool { - self.theme || self.breakpoint || self.landscape + pub(super) fn any(self) -> bool { + self.0.contains(&true) + } + + /// Whether it reads the window's size + pub(super) const fn sized(self) -> bool { + self.has(Read::Width) || self.has(Read::Height) } /// What it reads, in the order of the runtime's hooks - pub(super) const fn flags(self) -> [bool; 3] { - [self.theme, self.breakpoint, self.landscape] + pub(super) const fn flags(self) -> [bool; READS] { + self.0 } - pub(super) const fn union(self, other: Self) -> Self { - Self { - theme: self.theme || other.theme, - breakpoint: self.breakpoint || other.breakpoint, - landscape: self.landscape || other.landscape, - } + pub(super) fn union(self, other: Self) -> Self { + Self(std::array::from_fn(|at| self.0[at] || other.0[at])) } } @@ -89,6 +125,7 @@ pub(super) struct Vars<'v> { pub theme: &'v str, pub breakpoint: &'v str, pub landscape: &'v str, + pub motion: &'v str, pub pressed: &'v str, pub hovered: &'v str, pub focused: &'v str, @@ -187,7 +224,9 @@ impl Choice { match self { Self::Empty => false, Self::Static(declarations) => declares(declarations, key), - Self::Dynamic(values) => values.iter().any(|(name, _)| name == key), + Self::Dynamic(values) | Self::Computed(values, _) => { + values.iter().any(|(name, _)| name == key) + } Self::Given(_) => true, Self::Condition { consequent, @@ -207,16 +246,15 @@ impl Choice { pub(super) fn reads(&self) -> Reads { match self { Self::Empty | Self::Static(_) | Self::Dynamic(_) | Self::Given(_) => Reads::default(), + Self::Computed(_, reads) => *reads, Self::Condition { consequent, alternate, .. } => consequent.reads().union(alternate.reads()), - Self::Varied(grid) => Reads { - theme: themes_of(grid) > 1, - breakpoint: grid.len() > 1, - landscape: false, - }, + Self::Varied(grid) => Reads::default() + .with(Read::Theme, themes_of(grid) > 1) + .with(Read::Breakpoint, grid.len() > 1), Self::When { state, choice } => choice.reads().union(state.reads()), Self::All(choices) => choices.iter().fold(Reads::default(), |reads, choice| { reads.union(choice.reads()) @@ -247,7 +285,7 @@ impl Choice { match self { Self::Empty => "null".to_string(), Self::Static(declarations) => sheet.reference(declarations), - Self::Dynamic(values) => object_code(values), + Self::Dynamic(values) | Self::Computed(values, _) => object_code(values), Self::Given(code) => code.clone(), Self::Condition { test, @@ -312,11 +350,16 @@ impl Choice { impl State { const fn reads(self) -> Reads { - Reads { - theme: matches!(self, Self::Theme(_)), - breakpoint: matches!(self, Self::AtLeast(_)), - landscape: matches!(self, Self::Landscape(_)), - } + let read = match self { + Self::Theme(_) => Read::Theme, + Self::AtLeast(_) => Read::Breakpoint, + Self::Landscape(_) => Read::Landscape, + Self::ReducedMotion(_) => Read::Motion, + Self::Pressed | Self::Hovered | Self::Focused | Self::Disabled => { + return Reads([false; READS]); + } + }; + Reads([false; READS]).with(read, true) } /// The code testing that the state holds @@ -326,6 +369,8 @@ impl State { Self::AtLeast(level) => format!("{} >= {level}", vars.breakpoint), Self::Landscape(true) => vars.landscape.to_string(), Self::Landscape(false) => format!("!{}", vars.landscape), + Self::ReducedMotion(true) => vars.motion.to_string(), + Self::ReducedMotion(false) => format!("!{}", vars.motion), Self::Pressed => vars.pressed.to_string(), Self::Hovered => vars.hovered.to_string(), Self::Focused => vars.focused.to_string(), diff --git a/libs/extractor/src/native/tests.rs b/libs/extractor/src/native/tests.rs index 0209433b6..bcd5ad030 100644 --- a/libs/extractor/src/native/tests.rs +++ b/libs/extractor/src/native/tests.rs @@ -5,7 +5,7 @@ use super::element::units_declaration; use super::errors::Problem; use super::props::Declaration; use super::sheet::{Sheet, key_name}; -use super::style::{Choice, State, Vars, cascade, in_theme, style_code, varied, when}; +use super::style::{Choice, Read, State, Vars, cascade, in_theme, style_code, varied, when}; use super::values::{Literal, NativeValue, css_text, number_or_text, quoted_list}; use super::{NativePlatform, NativeTarget, NativeTheme, TokenLevels, TypographyProperties}; use crate::{ExtractOption, ExtractTarget, extract, extract_without_source_map}; @@ -14,6 +14,7 @@ const VARS: Vars<'static> = Vars { theme: "t", breakpoint: "b", landscape: "l", + motion: "m", pressed: "p", hovered: "h", focused: "f", @@ -646,6 +647,7 @@ fn two_themes() -> NativeTheme { ("onlyDark", &[None, Some("#000")]), ("captionSize", &[Some("12px"), Some("14px")]), ("primary-100", &[Some("#eef"), Some("#223")]), + ("wide", &[Some("50vw"), Some("50vw")]), ], ) } @@ -840,6 +842,7 @@ fn runtime_off_keeps_single_values(#[case] name: &str, #[case] theme: NativeThem )] #[case::unknown_theme("theme_unknown_theme", "")] #[case::token_loop("theme_token_loop", "")] +#[case::viewport_token("theme_viewport_token", "")] #[case::bad_values( "theme_bad_values", "" @@ -1108,7 +1111,7 @@ fn varied_choices_pick_by_breakpoint_and_theme() { vec![c.clone(), c.clone()], ])); assert_eq!(both, "b < 1 ? [s.a, s.b][t] : s.c"); - assert!(reads.theme && reads.breakpoint && !reads.landscape); + assert!(reads.has(Read::Theme) && reads.has(Read::Breakpoint) && !reads.has(Read::Landscape)); // In a condition, and applied while a state holds let (condition, reads) = code(Choice::Condition { test: "on".to_string(), @@ -1116,7 +1119,7 @@ fn varied_choices_pick_by_breakpoint_and_theme() { alternate: Box::new(when(State::Landscape(false), Choice::Static(c))), }); assert_eq!(condition, "on ? (b < 1 ? s.a : s.b) : (!l && s.c)"); - assert!(!reads.theme && reads.breakpoint && reads.landscape); + assert!(!reads.has(Read::Theme) && reads.has(Read::Breakpoint) && reads.has(Read::Landscape)); let (nested, _) = code(Choice::Condition { test: "on".to_string(), consequent: Box::new(Choice::Varied(vec![ @@ -1185,6 +1188,78 @@ fn compiles_pressed(#[case] name: &str, #[case] runtime: bool, #[case] code: &st assert_snapshot!(name, compile_themed(two_themes(), runtime, code)); } +#[rstest] +#[case::lengths( + "viewport_lengths", + true, + "export function A() { + return +}" +)] +#[case::responsive( + "viewport_responsive", + true, + "export function A() { + return +}" +)] +#[case::outside_component( + "viewport_outside_component", + true, + "export const a = +export const b = " +)] +#[case::css_and_styled( + "viewport_css_and_styled", + true, + "import { css, styled } from '@devup-ui/react' +export const Tall = styled.View({ h: '50vh' }) +export function A() { + const wide = css({ w: '50vw' }) + return +}" +)] +#[case::focused_input( + "viewport_focused_input", + true, + "export const a = +export function B() { + return +}" +)] +#[case::keyframes( + "viewport_keyframes", + true, + "import { keyframes } from '@devup-ui/react' +const grow = keyframes({ from: { w: '0vw' }, to: { w: '100vw' } })" +)] +#[case::runtime_off( + "viewport_runtime_off", + false, + "export function A() { + return +}" +)] +#[case::motion( + "motion_blocks", + true, + "export function A() { + return +} +export const b = +export function C() { + return +}" +)] +#[case::motion_runtime_off( + "motion_runtime_off", + false, + "export const a = " +)] +fn compiles_viewport_and_motion(#[case] name: &str, #[case] runtime: bool, #[case] code: &str) { + assert_snapshot!(name, compile_themed(two_themes(), runtime, code)); +} + const CSS_ELEMENTS: &str = r"import { css as style, type DevupProps } from '@devup-ui/react' const card = style({ p: 4, borderRadius: '8px' }) export function Card({ on, extra, children }) { diff --git a/libs/extractor/src/native/values.rs b/libs/extractor/src/native/values.rs index 94441044e..76f4a2aa7 100644 --- a/libs/extractor/src/native/values.rs +++ b/libs/extractor/src/native/values.rs @@ -100,14 +100,66 @@ pub(super) fn scaled_length(text: &str) -> Option { }) } +/// What a viewport length measures a hundredth of +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Viewport { + Width, + Height, + /// The smaller of the width and the height + Min, + /// The larger of the width and the height + Max, +} + +/// The viewport units, by what they measure. A window has no browser +/// interface that comes and goes, so the small, large and dynamic units +/// measure the window as the plain ones do; the inline and block axes are +/// the width and the height +const VIEWPORT_UNITS: [(&str, Viewport); 24] = [ + ("vw", Viewport::Width), + ("svw", Viewport::Width), + ("lvw", Viewport::Width), + ("dvw", Viewport::Width), + ("vi", Viewport::Width), + ("vh", Viewport::Height), + ("svh", Viewport::Height), + ("lvh", Viewport::Height), + ("dvh", Viewport::Height), + ("vb", Viewport::Height), + ("vmin", Viewport::Min), + ("svmin", Viewport::Min), + ("lvmin", Viewport::Min), + ("dvmin", Viewport::Min), + ("vmax", Viewport::Max), + ("svmax", Viewport::Max), + ("lvmax", Viewport::Max), + ("dvmax", Viewport::Max), + ("svi", Viewport::Width), + ("lvi", Viewport::Width), + ("dvi", Viewport::Width), + ("svb", Viewport::Height), + ("lvb", Viewport::Height), + ("dvb", Viewport::Height), +]; + +/// The number of hundredths `text` measures and of what, for a viewport +/// length such as `50vw` +pub(super) fn viewport_length(text: &str) -> Option<(f64, Viewport)> { + let text = text.trim(); + VIEWPORT_UNITS.iter().find_map(|(unit, viewport)| { + text.strip_suffix(unit) + .and_then(number) + .map(|amount| (amount, *viewport)) + }) +} + fn unsupported_length(text: &str) -> Problem { - if ["vw", "vh", "vmin", "vmax", "dvh", "svh", "lvh"] - .iter() - .any(|unit| text.ends_with(unit)) - { + if viewport_length(text).is_some() { return Problem::new( - format!("`{text}` needs the window size, which React Native knows only at runtime"), - "use a number of pixels or a percentage", + format!( + "`{text}` is a viewport length, which the build computes only where a style prop writes it" + ), + "write the viewport length in the style prop, or use a number of pixels or a percentage", ); } Problem::new( diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md index fda3842db..8d6afaeac 100644 --- a/packages/metro-plugin/README.md +++ b/packages/metro-plugin/README.md @@ -160,6 +160,40 @@ is in that orientation. A value read at runtime in an array (`p={[x, 2]}`) applies from its breakpoint on as it is. +## Viewport lengths + +`vw`, `vh`, `vmin` and `vmax` measure the window, as on the web. Its small, +large and dynamic forms (`svh`, `dvh`, ...) measure the same, since an app's +window has no browser bar that comes and goes. The build turns each length +into one multiplication of the window's size, which the runtime gives: + +```tsx + +// const __vw = __useWindowWidth(); const __vh = __useWindowHeight(); +// +``` + +A component renders again when the window's size changes only if it uses a +viewport length. Components that read only the breakpoint or the theme +render again only when those change. A viewport length works in responsive +arrays, `css()` and `styled()`. With `runtime: false`, it is a build error. +In a theme token, it is a build error too: write it in the style prop. + +## Reduced motion + +`_motionReduce` applies its styles while the system asks apps to reduce +motion (React Native's `AccessibilityInfo`), and `_motionSafe` applies its +styles while it does not. The runtime asks the system once and follows its +changes: + +```tsx + +``` + ## Press styles `_active` (or its React Native name, `_pressed`) applies its styles while the @@ -347,16 +381,17 @@ Rsbuild or Bun plugin, which output atomic CSS instead. Only styles the build can decide are supported: literals, values read at runtime, theme tokens, responsive values, conditions between them and the -platform, theme, orientation and interaction blocks, `css()`, `styled()` -and animations. These are build errors, reported by Metro at the file, line and column: +platform, theme, orientation, motion and interaction blocks, viewport +lengths, `css()`, `styled()` and animations. These are build errors, reported by Metro at the file, line and column: - selectors other than the states above (`_focusVisible`, `_checked`, `_before`, ...) - `globalCss()` and `Grid` - animations and transitions in an app without react-native-reanimated - any prop React Native has no style for - with `runtime: false`, a value that differs by theme or breakpoint, - `_theme*` with more than one theme, `_portrait`, `_landscape`, and - `useTheme`, `getTheme` and `setTheme` + `_theme*` with more than one theme, `_portrait`, `_landscape`, + `_motionReduce`, `_motionSafe`, viewport lengths, and `useTheme`, + `getTheme` and `setTheme` Metro reads devup.json when it starts, so restart Metro after changing it (`--reset-cache` is not needed). diff --git a/packages/react/src/native/__tests__/index.browser.test.tsx b/packages/react/src/native/__tests__/index.browser.test.tsx index 326169105..9edc0ccf1 100644 --- a/packages/react/src/native/__tests__/index.browser.test.tsx +++ b/packages/react/src/native/__tests__/index.browser.test.tsx @@ -17,7 +17,20 @@ const dimensions = { listeners: [] as (() => void)[], } +/** Whether the system reduces motion, and who listens to it */ +const accessibility = { + listeners: [] as ((reduced: boolean) => void)[], +} + mock.module('react-native', () => ({ + AccessibilityInfo: { + isReduceMotionEnabled: () => Promise.resolve(false), + addEventListener: (event: string, listener: (reduced: boolean) => void) => { + if (event === 'reduceMotionChanged') + accessibility.listeners.push(listener) + return { remove: () => {} } + }, + }, Dimensions: { get: () => ({ width: dimensions.width, height: dimensions.height }), addEventListener: (event: string, listener: () => void) => { @@ -51,6 +64,13 @@ function resize(width: number, height: number) { }) } +/** The system starting or stopping to reduce motion */ +function reduceMotion(reduced: boolean) { + act(() => { + for (const listener of accessibility.listeners) listener(reduced) + }) +} + const runtime = await import('../index') const { defineBreakpoints, @@ -58,11 +78,15 @@ const { getBreakpoint, getTheme, setTheme, + Sized, Themed, useBreakpoint, useLandscape, + useReducedMotion, useTheme, useThemeIndex, + useWindowHeight, + useWindowWidth, } = runtime beforeEach(() => { @@ -223,6 +247,66 @@ describe('useLandscape', () => { }) }) +describe('useReducedMotion', () => { + it('follows whether the system reduces motion', async () => { + const { result } = renderHook(() => useReducedMotion()) + await act(async () => {}) + expect(result.current).toBe(false) + reduceMotion(true) + expect(result.current).toBe(true) + reduceMotion(false) + expect(result.current).toBe(false) + expect(accessibility.listeners).toHaveLength(1) + }) +}) + +describe('useWindowWidth and useWindowHeight', () => { + it('render again with the size of the window', () => { + const { result } = renderHook(() => [useWindowWidth(), useWindowHeight()]) + expect(result.current).toEqual([390, 844]) + resize(400, 800) + expect(result.current).toEqual([400, 800]) + }) + + it('leave the components reading only the breakpoint alone', () => { + let breakpointRenders = 0 + let widthRenders = 0 + renderHook(() => { + breakpointRenders++ + return useBreakpoint() + }) + renderHook(() => { + widthRenders++ + return useWindowWidth() + }) + resize(400, 844) + resize(410, 844) + expect(breakpointRenders).toBe(1) + expect(widthRenders).toBe(3) + }) +}) + +describe('Sized', () => { + it('renders the style of what the runtime tells and of the window size', () => { + const Probe = ({ style }: { style?: string }) => + createElement('span', { 'data-style': style }) + const { container } = render( + createElement(Sized, { + $c: Probe, + $s: (...reads: unknown[]) => reads.join('-'), + }), + ) + const style = () => + container.querySelector('span')?.getAttribute('data-style') + expect(style()).toBe('0-0-false-false-390-844') + resize(844, 390) + expect(style()).toBe('0-2-true-false-844-390') + reduceMotion(true) + expect(style()).toBe('0-2-true-true-844-390') + reduceMotion(false) + }) +}) + describe('Themed with breakpoints', () => { it('renders the style of the breakpoint and orientation of the window', () => { const Probe = ({ style }: { style?: string }) => diff --git a/packages/react/src/native/index.ts b/packages/react/src/native/index.ts index 15f14c045..325b54b77 100644 --- a/packages/react/src/native/index.ts +++ b/packages/react/src/native/index.ts @@ -8,7 +8,7 @@ import { useState, useSyncExternalStore, } from 'react' -import { Appearance, Dimensions } from 'react-native' +import { AccessibilityInfo, Appearance, Dimensions } from 'react-native' import type { StyledTheme } from '../types/props' import type { DevupTheme } from '../types/theme' @@ -18,8 +18,9 @@ import { StyledThemeContext } from '../utils/theme-context' * The React Native runtime of Devup UI. The build compiles every style to * `StyleSheet` objects, one a theme or a breakpoint when a value differs by * them; this module only tells which theme shows, which breakpoint the - * window is at and whether it is in landscape. It reads no CSS, resolves no - * token and computes no style. Web builds never import it. + * window is at, whether it is in landscape, whether the system reduces + * motion and, for viewport lengths, the window's size. It reads no CSS and + * resolves no token. Web builds never import it. */ type ThemeName = keyof DevupTheme extends undefined ? string : keyof DevupTheme @@ -32,35 +33,33 @@ let dark = -1 let chosen: string | null = null /** The window widths the breakpoints start at, as devup.json gives them */ let breakpoints: readonly number[] = [0, 480, 768, 992, 1280, 1600] -/** The breakpoint and orientation listeners last heard of, as one number */ -let layout = -1 +/** Whether the system asks apps to reduce motion */ +let reduced = false let following = false const listeners = new Set<() => void>() +/** + * Tells every listener that something changed. Each hook reads only its own + * value, and React renders a component again only when the value its hook + * reads changes, so a resize that crosses no breakpoint renders again only + * the components reading the window's size. + */ function notify(): void { for (const listener of listeners) listener() } -/** The breakpoint the window is at and whether it is in landscape, as one number */ -function readLayout(): number { - return getBreakpoint() * 2 + Number(getLandscape()) -} - -/** Tells the listeners when the window crosses a breakpoint or turns */ -function resize(): void { - const next = readLayout() - if (next !== layout) { - layout = next - notify() - } +function setReduced(value: boolean): void { + reduced = value + notify() } function subscribe(listener: () => void): () => void { if (!following) { following = true - layout = readLayout() Appearance.addChangeListener(notify) - Dimensions.addEventListener('change', resize) + Dimensions.addEventListener('change', notify) + AccessibilityInfo.addEventListener('reduceMotionChanged', setReduced) + void AccessibilityInfo.isReduceMotionEnabled().then(setReduced) } listeners.add(listener) return () => { @@ -160,32 +159,111 @@ export function useLandscape(): boolean { return useSyncExternalStore(subscribe, getLandscape, getLandscape) } +/** Whether the system asks apps to reduce motion */ +function getReducedMotion(): boolean { + return reduced +} + +/** + * Whether the system asks apps to reduce motion, which `_motionReduce` and + * `_motionSafe` apply by, rendering again when the setting changes + * @internal + */ +export function useReducedMotion(): boolean { + return useSyncExternalStore(subscribe, getReducedMotion, getReducedMotion) +} + +function getWindowWidth(): number { + return Dimensions.get('window').width +} + +function getWindowHeight(): number { + return Dimensions.get('window').height +} + +/** + * The window's width, which a `vw` length is a hundredth of, rendering again + * when it changes + * @internal + */ +export function useWindowWidth(): number { + return useSyncExternalStore(subscribe, getWindowWidth, getWindowWidth) +} + +/** + * The window's height, which a `vh` length is a hundredth of, rendering + * again when it changes + * @internal + */ +export function useWindowHeight(): number { + return useSyncExternalStore(subscribe, getWindowHeight, getWindowHeight) +} + +/** What `Themed` gives the style: what the runtime tells, in this order */ +type Reads = ( + theme: number, + breakpoint: number, + landscape: boolean, + reducedMotion: boolean, +) => unknown + /** * Renders `$c` with the style `$s` gives for the theme the app shows, the - * breakpoint the window is at and whether it is in landscape. The build - * renders an element through it where no function component can read them - * for it. + * breakpoint the window is at, whether it is in landscape and whether the + * system reduces motion. The build renders an element through it where no + * function component can read them for it. * @internal */ export function Themed({ $c, $s, ...props +}: { $c: ElementType; $s: Reads } & Record): ReactElement { + return createElement($c, { + ...props, + style: $s( + useThemeIndex(), + useBreakpoint(), + useLandscape(), + useReducedMotion(), + ), + }) +} + +/** + * `Themed` for an element that also takes a viewport length: its style also + * takes the window's width and height. Only such elements render through it, + * so a resize renders again only them. + * @internal + */ +export function Sized({ + $c, + $s, + ...props }: { $c: ElementType - $s: (theme: number, breakpoint: number, landscape: boolean) => unknown + $s: ( + ...reads: [...Parameters, width: number, height: number] + ) => unknown } & Record): ReactElement { return createElement($c, { ...props, - style: $s(useThemeIndex(), useBreakpoint(), useLandscape()), + style: $s( + useThemeIndex(), + useBreakpoint(), + useLandscape(), + useReducedMotion(), + useWindowWidth(), + useWindowHeight(), + ), }) } /** * Renders `$c`, a `TextInput`, with the style `$s` gives for whether it has * focus, which a `TextInput` tells only through its events, and for the - * theme, the breakpoint and the orientation, as `Themed` does. The build - * renders an input taking a focus style with it. + * theme, the breakpoint, the orientation and reduced motion, as `Themed` + * does. The build renders an input taking a focus style with it. * @internal */ export function Focused({ @@ -196,12 +274,7 @@ export function Focused({ ...props }: { $c: ElementType - $s: ( - focused: boolean, - theme: number, - breakpoint: number, - landscape: boolean, - ) => unknown + $s: (focused: boolean, ...reads: Parameters) => unknown onFocus?: (event: unknown) => void onBlur?: (event: unknown) => void } & Record): ReactElement { @@ -216,7 +289,13 @@ export function Focused({ setFocused(false) onBlur?.(event) }, - style: $s(focused, useThemeIndex(), useBreakpoint(), useLandscape()), + style: $s( + focused, + useThemeIndex(), + useBreakpoint(), + useLandscape(), + useReducedMotion(), + ), }) } From 27976fb9361a61e1305d685704b5d4d5e7f6e40f Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sun, 22 Nov 2026 03:22:06 +0900 Subject: [PATCH 2/2] fix(react): let verify-dist load the native runtime that reads AccessibilityInfo Co-Authored-By: Claude Opus 5.5 --- verify-dist.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/verify-dist.ts b/verify-dist.ts index d2a4f414a..5c0baff9e 100644 --- a/verify-dist.ts +++ b/verify-dist.ts @@ -85,7 +85,7 @@ Bun.plugin({ name: 'react-native-stand-in', setup(build) { build.module('react-native', () => ({ - exports: { Appearance: {}, Dimensions: {} }, + exports: { AccessibilityInfo: {}, Appearance: {}, Dimensions: {} }, loader: 'object', })) },