diff --git a/.changepacks/changepack_log_metro_viewport_motion.json b/.changepacks/changepack_log_metro_viewport_motion.json new file mode 100644 index 000000000..67690a931 --- /dev/null +++ b/.changepacks/changepack_log_metro_viewport_motion.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/metro-plugin/package.json": "Patch" + }, + "note": "Compile `vw`/`vh`/`vmin`/`vmax` (and their small, large and dynamic forms) to one multiplication of the window size, and `_motionReduce`/`_motionSafe` to the system's reduced-motion setting, on React Native.", + "date": "2026-11-22T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_react_native_viewport_motion.json b/.changepacks/changepack_log_react_native_viewport_motion.json new file mode 100644 index 000000000..cd493d3e8 --- /dev/null +++ b/.changepacks/changepack_log_react_native_viewport_motion.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/react/package.json": "Patch" + }, + "note": "The React Native runtime adds `useReducedMotion` (from `AccessibilityInfo`), `useWindowWidth`, `useWindowHeight` and the `Sized` wrapper, for `_motionReduce`/`_motionSafe` and viewport lengths. Window changes now notify every hook, and React renders again only the components whose value changed. The runtime grows from 1,185 B to 1,302 B min+gzip.", + "date": "2026-11-22T00:00:00.000Z" +} diff --git a/apps/expo/check-bundle.mjs b/apps/expo/check-bundle.mjs index 704d8d76f..cf2898846 100644 --- a/apps/expo/check-bundle.mjs +++ b/apps/expo/check-bundle.mjs @@ -15,9 +15,16 @@ 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|useBreakpoint|useLandscape|Focused)\b/g + /\b(?:defineThemes|useThemeIndex|useBreakpoint|useLandscape|useReducedMotion|useWindowWidth|useWindowHeight|Focused)\b/g /** What src/App.tsx must use from the runtime */ -const APP_HOOKS = ['useThemeIndex', 'useBreakpoint', 'useLandscape', 'Focused'] +const APP_HOOKS = [ + 'useThemeIndex', + 'useBreakpoint', + 'useLandscape', + 'useReducedMotion', + 'useWindowHeight', + 'Focused', +] /** Modules of @devup-ui/react, by the path Metro resolves */ const REACT_PACKAGE = /(^|[\\/])(@devup-ui[\\/]react|packages[\\/]react)[\\/]/ /** @@ -99,13 +106,21 @@ function mapSources(map) { : map.sources } -/** Each name of the runtime, with the sources of the code that names it */ +/** + * Each name of the runtime, with the sources of the app that name it: a + * package may name its own hook the same (Reanimated's `useReducedMotion`) + */ function runtimeUsers(code, locate) { const users = new Map() code.split('\n').forEach((line, index) => { for (const match of line.matchAll(RUNTIME_NAMES)) { const source = locate(index, match.index) - if (source === null || NATIVE_RUNTIME.test(source)) continue + if ( + source === null || + NATIVE_RUNTIME.test(source) || + /[\\/]node_modules[\\/]/.test(source) + ) + continue const sources = users.get(match[0]) ?? new Set() sources.add(source) users.set(match[0], sources) diff --git a/apps/expo/check-web.mjs b/apps/expo/check-web.mjs index 2d28949c7..0aad26c65 100644 --- a/apps/expo/check-web.mjs +++ b/apps/expo/check-web.mjs @@ -1,6 +1,7 @@ // Opens the web export (`expo export --platform web` wrote dist/) in Chromium // and checks that react-native-web renders the styles Devup UI compiled: the -// card takes the theme's color and switches with the theme, the input takes +// card takes the theme's color and switches with the theme and is at least +// 30vh tall, the input takes // its focus style through the runtime's `Focused`, and the button, a // `Pressable`, counts a press. import { createReadStream, existsSync, statSync } from 'node:fs' @@ -66,6 +67,11 @@ try { 'rgb(255, 255, 255)', 'the card in the light theme', ) + expectEqual( + await style(card, 'minHeight'), + `${(await page.evaluate(() => window.innerHeight)) * 0.3}px`, + 'the card, at least 30vh tall', + ) expectEqual( await style(count, 'backgroundColor'), 'rgb(90, 68, 255)', diff --git a/apps/expo/src/App.tsx b/apps/expo/src/App.tsx index e6318fa87..475183f84 100644 --- a/apps/expo/src/App.tsx +++ b/apps/expo/src/App.tsx @@ -58,11 +58,17 @@ export function App() { borderRadius="$radius" boxShadow="$raised" maxW={[null, null, '480px']} + minH="30vh" p={[4, null, 6]} testID="card" w="100%" > - + Your name {t('features')} {t('limitations')} {t('buildErrors')} - React Native + {t('reactNative')} **실험적 기능(0.x).** React Native 지원은 진행 중이며 +> ([#411](https://github.com/dev-five-git/devup-ui/issues/411)), +> `@devup-ui/metro-plugin`은 아직 배포되지 않았습니다. API는 바뀔 수 있습니다. + +Devup UI는 React Native와 Expo의 번들러인 Metro에서 React Native용으로 +컴파일됩니다. `Box`, `Text`, `css`, `styled` 등은 그대로 `@devup-ui/react`에서 +import합니다. 빌드 시점에 각 요소는 React Native 컴포넌트가 되고, 스타일 props는 +파일마다 하나의 `StyleSheet.create`로 끌어올려진 스타일 객체가 됩니다. 런타임에 +CSS를 파싱하는 일은 없습니다. + +## 설정 + +```bash +npm install @devup-ui/react @devup-ui/metro-plugin +``` + +```js +// metro.config.js (Expo) +const { getDefaultConfig } = require('expo/metro-config') +const { withDevupUI } = require('@devup-ui/metro-plugin') + +module.exports = withDevupUI(getDefaultConfig(__dirname)) +``` + +```js +// metro.config.js (React Native CLI) +const { getDefaultConfig } = require('@react-native/metro-config') +const { withDevupUI } = require('@devup-ui/metro-plugin') + +module.exports = withDevupUI(getDefaultConfig(__dirname)) +``` + +```tsx +import { Box, Flex, Text } from '@devup-ui/react' + +export function Card() { + return ( + + + Hello + + + + ) +} +``` + +Metro는 설정을 읽을 때 `df/theme.d.ts`와 `df/native.d.ts`를 생성합니다. 이 파일들 +덕분에 에디터에서 테마 토큰이 자동 완성되고, 각 컴포넌트는 자신이 렌더링하는 +React Native 컴포넌트의 props(`onPress`, `onChangeText`, `testID` 등)를 받습니다. + +## 요소 + +| 요소 | React Native | +| --------------------------------- | ------------------------------- | +| `Box`, `Flex`, `VStack`, `Center` | `View` | +| `Text` | `Text` | +| `Image` | `Image` (`src`는 `source`가 됨) | +| `Input` | `TextInput` | +| `Button` | `Pressable` | + +## 웹과의 차이 + +같은 컴포넌트 코드가 양쪽 모두로 빌드되지만, React Native에는 CSS가 없기 때문에 +일부는 다르게 동작합니다. + +| | 웹 | React Native | +| ------------------------------------------ | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 출력 | 스타일시트의 아토믹 CSS 클래스 | 파일마다 하나의 `StyleSheet.create` 안의 스타일 객체 | +| 런타임 | 없음 | 정적 스타일에는 없습니다. 작은 런타임(gzip 약 1.3 kB)이 테마, 창, 동작 줄이기 설정, 입력 요소의 포커스를 읽지만, 이를 사용하는 스타일에만 쓰입니다. `runtime: false`로 설정하면 그런 스타일은 대신 빌드 오류가 됩니다. | +| 숫자 | `p={4}`는 `16px` | `p={4}`는 `16`: 밀도 독립 픽셀이며, 웹과 같은 배율을 사용합니다 | +| 단위 | 모든 CSS 단위 | 픽셀, `rem`과 `em`(각각 16픽셀), 백분율, `auto`. `vw`, `vh`, `vmin`, `vmax`는 창 크기에 대한 곱셈 한 번이 되며, 창 크기가 바뀌면 이를 사용하는 컴포넌트만 다시 렌더링됩니다. | +| 테마 | `data-theme`으로 전환되는 CSS 변수 | 런타임이 현재 테마의 스타일 객체를 고릅니다. `setTheme`, `useTheme`, `getTheme`가 동작하며, 시스템 화면 모드에 따라 `light` 또는 `dark`가 선택됩니다. | +| 브레이크포인트 | 미디어 쿼리 | devup.json의 `breakpoints`를 기준으로 한 창 너비. 창이 다른 브레이크포인트로 넘어갈 때만 컴포넌트가 다시 렌더링됩니다. | +| `_active`, `_hover`, `_focus`, `_disabled` | CSS 가상 클래스 | `Pressable`이 스타일 함수에 눌림, 호버, 포커스 여부를 알려 줍니다. `Button`은 `Pressable`이며, 이런 스타일을 가진 `Box`는 `Pressable`이 됩니다. `Input`의 `_focus`는 런타임을 통해 동작합니다. `_disabled`는 `disabled` prop을 읽습니다. 호버와 포커스는 웹처럼 포인터나 키보드 포커스가 있는 곳에서만 일어납니다. | +| 그 밖의 선택자 | `_before`, `_focusVisible`, `selectors` 등 | 빌드 오류: React Native에는 선택자가 없습니다 | +| `_ios`, `_android`, `_web` | — | 해당 플랫폼에서만 적용 | +| `_portrait`, `_landscape` | 미디어 쿼리 | 창의 방향 | +| `_motionReduce`, `_motionSafe` | `prefers-reduced-motion` 미디어 쿼리 | 시스템이 앱에 동작 줄이기를 요청하는지 여부(`AccessibilityInfo`) | +| `className={css(...)}` | 클래스 | 빌드가 이를 요소의 스타일로 바꿉니다 | +| `keyframes`, `animation*`, `transition*` | CSS 애니메이션 | [react-native-reanimated](https://docs.swmansion.com/react-native-reanimated/): 애니메이션되는 요소는 Reanimated의 animated 컴포넌트를 렌더링합니다. Reanimated가 설치되어 있지 않으면 빌드 오류가 됩니다. | +| `globalCss`, `Grid` | 지원 | 빌드 오류 | +| styled-components와 Emotion | `styled-components`, `@emotion/styled` 등 | `styled-components/native`와 `@emotion/native`도 같은 방식으로 컴파일됩니다. 숫자는 해당 패키지가 해석하는 대로 픽셀입니다. | +| 지원하지 않는 속성 | — | React Native에 해당 스타일이 없는 속성(`gridTemplateColumns`, `float` 등)은 빌드 오류입니다 | + +빌드 오류는 웹과 마찬가지로 스타일이 있는 파일, 줄, 열을 가리킵니다. + +## Expo 웹 + +웹에서 Expo는 [react-native-web](https://necolas.github.io/react-native-web/)을 +통해 Metro로 앱을 번들링하며, 같은 네이티브 출력이 그곳에서 CSS로 바뀝니다. Expo +앱이 아닌 사이트는 계속 [Vite, Next.js, Webpack, Rsbuild 또는 Bun 플러그인](/docs/installation)을 +사용하며, 이 플러그인들은 대신 아토믹 CSS를 출력합니다. + +각 옵션과 기능의 자세한 내용은 +[`@devup-ui/metro-plugin` README](https://github.com/dev-five-git/devup-ui/tree/main/packages/metro-plugin)를 +참고하세요. diff --git a/apps/landing/src/app/(detail)/docs/react-native/page.mdx b/apps/landing/src/app/(detail)/docs/react-native/page.mdx index 806c78b8a..e276a6fc9 100644 --- a/apps/landing/src/app/(detail)/docs/react-native/page.mdx +++ b/apps/landing/src/app/(detail)/docs/react-native/page.mdx @@ -1,6 +1,13 @@ export const metadata = { title: 'React Native', - alternates: { canonical: '/docs/react-native' }, + alternates: { + canonical: '/docs/react-native', + languages: { + en: '/docs/react-native', + ko: '/ko/docs/react-native', + 'x-default': '/docs/react-native', + }, + }, } # React Native @@ -75,15 +82,16 @@ things work differently. | | Web | React Native | | ------------------------------------------ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Output | Atomic CSS classes in a stylesheet | Style objects in one `StyleSheet.create` per file | -| Runtime | None | None for static styles. A small runtime (about 1.2 kB gzip) reads the theme, the window and press, hover and focus states, but only for the styles that use them. With `runtime: false`, those styles are build errors instead. | +| Runtime | None | None for static styles. A small runtime (about 1.3 kB gzip) reads the theme, the window, reduced motion and the focus of inputs, but only for the styles that use them. With `runtime: false`, those styles are build errors instead. | | Numbers | `p={4}` is `16px` | `p={4}` is `16`: density-independent pixels, with the same scale as the web | -| Units | Any CSS unit | Pixels, `rem` and `em` (16 pixels each), percentages and `auto`. `vw`, `vh` and other units are build errors. | +| Units | Any CSS unit | Pixels, `rem` and `em` (16 pixels each), percentages and `auto`. `vw`, `vh`, `vmin` and `vmax` become one multiplication of the window's size, and only components using them render again on a resize. | | Themes | CSS variables, switched by `data-theme` | The runtime picks the style object of the current theme. `setTheme`, `useTheme` and `getTheme` work, and the system appearance picks `light` or `dark`. | | Breakpoints | Media queries | The window width, with the `breakpoints` of devup.json. A component renders again only when the window crosses into another breakpoint. | | `_active`, `_hover`, `_focus`, `_disabled` | CSS pseudo-classes | `Pressable` tells its style function whether it is pressed, hovered or focused: a `Button` is one, and a `Box` with these styles becomes one. `_focus` on an `Input` works through the runtime. `_disabled` reads the `disabled` prop. Hover and focus happen only where there is a pointer or keyboard focus, such as the web. | | Other selectors | `_before`, `_focusVisible`, `selectors`, ... | Build errors: React Native has no selectors | | `_ios`, `_android`, `_web` | — | Apply on that platform only | | `_portrait`, `_landscape` | Media queries | The window's orientation | +| `_motionReduce`, `_motionSafe` | `prefers-reduced-motion` media queries | Whether the system asks apps to reduce motion (`AccessibilityInfo`) | | `className={css(...)}` | A class | The build turns it into the element's styles | | `keyframes`, `animation*`, `transition*` | CSS animations | [react-native-reanimated](https://docs.swmansion.com/react-native-reanimated/): an element that animates renders Reanimated's animated component. Without Reanimated installed, these are build errors. | | `globalCss`, `Grid` | Supported | Build errors | diff --git a/apps/landing/src/app/(detail)/page.ko.tsx b/apps/landing/src/app/(detail)/page.ko.tsx index d25bbed21..be5daf3f0 100644 --- a/apps/landing/src/app/(detail)/page.ko.tsx +++ b/apps/landing/src/app/(detail)/page.ko.tsx @@ -3,6 +3,7 @@ import type { Metadata } from 'next' import { Bench } from '@/app/Bench' import { Feature } from '@/app/Feature' +import { ReactNative } from '@/app/ReactNative' import { TopBanner } from '@/app/TopBanner' import { Container } from '@/components/Container' import { Discord } from '@/components/Discord' @@ -37,6 +38,7 @@ export default function HomePage() { + diff --git a/apps/landing/src/app/(detail)/page.tsx b/apps/landing/src/app/(detail)/page.tsx index 8b4b56389..977515c34 100644 --- a/apps/landing/src/app/(detail)/page.tsx +++ b/apps/landing/src/app/(detail)/page.tsx @@ -6,6 +6,7 @@ import { Discord } from '@/components/Discord' import { Bench } from '../Bench' import { Feature } from '../Feature' +import { ReactNative } from '../ReactNative' import { TopBanner } from '../TopBanner' export const metadata: Metadata = { @@ -25,6 +26,7 @@ export default function HomePage() { + diff --git a/apps/landing/src/app/ReactNative.tsx b/apps/landing/src/app/ReactNative.tsx new file mode 100644 index 000000000..8dbae1f08 --- /dev/null +++ b/apps/landing/src/app/ReactNative.tsx @@ -0,0 +1,66 @@ +import { css, Flex, Grid, Image, Text, VStack } from '@devup-ui/react' +import type { Locale } from 'next-intl' +import { getTranslations } from 'next-intl/server' + +import { Link } from '@/i18n/navigation' + +const POINTS = ['metro', 'styleSheet', 'runtime'] as const + +export async function ReactNative({ locale = 'en' }: { locale?: Locale }) { + const t = await getTranslations({ locale, namespace: 'Home' }) + return ( + + + + + {t('reactNativeTitle')} + + + {t('reactNativeDescription')} + + + + {POINTS.map((key) => ( + + + {t(`reactNative.${key}.title`)} + + + {t(`reactNative.${key}.description`)} + + + ))} + + + + + {t('reactNativeDocs')} + + + + + + + ) +} diff --git a/apps/landing/src/i18n/messages/en.json b/apps/landing/src/i18n/messages/en.json index 76c04204c..11b149341 100644 --- a/apps/landing/src/i18n/messages/en.json +++ b/apps/landing/src/i18n/messages/en.json @@ -41,6 +41,7 @@ "optimizeCss": "Optimize CSS", "overview": "Overview", "quickStart": "Quick Start", + "reactNative": "React Native", "selector": "Selector", "shadow": "Shadow", "styleProps": "Style Props", @@ -93,6 +94,23 @@ "joinDiscord": "Join our Discord", "openKakaoTalk": "Open KakaoTalk", "preprocessor": "CSS in JS Preprocessor", + "reactNative": { + "metro": { + "title": "Metro plugin", + "description": "Wrap your Metro config with withDevupUI, in Expo or the React Native CLI. Keep importing Box, Text, css and styled from @devup-ui/react." + }, + "runtime": { + "description": "Static styles need no runtime. A tiny one (about 1.3 kB gzip) is imported only by styles that read the theme or the window, such as themes and responsive values. _pressed compiles to the Pressable style function.", + "title": "Minimal runtime" + }, + "styleSheet": { + "description": "Each element becomes a React Native component, and its style props become style objects in one StyleSheet.create per file. CSS is never parsed at runtime.", + "title": "StyleSheet at build time" + } + }, + "reactNativeDescription": "The same components now compile for React Native too. Experimental for now.", + "reactNativeDocs": "Read the React Native docs", + "reactNativeTitle": "React Native", "tagline": "Building the Future of CSS-in-JS

Analyze all possible scenarios at the fastest speed and style with optimal performance." }, "PropsTable": { diff --git a/apps/landing/src/i18n/messages/ko.json b/apps/landing/src/i18n/messages/ko.json index 34e070065..6e75eb993 100644 --- a/apps/landing/src/i18n/messages/ko.json +++ b/apps/landing/src/i18n/messages/ko.json @@ -41,6 +41,7 @@ "optimizeCss": "CSS 최적화", "overview": "개요", "quickStart": "빠른 시작", + "reactNative": "React Native", "selector": "선택자", "shadow": "그림자", "styleProps": "스타일 속성", @@ -93,6 +94,23 @@ "joinDiscord": "Discord 참여하기", "openKakaoTalk": "카카오톡 오픈채팅 열기", "preprocessor": "CSS-in-JS 전처리기", + "reactNative": { + "metro": { + "title": "Metro 플러그인", + "description": "Expo나 React Native CLI의 Metro 설정을 withDevupUI로 감싸면 됩니다. Box, Text, css, styled는 그대로 @devup-ui/react에서 import합니다." + }, + "runtime": { + "description": "정적 스타일에는 런타임이 필요 없습니다. 작은 런타임(gzip 약 1.3 kB)은 테마나 창 크기를 읽는 스타일(테마, 반응형 값 등)에서만 import됩니다. _pressed는 Pressable의 스타일 함수로 컴파일됩니다.", + "title": "최소한의 런타임" + }, + "styleSheet": { + "description": "각 요소는 React Native 컴포넌트가 되고, 스타일 props는 파일마다 하나의 StyleSheet.create 안의 스타일 객체가 됩니다. 런타임에 CSS를 파싱하는 일은 없습니다.", + "title": "빌드 시점의 StyleSheet" + } + }, + "reactNativeDescription": "이제 같은 컴포넌트를 React Native용으로도 컴파일할 수 있습니다. 현재는 실험적 기능입니다.", + "reactNativeDocs": "React Native 문서 보기", + "reactNativeTitle": "React Native", "tagline": "CSS-in-JS의 미래를 만듭니다

가능한 모든 시나리오를 가장 빠르게 분석하고, 최적의 성능으로 스타일을 적용합니다." }, "PropsTable": { diff --git a/e2e/landing-visual-dark.spec.ts b/e2e/landing-visual-dark.spec.ts index aa3a310a1..c995355d6 100644 --- a/e2e/landing-visual-dark.spec.ts +++ b/e2e/landing-visual-dark.spec.ts @@ -96,6 +96,24 @@ test.describe('Landing Page - Dark Mode Visual Regression', () => { await expect(featureSection).toHaveScreenshot('dark-section-features.png') }) + test('React Native section (dark)', async ({ page }) => { + const reactNativeHeading = page.getByRole('heading', { + name: 'React Native', + exact: true, + }) + await reactNativeHeading.scrollIntoViewIfNeeded() + await waitForStyleSettle(page) + + const reactNativeSection = reactNativeHeading + .locator('..') + .locator('..') + .locator('..') + + await expect(reactNativeSection).toHaveScreenshot( + 'dark-section-react-native.png', + ) + }) + test('Bench section (dark)', async ({ page }) => { const benchHeading = page.getByText('Comparison Benchmarks').first() await benchHeading.scrollIntoViewIfNeeded() diff --git a/e2e/landing-visual-dark.spec.ts-snapshots/dark-full-page-desktop-linux.png b/e2e/landing-visual-dark.spec.ts-snapshots/dark-full-page-desktop-linux.png index 556d79d32..fecaa2591 100644 Binary files a/e2e/landing-visual-dark.spec.ts-snapshots/dark-full-page-desktop-linux.png and b/e2e/landing-visual-dark.spec.ts-snapshots/dark-full-page-desktop-linux.png differ diff --git a/e2e/landing-visual-dark.spec.ts-snapshots/dark-full-page-mobile-linux.png b/e2e/landing-visual-dark.spec.ts-snapshots/dark-full-page-mobile-linux.png index 769cae3f2..ed55cde0e 100644 Binary files a/e2e/landing-visual-dark.spec.ts-snapshots/dark-full-page-mobile-linux.png and b/e2e/landing-visual-dark.spec.ts-snapshots/dark-full-page-mobile-linux.png differ diff --git a/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-react-native-linux.png b/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-react-native-linux.png new file mode 100644 index 000000000..858243d62 Binary files /dev/null and b/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-react-native-linux.png differ diff --git a/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-react-native-win32.png b/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-react-native-win32.png new file mode 100644 index 000000000..41bf3141e Binary files /dev/null and b/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-react-native-win32.png differ diff --git a/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-top-banner-linux.png b/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-top-banner-linux.png index 9010ed39e..e5e09e862 100644 Binary files a/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-top-banner-linux.png and b/e2e/landing-visual-dark.spec.ts-snapshots/dark-section-top-banner-linux.png differ diff --git a/e2e/landing-visual.spec.ts b/e2e/landing-visual.spec.ts index a22b3612c..3b8ab14fb 100644 --- a/e2e/landing-visual.spec.ts +++ b/e2e/landing-visual.spec.ts @@ -83,6 +83,24 @@ test.describe('Landing Page - Visual Regression', () => { await expect(featureSection).toHaveScreenshot('section-features.png') }) + test('React Native section', async ({ page }) => { + const reactNativeHeading = page.getByRole('heading', { + name: 'React Native', + exact: true, + }) + await reactNativeHeading.scrollIntoViewIfNeeded() + await waitForStyleSettle(page) + + const reactNativeSection = reactNativeHeading + .locator('..') + .locator('..') + .locator('..') + + await expect(reactNativeSection).toHaveScreenshot( + 'section-react-native.png', + ) + }) + test('Bench section', async ({ page }) => { const benchHeading = page.getByText('Comparison Benchmarks').first() await benchHeading.scrollIntoViewIfNeeded() diff --git a/e2e/landing-visual.spec.ts-snapshots/full-page-desktop-linux.png b/e2e/landing-visual.spec.ts-snapshots/full-page-desktop-linux.png index 709909682..96d8f6113 100644 Binary files a/e2e/landing-visual.spec.ts-snapshots/full-page-desktop-linux.png and b/e2e/landing-visual.spec.ts-snapshots/full-page-desktop-linux.png differ diff --git a/e2e/landing-visual.spec.ts-snapshots/full-page-mobile-linux.png b/e2e/landing-visual.spec.ts-snapshots/full-page-mobile-linux.png index d23321e04..b23bec2cf 100644 Binary files a/e2e/landing-visual.spec.ts-snapshots/full-page-mobile-linux.png and b/e2e/landing-visual.spec.ts-snapshots/full-page-mobile-linux.png differ diff --git a/e2e/landing-visual.spec.ts-snapshots/section-react-native-linux.png b/e2e/landing-visual.spec.ts-snapshots/section-react-native-linux.png new file mode 100644 index 000000000..0016ff6c3 Binary files /dev/null and b/e2e/landing-visual.spec.ts-snapshots/section-react-native-linux.png differ diff --git a/e2e/landing-visual.spec.ts-snapshots/section-react-native-win32.png b/e2e/landing-visual.spec.ts-snapshots/section-react-native-win32.png new file mode 100644 index 000000000..38f56e751 Binary files /dev/null and b/e2e/landing-visual.spec.ts-snapshots/section-react-native-win32.png differ diff --git a/e2e/landing-visual.spec.ts-snapshots/section-top-banner-linux.png b/e2e/landing-visual.spec.ts-snapshots/section-top-banner-linux.png index 437b9834c..469795cf3 100644 Binary files a/e2e/landing-visual.spec.ts-snapshots/section-top-banner-linux.png and b/e2e/landing-visual.spec.ts-snapshots/section-top-banner-linux.png differ diff --git a/libs/extractor/src/native/element.rs b/libs/extractor/src/native/element.rs index c716301a3..d6c12f7e7 100644 --- a/libs/extractor/src/native/element.rs +++ b/libs/extractor/src/native/element.rs @@ -22,14 +22,14 @@ use rustc_hash::{FxHashMap, FxHashSet}; use super::errors::{Problem, RuntimeFeature}; use super::imports::{self, native_component}; -use super::props::{Declaration, Tokens, declarations, dynamic_keys, literal_levels}; +use super::props::{Declaration, Tokens, declarations, dynamic_keys, length_keys, literal_levels}; use super::sheet::Sheet; use super::style::{ - Choice, INTERACTIONS, Reads, State, Vars, cascade, in_theme, interaction_keys, style_code, - varied, when, without, + Choice, INTERACTIONS, READS, Read, Reads, State, Vars, cascade, in_theme, interaction_keys, + style_code, varied, when, without, }; use super::theme::{DEFAULT_BREAKPOINTS, selector_theme}; -use super::values::{Literal, NativeValue, TIMED, number_code}; +use super::values::{Literal, NativeValue, TIMED, Viewport, number_code, viewport_length}; use super::{NativePlatform, NativeTarget, REACT_NATIVE, RUNTIME, Replacement}; use crate::component::ExportVariableKind; use crate::extract_style::constant::is_maintain_value_property; @@ -58,6 +58,11 @@ struct Runtime { breakpoint: String, /// The variable holding whether the window is in landscape landscape: String, + /// The variable holding whether the system reduces motion + motion: String, + /// The variables holding the window's width and height + width: String, + height: String, /// The variable holding whether the element is pressed, in the function /// `Pressable` calls for its style pressed: String, @@ -72,13 +77,15 @@ struct Runtime { styled_theme: String, styled_theme_used: bool, /// The hooks reading each, by what they read - hooks: [String; 3], + hooks: [String; READS], /// 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, + wrapper: Import, + /// The one that also reads the window's size, for such an element taking + /// a viewport length + sized_wrapper: Import, /// What the elements rendered through it read wrapper_reads: Reads, /// The function telling the runtime the theme names @@ -87,9 +94,37 @@ struct Runtime { define_breakpoints: String, } +/// A name the file imports from the runtime under, and whether it uses it +struct Import { + name: String, + used: bool, +} + +impl Import { + fn new(name: &str, code: &str) -> Self { + Self { + name: fresh_name(name, code), + used: false, + } + } + + /// The name, which the file now uses + fn use_name(&mut self) -> String { + self.used = true; + self.name.clone() + } +} + /// 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"]; +/// exported under: they read what each `Read` names +const HOOKS: [&str; READS] = [ + "useThemeIndex", + "useBreakpoint", + "useLandscape", + "useReducedMotion", + "useWindowWidth", + "useWindowHeight", +]; impl Runtime { fn new(code: &str) -> Self { @@ -97,6 +132,9 @@ impl Runtime { index: fresh_name("__t", code), breakpoint: fresh_name("__b", code), landscape: fresh_name("__l", code), + motion: fresh_name("__m", code), + width: fresh_name("__vw", code), + height: fresh_name("__vh", code), pressed: fresh_name("__p", code), hovered: fresh_name("__h", code), focused: fresh_name("__f", code), @@ -106,8 +144,8 @@ impl Runtime { styled_theme_used: false, hooks: HOOKS.map(|hook| fresh_name(&format!("__{hook}"), code)), hooks_used: Reads::default(), - wrapper: fresh_name("__Themed", code), - wrapper_used: false, + wrapper: Import::new("__Themed", code), + sized_wrapper: Import::new("__Sized", code), wrapper_reads: Reads::default(), define: fresh_name("__defineThemes", code), define_breakpoints: fresh_name("__defineBreakpoints", code), @@ -120,6 +158,7 @@ impl Runtime { theme: &self.index, breakpoint: &self.breakpoint, landscape: &self.landscape, + motion: &self.motion, pressed: &self.pressed, hovered: &self.hovered, focused: &self.focused, @@ -129,18 +168,32 @@ impl Runtime { /// The variables of `reads`, in the order of the hooks fn variables(&self, reads: Reads) -> impl Iterator { - [&self.index, &self.breakpoint, &self.landscape] + self.runtime_variables() .into_iter() .enumerate() .filter(move |(at, _)| reads.flags()[*at]) .map(|(at, name)| (at, name.as_str())) } + /// The variables holding what the runtime tells, in the order of the + /// hooks + const fn runtime_variables(&self) -> [&String; READS] { + [ + &self.index, + &self.breakpoint, + &self.landscape, + &self.motion, + &self.width, + &self.height, + ] + } + /// The import of the runtime and the calls telling it the theme names /// and the breakpoints, when the file uses it fn prelude(&self, target: &NativeTarget, theme_api: bool) -> Option { if !(self.hooks_used.any() - || self.wrapper_used + || self.wrapper.used + || self.sized_wrapper.used || self.focused_used || self.styled_theme_used || theme_api) @@ -152,8 +205,10 @@ impl Runtime { .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)); + for (export, import) in [("Themed", &self.wrapper), ("Sized", &self.sized_wrapper)] { + if import.used { + specifiers.push(format!("{export} as {}", import.name)); + } } if self.styled_theme_used { specifiers.push(format!("useStyledTheme as {}", self.styled_theme)); @@ -163,7 +218,7 @@ impl Runtime { } let theme = &target.theme; let mut calls = String::new(); - if reads.theme || theme_api { + if reads.has(Read::Theme) || theme_api { specifiers.push(format!("defineThemes as {}", self.define)); let names = serde_json::Value::from(theme.names.clone()).to_string(); let dark = theme @@ -171,7 +226,7 @@ impl Runtime { .map_or_else(String::new, |dark| format!(", {dark}")); let _ = writeln!(calls, "{}({names}{dark});", self.define); } - if reads.breakpoint && theme.breakpoints != DEFAULT_BREAKPOINTS { + if reads.has(Read::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); @@ -313,8 +368,9 @@ enum Prop { Platform(NativePlatform), /// `_themeDark` and the like: styles for the theme named Theme(String), - /// `_landscape`, `_portrait` and `_pressed`: styles applied while the - /// window is in that orientation or the element is pressed + /// `_landscape`, `_motionReduce`, `_pressed` and the like: styles + /// applied while the window is in that orientation, the system reduces + /// motion or the element is pressed When(State), /// What React Native has no equivalent of Unsupported(Problem), @@ -332,6 +388,8 @@ fn classify(name: &str) -> Prop { "_web" => Prop::Platform(NativePlatform::Web), "_portrait" => Prop::When(State::Landscape(false)), "_landscape" => Prop::When(State::Landscape(true)), + "_motionReduce" => Prop::When(State::ReducedMotion(true)), + "_motionSafe" => Prop::When(State::ReducedMotion(false)), "_pressed" | "_active" => Prop::When(State::Pressed), "_hover" => Prop::When(State::Hovered), "_focus" => Prop::When(State::Focused), @@ -705,6 +763,13 @@ impl<'a> Elements<'_> { } else { Cow::Borrowed(items) }; + if items + .iter() + .any(|(_, literal)| viewport_of(literal).is_some()) + && let Some(keys) = length_keys(name) + { + return self.viewport_choice(name, &keys, &items); + } let theme = &self.target.theme; let themes = match self.theme_scope { Some(index) => index..index + 1, @@ -739,14 +804,73 @@ impl<'a> Elements<'_> { Ok(choice) } + /// The styles of the literals of the style prop `name`, which sets + /// `keys`, where one at least is a viewport length: each from its + /// breakpoint on, a viewport length computed from the window's size + fn viewport_choice( + &self, + name: &str, + keys: &[&str], + items: &[(usize, Literal)], + ) -> Result { + if !self.target.runtime { + return Err(RuntimeFeature::Viewport.problem()); + } + let mut choices = Vec::with_capacity(items.len()); + for (level, literal) in items { + let choice = match viewport_of(literal) { + Some(length) => self.computed(keys, length), + None => self.static_choice(name, &[(0, literal.clone())])?, + }; + choices.push(if *level == 0 { + choice + } else { + when(State::AtLeast(*level), choice) + }); + } + Ok(if choices.len() == 1 { + choices.remove(0) + } else { + Choice::All(choices) + }) + } + + /// The styles `keys` take from a viewport length: the hundredths + /// `amount` of what `viewport` measures, one multiplication of the size + /// the runtime tells + fn computed(&self, keys: &[&str], (amount, viewport): (f64, Viewport)) -> Choice { + let (width, height) = (&self.runtime.width, &self.runtime.height); + let both = Reads::default() + .with(Read::Width, true) + .with(Read::Height, true); + let (side, reads) = match viewport { + Viewport::Width => (width.clone(), Reads::default().with(Read::Width, true)), + Viewport::Height => (height.clone(), Reads::default().with(Read::Height, true)), + Viewport::Min => (format!("Math.min({width}, {height})"), both), + Viewport::Max => (format!("Math.max({width}, {height})"), both), + }; + let factor = number_code(amount / 100.0); + let code = if factor == "1" { + side + } else { + format!("{side} * {factor}") + }; + Choice::Computed( + keys.iter() + .map(|key| ((*key).to_string(), code.clone())) + .collect(), + reads, + ) + } + /// 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 { + } else if reads.has(Read::Breakpoint) { Some(RuntimeFeature::Responsive) - } else if reads.theme { + } else if reads.has(Read::Theme) { Some(RuntimeFeature::Theme) } else { None @@ -1042,10 +1166,12 @@ impl<'a> Elements<'_> { if INTERACTIONS.contains(&state) { self.press.get_or_insert_with(|| (offset, name.to_string())); } else if !self.target.runtime && state != State::Disabled { - self.error( - offset, - RuntimeFeature::Orientation.problem().on(local, name), - ); + let feature = if matches!(state, State::ReducedMotion(_)) { + RuntimeFeature::Motion + } else { + RuntimeFeature::Orientation + }; + self.error(offset, feature.problem().on(local, name)); return Vec::new(); } self.block(value, name, offset, local) @@ -1369,15 +1495,17 @@ impl<'a> Elements<'_> { if !in_component { self.runtime.wrapper_reads = self.runtime.wrapper_reads.union(reads); } - let wrapper = if focus_wrapped { - self.runtime.focused_used = true; - Some(self.runtime.focused_wrapper.clone()) - } else if in_component { - None - } else { - self.runtime.wrapper_used = true; - Some(self.runtime.wrapper.clone()) - }; + if focus_wrapped && !in_component && reads.sized() { + self.error( + element.span.start, + Problem::new( + "an input with a focus style outside a function component cannot read the window's size, which a viewport length needs", + "render the input in a function component", + ) + .on(local, "_focus"), + ); + } + let wrapper = self.wrapper(focus_wrapped, in_component, reads); if let Some(name) = wrapper.as_ref().or(tag.as_ref()) { self.rename(element, name); } @@ -1393,11 +1521,7 @@ impl<'a> Elements<'_> { // up to the last it reads let focus = focus_wrapped.then_some(self.runtime.focused.as_str()); let read = self.runtime.variables(reads).last().map(|(at, _)| at); - let runtime = [ - &self.runtime.index, - &self.runtime.breakpoint, - &self.runtime.landscape, - ]; + let runtime = self.runtime.runtime_variables(); let parameters = focus .into_iter() .chain( @@ -1427,6 +1551,24 @@ impl<'a> Elements<'_> { .push((attributes_end as usize, attributes_end as usize, code)); } + /// The component rendering an element that reads `reads` from the + /// runtime for it: `Focused` for an input with a focus style, none in a + /// function component, else `Themed`, or `Sized` where it reads the + /// window's size + fn wrapper(&mut self, focus_wrapped: bool, in_component: bool, reads: Reads) -> Option { + let runtime = &mut self.runtime; + if focus_wrapped { + runtime.focused_used = true; + Some(runtime.focused_wrapper.clone()) + } else if in_component { + None + } else if reads.sized() { + Some(runtime.sized_wrapper.use_name()) + } else { + Some(runtime.wrapper.use_name()) + } + } + /// 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 @@ -1622,6 +1764,14 @@ fn units_import(package: &str, name: &str) -> String { crate::runtime_units::import_code(package, crate::runtime_units::NATIVE_EXPORT, name, false) } +/// The viewport length `literal` writes, if it writes one +fn viewport_of(literal: &Literal) -> Option<(f64, Viewport)> { + match literal { + Literal::Text(text) => viewport_length(text), + Literal::Number(_) => None, + } +} + /// The span of a child writing text, if it writes any fn text_child(child: &JSXChild<'_>) -> Option { match child { diff --git a/libs/extractor/src/native/element/animation.rs b/libs/extractor/src/native/element/animation.rs index cff658c58..ba160abbc 100644 --- a/libs/extractor/src/native/element/animation.rs +++ b/libs/extractor/src/native/element/animation.rs @@ -244,7 +244,7 @@ impl<'a> Elements<'_> { self.error( property.span.start, Problem::new( - "react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition", + "react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size", "write one value for each style of the keyframe", ) .on(KEYFRAMES, &key), diff --git a/libs/extractor/src/native/element/css_call.rs b/libs/extractor/src/native/element/css_call.rs index 45ecf7bfc..57e5215b6 100644 --- a/libs/extractor/src/native/element/css_call.rs +++ b/libs/extractor/src/native/element/css_call.rs @@ -399,7 +399,7 @@ fn spread_problem() -> String { 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", + "its styles differ by theme, breakpoint, orientation, motion or the window's size, which only a function component or a hook can read", "call `css()` in the component that uses it", ) .call(CSS) diff --git a/libs/extractor/src/native/errors.rs b/libs/extractor/src/native/errors.rs index 3eb7df9fa..477020cc2 100644 --- a/libs/extractor/src/native/errors.rs +++ b/libs/extractor/src/native/errors.rs @@ -53,6 +53,8 @@ pub(super) enum RuntimeFeature { Responsive, Orientation, Theme, + Motion, + Viewport, } impl RuntimeFeature { @@ -61,14 +63,17 @@ impl RuntimeFeature { Self::Responsive => "a responsive value is chosen by the window width", Self::Orientation => "an orientation style is chosen by the orientation of the window", Self::Theme => "a theme variant is chosen by the theme the app shows", + Self::Motion => "a motion style is chosen by whether the system reduces motion", + Self::Viewport => "a viewport length is computed from the window's size", } } const fn fix(self) -> &'static str { match self { Self::Responsive => "give one value, or turn the runtime on", - Self::Orientation => "remove it, or turn the runtime on", + Self::Orientation | Self::Motion => "remove it, or turn the runtime on", Self::Theme => "give the value for one theme, or turn the runtime on", + Self::Viewport => "use a number of pixels or a percentage, or turn the runtime on", } } diff --git a/libs/extractor/src/native/props.rs b/libs/extractor/src/native/props.rs index 8bfe34acf..e1e3b41b8 100644 --- a/libs/extractor/src/native/props.rs +++ b/libs/extractor/src/native/props.rs @@ -570,6 +570,21 @@ pub(super) fn dynamic_keys(prop: &str) -> Result) .collect() } +/// The React Native keys a viewport length of the style prop `prop` sets, +/// when each takes a length +pub(super) fn length_keys(prop: &str) -> Option> { + css::disassemble_property(prop) + .map(|property| match property.as_ref() { + "margin" => Some("margin"), + "padding" => Some("padding"), + property => native_property(property) + .ok() + .filter(|(_, kind)| matches!(kind, Kind::Length | Kind::LineHeight)) + .map(|(key, _)| key), + }) + .collect() +} + /// The scale a number read at runtime for the CSS `property` of `kind` is /// multiplied by, as the web build scales a literal: four pixels a unit for a /// length, but for the properties taking a plain number diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__animation_errors.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__animation_errors.snap index 6f4ced5bf..8c305cf3a 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__animation_errors.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__animation_errors.snap @@ -2,10 +2,10 @@ source: libs/extractor/src/native/tests.rs expression: output --- -error: test.tsx:3:23: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition. Fix: write one value for each style of the keyframe -test.tsx:3:49: `keyframes()` cannot use `to` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition. Fix: write one value for each style of the keyframe -test.tsx:3:74: `keyframes()` cannot use `at` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition. Fix: write one value for each style of the keyframe -test.tsx:4:23: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state or condition. Fix: write one value for each style of the keyframe +error: test.tsx:3:23: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe +test.tsx:3:49: `keyframes()` cannot use `to` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe +test.tsx:3:74: `keyframes()` cannot use `at` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe +test.tsx:4:23: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe test.tsx:4:62: `keyframes()` cannot use `to` on React Native: a keyframe holds style props. Fix: give it an object, such as `{ opacity: 0 }` test.tsx:4:65: `keyframes()` cannot compile here on React Native: the build reads only the keyframes written in the object. Fix: write each keyframe in it test.tsx:5:11: `keyframes()` cannot compile here on React Native: the build reads the keyframes written in the call. Fix: pass one object of keyframes, such as `keyframes({ from: { opacity: 0 }, to: { opacity: 1 } })` 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 index ba1792e28..b42166b23 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__css_errors.snap @@ -2,7 +2,7 @@ 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 +error: test.tsx:3:18: `css()` cannot compile here on React Native: its styles differ by theme, breakpoint, orientation, motion or the window's size, 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 diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__motion_blocks.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__motion_blocks.snap new file mode 100644 index 000000000..234749dbf --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__motion_blocks.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 { useReducedMotion as __useReducedMotion, Themed as __Themed } from "@devup-ui/react/native"; +import __Animated from "react-native-reanimated"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { padding: 4 }, + b: { opacity: 1 }, + c: { opacity: .5 }, + d: { padding: 8 }, + e: { + transitionDuration: "300ms", + transitionProperty: "opacity" + }, + f: { transitionDuration: "0ms" } +}); +export function A() { + const __m = __useReducedMotion(); + return ; +} +export const b = <__Themed $c={Box} $s={(__t, __b, __l, __m) => __m && __s.d} />; +export function C() { + const __m = __useReducedMotion(); + return <__Animated.View style={[__s.e, __m && __s.f]} />; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__motion_runtime_off.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__motion_runtime_off.snap new file mode 100644 index 000000000..5e2cc389f --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__motion_runtime_off.snap @@ -0,0 +1,6 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:2:23: `` cannot use `_motionReduce` on React Native: a motion style is chosen by whether the system reduces motion, which needs the React Native runtime that `runtime: false` turns off. Fix: remove it, or turn the runtime on +test.tsx:2:48: `` cannot use `_motionSafe` on React Native: a motion style is chosen by whether the system reduces motion, 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__theme_viewport_token.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_viewport_token.snap new file mode 100644 index 000000000..4a00f3f14 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__theme_viewport_token.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 `w` on React Native: `50vw` is a viewport length, which the build computes only where a style prop writes it. Fix: write the viewport length in the style prop, or use a number of pixels or a percentage diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__unsupported_values.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__unsupported_values.snap index 9e2cb108a..fc0afc561 100644 --- a/libs/extractor/src/native/snapshots/extractor__native__tests__unsupported_values.snap +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__unsupported_values.snap @@ -4,7 +4,6 @@ expression: compile(code) --- error: test.tsx:2:6: `` cannot use `display` on React Native: React Native does not read `grid` here. Fix: use one of `none`, `flex` or `contents` test.tsx:2:21: `` cannot use `position` on React Native: React Native does not read `fixed` here. Fix: use one of `absolute`, `relative` or `static` -test.tsx:2:38: `` cannot use `w` on React Native: `10vw` needs the window size, which React Native knows only at runtime. Fix: use a number of pixels or a percentage test.tsx:2:47: `` cannot use `h` on React Native: React Native cannot compute `calc(100% - 4px)`. Fix: write the value itself test.tsx:2:68: `` cannot use `maxW` on React Native: React Native cannot compute `var(--w)`. Fix: write the value itself test.tsx:3:3: `` cannot use `minW` on React Native: React Native styles have no `!important`. Fix: remove `!important`; a later style already wins diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_css_and_styled.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_css_and_styled.snap new file mode 100644 index 000000000..07249b7ec --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_css_and_styled.snap @@ -0,0 +1,16 @@ +--- +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 { useWindowWidth as __useWindowWidth, useWindowHeight as __useWindowHeight } from "@devup-ui/react/native"; +import { View as __View } from "react-native"; +export const Tall = (__props) => { + const __vh = __useWindowHeight(); + return <__View {...__props} style={[{ height: __vh * .5 }, __props.style]} />; +}; +export function A() { + const __vw = __useWindowWidth(); + const wide = { width: __vw * .5 }; + return ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_focused_input.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_focused_input.snap new file mode 100644 index 000000000..05f796a1b --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_focused_input.snap @@ -0,0 +1,5 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:2:18: `` cannot use `_focus` on React Native: an input with a focus style outside a function component cannot read the window's size, which a viewport length needs. Fix: render the input in a function component diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_keyframes.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_keyframes.snap new file mode 100644 index 000000000..c90153508 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_keyframes.snap @@ -0,0 +1,6 @@ +--- +source: libs/extractor/src/native/tests.rs +expression: "compile_themed(two_themes(), runtime, code)" +--- +error: test.tsx:3:26: `keyframes()` cannot use `from` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe +test.tsx:3:46: `keyframes()` cannot use `to` on React Native: react-native-reanimated reads each keyframe once, so its styles cannot differ by theme, breakpoint, orientation, state, condition or the window's size. Fix: write one value for each style of the keyframe diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_lengths.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_lengths.snap new file mode 100644 index 000000000..915670c4c --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_lengths.snap @@ -0,0 +1,23 @@ +--- +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 { useWindowWidth as __useWindowWidth, useWindowHeight as __useWindowHeight } from "@devup-ui/react/native"; +export function A() { + const __vw = __useWindowWidth(); + const __vh = __useWindowHeight(); + return ; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_outside_component.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_outside_component.snap new file mode 100644 index 000000000..d0b3b7656 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_outside_component.snap @@ -0,0 +1,14 @@ +--- +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 { Themed as __Themed, Sized as __Sized, 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" } +}); +export const a = <__Sized $c={Box} $s={(__t, __b, __l, __m, __vw) => [{ width: __vw * .5 }, [__s.a, __s.b][__t]]} />; +export const b = <__Themed $c={Box} $s={(__t) => [__s.a, __s.b][__t]} />; diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_responsive.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_responsive.snap new file mode 100644 index 000000000..b114da2dc --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_responsive.snap @@ -0,0 +1,25 @@ +--- +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 { useBreakpoint as __useBreakpoint, useWindowWidth as __useWindowWidth, useWindowHeight as __useWindowHeight } from "@devup-ui/react/native"; +import { StyleSheet } from "react-native"; +const __s = StyleSheet.create({ + a: { + height: 32, + backgroundColor: "10vw" + }, + b: { width: 16 } +}); +export function A() { + const __b = __useBreakpoint(); + const __vw = __useWindowWidth(); + const __vh = __useWindowHeight(); + return = 2 && __s.b, + __b >= 1 && { height: __vh * .5 } + ]} />; +} diff --git a/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_runtime_off.snap b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_runtime_off.snap new file mode 100644 index 000000000..b9846a512 --- /dev/null +++ b/libs/extractor/src/native/snapshots/extractor__native__tests__viewport_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:15: `` cannot use `w` on React Native: a viewport length is computed from the window's size, which needs the React Native runtime that `runtime: false` turns off. Fix: use a number of pixels or a percentage, or turn the runtime on diff --git a/libs/extractor/src/native/style.rs b/libs/extractor/src/native/style.rs index 78c37db50..13fc8d6c6 100644 --- a/libs/extractor/src/native/style.rs +++ b/libs/extractor/src/native/style.rs @@ -18,6 +18,8 @@ pub(super) enum State { AtLeast(usize), /// The window is in landscape (`true`) or portrait (`false`) orientation Landscape(bool), + /// The system reduces motion (`true`) or does not (`false`) + ReducedMotion(bool), /// The element is pressed Pressed, /// The pointer is over the element @@ -53,34 +55,68 @@ pub(super) enum Choice { All(Vec), /// A style passed on whole, by its code, which may declare any style Given(String), + /// Styles whose values the element computes from what the runtime + /// tells, as a viewport length from the window's size: each key with the + /// code of its value + Computed(Vec<(String, String)>, Reads), } -/// What the runtime tells a style: which theme shows, which breakpoint the -/// window is at, and whether it is in landscape +/// What the runtime tells, by the hook telling it, in the order the hooks +/// are called and a wrapper gives them to a style +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Read { + /// Which theme shows + Theme, + /// Which breakpoint the window is at + Breakpoint, + /// Whether the window is in landscape + Landscape, + /// Whether the system reduces motion + Motion, + /// The window's width + Width, + /// The window's height + Height, +} + +/// How many things the runtime tells +pub(super) const READS: usize = 6; + +/// What a style reads from the runtime #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub(super) struct Reads { - pub theme: bool, - pub breakpoint: bool, - pub landscape: bool, -} +pub(super) struct Reads([bool; READS]); impl Reads { + /// Reading `read` too when `on` + pub(super) const fn with(mut self, read: Read, on: bool) -> Self { + if on { + self.0[read as usize] = true; + } + self + } + + /// Whether it reads `read` + pub(super) const fn has(self, read: Read) -> bool { + self.0[read as usize] + } + /// Whether it reads what a hook of the runtime gives - pub(super) const fn any(self) -> bool { - self.theme || self.breakpoint || self.landscape + pub(super) fn any(self) -> bool { + self.0.contains(&true) + } + + /// Whether it reads the window's size + pub(super) const fn sized(self) -> bool { + self.has(Read::Width) || self.has(Read::Height) } /// 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 flags(self) -> [bool; READS] { + self.0 } - 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, - } + pub(super) fn union(self, other: Self) -> Self { + Self(std::array::from_fn(|at| self.0[at] || other.0[at])) } } @@ -89,6 +125,7 @@ pub(super) struct Vars<'v> { pub theme: &'v str, pub breakpoint: &'v str, pub landscape: &'v str, + pub motion: &'v str, pub pressed: &'v str, pub hovered: &'v str, pub focused: &'v str, @@ -187,7 +224,9 @@ impl Choice { match self { Self::Empty => false, Self::Static(declarations) => declares(declarations, key), - Self::Dynamic(values) => values.iter().any(|(name, _)| name == key), + Self::Dynamic(values) | Self::Computed(values, _) => { + values.iter().any(|(name, _)| name == key) + } Self::Given(_) => true, Self::Condition { consequent, @@ -207,16 +246,15 @@ impl Choice { pub(super) fn reads(&self) -> Reads { match self { Self::Empty | Self::Static(_) | Self::Dynamic(_) | Self::Given(_) => Reads::default(), + Self::Computed(_, reads) => *reads, Self::Condition { consequent, alternate, .. } => consequent.reads().union(alternate.reads()), - Self::Varied(grid) => Reads { - theme: themes_of(grid) > 1, - breakpoint: grid.len() > 1, - landscape: false, - }, + Self::Varied(grid) => Reads::default() + .with(Read::Theme, themes_of(grid) > 1) + .with(Read::Breakpoint, grid.len() > 1), Self::When { state, choice } => choice.reads().union(state.reads()), Self::All(choices) => choices.iter().fold(Reads::default(), |reads, choice| { reads.union(choice.reads()) @@ -247,7 +285,7 @@ impl Choice { match self { Self::Empty => "null".to_string(), Self::Static(declarations) => sheet.reference(declarations), - Self::Dynamic(values) => object_code(values), + Self::Dynamic(values) | Self::Computed(values, _) => object_code(values), Self::Given(code) => code.clone(), Self::Condition { test, @@ -312,11 +350,16 @@ impl Choice { impl State { const fn reads(self) -> Reads { - Reads { - theme: matches!(self, Self::Theme(_)), - breakpoint: matches!(self, Self::AtLeast(_)), - landscape: matches!(self, Self::Landscape(_)), - } + let read = match self { + Self::Theme(_) => Read::Theme, + Self::AtLeast(_) => Read::Breakpoint, + Self::Landscape(_) => Read::Landscape, + Self::ReducedMotion(_) => Read::Motion, + Self::Pressed | Self::Hovered | Self::Focused | Self::Disabled => { + return Reads([false; READS]); + } + }; + Reads([false; READS]).with(read, true) } /// The code testing that the state holds @@ -326,6 +369,8 @@ impl State { Self::AtLeast(level) => format!("{} >= {level}", vars.breakpoint), Self::Landscape(true) => vars.landscape.to_string(), Self::Landscape(false) => format!("!{}", vars.landscape), + Self::ReducedMotion(true) => vars.motion.to_string(), + Self::ReducedMotion(false) => format!("!{}", vars.motion), Self::Pressed => vars.pressed.to_string(), Self::Hovered => vars.hovered.to_string(), Self::Focused => vars.focused.to_string(), diff --git a/libs/extractor/src/native/tests.rs b/libs/extractor/src/native/tests.rs index 9aa42ae59..491b9a861 100644 --- a/libs/extractor/src/native/tests.rs +++ b/libs/extractor/src/native/tests.rs @@ -4,7 +4,7 @@ use rstest::rstest; use super::errors::Problem; use super::props::Declaration; use super::sheet::{Sheet, key_name}; -use super::style::{Choice, State, Vars, cascade, in_theme, style_code, varied, when}; +use super::style::{Choice, Read, 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}; @@ -13,6 +13,7 @@ const VARS: Vars<'static> = Vars { theme: "t", breakpoint: "b", landscape: "l", + motion: "m", pressed: "p", hovered: "h", focused: "f", @@ -648,6 +649,7 @@ fn two_themes() -> NativeTheme { ("onlyDark", &[None, Some("#000")]), ("captionSize", &[Some("12px"), Some("14px")]), ("primary-100", &[Some("#eef"), Some("#223")]), + ("wide", &[Some("50vw"), Some("50vw")]), ], ) } @@ -842,6 +844,7 @@ fn runtime_off_keeps_single_values(#[case] name: &str, #[case] theme: NativeThem )] #[case::unknown_theme("theme_unknown_theme", "")] #[case::token_loop("theme_token_loop", "")] +#[case::viewport_token("theme_viewport_token", "")] #[case::bad_values( "theme_bad_values", "" @@ -1110,7 +1113,7 @@ fn varied_choices_pick_by_breakpoint_and_theme() { vec![c.clone(), c.clone()], ])); assert_eq!(both, "b < 1 ? [s.a, s.b][t] : s.c"); - assert!(reads.theme && reads.breakpoint && !reads.landscape); + assert!(reads.has(Read::Theme) && reads.has(Read::Breakpoint) && !reads.has(Read::Landscape)); // In a condition, and applied while a state holds let (condition, reads) = code(Choice::Condition { test: "on".to_string(), @@ -1118,7 +1121,7 @@ fn varied_choices_pick_by_breakpoint_and_theme() { 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); + assert!(!reads.has(Read::Theme) && reads.has(Read::Breakpoint) && reads.has(Read::Landscape)); let (nested, _) = code(Choice::Condition { test: "on".to_string(), consequent: Box::new(Choice::Varied(vec![ @@ -1187,6 +1190,78 @@ fn compiles_pressed(#[case] name: &str, #[case] runtime: bool, #[case] code: &st assert_snapshot!(name, compile_themed(two_themes(), runtime, code)); } +#[rstest] +#[case::lengths( + "viewport_lengths", + true, + "export function A() { + return +}" +)] +#[case::responsive( + "viewport_responsive", + true, + "export function A() { + return +}" +)] +#[case::outside_component( + "viewport_outside_component", + true, + "export const a = +export const b = " +)] +#[case::css_and_styled( + "viewport_css_and_styled", + true, + "import { css, styled } from '@devup-ui/react' +export const Tall = styled.View({ h: '50vh' }) +export function A() { + const wide = css({ w: '50vw' }) + return +}" +)] +#[case::focused_input( + "viewport_focused_input", + true, + "export const a = +export function B() { + return +}" +)] +#[case::keyframes( + "viewport_keyframes", + true, + "import { keyframes } from '@devup-ui/react' +const grow = keyframes({ from: { w: '0vw' }, to: { w: '100vw' } })" +)] +#[case::runtime_off( + "viewport_runtime_off", + false, + "export function A() { + return +}" +)] +#[case::motion( + "motion_blocks", + true, + "export function A() { + return +} +export const b = +export function C() { + return +}" +)] +#[case::motion_runtime_off( + "motion_runtime_off", + false, + "export const a = " +)] +fn compiles_viewport_and_motion(#[case] name: &str, #[case] runtime: bool, #[case] code: &str) { + assert_snapshot!(name, compile_themed(two_themes(), runtime, code)); +} + const CSS_ELEMENTS: &str = r"import { css as style, type DevupProps } from '@devup-ui/react' const card = style({ p: 4, borderRadius: '8px' }) export function Card({ on, extra, children }) { diff --git a/libs/extractor/src/native/values.rs b/libs/extractor/src/native/values.rs index 94441044e..76f4a2aa7 100644 --- a/libs/extractor/src/native/values.rs +++ b/libs/extractor/src/native/values.rs @@ -100,14 +100,66 @@ pub(super) fn scaled_length(text: &str) -> Option { }) } +/// What a viewport length measures a hundredth of +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum Viewport { + Width, + Height, + /// The smaller of the width and the height + Min, + /// The larger of the width and the height + Max, +} + +/// The viewport units, by what they measure. A window has no browser +/// interface that comes and goes, so the small, large and dynamic units +/// measure the window as the plain ones do; the inline and block axes are +/// the width and the height +const VIEWPORT_UNITS: [(&str, Viewport); 24] = [ + ("vw", Viewport::Width), + ("svw", Viewport::Width), + ("lvw", Viewport::Width), + ("dvw", Viewport::Width), + ("vi", Viewport::Width), + ("vh", Viewport::Height), + ("svh", Viewport::Height), + ("lvh", Viewport::Height), + ("dvh", Viewport::Height), + ("vb", Viewport::Height), + ("vmin", Viewport::Min), + ("svmin", Viewport::Min), + ("lvmin", Viewport::Min), + ("dvmin", Viewport::Min), + ("vmax", Viewport::Max), + ("svmax", Viewport::Max), + ("lvmax", Viewport::Max), + ("dvmax", Viewport::Max), + ("svi", Viewport::Width), + ("lvi", Viewport::Width), + ("dvi", Viewport::Width), + ("svb", Viewport::Height), + ("lvb", Viewport::Height), + ("dvb", Viewport::Height), +]; + +/// The number of hundredths `text` measures and of what, for a viewport +/// length such as `50vw` +pub(super) fn viewport_length(text: &str) -> Option<(f64, Viewport)> { + let text = text.trim(); + VIEWPORT_UNITS.iter().find_map(|(unit, viewport)| { + text.strip_suffix(unit) + .and_then(number) + .map(|amount| (amount, *viewport)) + }) +} + fn unsupported_length(text: &str) -> Problem { - if ["vw", "vh", "vmin", "vmax", "dvh", "svh", "lvh"] - .iter() - .any(|unit| text.ends_with(unit)) - { + if viewport_length(text).is_some() { return Problem::new( - format!("`{text}` needs the window size, which React Native knows only at runtime"), - "use a number of pixels or a percentage", + format!( + "`{text}` is a viewport length, which the build computes only where a style prop writes it" + ), + "write the viewport length in the style prop, or use a number of pixels or a percentage", ); } Problem::new( diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md index fda3842db..8d6afaeac 100644 --- a/packages/metro-plugin/README.md +++ b/packages/metro-plugin/README.md @@ -160,6 +160,40 @@ is in that orientation. A value read at runtime in an array (`p={[x, 2]}`) applies from its breakpoint on as it is. +## Viewport lengths + +`vw`, `vh`, `vmin` and `vmax` measure the window, as on the web. Its small, +large and dynamic forms (`svh`, `dvh`, ...) measure the same, since an app's +window has no browser bar that comes and goes. The build turns each length +into one multiplication of the window's size, which the runtime gives: + +```tsx + +// const __vw = __useWindowWidth(); const __vh = __useWindowHeight(); +// +``` + +A component renders again when the window's size changes only if it uses a +viewport length. Components that read only the breakpoint or the theme +render again only when those change. A viewport length works in responsive +arrays, `css()` and `styled()`. With `runtime: false`, it is a build error. +In a theme token, it is a build error too: write it in the style prop. + +## Reduced motion + +`_motionReduce` applies its styles while the system asks apps to reduce +motion (React Native's `AccessibilityInfo`), and `_motionSafe` applies its +styles while it does not. The runtime asks the system once and follows its +changes: + +```tsx + +``` + ## Press styles `_active` (or its React Native name, `_pressed`) applies its styles while the @@ -347,16 +381,17 @@ Rsbuild or Bun plugin, which output atomic CSS instead. Only styles the build can decide are supported: literals, values read at runtime, theme tokens, responsive values, conditions between them and the -platform, theme, orientation and interaction blocks, `css()`, `styled()` -and animations. These are build errors, reported by Metro at the file, line and column: +platform, theme, orientation, motion and interaction blocks, viewport +lengths, `css()`, `styled()` and animations. These are build errors, reported by Metro at the file, line and column: - selectors other than the states above (`_focusVisible`, `_checked`, `_before`, ...) - `globalCss()` and `Grid` - animations and transitions in an app without react-native-reanimated - 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` + `_theme*` with more than one theme, `_portrait`, `_landscape`, + `_motionReduce`, `_motionSafe`, viewport lengths, 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 326169105..9edc0ccf1 100644 --- a/packages/react/src/native/__tests__/index.browser.test.tsx +++ b/packages/react/src/native/__tests__/index.browser.test.tsx @@ -17,7 +17,20 @@ const dimensions = { listeners: [] as (() => void)[], } +/** Whether the system reduces motion, and who listens to it */ +const accessibility = { + listeners: [] as ((reduced: boolean) => void)[], +} + mock.module('react-native', () => ({ + AccessibilityInfo: { + isReduceMotionEnabled: () => Promise.resolve(false), + addEventListener: (event: string, listener: (reduced: boolean) => void) => { + if (event === 'reduceMotionChanged') + accessibility.listeners.push(listener) + return { remove: () => {} } + }, + }, Dimensions: { get: () => ({ width: dimensions.width, height: dimensions.height }), addEventListener: (event: string, listener: () => void) => { @@ -51,6 +64,13 @@ function resize(width: number, height: number) { }) } +/** The system starting or stopping to reduce motion */ +function reduceMotion(reduced: boolean) { + act(() => { + for (const listener of accessibility.listeners) listener(reduced) + }) +} + const runtime = await import('../index') const { defineBreakpoints, @@ -58,11 +78,15 @@ const { getBreakpoint, getTheme, setTheme, + Sized, Themed, useBreakpoint, useLandscape, + useReducedMotion, useTheme, useThemeIndex, + useWindowHeight, + useWindowWidth, } = runtime beforeEach(() => { @@ -223,6 +247,66 @@ describe('useLandscape', () => { }) }) +describe('useReducedMotion', () => { + it('follows whether the system reduces motion', async () => { + const { result } = renderHook(() => useReducedMotion()) + await act(async () => {}) + expect(result.current).toBe(false) + reduceMotion(true) + expect(result.current).toBe(true) + reduceMotion(false) + expect(result.current).toBe(false) + expect(accessibility.listeners).toHaveLength(1) + }) +}) + +describe('useWindowWidth and useWindowHeight', () => { + it('render again with the size of the window', () => { + const { result } = renderHook(() => [useWindowWidth(), useWindowHeight()]) + expect(result.current).toEqual([390, 844]) + resize(400, 800) + expect(result.current).toEqual([400, 800]) + }) + + it('leave the components reading only the breakpoint alone', () => { + let breakpointRenders = 0 + let widthRenders = 0 + renderHook(() => { + breakpointRenders++ + return useBreakpoint() + }) + renderHook(() => { + widthRenders++ + return useWindowWidth() + }) + resize(400, 844) + resize(410, 844) + expect(breakpointRenders).toBe(1) + expect(widthRenders).toBe(3) + }) +}) + +describe('Sized', () => { + it('renders the style of what the runtime tells and of the window size', () => { + const Probe = ({ style }: { style?: string }) => + createElement('span', { 'data-style': style }) + const { container } = render( + createElement(Sized, { + $c: Probe, + $s: (...reads: unknown[]) => reads.join('-'), + }), + ) + const style = () => + container.querySelector('span')?.getAttribute('data-style') + expect(style()).toBe('0-0-false-false-390-844') + resize(844, 390) + expect(style()).toBe('0-2-true-false-844-390') + reduceMotion(true) + expect(style()).toBe('0-2-true-true-844-390') + reduceMotion(false) + }) +}) + describe('Themed with breakpoints', () => { it('renders the style of the breakpoint and orientation of the window', () => { const Probe = ({ style }: { style?: string }) => diff --git a/packages/react/src/native/index.ts b/packages/react/src/native/index.ts index 15f14c045..325b54b77 100644 --- a/packages/react/src/native/index.ts +++ b/packages/react/src/native/index.ts @@ -8,7 +8,7 @@ import { useState, useSyncExternalStore, } from 'react' -import { Appearance, Dimensions } from 'react-native' +import { AccessibilityInfo, Appearance, Dimensions } from 'react-native' import type { StyledTheme } from '../types/props' import type { DevupTheme } from '../types/theme' @@ -18,8 +18,9 @@ import { StyledThemeContext } from '../utils/theme-context' * The React Native runtime of Devup UI. The build compiles every style to * `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. + * window is at, whether it is in landscape, whether the system reduces + * motion and, for viewport lengths, the window's size. It reads no CSS and + * resolves no token. Web builds never import it. */ type ThemeName = keyof DevupTheme extends undefined ? string : keyof DevupTheme @@ -32,35 +33,33 @@ let dark = -1 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 +/** Whether the system asks apps to reduce motion */ +let reduced = false let following = false const listeners = new Set<() => void>() +/** + * Tells every listener that something changed. Each hook reads only its own + * value, and React renders a component again only when the value its hook + * reads changes, so a resize that crosses no breakpoint renders again only + * the components reading the window's size. + */ 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 setReduced(value: boolean): void { + reduced = value + notify() } function subscribe(listener: () => void): () => void { if (!following) { following = true - layout = readLayout() Appearance.addChangeListener(notify) - Dimensions.addEventListener('change', resize) + Dimensions.addEventListener('change', notify) + AccessibilityInfo.addEventListener('reduceMotionChanged', setReduced) + void AccessibilityInfo.isReduceMotionEnabled().then(setReduced) } listeners.add(listener) return () => { @@ -160,32 +159,111 @@ export function useLandscape(): boolean { return useSyncExternalStore(subscribe, getLandscape, getLandscape) } +/** Whether the system asks apps to reduce motion */ +function getReducedMotion(): boolean { + return reduced +} + +/** + * Whether the system asks apps to reduce motion, which `_motionReduce` and + * `_motionSafe` apply by, rendering again when the setting changes + * @internal + */ +export function useReducedMotion(): boolean { + return useSyncExternalStore(subscribe, getReducedMotion, getReducedMotion) +} + +function getWindowWidth(): number { + return Dimensions.get('window').width +} + +function getWindowHeight(): number { + return Dimensions.get('window').height +} + +/** + * The window's width, which a `vw` length is a hundredth of, rendering again + * when it changes + * @internal + */ +export function useWindowWidth(): number { + return useSyncExternalStore(subscribe, getWindowWidth, getWindowWidth) +} + +/** + * The window's height, which a `vh` length is a hundredth of, rendering + * again when it changes + * @internal + */ +export function useWindowHeight(): number { + return useSyncExternalStore(subscribe, getWindowHeight, getWindowHeight) +} + +/** What `Themed` gives the style: what the runtime tells, in this order */ +type Reads = ( + theme: number, + breakpoint: number, + landscape: boolean, + reducedMotion: boolean, +) => unknown + /** * 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. + * breakpoint the window is at, whether it is in landscape and whether the + * system reduces motion. The build renders an element through it where no + * function component can read them for it. * @internal */ export function Themed({ $c, $s, ...props +}: { $c: ElementType; $s: Reads } & Record): ReactElement { + return createElement($c, { + ...props, + style: $s( + useThemeIndex(), + useBreakpoint(), + useLandscape(), + useReducedMotion(), + ), + }) +} + +/** + * `Themed` for an element that also takes a viewport length: its style also + * takes the window's width and height. Only such elements render through it, + * so a resize renders again only them. + * @internal + */ +export function Sized({ + $c, + $s, + ...props }: { $c: ElementType - $s: (theme: number, breakpoint: number, landscape: boolean) => unknown + $s: ( + ...reads: [...Parameters, width: number, height: number] + ) => unknown } & Record): ReactElement { return createElement($c, { ...props, - style: $s(useThemeIndex(), useBreakpoint(), useLandscape()), + style: $s( + useThemeIndex(), + useBreakpoint(), + useLandscape(), + useReducedMotion(), + useWindowWidth(), + useWindowHeight(), + ), }) } /** * Renders `$c`, a `TextInput`, with the style `$s` gives for whether it has * focus, which a `TextInput` tells only through its events, and for the - * theme, the breakpoint and the orientation, as `Themed` does. The build - * renders an input taking a focus style with it. + * theme, the breakpoint, the orientation and reduced motion, as `Themed` + * does. The build renders an input taking a focus style with it. * @internal */ export function Focused({ @@ -196,12 +274,7 @@ export function Focused({ ...props }: { $c: ElementType - $s: ( - focused: boolean, - theme: number, - breakpoint: number, - landscape: boolean, - ) => unknown + $s: (focused: boolean, ...reads: Parameters) => unknown onFocus?: (event: unknown) => void onBlur?: (event: unknown) => void } & Record): ReactElement { @@ -216,7 +289,13 @@ export function Focused({ setFocused(false) onBlur?.(event) }, - style: $s(focused, useThemeIndex(), useBreakpoint(), useLandscape()), + style: $s( + focused, + useThemeIndex(), + useBreakpoint(), + useLandscape(), + useReducedMotion(), + ), }) } diff --git a/verify-dist.ts b/verify-dist.ts index d2a4f414a..5c0baff9e 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: {}, Dimensions: {} }, + exports: { AccessibilityInfo: {}, Appearance: {}, Dimensions: {} }, loader: 'object', })) },