diff --git a/.changepacks/changepack_log_react_native_pressed.json b/.changepacks/changepack_log_react_native_pressed.json
new file mode 100644
index 000000000..9ed03be7e
--- /dev/null
+++ b/.changepacks/changepack_log_react_native_pressed.json
@@ -0,0 +1,8 @@
+{
+ "changes": {
+ "bindings/devup-ui-binding/package.json": "Patch",
+ "bindings/devup-ui-wasm/package.json": "Patch"
+ },
+ "note": "`codeExtractNative` compiles press styles for React Native (part of #411): `_active` and its React Native name `_pressed` make the element a `Pressable` (a `Box`, `Flex`, `Center` or `VStack` becomes one, a `Button` already is) whose `style` is a function of whether it is pressed, `({ pressed }) => [styles.a, pressed && styles.b]`. Press styles combine with responsive values, themes, platforms, orientations and conditions, and work with `runtime: false` as they need no runtime. They are build errors on a `Text`, an `Image` or an `Input`, and with `as`. Web output is unchanged.",
+ "date": "2026-11-21T00:00:00.000Z"
+}
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index 1696a4342..2bf0a8564 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -10,6 +10,7 @@ on:
- feat/napi-binding
- feat/react-native-metro
- feat/react-native-themes
+ - feat/react-native-responsive
# 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 445677c7b..a7168e173 100644
--- a/apps/expo/check-bundle.mjs
+++ b/apps/expo/check-bundle.mjs
@@ -5,7 +5,8 @@
// must be there as React Native style objects. src/App.tsx reads the theme,
// the breakpoint and the orientation, so it calls each of those hooks of the
// runtime; src/Badge.tsx is styled the same in every theme and at every
-// width, so it must not use the runtime.
+// width, so it must not use the runtime. Its buttons take press styles, which
+// React Native's `Pressable` applies through a function for `style`.
import { readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
@@ -117,7 +118,12 @@ for (const platform of ['ios', 'android']) {
if (code.includes(PLACEHOLDER)) {
failures.push(`${platform}/${file}: holds "${PLACEHOLDER}"`)
}
- for (const style of ['backgroundColor:"#5a44ff"', 'StyleSheet']) {
+ for (const style of [
+ 'backgroundColor:"#5a44ff"',
+ 'backgroundColor:"#4330d9"',
+ 'StyleSheet',
+ 'style:({pressed:',
+ ]) {
if (!code.replaceAll(' ', '').includes(style)) {
failures.push(`${platform}/${file}: lacks ${style}`)
}
diff --git a/apps/expo/src/App.tsx b/apps/expo/src/App.tsx
index 02be3958e..624128e25 100644
--- a/apps/expo/src/App.tsx
+++ b/apps/expo/src/App.tsx
@@ -67,6 +67,7 @@ export function App() {
gap={3}
>
setCount(count + 1)}
@@ -78,6 +79,7 @@ export function App() {
setTheme(theme === 'dark' ? 'light' : 'dark')}
diff --git a/libs/extractor/src/native/element.rs b/libs/extractor/src/native/element.rs
index 84bac63a8..7139a40f1 100644
--- a/libs/extractor/src/native/element.rs
+++ b/libs/extractor/src/native/element.rs
@@ -45,6 +45,9 @@ struct Runtime {
breakpoint: String,
/// The variable holding whether the window is in landscape
landscape: String,
+ /// The variable holding whether the element is pressed, in the function
+ /// `Pressable` calls for its style
+ pressed: String,
/// The hooks reading each, by what they read
hooks: [String; 3],
/// What the hooks the file calls read
@@ -71,6 +74,7 @@ impl Runtime {
index: fresh_name("__t", code),
breakpoint: fresh_name("__b", code),
landscape: fresh_name("__l", code),
+ pressed: fresh_name("__p", code),
hooks: HOOKS.map(|hook| fresh_name(&format!("__{hook}"), code)),
hooks_used: Reads::default(),
wrapper: fresh_name("__Themed", code),
@@ -87,6 +91,7 @@ impl Runtime {
theme: &self.index,
breakpoint: &self.breakpoint,
landscape: &self.landscape,
+ pressed: &self.pressed,
}
}
@@ -172,6 +177,9 @@ pub(super) fn compile(
sheet: Sheet::new(fresh_name("__s", code)),
units: fresh_name("__u", code),
units_used: Cell::new(false),
+ pressable: fresh_name("__Pressable", code),
+ pressable_used: false,
+ press: None,
runtime: Runtime::new(code),
theme_scope: None,
frames: Vec::new(),
@@ -186,6 +194,8 @@ pub(super) fn compile(
sheet,
units,
units_used,
+ pressable,
+ pressable_used,
runtime,
mut replacements,
errors,
@@ -194,6 +204,12 @@ pub(super) fn compile(
let mut prelude = runtime
.prelude(target, imports.theme_api)
.unwrap_or_default();
+ if pressable_used {
+ let _ = writeln!(
+ prelude,
+ "import {{ Pressable as {pressable} }} from \"{REACT_NATIVE}\";"
+ );
+ }
if !sheet.is_empty() {
prelude.push_str(&sheet_prelude(&sheet, code));
}
@@ -223,11 +239,9 @@ enum Prop {
Platform(NativePlatform),
/// `_themeDark` and the like: styles for the theme named
Theme(String),
- /// `_landscape` (`true`) or `_portrait` (`false`): styles for the
- /// orientation of the window
- Orientation(bool),
- /// What needs the React Native runtime
- Runtime(RuntimeFeature),
+ /// `_landscape`, `_portrait` and `_pressed`: styles applied while the
+ /// window is in that orientation or the element is pressed
+ When(State),
/// What React Native has no equivalent of
Unsupported(Problem),
/// A prop the element passes on to the React Native component
@@ -242,9 +256,9 @@ fn classify(name: &str) -> Prop {
"_ios" => Prop::Platform(NativePlatform::Ios),
"_android" => Prop::Platform(NativePlatform::Android),
"_web" => Prop::Platform(NativePlatform::Web),
- "_pressed" | "_active" => Prop::Runtime(RuntimeFeature::Pressed),
- "_portrait" => Prop::Orientation(false),
- "_landscape" => Prop::Orientation(true),
+ "_portrait" => Prop::When(State::Landscape(false)),
+ "_landscape" => Prop::When(State::Landscape(true)),
+ "_pressed" | "_active" => Prop::When(State::Pressed),
"className" => Prop::Unsupported(Problem::new(
"React Native has no class names",
"write the styles as props, or pass them in `style`",
@@ -301,6 +315,12 @@ struct Elements<'s> {
units: String,
/// Whether a value read at runtime is converted
units_used: Cell,
+ /// The name React Native's `Pressable` is imported under, for an element
+ /// that is a `View` but takes a press style
+ pressable: String,
+ pressable_used: bool,
+ /// The offset and the name of the first press style of the element read
+ press: Option<(u32, String)>,
runtime: Runtime,
/// The theme of the `_theme*` block being read, whose tokens resolve in
/// that theme alone
@@ -317,6 +337,10 @@ struct Elements<'s> {
#[derive(Default)]
struct Styles {
choices: Vec,
+ /// The styles of the theme, orientation and press blocks, which apply
+ /// after the other styles whatever the order of the props, as their
+ /// selectors and media queries do on the web
+ blocks: Vec,
/// The code of each style given whole, in prop order
given: Vec,
/// The span of each prop leaving the element once it takes `style`
@@ -571,7 +595,7 @@ impl<'a> Elements<'_> {
} else {
None
};
- feature.map_or(Ok(()), |feature| Err(feature.problem(self.target)))
+ feature.map_or(Ok(()), |feature| Err(feature.problem()))
}
/// Compile one Devup UI element
@@ -605,6 +629,10 @@ impl<'a> Elements<'_> {
}
}
let retagged = tag.is_some();
+ let press = self.press.take();
+ if let Some(press) = press.filter(|_| styles.blocks.iter().any(Choice::pressed)) {
+ tag = self.pressable(press, kind, local, tag);
+ }
self.finish(element, styles, (tag, local), previous_end);
self.children(element, kind, local, retagged);
}
@@ -661,22 +689,18 @@ impl<'a> Elements<'_> {
attribute.span.start,
local,
);
- styles.choices.extend(choices);
+ styles.blocks.extend(choices);
}
- Prop::Orientation(landscape) => {
+ Prop::When(state) => {
styles.removed.push(span);
- let choices = self.orientation_block(
+ let choices = self.state_block(
attribute_expression(attribute),
- (name, landscape),
+ (name, state),
attribute.span.start,
local,
);
- styles.choices.extend(choices);
+ styles.blocks.extend(choices);
}
- Prop::Runtime(feature) => self.error(
- attribute.span.start,
- feature.problem(self.target).on(local, name),
- ),
Prop::Unsupported(problem) => self.error(attribute.span.start, problem.on(local, name)),
Prop::Pass => self.pass(attribute),
}
@@ -808,10 +832,7 @@ impl<'a> Elements<'_> {
};
let count = self.target.theme.count();
if count > 1 && !self.target.runtime {
- self.error(
- offset,
- RuntimeFeature::Theme.problem(self.target).on(local, name),
- );
+ self.error(offset, RuntimeFeature::Theme.problem().on(local, name));
return Vec::new();
}
if self.theme_scope.is_some_and(|scope| scope != index) {
@@ -826,33 +847,36 @@ impl<'a> Elements<'_> {
.collect()
}
- /// The styles of `_landscape` or `_portrait`, `name` being the prop: they
- /// apply only while the window is in that orientation
- fn orientation_block(
+ /// The styles of `_landscape`, `_portrait` or `_pressed`, `name` being
+ /// the prop: they apply only while `state` holds
+ fn state_block(
&mut self,
value: Option<&Expression<'a>>,
- (name, landscape): (&str, bool),
+ (name, state): (&str, State),
offset: u32,
local: &str,
) -> Vec {
- if !self.target.runtime {
+ // `Pressable` tells whether it is pressed; only the orientation needs
+ // the runtime
+ if state == State::Pressed {
+ self.press.get_or_insert_with(|| (offset, name.to_string()));
+ } else if !self.target.runtime {
self.error(
offset,
- RuntimeFeature::Orientation
- .problem(self.target)
- .on(local, name),
+ RuntimeFeature::Orientation.problem().on(local, name),
);
return Vec::new();
}
self.block(value, name, offset, local)
.into_iter()
- .map(|choice| when(State::Landscape(landscape), choice))
+ .map(|choice| when(state, choice))
.collect()
}
/// The styles of an object of style props
fn object_choices(&mut self, object: &ObjectExpression<'a>, local: &str) -> Vec {
let mut choices = Vec::new();
+ let mut blocks = Vec::new();
for property in &object.properties {
let ObjectPropertyKind::ObjectProperty(property) = property else {
self.error(
@@ -882,8 +906,12 @@ impl<'a> Elements<'_> {
);
continue;
};
- choices.extend(self.object_property(&key, &property.value, property.span.start, local));
+ let block = matches!(classify(&key), Prop::Theme(_) | Prop::When(_));
+ let property_choices =
+ self.object_property(&key, &property.value, property.span.start, local);
+ if block { &mut blocks } else { &mut choices }.extend(property_choices);
}
+ choices.extend(blocks);
choices
}
@@ -909,11 +937,8 @@ impl<'a> Elements<'_> {
Prop::Theme(theme) => {
return self.theme_block(Some(value), (key, &theme), offset, local);
}
- Prop::Orientation(landscape) => {
- return self.orientation_block(Some(value), (key, landscape), offset, local);
- }
- Prop::Runtime(feature) => {
- self.error(offset, feature.problem(self.target).on(local, key));
+ Prop::When(state) => {
+ return self.state_block(Some(value), (key, state), offset, local);
}
Prop::Unsupported(problem) => self.error(offset, problem.on(local, key)),
Prop::As | Prop::Style | Prop::Pass => self.error(
@@ -1020,7 +1045,7 @@ impl<'a> Elements<'_> {
return self.static_choice(name, &literals);
}
if !self.target.runtime {
- return Err(RuntimeFeature::Responsive.problem(self.target));
+ return Err(RuntimeFeature::Responsive.problem());
}
let mut choices = Vec::with_capacity(items.len());
for (level, expression) in items {
@@ -1112,16 +1137,26 @@ impl<'a> Elements<'_> {
attributes_end: u32,
) {
let Styles {
- choices,
+ mut choices,
+ blocks,
given,
mut removed,
style,
opaque_spread,
} = styles;
- let style_code = style_code(choices, given, &mut self.sheet, &self.runtime.vars());
+ choices.extend(blocks);
+ let pressed = choices.iter().any(Choice::pressed);
+ let mut style_code = style_code(choices, given, &mut self.sheet, &self.runtime.vars());
let reads = style_code
.as_ref()
.map_or_else(Reads::default, |style| style.reads);
+ if let Some(style) = style_code.as_mut().filter(|_| pressed) {
+ // `Pressable` calls a function for its style with its state
+ style.code = format!(
+ "({{ pressed: {} }}) => {}",
+ self.runtime.pressed, style.code
+ );
+ }
let wrapped = reads.any() && !self.read_in_component(reads);
if wrapped {
self.runtime.wrapper_used = true;
@@ -1168,6 +1203,37 @@ impl<'a> Elements<'_> {
.push((attributes_end as usize, attributes_end as usize, code));
}
+ /// The component an element taking a press style renders: React Native's
+ /// `Pressable` for a `View`, which only it can call the style of with
+ /// whether it is pressed, or the `Pressable` it already renders
+ fn pressable(
+ &mut self,
+ (offset, name): (u32, String),
+ kind: &ExportVariableKind,
+ local: &str,
+ tag: Option,
+ ) -> Option {
+ let problem = match (native_component(kind), &tag) {
+ ("Pressable", None) => return None,
+ ("View", None) => {
+ self.pressable_used = true;
+ return Some(self.pressable.clone());
+ }
+ (_, Some(_)) => Problem::new(
+ "a press style makes the element React Native's `Pressable`, which cannot render the component `as` gives",
+ "remove `as`, or pass a function reading `pressed` to the `style` of a `Pressable`",
+ ),
+ (native, None) => Problem::new(
+ format!(
+ "a press style needs React Native's `Pressable`, and the element renders React Native's `{native}`"
+ ),
+ "wrap it in a `Box` or a `Button` with `_pressed`",
+ ),
+ };
+ self.error(offset, problem.on(local, &name));
+ tag
+ }
+
/// Render the component `as` gives
fn rename(&mut self, element: &JSXElement<'a>, tag: &str) {
let names = std::iter::once(element.opening_element.name.span()).chain(
diff --git a/libs/extractor/src/native/errors.rs b/libs/extractor/src/native/errors.rs
index 31259ea32..5e8f814e8 100644
--- a/libs/extractor/src/native/errors.rs
+++ b/libs/extractor/src/native/errors.rs
@@ -1,7 +1,5 @@
//! The build errors of the React Native output
-use super::NativeTarget;
-
/// Why a value or prop cannot compile, and what to write instead
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Problem {
@@ -35,13 +33,12 @@ impl Problem {
}
/// What needs the React Native runtime: one style object a breakpoint, a
-/// theme or a press state, chosen while the app runs
+/// theme or an orientation, chosen while the app runs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum RuntimeFeature {
Responsive,
Orientation,
Theme,
- Pressed,
}
impl RuntimeFeature {
@@ -50,7 +47,6 @@ impl RuntimeFeature {
Self::Responsive => "a responsive value is chosen by the window width",
Self::Orientation => "an orientation style is chosen by the orientation of the window",
Self::Theme => "a theme variant is chosen by the theme the app shows",
- Self::Pressed => "a press style is chosen while the element is pressed",
}
}
@@ -59,20 +55,18 @@ impl RuntimeFeature {
Self::Responsive => "give one value, or turn the runtime on",
Self::Orientation => "remove it, or turn the runtime on",
Self::Theme => "give the value for one theme, or turn the runtime on",
- Self::Pressed => {
- "pass a function to the `style` of a React Native `Pressable`, reading `pressed`"
- }
}
}
- /// Why the feature cannot compile for `target`
- pub(super) fn problem(self, target: &NativeTarget) -> Problem {
- let runtime = if target.runtime {
- "which needs the React Native runtime that this version does not include yet"
- } else {
- "which needs the React Native runtime that `runtime: false` turns off"
- };
- Problem::new(format!("{}, {runtime}", self.what()), self.fix())
+ /// Why the feature cannot compile with `runtime: false`
+ pub(super) fn problem(self) -> Problem {
+ Problem::new(
+ format!(
+ "{}, which needs the React Native runtime that `runtime: false` turns off",
+ self.what()
+ ),
+ self.fix(),
+ )
}
}
diff --git a/libs/extractor/src/native/mod.rs b/libs/extractor/src/native/mod.rs
index e578e65a8..fa0fa54bc 100644
--- a/libs/extractor/src/native/mod.rs
+++ b/libs/extractor/src/native/mod.rs
@@ -12,8 +12,9 @@
//! runtime of `@devup-ui/react/native` gives; a responsive value compiles to
//! one style object a run of breakpoints, picked by the breakpoint the
//! runtime gives, and `_portrait`/`_landscape` apply by its orientation.
-//! `_pressed` needs a runtime that this version does not include, and a prop
-//! React Native has no style for is a build error naming the prop.
+//! `_active`/`_pressed` make the element a `Pressable`, whose `style` is a
+//! function of whether it is pressed. A prop React Native has no style for is
+//! a build error naming the prop.
mod element;
mod errors;
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_nested.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_nested.snap
new file mode 100644
index 000000000..b62027d3e
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_nested.snap
@@ -0,0 +1,27 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), true, &code)"
+---
+import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native";
+import { useThemeIndex as __useThemeIndex, useLandscape as __useLandscape, defineThemes as __defineThemes } from "@devup-ui/react/native";
+__defineThemes(["light", "dark"], 1);
+import { Pressable as __Pressable } from "react-native";
+import { StyleSheet } from "react-native";
+const __s = StyleSheet.create({
+ a: { padding: 20 },
+ b: { margin: 8 },
+ c: { padding: 16 },
+ d: { margin: 4 },
+ e: { margin: 12 }
+});
+export function A() {
+ const __t = __useThemeIndex();
+ const __l = __useLandscape();
+ return <__Pressable style={({ pressed: __p }) => [
+ __s.a,
+ __l && __s.b,
+ __l && __s.c,
+ __l && __p && __s.d,
+ __l && [null, __s.e][__t]
+ ]} />;
+}
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_orientation.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_orientation.snap
new file mode 100644
index 000000000..e70c7d75c
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_orientation.snap
@@ -0,0 +1,15 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), true, &code)"
+---
+import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native";
+import { useLandscape as __useLandscape } from "@devup-ui/react/native";
+import { StyleSheet } from "react-native";
+const __s = StyleSheet.create({
+ a: { padding: 8 },
+ b: { padding: 4 }
+});
+export function A() {
+ const __l = __useLandscape();
+ return ;
+}
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_platform.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_platform.snap
new file mode 100644
index 000000000..982549a93
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_platform.snap
@@ -0,0 +1,10 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), true, &code)"
+---
+import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native";
+import { StyleSheet } from "react-native";
+const __s = StyleSheet.create({ a: { margin: 8 } });
+export function A() {
+ return ;
+}
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_pressed.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_pressed.snap
new file mode 100644
index 000000000..1d57155ca
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_pressed.snap
@@ -0,0 +1,14 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), true, &code)"
+---
+import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native";
+import { Pressable as __Pressable } from "react-native";
+import { StyleSheet } from "react-native";
+const __s = StyleSheet.create({
+ a: { margin: 8 },
+ b: { margin: 4 }
+});
+export function A() {
+ return <__Pressable style={({ pressed: __p }) => [__s.a, __p && __s.b]} />;
+}
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_theme.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_theme.snap
new file mode 100644
index 000000000..8d5ffe18a
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_theme.snap
@@ -0,0 +1,16 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), true, &code)"
+---
+import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native";
+import { useThemeIndex as __useThemeIndex, defineThemes as __defineThemes } from "@devup-ui/react/native";
+__defineThemes(["light", "dark"], 1);
+import { StyleSheet } from "react-native";
+const __s = StyleSheet.create({
+ a: { backgroundColor: "blue" },
+ b: { backgroundColor: "red" }
+});
+export function A() {
+ const __t = __useThemeIndex();
+ return ;
+}
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__orientation_blocks.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__orientation_blocks.snap
index d939c9b22..4bc7603e6 100644
--- a/libs/extractor/src/native/snapshots/extractor__native__tests__orientation_blocks.snap
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__orientation_blocks.snap
@@ -24,6 +24,6 @@ export function Screen({ on }) {
__l && (on ? __s.e : __s.f),
__l && __s.g
]}>
-
+
;
}
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__platform_shapes.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__platform_shapes.snap
index 725ae4af6..ed184d1d0 100644
--- a/libs/extractor/src/native/snapshots/extractor__native__tests__platform_shapes.snap
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__platform_shapes.snap
@@ -7,6 +7,5 @@ test.tsx:2:32: `` cannot use `...` on React Native: the build reads only th
test.tsx:2:41: `` cannot use `[key]` on React Native: the build reads only keys written in a block. Fix: write the key itself
test.tsx:2:51: `` cannot use `onPress` on React Native: a block holds only style props. Fix: pass it to the element itself
test.tsx:2:63: `` cannot use `_hover` on React Native: React Native has no selectors, pseudo-elements or media queries. Fix: remove it, or write the style the element takes in every state
-test.tsx:2:75: `` cannot use `_pressed` on React Native: a press style is chosen while the element is pressed, which needs the React Native runtime that this version does not include yet. Fix: pass a function to the `style` of a React Native `Pressable`, reading `pressed`
test.tsx:2:89: `` cannot use `_web` on React Native: `_web` takes an object of styles. Fix: write the styles in an object, such as `_web={{ p: 2 }}`
test.tsx:2:103: `` cannot use `as` on React Native: a block holds only style props. Fix: pass it to the element itself
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__pressed.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed.snap
deleted file mode 100644
index bbe1020a8..000000000
--- a/libs/extractor/src/native/snapshots/extractor__native__tests__pressed.snap
+++ /dev/null
@@ -1,6 +0,0 @@
----
-source: libs/extractor/src/native/tests.rs
-expression: compile(code)
----
-error: test.tsx:2:9: `` cannot use `_pressed` on React Native: a press style is chosen while the element is pressed, which needs the React Native runtime that this version does not include yet. Fix: pass a function to the `style` of a React Native `Pressable`, reading `pressed`
-test.tsx:2:34: `` cannot use `_active` on React Native: a press style is chosen while the element is pressed, which needs the React Native runtime that this version does not include yet. Fix: pass a function to the `style` of a React Native `Pressable`, reading `pressed`
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_errors.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_errors.snap
new file mode 100644
index 000000000..aa8d58716
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_errors.snap
@@ -0,0 +1,9 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), runtime, code)"
+---
+error: test.tsx:2:7: `` cannot use `_pressed` on React Native: a press style needs React Native's `Pressable`, and the element renders React Native's `Text`. Fix: wrap it in a `Box` or a `Button` with `_pressed`
+test.tsx:3:8: `` cannot use `_pressed` on React Native: a press style needs React Native's `Pressable`, and the element renders React Native's `Image`. Fix: wrap it in a `Box` or a `Button` with `_pressed`
+test.tsx:4:8: ` ` cannot use `_pressed` on React Native: a press style needs React Native's `Pressable`, and the element renders React Native's `TextInput`. Fix: wrap it in a `Box` or a `Button` with `_pressed`
+test.tsx:5:25: `` cannot use `_pressed` on React Native: a press style makes the element React Native's `Pressable`, which cannot render the component `as` gives. Fix: remove `as`, or pass a function reading `pressed` to the `style` of a `Pressable`
+test.tsx:6:6: `` cannot use `_pressed` on React Native: `_pressed` takes an object of styles. Fix: write the styles in an object, such as `_pressed={{ p: 2 }}`
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_name_collisions.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_name_collisions.snap
new file mode 100644
index 000000000..0c7629f8a
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_name_collisions.snap
@@ -0,0 +1,10 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), true, code)"
+---
+import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native";
+import { Pressable as __Pressable_ } from "react-native";
+import { StyleSheet } from "react-native";
+const __s = StyleSheet.create({ a: { margin: 4 } });
+const __p = 1, __Pressable = 2;
+export const A = () => <__Pressable_ style={({ pressed: __p_ }) => __p_ && __s.a} />;
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_runtime_off.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_runtime_off.snap
new file mode 100644
index 000000000..bb1d06652
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_runtime_off.snap
@@ -0,0 +1,17 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), runtime, code)"
+---
+import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native";
+import { Pressable as __Pressable } from "react-native";
+import { StyleSheet } from "react-native";
+const __s = StyleSheet.create({
+ a: { backgroundColor: "red" },
+ b: { margin: 4 },
+ c: { padding: 4 }
+});
+export const a = <__Pressable style={({ pressed: __p }) => [
+ __s.a,
+ __p && __s.b,
+ __p && __s.c
+]} />;
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_styles.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_styles.snap
new file mode 100644
index 000000000..a5ca62584
--- /dev/null
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed_styles.snap
@@ -0,0 +1,47 @@
+---
+source: libs/extractor/src/native/tests.rs
+expression: "compile_themed(two_themes(), runtime, code)"
+---
+import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native";
+import { useThemeIndex as __useThemeIndex, useBreakpoint as __useBreakpoint, Themed as __Themed, defineThemes as __defineThemes } from "@devup-ui/react/native";
+__defineThemes(["light", "dark"], 1);
+import { Pressable as __Pressable } from "react-native";
+import { StyleSheet } from "react-native";
+const __s = StyleSheet.create({
+ a: { padding: 8 },
+ b: { backgroundColor: "#5a44ff" },
+ c: { backgroundColor: "#8c7bff" },
+ d: { backgroundColor: "#111" },
+ e: { backgroundColor: "#eee" },
+ f: { opacity: .8 },
+ g: { padding: 4 },
+ h: { opacity: .5 },
+ i: { flexDirection: "row" },
+ j: { backgroundColor: "red" }
+});
+export function Buttons({ on, go, extra }) {
+ const __t = __useThemeIndex();
+ const __b = __useBreakpoint();
+ return
+ [
+ __s.a,
+ [__s.b, __s.c][__t],
+ __p && [__s.d, __s.e][__t],
+ __p && __s.f
+ ]}>
+ Go
+
+ <__Pressable onPress={go} style={({ pressed: __p }) => [__b < 1 ? __s.g : __s.a, __p && __s.h]} />
+ <__Pressable onPress={go} style={({ pressed: __p }) => [
+ __s.i,
+ __p && (on ? __s.g : __s.a),
+ extra
+ ]}>
+
+
+ <__Pressable style={({ pressed: __p }) => __t === 1 && __p && __s.j} />
+
+
+ ;
+}
+export const outside = <__Themed $c={__Pressable} $s={(__t) => (({ pressed: __p }) => __p && [__s.b, __s.c][__t])} />;
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_false.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_false.snap
index 9dc9cebe4..fb7fe7294 100644
--- a/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_false.snap
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_false.snap
@@ -4,4 +4,3 @@ expression: "compile_for(NativePlatform::Ios, runtime, &code)"
---
error: test.tsx:2:6: `` cannot use `p` on React Native: a responsive value is chosen by the window width, which needs the React Native runtime that `runtime: false` turns off. Fix: give one value, or turn the runtime on
test.tsx:2:17: `` cannot use `_themeDark` on React Native: devup.json defines no `dark` theme. Fix: add the theme to devup.json, or remove the block
-test.tsx:2:33: `` cannot use `_pressed` on React Native: a press style is chosen while the element is pressed, which needs the React Native runtime that `runtime: false` turns off. Fix: pass a function to the `style` of a React Native `Pressable`, reading `pressed`
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_true.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_true.snap
index 7b1927f74..c4d3d7e28 100644
--- a/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_true.snap
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_true.snap
@@ -3,4 +3,3 @@ source: libs/extractor/src/native/tests.rs
expression: "compile_for(NativePlatform::Ios, runtime, &code)"
---
error: test.tsx:2:17: `` cannot use `_themeDark` on React Native: devup.json defines no `dark` theme. Fix: add the theme to devup.json, or remove the block
-test.tsx:2:33: `` cannot use `_pressed` on React Native: a press style is chosen while the element is pressed, which needs the React Native runtime that this version does not include yet. Fix: pass a function to the `style` of a React Native `Pressable`, reading `pressed`
diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__theme_two.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_two.snap
index 78a879126..621f269f2 100644
--- a/libs/extractor/src/native/snapshots/extractor__native__tests__theme_two.snap
+++ b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_two.snap
@@ -83,7 +83,7 @@ export function Card({ on, color }) {
]} />
-
+
;
}
diff --git a/libs/extractor/src/native/style.rs b/libs/extractor/src/native/style.rs
index 26e71d31d..4a847b6fd 100644
--- a/libs/extractor/src/native/style.rs
+++ b/libs/extractor/src/native/style.rs
@@ -18,6 +18,8 @@ pub(super) enum State {
AtLeast(usize),
/// The window is in landscape (`true`) or portrait (`false`) orientation
Landscape(bool),
+ /// The element is pressed
+ Pressed,
}
/// The styles one prop declares
@@ -55,6 +57,7 @@ pub(super) struct Reads {
}
impl Reads {
+ /// Whether it reads what a hook of the runtime gives
pub(super) const fn any(self) -> bool {
self.theme || self.breakpoint || self.landscape
}
@@ -78,6 +81,7 @@ pub(super) struct Vars<'v> {
pub theme: &'v str,
pub breakpoint: &'v str,
pub landscape: &'v str,
+ pub pressed: &'v str,
}
/// The choice of `grid`, as small as it can be: the last breakpoints that
@@ -207,6 +211,20 @@ impl Choice {
}
}
+ /// Whether the choice applies styles only while the element is pressed
+ pub(super) fn pressed(&self) -> bool {
+ match self {
+ Self::Condition {
+ consequent,
+ alternate,
+ ..
+ } => consequent.pressed() || alternate.pressed(),
+ Self::When { state, choice } => *state == State::Pressed || choice.pressed(),
+ Self::All(choices) => choices.iter().any(Self::pressed),
+ _ => false,
+ }
+ }
+
/// The code of the choice, its static styles named in `sheet`
fn code(&self, sheet: &mut Sheet, vars: &Vars<'_>) -> String {
match self {
@@ -290,6 +308,7 @@ impl State {
Self::AtLeast(level) => format!("{} >= {level}", vars.breakpoint),
Self::Landscape(true) => vars.landscape.to_string(),
Self::Landscape(false) => format!("!{}", vars.landscape),
+ Self::Pressed => vars.pressed.to_string(),
}
}
}
diff --git a/libs/extractor/src/native/tests.rs b/libs/extractor/src/native/tests.rs
index 3665d9263..57ae043ab 100644
--- a/libs/extractor/src/native/tests.rs
+++ b/libs/extractor/src/native/tests.rs
@@ -2,7 +2,7 @@ use insta::assert_snapshot;
use rstest::rstest;
use super::element::units_declaration;
-use super::errors::{Problem, RuntimeFeature};
+use super::errors::Problem;
use super::props::Declaration;
use super::sheet::{Sheet, key_name};
use super::style::{Choice, State, Vars, cascade, in_theme, style_code, varied, when};
@@ -14,6 +14,7 @@ const VARS: Vars<'static> = Vars {
theme: "t",
breakpoint: "b",
landscape: "l",
+ pressed: "p",
};
const IMPORT: &str =
@@ -209,10 +210,6 @@ fn compiles_files(#[case] name: &str, #[case] code: &str) {
#[case::theme_token("theme_token", " ")]
#[case::theme_selector("theme_selector", " ")]
#[case::typography("typography", " ")]
-#[case::pressed(
- "pressed",
- " "
-)]
#[case::selectors(
"selectors",
" "
@@ -470,17 +467,6 @@ fn problems_format_for_props_and_imports() {
problem.import("css", "@devup-ui/react"),
"`css` from `@devup-ui/react` cannot be used on React Native: why. Fix: how"
);
- let target = NativeTarget {
- platform: NativePlatform::Ios,
- runtime: true,
- theme: std::sync::Arc::default(),
- };
- assert!(
- RuntimeFeature::Pressed
- .problem(&target)
- .fix
- .contains("Pressable")
- );
}
#[rstest]
@@ -1144,3 +1130,82 @@ fn varied_choices_pick_by_breakpoint_and_theme() {
)
);
}
+
+const PRESSED_ELEMENTS: &str = r#"export function Buttons({ on, go, extra }) {
+ return (
+
+
+ Go
+
+
+
+
+
+
+
+
+
+ )
+}
+export const outside = "#;
+
+#[rstest]
+#[case::pressed("pressed_styles", true, PRESSED_ELEMENTS)]
+#[case::runtime_off(
+ "pressed_runtime_off",
+ false,
+ "export const a = "
+)]
+#[case::name_collisions(
+ "pressed_name_collisions",
+ true,
+ "const __p = 1, __Pressable = 2;\nexport const A = () => "
+)]
+#[case::errors(
+ "pressed_errors",
+ true,
+ " ;\n ;\n ;\n ;\n "
+)]
+fn compiles_pressed(#[case] name: &str, #[case] runtime: bool, #[case] code: &str) {
+ assert_snapshot!(name, compile_themed(two_themes(), runtime, code));
+}
+
+#[rstest]
+#[case::theme("block_order_theme", " ")]
+#[case::orientation("block_order_orientation", " ")]
+#[case::pressed("block_order_pressed", " ")]
+#[case::nested(
+ "block_order_nested",
+ " "
+)]
+#[case::platform("block_order_platform", " ")]
+fn blocks_apply_after_the_other_styles(#[case] name: &str, #[case] code: &str) {
+ let code = format!("export function A() {{ return {code} }}");
+ assert_snapshot!(name, compile_themed(two_themes(), true, &code));
+}
+
+#[test]
+fn a_static_style_after_one_kept_in_order_checks_it() {
+ let mut sheet = Sheet::new("s".to_string());
+ let code = style_code(
+ vec![
+ Choice::Dynamic(vec![("margin".to_string(), "m".to_string())]),
+ Choice::Static(declarations(&[("margin", 2.0)])),
+ Choice::Dynamic(vec![("width".to_string(), "w".to_string())]),
+ Choice::Static(declarations(&[("padding", 1.0)])),
+ when(
+ State::Pressed,
+ Choice::Static(declarations(&[("height", 1.0)])),
+ ),
+ Choice::Static(declarations(&[("top", 1.0)])),
+ ],
+ vec![],
+ &mut sheet,
+ &VARS,
+ )
+ .map(|style| style.code);
+ assert_eq!(
+ code.as_deref(),
+ Some("[s.a, { margin: m }, s.b, { width: w }, p && s.c]")
+ );
+}
diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md
index 1a4e54e18..728b1c8f2 100644
--- a/packages/metro-plugin/README.md
+++ b/packages/metro-plugin/README.md
@@ -140,6 +140,24 @@ 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`.
+
## Limits of this version
Only styles the build can decide are supported: literals, values read at
@@ -147,14 +165,12 @@ runtime, theme tokens, responsive values, conditions between them and the
platform, theme and orientation blocks. These are build errors, reported by
Metro at the file, line and column:
-- interaction states (`_hover`, `_active`, `_pressed`, `_focus`, ...)
+- interaction states other than `_active`/`_pressed` (`_hover`, `_focus`, ...)
- `css()`, `styled()`, `globalCss()`, `keyframes()` and `Grid`
- any prop React Native has no style for
- with `runtime: false`, a value that differs by theme or breakpoint,
`_theme*` with more than one theme, `_portrait`, `_landscape`, and
`useTheme`, `getTheme` and `setTheme`
-The runtime that brings `_pressed` comes in a later version.
-
Metro reads devup.json when it starts, so restart Metro after changing it
(`--reset-cache` is not needed).