From 7ab44df26bbc64de6b72ca9c57aa56c11845dfbd Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 15:18:37 +0900 Subject: [PATCH 1/3] feat(native): compile styled-components/native and @emotion/native Their `styled` (with `styled.View` and any other `styled.Name`) and `css` compile as Devup UI's, with numbers as pixels as those packages read them. Function parts get `props.theme` from the runtime's new `ThemeProvider`, and `ThemeProvider`, `useTheme` and `withTheme` import from the React Native runtime, sharing the web compat theme context. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_react_native_compat.json | 8 + ...epack_log_react_native_compat_runtime.json | 7 + .github/workflows/publish.yml | 1 + apps/expo/check-bundle.mjs | 7 +- libs/extractor/src/native/element.rs | 73 +++- .../extractor/src/native/element/animation.rs | 38 ++- libs/extractor/src/native/element/css_call.rs | 10 +- libs/extractor/src/native/element/styled.rs | 120 +++++-- libs/extractor/src/native/errors.rs | 11 + libs/extractor/src/native/imports.rs | 77 ++++- libs/extractor/src/native/mod.rs | 6 +- ...xtractor__native__tests__compat_alone.snap | 6 + ...ractor__native__tests__compat_emotion.snap | 72 ++++ ...or__native__tests__compat_runtime_off.snap | 8 + ...tive__tests__compat_styled_components.snap | 60 ++++ libs/extractor/src/native/tests.rs | 57 ++++ packages/metro-plugin/README.md | 312 ++++++++++++++++++ .../native/__tests__/index.browser.test.tsx | 50 +++ packages/react/src/native/index.ts | 38 +++ 19 files changed, 919 insertions(+), 42 deletions(-) create mode 100644 .changepacks/changepack_log_react_native_compat.json create mode 100644 .changepacks/changepack_log_react_native_compat_runtime.json create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__compat_alone.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__compat_emotion.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__compat_runtime_off.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__compat_styled_components.snap diff --git a/.changepacks/changepack_log_react_native_compat.json b/.changepacks/changepack_log_react_native_compat.json new file mode 100644 index 000000000..f2887fe65 --- /dev/null +++ b/.changepacks/changepack_log_react_native_compat.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-binding/package.json": "Patch", + "bindings/devup-ui-wasm/package.json": "Patch" + }, + "note": "`codeExtractNative` compiles `styled-components/native` and `@emotion/native` (part of #411): their `styled` (including `styled.View` and any other `styled.Name`) and `css` compile as Devup UI's with numbers as pixels, function parts receive `props.theme` from the runtime's `ThemeProvider`, and `ThemeProvider`, `useTheme` and `withTheme` import from the React Native runtime. Web output is unchanged.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_react_native_compat_runtime.json b/.changepacks/changepack_log_react_native_compat_runtime.json new file mode 100644 index 000000000..93731b2f3 --- /dev/null +++ b/.changepacks/changepack_log_react_native_compat_runtime.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/react/package.json": "Patch" + }, + "note": "`@devup-ui/react/native` adds `ThemeProvider`, `useStyledTheme` and `withTheme`, the theme context the build imports for styled-components and Emotion on React Native. They share the context and `withTheme` of the web compat entry. The runtime grows from 702 B to 1,185 B min+gzip.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 577868727..9ae22ef70 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -15,6 +15,7 @@ on: - feat/react-native-css - feat/react-native-styled - feat/react-native-states + - feat/react-native-animations # 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 cffba661e..81297af7a 100644 --- a/apps/expo/check-bundle.mjs +++ b/apps/expo/check-bundle.mjs @@ -20,9 +20,12 @@ const RUNTIME_NAMES = 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 */ +/** + * The React Native runtime among them, with the theme context of + * styled-components and Emotion it shares with the web build + */ const NATIVE_RUNTIME = - /(^|[\\/])(@devup-ui[\\/]react|packages[\\/]react)[\\/]dist[\\/]native[\\/]/ + /(^|[\\/])(@devup-ui[\\/]react|packages[\\/]react)[\\/]dist[\\/](native[\\/]|utils[\\/](theme-context|with-theme)\.)/ const root = join(import.meta.dirname, 'dist', '_expo', 'static', 'js') const failures = [] diff --git a/libs/extractor/src/native/element.rs b/libs/extractor/src/native/element.rs index 0c32f967c..a938dbb9e 100644 --- a/libs/extractor/src/native/element.rs +++ b/libs/extractor/src/native/element.rs @@ -28,9 +28,10 @@ use super::style::{ varied, when, without, }; use super::theme::{DEFAULT_BREAKPOINTS, selector_theme}; -use super::values::{Literal, NativeValue, ROOT_FONT_SIZE}; +use super::values::{Literal, NativeValue, ROOT_FONT_SIZE, TIMED, number_code}; use super::{NativePlatform, NativeTarget, REACT_NATIVE, RUNTIME, Replacement}; use crate::component::ExportVariableKind; +use crate::extract_style::constant::is_maintain_value_property; use crate::fresh_name::fresh_name; mod animation; @@ -66,6 +67,9 @@ struct Runtime { /// The component telling a `TextInput` whether it has focus focused_wrapper: String, focused_used: bool, + /// The hook giving the theme of a compat `ThemeProvider` + styled_theme: String, + styled_theme_used: bool, /// The hooks reading each, by what they read hooks: [String; 3], /// What the hooks the file calls read @@ -97,6 +101,8 @@ impl Runtime { focused: fresh_name("__f", code), focused_wrapper: fresh_name("__Focused", code), focused_used: false, + styled_theme: fresh_name("__useStyledTheme", code), + styled_theme_used: false, hooks: HOOKS.map(|hook| fresh_name(&format!("__{hook}"), code)), hooks_used: Reads::default(), wrapper: fresh_name("__Themed", code), @@ -132,7 +138,12 @@ 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 || self.focused_used || theme_api) { + if !(self.hooks_used.any() + || self.wrapper_used + || self.focused_used + || self.styled_theme_used + || theme_api) + { return None; } let reads = self.hooks_used.union(self.wrapper_reads); @@ -143,6 +154,9 @@ impl Runtime { if self.wrapper_used { specifiers.push(format!("Themed as {}", self.wrapper)); } + if self.styled_theme_used { + specifiers.push(format!("useStyledTheme as {}", self.styled_theme)); + } if self.focused_used { specifiers.push(format!("Focused as {}", self.focused_wrapper)); } @@ -204,6 +218,10 @@ pub(super) fn compile( components: &imports.components, css: &imports.css, styled: &imports.styled, + compat_bindings: &imports.compat, + compat: false, + props_called: Cell::new(false), + natives: Vec::new(), keyframes: &imports.keyframes, animation: None, animated: Animated::new(code), @@ -237,6 +255,7 @@ pub(super) fn compile( pressable_used, runtime, animated, + natives, mut replacements, errors, .. @@ -250,6 +269,17 @@ pub(super) fn compile( "import {{ Pressable as {pressable} }} from \"{REACT_NATIVE}\";" ); } + if !natives.is_empty() { + let specifiers: Vec = natives + .iter() + .map(|(name, local)| format!("{name} as {local}")) + .collect(); + let _ = writeln!( + prelude, + "import {{ {} }} from \"{REACT_NATIVE}\";", + specifiers.join(", ") + ); + } prelude.push_str(&animated.prelude()); if !sheet.is_empty() { prelude.push_str(&sheet_prelude(&sheet, code)); @@ -357,6 +387,17 @@ struct Elements<'s> { css: &'s FxHashSet, /// The bindings of `styled` styled: &'s FxHashSet, + /// The bindings of `styled` and `css` imported from a compat package + compat_bindings: &'s FxHashSet, + /// Whether the styles read are a compat package's, whose numbers are + /// pixels as React Native reads them + compat: bool, + /// Whether a function was called with `props`, the props of the + /// `styled()` component being read + props_called: Cell, + /// The React Native components `styled.Name` renders: each name and the + /// local name it is imported under + natives: Vec<(String, String)>, /// The bindings of `keyframes` keyframes: &'s FxHashSet, /// The offset and the name of the first animation or transition of the @@ -657,6 +698,14 @@ impl<'a> Elements<'_> { /// breakpoint it is paired with on: one style object, or one a /// breakpoint and a theme where the styles differ by them fn static_choice(&self, name: &str, items: &[(usize, Literal)]) -> Result { + let pixels; + let items = if self.compat { + // A number of a compat package is pixels, as React Native reads it + pixels = in_pixels(name, items); + &pixels + } else { + items + }; let theme = &self.target.theme; let themes = match self.theme_scope { Some(index) => index..index + 1, @@ -1218,6 +1267,8 @@ impl<'a> Elements<'_> { /// `code`, converted at runtime when its numbers take `scale` fn converted(&self, code: &str, scale: Option) -> String { + // A number of a compat package is pixels, as React Native reads it + let scale = scale.map(|scale| if self.compat { 1 } else { scale }); scale.map_or_else( || code.to_string(), |scale| { @@ -1232,6 +1283,7 @@ impl<'a> Elements<'_> { 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 + self.props_called.set(true); return format!("({code})({})", self.props); } if matches!( @@ -1585,3 +1637,20 @@ fn text_child(child: &JSXChild<'_>) -> Option { _ => None, } } + +/// `items`, the literals of the style prop `name`, with each number of a +/// length as pixels, as styled-components and Emotion read it +fn in_pixels(name: &str, items: &[(usize, Literal)]) -> Vec<(usize, Literal)> { + let unitless = css::disassemble_property(name).into_iter().any(|property| { + is_maintain_value_property(&property) || TIMED.contains(&property.as_ref()) + }); + items + .iter() + .map(|(level, literal)| match literal { + Literal::Number(number) if !unitless => { + (*level, Literal::Text(format!("{}px", number_code(*number)))) + } + literal => (*level, literal.clone()), + }) + .collect() +} diff --git a/libs/extractor/src/native/element/animation.rs b/libs/extractor/src/native/element/animation.rs index 79a44ff5c..cff658c58 100644 --- a/libs/extractor/src/native/element/animation.rs +++ b/libs/extractor/src/native/element/animation.rs @@ -97,9 +97,28 @@ impl<'a> Elements<'_> { tag: Option, interactive: bool, ) -> Option { - if !self.reanimated(animation, on) { + if tag.is_some() && !interactive { + // The component `as` gives animates when it is animated + self.reanimated(animation, on); return tag; } + self.animated_native(animation, (native_component(kind), local), on, interactive) + .or(tag) + } + + /// Reanimated's animated component of the React Native component + /// `native`, which `local` is bound to, for an element taking an + /// animation + pub(super) fn animated_native( + &mut self, + animation: &(u32, String), + (native, local): (&str, &str), + on: &str, + interactive: bool, + ) -> Option { + if !self.reanimated(animation, on) { + return None; + } if interactive { self.error( animation.0, @@ -109,24 +128,25 @@ impl<'a> Elements<'_> { ) .on(on, &animation.1), ); - return tag; + return None; } - // The component `as` gives animates when it is animated - tag.or_else(|| Some(self.animated_component(kind, local))) + Some(self.animated_component(native, local)) } - /// Reanimated's animated component of the React Native component `local` - /// is bound to - fn animated_component(&mut self, kind: &ExportVariableKind, local: &str) -> String { + /// Reanimated's animated component of the React Native component + /// `native`, which `local` is bound to + fn animated_component(&mut self, native: &str, local: &str) -> String { self.animated.used = true; - let native = native_component(kind); if ANIMATED.contains(&native) { return format!("{}.{native}", self.animated.name); } if let Some((_, name)) = self.animated.created.iter().find(|(of, _)| of == local) { return name.clone(); } - let name = fresh_name(&format!("__Animated{local}"), self.code); + let name = fresh_name( + &format!("__Animated{}", local.trim_start_matches('_')), + self.code, + ); self.animated .created .push((local.to_string(), name.clone())); diff --git a/libs/extractor/src/native/element/css_call.rs b/libs/extractor/src/native/element/css_call.rs index 6b7864d99..45ecf7bfc 100644 --- a/libs/extractor/src/native/element/css_call.rs +++ b/libs/extractor/src/native/element/css_call.rs @@ -38,6 +38,8 @@ impl<'a> Elements<'_> { /// Compile a call of `css` to the style it describes pub(super) fn css_call(&mut self, call: &CallExpression<'a>) { + let compat = self.is_compat(&call.callee); + let outer = std::mem::replace(&mut self.compat, compat); let mut choices = Vec::new(); for argument in &call.arguments { match argument.as_expression() { @@ -60,12 +62,16 @@ impl<'a> Elements<'_> { self.reanimated(&animation, CSS); } self.css_code(call.span, choices); + self.compat = outer; } /// Compile `css` tagged with CSS text, such as `` css`padding: 8px;` ``, /// to the style it describes pub(super) fn css_template(&mut self, template: &TaggedTemplateExpression<'a>) { + let compat = self.is_compat(&template.tag); + let outer = std::mem::replace(&mut self.compat, compat); let choices = self.css_text(&template.quasi, template.span.start); + self.compat = outer; self.css_code(template.span, choices); } @@ -204,7 +210,8 @@ impl<'a> Elements<'_> { } expression if is_nothing(expression) => {} expression if self.in_styled && is_function(expression) => { - if gives_style_props(expression) { + // A compat package's function gives React Native styles + if !self.compat && gives_style_props(expression) { self.error( expression.span().start, Problem::new( @@ -216,6 +223,7 @@ impl<'a> Elements<'_> { return; } let code = format!("({})({})", self.rewritten(expression), self.props); + self.props_called.set(true); choices.push(Choice::Given(code)); } expression => { diff --git a/libs/extractor/src/native/element/styled.rs b/libs/extractor/src/native/element/styled.rs index f88cadc38..c41dfa758 100644 --- a/libs/extractor/src/native/element/styled.rs +++ b/libs/extractor/src/native/element/styled.rs @@ -5,8 +5,13 @@ use oxc_ast::ast::{CallExpression, Expression, IdentifierReference, TaggedTemplateExpression}; use oxc_span::{GetSpan, Span}; +use std::fmt::Write; + +use oxc_syntax::symbol::SymbolId; + use super::{Elements, Frame, HookAt, component_name, defaults}; use crate::component::ExportVariableKind; +use crate::fresh_name::fresh_name; use crate::native::errors::Problem; use crate::native::style::{Choice, INTERACTIONS, Reads, Vars, interaction_keys, style_code}; @@ -18,6 +23,9 @@ pub(super) enum Target { /// A Devup UI component, which renders its React Native component with /// the styles it declares first Devup(ExportVariableKind, String), + /// A React Native component `styled.Name` names, and the local name it is + /// imported under + Native(String, String), /// Any other component, by its code Other(String), } @@ -33,24 +41,49 @@ impl<'a> Elements<'_> { /// Whether `identifier` reads the `styled` the file imports pub(super) fn is_styled_reference(&self, identifier: &IdentifierReference<'_>) -> bool { + self.symbol(identifier) + .is_some_and(|symbol| self.styled.contains(&symbol)) + } + + /// Whether `callee` reads the `styled` or the `css` of a compat package, + /// whose numbers are pixels and whose function parts read the theme of + /// its `ThemeProvider` + pub(super) fn is_compat(&self, callee: &Expression<'_>) -> bool { + matches!( + callee.without_parentheses(), + Expression::Identifier(identifier) if self + .symbol(identifier) + .is_some_and(|symbol| self.compat_bindings.contains(&symbol)) + ) + } + + /// The binding `identifier` reads + fn symbol(&self, identifier: &IdentifierReference<'_>) -> Option { 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; + /// The target of `callee` when it is `styled(Target)` or `styled.Name`, + /// whose call or tagged template gives the styles, and whether the + /// `styled` is a compat package's + pub(super) fn styled_target(&mut self, callee: &Expression<'a>) -> Option<(Target, bool)> { + match callee.without_parentheses() { + Expression::CallExpression(call) + if self.is_styled(&call.callee) && call.arguments.len() == 1 => + { + let target = call.arguments[0].as_expression()?; + Some((self.target(target), self.is_compat(&call.callee))) + } + Expression::StaticMemberExpression(member) if self.is_styled(&member.object) => { + // `styled.View`: the React Native component of that name + let name = member.property.name.to_string(); + let local = self.native_import(&name); + Some((Target::Native(name, local), self.is_compat(&member.object))) + } + _ => None, } - let target = call.arguments[0].as_expression()?; - Some(self.target(target)) } /// The target `expression` names @@ -75,7 +108,11 @@ impl<'a> Elements<'_> { } /// `styled(Target)(...styles)` - pub(super) fn styled_call(&mut self, call: &CallExpression<'a>, target: Target) { + pub(super) fn styled_call( + &mut self, + call: &CallExpression<'a>, + (target, compat): (Target, bool), + ) { let arguments: Vec<&Expression<'a>> = call .arguments .iter() @@ -91,7 +128,7 @@ impl<'a> Elements<'_> { .call(STYLED), ); } - self.styled_component(call.span, target, |visitor, choices| { + self.styled_component(call.span, (target, compat), |visitor, choices| { for argument in arguments { visitor.css_part(argument, choices); } @@ -102,9 +139,9 @@ impl<'a> Elements<'_> { pub(super) fn styled_template( &mut self, template: &TaggedTemplateExpression<'a>, - target: Target, + (target, compat): (Target, bool), ) { - self.styled_component(template.span, target, |visitor, choices| { + self.styled_component(template.span, (target, compat), |visitor, choices| { let text = visitor.css_text(&template.quasi, template.span.start); choices.extend(text); }); @@ -129,7 +166,8 @@ impl<'a> Elements<'_> { return; }; let target = self.target(target); - self.styled_component(call.span, target, |visitor, choices| { + let compat = self.is_compat(&call.callee); + self.styled_component(call.span, (target, compat), |visitor, choices| { visitor.css_part(styles, choices); }); } @@ -139,12 +177,12 @@ impl<'a> Elements<'_> { fn styled_component( &mut self, span: Span, - target: Target, + (target, compat): (Target, bool), 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()), + Target::Native(_, code) | Target::Other(code) => (code.clone(), Vec::new()), }; // The component calls the hooks its styles read, as a function // component does @@ -154,8 +192,21 @@ impl<'a> Elements<'_> { hook_at: HookAt::Body(span.start as usize), }); let outer = std::mem::replace(&mut self.in_styled, true); + let outer_compat = std::mem::replace(&mut self.compat, compat); + // A compat package's function parts read the theme of its + // `ThemeProvider`, which the props they are called with hold + let props = self.props.clone(); + let themed = fresh_name("__themed", self.code); + if compat { + self.props.clone_from(&themed); + } + let called = self.props_called.replace(false); read(self, &mut choices); + let themed = (compat && self.props_called.get()).then_some(themed); + self.props_called.set(called); + self.props = props; self.in_styled = outer; + self.compat = outer_compat; let frame_reads = self .frames .pop() @@ -164,7 +215,9 @@ impl<'a> Elements<'_> { (Some(press), Target::Devup(kind, _)) => { self.pressable(press, kind, "styled()", None).unwrap_or(tag) } - (Some((offset, name)), Target::Other(_)) => { + // `Pressable` calls the function its `style` is with its state + (Some(_), Target::Native(native, _)) if native == "Pressable" => tag, + (Some((offset, name)), Target::Native(..) | Target::Other(_)) => { self.error( offset, Problem::new( @@ -185,6 +238,13 @@ impl<'a> Elements<'_> { self.animated(&animation, (kind, local), STYLED, None, interactive) .unwrap_or(tag) } + (Some(animation), Target::Native(native, local)) => { + let interactive = INTERACTIONS + .iter() + .any(|state| choices.iter().any(|choice| choice.holds(*state))); + self.animated_native(&animation, (native, local), STYLED, interactive) + .unwrap_or(tag) + } (Some(animation), Target::Other(_)) => { // The component given animates when it is animated self.reanimated(&animation, STYLED); @@ -205,11 +265,19 @@ impl<'a> Elements<'_> { .as_ref() .map_or_else(Reads::default, |style| style.reads) .union(frame_reads); - let hooks = if reads.any() { + let mut hooks = if reads.any() { format!("{} ", self.hook_calls(reads)) } else { String::new() }; + if let Some(themed) = themed { + self.runtime.styled_theme_used = true; + let _ = write!( + hooks, + "const {themed} = {{ theme: {}(), ...{props} }}; ", + self.runtime.styled_theme + ); + } let style = style.map_or_else(String::new, |style| { let code = if keys.is_empty() { style.code @@ -252,3 +320,15 @@ fn holds_object(expression: &Expression<'_>) -> bool { _ => false, } } + +impl Elements<'_> { + /// The local name the React Native component `name` is imported under + fn native_import(&mut self, name: &str) -> String { + if let Some((_, local)) = self.natives.iter().find(|(native, _)| native == name) { + return local.clone(); + } + let local = fresh_name(&format!("__{name}"), self.code); + self.natives.push((name.to_string(), local.clone())); + local + } +} diff --git a/libs/extractor/src/native/errors.rs b/libs/extractor/src/native/errors.rs index 334b9c20e..3eb7df9fa 100644 --- a/libs/extractor/src/native/errors.rs +++ b/libs/extractor/src/native/errors.rs @@ -102,3 +102,14 @@ pub(super) fn reanimated_problem() -> Problem { "install react-native-reanimated 4 or later (`npx expo install react-native-reanimated`), then restart Metro", ) } + +/// Why `name`, the theme API of styled-components or Emotion, cannot be +/// imported with the runtime off +pub(super) fn compat_theme_problem(name: &str) -> Problem { + Problem::new( + format!( + "`{name}` gives the theme of `ThemeProvider` through the React Native runtime, which `runtime: false` turns off" + ), + "remove it, or turn the runtime on", + ) +} diff --git a/libs/extractor/src/native/imports.rs b/libs/extractor/src/native/imports.rs index 802fe4dbe..26ed15596 100644 --- a/libs/extractor/src/native/imports.rs +++ b/libs/extractor/src/native/imports.rs @@ -12,8 +12,8 @@ use oxc_span::GetSpan; use oxc_syntax::symbol::SymbolId; use rustc_hash::{FxHashMap, FxHashSet}; -use super::errors::{Problem, reanimated_problem, theme_api}; -use super::{NativeTarget, REACT_NATIVE, RUNTIME, Replacement}; +use super::errors::{Problem, compat_theme_problem, reanimated_problem, theme_api}; +use super::{COMPAT_PACKAGES, NativeTarget, REACT_NATIVE, RUNTIME, Replacement}; use crate::component::ExportVariableKind; /// The Devup UI components a file imports, and how its imports change @@ -25,6 +25,9 @@ pub(super) struct Imports { pub css: FxHashSet, /// The bindings of `styled`, whose calls compile to components pub styled: FxHashSet, + /// The bindings of `styled` and `css` imported from a compat package, whose + /// function parts read the theme of its `ThemeProvider` + pub compat: FxHashSet, /// The bindings of `keyframes`, whose calls compile to the keyframes /// react-native-reanimated reads pub keyframes: FxHashSet, @@ -103,8 +106,11 @@ pub(super) fn read( for statement in &program.body { match statement { Statement::ImportDeclaration(declaration) => { - if declaration.source.value == package && !declaration.import_kind.is_type() { - imports.declaration(declaration, code, package, target); + let source = declaration.source.value.as_str().unwrap_or_default(); + let compat = COMPAT_PACKAGES.contains(&source); + if (source == package || compat) && !declaration.import_kind.is_type() { + let package = if compat { source } else { package }; + imports.declaration(declaration, code, (package, compat), target); } } statement => { @@ -122,7 +128,7 @@ impl Imports { &mut self, declaration: &ImportDeclaration<'_>, code: &str, - package: &str, + (package, compat): (&str, bool), target: &NativeTarget, ) { let mut natives = Vec::new(); @@ -130,8 +136,17 @@ impl Imports { let mut kept = Vec::new(); for specifier in declaration.specifiers.iter().flatten() { match specifier { + ImportDeclarationSpecifier::ImportDefaultSpecifier(specifier) if compat => { + // The default export of a compat package is its `styled` + self.compat_styled(specifier.local.symbol_id.get()); + } ImportDeclarationSpecifier::ImportSpecifier(specifier) => { - match self.specifier(specifier, package, target) { + let destination = if compat { + self.compat_specifier(specifier, package, target) + } else { + self.specifier(specifier, package, target) + }; + match destination { Destination::Native(native) => natives.push(native), Destination::Runtime(name) => runtime.push(name), Destination::Kept => kept.push(specifier_code(specifier, code)), @@ -153,7 +168,7 @@ impl Imports { if natives.is_empty() && runtime.is_empty() && !dropped { return; } - self.theme_api |= !runtime.is_empty(); + self.theme_api |= !runtime.is_empty() && !compat; let source = declaration.source.span.source_text(code).to_string(); let text: Vec = [ (natives, format!("\"{REACT_NATIVE}\"")), @@ -169,6 +184,54 @@ impl Imports { .push((span.start as usize, span.end as usize, text.join("\n"))); } + /// Bind `styled` of a compat package, whose function parts read the theme + /// of its `ThemeProvider` + fn compat_styled(&mut self, symbol: Option) { + self.styled.extend(symbol); + self.compat.extend(symbol); + } + + /// Where a specifier of a compat package goes on React Native: `styled` + /// and `css` compile as Devup UI's, the theme API is the runtime's, and + /// the rest stays on the package + fn compat_specifier( + &mut self, + specifier: &ImportSpecifier<'_>, + package: &str, + target: &NativeTarget, + ) -> Destination { + if specifier.import_kind.is_type() { + return Destination::Kept; + } + let name = imported_name(&specifier.imported); + let symbol = specifier.local.symbol_id.get(); + match name.as_str() { + "styled" => self.compat_styled(symbol), + "css" => { + self.css.extend(symbol); + self.compat.extend(symbol); + } + "ThemeProvider" | "useTheme" | "withTheme" if !target.runtime => { + self.errors.push(( + specifier.span.start, + compat_theme_problem(&name).import(&name, package), + )); + return Destination::Kept; + } + "ThemeProvider" | "withTheme" => { + return Destination::Runtime(renamed(&name, specifier.local.name.to_string())); + } + "useTheme" => { + return Destination::Runtime(renamed( + "useStyledTheme", + specifier.local.name.to_string(), + )); + } + _ => return Destination::Kept, + } + Destination::Dropped + } + /// Where a specifier goes on React Native fn specifier( &mut self, diff --git a/libs/extractor/src/native/mod.rs b/libs/extractor/src/native/mod.rs index 3ad4e98a0..5fe70def8 100644 --- a/libs/extractor/src/native/mod.rs +++ b/libs/extractor/src/native/mod.rs @@ -84,6 +84,10 @@ pub(crate) const RUNTIME: &str = "@devup-ui/react/native"; /// The package animations and transitions run on pub(crate) const REANIMATED: &str = "react-native-reanimated"; +/// The React Native packages of styled-components and Emotion, whose +/// `styled` and `css` compile as Devup UI's +pub(crate) const COMPAT_PACKAGES: [&str; 2] = ["@emotion/native", "styled-components/native"]; + /// Compile `code` for React Native, or tell every place it cannot be, each /// led by `filename:line:column` pub(crate) fn extract( @@ -93,7 +97,7 @@ pub(crate) fn extract( target: NativeTarget, source_map: bool, ) -> Result> { - if !code.contains(package) { + if !code.contains(package) && !COMPAT_PACKAGES.iter().any(|compat| code.contains(compat)) { return Ok(unchanged(code)); } let source_type = crate::supported_source_type(filename)?; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__compat_alone.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__compat_alone.snap new file mode 100644 index 000000000..4188dd21c --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__compat_alone.snap @@ -0,0 +1,6 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: output +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +export const value = "styled-components/native"; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__compat_emotion.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__compat_emotion.snap new file mode 100644 index 000000000..3ce66b873 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__compat_emotion.snap @@ -0,0 +1,72 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: output +--- +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 { useStyledTheme as __useStyledTheme } from "@devup-ui/react/native"; +import { View as __View, Pressable as __Pressable, Text as __Text } from "react-native"; +import __Animated from "react-native-reanimated"; +const __AnimatedPressable = __Animated.createAnimatedComponent(__Pressable); +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { margin: 1 }, + b: { padding: 2 }, + c: { opacity: .5 }, + d: { + padding: 8, + opacity: .5 + }, + e: { + padding: 8, + flex: 1, + transitionDuration: 300 + }, + f: { transition: "opacity 1s" }, + g: { padding: 1 } +}); +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 Named = (__props) => { + return <__View {...__props} style={[__s.a, __props.style]} />; +}; +export const Press = (__props) => { + return <__Pressable {...__props} style={({ pressed: __p }) => [ + __s.b, + __p && __s.c, + __props.style + ]} />; +}; +export const Label = (__props) => { + const __themed = { + theme: __useStyledTheme(), + ...__props + }; + return <__Text {...__props} style={[((props) => ({ color: props.color }))(__themed), __props.style]} />; +}; +export const Sized = (__props) => { + const __themed = { + theme: __useStyledTheme(), + ...__props + }; + return <__View {...__props} style={[ + __s.d, + { margin: __u(((p) => p.gap)(__themed), 1) }, + __props.style + ]} />; +}; +export const Spaced = (__props) => { + return <__Animated.View {...__props} style={[__s.e, __props.style]} />; +}; +export const Fading = (__props) => { + return <__Animated.View {...__props} style={[__s.f, __props.style]} />; +}; +export const Moving = (__props) => { + return <__AnimatedPressable {...__props} style={[__s.f, __props.style]} />; +}; +export const Box2 = (__props) => { + return ; +}; +export const pad = __s.g; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__compat_runtime_off.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__compat_runtime_off.snap new file mode 100644 index 000000000..d76171479 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__compat_runtime_off.snap @@ -0,0 +1,8 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: output +--- +error: test.tsx:2:10: `ThemeProvider` from `@emotion/native` cannot be used on React Native: `ThemeProvider` gives the theme of `ThemeProvider` through the React Native runtime, which `runtime: false` turns off. Fix: remove it, or turn the runtime on +test.tsx:2:25: `useTheme` from `@emotion/native` cannot be used on React Native: `useTheme` gives the theme of `ThemeProvider` through the React Native runtime, which `runtime: false` turns off. Fix: remove it, or turn the runtime on +test.tsx:2:35: `withTheme` from `@emotion/native` cannot be used on React Native: `withTheme` gives the theme of `ThemeProvider` through the React Native runtime, which `runtime: false` turns off. Fix: remove it, or turn the runtime on +test.tsx:3:8: `* as S` from `styled-components/native` cannot be used on React Native: the build reads only components imported by name. Fix: import each component by name, such as `import { Box } from 'styled-components/native'` diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__compat_styled_components.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__compat_styled_components.snap new file mode 100644 index 000000000..6c0b82659 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__compat_styled_components.snap @@ -0,0 +1,60 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: output +--- +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 { ThemeProvider, useStyledTheme as useTheme, withTheme } from "@devup-ui/react/native"; +import { ThemeContext, type DefaultTheme } from "styled-components/native"; +import { useThemeIndex as __useThemeIndex, useStyledTheme as __useStyledTheme, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { Text as __Text, View as __View } from "react-native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { margin: 1 }, + b: { fontSize: 18 }, + c: { padding: 2 }, + d: { backgroundColor: "#5a44ff" }, + e: { backgroundColor: "#8c7bff" }, + f: { flexDirection: "row" }, + g: { padding: 4 }, + h: { opacity: .5 } +}); +const shared = __s.a; +export const Title = (__props) => { + const __themed = { + theme: __useStyledTheme(), + ...__props + }; + return <__Text {...__props} style={[ + __s.b, + { color: ((props) => props.theme.primary)(__themed) }, + __props.style + ]} />; +}; +export const Card = (__props) => { + const __t = __useThemeIndex(); + return <__View {...__props} style={[ + __s.c, + [__s.d, __s.e][__t], + __props.style + ]} />; +}; +export const Row = (__props) => { + return <__View {...__props} style={[__s.f, __props.style]} />; +}; +export const Plain = (__props) => { + return ; +}; +export const Note = (__props) => { + const __themed = { + theme: __useStyledTheme(), + ...__props + }; + return props.theme.dim && __s.h)(__themed), __props.style]} />; +}; +export function App() { + const theme = useTheme(); + return Hi; +} +export const Themed = withTheme(App); +export const context = ThemeContext; diff --git a/libs/extractor/src/native/tests.rs b/libs/extractor/src/native/tests.rs index 8ddfb280e..0209433b6 100644 --- a/libs/extractor/src/native/tests.rs +++ b/libs/extractor/src/native/tests.rs @@ -1414,3 +1414,60 @@ fn compiles_animations(#[case] name: &str, #[case] code: &str, #[case] reanimate }; assert_snapshot!(name, output); } + +const STYLED_COMPONENTS: &str = r"import styled, { css, ThemeProvider, useTheme, withTheme, ThemeContext, type DefaultTheme } from 'styled-components/native' +const shared = css({ m: 1 }) +export const Title = styled.Text` + color: ${(props) => props.theme.primary}; + font-size: 18px; +` +export const Card = styled.View({ p: 2, bg: '$primary' }) +export const Row = styled.View`flex-direction: row;` +export const Plain = styled(Box)`padding: 4px;` +export const Note = styled(Text)((props) => props.theme.dim && css({ opacity: 0.5 })) +export function App() { + const theme = useTheme() + return Hi +} +export const Themed = withTheme(App) +export const context = ThemeContext +"; + +const EMOTION_NATIVE: &str = r"import styled from '@emotion/native' +import { css } from '@emotion/native' +import { styled as named } from 'styled-components/native' +export const Named = named.View({ m: 1 }) +export const Press = styled.Pressable({ p: 2, _active: { opacity: 0.5 } }) +export const Label = styled.Text((props) => ({ color: props.color })) +export const Sized = styled.View`padding: 8px; margin: ${(p) => p.gap}; opacity: 0.5;` +export const Spaced = styled.View({ padding: 8, flex: 1, transitionDuration: 300 }) +export const Fading = styled.View({ transition: 'opacity 1s' }) +export const Moving = styled.Pressable({ transition: 'opacity 1s' }) +export const Box2 = styled(View, { m: 1 }) +export const pad = css({ p: 1 }) +"; + +#[rstest] +#[case::styled_components("compat_styled_components", STYLED_COMPONENTS, true)] +#[case::emotion("compat_emotion", EMOTION_NATIVE, true)] +#[case::runtime_off( + "compat_runtime_off", + "import { ThemeProvider, useTheme, withTheme } from '@emotion/native'\nimport * as S from 'styled-components/native'\n", + false +)] +#[case::alone( + "compat_alone", + "export const value = 'styled-components/native'\n", + true +)] +fn compiles_compat_packages(#[case] name: &str, #[case] code: &str, #[case] runtime: bool) { + let output = match extract( + "test.tsx", + &format!("{IMPORT}{code}"), + themed_option(NativePlatform::Ios, runtime, two_themes()), + ) { + Ok(output) => output.code, + Err(error) => format!("error: {error}"), + }; + assert_snapshot!(name, output); +} diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md index a3fbc6d12..e3cc2e684 100644 --- a/packages/metro-plugin/README.md +++ b/packages/metro-plugin/README.md @@ -281,6 +281,318 @@ The component reads style props only through `styled()`: on React Native, `` passes `p` on to the target, so give it `style` or `className` instead. +## styled-components and Emotion + +Files importing `styled-components/native` or `@emotion/native` compile +without those packages at runtime: their `styled` and `css` compile as Devup +UI's, so the CSS is parsed at build time instead of on every render. + +```tsx +import styled, { ThemeProvider } from 'styled-components/native' + +const Title = styled.Text` + color: ${(props) => props.theme.primary}; + font-size: 18px; +` +const Card = styled.View({ padding: 8, backgroundColor: '$surface' }) +``` + +- `styled.View`, `styled.Text`, `styled.Pressable` and any other + `styled.Name` render React Native's component of that name; `styled(X)` + works as Devup UI's `styled()`. +- A number is pixels, as those packages read it: `padding: 8` is 8, not + Devup UI's `8 * 4`. Devup UI's shorthands and `# @devup-ui/metro-plugin + +> **Experimental (0.x).** React Native support is in progress +> ([#411](https://github.com/dev-five-git/devup-ui/issues/411)). This package +> is not published yet, and its API may change. + +Compiles Devup UI for React Native in [Metro](https://metrobundler.dev/), the +bundler of React Native and Expo. You keep importing `Box`, `Text`, ... from +`@devup-ui/react`; at build time each element becomes a React Native component +and its style props become style objects hoisted into one `StyleSheet.create` +per file. With one theme nothing runs at runtime; with more, a tiny runtime +(`@devup-ui/react/native`) only tells which theme shows. + +## Setup + +```js +// metro.config.js (Expo) +const { getDefaultConfig } = require('expo/metro-config') +const { withDevupUI } = require('@devup-ui/metro-plugin') + +module.exports = withDevupUI(getDefaultConfig(__dirname)) +``` + +```js +// metro.config.js (React Native CLI) +const { getDefaultConfig } = require('@react-native/metro-config') +const { withDevupUI } = require('@devup-ui/metro-plugin') + +module.exports = withDevupUI(getDefaultConfig(__dirname)) +``` + +```tsx +import { Box, Flex, Text } from '@devup-ui/react' + +export function Card() { + return ( + + + Hello + + + + ) +} +``` + +`withDevupUI` sets `transformer.babelTransformerPath` to its own transformer. +The transformer compiles each file that imports Devup UI for the platform +Metro builds (`ios`, `android` or `web`) and then hands the code to the +transformer the config had: Expo's, React Native's, or the one you name. + +| Element | React Native | +| --- | --- | +| `Box`, `Flex`, `VStack`, `Center` | `View` (`Flex`, `VStack` and `Center` add their flex styles) | +| `Text` | `Text` | +| `Image` | `Image` (`src` becomes `source`) | +| `Input` | `TextInput` | +| `Button` | `Pressable` | + +`_ios`, `_android` and `_web` apply their styles on that platform only. + +## Options + +```js +withDevupUI(config, { + // The package Devup UI is imported from. Default: '@devup-ui/react' + package: '@devup-ui/react', + // devup.json, from the project root. Default: 'devup.json' + devupFile: 'devup.json', + // Packages in node_modules that ship uncompiled Devup UI. Default: [] + include: [], + // Whether styles that need the React Native runtime may import it. + // Default: true. false is a strict zero-runtime mode. + runtime: true, + // 'native' (default) or 'wasm' + engine: 'native', + // The Babel transformer the compiled code goes to. + // Default: the config's babelTransformerPath, else Expo's, else React Native's. + upstreamTransformer: undefined, +}) +``` + +## Themes + +`$` tokens of devup.json (colors, `length` and `shadow`) and `typography` +resolve at build time to the values React Native takes. With one theme each +becomes its literal value, and no file imports a runtime: + +```tsx + +// const __s = StyleSheet.create({ a: { backgroundColor: "#fff", padding: 16 } }) +// +``` + +With more themes, the styles of every theme are precomputed, and the element +picks one by the index of the theme that shows; what does not differ by theme +stays shared: + +```tsx +// +``` + +The themes are the color variants of devup.json, the default first. The app +starts on the theme that follows the system appearance (React Native's +`Appearance`): while it is dark, `dark`, or else the first theme `colorScheme` +makes dark; otherwise the default theme. `_themeDark`, `_themeSepia`, ... +apply their styles in that theme only. + +```tsx +import { getTheme, setTheme, useTheme } from '@devup-ui/react' + +const theme = useTheme() // renders again when the theme changes +setTheme('sepia') // wins over the system appearance +``` + +The build imports these from `@devup-ui/react/native`, a store read with +`useSyncExternalStore` that computes no style; web builds never import it. +`setTheme` does not save the choice across launches. + +## Responsive values + +Responsive arrays, and `length`, `shadow` and `typography` tokens with a value +at each breakpoint, use the `breakpoints` of devup.json (the web's +`[0, 480, 768, 992, 1280, 1600]` by default), measured against the window +width in density-independent pixels. As on the web, each value applies from +its breakpoint on and `null` keeps the one before: + +```tsx + +// +``` + +The build precomputes one style object for each run of breakpoints that +share their styles, only for the styles that differ; a value that differs by +theme and breakpoint picks by both. The runtime listens to the window once +and renders a component again only when the window crosses into another +breakpoint. `_portrait` and `_landscape` apply their styles while the window +is in that orientation. + +A value read at runtime in an array (`p={[x, 2]}`) applies from its +breakpoint on as it is. + +## Press styles + +`_active` (or its React Native name, `_pressed`) applies its styles while the +element is pressed. React Native tells only a `Pressable` whether it is +pressed, so the build passes it a function for its `style`: + +```tsx + +// renders + [styles.a, pressed && styles.b]} /> +``` + +A `Button` is already a `Pressable`. A `Box`, `Flex`, `Center` or `VStack` +with a press style becomes one, so it takes `onPress` and the other props of +`Pressable`. A press style works with `runtime: false` too, as it needs no +runtime. It is a build error on a `Text`, an `Image` or an `Input`, and with +`as`. + +### Hover, focus and disabled + +`_hover` and `_focus` apply while the pointer is over the element and while +it has focus. A `Pressable` tells these to its style function too +(`({ hovered, focused }) => ...`). React Native reports them where the +platform has a pointer or keyboard focus, such as the web through +react-native-web, and never on a phone's touch screen. An `Input` with +`_focus` renders through the runtime's `Focused`, which follows its +`onFocus` and `onBlur` and still calls yours. `_hover` on an `Input`, and any +of these on a `Text` or an `Image`, is a build error. + +`_disabled` applies while the element's `disabled` prop is true: +` + ) +} +``` + +`css()` takes what it does on the web: objects of style props (with +responsive values, theme tokens and the theme, platform and orientation +blocks), conditions choosing between them, what another `css()` gives, and +CSS text (`` css`padding: 8px; background-color: $primary;` ``, each +interpolation a whole value). The element's style props apply after its +`className`, and its `style` prop last. + +A `css()` whose styles differ by theme, breakpoint or orientation reads the +runtime, so it must be called in a function component or a hook. One that does +not can be called anywhere, such as at the top of the file. These are build +errors: + +- a class name (`className="p-4"`, `css('p-4')`) +- a press style in `css()`: give `_active` to the element itself +- selectors, nesting and at-rules in CSS text + +`css()` gives a style rather than a class on React Native, so pass it to +`className`, not to the `style` of a React Native component, which TypeScript +types as a string. + +## `styled()` + +`styled()` compiles to a function component that renders its target with the +styles it describes, before the `style` the component is given: + +```tsx +const Card = styled(Box)({ bg: '$surface', p: [2, null, 4] }) +const Title = styled(Text)` + color: ${(props) => props.color}; + font-size: 18px; +` +// compiles to +const Card = (props) => { + const t = useThemeIndex(), b = useBreakpoint() + return +} +``` + +It takes the parts `css()` takes, as `styled(Target)(...parts)`, +`` styled(Target)`css text` `` or `styled(Target, styles)`. A function in +them is called with the component's props: a value (`w: (p) => p.width`, or +an interpolation in CSS text), or a part giving what `css()` gives +(`(p) => p.active && css({ opacity: 0.5 })`). The target is a Devup UI +component, which keeps the styles it declares first (`Flex` its row), or any +React Native component. A press style makes a styled `Box` a `Pressable`. +These are build errors: + +- a tag (`styled('div')`, `styled.div`) +- a function of the props giving style props (`(p) => ({ bg: p.color })`): + return what `css()` gives instead +- a press style on a component other than a `Box` or a `Button` + +The component reads style props only through `styled()`: on React Native, +`` passes `p` on to the target, so give it `style` or +`className` instead. + + tokens work too. +- A function of the props is called with `props.theme`, the theme of the + nearest `ThemeProvider`. A function giving an object gives React Native + styles as they are. +- `ThemeProvider`, `useTheme` and `withTheme` are the runtime's: a React + context, whose theme a provider merges over the outer one's. With + `runtime: false` they are build errors. +- Any other import stays on the package. + ## Limits of this version Only styles the build can decide are supported: literals, values read at diff --git a/packages/react/src/native/__tests__/index.browser.test.tsx b/packages/react/src/native/__tests__/index.browser.test.tsx index cb37e535c..326169105 100644 --- a/packages/react/src/native/__tests__/index.browser.test.tsx +++ b/packages/react/src/native/__tests__/index.browser.test.tsx @@ -2,6 +2,8 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test' import { act, render, renderHook } from 'bun-test-env-dom' import { createElement, type ReactNode } from 'react' +import type { StyledTheme } from '../../types/props' + /** The system appearance React Native reports, and who listens to it */ const appearance = { scheme: 'light' as string | null, @@ -287,3 +289,51 @@ describe('Focused', () => { expect(input()?.getAttribute('data-color')).toBe('false') }) }) + +describe('ThemeProvider, useStyledTheme and withTheme', () => { + it('give the theme merged over the outer one, or what a function makes of it', () => { + const seen: StyledTheme[] = [] + const Probe = () => { + seen.push(runtime.useStyledTheme()) + return null + } + render(createElement(Probe)) + render( + createElement( + runtime.ThemeProvider, + { theme: { a: 1, b: 1 } }, + createElement( + runtime.ThemeProvider, + { theme: { b: 2 } }, + createElement(Probe), + ), + createElement( + runtime.ThemeProvider, + { + theme: (outer: StyledTheme | undefined) => ({ ...outer, c: 3 }), + }, + createElement(Probe), + ), + ), + ) + expect(seen).toEqual([{}, { a: 1, b: 2 }, { a: 1, b: 1, c: 3 }]) + }) + + it('gives a component the theme as its prop unless it is given one', () => { + const Named = ({ theme }: { theme?: { name?: string } }) => + createElement('span', null, theme?.name) + const ThemedNamed = runtime.withTheme(Named) + expect(ThemedNamed.displayName).toBe('WithTheme(Named)') + const { container } = render( + createElement( + runtime.ThemeProvider, + { theme: { name: 'ctx' } }, + createElement(ThemedNamed), + createElement(ThemedNamed, { theme: { name: 'own' } }), + ), + ) + expect( + [...container.querySelectorAll('span')].map((span) => span.textContent), + ).toEqual(['ctx', 'own']) + }) +}) diff --git a/packages/react/src/native/index.ts b/packages/react/src/native/index.ts index c9bc252d0..15f14c045 100644 --- a/packages/react/src/native/index.ts +++ b/packages/react/src/native/index.ts @@ -2,12 +2,17 @@ import { createElement, type ElementType, type ReactElement, + type ReactNode, + useContext, + useMemo, useState, useSyncExternalStore, } from 'react' import { Appearance, Dimensions } from 'react-native' +import type { StyledTheme } from '../types/props' import type { DevupTheme } from '../types/theme' +import { StyledThemeContext } from '../utils/theme-context' /** * The React Native runtime of Devup UI. The build compiles every style to @@ -214,3 +219,36 @@ export function Focused({ style: $s(focused, useThemeIndex(), useBreakpoint(), useLandscape()), }) } + +export { withTheme } from '../utils/with-theme' + +/** + * The `ThemeProvider` of styled-components and Emotion, which the build + * imports for theirs: it gives its descendants `theme`, merged over the + * theme of an outer provider, or what a function of that theme returns. The + * `styled()` components of those packages call their functions with it as + * `props.theme`, and `withTheme` gives it as the `theme` prop. + */ +export function ThemeProvider({ + theme, + children, +}: { + theme: StyledTheme | ((outer: StyledTheme | undefined) => StyledTheme) + children?: ReactNode +}): ReactElement { + const outer = useContext(StyledThemeContext) + const value = useMemo( + () => (typeof theme === 'function' ? theme(outer) : { ...outer, ...theme }), + [outer, theme], + ) + return createElement(StyledThemeContext.Provider, { value }, children) +} + +/** + * The theme of the nearest `ThemeProvider`, or an empty object outside one: + * the `useTheme` of styled-components and Emotion, which the build imports + * for theirs + */ +export function useStyledTheme(): StyledTheme { + return useContext(StyledThemeContext) ?? {} +} From 4f9b42a66c8042313a3f481e850485fa284180f3 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 15:24:59 +0900 Subject: [PATCH 2/3] docs(metro-plugin): fix the duplicated README of the compat section Co-Authored-By: Claude Opus 5.5 --- packages/metro-plugin/README.md | 285 +------------------------------- 1 file changed, 1 insertion(+), 284 deletions(-) diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md index e3cc2e684..62ce77ca8 100644 --- a/packages/metro-plugin/README.md +++ b/packages/metro-plugin/README.md @@ -301,290 +301,7 @@ const Card = styled.View({ padding: 8, backgroundColor: '$surface' }) `styled.Name` render React Native's component of that name; `styled(X)` works as Devup UI's `styled()`. - A number is pixels, as those packages read it: `padding: 8` is 8, not - Devup UI's `8 * 4`. Devup UI's shorthands and `# @devup-ui/metro-plugin - -> **Experimental (0.x).** React Native support is in progress -> ([#411](https://github.com/dev-five-git/devup-ui/issues/411)). This package -> is not published yet, and its API may change. - -Compiles Devup UI for React Native in [Metro](https://metrobundler.dev/), the -bundler of React Native and Expo. You keep importing `Box`, `Text`, ... from -`@devup-ui/react`; at build time each element becomes a React Native component -and its style props become style objects hoisted into one `StyleSheet.create` -per file. With one theme nothing runs at runtime; with more, a tiny runtime -(`@devup-ui/react/native`) only tells which theme shows. - -## Setup - -```js -// metro.config.js (Expo) -const { getDefaultConfig } = require('expo/metro-config') -const { withDevupUI } = require('@devup-ui/metro-plugin') - -module.exports = withDevupUI(getDefaultConfig(__dirname)) -``` - -```js -// metro.config.js (React Native CLI) -const { getDefaultConfig } = require('@react-native/metro-config') -const { withDevupUI } = require('@devup-ui/metro-plugin') - -module.exports = withDevupUI(getDefaultConfig(__dirname)) -``` - -```tsx -import { Box, Flex, Text } from '@devup-ui/react' - -export function Card() { - return ( - - - Hello - - - - ) -} -``` - -`withDevupUI` sets `transformer.babelTransformerPath` to its own transformer. -The transformer compiles each file that imports Devup UI for the platform -Metro builds (`ios`, `android` or `web`) and then hands the code to the -transformer the config had: Expo's, React Native's, or the one you name. - -| Element | React Native | -| --- | --- | -| `Box`, `Flex`, `VStack`, `Center` | `View` (`Flex`, `VStack` and `Center` add their flex styles) | -| `Text` | `Text` | -| `Image` | `Image` (`src` becomes `source`) | -| `Input` | `TextInput` | -| `Button` | `Pressable` | - -`_ios`, `_android` and `_web` apply their styles on that platform only. - -## Options - -```js -withDevupUI(config, { - // The package Devup UI is imported from. Default: '@devup-ui/react' - package: '@devup-ui/react', - // devup.json, from the project root. Default: 'devup.json' - devupFile: 'devup.json', - // Packages in node_modules that ship uncompiled Devup UI. Default: [] - include: [], - // Whether styles that need the React Native runtime may import it. - // Default: true. false is a strict zero-runtime mode. - runtime: true, - // 'native' (default) or 'wasm' - engine: 'native', - // The Babel transformer the compiled code goes to. - // Default: the config's babelTransformerPath, else Expo's, else React Native's. - upstreamTransformer: undefined, -}) -``` - -## Themes - -`$` tokens of devup.json (colors, `length` and `shadow`) and `typography` -resolve at build time to the values React Native takes. With one theme each -becomes its literal value, and no file imports a runtime: - -```tsx - -// const __s = StyleSheet.create({ a: { backgroundColor: "#fff", padding: 16 } }) -// -``` - -With more themes, the styles of every theme are precomputed, and the element -picks one by the index of the theme that shows; what does not differ by theme -stays shared: - -```tsx -// -``` - -The themes are the color variants of devup.json, the default first. The app -starts on the theme that follows the system appearance (React Native's -`Appearance`): while it is dark, `dark`, or else the first theme `colorScheme` -makes dark; otherwise the default theme. `_themeDark`, `_themeSepia`, ... -apply their styles in that theme only. - -```tsx -import { getTheme, setTheme, useTheme } from '@devup-ui/react' - -const theme = useTheme() // renders again when the theme changes -setTheme('sepia') // wins over the system appearance -``` - -The build imports these from `@devup-ui/react/native`, a store read with -`useSyncExternalStore` that computes no style; web builds never import it. -`setTheme` does not save the choice across launches. - -## Responsive values - -Responsive arrays, and `length`, `shadow` and `typography` tokens with a value -at each breakpoint, use the `breakpoints` of devup.json (the web's -`[0, 480, 768, 992, 1280, 1600]` by default), measured against the window -width in density-independent pixels. As on the web, each value applies from -its breakpoint on and `null` keeps the one before: - -```tsx - -// -``` - -The build precomputes one style object for each run of breakpoints that -share their styles, only for the styles that differ; a value that differs by -theme and breakpoint picks by both. The runtime listens to the window once -and renders a component again only when the window crosses into another -breakpoint. `_portrait` and `_landscape` apply their styles while the window -is in that orientation. - -A value read at runtime in an array (`p={[x, 2]}`) applies from its -breakpoint on as it is. - -## Press styles - -`_active` (or its React Native name, `_pressed`) applies its styles while the -element is pressed. React Native tells only a `Pressable` whether it is -pressed, so the build passes it a function for its `style`: - -```tsx - -// renders - [styles.a, pressed && styles.b]} /> -``` - -A `Button` is already a `Pressable`. A `Box`, `Flex`, `Center` or `VStack` -with a press style becomes one, so it takes `onPress` and the other props of -`Pressable`. A press style works with `runtime: false` too, as it needs no -runtime. It is a build error on a `Text`, an `Image` or an `Input`, and with -`as`. - -### Hover, focus and disabled - -`_hover` and `_focus` apply while the pointer is over the element and while -it has focus. A `Pressable` tells these to its style function too -(`({ hovered, focused }) => ...`). React Native reports them where the -platform has a pointer or keyboard focus, such as the web through -react-native-web, and never on a phone's touch screen. An `Input` with -`_focus` renders through the runtime's `Focused`, which follows its -`onFocus` and `onBlur` and still calls yours. `_hover` on an `Input`, and any -of these on a `Text` or an `Image`, is a build error. - -`_disabled` applies while the element's `disabled` prop is true: -` - ) -} -``` - -`css()` takes what it does on the web: objects of style props (with -responsive values, theme tokens and the theme, platform and orientation -blocks), conditions choosing between them, what another `css()` gives, and -CSS text (`` css`padding: 8px; background-color: $primary;` ``, each -interpolation a whole value). The element's style props apply after its -`className`, and its `style` prop last. - -A `css()` whose styles differ by theme, breakpoint or orientation reads the -runtime, so it must be called in a function component or a hook. One that does -not can be called anywhere, such as at the top of the file. These are build -errors: - -- a class name (`className="p-4"`, `css('p-4')`) -- a press style in `css()`: give `_active` to the element itself -- selectors, nesting and at-rules in CSS text - -`css()` gives a style rather than a class on React Native, so pass it to -`className`, not to the `style` of a React Native component, which TypeScript -types as a string. - -## `styled()` - -`styled()` compiles to a function component that renders its target with the -styles it describes, before the `style` the component is given: - -```tsx -const Card = styled(Box)({ bg: '$surface', p: [2, null, 4] }) -const Title = styled(Text)` - color: ${(props) => props.color}; - font-size: 18px; -` -// compiles to -const Card = (props) => { - const t = useThemeIndex(), b = useBreakpoint() - return -} -``` - -It takes the parts `css()` takes, as `styled(Target)(...parts)`, -`` styled(Target)`css text` `` or `styled(Target, styles)`. A function in -them is called with the component's props: a value (`w: (p) => p.width`, or -an interpolation in CSS text), or a part giving what `css()` gives -(`(p) => p.active && css({ opacity: 0.5 })`). The target is a Devup UI -component, which keeps the styles it declares first (`Flex` its row), or any -React Native component. A press style makes a styled `Box` a `Pressable`. -These are build errors: - -- a tag (`styled('div')`, `styled.div`) -- a function of the props giving style props (`(p) => ({ bg: p.color })`): - return what `css()` gives instead -- a press style on a component other than a `Box` or a `Button` - -The component reads style props only through `styled()`: on React Native, -`` passes `p` on to the target, so give it `style` or -`className` instead. - - tokens work too. + Devup UI's `8 * 4`. Devup UI's shorthands and `$` tokens work too. - A function of the props is called with `props.theme`, the theme of the nearest `ThemeProvider`. A function giving an object gives React Native styles as they are. From 6fd7158706b4ad8b7a0c7c230792be5f6d8909b8 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 15:56:35 +0900 Subject: [PATCH 3/3] fix(native): cover the pixel conversion of compat numbers in one statement Tarpaulin counted the deferred `let pixels;` as an uncovered line. Co-Authored-By: Claude Opus 5.5 --- libs/extractor/src/native/element.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/libs/extractor/src/native/element.rs b/libs/extractor/src/native/element.rs index a938dbb9e..989848b25 100644 --- a/libs/extractor/src/native/element.rs +++ b/libs/extractor/src/native/element.rs @@ -9,6 +9,7 @@ use oxc_ast::ast::{ JSXElementName, JSXExpression, LogicalOperator, ObjectExpression, ObjectPropertyKind, Program, TSType, TaggedTemplateExpression, UnaryOperator, VariableDeclarator, }; +use std::borrow::Cow; use std::cell::Cell; use std::fmt::Write; @@ -698,13 +699,11 @@ impl<'a> Elements<'_> { /// breakpoint it is paired with on: one style object, or one a /// breakpoint and a theme where the styles differ by them fn static_choice(&self, name: &str, items: &[(usize, Literal)]) -> Result { - let pixels; - let items = if self.compat { - // A number of a compat package is pixels, as React Native reads it - pixels = in_pixels(name, items); - &pixels + // A number of a compat package is pixels, as React Native reads it + let items: Cow<[(usize, Literal)]> = if self.compat { + Cow::Owned(in_pixels(name, items)) } else { - items + Cow::Borrowed(items) }; let theme = &self.target.theme; let themes = match self.theme_scope { @@ -725,7 +724,7 @@ impl<'a> Elements<'_> { for index in themes.clone() { row.push(cell( name, - items, + &items, &Tokens { theme, index,