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/.github/workflows/publish.yml b/.github/workflows/publish.yml index e1017f857..af9dc3598 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -12,6 +12,7 @@ on: - feat/react-native-themes - feat/react-native-responsive - feat/react-native-pressed + - feat/react-native-css # 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/src/Badge.tsx b/apps/expo/src/Badge.tsx index abc21d682..c53b56085 100644 --- a/apps/expo/src/Badge.tsx +++ b/apps/expo/src/Badge.tsx @@ -1,18 +1,16 @@ -import { Text } from '@devup-ui/react' +import { styled, Text } from '@devup-ui/react' + +/** Styled the same in every theme, so it compiles without the runtime */ +const Pill = styled(Text)({ + bg: '#5a44ff', + borderRadius: '999px', + color: '#fff', + fontSize: '12px', + fontWeight: '600', + px: 2, + py: 1, +}) -/** Styles the same in every theme, so it compiles without the runtime */ export function Badge({ label }: { label: string }) { - return ( - - {label} - - ) + return {label} } diff --git a/libs/extractor/src/native/element.rs b/libs/extractor/src/native/element.rs index b38bf526c..f034f8828 100644 --- a/libs/extractor/src/native/element.rs +++ b/libs/extractor/src/native/element.rs @@ -31,6 +31,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 { @@ -177,6 +180,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 +196,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 { @@ -314,6 +320,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, @@ -376,7 +389,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 +405,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 +415,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 +568,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 +579,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 { @@ -1128,6 +1152,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(_) diff --git a/libs/extractor/src/native/element/css_call.rs b/libs/extractor/src/native/element/css_call.rs index b0ff3cdbd..7fc573276 100644 --- a/libs/extractor/src/native/element/css_call.rs +++ b/libs/extractor/src/native/element/css_call.rs @@ -9,6 +9,7 @@ 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}; @@ -154,7 +155,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 +186,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..3f49a70d1 --- /dev/null +++ b/libs/extractor/src/native/element/styled.rs @@ -0,0 +1,242 @@ +//! `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, 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 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 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 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 pressed { + format!( + "({{ pressed: {} }}) => {}", + self.runtime.pressed, style.code + ) + } else { + 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__styled_components.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__styled_components.snap new file mode 100644 index 000000000..1d44afee8 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__styled_components.snap @@ -0,0 +1,76 @@ +--- +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 { View, Animated } from "react-native"; +import { useThemeIndex as __useThemeIndex, useBreakpoint as __useBreakpoint, 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: { borderRadius: 8 }, + b: { backgroundColor: "#fff" }, + c: { backgroundColor: "#1a1a2e" }, + d: { padding: 8 }, + e: { padding: 16 }, + f: { + flexDirection: "row", + gap: 8 + }, + g: { fontSize: 18 }, + h: { opacity: .5 }, + i: { margin: 4 }, + j: { opacity: .6 }, + k: { backgroundColor: "black" } +}); +const __u = (v, s) => { + if (typeof v === "number") return v * s; + const m = typeof v === "string" && /^\s*(-?(?:\d+\.?\d*|\.\d+))(px|r?em)?\s*$/.exec(v); + return m ? Number(m[1]) * (m[2] ? m[2] === "px" ? 1 : 16 : s) : v; +}; +export const Card = (__props) => { + const __t = __useThemeIndex(); + const __b = __useBreakpoint(); + return ; +}; +export const Row = (__props) => { + return ; +}; +export const Title = (__props) => { + return props.color)(__props) }, + __props.style + ]} />; +}; +export const Item = (__props) => { + return props.active && __s.h)(__props), + { width: __u(((p) => p.width)(__props), 4) }, + __props.style + ]} />; +}; +export const Tap = (__props) => { + const __t = __useThemeIndex(); + return <__Pressable {...__props} style={({ pressed: __p }) => [ + __p && __s.j, + [null, __s.k][__t], + __props.style + ]} />; +}; +export const Plain = (__props) => { + return