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_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/.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/.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..e1017f857 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -9,6 +9,9 @@ on: - main - feat/napi-binding - 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/check-bundle.mjs b/apps/expo/check-bundle.mjs index 913534639..a7168e173 100644 --- a/apps/expo/check-bundle.mjs +++ b/apps/expo/check-bundle.mjs @@ -3,14 +3,19 @@ // 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. 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' 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 +94,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']) { @@ -111,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}`) } @@ -129,16 +141,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..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) @@ -24,7 +28,8 @@ export function App() { flexDirection="column" gap={4} justifyContent="center" - p={6} + px="$gutter" + py={[6, null, 10]} > - + Your name @@ -53,28 +65,32 @@ 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..b38bf526c 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, CallExpression, + ExportDefaultDeclaration, Expression, Function, FunctionBody, IdentifierReference, + JSXAttribute, JSXAttributeItem, JSXAttributeName, JSXAttributeValue, JSXChild, JSXElement, + JSXElementName, JSXExpression, LogicalOperator, ObjectExpression, ObjectPropertyKind, Program, + TSType, TaggedTemplateExpression, UnaryOperator, VariableDeclarator, }; use std::cell::Cell; +use std::fmt::Write; use oxc_ast_visit::{Visit, walk}; use oxc_semantic::Scoping; @@ -19,15 +21,17 @@ 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; use crate::fresh_name::fresh_name; +mod css_call; + /// The changes compiling a file makes, or why it cannot compile pub(super) struct Compiled { pub replacements: Vec, @@ -39,52 +43,101 @@ 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 variable holding whether the element is pressed, in the function + /// `Pressable` calls for its style + pressed: String, + /// The hooks reading each, by what they read + hooks: [String; 3], + /// What the hooks the file calls read + 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), + pressed: fresh_name("__p", 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 import of the runtime and the call telling it the theme names, - /// when the file uses it + /// The variables holding what the runtime tells + fn vars(&self) -> Vars<'_> { + Vars { + theme: &self.index, + breakpoint: &self.breakpoint, + landscape: &self.landscape, + pressed: &self.pressed, + } + } + + /// 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 +147,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, } @@ -123,9 +176,13 @@ pub(super) fn compile( target, scoping, components: &imports.components, + css: &imports.css, sheet: Sheet::new(fresh_name("__s", code)), units: fresh_name("__u", code), units_used: Cell::new(false), + pressable: fresh_name("__Pressable", code), + pressable_used: false, + press: None, runtime: Runtime::new(code), theme_scope: None, frames: Vec::new(), @@ -133,13 +190,15 @@ pub(super) fn compile( replacements: imports.replacements, errors: imports.errors, }; - if !visitor.components.is_empty() { + if !visitor.components.is_empty() || !visitor.css.is_empty() { visitor.visit_program(program); } let Elements { sheet, units, units_used, + pressable, + pressable_used, runtime, mut replacements, errors, @@ -148,6 +207,12 @@ pub(super) fn compile( let mut prelude = runtime .prelude(target, imports.theme_api) .unwrap_or_default(); + if pressable_used { + let _ = writeln!( + prelude, + "import {{ Pressable as {pressable} }} from \"{REACT_NATIVE}\";" + ); + } if !sheet.is_empty() { prelude.push_str(&sheet_prelude(&sheet, code)); } @@ -171,14 +236,17 @@ enum Prop { As, /// `style`, given whole Style, + /// `className`, the styles `css()` gives + ClassName, /// A style prop Declares, /// `_ios`, `_android` or `_web`: styles for one platform Platform(NativePlatform), /// `_themeDark` and the like: styles for the theme named Theme(String), - /// What needs the React Native runtime - Runtime(RuntimeFeature), + /// `_landscape`, `_portrait` and `_pressed`: styles applied while the + /// window is in that orientation or the element is pressed + When(State), /// What React Native has no equivalent of Unsupported(Problem), /// A prop the element passes on to the React Native component @@ -193,12 +261,10 @@ fn classify(name: &str) -> Prop { "_ios" => Prop::Platform(NativePlatform::Ios), "_android" => Prop::Platform(NativePlatform::Android), "_web" => Prop::Platform(NativePlatform::Web), - "_pressed" | "_active" => Prop::Runtime(RuntimeFeature::Pressed), - "_portrait" | "_landscape" => Prop::Runtime(RuntimeFeature::Responsive), - "className" => Prop::Unsupported(Problem::new( - "React Native has no class names", - "write the styles as props, or pass them in `style`", - )), + "_portrait" => Prop::When(State::Landscape(false)), + "_landscape" => Prop::When(State::Landscape(true)), + "_pressed" | "_active" => Prop::When(State::Pressed), + "className" => Prop::ClassName, "typography" => Prop::Declares, "styleOrder" | "styleVars" => Prop::Unsupported(Problem::new( "React Native has no stylesheet order and no CSS variables", @@ -246,11 +312,19 @@ struct Elements<'s> { target: &'s NativeTarget, scoping: &'s Scoping, components: &'s FxHashMap, + /// The bindings of `css` + css: &'s FxHashSet, sheet: Sheet, /// The name of the function converting values read at runtime units: String, /// Whether a value read at runtime is converted units_used: Cell, + /// The name React Native's `Pressable` is imported under, for an element + /// that is a `View` but takes a press style + pressable: String, + pressable_used: bool, + /// The offset and the name of the first press style of the element read + press: Option<(u32, String)>, runtime: Runtime, /// The theme of the `_theme*` block being read, whose tokens resolve in /// that theme alone @@ -266,13 +340,22 @@ struct Elements<'s> { /// What the props of one element give its `style` #[derive(Default)] struct Styles { + /// The code of what `className` gives, before the style props + classes: Vec, choices: Vec, + /// The styles of the theme, orientation and press blocks, which apply + /// after the other styles whatever the order of the props, as their + /// selectors and media queries do on the web + blocks: Vec, /// The code of each style given whole, in prop order given: Vec, /// The span of each prop leaving the element once it takes `style` removed: Vec, /// The `style` prop, which leaves the element with the style props style: Option, + /// The `style` prop's value compiled, which it keeps when the element + /// takes no other style + kept: Option, /// A spread whose `style` cannot be read twice opaque_spread: Option, } @@ -293,11 +376,35 @@ impl<'a> Visit<'a> for Elements<'_> { "`{local}` can only be rendered as a JSX element on React Native: the build compiles its props into styles only there. Fix: render `<{local} />`, or use a React Native component here" ), )); + } else if self.is_css_reference(identifier) { + self.errors.push(( + identifier.span.start, + format!( + "`{}` can only be called on React Native: the build compiles each call into styles. Fix: call it where the styles are used", + identifier.name + ), + )); } } fn visit_ts_type(&mut self, _: &TSType<'a>) {} + fn visit_tagged_template_expression(&mut self, template: &TaggedTemplateExpression<'a>) { + if self.is_css(&template.tag) { + self.css_template(template); + } else { + walk::walk_tagged_template_expression(self, template); + } + } + + fn visit_call_expression(&mut self, call: &CallExpression<'a>) { + if self.is_css(&call.callee) { + self.css_call(call); + } else { + walk::walk_call_expression(self, call); + } + } + fn visit_variable_declarator(&mut self, declarator: &VariableDeclarator<'a>) { if let (Some(name), Some(init)) = (declarator.id.get_identifier_name(), &declarator.init) && is_component_name(&name) @@ -429,21 +536,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 +567,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())) + } + /// Compile one Devup UI element fn element(&mut self, element: &JSXElement<'a>, kind: &ExportVariableKind, local: &str) { let opening = &element.opening_element; @@ -522,6 +662,10 @@ impl<'a> Elements<'_> { } } let retagged = tag.is_some(); + let press = self.press.take(); + if let Some(press) = press.filter(|_| styles.blocks.iter().any(Choice::pressed)) { + tag = self.pressable(press, kind, local, tag); + } self.finish(element, styles, (tag, local), previous_end); self.children(element, kind, local, retagged); } @@ -551,6 +695,7 @@ impl<'a> Elements<'_> { return self.tag(attribute, local); } Prop::Style => self.given_style(attribute, span, local, styles), + Prop::ClassName => self.class_name(attribute, span, local, styles), Prop::Declares => { styles.removed.push(span); match self.value_choice(name, attribute.value.as_ref()) { @@ -578,12 +723,18 @@ impl<'a> Elements<'_> { attribute.span.start, local, ); - styles.choices.extend(choices); + styles.blocks.extend(choices); + } + Prop::When(state) => { + styles.removed.push(span); + let choices = self.state_block( + attribute_expression(attribute), + (name, state), + attribute.span.start, + local, + ); + styles.blocks.extend(choices); } - Prop::Runtime(feature) => self.error( - attribute.span.start, - feature.problem(self.target).on(local, name), - ), Prop::Unsupported(problem) => self.error(attribute.span.start, problem.on(local, name)), Prop::Pass => self.pass(attribute), } @@ -607,11 +758,11 @@ impl<'a> Elements<'_> { ) { match attribute_expression(attribute) { Some(expression) => { - styles - .given - .push(expression.span().source_text(self.code).to_string()); + let code = self.rewritten(expression); + let at = expression.span(); + styles.kept = Some((at.start as usize, at.end as usize, code.clone())); + styles.given.push(code); styles.style = Some(span); - self.visit_expression(expression); } None => self.error( attribute.span.start, @@ -715,10 +866,7 @@ impl<'a> Elements<'_> { }; let count = self.target.theme.count(); if count > 1 && !self.target.runtime { - self.error( - offset, - RuntimeFeature::Theme.problem(self.target).on(local, name), - ); + self.error(offset, RuntimeFeature::Theme.problem().on(local, name)); return Vec::new(); } if self.theme_scope.is_some_and(|scope| scope != index) { @@ -733,9 +881,36 @@ impl<'a> Elements<'_> { .collect() } + /// The styles of `_landscape`, `_portrait` or `_pressed`, `name` being + /// the prop: they apply only while `state` holds + fn state_block( + &mut self, + value: Option<&Expression<'a>>, + (name, state): (&str, State), + offset: u32, + local: &str, + ) -> Vec { + // `Pressable` tells whether it is pressed; only the orientation needs + // the runtime + if state == State::Pressed { + self.press.get_or_insert_with(|| (offset, name.to_string())); + } else if !self.target.runtime { + self.error( + offset, + RuntimeFeature::Orientation.problem().on(local, name), + ); + return Vec::new(); + } + self.block(value, name, offset, local) + .into_iter() + .map(|choice| when(state, choice)) + .collect() + } + /// The styles of an object of style props fn object_choices(&mut self, object: &ObjectExpression<'a>, local: &str) -> Vec { let mut choices = Vec::new(); + let mut blocks = Vec::new(); for property in &object.properties { let ObjectPropertyKind::ObjectProperty(property) = property else { self.error( @@ -765,8 +940,12 @@ impl<'a> Elements<'_> { ); continue; }; - choices.extend(self.object_property(&key, &property.value, property.span.start, local)); + let block = matches!(classify(&key), Prop::Theme(_) | Prop::When(_)); + let property_choices = + self.object_property(&key, &property.value, property.span.start, local); + if block { &mut blocks } else { &mut choices }.extend(property_choices); } + choices.extend(blocks); choices } @@ -792,11 +971,11 @@ impl<'a> Elements<'_> { Prop::Theme(theme) => { return self.theme_block(Some(value), (key, &theme), offset, local); } - Prop::Runtime(feature) => { - self.error(offset, feature.problem(self.target).on(local, key)); + Prop::When(state) => { + return self.state_block(Some(value), (key, state), offset, local); } Prop::Unsupported(problem) => self.error(offset, problem.on(local, key)), - Prop::As | Prop::Style | Prop::Pass => self.error( + Prop::As | Prop::Style | Prop::ClassName | Prop::Pass => self.error( offset, Problem::new( "a block holds only style props", @@ -817,7 +996,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 +1018,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 +1037,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 +1046,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()); + } + 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 { @@ -936,18 +1171,37 @@ impl<'a> Elements<'_> { attributes_end: u32, ) { let Styles { - choices, + classes, + mut choices, + blocks, given, mut removed, style, + kept, opaque_spread, } = styles; - let style_code = style_code(choices, given, &mut self.sheet, &self.runtime.index); - let wrapped = style_code + choices.extend(blocks); + let pressed = choices.iter().any(Choice::pressed); + let mut style_code = style_code( + choices, + (classes, 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); + if let Some(style) = style_code.as_mut().filter(|_| pressed) { + // `Pressable` calls a function for its style with its state + style.code = format!( + "({{ pressed: {} }}) => {}", + self.runtime.pressed, style.code + ); + } + let wrapped = reads.any() && !self.read_in_component(reads); if wrapped { self.runtime.wrapper_used = true; + 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 { @@ -955,13 +1209,25 @@ impl<'a> Elements<'_> { } let Some(style_code) = style_code else { self.remove(&removed); + self.replacements.extend(kept); 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 { @@ -979,6 +1245,37 @@ impl<'a> Elements<'_> { .push((attributes_end as usize, attributes_end as usize, code)); } + /// The component an element taking a press style renders: React Native's + /// `Pressable` for a `View`, which only it can call the style of with + /// whether it is pressed, or the `Pressable` it already renders + fn pressable( + &mut self, + (offset, name): (u32, String), + kind: &ExportVariableKind, + local: &str, + tag: Option, + ) -> Option { + let problem = match (native_component(kind), &tag) { + ("Pressable", None) => return None, + ("View", None) => { + self.pressable_used = true; + return Some(self.pressable.clone()); + } + (_, Some(_)) => Problem::new( + "a press style makes the element React Native's `Pressable`, which cannot render the component `as` gives", + "remove `as`, or pass a function reading `pressed` to the `style` of a `Pressable`", + ), + (native, None) => Problem::new( + format!( + "a press style needs React Native's `Pressable`, and the element renders React Native's `{native}`" + ), + "wrap it in a `Box` or a `Button` with `_pressed`", + ), + }; + self.error(offset, problem.on(local, &name)); + tag + } + /// Render the component `as` gives fn rename(&mut self, element: &JSXElement<'a>, tag: &str) { let names = std::iter::once(element.opening_element.name.span()).chain( @@ -1085,6 +1382,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/element/css_call.rs b/libs/extractor/src/native/element/css_call.rs new file mode 100644 index 000000000..b0ff3cdbd --- /dev/null +++ b/libs/extractor/src/native/element/css_call.rs @@ -0,0 +1,374 @@ +//! `css()` on React Native: a call compiles to the style it describes, the +//! code an element's `style` takes, and `className` passes that style on. + +use oxc_ast::ast::{ + CallExpression, Expression, IdentifierReference, JSXAttribute, LogicalOperator, + ObjectExpression, TaggedTemplateExpression, TemplateLiteral, +}; +use oxc_ast_visit::Visit; +use oxc_span::{GetSpan, Span}; +use std::fmt::Write; + +use super::{Elements, Prop, Styles, attribute_expression, classify}; +use crate::native::errors::Problem; +use crate::native::style::{Choice, combined, style_code}; +use crate::native::values::Literal; + +/// The name `css()` errors call the call by +const CSS: &str = "css()"; + +impl<'a> Elements<'_> { + /// Whether `callee` reads the `css` the file imports + pub(super) fn is_css(&self, callee: &Expression<'_>) -> bool { + match callee.without_parentheses() { + Expression::Identifier(identifier) => self.is_css_reference(identifier), + _ => false, + } + } + + /// Whether `identifier` reads the `css` the file imports + pub(super) fn is_css_reference(&self, identifier: &IdentifierReference<'_>) -> bool { + identifier + .reference_id + .get() + .and_then(|reference| self.scoping.get_reference(reference).symbol_id()) + .is_some_and(|symbol| self.css.contains(&symbol)) + } + + /// Compile a call of `css` to the style it describes + pub(super) fn css_call(&mut self, call: &CallExpression<'a>) { + let mut choices = Vec::new(); + for argument in &call.arguments { + match argument.as_expression() { + Some(expression) => self.css_part(expression, &mut choices), + None => self.error(argument.span().start, spread_problem()), + } + } + if let Some((offset, name)) = self.press.take() { + self.error( + offset, + Problem::new( + "a press style applies while an element is pressed, which `css()` cannot tell", + format!("give `{name}` to the element"), + ) + .on(CSS, &name), + ); + } + self.css_code(call.span, choices); + } + + /// Compile `css` tagged with CSS text, such as `` css`padding: 8px;` ``, + /// to the style it describes + pub(super) fn css_template(&mut self, template: &TaggedTemplateExpression<'a>) { + let choices = self.css_text(&template.quasi, template.span.start); + self.css_code(template.span, choices); + } + + /// Put the style `choices` describe in place of the `css` at `span` + fn css_code(&mut self, span: Span, choices: Vec) { + let code = style_code( + choices, + (Vec::new(), Vec::new()), + &mut self.sheet, + &self.runtime.vars(), + ) + .map_or_else( + || "null".to_string(), + |style| { + if style.reads.any() && !self.read_in_component(style.reads) { + self.error(span.start, outside_component_problem()); + } + style.code + }, + ); + self.replacements + .push((span.start as usize, span.end as usize, code)); + } + + /// The styles CSS text declares, each value written in it or given whole + /// by an interpolation + pub(super) fn css_text(&mut self, template: &TemplateLiteral<'a>, offset: u32) -> Vec { + let text = marked_text(template); + if text.contains(['{', '}']) { + self.error( + offset, + Problem::new( + "CSS text on React Native holds only declarations: React Native has no selectors, nesting or at-rules", + "write the declarations alone, and the styles of other states as props such as `_active`", + ) + .call(CSS), + ); + return Vec::new(); + } + let mut choices = Vec::new(); + for declaration in text + .split(';') + .map(str::trim) + .filter(|text| !text.is_empty()) + { + match self.css_declaration(declaration, &template.expressions) { + Ok(choice) => choices.push(choice), + Err((name, problem)) => self.error(offset, problem.on(CSS, &name)), + } + } + choices + } + + /// The styles one declaration of CSS text declares + fn css_declaration( + &self, + declaration: &str, + expressions: &[Expression<'a>], + ) -> Result { + let Some((name, value)) = declaration.split_once(':') else { + return Err(( + unmarked(declaration), + Problem::new( + "a declaration of CSS text is a property and a value", + "write it as `property: value`", + ), + )); + }; + let name = camel_case(name.trim()); + let value = value.trim().trim_end_matches("!important").trim_end(); + if classify(&name) != Prop::Declares { + return Err(( + name, + Problem::new( + "React Native has no such style", + "remove it, or write a style React Native has", + ), + )); + } + let result = match marker_index(value) { + Some(index) => self.expression_choice(&name, &expressions[index]), + None if value.contains(MARKER) => Err(Problem::new( + "the build reads an interpolation in CSS text only as a whole value", + "compute the whole value in the interpolation, such as `${`${size}px`}`", + )), + None => self.static_choice(&name, &[(0, Literal::Text(value.to_string()))]), + }; + result.map_err(|problem| (name, problem)) + } + + /// One argument of `css()`: an object of styles, a condition choosing + /// objects, or a style it passes on whole, such as what another `css()` + /// gives + fn css_part(&mut self, expression: &Expression<'a>, choices: &mut Vec) { + match expression.without_parentheses() { + Expression::ObjectExpression(object) => { + let object_choices = self.object_choices(object, CSS); + choices.extend(object_choices); + } + Expression::ConditionalExpression(condition) + if is_object(&condition.consequent) || is_object(&condition.alternate) => + { + let consequent = self.css_branch(&condition.consequent); + let alternate = self.css_branch(&condition.alternate); + choices.push(Choice::Condition { + test: self.rewritten(&condition.test), + consequent: Box::new(consequent), + alternate: Box::new(alternate), + }); + } + Expression::LogicalExpression(logical) + if logical.operator == LogicalOperator::And && is_object(&logical.right) => + { + let consequent = self.css_branch(&logical.right); + choices.push(Choice::Condition { + test: self.rewritten(&logical.left), + consequent: Box::new(consequent), + alternate: Box::new(Choice::Empty), + }); + } + Expression::StringLiteral(_) | Expression::TemplateLiteral(_) => { + self.error(expression.span().start, class_problem(CSS, "a part")); + } + expression if is_nothing(expression) => {} + expression => { + let code = self.rewritten(expression); + choices.push(Choice::Given(code)); + } + } + } + + /// The styles of a branch of a condition in `css()`: an object, or none + fn css_branch(&mut self, expression: &Expression<'a>) -> Choice { + match expression.without_parentheses() { + Expression::ObjectExpression(object) => self.css_object(object), + expression if is_nothing(expression) => Choice::Empty, + expression => { + self.error( + expression.span().start, + Problem::new( + "a condition in `css()` chooses between objects of styles", + "write each branch as an object, or as `null`", + ) + .on(CSS, "?"), + ); + Choice::Empty + } + } + } + + fn css_object(&mut self, object: &ObjectExpression<'a>) -> Choice { + let choices = self.object_choices(object, CSS); + combined(choices) + } + + /// `className` on an element: the style a `css()` gives, before the + /// element's style props + pub(super) fn class_name( + &mut self, + attribute: &JSXAttribute<'a>, + span: Span, + local: &str, + styles: &mut Styles, + ) { + match attribute_expression(attribute).map(Expression::without_parentheses) { + Some(Expression::StringLiteral(_) | Expression::TemplateLiteral(_)) | None => { + self.error(attribute.span.start, class_problem(local, "className")); + } + Some(expression) => { + let code = self.rewritten(expression); + styles.classes.push(code); + styles.removed.push(span); + } + } + } + + /// The code of `expression` with what the build compiles in it compiled, + /// such as a `css()` call or a Devup UI element + pub(super) fn rewritten(&mut self, expression: &Expression<'a>) -> String { + let span = expression.span(); + let mark = self.replacements.len(); + self.visit_expression(expression); + let (start, end) = (span.start as usize, span.end as usize); + // What visiting the expression changes lies in it + let mut inner = self.replacements.split_off(mark); + inner.sort_by_key(|(from, to, _)| (*from, *to)); + let mut code = String::new(); + let mut at = start; + for (from, to, text) in inner { + code.push_str(&self.code[at..from]); + code.push_str(&text); + at = to; + } + code.push_str(&self.code[at..end]); + if matches!( + expression.without_parentheses(), + Expression::SequenceExpression(_) + ) { + format!("({code})") + } else { + code + } + } +} + +/// What marks an interpolation in CSS text, around its index +const MARKER: char = char::MIN; + +/// The text of `template`, each interpolation marked by its index +fn marked_text(template: &TemplateLiteral<'_>) -> String { + let mut text = String::new(); + for (index, quasi) in template.quasis.iter().enumerate() { + text.push_str(quasi.value.raw.as_str()); + if index < template.expressions.len() { + let _ = write!(text, "{MARKER}{index}{MARKER}"); + } + } + strip_comments(&text) +} + +/// `text` without its CSS comments +fn strip_comments(text: &str) -> String { + let mut rest = text; + let mut kept = String::new(); + while let Some(start) = rest.find("/*") { + kept.push_str(&rest[..start]); + rest = rest[start + 2..] + .find("*/") + .map_or("", |end| &rest[start + 2 + end + 2..]); + } + kept.push_str(rest); + kept +} + +/// `text` as it is written, each interpolation as `${…}` +fn unmarked(text: &str) -> String { + text.split(MARKER) + .enumerate() + .map(|(at, part)| if at % 2 == 1 { "${…}" } else { part }) + .collect() +} + +/// The index of the interpolation `value` is, when it is one whole +fn marker_index(value: &str) -> Option { + value + .strip_prefix(MARKER)? + .strip_suffix(MARKER)? + .parse() + .ok() +} + +/// A CSS property name as React Native names its style: `background-color` +/// as `backgroundColor` +fn camel_case(name: &str) -> String { + let mut camel = String::with_capacity(name.len()); + let mut upper = false; + for character in name.chars() { + if character == '-' { + upper = !camel.is_empty(); + } else if upper { + camel.extend(character.to_uppercase()); + upper = false; + } else { + camel.push(character); + } + } + camel +} + +/// Whether `expression` is an object of styles +fn is_object(expression: &Expression<'_>) -> bool { + matches!( + expression.without_parentheses(), + Expression::ObjectExpression(_) + ) +} + +/// Whether `expression` gives no style: `null`, `undefined` or `false` +fn is_nothing(expression: &Expression<'_>) -> bool { + match expression { + Expression::NullLiteral(_) => true, + Expression::BooleanLiteral(literal) => !literal.value, + Expression::Identifier(identifier) => identifier.name == "undefined", + _ => false, + } +} + +fn spread_problem() -> String { + Problem::new( + "the build reads only the parts written in the call", + "pass each part to `css()` itself", + ) + .call(CSS) +} + +fn outside_component_problem() -> String { + Problem::new( + "its styles differ by theme, breakpoint or orientation, which only a function component or a hook can read", + "call `css()` in the component that uses it", + ) + .call(CSS) +} + +/// The error for a class name, which React Native has none of +fn class_problem(subject: &str, prop: &str) -> String { + Problem::new( + "React Native has no class names", + "pass what `css()` gives, or write the styles as props", + ) + .on(subject, prop) +} diff --git a/libs/extractor/src/native/errors.rs b/libs/extractor/src/native/errors.rs index 6e21074b3..9cc2c1fa6 100644 --- a/libs/extractor/src/native/errors.rs +++ b/libs/extractor/src/native/errors.rs @@ -1,7 +1,5 @@ //! The build errors of the React Native output -use super::NativeTarget; - /// Why a value or prop cannot compile, and what to write instead #[derive(Debug, Clone, PartialEq, Eq)] pub(super) struct Problem { @@ -17,10 +15,24 @@ impl Problem { } } - /// The error for the prop `prop` of `` + /// The error for the prop `prop` of ``, or the key `prop` of a + /// call such as `css()` pub(super) fn on(&self, element: &str, prop: &str) -> String { + let subject = if element.ends_with(')') { + element.to_string() + } else { + format!("<{element}>") + }; format!( - "`<{element}>` cannot use `{prop}` on React Native: {}. Fix: {}", + "`{subject}` cannot use `{prop}` on React Native: {}. Fix: {}", + self.reason, self.fix + ) + } + + /// The error for a call such as `css()` + pub(super) fn call(&self, call: &str) -> String { + format!( + "`{call}` cannot compile here on React Native: {}. Fix: {}", self.reason, self.fix ) } @@ -35,41 +47,40 @@ impl Problem { } /// What needs the React Native runtime: one style object a breakpoint, a -/// theme or a press state, chosen while the app runs +/// theme or an orientation, chosen while the app runs #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) enum RuntimeFeature { Responsive, + Orientation, Theme, - Pressed, } impl RuntimeFeature { 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", } } 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`" - } } } - /// Why the feature cannot compile for `target` - pub(super) fn problem(self, target: &NativeTarget) -> Problem { - let runtime = if target.runtime { - "which needs the React Native runtime that this version does not include yet" - } else { - "which needs the React Native runtime that `runtime: false` turns off" - }; - Problem::new(format!("{}, {runtime}", self.what()), self.fix()) + /// Why the feature cannot compile with `runtime: false` + pub(super) fn problem(self) -> Problem { + Problem::new( + format!( + "{}, which needs the React Native runtime that `runtime: false` turns off", + self.what() + ), + self.fix(), + ) } } diff --git a/libs/extractor/src/native/imports.rs b/libs/extractor/src/native/imports.rs index ae544d5a3..cae451be3 100644 --- a/libs/extractor/src/native/imports.rs +++ b/libs/extractor/src/native/imports.rs @@ -10,7 +10,7 @@ use oxc_ast::ast::{ }; use oxc_span::GetSpan; use oxc_syntax::symbol::SymbolId; -use rustc_hash::FxHashMap; +use rustc_hash::{FxHashMap, FxHashSet}; use super::errors::{Problem, theme_api}; use super::{NativeTarget, REACT_NATIVE, RUNTIME, Replacement}; @@ -21,6 +21,8 @@ use crate::component::ExportVariableKind; pub(super) struct Imports { /// Each component's binding: its kind and local name pub components: FxHashMap, + /// The bindings of `css`, whose calls compile to style objects + pub css: FxHashSet, pub replacements: Vec, pub errors: Vec<(u32, String)>, /// Whether the file imports the theme API of the runtime @@ -58,6 +60,8 @@ enum Destination { Runtime(String), /// The package, as it is: a name only types read Kept, + /// Nowhere: the build compiles each use of the name away + Dropped, } /// Why an export of the package cannot be imported on React Native, or `None` @@ -69,8 +73,8 @@ fn unsupported(name: &str, target: &NativeTarget) -> Option { "React Native has no grid layout", "lay the items out with `Flex` and `flexWrap`", )), - "css" | "styled" => Some(Problem::new( - format!("`{name}` is not compiled for React Native yet"), + "styled" => Some(Problem::new( + "`styled` is not compiled for React Native yet", "write the styles as props of a Devup UI component", )), name if is_theme_api(name) => (!target.runtime).then(|| theme_api(name)), @@ -133,6 +137,7 @@ impl Imports { Destination::Native(native) => natives.push(native), Destination::Runtime(name) => runtime.push(name), Destination::Kept => kept.push(specifier_code(specifier, code)), + Destination::Dropped => {} } } specifier => self.errors.push(( @@ -145,7 +150,9 @@ impl Imports { )), } } - if natives.is_empty() && runtime.is_empty() { + let dropped = natives.len() + runtime.len() + kept.len() + < declaration.specifiers.iter().flatten().count(); + if natives.is_empty() && runtime.is_empty() && !dropped { return; } self.theme_api |= !runtime.is_empty(); @@ -181,6 +188,10 @@ impl Imports { return Destination::Kept; } let local = specifier.local.name.to_string(); + if name == "css" { + self.css.extend(specifier.local.symbol_id.get()); + return Destination::Dropped; + } if is_theme_api(&name) { return Destination::Runtime(renamed(&name, local)); } diff --git a/libs/extractor/src/native/mod.rs b/libs/extractor/src/native/mod.rs index 68911d456..fa0fa54bc 100644 --- a/libs/extractor/src/native/mod.rs +++ b/libs/extractor/src/native/mod.rs @@ -9,9 +9,12 @@ //! 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 -//! React Native has no style for is a build error naming the 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. +//! `_active`/`_pressed` make the element a `Pressable`, whose `style` is a +//! function of whether it is pressed. A prop React Native has no style for is +//! a build error naming the prop. mod element; mod errors; diff --git a/libs/extractor/src/native/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__apis.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__apis.snap index 6d3e6d0a6..ef9f8356a 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__apis.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__apis.snap @@ -2,8 +2,7 @@ source: libs/extractor/src/native/tests.rs expression: "compile_for(NativePlatform::Ios, false, code)" --- -error: test.tsx:1:10: `css` from `@devup-ui/react` cannot be used on React Native: `css` is not compiled for React Native yet. Fix: write the styles as props of a Devup UI component -test.tsx:1:15: `styled` from `@devup-ui/react` cannot be used on React Native: `styled` is not compiled for React Native yet. Fix: write the styles as props of a Devup UI component +error: test.tsx:1:15: `styled` from `@devup-ui/react` cannot be used on React Native: `styled` is not compiled for React Native yet. Fix: write the styles as props of a Devup UI component test.tsx:1:23: `globalCss` from `@devup-ui/react` cannot be used on React Native: React Native has no document and no global stylesheet. Fix: remove it from the React Native build test.tsx:1:34: `ThemeScript` from `@devup-ui/react` cannot be used on React Native: React Native has no document and no global stylesheet. Fix: remove it from the React Native build test.tsx:1:47: `initTheme` from `@devup-ui/react` cannot be used on React Native: React Native has no document and no global stylesheet. Fix: remove it from the React Native build diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_nested.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_nested.snap new file mode 100644 index 000000000..b62027d3e --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_nested.snap @@ -0,0 +1,27 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, &code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useThemeIndex as __useThemeIndex, useLandscape as __useLandscape, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { Pressable as __Pressable } from "react-native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { padding: 20 }, + b: { margin: 8 }, + c: { padding: 16 }, + d: { margin: 4 }, + e: { margin: 12 } +}); +export function A() { + const __t = __useThemeIndex(); + const __l = __useLandscape(); + return <__Pressable style={({ pressed: __p }) => [ + __s.a, + __l && __s.b, + __l && __s.c, + __l && __p && __s.d, + __l && [null, __s.e][__t] + ]} />; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_orientation.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_orientation.snap new file mode 100644 index 000000000..e70c7d75c --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_orientation.snap @@ -0,0 +1,15 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, &code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useLandscape as __useLandscape } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { padding: 8 }, + b: { padding: 4 } +}); +export function A() { + const __l = __useLandscape(); + return ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_platform.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_platform.snap new file mode 100644 index 000000000..982549a93 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_platform.snap @@ -0,0 +1,10 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, &code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ a: { margin: 8 } }); +export function A() { + return ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_pressed.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_pressed.snap new file mode 100644 index 000000000..1d57155ca --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_pressed.snap @@ -0,0 +1,14 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, &code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { Pressable as __Pressable } from "react-native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { margin: 8 }, + b: { margin: 4 } +}); +export function A() { + return <__Pressable style={({ pressed: __p }) => [__s.a, __p && __s.b]} />; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_theme.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_theme.snap new file mode 100644 index 000000000..8d5ffe18a --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__block_order_theme.snap @@ -0,0 +1,16 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), true, &code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useThemeIndex as __useThemeIndex, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { backgroundColor: "blue" }, + b: { backgroundColor: "red" } +}); +export function A() { + const __t = __useThemeIndex(); + return ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__css_alone.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__css_alone.snap new file mode 100644 index 000000000..2bdf81a08 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__css_alone.snap @@ -0,0 +1,8 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_for(NativePlatform::Android, false,\n\"import { css } from '@devup-ui/react'\\nimport { View } from 'react-native'\\nexport const A = () => \")" +--- +import { View } from "react-native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ a: { padding: 4 } }); +export const A = () => ; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__css_calls.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__css_calls.snap new file mode 100644 index 000000000..08d63481b --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__css_calls.snap @@ -0,0 +1,47 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { type DevupProps } from "@devup-ui/react"; +import { useThemeIndex as __useThemeIndex, useBreakpoint as __useBreakpoint, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { + padding: 16, + borderRadius: 8 + }, + b: { color: "#111" }, + c: { color: "#eee" }, + d: { fontSize: 56 }, + e: { fontSize: 72 }, + f: { padding: 8 }, + g: { fontWeight: "700" }, + h: { color: "red" }, + i: { backgroundColor: "#1a1a2e" }, + j: { margin: 4 }, + k: { padding: 4 } +}); +const card = __s.a; +export function Card({ on, extra, children }) { + const __t = __useThemeIndex(); + const __b = __useBreakpoint(); + const title = [[__s.b, __s.c][__t], __b < 2 ? __s.d : __s.e]; + return + {children} + + + + + + ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap new file mode 100644 index 000000000..a9c1b400e --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap @@ -0,0 +1,22 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:3:18: `css()` cannot compile here on React Native: its styles differ by theme, breakpoint or orientation, which only a function component or a hook can read. Fix: call `css()` in the component that uses it +test.tsx:4:22: `css()` cannot compile here on React Native: the build reads only the parts written in the call. Fix: pass each part to `css()` itself +test.tsx:5:22: `css()` cannot use `a part` on React Native: React Native has no class names. Fix: pass what `css()` gives, or write the styles as props +test.tsx:5:30: `css()` cannot use `a part` on React Native: React Native has no class names. Fix: pass what `css()` gives, or write the styles as props +test.tsx:5:55: `css()` cannot use `?` on React Native: a condition in `css()` chooses between objects of styles. Fix: write each branch as an object, or as `null` +test.tsx:6:24: `css()` cannot use `_hover` on React Native: React Native has no selectors, pseudo-elements or media queries. Fix: remove it, or write the style the element takes in every state +test.tsx:6:42: `css()` cannot use `[key]` on React Native: the build reads only keys written in a block. Fix: write the key itself +test.tsx:7:18: `css` can only be called on React Native: the build compiles each call into styles. Fix: call it where the styles are used +test.tsx:8:32: `css()` cannot use `className` on React Native: a block holds only style props. Fix: pass it to the element itself +test.tsx:8:57: `css()` cannot use `?` on React Native: a condition in `css()` chooses between objects of styles. Fix: write each branch as an object, or as `null` +test.tsx:9:18: `css()` cannot compile here on React Native: CSS text on React Native holds only declarations: React Native has no selectors, nesting or at-rules. Fix: write the declarations alone, and the styles of other states as props such as `_active` +test.tsx:10:18: `css()` cannot use `color` on React Native: a declaration of CSS text is a property and a value. Fix: write it as `property: value` +test.tsx:10:18: `css()` cannot use `padding ${…}px` on React Native: a declaration of CSS text is a property and a value. Fix: write it as `property: value` +test.tsx:10:18: `css()` cannot use `padding` on React Native: the build reads an interpolation in CSS text only as a whole value. Fix: compute the whole value in the interpolation, such as `${`${size}px`}` +test.tsx:10:18: `css()` cannot use `webkitMask` on React Native: React Native has no such style. Fix: remove it, or write a style React Native has +test.tsx:12:15: `` cannot use `className` on React Native: React Native has no class names. Fix: pass what `css()` gives, or write the styles as props +test.tsx:12:31: `css()` cannot use `_active` on React Native: a press style applies while an element is pressed, which `css()` cannot tell. Fix: give `_active` to the element +test.tsx:12:91: `` cannot use `className` on React Native: React Native has no class names. Fix: pass what `css()` gives, or write the styles as props diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__css_only.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__css_only.snap new file mode 100644 index 000000000..99100733a --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__css_only.snap @@ -0,0 +1,36 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useLandscape as __useLandscape } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { margin: 8 }, + b: { padding: 4 }, + c: { padding: 8 }, + d: { margin: 4 }, + e: { padding: 12 } +}); +export const s = [__s.a, cond ? __s.b : __s.c]; +export const t = [ + true, + on ? null : __s.b, + on && __s.d, + other.css({ p: 1 }) +]; +export const useU = () => { + const __l = __useLandscape(); + return [ + t, + __s.b, + __l && __s.d, + __s.a, + on ? null : [__s.c, __l && __s.e], + other`x` + ]; +}; +export const useV = () => { + const __l = __useLandscape(); + return [__s.c, __l && __s.d]; +}; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__css_runtime_off.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__css_runtime_off.snap new file mode 100644 index 000000000..5f220db6c --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__css_runtime_off.snap @@ -0,0 +1,5 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:3:24: `css()` cannot use `m` 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__css_text.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__css_text.snap new file mode 100644 index 000000000..54fe38b63 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__css_text.snap @@ -0,0 +1,32 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +import { View as Box, Pressable as Button, View as Center, View as Flex, Image, TextInput as Input, Text, View as VStack } from "react-native"; +import { useThemeIndex as __useThemeIndex, defineThemes as __defineThemes } from "@devup-ui/react/native"; +__defineThemes(["light", "dark"], 1); +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { + paddingVertical: 8, + paddingHorizontal: 16, + fontWeight: "bold" + }, + b: { backgroundColor: "#5a44ff" }, + c: { backgroundColor: "#8c7bff" } +}); +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 A({ size }) { + const __t = __useThemeIndex(); + const s = [ + __s.a, + [__s.b, __s.c][__t], + { borderRadius: __u(size, 4) } + ]; + return ; +} +export const t = null; 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..4bc7603e6 --- /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..ed184d1d0 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__platform_shapes.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__platform_shapes.snap @@ -7,7 +7,5 @@ test.tsx:2:32: `` cannot use `...` on React Native: the build reads only th test.tsx:2:41: `` cannot use `[key]` on React Native: the build reads only keys written in a block. Fix: write the key itself test.tsx:2:51: `` cannot use `onPress` on React Native: a block holds only style props. Fix: pass it to the element itself test.tsx:2:63: `` cannot use `_hover` on React Native: React Native has no selectors, pseudo-elements or media queries. Fix: remove it, or write the style the element takes in every state -test.tsx:2:75: `` cannot use `_pressed` on React Native: a press style is chosen while the element is pressed, which needs the React Native runtime that this version does not include yet. Fix: pass a function to the `style` of a React Native `Pressable`, reading `pressed` test.tsx:2:89: `` cannot use `_web` on React Native: `_web` takes an object of styles. Fix: write the styles in an object, such as `_web={{ p: 2 }}` test.tsx:2:103: `` cannot use `as` on React Native: a block holds only style props. Fix: pass it to the element itself -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__pressed.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__pressed.snap deleted file mode 100644 index bbe1020a8..000000000 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__pressed.snap +++ /dev/null @@ -1,6 +0,0 @@ ---- -source: libs/extractor/src/native/tests.rs -expression: compile(code) ---- -error: test.tsx:2:9: ` + <__Pressable onPress={go} style={({ pressed: __p }) => [__b < 1 ? __s.g : __s.a, __p && __s.h]} /> + <__Pressable onPress={go} style={({ pressed: __p }) => [ + __s.i, + __p && (on ? __s.g : __s.a), + extra + ]}> + + + <__Pressable style={({ pressed: __p }) => __t === 1 && __p && __s.j} /> + + + + + + + + ) +} +``` + +`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, conditions between them and the platform and theme -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` +runtime, theme tokens, responsive values, conditions between them and the +platform, theme, orientation and press blocks, and `css()`. These are build +errors, reported by Metro at the file, line and column: -The runtime that brings responsive values and `_pressed` comes in a later -version. +- interaction states other than `_active`/`_pressed` (`_hover`, `_focus`, ...) +- `styled()`, `globalCss()`, `keyframes()` and `Grid` +- any prop React Native has no style for +- with `runtime: false`, a value that differs by theme or breakpoint, + `_theme*` with more than one theme, `_portrait`, `_landscape`, and + `useTheme`, `getTheme` and `setTheme` 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()), + }) } 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', })) },