diff --git a/.changepacks/changepack_log_react_native_focused_runtime.json b/.changepacks/changepack_log_react_native_focused_runtime.json new file mode 100644 index 000000000..49a5b47bc --- /dev/null +++ b/.changepacks/changepack_log_react_native_focused_runtime.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/react/package.json": "Patch" + }, + "note": "`@devup-ui/react/native` adds `Focused` (internal), which renders a `TextInput` with the style the build compiles for whether it has focus, following its `onFocus` and `onBlur` and still calling the ones it is given. The runtime grows from 630 B to 702 B min+gzip.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_react_native_states.json b/.changepacks/changepack_log_react_native_states.json new file mode 100644 index 000000000..ea7449058 --- /dev/null +++ b/.changepacks/changepack_log_react_native_states.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-binding/package.json": "Patch", + "bindings/devup-ui-wasm/package.json": "Patch" + }, + "note": "`codeExtractNative` compiles `_hover`, `_focus` and `_disabled` for React Native (part of #411): `_hover` and `_focus` read the `hovered` and `focused` that `Pressable` gives its style function, an `Input` with `_focus` renders through the runtime's `Focused`, and `_disabled` applies while the element's `disabled` prop is true. In `css()` these and `_active` are build errors. Web output is unchanged.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index af9dc3598..e80a4d24d 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -13,6 +13,7 @@ on: - feat/react-native-responsive - feat/react-native-pressed - feat/react-native-css + - feat/react-native-styled # 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 a7168e173..bc2d2a4c6 100644 --- a/apps/expo/check-bundle.mjs +++ b/apps/expo/check-bundle.mjs @@ -6,16 +6,17 @@ // the breakpoint and the orientation, so it calls each of those hooks of the // runtime; src/Badge.tsx is styled the same in every theme and at every // width, so it must not use the runtime. Its buttons take press styles, which -// React Native's `Pressable` applies through a function for `style`. +// React Native's `Pressable` applies through a function for `style`, and its +// input a focus style, which the runtime's `Focused` applies. import { readdirSync, readFileSync } from 'node:fs' 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)\b/g -/** The hooks src/App.tsx must call */ -const APP_HOOKS = ['useThemeIndex', 'useBreakpoint', 'useLandscape'] + /\b(?:defineThemes|useThemeIndex|useBreakpoint|useLandscape|Focused)\b/g +/** What src/App.tsx must use from the runtime */ +const APP_HOOKS = ['useThemeIndex', 'useBreakpoint', 'useLandscape', 'Focused'] /** Modules of @devup-ui/react, by the path Metro resolves */ const REACT_PACKAGE = /(^|[\\/])(@devup-ui[\\/]react|packages[\\/]react)[\\/]/ /** The React Native runtime among them */ @@ -144,7 +145,7 @@ for (const platform of ['ios', 'android']) { for (const hook of APP_HOOKS) { const callers = [...(users.get(hook) ?? [])] if (!callers.some((source) => /src[\\/]App\.tsx$/.test(source))) { - failures.push(`${platform}/${file}: src/App.tsx does not call ${hook}`) + failures.push(`${platform}/${file}: src/App.tsx does not use ${hook}`) } } const all = [ diff --git a/apps/expo/src/App.tsx b/apps/expo/src/App.tsx index 6d8174a5f..fb764ead4 100644 --- a/apps/expo/src/App.tsx +++ b/apps/expo/src/App.tsx @@ -53,6 +53,7 @@ export function App() { Your name Option { - if !(self.hooks_used.any() || self.wrapper_used || theme_api) { + if !(self.hooks_used.any() || self.wrapper_used || self.focused_used || theme_api) { return None; } let reads = self.hooks_used.union(self.wrapper_reads); @@ -123,6 +140,9 @@ impl Runtime { if self.wrapper_used { specifiers.push(format!("Themed as {}", self.wrapper)); } + if self.focused_used { + specifiers.push(format!("Focused as {}", self.focused_wrapper)); + } let theme = &target.theme; let mut calls = String::new(); if reads.theme || theme_api { @@ -270,6 +290,9 @@ fn classify(name: &str) -> Prop { "_portrait" => Prop::When(State::Landscape(false)), "_landscape" => Prop::When(State::Landscape(true)), "_pressed" | "_active" => Prop::When(State::Pressed), + "_hover" => Prop::When(State::Hovered), + "_focus" => Prop::When(State::Focused), + "_disabled" => Prop::When(State::Disabled), "className" => Prop::ClassName, "typography" => Prop::Declares, "styleOrder" | "styleVars" => Prop::Unsupported(Problem::new( @@ -366,6 +389,11 @@ struct Styles { removed: Vec, /// The `style` prop, which leaves the element with the style props style: Option, + /// The code of the element's `disabled` prop, which `_disabled` reads + disabled: Option, + /// Whether `Focused` renders the element, which tells whether it has + /// focus: a `TextInput` taking a focus style + focus_wrapped: bool, /// The `style` prop's value compiled, which it keeps when the element /// takes no other style kept: Option, @@ -687,8 +715,17 @@ impl<'a> Elements<'_> { } let retagged = tag.is_some(); let press = self.press.take(); - if let Some(press) = press.filter(|_| styles.blocks.iter().any(Choice::pressed)) { - tag = self.pressable(press, kind, local, tag); + let held: Vec = INTERACTIONS + .into_iter() + .filter(|state| styles.blocks.iter().any(|choice| choice.holds(*state))) + .collect(); + if let Some(press) = press.filter(|_| !held.is_empty()) { + if *kind == ExportVariableKind::Input && held == [State::Focused] && tag.is_none() { + // A `TextInput` tells its focus only through its events + styles.focus_wrapped = true; + } else { + tag = self.pressable(press, kind, local, tag); + } } self.finish(element, styles, (tag, local), previous_end); self.children(element, kind, local, retagged); @@ -709,6 +746,12 @@ impl<'a> Elements<'_> { return None; }; let name = name.name.as_str(); + if name == "disabled" { + styles.disabled = Some( + attribute_expression(attribute) + .map_or_else(|| "true".to_string(), |value| self.source(value)), + ); + } if name == "src" && *kind == ExportVariableKind::Image { self.image_source(attribute, local); return None; @@ -914,11 +957,12 @@ impl<'a> Elements<'_> { offset: u32, local: &str, ) -> Vec { - // `Pressable` tells whether it is pressed; only the orientation needs - // the runtime - if state == State::Pressed { + // `Pressable` tells whether it is pressed, hovered or focused, and + // `disabled` whether it is disabled: only the orientation needs the + // runtime + if INTERACTIONS.contains(&state) { self.press.get_or_insert_with(|| (offset, name.to_string())); - } else if !self.target.runtime { + } else if !self.target.runtime && state != State::Disabled { self.error( offset, RuntimeFeature::Orientation.problem().on(local, name), @@ -1207,50 +1251,75 @@ impl<'a> Elements<'_> { style, kept, opaque_spread, + disabled, + focus_wrapped, } = styles; choices.extend(blocks); - let pressed = choices.iter().any(Choice::pressed); - let mut style_code = style_code( - choices, - (classes, given), - &mut self.sheet, - &self.runtime.vars(), - ); + if disabled.is_none() { + // `_disabled` applies only to an element given `disabled` + choices = choices + .into_iter() + .map(|choice| without(choice, State::Disabled)) + .collect(); + } + let disabled = disabled.unwrap_or_default(); + let vars = Vars { + disabled: &disabled, + ..self.runtime.vars() + }; + let keys = interaction_keys(&choices, &vars); + let mut style_code = style_code(choices, (classes, given), &mut self.sheet, &vars); let reads = style_code .as_ref() .map_or_else(Reads::default, |style| style.reads); - if let Some(style) = style_code.as_mut().filter(|_| pressed) { + let focus_wrapped = focus_wrapped && style_code.is_some(); + if let Some(style) = style_code + .as_mut() + .filter(|_| !keys.is_empty() && !focus_wrapped) + { // `Pressable` calls a function for its style with its state - style.code = format!( - "({{ pressed: {} }}) => {}", - self.runtime.pressed, style.code - ); + style.code = format!("({{ {} }}) => {}", keys.join(", "), style.code); } - let wrapped = reads.any() && !self.read_in_component(reads); - if wrapped { - self.runtime.wrapper_used = true; + let in_component = !reads.any() || self.read_in_component(reads); + if !in_component { self.runtime.wrapper_reads = self.runtime.wrapper_reads.union(reads); - let wrapper = self.runtime.wrapper.clone(); - self.rename(element, &wrapper); - } else if let Some(tag) = &tag { - self.rename(element, tag); + } + 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 let Some(name) = wrapper.as_ref().or(tag.as_ref()) { + self.rename(element, name); } let Some(style_code) = style_code else { self.remove(&removed); self.replacements.extend(kept); return; }; - let code = if wrapped { - // The wrapper gives the theme, the breakpoint and the orientation, - // in this order: the style takes them up to the last it reads - let read = self.runtime.variables(reads).last().map_or(0, |(at, _)| at); - let parameters = [ + let code = if wrapper.is_some() { + // `Focused` gives whether the element has focus first; a wrapper + // gives the theme, the breakpoint and the orientation, in this + // order, to an element outside a component: the style takes them + // 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, - ][..=read] - .iter() - .map(|name| name.as_str()) + ]; + let parameters = focus + .into_iter() + .chain( + runtime[..read.filter(|_| !in_component).map_or(0, |at| at + 1)] + .iter() + .map(|name| name.as_str()), + ) .collect::>() .join(", "); format!( @@ -1290,12 +1359,12 @@ impl<'a> Elements<'_> { return Some(self.pressable.clone()); } (_, Some(_)) => Problem::new( - "a press style makes the element React Native's `Pressable`, which cannot render the component `as` gives", + "a press, hover or focus style makes the element React Native's `Pressable`, which cannot render the component `as` gives", "remove `as`, or pass a function reading `pressed` to the `style` of a `Pressable`", ), (native, None) => Problem::new( format!( - "a press style needs React Native's `Pressable`, and the element renders React Native's `{native}`" + "a press, hover or focus style needs React Native's `Pressable`, and the element renders React Native's `{native}`" ), "wrap it in a `Box` or a `Button` with `_pressed`", ), diff --git a/libs/extractor/src/native/element/css_call.rs b/libs/extractor/src/native/element/css_call.rs index 7fc573276..d4b44b7d6 100644 --- a/libs/extractor/src/native/element/css_call.rs +++ b/libs/extractor/src/native/element/css_call.rs @@ -12,7 +12,7 @@ use std::fmt::Write; use super::styled::{gives_style_props, is_function}; use super::{Elements, Prop, Styles, attribute_expression, classify}; use crate::native::errors::Problem; -use crate::native::style::{Choice, combined, style_code}; +use crate::native::style::{Choice, State, combined, style_code}; use crate::native::values::Literal; /// The name `css()` errors call the call by @@ -49,7 +49,7 @@ impl<'a> Elements<'_> { self.error( offset, Problem::new( - "a press style applies while an element is pressed, which `css()` cannot tell", + "a press, hover or focus style applies while the element is in that state, which `css()` cannot tell", format!("give `{name}` to the element"), ) .on(CSS, &name), @@ -67,6 +67,16 @@ impl<'a> Elements<'_> { /// Put the style `choices` describe in place of the `css` at `span` fn css_code(&mut self, span: Span, choices: Vec) { + if choices.iter().any(|choice| choice.holds(State::Disabled)) { + self.error( + span.start, + Problem::new( + "`_disabled` applies while the element is disabled, which `css()` cannot tell", + "give `_disabled` to the element", + ) + .call(CSS), + ); + } let code = style_code( choices, (Vec::new(), Vec::new()), diff --git a/libs/extractor/src/native/element/styled.rs b/libs/extractor/src/native/element/styled.rs index 3f49a70d1..928364873 100644 --- a/libs/extractor/src/native/element/styled.rs +++ b/libs/extractor/src/native/element/styled.rs @@ -8,7 +8,7 @@ use oxc_span::{GetSpan, Span}; use super::{Elements, Frame, HookAt, component_name, defaults}; use crate::component::ExportVariableKind; use crate::native::errors::Problem; -use crate::native::style::{Choice, Reads, style_code}; +use crate::native::style::{Choice, Reads, Vars, interaction_keys, style_code}; /// The name `styled()` errors call the call by const STYLED: &str = "styled()"; @@ -168,7 +168,7 @@ impl<'a> Elements<'_> { self.error( offset, Problem::new( - "a press style needs React Native's `Pressable`, which the build knows only a Devup UI component renders", + "a press, hover or focus style needs React Native's `Pressable`, which the build knows only a Devup UI component renders", "style a `Box` or a `Button`, or pass a function reading `pressed` to the `style` of a `Pressable`", ) .on(STYLED, &name), @@ -177,15 +177,15 @@ impl<'a> Elements<'_> { } (None, _) => tag, }; - let pressed = choices.iter().any(Choice::pressed); let props = self.props.clone(); let given = format!("{props}.style"); - let style = style_code( - choices, - (Vec::new(), vec![given]), - &mut self.sheet, - &self.runtime.vars(), - ); + let disabled = format!("{props}.disabled"); + let vars = Vars { + disabled: &disabled, + ..self.runtime.vars() + }; + let keys = interaction_keys(&choices, &vars); + let style = style_code(choices, (Vec::new(), vec![given]), &mut self.sheet, &vars); let reads = style .as_ref() .map_or_else(Reads::default, |style| style.reads) @@ -196,13 +196,10 @@ impl<'a> Elements<'_> { String::new() }; let style = style.map_or_else(String::new, |style| { - let code = if pressed { - format!( - "({{ pressed: {} }}) => {}", - self.runtime.pressed, style.code - ) - } else { + let code = if keys.is_empty() { style.code + } else { + format!("({{ {} }}) => {}", keys.join(", "), style.code) }; format!(" style={{{code}}}") }); 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 a9c1b400e..ba1792e28 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 @@ -7,7 +7,7 @@ test.tsx:4:22: `css()` cannot compile here on React Native: the build reads only 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 test.tsx:5:55: `css()` cannot use `?` on React Native: a condition in `css()` chooses between objects of styles. Fix: write each branch as an object, or as `null` -test.tsx:6:24: `css()` cannot use `_hover` on React Native: React Native has no selectors, pseudo-elements or media queries. Fix: remove it, or write the style the element takes in every state +test.tsx:6:24: `css()` cannot use `_hover` on React Native: a press, hover or focus style applies while the element is in that state, which `css()` cannot tell. Fix: give `_hover` to the element test.tsx:6:42: `css()` cannot use `[key]` on React Native: the build reads only keys written in a block. Fix: write the key itself test.tsx:7:18: `css` can only be called on React Native: the build compiles each call into styles. Fix: call it where the styles are used test.tsx:8:32: `css()` cannot use `className` on React Native: a block holds only style props. Fix: pass it to the element itself @@ -18,5 +18,5 @@ test.tsx:10:18: `css()` cannot use `padding ${…}px` on React Native: a declara test.tsx:10:18: `css()` cannot use `padding` on React Native: the build reads an interpolation in CSS text only as a whole value. Fix: compute the whole value in the interpolation, such as `${`${size}px`}` test.tsx:10:18: `css()` cannot use `webkitMask` on React Native: React Native has no such style. Fix: remove it, or write a style React Native has test.tsx:12:15: `` cannot use `className` on React Native: React Native has no class names. Fix: pass what `css()` gives, or write the styles as props -test.tsx:12:31: `css()` cannot use `_active` on React Native: a press style applies while an element is pressed, which `css()` cannot tell. Fix: give `_active` to the element +test.tsx:12:31: `css()` cannot use `_active` on React Native: a press, hover or focus style applies while the element is in that state, which `css()` cannot tell. Fix: give `_active` to the element test.tsx:12:91: `` cannot use `className` 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__interaction_errors.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__interaction_errors.snap new file mode 100644 index 000000000..8ca400a42 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__interaction_errors.snap @@ -0,0 +1,10 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, code)" +--- +error: test.tsx:3:18: `css()` cannot compile here on React Native: `_disabled` applies while the element is disabled, which `css()` cannot tell. Fix: give `_disabled` to the element +test.tsx:4:24: `css()` cannot use `_hover` on React Native: a press, hover or focus style applies while the element is in that state, which `css()` cannot tell. Fix: give `_hover` to the element +test.tsx:5:7: `` cannot use `_hover` on React Native: a press, hover or focus style needs React Native's `Pressable`, and the element renders React Native's `Text`. Fix: wrap it in a `Box` or a `Button` with `_pressed` +test.tsx:6:15: `` cannot use `_focus` on React Native: a press, hover or focus style makes the element React Native's `Pressable`, which cannot render the component `as` gives. Fix: remove `as`, or pass a function reading `pressed` to the `style` of a `Pressable` +test.tsx:7:8: `` cannot use `_hover` on React Native: a press, hover or focus style needs React Native's `Pressable`, and the element renders React Native's `TextInput`. Fix: wrap it in a `Box` or a `Button` with `_pressed` +test.tsx:8:14: `` cannot use `_before` on React Native: React Native has no selectors, pseudo-elements or media queries. Fix: remove it, or write the style the element takes in every state diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__interaction_states.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__interaction_states.snap new file mode 100644 index 000000000..e5b7adfb7 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__interaction_states.snap @@ -0,0 +1,43 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, 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 { useThemeIndex as __useThemeIndex, Focused as __Focused, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { Pressable as __Pressable } from "react-native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { backgroundColor: "#5a44ff" }, + b: { backgroundColor: "#8c7bff" }, + c: { opacity: .9 }, + d: { borderColor: "blue" }, + e: { opacity: .4 }, + f: { opacity: .7 }, + g: { backgroundColor: "red" }, + h: { borderColor: "#5a44ff" }, + i: { borderColor: "#8c7bff" }, + j: { borderColor: "red" }, + k: { opacity: .5 }, + l: { padding: 4 }, + m: { padding: 8 }, + n: { margin: 4 } +}); +export function Form({ busy, go, value }) { + const __t = __useThemeIndex(); + return +