From 7ab44df26bbc64de6b72ca9c57aa56c11845dfbd Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 15:18:37 +0900 Subject: [PATCH 1/6] 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/6] 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 d4ba46dcae488ec3b0e7cdb9e1629edc92ccac83 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 15:26:59 +0900 Subject: [PATCH 3/6] feat(expo): export and check the example on the web The Expo example exports for the web through react-native-web with the same compiled output as iOS and Android. CI checks the web bundle as the others and opens it in Chromium: the card's theme color and its switch, the input's focus style and a button press. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_metro_expo_web.json | 7 ++ .github/workflows/publish.yml | 16 ++- apps/expo/app.json | 2 +- apps/expo/check-bundle.mjs | 2 +- apps/expo/check-web.mjs | 102 ++++++++++++++++++ apps/expo/package.json | 8 +- apps/expo/src/App.tsx | 4 + bun.lock | 45 +++++++- packages/metro-plugin/README.md | 13 +++ 9 files changed, 190 insertions(+), 9 deletions(-) create mode 100644 .changepacks/changepack_log_metro_expo_web.json create mode 100644 apps/expo/check-web.mjs diff --git a/.changepacks/changepack_log_metro_expo_web.json b/.changepacks/changepack_log_metro_expo_web.json new file mode 100644 index 000000000..bd3611187 --- /dev/null +++ b/.changepacks/changepack_log_metro_expo_web.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/metro-plugin/package.json": "Patch" + }, + "note": "Document Expo web (part of #411): Metro compiles the web build through react-native-web with the same output as iOS and Android, which the Expo example now exports and checks in Chromium.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 9ae22ef70..9cade6c4a 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -16,6 +16,7 @@ on: - feat/react-native-styled - feat/react-native-states - feat/react-native-animations + - feat/react-native-compat # 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 @@ -929,14 +930,15 @@ jobs: fi files="$(git diff --name-only "$(git merge-base "$BASE" HEAD)" HEAD)" echo "$files" - if grep -qE '^(libs/extractor/src/native/|libs/binding/|bindings/devup-ui-(binding|wasm)/|packages/(metro-plugin|plugin-utils)/|packages/react/src/native/|apps/expo/|\.github/workflows/publish\.yml$)' <<< "$files"; then + if grep -qE '^(libs/extractor/src/native/|libs/binding/|bindings/devup-ui-(binding|wasm)/|packages/(metro-plugin|plugin-utils)/|packages/react/src/native/|packages/react/src/utils/(theme-context|with-theme).|apps/expo/|\.github/workflows/publish\.yml$)' <<< "$files"; then echo "changed=true" >> "$GITHUB_OUTPUT" else echo "changed=false" >> "$GITHUB_OUTPUT" fi - # The Expo example app (apps/expo) bundled for iOS and Android through - # @devup-ui/metro-plugin, as a release build does. Devup UI compiles away, + # The Expo example app (apps/expo) bundled for iOS, Android and the web + # (react-native-web) through @devup-ui/metro-plugin, as a release build + # does, and the web export opened in Chromium. Devup UI compiles away, # so no bundle may keep a module of @devup-ui/react but its React Native # runtime (`@devup-ui/react/native`), nor its runtime placeholder, and a # file styled the same in every theme must not use that runtime. @@ -955,7 +957,7 @@ jobs: - run: bun install --frozen-lockfile - *download-build - *unpack-build - - name: Export the iOS and Android bundles + - name: Export the iOS, Android and web bundles working-directory: apps/expo env: EXPO_NO_TELEMETRY: '1' @@ -963,6 +965,12 @@ jobs: - name: Check the bundles working-directory: apps/expo run: bun run check + - *record-playwright-revisions + - *restore-playwright-cache + - *install-chromium + - name: Check the web export in Chromium + working-directory: apps/expo + run: bun run check:web # @devup-ui/vite-plugin must keep the CSS every server page needs when the # build is vinext/RSC. The fixture shares one Devup UI header between server diff --git a/apps/expo/app.json b/apps/expo/app.json index ad7952e54..c9389260f 100644 --- a/apps/expo/app.json +++ b/apps/expo/app.json @@ -3,6 +3,6 @@ "name": "Devup UI Expo", "slug": "devup-ui-expo", "version": "0.1.0", - "platforms": ["ios", "android"] + "platforms": ["ios", "android", "web"] } } diff --git a/apps/expo/check-bundle.mjs b/apps/expo/check-bundle.mjs index 81297af7a..704d8d76f 100644 --- a/apps/expo/check-bundle.mjs +++ b/apps/expo/check-bundle.mjs @@ -114,7 +114,7 @@ function runtimeUsers(code, locate) { return users } -for (const platform of ['ios', 'android']) { +for (const platform of ['ios', 'android', 'web']) { const directory = join(root, platform) const bundles = readdirSync(directory).filter((file) => file.endsWith('.js')) if (bundles.length === 0) failures.push(`${platform}: no JavaScript bundle`) diff --git a/apps/expo/check-web.mjs b/apps/expo/check-web.mjs new file mode 100644 index 000000000..2d28949c7 --- /dev/null +++ b/apps/expo/check-web.mjs @@ -0,0 +1,102 @@ +// Opens the web export (`expo export --platform web` wrote dist/) in Chromium +// and checks that react-native-web renders the styles Devup UI compiled: the +// card takes the theme's color and switches with the theme, the input takes +// its focus style through the runtime's `Focused`, and the button, a +// `Pressable`, counts a press. +import { createReadStream, existsSync, statSync } from 'node:fs' +import { createServer } from 'node:http' +import { extname, join, normalize } from 'node:path' + +import { chromium } from '@playwright/test' + +const root = join(import.meta.dirname, 'dist') +const TYPES = { + '.html': 'text/html', + '.js': 'text/javascript', + '.json': 'application/json', + '.png': 'image/png', +} + +const server = createServer((request, response) => { + const path = join(root, normalize(new URL(request.url, 'http://x').pathname)) + if (!path.startsWith(root)) { + response.writeHead(404).end() + return + } + // A path that is no file is the app's page + const file = + existsSync(path) && statSync(path).isFile() + ? path + : join(root, 'index.html') + response.writeHead(200, { + 'content-type': TYPES[extname(file)] ?? 'application/octet-stream', + }) + createReadStream(file).pipe(response) +}) +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) +const url = `http://127.0.0.1:${server.address().port}/` + +const failures = [] +/** Fail with `message` unless `actual` is `expected` */ +function expectEqual(actual, expected, message) { + if (actual !== expected) { + failures.push(`${message}: expected ${expected}, got ${actual}`) + } +} + +const browser = await chromium.launch() +try { + const page = await browser.newPage({ colorScheme: 'light' }) + const errors = [] + page.on('pageerror', (error) => errors.push(error.message)) + await page.goto(url) + const card = page.getByTestId('card') + const name = page.getByTestId('name') + const count = page.getByTestId('count') + await card.waitFor() + /** The computed style `property` of `locator` */ + const style = (locator, property) => + locator.evaluate( + (element, property) => getComputedStyle(element)[property], + property, + ) + + expectEqual( + await style(card, 'backgroundColor'), + 'rgb(255, 255, 255)', + 'the card in the light theme', + ) + expectEqual( + await style(count, 'backgroundColor'), + 'rgb(90, 68, 255)', + 'the count button', + ) + await name.focus() + expectEqual( + await style(name, 'borderTopColor'), + 'rgb(90, 68, 255)', + 'the focused input', + ) + await count.click() + expectEqual( + (await count.textContent())?.trim(), + 'Pressed 1 times', + 'the count after a press', + ) + await page.getByTestId('theme').click() + expectEqual( + await style(card, 'backgroundColor'), + 'rgb(31, 31, 46)', + 'the card in the dark theme', + ) + for (const error of errors) failures.push(`page error: ${error}`) +} finally { + await browser.close() + server.close() +} + +if (failures.length > 0) { + console.error(failures.join('\n')) + process.exit(1) +} +console.info('web: react-native-web renders the compiled styles') diff --git a/apps/expo/package.json b/apps/expo/package.json index c9662f3d0..04463f3bc 100644 --- a/apps/expo/package.json +++ b/apps/expo/package.json @@ -5,15 +5,19 @@ "main": "index.ts", "scripts": { "start": "expo start", - "export": "expo export --platform ios --platform android --no-bytecode --source-maps", - "check": "node check-bundle.mjs" + "export": "expo export --platform ios --platform android --platform web --no-bytecode --source-maps", + "check": "node check-bundle.mjs", + "check:web": "node check-web.mjs" }, "dependencies": { "@devup-ui/react": "workspace:^", + "@expo/metro-runtime": "~58.0.17", "expo": "~58.0.26", "react": "^19.3.1", + "react-dom": "^19.3.1", "react-native": "0.88.1", "react-native-reanimated": "~4.7.1", + "react-native-web": "~0.21.4", "react-native-worklets": "0.13.0" }, "devDependencies": { diff --git a/apps/expo/src/App.tsx b/apps/expo/src/App.tsx index 56d362fdd..e6318fa87 100644 --- a/apps/expo/src/App.tsx +++ b/apps/expo/src/App.tsx @@ -59,6 +59,7 @@ export function App() { boxShadow="$raised" maxW={[null, null, '480px']} p={[4, null, 6]} + testID="card" w="100%" > @@ -72,6 +73,7 @@ export function App() { onChangeText={setName} px={3} py={2} + testID="name" value={name} /> @@ -88,6 +90,7 @@ export function App() { bg="#5a44ff" className={button} onPress={() => setCount(count + 1)} + testID="count" > Pressed {count} times @@ -98,6 +101,7 @@ export function App() { border="1px solid $border" className={button} onPress={() => setTheme(theme === 'dark' ? 'light' : 'dark')} + testID="theme" > Switch to {theme === 'dark' ? 'light' : 'dark'} diff --git a/bun.lock b/bun.lock index 699ed7003..62ce0b80a 100644 --- a/bun.lock +++ b/bun.lock @@ -27,10 +27,13 @@ "version": "0.1.0", "dependencies": { "@devup-ui/react": "workspace:^", + "@expo/metro-runtime": "~58.0.17", "expo": "~58.0.26", "react": "^19.3.1", + "react-dom": "^19.3.1", "react-native": "0.88.1", "react-native-reanimated": "~4.7.1", + "react-native-web": "~0.21.4", "react-native-worklets": "0.13.0", }, "devDependencies": { @@ -1262,6 +1265,8 @@ "@expo/metro-file-map": ["@expo/metro-file-map@58.0.6", "", { "dependencies": { "2g": "^1.0.1", "debug": "^4.3.4", "fb-watchman": "^2.0.2", "invariant": "^2.2.4", "jest-worker": "^29.7.0", "walker": "^1.0.8" } }, "sha512-+kPFI328BSUxpK7OO0kM31NQlYG/z7WOTISbPEuY4fMZxmN/nLnmJIDNG8NTtM5ZHXlNPqgjRvdukxtsBEkvuw=="], + "@expo/metro-runtime": ["@expo/metro-runtime@58.0.17", "", { "dependencies": { "@expo/log-box": "^58.0.15", "anser": "^1.4.9", "pretty-format": "^29.7.0", "stacktrace-parser": "^0.1.10", "whatwg-fetch": "^3.0.0" }, "peerDependencies": { "expo": "*", "react": "*", "react-dom": "*", "react-native": "*" }, "optionalPeers": ["react-dom"] }, "sha512-onJvBi90uwLj69F1EaVPmPeds/ndxc2/vNc0Z5n8rqcMKToMyLxGaL3Be6yf7OVjPhGvoDj+LWQ/IcbpN1hnoA=="], + "@expo/modules-macros-linux-arm64": ["@expo/modules-macros-linux-arm64@0.33.0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-5F4L/IJThOBq3oRo9NB5BI4+Od8K2YDTbU+2IHgsnXsrTc5icQtOlLwHOEfExghjo0PHCXGap4zprfOKvtANxw=="], "@expo/modules-macros-linux-x64": ["@expo/modules-macros-linux-x64@0.33.0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-G3kxfmMpH7BDtoeBVeJA4vh5O3kQ3wmjmSfDremRBWENHKwHJXTOsyerLQqkJC39oPKCuXgXhzvp+/5qy+DyvA=="], @@ -2502,6 +2507,8 @@ "cosmiconfig": ["cosmiconfig@7.1.0", "", { "dependencies": { "@types/parse-json": "^4.0.0", "import-fresh": "^3.2.1", "parse-json": "^5.0.0", "path-type": "^4.0.0", "yaml": "^1.10.0" } }, "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA=="], + "cross-fetch": ["cross-fetch@3.2.0", "", { "dependencies": { "node-fetch": "^2.7.0" } }, "sha512-Q+xVJLoGOeIMXZmbUK4HYk+69cQH6LudR0Vu/pRm2YlU/hDV9CiS0gKUMaWY5f2NeUH9C1nV3bsTlCo0FsTV1Q=="], + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], "css-background-parser": ["css-background-parser@0.1.0", "", {}, "sha512-2EZLisiZQ+7m4wwur/qiYJRniHX4K5Tc9w93MT3AS0WS1u5kaZ4FKXlOTBhOjc+CgEgPiGY+fX1yWD8UwpEqUA=="], @@ -2512,6 +2519,8 @@ "css-gradient-parser": ["css-gradient-parser@0.0.17", "", {}, "sha512-w2Xy9UMMwlKtou0vlRnXvWglPAceXCTtcmVSo8ZBUvqCV5aXEFP/PC6d+I464810I9FT++UACwTD5511bmGPUg=="], + "css-in-js-utils": ["css-in-js-utils@3.1.0", "", { "dependencies": { "hyphenate-style-name": "^1.0.3" } }, "sha512-fJAcud6B3rRu+KHYk+Bwf+WFL2MDCJJ1XG9x137tJQ0xYxor7XziQtuGFbWNdqrvF4Tk26O3H73nfVqXt/fW1A=="], + "css-mediaquery": ["css-mediaquery@0.1.2", "", {}, "sha512-COtn4EROW5dBGlE/4PiKnh6rZpAPxDeFLaEEwt4i10jpDMFt2EhQGS79QmmrO+iKCHv0PU/HrOWEhijFd1x99Q=="], "css-to-react-native": ["css-to-react-native@3.2.0", "", { "dependencies": { "camelize": "^1.0.0", "css-color-keywords": "^1.0.0", "postcss-value-parser": "^4.0.2" } }, "sha512-e8RKaLXMOFii+02mOlqwjbD00KSEKqblnpO9e++1aXS1fPQOpS1YoqdVHBqPjHNoxeF2mimzVqawm2KCbEdtHQ=="], @@ -2744,6 +2753,10 @@ "fb-watchman": ["fb-watchman@2.0.4", "", { "dependencies": { "bser": "2.1.2" } }, "sha512-tGQtaoYisPDriJBN0mT5yZSyNETnJGA1gTYxaVRAE5KUO3LI9kPUc9WIu8JXcxaIci+faIKlzXqXyPgrmubtBQ=="], + "fbjs": ["fbjs@3.0.5", "", { "dependencies": { "cross-fetch": "^3.1.5", "fbjs-css-vars": "^1.0.0", "loose-envify": "^1.0.0", "object-assign": "^4.1.0", "promise": "^7.1.1", "setimmediate": "^1.0.5", "ua-parser-js": "^1.0.35" } }, "sha512-ztsSx77JBtkuMrEypfhgc3cI0+0h+svqeie7xHbh1k/IKdcydnvadp/mUaGgjAOXQmQSxsqgaRhS3q9fy+1kxg=="], + + "fbjs-css-vars": ["fbjs-css-vars@1.0.2", "", {}, "sha512-b2XGFAFdWZWg0phtAWLHCk836A1Xann+I+Dgd3Gk64MHKZO44FfoD1KxyvbSh0qZsIoXQGGlVztIY+oitJPpRQ=="], + "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], "fetch-nodeshim": ["fetch-nodeshim@0.4.10", "", {}, "sha512-m6I8ALe4L4XpdETy7MJZWs6L1IVMbjs99bwbpIKphxX+0CTns4IKDWJY0LWfr4YsFjfg+z1TjzTMU8lKl8rG0w=="], @@ -2848,6 +2861,8 @@ "husky": ["husky@9.1.7", "", { "bin": { "husky": "bin.js" } }, "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA=="], + "hyphenate-style-name": ["hyphenate-style-name@1.1.0", "", {}, "sha512-WDC/ui2VVRrz3jOVi+XtjqkDjiVjTtFaAGiW37k6b+ohyQ5wYDOGkvCZa8+H0nx3gyvv0+BST9xuOgIyGQ00gw=="], + "icu-minify": ["icu-minify@4.15.2", "", { "dependencies": { "@formatjs/icu-messageformat-parser": "^3.4.0" } }, "sha512-IsgBR7/1RBkYWUqP2wS+vE9BBBfH4HjNjDbSPF3uK2Jjlzlsd7R+loUhjEEUySU6tjGmUIuft7w3qp7PI0KkXA=="], "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], @@ -2868,6 +2883,8 @@ "inline-style-parser": ["inline-style-parser@0.2.9", "", {}, "sha512-IttN8BqKLxzUrnTqHI+/hwAJQItBAUjdoHERCDv+oOuX48VP6bzW8+QjOXSfoevzq3YrYAwX1uLHp8TqO9yIeg=="], + "inline-style-prefixer": ["inline-style-prefixer@7.0.1", "", { "dependencies": { "css-in-js-utils": "^3.1.0" } }, "sha512-lhYo5qNTQp3EvSSp3sRvXMbVQTLrvGV6DycRMJ5dm2BLMiJ30wpXKdDdgX+GmJZ5uQMucwRKHamXSst3Sj/Giw=="], + "intl-messageformat": ["intl-messageformat@12.2.0", "", { "dependencies": { "@formatjs/fast-memoize": "3.1.7", "@formatjs/icu-messageformat-parser": "3.5.23" } }, "sha512-zFzW80iYSSJm4V185g3ItJQ96lBZ2RDO8O8qmRiPAAVKYXJeHfDQN2ITdtLlV+CjSi9Lo7zVW9xGt9CPCx7J6A=="], "invariant": ["invariant@2.2.4", "", { "dependencies": { "loose-envify": "^1.0.0" } }, "sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA=="], @@ -3228,6 +3245,8 @@ "node-addon-api": ["node-addon-api@7.1.1", "", {}, "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ=="], + "node-fetch": ["node-fetch@2.7.0", "", { "dependencies": { "whatwg-url": "^5.0.0" }, "peerDependencies": { "encoding": "^0.1.0" }, "optionalPeers": ["encoding"] }, "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A=="], + "node-forge": ["node-forge@1.4.3", "", {}, "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g=="], "node-int64": ["node-int64@0.4.0", "", {}, "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw=="], @@ -3404,6 +3423,8 @@ "react-native-reanimated": ["react-native-reanimated@4.7.2", "", { "dependencies": { "react-native-is-edge-to-edge": "^1.3.1", "semver": "^7.7.3" }, "peerDependencies": { "react": "*", "react-native": "0.86 - 0.88", "react-native-worklets": "0.13.x" } }, "sha512-dlPMG+dKKbcumR8k2C8wApqVsrCevINxEki3I6t0S/6LPqa639unbwRn85yu1yhtC9oJI94xk+ycdGuEGdH4Gw=="], + "react-native-web": ["react-native-web@0.21.4", "", { "dependencies": { "@babel/runtime": "^7.18.6", "@react-native/normalize-colors": "^0.74.1", "fbjs": "^3.0.4", "inline-style-prefixer": "^7.0.1", "memoize-one": "^6.0.0", "nullthrows": "^1.1.1", "postcss-value-parser": "^4.2.0", "styleq": "^0.1.3" }, "peerDependencies": { "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" } }, "sha512-77B6KlalB4osNIck91TNFixPkYPsTbuNEvw8P7IV+4v4/5wZSBRKZnw0Zhx6YjuauDTz71gc8IW+fVhcBMjr5A=="], + "react-native-worklets": ["react-native-worklets@0.13.0", "", { "dependencies": { "@babel/generator": "^7.27.1", "@babel/plugin-transform-arrow-functions": "^7.27.1", "@babel/plugin-transform-class-properties": "^7.28.6", "@babel/plugin-transform-classes": "^7.28.6", "@babel/plugin-transform-nullish-coalescing-operator": "^7.28.6", "@babel/plugin-transform-optional-chaining": "^7.28.6", "@babel/plugin-transform-shorthand-properties": "^7.27.1", "@babel/plugin-transform-template-literals": "^7.27.1", "@babel/plugin-transform-unicode-regex": "^7.27.1", "@babel/preset-typescript": "^7.28.5", "@babel/traverse": "^7.27.1", "@babel/types": "^7.27.1", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "semver": "^7.7.4", "whatwg-fetch": "^3.6.20" }, "peerDependencies": { "@babel/core": "*", "@react-native/metro-config": "*", "react": "*", "react-native": "0.86 - 0.88" } }, "sha512-1OrhAeAKaZF4XrBa4YbPQbKzNOpjh52HDlId8e6ete1OCHNdAlrQHzG4gznJ225EAj3dgQXHViJvK51M9B52jQ=="], "react-refresh": ["react-refresh@0.14.2", "", {}, "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA=="], @@ -3516,6 +3537,8 @@ "set-blocking": ["set-blocking@2.0.0", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="], + "setimmediate": ["setimmediate@1.0.5", "", {}, "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="], + "setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="], "sharp": ["sharp@0.35.5", "", { "dependencies": { "@img/colour": "^1.1.0", "detect-libc": "^2.1.2", "semver": "^7.8.5" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.35.5", "@img/sharp-darwin-x64": "0.35.5", "@img/sharp-freebsd-wasm32": "0.35.5", "@img/sharp-libvips-darwin-arm64": "1.3.4", "@img/sharp-libvips-darwin-x64": "1.3.4", "@img/sharp-libvips-linux-arm": "1.3.4", "@img/sharp-libvips-linux-arm64": "1.3.4", "@img/sharp-libvips-linux-ppc64": "1.3.4", "@img/sharp-libvips-linux-riscv64": "1.3.4", "@img/sharp-libvips-linux-s390x": "1.3.4", "@img/sharp-libvips-linux-x64": "1.3.4", "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", "@img/sharp-libvips-linuxmusl-x64": "1.3.4", "@img/sharp-linux-arm": "0.35.5", "@img/sharp-linux-arm64": "0.35.5", "@img/sharp-linux-ppc64": "0.35.5", "@img/sharp-linux-riscv64": "0.35.5", "@img/sharp-linux-s390x": "0.35.5", "@img/sharp-linux-x64": "0.35.5", "@img/sharp-linuxmusl-arm64": "0.35.5", "@img/sharp-linuxmusl-x64": "0.35.5", "@img/sharp-webcontainers-wasm32": "0.35.5", "@img/sharp-win32-arm64": "0.35.5", "@img/sharp-win32-ia32": "0.35.5", "@img/sharp-win32-x64": "0.35.5" }, "peerDependencies": { "@types/node": "*" }, "optionalPeers": ["@types/node"] }, "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g=="], @@ -3592,7 +3615,7 @@ "styled-jsx": ["styled-jsx@5.1.6", "", { "dependencies": { "client-only": "0.0.1" }, "peerDependencies": { "@babel/core": "*", "babel-plugin-macros": "*", "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" }, "optionalPeers": ["@babel/core", "babel-plugin-macros"] }, "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA=="], - "styleq": ["styleq@0.2.1", "", {}, "sha512-L0TR0NQb+X4/ktDEKmjWyp27gla+LUYi/by5k5SjKXf6/pvZP7wbwEB5J+tqxdFVPgzbsuz+d4RTScO/QZquBw=="], + "styleq": ["styleq@0.1.3", "", {}, "sha512-3ZUifmCDCQanjeej1f6kyl/BeP/Vae5EYkQ9iJfUm/QwZvlgnZzyflqAsAWYURdtea8Vkvswu2GrC57h3qffcA=="], "stylis": ["stylis@4.2.0", "", {}, "sha512-Orov6g6BB1sDfYgzWfTHDOxamtX1bE/zo104Dh9e6fqJ3PooipYyfJ0pUmrZO2wAvO8YbEyeFrkV91XTsGMSrw=="], @@ -3634,6 +3657,8 @@ "toqr": ["toqr@0.1.1", "", {}, "sha512-FWAPzCIHZHnrE/5/w9MPk0kK25hSQSH2IKhYh9PyjS3SG/+IEMvlwIHbhz+oF7xl54I+ueZlVnMjyzdSwLmAwA=="], + "tr46": ["tr46@0.0.3", "", {}, "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="], + "trim-lines": ["trim-lines@3.0.1", "", {}, "sha512-kRj8B+YHZCc9kQYdWfJB2/oUl9rA99qbowYYBtr4ui4mZyAQ2JpvVBd/6U2YloATfqBhBTSMhTpgBHtU0Mf3Rg=="], "trough": ["trough@2.2.0", "", {}, "sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw=="], @@ -3664,6 +3689,8 @@ "typescript-eslint": ["typescript-eslint@8.73.0", "", { "dependencies": { "@typescript-eslint/eslint-plugin": "8.73.0", "@typescript-eslint/parser": "8.73.0", "@typescript-eslint/typescript-estree": "8.73.0", "@typescript-eslint/utils": "8.73.0" }, "peerDependencies": { "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", "typescript": ">=4.8.4 <6.1.0" } }, "sha512-+EnKy9rkYPun4l+kG2bDuYWQ6y1tGVgdR/tY1U9AC6h21CjEwOoc7gsjwe0FXB8uWFzk4QiCFbuRWgX758PiAg=="], + "ua-parser-js": ["ua-parser-js@1.0.41", "", { "bin": { "ua-parser-js": "script/cli.js" } }, "sha512-LbBDqdIC5s8iROCUjMbW1f5dJQTEFB1+KO9ogbvlb3nm9n4YHa5p4KTvFPWvh2Hs8gZMBuiB1/8+pdfe/tDPug=="], + "ufo": ["ufo@1.6.4", "", {}, "sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA=="], "undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="], @@ -3780,6 +3807,8 @@ "web-vitals": ["web-vitals@4.2.4", "", {}, "sha512-r4DIlprAGwJ7YM11VZp4R884m0Vmgr6EAKe3P+kO0PPj3Unqyvv59rczf6UiGcb9Z8QxZVcqKNwv/g0WNdWwsw=="], + "webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], + "webpack": ["webpack@5.112.2", "", { "dependencies": { "@types/estree": "^1.0.8", "@types/json-schema": "^7.0.15", "@webassemblyjs/ast": "^1.14.1", "@webassemblyjs/wasm-edit": "^1.14.1", "@webassemblyjs/wasm-parser": "^1.14.1", "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", "enhanced-resolve": "^5.26.0", "es-module-lexer": "^2.1.0", "events": "^3.2.0", "graceful-fs": "^4.2.11", "mime-db": "^1.54.0", "minimizer-webpack-plugin": "^5.13.0", "schema-utils": "^4.8.1", "tapable": "^2.3.0", "watchpack": "^2.6.3", "webpack-sources": "^3.6.0" }, "peerDependencies": { "webpack-cli": "*" }, "optionalPeers": ["webpack-cli"], "bin": { "webpack": "bin/webpack.js" } }, "sha512-B2tp1LI9D8GVpPDqprdt12ukTkXXahj9MzqSWJq4faSPgOUM7CdZaGAB6HrL/8E6UwbBpdj4vzWDbKoFnVoU6g=="], "webpack-sources": ["webpack-sources@3.7.1", "", {}, "sha512-mcxs7A2LsEdwsNqQburqS4QHPR2Ca3NGplUakn6J5GPQvnVZ4oD4IM4FJcT3f8AVN2e2EsjuIVxKj4rorHvyuQ=="], @@ -3790,6 +3819,8 @@ "whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="], + "whatwg-url": ["whatwg-url@5.0.0", "", { "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" } }, "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw=="], + "whatwg-url-minimum": ["whatwg-url-minimum@0.2.0", "", {}, "sha512-BtjXU1caNcCFfETP2DhqSeVPfRDl2MTUitI107RE34rJXjR/izfUtR5IoTFOK1WqjNLXbbeqaCH/mQAOLjpc8g=="], "which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], @@ -4406,6 +4437,8 @@ "@stylexjs/postcss-plugin/@babel/core": ["@babel/core@7.29.13", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.13", "@babel/helper-compilation-targets": "^7.29.13", "@babel/helper-module-transforms": "^7.29.13", "@babel/helpers": "^7.29.13", "@babel/parser": "^7.29.13", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.13", "@babel/types": "^7.29.11", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw=="], + "@stylexjs/stylex/styleq": ["styleq@0.2.1", "", {}, "sha512-L0TR0NQb+X4/ktDEKmjWyp27gla+LUYi/by5k5SjKXf6/pvZP7wbwEB5J+tqxdFVPgzbsuz+d4RTScO/QZquBw=="], + "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" }, "bundled": true }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="], @@ -4490,6 +4523,8 @@ "fast-glob/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], + "fbjs/promise": ["promise@7.3.1", "", { "dependencies": { "asap": "~2.0.3" } }, "sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg=="], + "finalhandler/debug": ["debug@2.6.9", "", { "dependencies": { "ms": "2.0.0" } }, "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA=="], "finalhandler/encodeurl": ["encodeurl@1.0.4", "", {}, "sha512-ImAQpWtQZKdkUxvj9CMNzB8M4IGg0DkRTZzmOHqgVFrf71JDmUacbt+iKljfIpD2yHcxI+HR76d8bwvdvtSvGA=="], @@ -4608,6 +4643,10 @@ "react-native/ws": ["ws@7.5.14", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": "^5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug=="], + "react-native-web/@react-native/normalize-colors": ["@react-native/normalize-colors@0.74.89", "", {}, "sha512-qoMMXddVKVhZ8PA1AbUCk83trpd6N+1nF2A6k1i6LsQObyS92fELuk8kU/lQs6M7BsMHwqyLCpQJ1uFgNvIQXg=="], + + "react-native-web/memoize-one": ["memoize-one@6.0.0", "", {}, "sha512-rkpe71W0N0c0Xz6QD0eJETuWAJGnJ9afsl1srmwPrI+yBCkge5EycXXbYRyvL29zZVUWQCY7InPRCv3GDXuZNw=="], + "recast/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], "redent/strip-indent": ["strip-indent@3.0.0", "", { "dependencies": { "min-indent": "^1.0.0" } }, "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ=="], @@ -6228,6 +6267,8 @@ "@stylexjs/nextjs-plugin/@stylexjs/babel-plugin/@stylexjs/stylex": ["@stylexjs/stylex@0.11.1", "", { "dependencies": { "css-mediaquery": "^0.1.2", "invariant": "^2.2.4", "styleq": "0.2.1" } }, "sha512-1OofsiCP2DYV+Cw/iIuHYTAJRy34TtxQt0FDuQGTnNH915hb6NkPmX6iPa++9t4KP3HWR9oVRmAHkpP58BIYbw=="], + "@stylexjs/open-props/@stylexjs/stylex/styleq": ["styleq@0.2.1", "", {}, "sha512-L0TR0NQb+X4/ktDEKmjWyp27gla+LUYi/by5k5SjKXf6/pvZP7wbwEB5J+tqxdFVPgzbsuz+d4RTScO/QZquBw=="], + "@stylexjs/postcss-plugin/@babel/core/@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], "@stylexjs/postcss-plugin/@babel/core/@babel/helper-compilation-targets": ["@babel/helper-compilation-targets@7.29.13", "", { "dependencies": { "@babel/compat-data": "^7.29.7", "@babel/helper-validator-option": "^7.29.7", "browserslist": "^4.24.0", "lru-cache": "^5.1.1", "semver": "^6.3.1" } }, "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w=="], @@ -7114,6 +7155,8 @@ "@stylexjs/nextjs-plugin/@babel/core/@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="], + "@stylexjs/nextjs-plugin/@stylexjs/babel-plugin/@stylexjs/stylex/styleq": ["styleq@0.2.1", "", {}, "sha512-L0TR0NQb+X4/ktDEKmjWyp27gla+LUYi/by5k5SjKXf6/pvZP7wbwEB5J+tqxdFVPgzbsuz+d4RTScO/QZquBw=="], + "@stylexjs/postcss-plugin/@babel/core/@babel/code-frame/js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "@stylexjs/postcss-plugin/@babel/core/@babel/helper-compilation-targets/browserslist": ["browserslist@4.29.6", "", { "dependencies": { "baseline-browser-mapping": "^2.11.37", "caniuse-lite": "^1.0.30001826", "electron-to-chromium": "^1.5.486", "node-releases": "^2.0.64", "update-browserslist-db": "^1.4.0" }, "bin": { "browserslist": "cli.js" } }, "sha512-CmVVIQ3RVc5HxYEc9X84GvxK/C8C1wH8TlKAiO7uTxF8PDwt7r8t9Qk3J9NkMOVzX5O/HbLv3yzxZg9HPrnI9w=="], diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md index 62ce77ca8..8a42d85f3 100644 --- a/packages/metro-plugin/README.md +++ b/packages/metro-plugin/README.md @@ -310,6 +310,19 @@ const Card = styled.View({ padding: 8, backgroundColor: '$surface' }) `runtime: false` they are build errors. - Any other import stays on the package. +## Expo web + +On the web, Expo bundles the app with Metro through +[react-native-web](https://necolas.github.io/react-native-web/), and this +plugin compiles it as for iOS and Android: the same `StyleSheet` objects, +which react-native-web turns into CSS. `_web` blocks apply there, and +`_hover` and `_focus` follow the mouse and the keyboard. Install the web +dependencies Expo asks for (`npx expo install react-dom react-native-web +@expo/metro-runtime`) and add `"web"` to the `platforms` of app.json. + +A site that is not an Expo app keeps using the Vite, Next.js, Webpack, +Rsbuild or Bun plugin, which output atomic CSS instead. + ## Limits of this version Only styles the build can decide are supported: literals, values read at From 6fd7158706b4ad8b7a0c7c230792be5f6d8909b8 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 15:56:35 +0900 Subject: [PATCH 4/6] 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, From 015bcfee1eb8b676a10bd1d26b63d0159442efe3 Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Sun, 29 Nov 2026 02:42:28 +0900 Subject: [PATCH 5/6] feat(native): type the theme and React Native props of each component (#1052) Metro writes df/theme.d.ts (the tokens of devup.json) and df/native.d.ts when it reads the config, as the web plugins do. native.d.ts imports the new @devup-ui/react/native/types, which fills the new DevupElementProps augmentation point so each component takes the props of the React Native component it renders. Web types are unchanged. The Expo example now type-checks in CI. Co-authored-by: Claude Opus 5.5 --- .changepacks/changepack_log_metro_types.json | 7 +++ .../changepack_log_react_native_types.json | 7 +++ apps/expo/package.json | 3 +- packages/metro-plugin/README.md | 20 +++++++ .../metro-plugin/src/__tests__/plugin.test.ts | 54 ++++++++++++++++++- packages/metro-plugin/src/plugin.ts | 16 +++++- packages/metro-plugin/src/types.ts | 44 +++++++++++++++ packages/react/package.json | 7 ++- packages/react/rollup.types.config.mjs | 4 +- packages/react/src/index.ts | 2 +- packages/react/src/native/types.d.ts | 39 ++++++++++++++ packages/react/src/types/props/index.ts | 20 ++++++- packages/react/type-tests/native/app.tsx | 28 ++++++++++ .../react/type-tests/native/tsconfig.json | 11 ++++ .../react/type-tests/published/native.tsx | 16 ++++++ .../type-tests/published/tsconfig.native.json | 4 ++ 16 files changed, 271 insertions(+), 11 deletions(-) create mode 100644 .changepacks/changepack_log_metro_types.json create mode 100644 .changepacks/changepack_log_react_native_types.json create mode 100644 packages/metro-plugin/src/types.ts create mode 100644 packages/react/src/native/types.d.ts create mode 100644 packages/react/type-tests/native/app.tsx create mode 100644 packages/react/type-tests/native/tsconfig.json create mode 100644 packages/react/type-tests/published/native.tsx create mode 100644 packages/react/type-tests/published/tsconfig.native.json diff --git a/.changepacks/changepack_log_metro_types.json b/.changepacks/changepack_log_metro_types.json new file mode 100644 index 000000000..f255a5bc0 --- /dev/null +++ b/.changepacks/changepack_log_metro_types.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/metro-plugin/package.json": "Patch" + }, + "note": "Write `df/theme.d.ts` (the tokens of devup.json) and `df/native.d.ts` (React Native props for each component) when Metro reads the config, with a `distDir` option, as the web plugins do.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_react_native_types.json b/.changepacks/changepack_log_react_native_types.json new file mode 100644 index 000000000..ac8e96aa9 --- /dev/null +++ b/.changepacks/changepack_log_react_native_types.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/react/package.json": "Patch" + }, + "note": "Add `@devup-ui/react/native/types`, which types each component as the React Native component it renders (`Box` takes `ViewProps`, `Button` takes `PressableProps`, ...) through the new `DevupElementProps` augmentation point. Web types are unchanged.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/apps/expo/package.json b/apps/expo/package.json index 04463f3bc..0f4dea58c 100644 --- a/apps/expo/package.json +++ b/apps/expo/package.json @@ -7,7 +7,8 @@ "start": "expo start", "export": "expo export --platform ios --platform android --platform web --no-bytecode --source-maps", "check": "node check-bundle.mjs", - "check:web": "node check-web.mjs" + "check:web": "node check-web.mjs", + "typecheck": "bun ../../node_modules/@typescript/native/bin/tsc --noEmit" }, "dependencies": { "@devup-ui/react": "workspace:^", diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md index 8a42d85f3..fda3842db 100644 --- a/packages/metro-plugin/README.md +++ b/packages/metro-plugin/README.md @@ -67,6 +67,8 @@ withDevupUI(config, { package: '@devup-ui/react', // devup.json, from the project root. Default: 'devup.json' devupFile: 'devup.json', + // Where the theme and React Native types are written. Default: 'df' + distDir: 'df', // Packages in node_modules that ship uncompiled Devup UI. Default: [] include: [], // Whether styles that need the React Native runtime may import it. @@ -80,6 +82,24 @@ withDevupUI(config, { }) ``` +## TypeScript + +When Metro reads the config, the plugin writes two declaration files into +`df` (the `distDir` option), which ignores itself in git: + +- `theme.d.ts`: the tokens of devup.json, as the web plugins write them, so + `bg="$primary"` and `typography="title"` complete and check. +- `native.d.ts`: it imports `@devup-ui/react/native/types`, so each + component takes the props of the React Native component it renders: + `Box`, `Flex`, `VStack`, `Center` and `Grid` take `View`'s (`onLayout`, + `testID`, ...), `Text` takes `Text`'s, `Image` takes `Image`'s, `Input` takes + `TextInput`'s (`onChangeText`, ...) and `Button` takes `Pressable`'s + (`onPress`, ...). Each also takes `className`, for `css()`. HTML props that + React Native lacks, such as `href` or `onInput`, become type errors. + +A tsconfig that names its files (`include`) must list `df/*.d.ts`. Expo's +default tsconfig includes every file of the project. + ## Themes `$` tokens of devup.json (colors, `length` and `shadow`) and `typography` diff --git a/packages/metro-plugin/src/__tests__/plugin.test.ts b/packages/metro-plugin/src/__tests__/plugin.test.ts index 55ecaa4e4..f8fbee424 100644 --- a/packages/metro-plugin/src/__tests__/plugin.test.ts +++ b/packages/metro-plugin/src/__tests__/plugin.test.ts @@ -1,8 +1,24 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test' +import * as pluginUtils from '@devup-ui/plugin-utils' +import { + afterEach, + beforeEach, + describe, + expect, + it, + type Mock, + spyOn, +} from 'bun:test' import { REANIMATED_PACKAGE, @@ -11,17 +27,22 @@ import { withDevupUI, } from '../plugin' import { readSettings, SETTINGS_ENV } from '../settings' +import { NATIVE_TYPES } from '../types' +const wasm = pluginUtils.loadCompiler('wasm') let root: string let previous: string | undefined +let selection: Mock beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'devup-metro-plugin-')) previous = process.env[SETTINGS_ENV] delete process.env[SETTINGS_ENV] + selection = spyOn(pluginUtils, 'loadCompiler').mockReturnValue(wasm) }) afterEach(() => { + selection.mockRestore() rmSync(root, { recursive: true, force: true }) if (previous === undefined) delete process.env[SETTINGS_ENV] else process.env[SETTINGS_ENV] = previous @@ -106,6 +127,35 @@ describe('withDevupUI', () => { devupFile: join(root, 'theme', 'devup.json'), engine: 'wasm', }) + expect(selection.mock.calls).toEqual([['wasm']]) + }) + + it('writes the types of the theme and of React Native into df', () => { + write( + 'devup.json', + JSON.stringify({ theme: { colors: { default: { primary: '#000' } } } }), + ) + withDevupUI({ + projectRoot: root, + transformer: { babelTransformerPath: '/up.js' }, + }) + expect(readFileSync(join(root, 'df', 'theme.d.ts'), 'utf-8')).toContain( + 'primary', + ) + expect(readFileSync(join(root, 'df', 'native.d.ts'), 'utf-8')).toBe( + NATIVE_TYPES, + ) + expect(readFileSync(join(root, 'df', '.gitignore'), 'utf-8')).toBe('*') + }) + + it('writes the types into the distDir option', () => { + withDevupUI( + { projectRoot: root, transformer: { babelTransformerPath: '/up.js' } }, + { distDir: 'types/devup' }, + ) + expect(existsSync(join(root, 'types', 'devup', 'theme.d.ts'))).toBe(true) + expect(existsSync(join(root, 'types', 'devup', 'native.d.ts'))).toBe(true) + expect(existsSync(join(root, 'df'))).toBe(false) }) it('resolves the upstreamTransformer option from the project root', () => { diff --git a/packages/metro-plugin/src/plugin.ts b/packages/metro-plugin/src/plugin.ts index 062ea148e..70bac22e6 100644 --- a/packages/metro-plugin/src/plugin.ts +++ b/packages/metro-plugin/src/plugin.ts @@ -13,6 +13,7 @@ import { readSettings, writeSettings, } from './settings' +import { writeTypes } from './types' export interface DevupUIMetroPluginOptions { /** @@ -24,6 +25,12 @@ export interface DevupUIMetroPluginOptions { package?: string /** Path of devup.json, from the project root. Defaults to `devup.json`. */ devupFile?: string + /** + * Where the TypeScript declarations are written, from the project root: + * the theme's tokens and the React Native props of each component. + * Defaults to `df`, as in the other plugins. + */ + distDir?: string /** * Packages in `node_modules` whose files are compiled as well: a library * that ships Devup UI components uncompiled. Each name matches that whole @@ -127,7 +134,8 @@ function upstreamTransformer( * Compile Devup UI for React Native in Metro: the config's Babel transformer * becomes Devup UI's, which compiles each file that imports Devup UI and then * hands the code to the transformer the config had (Expo's or React - * Native's). + * Native's). The TypeScript declarations of the theme and of the React Native + * props are written into `distDir`. * * ```js * // metro.config.js @@ -159,6 +167,12 @@ export function withDevupUI( engine: options.engine, } writeSettings(settings) + writeTypes({ + distDir: resolve(projectRoot, options.distDir ?? 'df'), + devupFile: settings.devupFile, + package: settings.package, + engine: settings.engine, + }) return { ...config, transformer: { diff --git a/packages/metro-plugin/src/types.ts b/packages/metro-plugin/src/types.ts new file mode 100644 index 000000000..3013e8349 --- /dev/null +++ b/packages/metro-plugin/src/types.ts @@ -0,0 +1,44 @@ +import { mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' + +import { + createThemeInterfaceArgs, + type DevupEngine, + loadCompiler, + loadDevupConfigSync, +} from '@devup-ui/plugin-utils' + +/** + * `native.d.ts`: it imports the declarations that type each component of + * `@devup-ui/react` as the React Native component it renders + */ +export const NATIVE_TYPES = "import '@devup-ui/react/native/types'\n" + +/** What the types of a project are written from */ +export interface TypesOptions { + /** The directory written, absolute */ + readonly distDir: string + /** devup.json, absolute */ + readonly devupFile: string + /** The package Devup UI is imported from */ + readonly package: string + readonly engine?: DevupEngine +} + +/** + * Write the TypeScript declarations of the project into `distDir`, as the web + * plugins do: `theme.d.ts`, the tokens of devup.json, and `native.d.ts`, which + * types the components for React Native. The directory ignores itself in git. + */ +export function writeTypes(options: TypesOptions): void { + const compiler = loadCompiler(options.engine) + compiler.registerTheme(loadDevupConfigSync(options.devupFile).theme ?? {}) + mkdirSync(options.distDir, { recursive: true }) + writeFileSync(join(options.distDir, '.gitignore'), '*', 'utf-8') + writeFileSync( + join(options.distDir, 'theme.d.ts'), + compiler.getThemeInterface(...createThemeInterfaceArgs(options.package)), + 'utf-8', + ) + writeFileSync(join(options.distDir, 'native.d.ts'), NATIVE_TYPES, 'utf-8') +} diff --git a/packages/react/package.json b/packages/react/package.json index 6d2b468b0..759ae00b0 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -21,8 +21,8 @@ "scripts": { "lint": "eslint && bun ../../node_modules/@typescript/native/bin/tsc --noEmit && bun run test:types", "build": "bun run test:types && bun ../../node_modules/@typescript/native/bin/tsc && vite build && rollup -c rollup.types.config.mjs && bun run test:published-types", - "test:types": "bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/tsconfig.json", - "test:published-types": "bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.bundler.json && bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.node16.json" + "test:types": "bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/tsconfig.json && bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/native/tsconfig.json", + "test:published-types": "bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.bundler.json && bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.node16.json && bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.native.json" }, "publishConfig": { "access": "public" @@ -79,6 +79,9 @@ "types": "./dist/native/index.d.ts", "import": "./dist/native/index.js", "require": "./dist/native/index.cjs" + }, + "./native/types": { + "types": "./dist/native/types.d.ts" } }, "files": [ diff --git a/packages/react/rollup.types.config.mjs b/packages/react/rollup.types.config.mjs index ca2bcc427..c54a74e35 100644 --- a/packages/react/rollup.types.config.mjs +++ b/packages/react/rollup.types.config.mjs @@ -20,8 +20,8 @@ const entries = { } const shared = '_shared' -/** Declarations written by hand, which ambiently declare modules and stay as they are */ -const ambient = /^compat\/(?!index\.)[^/]+\.d\.ts$/ +/** Declarations written by hand, which declare or augment modules and stay as they are */ +const ambient = /^(compat\/(?!index\.)[^/]+|native\/types)\.d\.ts$/ function files(directory) { return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 1de5d171a..1afc6989f 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -9,7 +9,7 @@ export { Text } from './components/Text' export { ThemeScript } from './components/ThemeScript' export { VStack } from './components/VStack' export { useTheme } from './hooks/use-theme' -export type { DevupProps } from './types/props' +export type { DevupElementProps, DevupProps } from './types/props' export type { ResponsiveValue } from './types/responsive-value' export type { DevupCustomShorthands } from './types/shorthand' export type { DevupTheme } from './types/theme' diff --git a/packages/react/src/native/types.d.ts b/packages/react/src/native/types.d.ts new file mode 100644 index 000000000..eb30b594f --- /dev/null +++ b/packages/react/src/native/types.d.ts @@ -0,0 +1,39 @@ +/** + * Types `@devup-ui/react` for React Native: each component takes the props of + * the React Native component the build renders it as, instead of those of the + * HTML element it renders on the web. `@devup-ui/metro-plugin` imports this + * file from `/native.d.ts`; to opt in by hand, import it from a + * declaration file of the project: + * + * ```ts + * import '@devup-ui/react/native/types' + * ``` + */ +import type { + ImageProps, + PressableProps, + TextInputProps, + TextProps, + ViewProps, +} from 'react-native' + +/** What every element takes besides its component's props */ +interface DevupNativeElementProps { + /** The class of `css()`, whose styles the build gives the element */ + className?: string +} + +declare module '@devup-ui/react' { + interface DevupElementProps { + /** `Box`, `Flex`, `VStack`, `Center` and `Grid`: a `View` */ + div: ViewProps & DevupNativeElementProps + /** `Text`: a `Text` */ + span: TextProps & DevupNativeElementProps + /** `Image`: an `Image` */ + img: ImageProps & DevupNativeElementProps + /** `Input`: a `TextInput` */ + input: TextInputProps & DevupNativeElementProps + /** `Button`: a `Pressable` */ + button: PressableProps & DevupNativeElementProps + } +} diff --git a/packages/react/src/types/props/index.ts b/packages/react/src/types/props/index.ts index c2646b9b5..043bedb09 100644 --- a/packages/react/src/types/props/index.ts +++ b/packages/react/src/types/props/index.ts @@ -63,12 +63,28 @@ type DevupDefaultIntrinsicPropConflicts = | 'width' | keyof DevupCustomShorthands +/** + * The props a component takes, by the HTML element it renders on the web, in + * place of that element's: empty on the web, and filled by + * `@devup-ui/react/native/types` with the props of the React Native component + * each renders on React Native (`div` a `View`, `span` a `Text`, ...). + */ +// biome-ignore lint/suspicious/noEmptyInterface: public module augmentation point for React Native. +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface DevupElementProps {} + +/** The props of the element `T` a component renders */ +export type DevupIntrinsicProps = + T extends keyof DevupElementProps + ? DevupElementProps[T] + : React.ComponentProps + // Component declarations put this overload first for fast resolution and last // so Parameters keeps describing the default element. export type DevupDefaultComponentMergedProps< T extends keyof React.JSX.IntrinsicElements, -> = Omit, DevupDefaultIntrinsicPropConflicts> & { - props?: FilterChildren> +> = Omit, DevupDefaultIntrinsicPropConflicts> & { + props?: FilterChildren> } & DevupComponentProps export type DevupComponentBaseProps = diff --git a/packages/react/type-tests/native/app.tsx b/packages/react/type-tests/native/app.tsx new file mode 100644 index 000000000..118bdb76d --- /dev/null +++ b/packages/react/type-tests/native/app.tsx @@ -0,0 +1,28 @@ +// The components typed for React Native (`@devup-ui/react/native/types`): +// each takes the props of the React Native component it renders, and its +// style props as on the web +import { Box, Button, css, Flex, Image, Input, Text } from '@devup-ui/react' + +export const app = ( + {}} testID="card"> + + {}}> + title + + + text} + secureTextEntry + /> + + + +) + +// @ts-expect-error a View has no href +export const link = +// @ts-expect-error a TextInput reports its text with onChangeText +export const input = {}} /> diff --git a/packages/react/type-tests/native/tsconfig.json b/packages/react/type-tests/native/tsconfig.json new file mode 100644 index 000000000..ecdf8f0c4 --- /dev/null +++ b/packages/react/type-tests/native/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "paths": { + "@devup-ui/react": ["../../src/index.ts"], + "@devup-ui/react/*": ["../../src/*"] + } + }, + "files": ["../../src/native/types.d.ts", "app.tsx"], + "include": [] +} diff --git a/packages/react/type-tests/published/native.tsx b/packages/react/type-tests/published/native.tsx new file mode 100644 index 000000000..a6e001e12 --- /dev/null +++ b/packages/react/type-tests/published/native.tsx @@ -0,0 +1,16 @@ +// Type-checks a React Native project against the published declarations: the +// import `@devup-ui/metro-plugin` writes types each component as the React +// Native component it renders +import '@devup-ui/react/native/types' + +import { Box, Button, Input } from '@devup-ui/react' + +export const app = ( + {}} p={2}> + text} /> +