From b61c8546c9781ad8a56821a1a9edb6c7a59dff59 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 10:45:24 +0900 Subject: [PATCH 1/7] feat(native): responsive values, responsive tokens and orientation on React Native Responsive arrays, length/shadow/typography tokens with a value at each breakpoint, responsive values in platform, theme and orientation blocks and conditions compile to one style object for each run of breakpoints that share their styles (by breakpoint and theme where both differ). The runtime store of @devup-ui/react/native also tells the breakpoint of devup.json the window is at and its orientation through one Dimensions listener that notifies only when a breakpoint is crossed or the window turns. _portrait/_landscape apply by orientation. With runtime: false these stay build errors. Co-Authored-By: Claude Opus 5.5 --- ..._log_react_native_breakpoints_runtime.json | 7 + ...hangepack_log_react_native_responsive.json | 8 + .github/workflows/publish.yml | 1 + apps/expo/check-bundle.mjs | 38 +- apps/expo/devup.json | 17 +- apps/expo/src/App.tsx | 60 ++- libs/binding/src/native_theme.rs | 1 + libs/binding/tests/native.rs | 9 + libs/extractor/src/native/element.rs | 349 ++++++++++--- libs/extractor/src/native/errors.rs | 5 +- libs/extractor/src/native/mod.rs | 6 +- libs/extractor/src/native/props.rs | 27 +- ...extractor__native__tests__orientation.snap | 10 +- ...or__native__tests__orientation_blocks.snap | 29 ++ ...tor__native__tests__orientation_value.snap | 6 + ...actor__native__tests__platform_shapes.snap | 1 - .../extractor__native__tests__responsive.snap | 9 +- ...tor__native__tests__responsive_arrays.snap | 98 ++++ ..._tests__responsive_custom_breakpoints.snap | 22 + ...ive__tests__responsive_hooks_in_arrow.snap | 31 ++ ...ative__tests__responsive_in_condition.snap | 10 +- ...ve__tests__responsive_name_collisions.snap | 18 + ...tor__native__tests__responsive_nested.snap | 5 + ...ive__tests__responsive_no_breakpoints.snap | 17 + ...tor__native__tests__responsive_spread.snap | 5 + ...tor__native__tests__responsive_themes.snap | 99 ++++ ...tractor__native__tests__runtime_false.snap | 2 +- ...or__native__tests__runtime_off_arrays.snap | 7 + ...ative__tests__runtime_off_orientation.snap | 6 + ..._tests__runtime_off_responsive_tokens.snap | 6 + ...xtractor__native__tests__runtime_true.snap | 3 +- ...ative__tests__theme_responsive_tokens.snap | 10 +- .../extractor__native__tests__theme_two.snap | 61 ++- ...or__native__tests__theme_typographies.snap | 1 - libs/extractor/src/native/style.rs | 476 ++++++++++++++---- libs/extractor/src/native/tests.rs | 280 ++++++++++- libs/extractor/src/native/theme.rs | 146 ++++-- packages/metro-plugin/README.md | 39 +- .../native/__tests__/index.browser.test.tsx | 122 ++++- packages/react/src/native/index.ts | 88 +++- 40 files changed, 1813 insertions(+), 322 deletions(-) create mode 100644 .changepacks/changepack_log_react_native_breakpoints_runtime.json create mode 100644 .changepacks/changepack_log_react_native_responsive.json create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__orientation_blocks.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__orientation_value.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__responsive_arrays.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__responsive_custom_breakpoints.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__responsive_hooks_in_arrow.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__responsive_name_collisions.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__responsive_nested.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__responsive_no_breakpoints.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__responsive_spread.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__responsive_themes.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_arrays.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_orientation.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_responsive_tokens.snap diff --git a/.changepacks/changepack_log_react_native_breakpoints_runtime.json b/.changepacks/changepack_log_react_native_breakpoints_runtime.json new file mode 100644 index 000000000..d5a77ade3 --- /dev/null +++ b/.changepacks/changepack_log_react_native_breakpoints_runtime.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/react/package.json": "Patch" + }, + "note": "`@devup-ui/react/native` also tells which breakpoint of devup.json the window is at (`useBreakpoint`, `getBreakpoint`) and whether it is in landscape, for responsive values on React Native (part of #411). One `Dimensions` listener is shared by every component, and a component renders again only when the window crosses into another breakpoint or turns, not on every pixel. The runtime is about 630 bytes minified and gzipped.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_react_native_responsive.json b/.changepacks/changepack_log_react_native_responsive.json new file mode 100644 index 000000000..38e58c018 --- /dev/null +++ b/.changepacks/changepack_log_react_native_responsive.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-binding/package.json": "Patch", + "bindings/devup-ui-wasm/package.json": "Patch" + }, + "note": "`codeExtractNative` compiles responsive values for React Native (part of #411): responsive arrays (`p={[1, null, 3]}`, `null` keeping the value before as on the web), `length`, `shadow` and `typography` tokens with a value at each breakpoint, responsive values inside `_ios`, `_theme*` and conditions, and `_portrait`/`_landscape`. The breakpoints of devup.json are measured against the window width. The build precomputes one style object for each run of breakpoints that share their styles, only for the styles that differ, and picks one by the breakpoint `useBreakpoint()` of `@devup-ui/react/native` gives (by breakpoint and theme where both differ). A value read at runtime in an array applies from its breakpoint on. With `runtime: false` these are build errors. Web output is unchanged.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index c1bd3a86b..1696a4342 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -9,6 +9,7 @@ on: - main - feat/napi-binding - feat/react-native-metro + - feat/react-native-themes # 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 913534639..445677c7b 100644 --- a/apps/expo/check-bundle.mjs +++ b/apps/expo/check-bundle.mjs @@ -3,14 +3,18 @@ // placeholders of @devup-ui/react or any module of that package but its React // Native runtime (`@devup-ui/react/native`), and the styles of src/App.tsx // must be there as React Native style objects. src/App.tsx reads the theme, -// so it uses the runtime; src/Badge.tsx is styled the same in every theme, so -// it must not. +// 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. import { readdirSync, readFileSync } from 'node:fs' import { join } from 'node:path' const PLACEHOLDER = 'Cannot run on the runtime' /** Names of the runtime that only code using it holds, as minified code keeps them */ -const RUNTIME_NAMES = /\b(?:defineThemes|useThemeIndex)\b/g +const RUNTIME_NAMES = + /\b(?:defineThemes|useThemeIndex|useBreakpoint|useLandscape)\b/g +/** The hooks src/App.tsx must call */ +const APP_HOOKS = ['useThemeIndex', 'useBreakpoint', 'useLandscape'] /** Modules of @devup-ui/react, by the path Metro resolves */ const REACT_PACKAGE = /(^|[\\/])(@devup-ui[\\/]react|packages[\\/]react)[\\/]/ /** The React Native runtime among them */ @@ -89,17 +93,19 @@ function mapSources(map) { : map.sources } -/** The sources of the code that names the runtime */ +/** Each name of the runtime, with the sources of the code that names it */ function runtimeUsers(code, locate) { - const users = new Set() + const users = new Map() code.split('\n').forEach((line, index) => { for (const match of line.matchAll(RUNTIME_NAMES)) { - users.add(locate(index, match.index)) + const source = locate(index, match.index) + if (source === null || NATIVE_RUNTIME.test(source)) continue + const sources = users.get(match[0]) ?? new Set() + sources.add(source) + users.set(match[0], sources) } }) - return [...users].filter( - (source) => source !== null && !NATIVE_RUNTIME.test(source), - ) + return users } for (const platform of ['ios', 'android']) { @@ -129,16 +135,22 @@ for (const platform of ['ios', 'android']) { failures.push(`${platform}/${file}: lacks @devup-ui/react/native`) } const users = runtimeUsers(code, sourceLocator(map)) - if (!users.some((source) => /src[\\/]App\.tsx$/.test(source))) { - failures.push(`${platform}/${file}: src/App.tsx does not use the runtime`) + for (const hook of APP_HOOKS) { + const callers = [...(users.get(hook) ?? [])] + if (!callers.some((source) => /src[\\/]App\.tsx$/.test(source))) { + failures.push(`${platform}/${file}: src/App.tsx does not call ${hook}`) + } } - for (const source of users.filter((source) => + const all = [ + ...new Set([...users.values()].flatMap((sources) => [...sources])), + ] + for (const source of all.filter((source) => /src[\\/]Badge\.tsx$/.test(source), )) { failures.push(`${platform}/${file}: ${source} uses the runtime`) } console.info( - `${platform}/${file}: ${sources.length} modules, runtime used by ${users.join(', ')}`, + `${platform}/${file}: ${sources.length} modules, runtime used by ${all.join(', ')}`, ) } } diff --git a/apps/expo/devup.json b/apps/expo/devup.json index a3a26daa2..beff56bfa 100644 --- a/apps/expo/devup.json +++ b/apps/expo/devup.json @@ -20,7 +20,8 @@ }, "length": { "default": { - "radius": ["12px"] + "radius": ["12px"], + "gutter": ["16px", null, "32px"] } }, "shadow": { @@ -29,11 +30,15 @@ } }, "typography": { - "title": { - "fontSize": "24px", - "fontWeight": 700, - "lineHeight": 1.3 - } + "title": [ + { + "fontSize": "24px", + "fontWeight": 700, + "lineHeight": 1.3 + }, + null, + { "fontSize": "32px" } + ] } } } diff --git a/apps/expo/src/App.tsx b/apps/expo/src/App.tsx index 4834b1d6c..02be3958e 100644 --- a/apps/expo/src/App.tsx +++ b/apps/expo/src/App.tsx @@ -24,7 +24,8 @@ export function App() { flexDirection="column" gap={4} justifyContent="center" - p={6} + px="$gutter" + py={[6, null, 10]} > - + Your name @@ -53,28 +61,34 @@ export function App() { {name ? `Hello, ${name}` : 'Type your name'} - - + + + ) } diff --git a/libs/binding/src/native_theme.rs b/libs/binding/src/native_theme.rs index d974d91fa..41d6a2200 100644 --- a/libs/binding/src/native_theme.rs +++ b/libs/binding/src/native_theme.rs @@ -44,6 +44,7 @@ pub fn native_theme(theme: &Theme) -> NativeTheme { .iter() .map(|(name, typography)| (name.clone(), typography_levels(typography))) .collect(), + breakpoints: theme.breakpoints.clone(), } } diff --git a/libs/binding/tests/native.rs b/libs/binding/tests/native.rs index 9c44f4d28..49010502c 100644 --- a/libs/binding/tests/native.rs +++ b/libs/binding/tests/native.rs @@ -159,3 +159,12 @@ fn native_extraction_resolves_the_registered_theme() -> Result<(), String> { assert!(code.contains("backgroundColor: \"#fff\""), "{code}"); Ok(()) } + +#[test] +fn native_theme_keeps_the_breakpoints() { + // The web's breakpoints by default, and those devup.json sets + let default = devup_ui_binding_core::native_theme(&theme("{}")); + let custom = devup_ui_binding_core::native_theme(&theme(r#"{ "breakpoints": [0, 600] }"#)); + assert_eq!(default.breakpoints, [0, 480, 768, 992, 1280, 1600]); + assert_eq!(custom.breakpoints, [0, 600]); +} diff --git a/libs/extractor/src/native/element.rs b/libs/extractor/src/native/element.rs index 36f2a0d08..84bac63a8 100644 --- a/libs/extractor/src/native/element.rs +++ b/libs/extractor/src/native/element.rs @@ -3,12 +3,14 @@ //! component its import is now bound to. use oxc_ast::ast::{ - ArrowFunctionExpression, ExportDefaultDeclaration, Expression, Function, FunctionBody, - IdentifierReference, JSXAttribute, JSXAttributeItem, JSXAttributeName, JSXAttributeValue, - JSXChild, JSXElement, JSXElementName, JSXExpression, LogicalOperator, ObjectExpression, - ObjectPropertyKind, Program, TSType, UnaryOperator, VariableDeclarator, + ArrayExpression, ArrayExpressionElement, ArrowFunctionExpression, ExportDefaultDeclaration, + Expression, Function, FunctionBody, IdentifierReference, JSXAttribute, JSXAttributeItem, + JSXAttributeName, JSXAttributeValue, JSXChild, JSXElement, JSXElementName, JSXExpression, + LogicalOperator, ObjectExpression, ObjectPropertyKind, Program, TSType, UnaryOperator, + VariableDeclarator, }; use std::cell::Cell; +use std::fmt::Write; use oxc_ast_visit::{Visit, walk}; use oxc_semantic::Scoping; @@ -19,10 +21,10 @@ use rustc_hash::{FxHashMap, FxHashSet}; use super::errors::{Problem, RuntimeFeature}; use super::imports::{self, native_component}; -use super::props::{Tokens, declarations, dynamic_keys}; +use super::props::{Declaration, Tokens, declarations, dynamic_keys, literal_levels}; use super::sheet::Sheet; -use super::style::{Choice, in_theme, style_code, themed}; -use super::theme::selector_theme; +use super::style::{Choice, Reads, State, Vars, cascade, in_theme, style_code, varied, when}; +use super::theme::{DEFAULT_BREAKPOINTS, selector_theme}; use super::values::{Literal, NativeValue, ROOT_FONT_SIZE}; use super::{NativePlatform, NativeTarget, REACT_NATIVE, RUNTIME, Replacement}; use crate::component::ExportVariableKind; @@ -39,52 +41,96 @@ pub(super) struct Compiled { struct Runtime { /// The variable holding the index of the theme the app shows index: String, - /// The hook reading that index - hook: String, - hook_used: bool, - /// The component that reads the index itself, for an element outside a + /// The variable holding the breakpoint the window is at + breakpoint: String, + /// The variable holding whether the window is in landscape + landscape: String, + /// The hooks reading each, by what they read + hooks: [String; 3], + /// What the hooks the file calls read + hooks_used: Reads, + /// The component that reads them itself, for an element outside a /// function component wrapper: String, wrapper_used: bool, + /// What the elements rendered through it read + wrapper_reads: Reads, /// The function telling the runtime the theme names define: String, + /// The function telling the runtime the breakpoints + define_breakpoints: String, } +/// The runtime hooks, in the order they are called, by the name they are +/// exported under: they read the theme, the breakpoint and the orientation +const HOOKS: [&str; 3] = ["useThemeIndex", "useBreakpoint", "useLandscape"]; + impl Runtime { fn new(code: &str) -> Self { Self { index: fresh_name("__t", code), - hook: fresh_name("__useThemeIndex", code), - hook_used: false, + breakpoint: fresh_name("__b", code), + landscape: fresh_name("__l", code), + hooks: HOOKS.map(|hook| fresh_name(&format!("__{hook}"), code)), + hooks_used: Reads::default(), wrapper: fresh_name("__Themed", code), wrapper_used: false, + wrapper_reads: Reads::default(), define: fresh_name("__defineThemes", code), + define_breakpoints: fresh_name("__defineBreakpoints", code), + } + } + + /// The variables holding what the runtime tells + fn vars(&self) -> Vars<'_> { + Vars { + theme: &self.index, + breakpoint: &self.breakpoint, + landscape: &self.landscape, } } - /// The import of the runtime and the call telling it the theme names, - /// when the file uses it + /// The variables of `reads`, in the order of the hooks + fn variables(&self, reads: Reads) -> impl Iterator { + [&self.index, &self.breakpoint, &self.landscape] + .into_iter() + .enumerate() + .filter(move |(at, _)| reads.flags()[*at]) + .map(|(at, name)| (at, name.as_str())) + } + + /// 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.hook_used || self.wrapper_used || theme_api) { + if !(self.hooks_used.any() || self.wrapper_used || theme_api) { return None; } - let mut specifiers = Vec::new(); - if self.hook_used { - specifiers.push(format!("useThemeIndex as {}", self.hook)); - } + let reads = self.hooks_used.union(self.wrapper_reads); + let mut specifiers: Vec = self + .variables(self.hooks_used) + .map(|(at, _)| format!("{} as {}", HOOKS[at], self.hooks[at])) + .collect(); if self.wrapper_used { specifiers.push(format!("Themed as {}", self.wrapper)); } - specifiers.push(format!("defineThemes as {}", self.define)); let theme = &target.theme; - let names = serde_json::Value::from(theme.names.clone()).to_string(); - let dark = theme - .dark - .map_or_else(String::new, |dark| format!(", {dark}")); + let mut calls = String::new(); + if reads.theme || theme_api { + specifiers.push(format!("defineThemes as {}", self.define)); + let names = serde_json::Value::from(theme.names.clone()).to_string(); + let dark = theme + .dark + .map_or_else(String::new, |dark| format!(", {dark}")); + let _ = writeln!(calls, "{}({names}{dark});", self.define); + } + if reads.breakpoint && theme.breakpoints != DEFAULT_BREAKPOINTS { + specifiers.push(format!("defineBreakpoints as {}", self.define_breakpoints)); + let breakpoints = serde_json::Value::from(theme.breakpoints.clone()).to_string(); + let _ = writeln!(calls, "{}({breakpoints});", self.define_breakpoints); + } Some(format!( - "import {{ {} }} from \"{RUNTIME}\";\n{}({names}{dark});\n", - specifiers.join(", "), - self.define + "import {{ {} }} from \"{RUNTIME}\";\n{calls}", + specifiers.join(", ") )) } } @@ -94,8 +140,8 @@ struct Frame { /// Whether it is a function component or a hook, where the hook reading /// the theme can be called first component: bool, - /// Whether an element in it reads the theme - used: bool, + /// What the elements in it read from the runtime + reads: Reads, /// Where the hook is called hook_at: HookAt, } @@ -177,6 +223,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), /// What React Native has no equivalent of @@ -194,7 +243,8 @@ fn classify(name: &str) -> Prop { "_android" => Prop::Platform(NativePlatform::Android), "_web" => Prop::Platform(NativePlatform::Web), "_pressed" | "_active" => Prop::Runtime(RuntimeFeature::Pressed), - "_portrait" | "_landscape" => Prop::Runtime(RuntimeFeature::Responsive), + "_portrait" => Prop::Orientation(false), + "_landscape" => Prop::Orientation(true), "className" => Prop::Unsupported(Problem::new( "React Native has no class names", "write the styles as props, or pass them in `style`", @@ -429,21 +479,26 @@ impl<'a> Elements<'_> { }; self.frames.push(Frame { component, - used: false, + reads: Reads::default(), hook_at, }); visit(self); if let Some(frame) = self.frames.pop() - && frame.used + && frame.reads.any() { - self.call_hook(frame.hook_at); + self.call_hooks(frame.hook_at, frame.reads); } } - /// Call the hook reading the theme at `at` - fn call_hook(&mut self, at: HookAt) { - self.runtime.hook_used = true; - let call = format!("const {} = {}();", self.runtime.index, self.runtime.hook); + /// Call the hooks reading what `reads` names at `at` + fn call_hooks(&mut self, at: HookAt, reads: Reads) { + self.runtime.hooks_used = self.runtime.hooks_used.union(reads); + let calls: Vec = self + .runtime + .variables(reads) + .map(|(hook, variable)| format!("const {variable} = {}();", self.runtime.hooks[hook])) + .collect(); + let call = calls.join(" "); match at { HookAt::Body(at) => self.replacements.push((at, at, format!("\n{call}"))), HookAt::Expression(start, end) => { @@ -455,42 +510,70 @@ impl<'a> Elements<'_> { } /// Whether the element being compiled is in a function component or a - /// hook, which then reads the theme first - fn reads_theme_in_component(&mut self) -> bool { + /// hook, which then calls the hooks reading what `reads` names first + fn read_in_component(&mut self, reads: Reads) -> bool { match self.frames.iter_mut().rev().find(|frame| frame.component) { Some(frame) => { - frame.used = true; + frame.reads = frame.reads.union(reads); true } None => false, } } - /// The styles a style prop declares with a literal: one style object, or - /// one a theme when its tokens differ by theme - fn static_choice(&self, name: &str, literal: &Literal) -> Result { + /// The styles a style prop declares with literals, each from the + /// 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 theme = &self.target.theme; - let indexes = match self.theme_scope { + let themes = match self.theme_scope { Some(index) => index..index + 1, - None if names_tokens(name, literal) => 0..theme.count(), + None if items.iter().any(|(_, literal)| names_tokens(name, literal)) => { + 0..theme.count() + } None => 0..1, }; - let mut variants = Vec::new(); - for index in indexes { - let tokens = Tokens { - theme, - index, - target: self.target, - }; - variants.push(declarations(name, literal, &tokens)?.unwrap_or_default()); - } - let choice = themed(variants); - if choice.reads_theme() && !self.target.runtime { - return Err(RuntimeFeature::Theme.problem(self.target)); + let levels = items + .iter() + .map(|(from, literal)| (from + 1).max(literal_levels(name, literal, theme))) + .fold(1, usize::max) + .min(theme.levels()); + let mut grid = Vec::with_capacity(levels); + for level in 0..levels { + let mut row = Vec::with_capacity(themes.len()); + for index in themes.clone() { + row.push(cell( + name, + items, + &Tokens { + theme, + index, + level, + }, + )?); + } + grid.push(row); } + let choice = varied(grid); + self.check_runtime(&choice)?; Ok(choice) } + /// Fail for a choice the runtime makes when it is turned off + fn check_runtime(&self, choice: &Choice) -> Result<(), Problem> { + let reads = choice.reads(); + let feature = if self.target.runtime { + None + } else if reads.breakpoint { + Some(RuntimeFeature::Responsive) + } else if reads.theme { + Some(RuntimeFeature::Theme) + } else { + None + }; + feature.map_or(Ok(()), |feature| Err(feature.problem(self.target))) + } + /// Compile one Devup UI element fn element(&mut self, element: &JSXElement<'a>, kind: &ExportVariableKind, local: &str) { let opening = &element.opening_element; @@ -580,6 +663,16 @@ impl<'a> Elements<'_> { ); styles.choices.extend(choices); } + Prop::Orientation(landscape) => { + styles.removed.push(span); + let choices = self.orientation_block( + attribute_expression(attribute), + (name, landscape), + attribute.span.start, + local, + ); + styles.choices.extend(choices); + } Prop::Runtime(feature) => self.error( attribute.span.start, feature.problem(self.target).on(local, name), @@ -733,6 +826,30 @@ 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( + &mut self, + value: Option<&Expression<'a>>, + (name, landscape): (&str, bool), + offset: u32, + local: &str, + ) -> Vec { + if !self.target.runtime { + self.error( + offset, + RuntimeFeature::Orientation + .problem(self.target) + .on(local, name), + ); + return Vec::new(); + } + self.block(value, name, offset, local) + .into_iter() + .map(|choice| when(State::Landscape(landscape), 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(); @@ -792,6 +909,9 @@ 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)); } @@ -817,7 +937,7 @@ impl<'a> Elements<'_> { match value { Some(JSXAttributeValue::StringLiteral(literal)) => literal.value.as_str().map_or_else( || self.dynamic_choice(name, literal.span.source_text(self.code)), - |text| self.static_choice(name, &Literal::Text(text.to_string())), + |text| self.static_choice(name, &[(0, Literal::Text(text.to_string()))]), ), Some(JSXAttributeValue::ExpressionContainer(container)) => container .expression @@ -839,7 +959,7 @@ impl<'a> Elements<'_> { expression: &Expression<'a>, ) -> Result { if let Some(literal) = literal(expression) { - return self.static_choice(name, &literal); + return self.static_choice(name, &[(0, literal)]); } match expression.without_parentheses() { Expression::NullLiteral(_) | Expression::BooleanLiteral(_) => Ok(Choice::Empty), @@ -858,7 +978,7 @@ impl<'a> Elements<'_> { alternate: Box::new(Choice::Empty), }) } - Expression::ArrayExpression(_) => Err(RuntimeFeature::Responsive.problem(self.target)), + Expression::ArrayExpression(array) => self.responsive_choice(name, array), Expression::ObjectExpression(_) => Err(Problem::new( "a style prop takes one value, not an object", "give one value, or use a platform block such as `_ios`", @@ -867,6 +987,62 @@ impl<'a> Elements<'_> { } } + /// The styles a responsive array declares: each value from the + /// breakpoint at its index on, as on the web, where `null` and + /// `undefined` keep the value before. Literals compile to one style + /// object a breakpoint; any other value applies from its breakpoint on + fn responsive_choice( + &self, + name: &str, + array: &ArrayExpression<'a>, + ) -> Result { + let last = self.target.theme.levels() - 1; + let mut items = Vec::new(); + for (index, element) in array.elements.iter().enumerate() { + match element.as_expression() { + Some(expression) if !is_empty_value(expression) => { + items.push((index.min(last), expression)); + } + None if matches!(element, ArrayExpressionElement::SpreadElement(_)) => { + return Err(Problem::new( + "the build reads only the values written in a responsive array", + "write each value in the array", + )); + } + _ => {} + } + } + let literals: Option> = items + .iter() + .map(|(level, expression)| literal(expression).map(|literal| (*level, literal))) + .collect(); + if let Some(literals) = literals { + return self.static_choice(name, &literals); + } + if !self.target.runtime { + return Err(RuntimeFeature::Responsive.problem(self.target)); + } + let mut choices = Vec::with_capacity(items.len()); + for (level, expression) in items { + if matches!( + expression.without_parentheses(), + Expression::ArrayExpression(_) + ) { + return Err(Problem::new( + "a responsive array holds one value a breakpoint", + "write each value itself, not an array", + )); + } + let choice = self.expression_choice(name, expression)?; + choices.push(if level == 0 { + choice + } else { + when(State::AtLeast(level), choice) + }); + } + Ok(Choice::All(choices)) + } + /// The styles a style prop declares with the value `code` the element /// reads at runtime fn dynamic_choice(&self, name: &str, code: &str) -> Result { @@ -942,12 +1118,14 @@ impl<'a> Elements<'_> { style, opaque_spread, } = styles; - let style_code = style_code(choices, given, &mut self.sheet, &self.runtime.index); - let wrapped = style_code + let style_code = style_code(choices, given, &mut self.sheet, &self.runtime.vars()); + let reads = style_code .as_ref() - .is_some_and(|style| style.reads_theme && !self.reads_theme_in_component()); + .map_or_else(Reads::default, |style| style.reads); + let wrapped = reads.any() && !self.read_in_component(reads); if wrapped { self.runtime.wrapper_used = true; + self.runtime.wrapper_reads = self.runtime.wrapper_reads.union(reads); let wrapper = self.runtime.wrapper.clone(); self.rename(element, &wrapper); } else if let Some(tag) = &tag { @@ -958,10 +1136,21 @@ impl<'a> Elements<'_> { return; }; let code = if wrapped { + // The wrapper gives the theme, the breakpoint and the orientation, + // in this order: the style takes them up to the last it reads + let read = self.runtime.variables(reads).last().map_or(0, |(at, _)| at); + let parameters = [ + &self.runtime.index, + &self.runtime.breakpoint, + &self.runtime.landscape, + ][..=read] + .iter() + .map(|name| name.as_str()) + .collect::>() + .join(", "); format!( - " $c={{{}}} $s={{({}) => ({})}}", + " $c={{{}}} $s={{({parameters}) => ({})}}", tag.as_deref().unwrap_or(local), - self.runtime.index, style_code.code ) } else { @@ -1085,6 +1274,34 @@ fn literal(expression: &Expression<'_>) -> Option { } } +/// The styles the literals of `items` declare for the style prop `name` at +/// the breakpoint and in the theme of `tokens`: each literal from its +/// breakpoint on, a later one declared after the one before +fn cell( + name: &str, + items: &[(usize, Literal)], + tokens: &Tokens<'_>, +) -> Result, Problem> { + let mut declared = Vec::new(); + for (_, literal) in items.iter().filter(|(from, _)| *from <= tokens.level) { + cascade( + &mut declared, + declarations(name, literal, tokens)?.unwrap_or_default(), + ); + } + Ok(declared) +} + +/// Whether `expression` declares nothing, as `null`, `undefined` and +/// booleans do +fn is_empty_value(expression: &Expression<'_>) -> bool { + match expression.without_parentheses() { + Expression::NullLiteral(_) | Expression::BooleanLiteral(_) => true, + Expression::Identifier(identifier) => identifier.name == "undefined", + _ => false, + } +} + /// Whether the styles of `literal` for the style prop `name` may differ by /// theme: a typography, or a value naming a `$token` fn names_tokens(name: &str, literal: &Literal) -> bool { diff --git a/libs/extractor/src/native/errors.rs b/libs/extractor/src/native/errors.rs index 6e21074b3..31259ea32 100644 --- a/libs/extractor/src/native/errors.rs +++ b/libs/extractor/src/native/errors.rs @@ -39,6 +39,7 @@ impl Problem { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum RuntimeFeature { Responsive, + Orientation, Theme, Pressed, } @@ -47,6 +48,7 @@ impl RuntimeFeature { const fn what(self) -> &'static str { match self { 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", } @@ -54,7 +56,8 @@ impl RuntimeFeature { const fn fix(self) -> &'static str { match self { - Self::Responsive => "give one value", + 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`" diff --git a/libs/extractor/src/native/mod.rs b/libs/extractor/src/native/mod.rs index 68911d456..e578e65a8 100644 --- a/libs/extractor/src/native/mod.rs +++ b/libs/extractor/src/native/mod.rs @@ -9,8 +9,10 @@ //! platform blocks `_ios`, `_android` and `_web`, and theme tokens when the //! theme has one value for them. A value that differs by theme compiles to //! one style object a theme, and the element picks one by the index the -//! runtime of `@devup-ui/react/native` gives. Responsive arrays and -//! `_pressed` need a runtime that this version does not include, and a prop +//! 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. mod element; diff --git a/libs/extractor/src/native/props.rs b/libs/extractor/src/native/props.rs index 6d0eceb1a..ca966cebd 100644 --- a/libs/extractor/src/native/props.rs +++ b/libs/extractor/src/native/props.rs @@ -11,7 +11,6 @@ use phf::phf_map; use crate::extract_style::constant::is_maintain_value_property; -use super::NativeTarget; use super::errors::Problem; use super::theme::NativeTheme; use super::values::{ @@ -238,14 +237,16 @@ fn check_text(text: &str) -> Result<(), Problem> { /// compiled with pub(super) struct Tokens<'t> { pub theme: &'t NativeTheme, + /// The index of the theme pub index: usize, - pub target: &'t NativeTarget, + /// The breakpoint + pub level: usize, } impl Tokens<'_> { /// `text` with its tokens resolved, or `None` when the theme lacks one fn resolve<'v>(&self, text: &'v str) -> Result>, Problem> { - self.theme.resolve(text, self.index, self.target) + self.theme.resolve(text, (self.index, self.level)) } } @@ -274,6 +275,16 @@ pub(super) fn declarations( Ok(Some(declarations)) } +/// How many breakpoints the styles of the style prop `prop` with the value +/// `literal` tell apart through the responsive tokens or typography it names +pub(super) fn literal_levels(prop: &str, literal: &Literal, theme: &NativeTheme) -> usize { + match literal { + Literal::Text(text) if prop == "typography" => theme.typography_levels(text), + Literal::Text(text) => theme.token_levels(text), + Literal::Number(_) => 1, + } +} + /// `literal` as text fn literal_text(literal: &Literal) -> Cow<'_, str> { match literal { @@ -287,20 +298,20 @@ fn literal_text(literal: &Literal) -> Cow<'_, str> { /// multiplied by it, as React Native reads both in pixels fn typography(name: &str, tokens: &Tokens<'_>) -> Result>, Problem> { let mut properties = Vec::new(); - for (property, value) in tokens.theme.typography(name, tokens.target)? { - let Some(value) = tokens.resolve(value)? else { + for (property, value) in tokens.theme.typography(name, tokens.level)? { + let Some(value) = tokens.resolve(&value)?.map(Cow::into_owned) else { return Ok(None); }; check_text(&value)?; - properties.push((property.as_str(), value.into_owned())); + properties.push((property, value)); } let font_size = properties .iter() - .find(|(property, _)| *property == "font-size") + .find(|(property, _)| property == "font-size") .and_then(|(_, value)| scaled_length(value.trim()).or_else(|| number(value))); let mut declarations = Vec::new(); for (property, value) in &properties { - match *property { + match property.as_str() { "line-height" | "letter-spacing" => { declarations.extend(relative_to_font(property, value, font_size)?); } diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__orientation.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__orientation.snap index 4b19decba..c9626a9d3 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__orientation.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__orientation.snap @@ -2,5 +2,11 @@ source: libs/extractor/src/native/tests.rs expression: compile(code) --- -error: test.tsx:2:6: `` cannot use `_portrait` on React Native: a responsive value is chosen by the window width, which needs the React Native runtime that this version does not include yet. Fix: give one value -test.tsx:2:27: `` cannot use `_landscape` on React Native: a responsive value is chosen by the window width, which needs the React Native runtime that this version does not include yet. Fix: give one value +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 { Themed as __Themed } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { padding: 4 }, + b: { padding: 8 } +}); +<__Themed $c={Box} $s={(__t, __b, __l) => [!__l && __s.a, __l && __s.b]} />; 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 new file mode 100644 index 000000000..d939c9b22 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__orientation_blocks.snap @@ -0,0 +1,29 @@ +--- +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 { useBreakpoint as __useBreakpoint, useLandscape as __useLandscape } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { flexDirection: "row" }, + b: { flexDirection: "column" }, + c: { padding: 4 }, + d: { padding: 8 }, + e: { padding: 12 }, + f: { padding: 16 }, + g: { margin: 4 } +}); +export function Screen({ on }) { + const __b = __useBreakpoint(); + const __l = __useLandscape(); + return + + ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__orientation_value.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__orientation_value.snap new file mode 100644 index 000000000..0c621a572 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__orientation_value.snap @@ -0,0 +1,6 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, code)" +--- +error: test.tsx:2:6: `` cannot use `_landscape` on React Native: `_landscape` takes an object of styles. Fix: write the styles in an object, such as `_landscape={{ p: 2 }}` +test.tsx:2:34: `` cannot use `p` on React Native: a style prop takes one value, not an object. Fix: give one value, or use a platform block such as `_ios` 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 0d58afdd6..725ae4af6 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 @@ -10,4 +10,3 @@ test.tsx:2:63: `` cannot use `_hover` on React Native: React Native has no 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 -test.tsx:2:110: `` cannot use `bg` on React Native: a responsive value is chosen by the window width, which needs the React Native runtime that this version does not include yet. Fix: give one value diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive.snap index 8ca40cd95..7ef5c17bd 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive.snap @@ -2,4 +2,11 @@ source: libs/extractor/src/native/tests.rs expression: compile(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 this version does not include yet. Fix: give one value +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 { Themed as __Themed } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { padding: 4 }, + b: { padding: 8 } +}); +<__Themed $c={Box} $s={(__t, __b) => __b < 1 ? __s.a : __s.b} />; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_arrays.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_arrays.snap new file mode 100644 index 000000000..5c5841189 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_arrays.snap @@ -0,0 +1,98 @@ +--- +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 { useBreakpoint as __useBreakpoint } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { margin: 8 }, + b: { padding: 4 }, + c: { padding: 12 }, + d: { padding: 8 }, + e: { padding: 16 }, + f: { padding: 20 }, + g: { padding: 32 }, + h: { + padding: 8, + width: "50%" + }, + i: { backgroundColor: "red" }, + j: { + marginVertical: 1, + marginHorizontal: 2, + paddingVertical: 1, + paddingHorizontal: 2 + }, + k: { + margin: 3, + paddingVertical: 1, + paddingHorizontal: 2 + }, + l: { + margin: 3, + paddingVertical: 3, + paddingHorizontal: 4 + }, + m: { margin: 4 }, + n: { + padding: 16, + margin: 8 + }, + o: { + padding: 4, + margin: 12, + gap: 4 + }, + p: { + padding: 8, + margin: 12, + gap: 8 + }, + q: { + padding: 8, + margin: 16, + gap: 8 + }, + r: { + paddingTop: 12, + paddingBottom: 12 + }, + s: { + paddingLeft: 4, + paddingRight: 4 + }, + t: { + paddingLeft: 8, + paddingRight: 8 + } +}); +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 function Layout({ on, x }) { + const __b = __useBreakpoint(); + return + + + + + = 1 && __s.d]} /> + = 2 && __s.c, + on && __s.m, + __b >= 1 && { margin: __u(x, 4) } + ]} /> + + + + + + + + = 1 && __s.d] : __s.c, __s.b]} /> + ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_custom_breakpoints.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_custom_breakpoints.snap new file mode 100644 index 000000000..7f2e12013 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_custom_breakpoints.snap @@ -0,0 +1,22 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(theme, 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, useBreakpoint as __useBreakpoint, Themed as __Themed, defineThemes as __defineThemes, defineBreakpoints as __defineBreakpoints } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +__defineBreakpoints([0, 600]); +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { margin: 4 }, + b: { margin: 6 }, + c: { padding: 4 }, + d: { padding: 12 }, + e: { padding: 8 } +}); +export const A = () => { + const __t = __useThemeIndex(); + const __b = __useBreakpoint(); + return ; +}; +export const b = <__Themed $c={Box} $s={(__t, __b) => __b < 1 ? __s.c : __s.e} />; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_hooks_in_arrow.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_hooks_in_arrow.snap new file mode 100644 index 000000000..862ae770b --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_hooks_in_arrow.snap @@ -0,0 +1,31 @@ +--- +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, useBreakpoint as __useBreakpoint, useLandscape as __useLandscape, Themed as __Themed, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { backgroundColor: "#5a44ff" }, + b: { backgroundColor: "#8c7bff" }, + c: { padding: 4 }, + d: { padding: 8 }, + e: { margin: 4 } +}); +export const A = () => { + const __t = __useThemeIndex(); + const __b = __useBreakpoint(); + const __l = __useLandscape(); + return ; +}; +export const B = () => { + const __l = __useLandscape(); + return ; +}; +export const c = <__Themed $c={Box} $s={(__t, __b, __l) => [__b < 1 ? __s.c : __s.d, __l && __s.e]} />; +export const d = <__Themed $c={Box} $s={(__t, __b) => [[__s.a, __s.b][__t], __b < 1 ? __s.c : __s.d]} />; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_in_condition.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_in_condition.snap index 8ca40cd95..80de23140 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_in_condition.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_in_condition.snap @@ -2,4 +2,12 @@ source: libs/extractor/src/native/tests.rs expression: compile(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 this version does not include yet. Fix: give one value +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 { Themed as __Themed } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { padding: 4 }, + b: { padding: 8 }, + c: { padding: 12 } +}); +<__Themed $c={Box} $s={(__t, __b) => on ? __b < 1 ? __s.a : __s.b : __s.c} />; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_name_collisions.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_name_collisions.snap new file mode 100644 index 000000000..1e32b3aef --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_name_collisions.snap @@ -0,0 +1,18 @@ +--- +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 { useBreakpoint as __useBreakpoint_, useLandscape as __useLandscape_ } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { padding: 4 }, + b: { padding: 8 }, + c: { margin: 4 } +}); +const __b = 1, __l = 2, __useBreakpoint = 3, __useLandscape = 4; +export const A = () => { + const __b_ = __useBreakpoint_(); + const __l_ = __useLandscape_(); + return ; +}; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_nested.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_nested.snap new file mode 100644 index 000000000..9fc3450e8 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_nested.snap @@ -0,0 +1,5 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, code)" +--- +error: test.tsx:2:6: `` cannot use `p` on React Native: a responsive array holds one value a breakpoint. Fix: write each value itself, not an array diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_no_breakpoints.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_no_breakpoints.snap new file mode 100644 index 000000000..d239d9ff0 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_no_breakpoints.snap @@ -0,0 +1,17 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(theme, 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: { padding: 12 }, + b: { margin: 4 }, + c: { margin: 6 } +}); +export const A = () => { + const __t = __useThemeIndex(); + return ; +}; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_spread.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_spread.snap new file mode 100644 index 000000000..4c3bcc5e2 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_spread.snap @@ -0,0 +1,5 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, code)" +--- +error: test.tsx:2:6: `` cannot use `p` on React Native: the build reads only the values written in a responsive array. Fix: write each value in the array diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_themes.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_themes.snap new file mode 100644 index 000000000..4b4b74e10 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__responsive_themes.snap @@ -0,0 +1,99 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(theme, 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, useBreakpoint as __useBreakpoint, useLandscape as __useLandscape, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { borderColor: "#5a44ff" }, + b: { borderColor: "#8c7bff" }, + c: { margin: 4 }, + d: { margin: 8 }, + e: { + backgroundColor: "#5a44ff", + padding: 4 + }, + f: { + backgroundColor: "#8c7bff", + padding: 6 + }, + g: { + backgroundColor: "#111", + padding: 4 + }, + h: { + backgroundColor: "#eee", + padding: 6 + }, + i: { + backgroundColor: "#111", + padding: 8 + }, + j: { + backgroundColor: "#eee", + padding: 12 + }, + k: { color: "#111" }, + l: { color: "#eee" }, + m: { fontSize: 24 }, + n: { fontSize: 32 }, + o: { fontFamily: "Inter" }, + p: { + fontSize: 12, + lineHeight: 18 + }, + q: { + fontSize: 14, + lineHeight: 21 + }, + r: { + fontSize: 40, + lineHeight: 60 + }, + s: { + fontFamily: "Inter", + fontWeight: "500", + lineHeight: 24, + letterSpacing: -.32 + }, + t: { fontSize: 16 }, + u: { backgroundColor: "#8c7bff" }, + v: { padding: 4 }, + w: { padding: 8 }, + x: { margin: 2 }, + y: { padding: 6 }, + z: { backgroundColor: "#5a44ff" }, + aa: { backgroundColor: "red" }, + ab: { backgroundColor: "#111" }, + ac: { backgroundColor: "#eee" }, + ad: { borderStyle: "solid" }, + ae: { borderWidth: 1 }, + af: { borderWidth: 2 }, + ag: { padding: 12 } +}); +export function Card({ on }) { + const __t = __useThemeIndex(); + const __b = __useBreakpoint(); + const __l = __useLandscape(); + return + + + + + = 1 && __s.x, __b < 2 ? [__s.v, __s.y][__t] : __s.v]} /> + + + + + ; +} 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 ec6bc54a4..9dc9cebe4 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 @@ -2,6 +2,6 @@ source: libs/extractor/src/native/tests.rs 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 +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_off_arrays.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_arrays.snap new file mode 100644 index 000000000..0baeb4e15 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_arrays.snap @@ -0,0 +1,7 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(one_theme(), false, 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:3: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:4:25: `` cannot use `w` 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 diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_orientation.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_orientation.snap new file mode 100644 index 000000000..4294c17ed --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_orientation.snap @@ -0,0 +1,6 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(one_theme(), false, code)" +--- +error: test.tsx:2:6: `` cannot use `_landscape` on React Native: an orientation style is chosen by the orientation of the window, which needs the React Native runtime that `runtime: false` turns off. Fix: remove it, or turn the runtime on +test.tsx:2:28: `` cannot use `_portrait` on React Native: an orientation style is chosen by the orientation of the window, which needs the React Native runtime that `runtime: false` turns off. Fix: remove it, or turn the runtime on diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_responsive_tokens.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_responsive_tokens.snap new file mode 100644 index 000000000..26dcc8b86 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__runtime_off_responsive_tokens.snap @@ -0,0 +1,6 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(one_theme(), false, 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:3:7: `` cannot use `typography` 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 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 441bb88d5..7b1927f74 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 @@ -2,6 +2,5 @@ source: libs/extractor/src/native/tests.rs 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 this version does not include yet. Fix: give one value -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 +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_responsive_tokens.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_responsive_tokens.snap index ee9541720..2e4b87ae3 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__theme_responsive_tokens.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_responsive_tokens.snap @@ -2,4 +2,12 @@ source: libs/extractor/src/native/tests.rs expression: "compile_themed(two_themes(), true, code)" --- -error: test.tsx:2:6: `` cannot use `p` on React Native: `gutter` has a value at each breakpoint: a responsive value is chosen by the window width, which needs the React Native runtime that this version does not include yet. Fix: give it one value in devup.json, or write the value itself +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 { Themed as __Themed } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { margin: 2 }, + b: { padding: 4 }, + c: { padding: 8 } +}); +<__Themed $c={Box} $s={(__t, __b) => [__s.a, __b < 2 ? __s.b : __s.c]} />; 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 559ed4ebb..78a879126 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 @@ -33,40 +33,36 @@ const __s = StyleSheet.create({ h: { color: "#eee" }, i: { color: "red" }, j: { - fontSize: 12, - lineHeight: 18, letterSpacing: 1, textTransform: "uppercase" }, k: { - fontSize: 14, - lineHeight: 21, - letterSpacing: 1, - textTransform: "uppercase" + fontSize: 12, + lineHeight: 18 }, - l: { borderColor: "#eef" }, - m: { borderColor: "#223" }, - n: { - borderWidth: 1, - borderStyle: "solid", - borderColor: "#5a44ff" + l: { + fontSize: 14, + lineHeight: 21 }, + m: { borderColor: "#eef" }, + n: { borderColor: "#223" }, o: { borderWidth: 1, - borderStyle: "solid", - borderColor: "#8c7bff" + borderStyle: "solid" }, - p: { margin: 8 }, - q: { opacity: .5 }, - r: { padding: 4 }, - s: { padding: 8 }, - t: { + p: { borderColor: "#5a44ff" }, + q: { borderColor: "#8c7bff" }, + r: { margin: 8 }, + s: { opacity: .5 }, + t: { padding: 4 }, + u: { padding: 8 }, + v: { backgroundColor: "#5a44ff", margin: 4 }, - u: { color: "#000" }, - v: { fontFamily: "#000" }, - w: { margin: 4 } + w: { color: "#000" }, + x: { fontFamily: "#000" }, + y: { margin: 4 } }); export function Card({ on, color }) { const __t = __useThemeIndex(); @@ -74,19 +70,20 @@ export function Card({ on, color }) { Hi - - - - + + + + ; } diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__theme_typographies.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_typographies.snap index 8d134d650..efb66b50f 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__theme_typographies.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_typographies.snap @@ -3,7 +3,6 @@ source: libs/extractor/src/native/tests.rs expression: "compile_themed(two_themes(), true, code)" --- error: test.tsx:2:7: `` cannot use `typography` on React Native: devup.json defines no `missing` typography. Fix: add the typography to the theme in devup.json -test.tsx:3:7: `` cannot use `typography` on React Native: `heading` has a value at each breakpoint: a responsive value is chosen by the window width, which needs the React Native runtime that this version does not include yet. Fix: give it one value in devup.json, or write the value itself test.tsx:4:7: `` cannot use `typography` on React Native: the build reads the styles of a typography by its name, which a value read at runtime does not give. Fix: write the name, or a condition between names such as `typography={big ? 'h1' : 'body'}` test.tsx:5:7: `` cannot use `typography` on React Native: `2em` is relative to the font size, and the typography has no font size in pixels. Fix: give the typography a `fontSize` in pixels, or the value in pixels test.tsx:6:7: `` cannot use `typography` on React Native: devup.json defines no `1` typography. Fix: add the typography to the theme in devup.json diff --git a/libs/extractor/src/native/style.rs b/libs/extractor/src/native/style.rs index f6e48f5ea..26e71d31d 100644 --- a/libs/extractor/src/native/style.rs +++ b/libs/extractor/src/native/style.rs @@ -4,6 +4,22 @@ use super::props::Declaration; use super::sheet::Sheet; +/// The styles of a value at each breakpoint, each with the styles in each +/// theme: `grid[level][theme]`. A breakpoint past the last takes the styles of +/// the last, and a row of one theme holds the styles of every theme +pub(super) type Grid = Vec>>; + +/// What a choice applies only while it holds +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum State { + /// The theme at this index shows + Theme(usize), + /// The window is at this breakpoint or a wider one + AtLeast(usize), + /// The window is in landscape (`true`) or portrait (`false`) orientation + Landscape(bool), +} + /// The styles one prop declares #[derive(Debug, Clone, PartialEq)] pub(super) enum Choice { @@ -20,24 +36,74 @@ pub(super) enum Choice { consequent: Box, alternate: Box, }, - /// Styles the build knows for each theme, in the order of the theme - /// names; the element picks one by the theme the app shows - Themed(Vec>), - /// A choice that applies only while the theme at `index` shows - InTheme { index: usize, choice: Box }, + /// Styles the build knows for each breakpoint and theme; the element + /// picks one by the breakpoint and the theme the app shows + Varied(Grid), + /// A choice that applies only while `state` holds + When { state: State, choice: Box }, + /// Choices applied one after the other + All(Vec), } -/// The choice of `variants`, one a theme: static when every theme declares -/// the same styles -pub(super) fn themed(mut variants: Vec>) -> Choice { - if variants.windows(2).all(|pair| pair[0] == pair[1]) { - variants - .pop() - .filter(|declarations| !declarations.is_empty()) - .map_or(Choice::Empty, Choice::Static) - } else { - Choice::Themed(variants) +/// What the runtime tells a style: which theme shows, which breakpoint the +/// window is at, and whether it is in landscape +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub(super) struct Reads { + pub theme: bool, + pub breakpoint: bool, + pub landscape: bool, +} + +impl Reads { + pub(super) const fn any(self) -> bool { + self.theme || self.breakpoint || self.landscape + } + + /// What it reads, in the order of the runtime's hooks + pub(super) const fn flags(self) -> [bool; 3] { + [self.theme, self.breakpoint, self.landscape] + } + + pub(super) const fn union(self, other: Self) -> Self { + Self { + theme: self.theme || other.theme, + breakpoint: self.breakpoint || other.breakpoint, + landscape: self.landscape || other.landscape, + } + } +} + +/// The names of the variables holding what the runtime tells +pub(super) struct Vars<'v> { + pub theme: &'v str, + pub breakpoint: &'v str, + pub landscape: &'v str, +} + +/// The choice of `grid`, as small as it can be: the last breakpoints that +/// repeat the one before dropped, one theme when every theme declares the +/// same, static with one breakpoint and one theme +pub(super) fn varied(mut grid: Grid) -> Choice { + if grid.iter().flatten().all(Vec::is_empty) { + return Choice::Empty; + } + while grid.len() > 1 && grid[grid.len() - 1] == grid[grid.len() - 2] { + grid.pop(); } + if grid + .iter() + .all(|row| row.windows(2).all(|pair| pair[0] == pair[1])) + { + for row in &mut grid { + row.truncate(1); + } + } + if let [row] = grid.as_mut_slice() + && let [declarations] = row.as_mut_slice() + { + return Choice::Static(std::mem::take(declarations)); + } + Choice::Varied(grid) } /// `choice` applied only while the theme at `index` of `count` shows @@ -45,32 +111,60 @@ pub(super) fn in_theme(index: usize, count: usize, choice: Choice) -> Choice { match choice { Choice::Empty => Choice::Empty, choice if count <= 1 => choice, - Choice::Static(declarations) => Choice::Themed( - (0..count) - .map(|at| { - if at == index { - declarations.clone() - } else { - Vec::new() - } + Choice::Static(declarations) => { + in_theme(index, count, Choice::Varied(vec![vec![declarations]])) + } + Choice::Varied(grid) => varied( + grid.into_iter() + .map(|row| { + (0..count) + .map(|at| { + if at == index { + cell(&row, at).clone() + } else { + Vec::new() + } + }) + .collect() }) .collect(), ), - Choice::Themed(mut variants) => { - for (at, variant) in variants.iter_mut().enumerate() { - if at != index { - variant.clear(); - } - } - Choice::Themed(variants) - } - choice => Choice::InTheme { - index, + choice => when(State::Theme(index), choice), + } +} + +/// `choice` applied only while `state` holds +pub(super) fn when(state: State, choice: Choice) -> Choice { + match choice { + Choice::Empty => Choice::Empty, + // A block in a block of the same state, such as `_landscape` in + // `_landscape`, holds while the outer one does + Choice::When { + state: inner, + choice, + } if inner == state => Choice::When { state, choice }, + choice => Choice::When { + state, choice: Box::new(choice), }, } } +/// The styles of `row` in the theme at `theme` +const fn cell(row: &[Vec], theme: usize) -> &Vec { + &row[if row.len() == 1 { 0 } else { theme }] +} + +/// The styles of `grid` at the breakpoint `level` in the theme at `theme` +fn grid_cell(grid: &Grid, level: usize, theme: usize) -> &Vec { + cell(&grid[level.min(grid.len() - 1)], theme) +} + +/// How many themes a row of `grid` holds +fn themes_of(grid: &Grid) -> usize { + grid.iter().map(Vec::len).max().unwrap_or(1) +} + impl Choice { /// Whether the choice declares the React Native style `key` fn declares(&self, key: &str) -> bool { @@ -83,29 +177,38 @@ impl Choice { alternate, .. } => consequent.declares(key) || alternate.declares(key), - Self::Themed(variants) => variants + Self::Varied(grid) => grid .iter() + .flatten() .any(|declarations| declares(declarations, key)), - Self::InTheme { choice, .. } => choice.declares(key), + Self::When { choice, .. } => choice.declares(key), + Self::All(choices) => choices.iter().any(|choice| choice.declares(key)), } } - /// Whether the choice reads the theme the app shows - pub(super) fn reads_theme(&self) -> bool { + /// What the choice reads from the runtime + pub(super) fn reads(&self) -> Reads { match self { - Self::Empty | Self::Static(_) | Self::Dynamic(_) => false, + Self::Empty | Self::Static(_) | Self::Dynamic(_) => Reads::default(), Self::Condition { consequent, alternate, .. - } => consequent.reads_theme() || alternate.reads_theme(), - Self::Themed(_) | Self::InTheme { .. } => true, + } => consequent.reads().union(alternate.reads()), + Self::Varied(grid) => Reads { + theme: themes_of(grid) > 1, + breakpoint: grid.len() > 1, + landscape: false, + }, + Self::When { state, choice } => choice.reads().union(state.reads()), + Self::All(choices) => choices.iter().fold(Reads::default(), |reads, choice| { + reads.union(choice.reads()) + }), } } - /// The code of the choice, its static styles named in `sheet` and the - /// index of the theme read from `theme` - fn code(&self, sheet: &mut Sheet, theme: &str) -> String { + /// The code of the choice, its static styles named in `sheet` + fn code(&self, sheet: &mut Sheet, vars: &Vars<'_>) -> String { match self { Self::Empty => "null".to_string(), Self::Static(declarations) => sheet.reference(declarations), @@ -118,48 +221,181 @@ impl Choice { let test = operand(test); match alternate.as_ref() { Self::Empty => { - format!("{test} && {}", consequent.operand_code(sheet, theme)) + format!("{test} && {}", consequent.operand_code(sheet, vars)) } alternate => format!( "{test} ? {} : {}", - consequent.operand_code(sheet, theme), - alternate.operand_code(sheet, theme) + consequent.operand_code(sheet, vars), + alternate.operand_code(sheet, vars) ), } } - Self::Themed(variants) => { - let references: Vec = variants + Self::Varied(grid) => { + let parts = split(grid); + let codes: Vec = parts .iter() - .map(|declarations| { - if declarations.is_empty() { - "null".to_string() - } else { - sheet.reference(declarations) - } + .map(|part| match part { + Self::Varied(grid) => grid_code(grid, sheet, vars), + part => part.code(sheet, vars), }) .collect(); - format!("[{}][{theme}]", references.join(", ")) + if codes.len() == 1 { + codes.concat() + } else { + format!("[{}]", codes.join(", ")) + } } - Self::InTheme { index, choice } => { + Self::When { state, choice } => { format!( - "{theme} === {index} && {}", - choice.operand_code(sheet, theme) + "{} && {}", + state.test(vars), + choice.operand_code(sheet, vars) ) } + Self::All(choices) => { + let codes: Vec = choices + .iter() + .map(|choice| choice.code(sheet, vars)) + .collect(); + format!("[{}]", codes.join(", ")) + } } } /// The code of the choice as an operand of a condition - fn operand_code(&self, sheet: &mut Sheet, theme: &str) -> String { - let code = self.code(sheet, theme); - if matches!(self, Self::Condition { .. } | Self::InTheme { .. }) { - format!("({code})") - } else { + fn operand_code(&self, sheet: &mut Sheet, vars: &Vars<'_>) -> String { + let code = self.code(sheet, vars); + let compound = match self { + Self::Condition { .. } | Self::When { .. } => true, + Self::Varied(grid) => grid.len() > 1, + _ => false, + }; + if compound { format!("({code})") } else { code } + } +} + +impl State { + const fn reads(self) -> Reads { + Reads { + theme: matches!(self, Self::Theme(_)), + breakpoint: matches!(self, Self::AtLeast(_)), + landscape: matches!(self, Self::Landscape(_)), + } + } + + /// The code testing that the state holds + fn test(self, vars: &Vars<'_>) -> String { + match self { + Self::Theme(index) => format!("{} === {index}", vars.theme), + Self::AtLeast(level) => format!("{} >= {level}", vars.breakpoint), + Self::Landscape(true) => vars.landscape.to_string(), + Self::Landscape(false) => format!("!{}", vars.landscape), + } + } +} + +/// The parts of `grid` by what their styles differ by: the styles every +/// breakpoint and theme share, those that differ only by theme, only by +/// breakpoint, and by both, so a style object is repeated only for what +/// differs +fn split(grid: &Grid) -> Vec { + let mut keys: Vec<&str> = Vec::new(); + for (key, _) in grid.iter().flatten().flatten() { + if !keys.contains(&key.as_str()) { + keys.push(key); + } + } + let themes = themes_of(grid); + let mut groups: [Vec<&str>; 4] = Default::default(); + for key in keys { + let by_theme = grid.iter().any(|row| { + (1..themes).any(|theme| value(cell(row, theme), key) != value(cell(row, 0), key)) + }); + let by_breakpoint = (0..themes).any(|theme| { + (1..grid.len()).any(|level| { + value(grid_cell(grid, level, theme), key) != value(grid_cell(grid, 0, theme), key) + }) + }); + groups[usize::from(by_theme) + 2 * usize::from(by_breakpoint)].push(key); + } + groups + .iter() + .filter(|keys| !keys.is_empty()) + .map(|keys| varied(project(grid, keys))) + .collect() +} + +/// The value of `key` in `declarations` +fn value<'d>(declarations: &'d [Declaration], key: &str) -> Option<&'d Declaration> { + declarations.iter().find(|(name, _)| name == key) +} + +/// `grid` with only the styles of `keys` +fn project(grid: &Grid, keys: &[&str]) -> Grid { + grid.iter() + .map(|row| { + row.iter() + .map(|declarations| { + declarations + .iter() + .filter(|(key, _)| keys.contains(&key.as_str())) + .cloned() + .collect() + }) + .collect() + }) + .collect() +} + +/// The code picking the style object of `grid` by breakpoint and theme: a +/// condition on the breakpoint for each run of breakpoints that share their +/// styles, each picking by theme where the themes differ +fn grid_code(grid: &Grid, sheet: &mut Sheet, vars: &Vars<'_>) -> String { + let mut runs: Vec<(usize, &Vec>)> = Vec::new(); + for (level, row) in grid.iter().enumerate() { + if runs.last().is_none_or(|(_, last)| *last != row) { + runs.push((level, row)); + } + } + let codes: Vec = runs + .iter() + .map(|(_, row)| row_code(row, sheet, vars)) + .collect(); + match (runs.as_slice(), codes.as_slice()) { + ([_, (start, _)], [first, second]) if first == "null" => { + format!("{} >= {start} && {second}", vars.breakpoint) + } + _ => { + let mut code = codes.last().cloned().unwrap_or_default(); + for index in (0..runs.len() - 1).rev() { + code = format!( + "{} < {} ? {} : {code}", + vars.breakpoint, + runs[index + 1].0, + codes[index] + ); + } code } } } +/// The code picking the style object of `row` by theme +fn row_code(row: &[Vec], sheet: &mut Sheet, vars: &Vars<'_>) -> String { + let mut reference = |declarations: &Vec| { + if declarations.is_empty() { + "null".to_string() + } else { + sheet.reference(declarations) + } + }; + if row.windows(2).all(|pair| pair[0] == pair[1]) { + return reference(&row[0]); + } + let references: Vec = row.iter().map(reference).collect(); + format!("[{}][{}]", references.join(", "), vars.theme) +} + fn declares(declarations: &[Declaration], key: &str) -> bool { declarations.iter().any(|(name, _)| name == key) } @@ -195,36 +431,88 @@ fn merge(declarations: &mut Vec, later: Vec) { } } +/// `declarations` of a narrower breakpoint with `later` of a wider one +/// declared after them, as a media query declares them on the web: a later +/// shorthand also replaces the longhands it covers, which React Native would +/// otherwise prefer whatever their order +pub(super) fn cascade(declarations: &mut Vec, later: Vec) { + declarations.retain(|(key, _)| !later.iter().any(|(shorthand, _)| covers(shorthand, key))); + merge(declarations, later); +} + +/// Whether React Native prefers the style `longhand` over `shorthand`, which +/// sets it too +fn covers(shorthand: &str, longhand: &str) -> bool { + let sides = |base: &str, sides: &[&str]| { + longhand + .strip_prefix(base) + .is_some_and(|side| sides.contains(&side)) + }; + match shorthand { + "margin" | "padding" => longhand != shorthand && longhand.starts_with(shorthand), + "inset" => { + longhand != shorthand + && (longhand.starts_with(shorthand) + || matches!(longhand, "top" | "right" | "bottom" | "left")) + } + "marginVertical" => sides("margin", &["Top", "Bottom"]), + "paddingVertical" => sides("padding", &["Top", "Bottom"]), + "marginHorizontal" => sides("margin", &["Left", "Right", "Start", "End"]), + "paddingHorizontal" => sides("padding", &["Left", "Right", "Start", "End"]), + "gap" => matches!(longhand, "rowGap" | "columnGap"), + "borderWidth" | "borderColor" | "borderRadius" => { + longhand != shorthand + && longhand.starts_with("border") + && longhand.ends_with(&shorthand["border".len()..]) + } + _ => false, + } +} + /// `later` merged into the last of `rest` when both are static or both -/// differ by theme, else `later` itself to apply after it +/// differ by breakpoint or theme, else `later` itself to apply after it fn merge_last(rest: &mut [Choice], later: Choice) -> Option { match (rest.last_mut(), later) { (Some(Choice::Static(last)), Choice::Static(declarations)) => { merge(last, declarations); None } - (Some(Choice::Themed(last)), Choice::Static(declarations)) => { - for variant in last { - merge(variant, declarations.clone()); + (Some(Choice::Varied(last)), Choice::Static(declarations)) => { + for cell in last.iter_mut().flatten() { + merge(cell, declarations.clone()); } None } - (Some(Choice::Themed(last)), Choice::Themed(variants)) => { - for (variant, later) in last.iter_mut().zip(variants) { - merge(variant, later); - } + (Some(Choice::Varied(last)), Choice::Varied(grid)) => { + *last = merge_grids(last, &grid); None } (_, later) => Some(later), } } +/// `later` declared after `earlier`, at every breakpoint and theme of either +fn merge_grids(earlier: &Grid, later: &Grid) -> Grid { + let themes = themes_of(earlier).max(themes_of(later)); + (0..earlier.len().max(later.len())) + .map(|level| { + (0..themes) + .map(|theme| { + let mut declarations = grid_cell(earlier, level, theme).clone(); + merge(&mut declarations, grid_cell(later, level, theme).clone()); + declarations + }) + .collect() + }) + .collect() +} + /// The choices of an element in the order they apply, with as many static /// styles as can be moved first merged into one fn ordered(choices: Vec) -> Vec { let mut first = Vec::new(); let mut rest: Vec = Vec::new(); - for choice in choices { + for choice in flattened(choices) { match choice { Choice::Empty => {} Choice::Static(declarations) @@ -243,36 +531,56 @@ fn ordered(choices: Vec) -> Vec { if !first.is_empty() { rest.insert(0, Choice::Static(first)); } - // A later style can make every theme declare the same + // A later style can make every breakpoint or theme declare the same, and + // what differs splits from what does not rest.into_iter() - .map(|choice| match choice { - Choice::Themed(variants) => themed(variants), - choice => choice, + .flat_map(|choice| match choice { + Choice::Varied(grid) => match varied(grid) { + Choice::Varied(grid) => split(&grid), + choice => vec![choice], + }, + choice => vec![choice], }) + .filter(|choice| *choice != Choice::Empty) .collect() } -/// The `style` an element takes, and whether it reads the theme the app shows +/// `choices` with the choices of each `All` in its place +fn flattened(choices: Vec) -> Vec { + choices + .into_iter() + .flat_map(|choice| match choice { + Choice::All(choices) => flattened(choices), + choice => vec![choice], + }) + .collect() +} + +/// The `style` an element takes, and what it reads from the runtime pub(super) struct StyleCode { pub code: String, - pub reads_theme: bool, + pub reads: Reads, } /// The code of the `style` an element takes: its choices, then the code of /// the styles it is given whole (a spread's `style`, its own `style` prop); -/// `None` when its props declare no style, and it keeps what it is given. -/// The index of the theme the app shows is read from `theme` +/// `None` when its props declare no style, and it keeps what it is given pub(super) fn style_code( choices: Vec, given: Vec, sheet: &mut Sheet, - theme: &str, + vars: &Vars<'_>, ) -> Option { let choices = ordered(choices); - let reads_theme = choices.iter().any(Choice::reads_theme); + let reads = choices.iter().fold(Reads::default(), |reads, choice| { + reads.union(choice.reads()) + }); let mut entries: Vec = choices .iter() - .map(|choice| choice.code(sheet, theme)) + .map(|choice| match choice { + Choice::Varied(grid) => grid_code(grid, sheet, vars), + choice => choice.code(sheet, vars), + }) .collect(); if entries.is_empty() { return None; @@ -283,5 +591,5 @@ pub(super) fn style_code( } else { format!("[{}]", entries.join(", ")) }; - Some(StyleCode { code, reads_theme }) + Some(StyleCode { code, reads }) } diff --git a/libs/extractor/src/native/tests.rs b/libs/extractor/src/native/tests.rs index ee1c164f3..3665d9263 100644 --- a/libs/extractor/src/native/tests.rs +++ b/libs/extractor/src/native/tests.rs @@ -5,11 +5,17 @@ use super::element::units_declaration; use super::errors::{Problem, RuntimeFeature}; use super::props::Declaration; use super::sheet::{Sheet, key_name}; -use super::style::{Choice, in_theme, style_code, themed}; +use super::style::{Choice, State, Vars, cascade, in_theme, style_code, varied, when}; use super::values::{Literal, NativeValue, css_text, number_or_text, quoted_list}; use super::{NativePlatform, NativeTarget, NativeTheme, TokenLevels, TypographyProperties}; use crate::{ExtractOption, ExtractTarget, extract, extract_without_source_map}; +const VARS: Vars<'static> = Vars { + theme: "t", + breakpoint: "b", + landscape: "l", +}; + const IMPORT: &str = "import { Box, Button, Center, Flex, Image, Input, Text, VStack } from '@devup-ui/react'\n"; @@ -429,7 +435,7 @@ fn style_code_orders_and_merges_choices() { ], vec!["given".to_string()], &mut sheet, - "t", + &VARS, ) .map(|style| style.code); assert_eq!( @@ -447,7 +453,7 @@ fn style_code_orders_and_merges_choices() { vec![Choice::Empty], vec!["given".to_string()], &mut sheet, - "t" + &VARS ) .is_none() ); @@ -606,6 +612,7 @@ fn theme(names: &[&str], dark: Option, tokens: &[(&str, &[Option<&str>])] .into_iter() .map(|(name, levels)| (name.to_string(), levels)) .collect(), + ..NativeTheme::default() } } @@ -862,10 +869,10 @@ fn names_selector_themes(#[case] prop: &str, #[case] expected: &str) { #[test] fn themed_choices_collapse_when_every_theme_agrees() { let red = declarations(&[("opacity", 1.0)]); - assert_eq!(themed(vec![]), Choice::Empty); - assert_eq!(themed(vec![vec![], vec![]]), Choice::Empty); + assert_eq!(varied(vec![vec![]]), Choice::Empty); + assert_eq!(varied(vec![vec![vec![], vec![]]]), Choice::Empty); assert_eq!( - themed(vec![red.clone(), red.clone()]), + varied(vec![vec![red.clone(), red.clone()]]), Choice::Static(red.clone()) ); assert_eq!( @@ -875,6 +882,265 @@ fn themed_choices_collapse_when_every_theme_agrees() { assert_eq!(in_theme(1, 2, Choice::Empty), Choice::Empty); assert_eq!( in_theme(1, 2, Choice::Static(red.clone())), - Choice::Themed(vec![vec![], red]) + Choice::Varied(vec![vec![vec![], red]]) + ); +} + +const RESPONSIVE_ELEMENTS: &str = r#"export function Layout({ on, x }) { + return ( + + + + + + + + + + + + + + + + + ) +}"#; + +const ORIENTATION_ELEMENTS: &str = r"export function Screen({ on }) { + return ( + + + + ) +}"; + +#[rstest] +#[case::responsive("responsive_arrays", RESPONSIVE_ELEMENTS)] +#[case::orientation("orientation_blocks", ORIENTATION_ELEMENTS)] +#[case::hooks_in_arrow( + "responsive_hooks_in_arrow", + "export const A = () => ;\nexport const B = () => ;\nexport const c = ;\nexport const d = " +)] +#[case::name_collisions( + "responsive_name_collisions", + "const __b = 1, __l = 2, __useBreakpoint = 3, __useLandscape = 4;\nexport const A = () => " +)] +fn compiles_responsive(#[case] name: &str, #[case] code: &str) { + assert_snapshot!(name, compile_themed(two_themes(), true, code)); +} + +/// Token values at each breakpoint +fn levels(values: &[Option<&str>]) -> TokenLevels { + values + .iter() + .map(|value| value.map(str::to_string)) + .collect() +} + +/// Two themes whose tokens and typographies differ by breakpoint +fn responsive_themes() -> NativeTheme { + let mut theme = two_themes(); + theme.tokens.insert( + "space".to_string(), + vec![ + Some(levels(&[Some("4px"), None, Some("8px")])), + Some(levels(&[Some("6px"), None, Some("12px")])), + ], + ); + theme.tokens.insert( + "edge".to_string(), + vec![ + Some(levels(&[ + Some("1px solid $primary"), + Some("2px solid $primary") + ])); + 2 + ], + ); + theme.tokens.insert( + "late".to_string(), + vec![Some(levels(&[None, Some("2px")])); 2], + ); + theme.typography.insert( + "display".to_string(), + vec![ + Some(typography_entry(&[ + ("font-family", "Inter"), + ("font-size", "$captionSize"), + ("line-height", "1.5"), + ])), + None, + Some(typography_entry(&[("font-size", "40px")])), + ], + ); + theme +} + +const THEMED_RESPONSIVE_ELEMENTS: &str = r#"export function Card({ on }) { + return ( + + + + + + + + + + + + ) +}"#; + +#[rstest] +#[case::two_themes("responsive_themes", responsive_themes(), THEMED_RESPONSIVE_ELEMENTS)] +#[case::custom_breakpoints( + "responsive_custom_breakpoints", + NativeTheme { + breakpoints: vec![0, 600], + ..responsive_themes() + }, + "export const A = () => ;\nexport const b = " +)] +#[case::no_breakpoints( + "responsive_no_breakpoints", + NativeTheme { + breakpoints: vec![], + ..responsive_themes() + }, + "export const A = () => " +)] +fn compiles_responsive_themes(#[case] name: &str, #[case] theme: NativeTheme, #[case] code: &str) { + assert_snapshot!(name, compile_themed(theme, true, code)); +} + +#[rstest] +#[case::arrays( + "runtime_off_arrays", + ";\n;\n" +)] +#[case::tokens( + "runtime_off_responsive_tokens", + ";\n" +)] +#[case::orientation( + "runtime_off_orientation", + "" +)] +fn runtime_off_rejects_responsive_values(#[case] name: &str, #[case] code: &str) { + assert_snapshot!(name, compile_themed(one_theme(), false, code)); +} + +#[rstest] +#[case::spread("responsive_spread", "")] +#[case::nested("responsive_nested", "")] +#[case::orientation_value( + "orientation_value", + "" +)] +fn responsive_errors(#[case] name: &str, #[case] code: &str) { + assert_snapshot!(name, compile_themed(two_themes(), true, code)); +} + +#[rstest] +#[case("margin", "marginTop", true)] +#[case("margin", "margin", false)] +#[case("margin", "padding", false)] +#[case("padding", "paddingVertical", true)] +#[case("inset", "insetBlock", true)] +#[case("inset", "top", true)] +#[case("inset", "inset", false)] +#[case("inset", "width", false)] +#[case("marginVertical", "marginTop", true)] +#[case("marginVertical", "marginLeft", false)] +#[case("paddingVertical", "paddingBottom", true)] +#[case("marginHorizontal", "marginStart", true)] +#[case("marginHorizontal", "marginTop", false)] +#[case("paddingHorizontal", "paddingRight", true)] +#[case("gap", "rowGap", true)] +#[case("gap", "gap", false)] +#[case("borderWidth", "borderTopWidth", true)] +#[case("borderWidth", "borderWidth", false)] +#[case("borderColor", "borderLeftColor", true)] +#[case("borderRadius", "borderTopLeftRadius", true)] +#[case("borderRadius", "outlineRadius", false)] +#[case("width", "minWidth", false)] +fn cascade_replaces_covered_longhands( + #[case] shorthand: &str, + #[case] longhand: &str, + #[case] replaced: bool, +) { + // Given: a narrower breakpoint declaring `longhand` + let mut declared = declarations(&[(longhand, 1.0), ("opacity", 1.0)]); + // When: a wider one declares `shorthand` + cascade(&mut declared, declarations(&[(shorthand, 2.0)])); + // Then + let kept = declared.iter().any(|(key, value)| { + key == longhand && (longhand == shorthand || *value == NativeValue::Number(1.0)) + }); + assert_eq!(!kept, replaced, "{declared:?}"); + assert!(declared.iter().any(|(key, _)| key == "opacity")); +} + +#[test] +fn varied_choices_pick_by_breakpoint_and_theme() { + let a = declarations(&[("padding", 1.0)]); + let b = declarations(&[("padding", 2.0)]); + let c = declarations(&[("padding", 3.0)]); + let mut sheet = Sheet::new("s".to_string()); + let mut code = |choice: Choice| { + style_code(vec![choice], vec![], &mut sheet, &VARS) + .map_or_else(Default::default, |style| (style.code, style.reads)) + }; + // Three runs of breakpoints, the first without styles + let (three, _) = code(Choice::Varied(vec![ + vec![vec![]], + vec![a.clone()], + vec![a.clone()], + vec![b.clone()], + ])); + assert_eq!(three, "b < 1 ? null : b < 3 ? s.a : s.b"); + // Breakpoints and themes both + let (both, reads) = code(Choice::Varied(vec![ + vec![a.clone(), b.clone()], + vec![c.clone(), c.clone()], + ])); + assert_eq!(both, "b < 1 ? [s.a, s.b][t] : s.c"); + assert!(reads.theme && reads.breakpoint && !reads.landscape); + // In a condition, and applied while a state holds + let (condition, reads) = code(Choice::Condition { + test: "on".to_string(), + consequent: Box::new(Choice::Varied(vec![vec![a.clone()], vec![b.clone()]])), + alternate: Box::new(when(State::Landscape(false), Choice::Static(c))), + }); + assert_eq!(condition, "on ? (b < 1 ? s.a : s.b) : (!l && s.c)"); + assert!(!reads.theme && reads.breakpoint && reads.landscape); + let (nested, _) = code(Choice::Condition { + test: "on".to_string(), + consequent: Box::new(Choice::Varied(vec![ + vec![declarations(&[("padding", 1.0), ("margin", 1.0)])], + vec![declarations(&[("padding", 2.0), ("margin", 1.0)])], + ])), + alternate: Box::new(Choice::All(vec![ + Choice::Static(a.clone()), + when(State::AtLeast(2), Choice::Static(b)), + ])), + }); + assert_eq!( + nested, + "on ? ([s.d, b < 1 ? s.a : s.b]) : [s.a, b >= 2 && s.b]" + ); + assert_eq!(when(State::Theme(1), Choice::Empty), Choice::Empty); + assert_eq!( + in_theme( + 1, + 2, + when(State::Landscape(true), Choice::Static(a.clone())) + ), + when( + State::Theme(1), + when(State::Landscape(true), Choice::Static(a)) + ) ); } diff --git a/libs/extractor/src/native/theme.rs b/libs/extractor/src/native/theme.rs index c7f99a530..e168d76e4 100644 --- a/libs/extractor/src/native/theme.rs +++ b/libs/extractor/src/native/theme.rs @@ -1,12 +1,12 @@ //! The theme of `devup.json` as the React Native output reads it: the names -//! of the themes in the order the runtime indexes them, and the value of each -//! token and typography in every theme, resolved at build time. +//! of the themes in the order the runtime indexes them, the breakpoints, and +//! the value of each token and typography in every theme at each breakpoint, +//! resolved at build time. use std::borrow::Cow; use std::collections::BTreeMap; -use super::NativeTarget; -use super::errors::{Problem, RuntimeFeature}; +use super::errors::Problem; /// The values of a token at each breakpoint, `None` where it has none pub type TokenLevels = Vec>; @@ -14,9 +14,12 @@ pub type TokenLevels = Vec>; /// The CSS properties of a typography, each with its value pub type TypographyProperties = Vec<(String, String)>; +/// The breakpoints of the web, which `devup.json` keeps unless it sets its own +pub const DEFAULT_BREAKPOINTS: [u16; 6] = [0, 480, 768, 992, 1280, 1600]; + /// The theme a file is compiled with. Built from `devup.json` by the /// bindings, which read it with the web's theme parser -#[derive(Debug, Clone, Default, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct NativeTheme { /// The theme names, the default first: the runtime picks a style object by /// the index of a name here @@ -29,6 +32,21 @@ pub struct NativeTheme { pub tokens: BTreeMap>>, /// Each typography by name, with its properties at each breakpoint pub typography: BTreeMap>>, + /// The window width, in density-independent pixels, each breakpoint + /// starts at, as the web's media queries read them + pub breakpoints: Vec, +} + +impl Default for NativeTheme { + fn default() -> Self { + Self { + names: Vec::new(), + dark: None, + tokens: BTreeMap::new(), + typography: BTreeMap::new(), + breakpoints: DEFAULT_BREAKPOINTS.to_vec(), + } + } } /// How many times a token's value may name another token @@ -41,25 +59,30 @@ impl NativeTheme { self.names.len().max(1) } + /// How many breakpoints a responsive value can tell apart: at least one + pub(super) fn levels(&self) -> usize { + self.breakpoints.len().max(1) + } + /// The index of the theme `name` pub(super) fn index_of(&self, name: &str) -> Option { self.names.iter().position(|theme| theme == name) } - /// `text` with each `$token` replaced by its value in the theme at - /// `index`, or `None` when that theme does not define one of them + /// `text` with each `$token` replaced by its value at the breakpoint + /// `level` in the theme at `index`, or `None` when that theme does not + /// define one of them there pub(super) fn resolve<'t>( &self, text: &'t str, - index: usize, - target: &NativeTarget, + at: (usize, usize), ) -> Result>, Problem> { if !text.contains('$') { return Ok(Some(Cow::Borrowed(text))); } let mut resolved = text.to_string(); for _ in 0..MAX_TOKEN_DEPTH { - match self.resolve_once(&resolved, index, target)? { + match self.resolve_once(&resolved, at)? { Some(next) if next == resolved => return Ok(Some(Cow::Owned(next))), Some(next) => resolved = next, None => return Ok(None), @@ -72,17 +95,12 @@ impl NativeTheme { } /// `text` with each `$token` replaced once - fn resolve_once( - &self, - text: &str, - index: usize, - target: &NativeTarget, - ) -> Result, Problem> { + fn resolve_once(&self, text: &str, at: (usize, usize)) -> Result, Problem> { let mut resolved = String::with_capacity(text.len()); let mut rest = text; while let Some((before, token, after)) = next_token(rest) { resolved.push_str(before); - match self.token(token, index, target)? { + match self.token(token, at)? { Some(value) => resolved.push_str(value), None => return Ok(None), } @@ -92,13 +110,10 @@ impl NativeTheme { Ok(Some(resolved)) } - /// The value of `token` (as written after `$`) in the theme at `index` - fn token( - &self, - token: &str, - index: usize, - target: &NativeTarget, - ) -> Result, Problem> { + /// The value of `token` (as written after `$`) at the breakpoint `level` + /// in the theme at `index`: its value at the last breakpoint up to + /// `level` that gives one, as the web's media queries cascade + fn token(&self, token: &str, (index, level): (usize, usize)) -> Result, Problem> { let key = token.replace('.', "-"); let themes = self.tokens.get(&key).ok_or_else(|| { Problem::new( @@ -106,51 +121,82 @@ impl NativeTheme { "add the token to the theme in devup.json, or write the value itself", ) })?; - if themes.iter().flatten().any(is_responsive) { - return Err(responsive_token(token, target)); - } Ok(themes .get(index) .and_then(Option::as_ref) - .and_then(|levels| levels.first()) - .and_then(Option::as_deref)) + .and_then(|levels| at_level(levels, level))) } - /// The properties of the typography `name` + /// The properties of the typography `name` at the breakpoint `level`: + /// each property as the last breakpoint up to `level` that gives it pub(super) fn typography( &self, name: &str, - target: &NativeTarget, - ) -> Result<&TypographyProperties, Problem> { + level: usize, + ) -> Result { let levels = self.typography.get(name).ok_or_else(|| { Problem::new( format!("devup.json defines no `{name}` typography"), "add the typography to the theme in devup.json", ) })?; - match levels.split_first() { - Some((Some(properties), rest)) if rest.iter().all(Option::is_none) => Ok(properties), - _ => Err(responsive_token(name, target)), + let mut properties: TypographyProperties = Vec::new(); + for entry in levels.iter().take(level + 1).flatten() { + for (property, value) in entry { + match properties.iter_mut().find(|(name, _)| name == property) { + Some(existing) => existing.1.clone_from(value), + None => properties.push((property.clone(), value.clone())), + } + } } + Ok(properties) + } + + /// How many breakpoints the tokens `text` names tell apart, through the + /// tokens their values name: one when none is responsive + pub(super) fn token_levels(&self, text: &str) -> usize { + self.token_levels_within(text, MAX_TOKEN_DEPTH) } -} -/// Whether a token has a value at a breakpoint but the first, which the -/// window width chooses -fn is_responsive(levels: &TokenLevels) -> bool { - !matches!(levels.split_first(), Some((Some(_), rest)) if rest.iter().all(Option::is_none)) + fn token_levels_within(&self, text: &str, depth: usize) -> usize { + let mut levels = 1; + let mut rest = text; + while let Some((_, token, after)) = next_token(rest) { + let all = self.tokens.get(&token.replace('.', "-")); + for values in all.into_iter().flatten().flatten() { + levels = levels.max(values.len()); + if depth > 0 { + for value in values.iter().flatten() { + levels = levels.max(self.token_levels_within(value, depth - 1)); + } + } + } + rest = after; + } + levels + } + + /// How many breakpoints the typography `name` tells apart, through the + /// tokens its values name + pub(super) fn typography_levels(&self, name: &str) -> usize { + self.typography.get(name).map_or(1, |levels| { + levels + .iter() + .flatten() + .flatten() + .map(|(_, value)| self.token_levels(value)) + .fold(levels.len(), usize::max) + }) + } } -/// Why a token with a value at each breakpoint cannot compile yet -fn responsive_token(name: &str, target: &NativeTarget) -> Problem { - let problem = RuntimeFeature::Responsive.problem(target); - Problem::new( - format!( - "`{name}` has a value at each breakpoint: {}", - problem.reason - ), - "give it one value in devup.json, or write the value itself", - ) +/// The value of `levels` at the breakpoint `level`: the last one up to it +fn at_level(levels: &TokenLevels, level: usize) -> Option<&str> { + levels + .iter() + .take(level + 1) + .rev() + .find_map(Option::as_deref) } /// The text before the first `$token` of `text`, the token's name and the diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md index 41d86cfa9..1a4e54e18 100644 --- a/packages/metro-plugin/README.md +++ b/packages/metro-plugin/README.md @@ -117,23 +117,44 @@ 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. + ## Limits of this version Only styles the build can decide are supported: literals, values read at -runtime, theme tokens, conditions between them and the platform and theme -blocks. These are build errors, reported by Metro at the file, line and -column: +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: -- responsive arrays (`p={[1, 2]}`), and tokens or typography with a value at - each breakpoint - interaction states (`_hover`, `_active`, `_pressed`, `_focus`, ...) - `css()`, `styled()`, `globalCss()`, `keyframes()` and `Grid` - any prop React Native has no style for -- with `runtime: false`, a value that differs by theme, `_theme*` with more - than one theme, and `useTheme`, `getTheme` and `setTheme` +- 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 responsive values and `_pressed` comes in a later -version. +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). diff --git a/packages/react/src/native/__tests__/index.browser.test.tsx b/packages/react/src/native/__tests__/index.browser.test.tsx index 1dd10010e..7dc2761e6 100644 --- a/packages/react/src/native/__tests__/index.browser.test.tsx +++ b/packages/react/src/native/__tests__/index.browser.test.tsx @@ -8,7 +8,21 @@ const appearance = { listeners: [] as (() => void)[], } +/** The window React Native reports, and who listens to its changes */ +const dimensions = { + width: 390, + height: 844, + listeners: [] as (() => void)[], +} + mock.module('react-native', () => ({ + Dimensions: { + get: () => ({ width: dimensions.width, height: dimensions.height }), + addEventListener: (event: string, listener: () => void) => { + if (event === 'change') dimensions.listeners.push(listener) + return { remove: () => {} } + }, + }, Appearance: { getColorScheme: () => appearance.scheme, addChangeListener: (listener: () => void) => { @@ -26,12 +40,34 @@ function changeAppearance(scheme: string | null) { }) } +/** The window resizing to `width` by `height` */ +function resize(width: number, height: number) { + act(() => { + dimensions.width = width + dimensions.height = height + for (const listener of dimensions.listeners) listener() + }) +} + const runtime = await import('../index') -const { defineThemes, getTheme, setTheme, Themed, useTheme, useThemeIndex } = - runtime +const { + defineBreakpoints, + defineThemes, + getBreakpoint, + getTheme, + setTheme, + Themed, + useBreakpoint, + useLandscape, + useTheme, + useThemeIndex, +} = runtime beforeEach(() => { appearance.scheme = 'light' + dimensions.width = 390 + dimensions.height = 844 + defineBreakpoints([0, 480, 768, 992, 1280, 1600]) defineThemes(['light', 'dark', 'sepia'], 1) setTheme(null) }) @@ -123,3 +159,85 @@ describe('Themed', () => { expect(span()?.getAttribute('data-color')).toBe('brown') }) }) + +describe('getBreakpoint and useBreakpoint', () => { + it('give the last breakpoint the window width reaches', () => { + expect(getBreakpoint()).toBe(0) + dimensions.width = 480 + expect(getBreakpoint()).toBe(1) + dimensions.width = 1599 + expect(getBreakpoint()).toBe(4) + dimensions.width = 4000 + expect(getBreakpoint()).toBe(5) + }) + + it('read the breakpoints devup.json gives', () => { + defineBreakpoints([100, 600]) + dimensions.width = 50 + expect(getBreakpoint()).toBe(0) + dimensions.width = 599 + expect(getBreakpoint()).toBe(0) + dimensions.width = 600 + expect(getBreakpoint()).toBe(1) + defineBreakpoints([]) + expect(getBreakpoint()).toBe(0) + }) + + it('render again only when the window crosses a breakpoint', () => { + let renders = 0 + const { result } = renderHook(() => { + renders += 1 + return useBreakpoint() + }) + expect([result.current, renders]).toEqual([0, 1]) + resize(400, 844) + resize(479, 844) + expect([result.current, renders]).toEqual([0, 1]) + resize(480, 844) + expect([result.current, renders]).toEqual([1, 2]) + resize(700, 844) + expect([result.current, renders]).toEqual([1, 2]) + resize(1024, 844) + expect(result.current).toBe(3) + resize(320, 844) + expect(result.current).toBe(0) + }) +}) + +describe('useLandscape', () => { + it('renders again when the window turns', () => { + const { result } = renderHook(() => useLandscape()) + expect(result.current).toBe(false) + resize(844, 390) + expect(result.current).toBe(true) + resize(390, 844) + expect(result.current).toBe(false) + }) + + it('shares one listener of the window with every hook', () => { + renderHook(() => [useLandscape(), useBreakpoint(), useTheme()]) + renderHook(() => useBreakpoint()) + expect(dimensions.listeners).toHaveLength(1) + }) +}) + +describe('Themed with breakpoints', () => { + it('renders the style of the breakpoint and orientation of the window', () => { + const Probe = ({ style }: { style?: string }) => + createElement('span', { 'data-style': style }) + const { container } = render( + createElement(Themed, { + $c: Probe, + $s: (theme: number, breakpoint: number, landscape: boolean) => + `${theme}-${breakpoint}-${landscape}`, + }), + ) + const style = () => + container.querySelector('span')?.getAttribute('data-style') + expect(style()).toBe('0-0-false') + resize(844, 390) + expect(style()).toBe('0-2-true') + changeAppearance('dark') + expect(style()).toBe('1-2-true') + }) +}) diff --git a/packages/react/src/native/index.ts b/packages/react/src/native/index.ts index cffcb461e..f9c147fd8 100644 --- a/packages/react/src/native/index.ts +++ b/packages/react/src/native/index.ts @@ -4,15 +4,16 @@ import { type ReactElement, useSyncExternalStore, } from 'react' -import { Appearance } from 'react-native' +import { Appearance, Dimensions } from 'react-native' import type { DevupTheme } from '../types/theme' /** * The React Native runtime of Devup UI. The build compiles every style to - * `StyleSheet` objects, one a theme when a value differs by theme; this - * module only tells which theme shows. It reads no CSS, resolves no token - * and computes no style. Web builds never import it. + * `StyleSheet` objects, one a theme or a breakpoint when a value differs by + * them; this module only tells which theme shows, which breakpoint the + * window is at and whether it is in landscape. It reads no CSS, resolves no + * token and computes no style. Web builds never import it. */ type ThemeName = keyof DevupTheme extends undefined ? string : keyof DevupTheme @@ -23,6 +24,10 @@ let names: readonly string[] = [] let dark = -1 /** The theme `setTheme` chose, which wins over the system appearance */ let chosen: string | null = null +/** The window widths the breakpoints start at, as devup.json gives them */ +let breakpoints: readonly number[] = [0, 480, 768, 992, 1280, 1600] +/** The breakpoint and orientation listeners last heard of, as one number */ +let layout = -1 let following = false const listeners = new Set<() => void>() @@ -30,10 +35,26 @@ function notify(): void { for (const listener of listeners) listener() } +/** The breakpoint the window is at and whether it is in landscape, as one number */ +function readLayout(): number { + return getBreakpoint() * 2 + Number(getLandscape()) +} + +/** Tells the listeners when the window crosses a breakpoint or turns */ +function resize(): void { + const next = readLayout() + if (next !== layout) { + layout = next + notify() + } +} + function subscribe(listener: () => void): () => void { if (!following) { following = true + layout = readLayout() Appearance.addChangeListener(notify) + Dimensions.addEventListener('change', resize) } listeners.add(listener) return () => { @@ -52,6 +73,15 @@ export function defineThemes(themes: readonly string[], darkIndex = -1): void { dark = darkIndex } +/** + * Tells the runtime the breakpoints of devup.json when they are not the + * web's default. The build calls it in each file that reads the breakpoint. + * @internal + */ +export function defineBreakpoints(widths: readonly number[]): void { + breakpoints = widths +} + /** * The theme the app shows: the one `setTheme` chose, else the dark theme * while the system appearance is dark, else the default theme; `null` @@ -89,9 +119,46 @@ export function useThemeIndex(): number { } /** - * Renders `$c` with the style `$s` gives for the theme the app shows. The - * build renders an element through it where no function component can read - * the theme for it. + * The breakpoint the window is at: the index of the last breakpoint whose + * width the window reaches, as the web's `min-width` media queries choose, + * and `0` below them all + */ +export function getBreakpoint(): number { + const { width } = Dimensions.get('window') + let level = 0 + for (let index = 1; index < breakpoints.length; index++) { + if (width >= breakpoints[index]) level = index + } + return level +} + +/** + * The breakpoint the window is at, rendering again only when the window + * crosses into another breakpoint + */ +export function useBreakpoint(): number { + return useSyncExternalStore(subscribe, getBreakpoint, getBreakpoint) +} + +/** Whether the window is wider than it is tall */ +function getLandscape(): boolean { + const { width, height } = Dimensions.get('window') + return width > height +} + +/** + * Whether the window is in landscape, rendering again when it turns + * @internal + */ +export function useLandscape(): boolean { + return useSyncExternalStore(subscribe, getLandscape, getLandscape) +} + +/** + * Renders `$c` with the style `$s` gives for the theme the app shows, the + * breakpoint the window is at and whether it is in landscape. The build + * renders an element through it where no function component can read them + * for it. * @internal */ export function Themed({ @@ -100,7 +167,10 @@ export function Themed({ ...props }: { $c: ElementType - $s: (theme: number) => unknown + $s: (theme: number, breakpoint: number, landscape: boolean) => unknown } & Record): ReactElement { - return createElement($c, { ...props, style: $s(useThemeIndex()) }) + return createElement($c, { + ...props, + style: $s(useThemeIndex(), useBreakpoint(), useLandscape()), + }) } From 4daea343095fb6dc9c59f8857e81d510d580871b Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 10:55:43 +0900 Subject: [PATCH 2/7] fix(verify-dist): give the react-native stand-in Dimensions The React Native runtime now reads the window size through Dimensions. Co-Authored-By: Claude Opus 5.5 --- verify-dist.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/verify-dist.ts b/verify-dist.ts index e65a5b665..d2a4f414a 100644 --- a/verify-dist.ts +++ b/verify-dist.ts @@ -85,7 +85,7 @@ Bun.plugin({ name: 'react-native-stand-in', setup(build) { build.module('react-native', () => ({ - exports: { Appearance: {} }, + exports: { Appearance: {}, Dimensions: {} }, loader: 'object', })) }, From 6c2b6f2c67f18d5082c05993d1202b88a36740bf Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 11:16:53 +0900 Subject: [PATCH 3/7] feat(native): press styles through Pressable on React Native `_active` and its React Native name `_pressed` make the element a `Pressable` whose `style` is a function of whether it is pressed: `({ pressed }) => [styles.a, pressed && styles.b]`. A `Box`, `Flex`, `Center` or `VStack` with a press style becomes a `Pressable`; a `Button` already is one. Press styles combine with responsive values, themes, platforms, orientations and conditions, and need no runtime, so they work with `runtime: false` too. On a `Text`, an `Image` or an `Input`, and with `as`, they are build errors. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_react_native_pressed.json | 8 ++ .github/workflows/publish.yml | 1 + apps/expo/check-bundle.mjs | 10 +- apps/expo/src/App.tsx | 2 + libs/extractor/src/native/element.rs | 127 +++++++++++++----- libs/extractor/src/native/errors.rs | 26 ++-- libs/extractor/src/native/mod.rs | 5 +- ...actor__native__tests__platform_shapes.snap | 1 - .../extractor__native__tests__pressed.snap | 6 - ...ractor__native__tests__pressed_errors.snap | 9 ++ ...ative__tests__pressed_name_collisions.snap | 10 ++ ...r__native__tests__pressed_runtime_off.snap | 17 +++ ...ractor__native__tests__pressed_styles.snap | 47 +++++++ ...tractor__native__tests__runtime_false.snap | 1 - ...xtractor__native__tests__runtime_true.snap | 1 - libs/extractor/src/native/style.rs | 19 +++ libs/extractor/src/native/tests.rs | 57 +++++--- packages/metro-plugin/README.md | 22 ++- 18 files changed, 285 insertions(+), 84 deletions(-) create mode 100644 .changepacks/changepack_log_react_native_pressed.json delete mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__pressed.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__pressed_errors.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__pressed_name_collisions.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__pressed_runtime_off.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__pressed_styles.snap 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} > + <__Pressable onPress={go} style={({ pressed: __p }) => [__p && __s.g, __b < 1 ? __s.h : __s.a]} /> + <__Pressable onPress={go} style={({ pressed: __p }) => [ + __s.i, + __p && (on ? __s.h : __s.a), + extra + ]}> + + + <__Pressable style={({ pressed: __p }) => __t === 1 && __p && __s.j} /> + + + + + + + - <__Pressable onPress={go} style={({ pressed: __p }) => [__p && __s.g, __b < 1 ? __s.h : __s.a]} /> + <__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.h : __s.a), + __p && (on ? __s.g : __s.a), extra ]}> 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/tests.rs b/libs/extractor/src/native/tests.rs index 026082155..7cb5c546d 100644 --- a/libs/extractor/src/native/tests.rs +++ b/libs/extractor/src/native/tests.rs @@ -1169,3 +1169,17 @@ export const outside = "#; 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)); +} From 3ba5930b1fd09a3bfea33aa3129c8bd9e973bc89 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 12:04:13 +0900 Subject: [PATCH 5/7] test(native): cover a static style checked against one kept in order Co-Authored-By: Claude Opus 5.5 --- libs/extractor/src/native/tests.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/libs/extractor/src/native/tests.rs b/libs/extractor/src/native/tests.rs index 7cb5c546d..d65cf36d7 100644 --- a/libs/extractor/src/native/tests.rs +++ b/libs/extractor/src/native/tests.rs @@ -1183,3 +1183,24 @@ 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)])), + ], + vec![], + &mut sheet, + &VARS, + ) + .map(|style| style.code); + assert_eq!( + code.as_deref(), + Some("[s.a, { margin: m }, s.b, { width: w }]") + ); +} From 7d52b64bbe893bae1d5bbfbbd494473c619e27b5 Mon Sep 17 00:00:00 2001 From: owjs3901 Date: Sat, 21 Nov 2026 12:30:43 +0900 Subject: [PATCH 6/7] test(native): cover a static style checked against a state block Co-Authored-By: Claude Opus 5.5 --- libs/extractor/src/native/tests.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/libs/extractor/src/native/tests.rs b/libs/extractor/src/native/tests.rs index d65cf36d7..57ae043ab 100644 --- a/libs/extractor/src/native/tests.rs +++ b/libs/extractor/src/native/tests.rs @@ -1193,6 +1193,11 @@ fn a_static_style_after_one_kept_in_order_checks_it() { 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, @@ -1201,6 +1206,6 @@ fn a_static_style_after_one_kept_in_order_checks_it() { .map(|style| style.code); assert_eq!( code.as_deref(), - Some("[s.a, { margin: m }, s.b, { width: w }]") + Some("[s.a, { margin: m }, s.b, { width: w }, p && s.c]") ); } From 8f4f0403f8b7184b84424bb724049b78bbd91449 Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Thu, 26 Nov 2026 00:26:04 +0900 Subject: [PATCH 7/7] feat(native): css() and className on React Native (#1046) * wip(native): css() and className on React Native Co-Authored-By: Claude Opus 5.5 * wip(native): drop a probe test Co-Authored-By: Claude Opus 5.5 * feat(native): css() as CSS text, README and changepack Co-Authored-By: Claude Opus 5.5 * test(native): pass classes to style_code in the merged test Co-Authored-By: Claude Opus 5.5 * test(native): cover css() parts around state blocks and empty objects Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../changepack_log_react_native_css.json | 8 + .github/workflows/publish.yml | 1 + apps/expo/src/App.tsx | 12 +- libs/extractor/src/native/element.rs | 74 +++- libs/extractor/src/native/element/css_call.rs | 374 ++++++++++++++++++ libs/extractor/src/native/errors.rs | 18 +- libs/extractor/src/native/imports.rs | 19 +- .../extractor__native__tests__apis.snap | 3 +- .../extractor__native__tests__css_alone.snap | 8 + .../extractor__native__tests__css_calls.snap | 47 +++ .../extractor__native__tests__css_errors.snap | 22 ++ .../extractor__native__tests__css_only.snap | 36 ++ ...actor__native__tests__css_runtime_off.snap | 5 + .../extractor__native__tests__css_text.snap | 32 ++ ...ractor__native__tests__web_only_props.snap | 2 +- libs/extractor/src/native/style.rs | 37 +- libs/extractor/src/native/tests.rs | 85 +++- packages/metro-plugin/README.md | 44 ++- 18 files changed, 777 insertions(+), 50 deletions(-) create mode 100644 .changepacks/changepack_log_react_native_css.json create mode 100644 libs/extractor/src/native/element/css_call.rs create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__css_alone.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__css_calls.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__css_only.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__css_runtime_off.snap create mode 100644 libs/extractor/src/native/snapshots/extractor__native__tests__css_text.snap diff --git a/.changepacks/changepack_log_react_native_css.json b/.changepacks/changepack_log_react_native_css.json new file mode 100644 index 000000000..77bab2bf9 --- /dev/null +++ b/.changepacks/changepack_log_react_native_css.json @@ -0,0 +1,8 @@ +{ + "changes": { + "bindings/devup-ui-binding/package.json": "Patch", + "bindings/devup-ui-wasm/package.json": "Patch" + }, + "note": "`codeExtractNative` compiles `css()` for React Native (part of #411): a call compiles to the style it describes, the value React Native's `style` takes, and `className` on a Devup UI element passes it on before the element's style props. `css()` takes objects of style props with responsive values, theme tokens and blocks, conditions choosing between objects, what another `css()` gives, and CSS text whose interpolations are whole values. A `css()` whose styles differ by theme, breakpoint or orientation must be called in a function component or a hook. A `style` prop holding Devup UI elements or `css()` calls now compiles them too. Web output is unchanged.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 2bf0a8564..e1017f857 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -11,6 +11,7 @@ on: - feat/react-native-metro - feat/react-native-themes - feat/react-native-responsive + - feat/react-native-pressed # Pull requests and every job below run read-only. Only the `release` and # `deploy-pages` jobs get write permissions, and they run on pushes to main diff --git a/apps/expo/src/App.tsx b/apps/expo/src/App.tsx index 624128e25..6d8174a5f 100644 --- a/apps/expo/src/App.tsx +++ b/apps/expo/src/App.tsx @@ -1,6 +1,7 @@ import { Box, Button, + css, Flex, Image, Input, @@ -12,6 +13,9 @@ import { useState } from 'react' import { Badge } from './Badge' +/** The shape both buttons share */ +const button = css({ borderRadius: '8px', px: 5, py: 3 }) + export function App() { const [name, setName] = useState('') const [count, setCount] = useState(0) @@ -69,10 +73,8 @@ export function App() { + ) +} +``` + +`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. + ## Limits of this version Only styles the build can decide are supported: literals, values read at 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: +platform, theme, orientation and press blocks, and `css()`. These are build +errors, reported by Metro at the file, line and column: - interaction states other than `_active`/`_pressed` (`_hover`, `_focus`, ...) -- `css()`, `styled()`, `globalCss()`, `keyframes()` and `Grid` +- `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