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/.changepacks/changepack_log_react_native_styled.json b/.changepacks/changepack_log_react_native_styled.json
new file mode 100644
index 000000000..f07bf4032
--- /dev/null
+++ b/.changepacks/changepack_log_react_native_styled.json
@@ -0,0 +1,8 @@
+{
+ "changes": {
+ "bindings/devup-ui-binding/package.json": "Patch",
+ "bindings/devup-ui-wasm/package.json": "Patch"
+ },
+ "note": "`codeExtractNative` compiles `styled()` for React Native (part of #411): `styled(Target)(...parts)`, `` styled(Target)`css text` `` and `styled(Target, styles)` compile to a function component rendering its target with the styles it describes, before the `style` it is given. It takes the parts `css()` takes; a function in them is called with the component's props, as a value or as a part giving what `css()` gives. A Devup UI target keeps the styles it declares first, and a styled `Box` with a press style becomes a `Pressable`. The hooks its styles read are called in the component. Web output is unchanged.",
+ "date": "2026-11-21T00:00:00.000Z"
+}
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
- {label}
-
- )
+ return {label}
}
diff --git a/libs/extractor/src/native/element.rs b/libs/extractor/src/native/element.rs
index a8132671c..0640a2e5c 100644
--- a/libs/extractor/src/native/element.rs
+++ b/libs/extractor/src/native/element.rs
@@ -23,7 +23,10 @@ use super::errors::{Problem, RuntimeFeature};
use super::imports::{self, native_component};
use super::props::{Declaration, Tokens, declarations, dynamic_keys, literal_levels};
use super::sheet::Sheet;
-use super::style::{Choice, Reads, State, Vars, cascade, in_theme, style_code, varied, when};
+use super::style::{
+ Choice, INTERACTIONS, Reads, State, Vars, cascade, in_theme, interaction_keys, style_code,
+ varied, when, without,
+};
use super::theme::{DEFAULT_BREAKPOINTS, selector_theme};
use super::values::{Literal, NativeValue};
use super::{NativePlatform, NativeTarget, REACT_NATIVE, RUNTIME, Replacement};
@@ -31,6 +34,9 @@ use crate::component::ExportVariableKind;
use crate::fresh_name::fresh_name;
mod css_call;
+mod styled;
+
+use styled::is_function;
/// The changes compiling a file makes, or why it cannot compile
pub(super) struct Compiled {
@@ -50,6 +56,13 @@ struct Runtime {
/// The variable holding whether the element is pressed, in the function
/// `Pressable` calls for its style
pressed: String,
+ /// The variables holding whether the pointer is over the element and
+ /// whether it has focus
+ hovered: String,
+ focused: String,
+ /// The component telling a `TextInput` whether it has focus
+ focused_wrapper: String,
+ focused_used: bool,
/// The hooks reading each, by what they read
hooks: [String; 3],
/// What the hooks the file calls read
@@ -77,6 +90,10 @@ impl Runtime {
breakpoint: fresh_name("__b", code),
landscape: fresh_name("__l", code),
pressed: fresh_name("__p", code),
+ hovered: fresh_name("__h", code),
+ focused: fresh_name("__f", code),
+ focused_wrapper: fresh_name("__Focused", code),
+ focused_used: false,
hooks: HOOKS.map(|hook| fresh_name(&format!("__{hook}"), code)),
hooks_used: Reads::default(),
wrapper: fresh_name("__Themed", code),
@@ -94,6 +111,9 @@ impl Runtime {
breakpoint: &self.breakpoint,
landscape: &self.landscape,
pressed: &self.pressed,
+ hovered: &self.hovered,
+ focused: &self.focused,
+ disabled: "false",
}
}
@@ -109,7 +129,7 @@ impl Runtime {
/// 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 || 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);
@@ -120,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 {
@@ -177,6 +200,9 @@ pub(super) fn compile(
scoping,
components: &imports.components,
css: &imports.css,
+ styled: &imports.styled,
+ props: fresh_name("__props", code),
+ in_styled: false,
sheet: Sheet::new(fresh_name("__s", code)),
units: fresh_name("__u", code),
units_used: Cell::new(false),
@@ -190,7 +216,7 @@ pub(super) fn compile(
replacements: imports.replacements,
errors: imports.errors,
};
- if !visitor.components.is_empty() || !visitor.css.is_empty() {
+ if !visitor.components.is_empty() || !visitor.css.is_empty() || !visitor.styled.is_empty() {
visitor.visit_program(program);
}
let Elements {
@@ -264,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(
@@ -314,6 +343,13 @@ struct Elements<'s> {
components: &'s FxHashMap,
/// The bindings of `css`
css: &'s FxHashSet,
+ /// The bindings of `styled`
+ styled: &'s FxHashSet,
+ /// The parameter holding the props of a component `styled()` gives
+ props: String,
+ /// Whether the styles of a `styled()` component are being read, where a
+ /// function is called with its props
+ in_styled: bool,
sheet: Sheet,
/// The name of the function converting values read at runtime
units: String,
@@ -353,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,
@@ -376,7 +417,7 @@ impl<'a> Visit<'a> for Elements<'_> {
"`{local}` can only be rendered as a JSX element on React Native: the build compiles its props into styles only there. Fix: render `<{local} />`, or use a React Native component here"
),
));
- } else if self.is_css_reference(identifier) {
+ } else if self.is_css_reference(identifier) || self.is_styled_reference(identifier) {
self.errors.push((
identifier.span.start,
format!(
@@ -392,6 +433,8 @@ impl<'a> Visit<'a> for Elements<'_> {
fn visit_tagged_template_expression(&mut self, template: &TaggedTemplateExpression<'a>) {
if self.is_css(&template.tag) {
self.css_template(template);
+ } else if let Some(target) = self.styled_target(&template.tag) {
+ self.styled_template(template, target);
} else {
walk::walk_tagged_template_expression(self, template);
}
@@ -400,6 +443,10 @@ impl<'a> Visit<'a> for Elements<'_> {
fn visit_call_expression(&mut self, call: &CallExpression<'a>) {
if self.is_css(&call.callee) {
self.css_call(call);
+ } else if let Some(target) = self.styled_target(&call.callee) {
+ self.styled_call(call, target);
+ } else if self.is_styled(&call.callee) {
+ self.styled_direct(call);
} else {
walk::walk_call_expression(self, call);
}
@@ -549,13 +596,7 @@ impl<'a> Elements<'_> {
/// Call the hooks reading what `reads` names at `at`
fn call_hooks(&mut self, at: HookAt, reads: Reads) {
- self.runtime.hooks_used = self.runtime.hooks_used.union(reads);
- let calls: Vec = self
- .runtime
- .variables(reads)
- .map(|(hook, variable)| format!("const {variable} = {}();", self.runtime.hooks[hook]))
- .collect();
- let call = calls.join(" ");
+ let call = self.hook_calls(reads);
match at {
HookAt::Body(at) => self.replacements.push((at, at, format!("\n{call}"))),
HookAt::Expression(start, end) => {
@@ -566,6 +607,17 @@ impl<'a> Elements<'_> {
}
}
+ /// The statements calling the hooks reading what `reads` names
+ fn hook_calls(&mut self, reads: Reads) -> String {
+ self.runtime.hooks_used = self.runtime.hooks_used.union(reads);
+ let calls: Vec = self
+ .runtime
+ .variables(reads)
+ .map(|(hook, variable)| format!("const {variable} = {}();", self.runtime.hooks[hook]))
+ .collect();
+ calls.join(" ")
+ }
+
/// Whether the element being compiled is in a function component or a
/// hook, which then calls the hooks reading what `reads` names first
fn read_in_component(&mut self, reads: Reads) -> bool {
@@ -663,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);
@@ -685,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;
@@ -890,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),
@@ -1128,6 +1196,10 @@ impl<'a> Elements<'_> {
/// The code of `expression`
fn source(&self, expression: &Expression<'_>) -> String {
let code = expression.span().source_text(self.code);
+ if self.in_styled && is_function(expression) {
+ // A function in the styles of a `styled()` component takes its props
+ return format!("({code})({})", self.props);
+ }
if matches!(
expression.without_parentheses(),
Expression::SequenceExpression(_)
@@ -1179,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!(
@@ -1262,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 b0ff3cdbd..d4b44b7d6 100644
--- a/libs/extractor/src/native/element/css_call.rs
+++ b/libs/extractor/src/native/element/css_call.rs
@@ -9,9 +9,10 @@ use oxc_ast_visit::Visit;
use oxc_span::{GetSpan, Span};
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
@@ -48,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),
@@ -66,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()),
@@ -154,7 +165,7 @@ impl<'a> Elements<'_> {
/// One argument of `css()`: an object of styles, a condition choosing
/// objects, or a style it passes on whole, such as what another `css()`
/// gives
- fn css_part(&mut self, expression: &Expression<'a>, choices: &mut Vec) {
+ pub(super) fn css_part(&mut self, expression: &Expression<'a>, choices: &mut Vec) {
match expression.without_parentheses() {
Expression::ObjectExpression(object) => {
let object_choices = self.object_choices(object, CSS);
@@ -185,6 +196,21 @@ impl<'a> Elements<'_> {
self.error(expression.span().start, class_problem(CSS, "a part"));
}
expression if is_nothing(expression) => {}
+ expression if self.in_styled && is_function(expression) => {
+ if gives_style_props(expression) {
+ self.error(
+ expression.span().start,
+ Problem::new(
+ "a function of the props gives style props, which React Native cannot read at runtime",
+ "return what `css()` gives, or write each value as a function of the props",
+ )
+ .call("styled()"),
+ );
+ return;
+ }
+ let code = format!("({})({})", self.rewritten(expression), self.props);
+ choices.push(Choice::Given(code));
+ }
expression => {
let code = self.rewritten(expression);
choices.push(Choice::Given(code));
diff --git a/libs/extractor/src/native/element/styled.rs b/libs/extractor/src/native/element/styled.rs
new file mode 100644
index 000000000..928364873
--- /dev/null
+++ b/libs/extractor/src/native/element/styled.rs
@@ -0,0 +1,239 @@
+//! `styled()` on React Native: a call compiles to a function component that
+//! renders its target with the styles it describes, before the `style` it is
+//! given.
+
+use oxc_ast::ast::{CallExpression, Expression, IdentifierReference, TaggedTemplateExpression};
+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, Vars, interaction_keys, style_code};
+
+/// The name `styled()` errors call the call by
+const STYLED: &str = "styled()";
+
+/// What a `styled()` component renders
+pub(super) enum Target {
+ /// A Devup UI component, which renders its React Native component with
+ /// the styles it declares first
+ Devup(ExportVariableKind, String),
+ /// Any other component, by its code
+ Other(String),
+}
+
+impl<'a> Elements<'_> {
+ /// Whether `callee` reads the `styled` the file imports
+ pub(super) fn is_styled(&self, callee: &Expression<'_>) -> bool {
+ match callee.without_parentheses() {
+ Expression::Identifier(identifier) => self.is_styled_reference(identifier),
+ _ => false,
+ }
+ }
+
+ /// Whether `identifier` reads the `styled` the file imports
+ pub(super) fn is_styled_reference(&self, identifier: &IdentifierReference<'_>) -> bool {
+ identifier
+ .reference_id
+ .get()
+ .and_then(|reference| self.scoping.get_reference(reference).symbol_id())
+ .is_some_and(|symbol| self.styled.contains(&symbol))
+ }
+
+ /// The target of `callee` when it is `styled(Target)`, whose call or
+ /// tagged template gives the styles
+ pub(super) fn styled_target(&mut self, callee: &Expression<'a>) -> Option {
+ let Expression::CallExpression(call) = callee.without_parentheses() else {
+ return None;
+ };
+ if !self.is_styled(&call.callee) || call.arguments.len() != 1 {
+ return None;
+ }
+ let target = call.arguments[0].as_expression()?;
+ Some(self.target(target))
+ }
+
+ /// The target `expression` names
+ fn target(&mut self, expression: &Expression<'a>) -> Target {
+ if let Expression::Identifier(identifier) = expression.without_parentheses()
+ && let Some((kind, local)) = self.binding(identifier)
+ {
+ return Target::Devup(kind, local);
+ }
+ let code = expression.span().source_text(self.code).to_string();
+ if !component_name(expression.without_parentheses()) {
+ self.error(
+ expression.span().start,
+ Problem::new(
+ "a `styled()` component on React Native renders a component, not a tag",
+ "pass a Devup UI or React Native component, such as `styled(View)`",
+ )
+ .call(STYLED),
+ );
+ }
+ Target::Other(code)
+ }
+
+ /// `styled(Target)(...styles)`
+ pub(super) fn styled_call(&mut self, call: &CallExpression<'a>, target: Target) {
+ let arguments: Vec<&Expression<'a>> = call
+ .arguments
+ .iter()
+ .filter_map(|argument| argument.as_expression())
+ .collect();
+ if arguments.len() < call.arguments.len() {
+ self.error(
+ call.span.start,
+ Problem::new(
+ "the build reads only the styles written in the call",
+ "pass each part to `styled()` itself",
+ )
+ .call(STYLED),
+ );
+ }
+ self.styled_component(call.span, target, |visitor, choices| {
+ for argument in arguments {
+ visitor.css_part(argument, choices);
+ }
+ });
+ }
+
+ /// `` styled(Target)`css text` ``
+ pub(super) fn styled_template(
+ &mut self,
+ template: &TaggedTemplateExpression<'a>,
+ target: Target,
+ ) {
+ self.styled_component(template.span, target, |visitor, choices| {
+ let text = visitor.css_text(&template.quasi, template.span.start);
+ choices.extend(text);
+ });
+ }
+
+ /// `styled(Target, styles)`, or `styled(Target)` alone, which gives no
+ /// component until it is called with styles
+ pub(super) fn styled_direct(&mut self, call: &CallExpression<'a>) {
+ let parts = match call.arguments.as_slice() {
+ [target, styles] => target.as_expression().zip(styles.as_expression()),
+ _ => None,
+ };
+ let Some((target, styles)) = parts else {
+ self.error(
+ call.span.start,
+ Problem::new(
+ "the build compiles `styled()` called with a component and its styles",
+ "write `styled(Target)({ ... })`, `` styled(Target)`...` `` or `styled(Target, { ... })`",
+ )
+ .call(STYLED),
+ );
+ return;
+ };
+ let target = self.target(target);
+ self.styled_component(call.span, target, |visitor, choices| {
+ visitor.css_part(styles, choices);
+ });
+ }
+
+ /// Put the component rendering `target` with the styles `read` reads in
+ /// place of the `styled()` at `span`
+ fn styled_component(
+ &mut self,
+ span: Span,
+ target: Target,
+ read: impl FnOnce(&mut Self, &mut Vec),
+ ) {
+ let (tag, mut choices) = match &target {
+ Target::Devup(kind, local) => (local.clone(), defaults(kind)),
+ Target::Other(code) => (code.clone(), Vec::new()),
+ };
+ // The component calls the hooks its styles read, as a function
+ // component does
+ self.frames.push(Frame {
+ component: true,
+ reads: Reads::default(),
+ hook_at: HookAt::Body(span.start as usize),
+ });
+ let outer = std::mem::replace(&mut self.in_styled, true);
+ read(self, &mut choices);
+ self.in_styled = outer;
+ let frame_reads = self
+ .frames
+ .pop()
+ .map_or_else(Reads::default, |frame| frame.reads);
+ let tag = match (self.press.take(), &target) {
+ (Some(press), Target::Devup(kind, _)) => {
+ self.pressable(press, kind, "styled()", None).unwrap_or(tag)
+ }
+ (Some((offset, name)), Target::Other(_)) => {
+ self.error(
+ offset,
+ Problem::new(
+ "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),
+ );
+ tag
+ }
+ (None, _) => tag,
+ };
+ let props = self.props.clone();
+ let given = format!("{props}.style");
+ 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)
+ .union(frame_reads);
+ let hooks = if reads.any() {
+ format!("{} ", self.hook_calls(reads))
+ } else {
+ String::new()
+ };
+ let style = style.map_or_else(String::new, |style| {
+ let code = if keys.is_empty() {
+ style.code
+ } else {
+ format!("({{ {} }}) => {}", keys.join(", "), style.code)
+ };
+ format!(" style={{{code}}}")
+ });
+ let code = format!("({props}) => {{ {hooks}return <{tag} {{...{props}}}{style} />; }}");
+ self.replacements
+ .push((span.start as usize, span.end as usize, code));
+ }
+}
+
+/// Whether `expression` is a function, which a `styled()` component calls
+/// with its props
+pub(super) fn is_function(expression: &Expression<'_>) -> bool {
+ matches!(
+ expression.without_parentheses(),
+ Expression::ArrowFunctionExpression(_) | Expression::FunctionExpression(_)
+ )
+}
+
+/// Whether the function `expression` gives an object of style props, which
+/// React Native cannot read: an object, or a condition choosing one
+pub(super) fn gives_style_props(expression: &Expression<'_>) -> bool {
+ let Expression::ArrowFunctionExpression(arrow) = expression.without_parentheses() else {
+ return false;
+ };
+ arrow.get_expression().is_some_and(holds_object)
+}
+
+fn holds_object(expression: &Expression<'_>) -> bool {
+ match expression.without_parentheses() {
+ Expression::ObjectExpression(_) => true,
+ Expression::ConditionalExpression(condition) => {
+ holds_object(&condition.consequent) || holds_object(&condition.alternate)
+ }
+ Expression::LogicalExpression(logical) => holds_object(&logical.right),
+ _ => false,
+ }
+}
diff --git a/libs/extractor/src/native/imports.rs b/libs/extractor/src/native/imports.rs
index cae451be3..4e4cf2c19 100644
--- a/libs/extractor/src/native/imports.rs
+++ b/libs/extractor/src/native/imports.rs
@@ -23,6 +23,8 @@ pub(super) struct Imports {
pub components: FxHashMap,
/// The bindings of `css`, whose calls compile to style objects
pub css: FxHashSet,
+ /// The bindings of `styled`, whose calls compile to components
+ pub styled: FxHashSet,
pub replacements: Vec,
pub errors: Vec<(u32, String)>,
/// Whether the file imports the theme API of the runtime
@@ -73,10 +75,6 @@ fn unsupported(name: &str, target: &NativeTarget) -> Option {
"React Native has no grid layout",
"lay the items out with `Flex` and `flexWrap`",
)),
- "styled" => Some(Problem::new(
- "`styled` is not compiled for React Native yet",
- "write the styles as props of a Devup UI component",
- )),
name if is_theme_api(name) => (!target.runtime).then(|| theme_api(name)),
"ThemeScript" | "initTheme" | "globalCss" => Some(Problem::new(
"React Native has no document and no global stylesheet",
@@ -188,8 +186,13 @@ impl Imports {
return Destination::Kept;
}
let local = specifier.local.name.to_string();
- if name == "css" {
- self.css.extend(specifier.local.symbol_id.get());
+ if name == "css" || name == "styled" {
+ let bindings = if name == "css" {
+ &mut self.css
+ } else {
+ &mut self.styled
+ };
+ bindings.extend(specifier.local.symbol_id.get());
return Destination::Dropped;
}
if is_theme_api(&name) {
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__apis.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__apis.snap
index ef9f8356a..76b3f8ba3 100644
--- a/libs/extractor/src/native/snapshots/extractor__native__tests__apis.snap
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__apis.snap
@@ -2,8 +2,7 @@
source: libs/extractor/src/native/tests.rs
expression: "compile_for(NativePlatform::Ios, false, code)"
---
-error: test.tsx:1:15: `styled` from `@devup-ui/react` cannot be used on React Native: `styled` is not compiled for React Native yet. Fix: write the styles as props of a Devup UI component
-test.tsx:1:23: `globalCss` from `@devup-ui/react` cannot be used on React Native: React Native has no document and no global stylesheet. Fix: remove it from the React Native build
+error: test.tsx:1:23: `globalCss` from `@devup-ui/react` cannot be used on React Native: React Native has no document and no global stylesheet. Fix: remove it from the React Native build
test.tsx:1:34: `ThemeScript` from `@devup-ui/react` cannot be used on React Native: React Native has no document and no global stylesheet. Fix: remove it from the React Native build
test.tsx:1:47: `initTheme` from `@devup-ui/react` cannot be used on React Native: React Native has no document and no global stylesheet. Fix: remove it from the React Native build
test.tsx:1:58: `keyframes` from `@devup-ui/react` cannot be used on React Native: animations need react-native-reanimated, which is not supported yet. Fix: animate with React Native's `Animated` or react-native-reanimated directly
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
+ ;
+}
+export const outside = <__Focused $c={Input} $s={(__f, __t, __b) => [__f && [__s.a, __s.b][__t], __f && (__b < 1 ? __s.l : __s.m)]} />;
+export const plain = <__Focused $c={Input} $s={(__f) => __f && __s.n} />;
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__interaction_styled.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__interaction_styled.snap
new file mode 100644
index 000000000..bf9c13d2a
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__interaction_styled.snap
@@ -0,0 +1,17 @@
+---
+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 { StyleSheet } from "react-native";
+const __s = StyleSheet.create({
+ a: { margin: 4 },
+ b: { opacity: .5 }
+});
+export const A = (__props) => {
+ return