Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changepacks/changepack_log_react_native_pressed.json
Original file line number Diff line number Diff line change
@@ -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"
}
1 change: 1 addition & 0 deletions .github/workflows/publish.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 8 additions & 2 deletions apps/expo/check-bundle.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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}`)
}
Expand Down
2 changes: 2 additions & 0 deletions apps/expo/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export function App() {
gap={3}
>
<Button
_active={{ bg: '#4330d9' }}
bg="#5a44ff"
borderRadius="8px"
onPress={() => setCount(count + 1)}
Expand All @@ -78,6 +79,7 @@ export function App() {
</Text>
</Button>
<Button
_active={{ opacity: 0.6 }}
border="1px solid $border"
borderRadius="8px"
onPress={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
Expand Down
146 changes: 106 additions & 40 deletions libs/extractor/src/native/element.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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),
Expand All @@ -87,6 +91,7 @@ impl Runtime {
theme: &self.index,
breakpoint: &self.breakpoint,
landscape: &self.landscape,
pressed: &self.pressed,
}
}

Expand Down Expand Up @@ -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(),
Expand All @@ -186,6 +194,8 @@ pub(super) fn compile(
sheet,
units,
units_used,
pressable,
pressable_used,
runtime,
mut replacements,
errors,
Expand All @@ -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));
}
Expand Down Expand Up @@ -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
Expand All @@ -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`",
Expand Down Expand Up @@ -301,6 +315,12 @@ struct Elements<'s> {
units: String,
/// Whether a value read at runtime is converted
units_used: Cell<bool>,
/// 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
Expand All @@ -317,6 +337,10 @@ struct Elements<'s> {
#[derive(Default)]
struct Styles {
choices: Vec<Choice>,
/// 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<Choice>,
/// The code of each style given whole, in prop order
given: Vec<String>,
/// The span of each prop leaving the element once it takes `style`
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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),
}
Expand Down Expand Up @@ -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) {
Expand All @@ -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<Choice> {
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<Choice> {
let mut choices = Vec::new();
let mut blocks = Vec::new();
for property in &object.properties {
let ObjectPropertyKind::ObjectProperty(property) = property else {
self.error(
Expand Down Expand Up @@ -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
}

Expand All @@ -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(
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<String>,
) -> Option<String> {
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(
Expand Down
Loading
Loading