diff --git a/.changepacks/changepack_log_metro_types.json b/.changepacks/changepack_log_metro_types.json new file mode 100644 index 000000000..f255a5bc0 --- /dev/null +++ b/.changepacks/changepack_log_metro_types.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/metro-plugin/package.json": "Patch" + }, + "note": "Write `df/theme.d.ts` (the tokens of devup.json) and `df/native.d.ts` (React Native props for each component) when Metro reads the config, with a `distDir` option, as the web plugins do.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/.changepacks/changepack_log_react_native_types.json b/.changepacks/changepack_log_react_native_types.json new file mode 100644 index 000000000..ac8e96aa9 --- /dev/null +++ b/.changepacks/changepack_log_react_native_types.json @@ -0,0 +1,7 @@ +{ + "changes": { + "packages/react/package.json": "Patch" + }, + "note": "Add `@devup-ui/react/native/types`, which types each component as the React Native component it renders (`Box` takes `ViewProps`, `Button` takes `PressableProps`, ...) through the new `DevupElementProps` augmentation point. Web types are unchanged.", + "date": "2026-11-21T00:00:00.000Z" +} diff --git a/apps/expo/package.json b/apps/expo/package.json index 04463f3bc..0f4dea58c 100644 --- a/apps/expo/package.json +++ b/apps/expo/package.json @@ -7,7 +7,8 @@ "start": "expo start", "export": "expo export --platform ios --platform android --platform web --no-bytecode --source-maps", "check": "node check-bundle.mjs", - "check:web": "node check-web.mjs" + "check:web": "node check-web.mjs", + "typecheck": "bun ../../node_modules/@typescript/native/bin/tsc --noEmit" }, "dependencies": { "@devup-ui/react": "workspace:^", diff --git a/apps/landing/src/app/(detail)/docs/LeftMenu.tsx b/apps/landing/src/app/(detail)/docs/LeftMenu.tsx index db5adc836..402cd2450 100644 --- a/apps/landing/src/app/(detail)/docs/LeftMenu.tsx +++ b/apps/landing/src/app/(detail)/docs/LeftMenu.tsx @@ -44,6 +44,7 @@ export function LeftMenu() { {t('features')} {t('limitations')} {t('buildErrors')} + React Native **Experimental (0.x).** React Native support is in progress +> ([#411](https://github.com/dev-five-git/devup-ui/issues/411)) and +> `@devup-ui/metro-plugin` is not published yet. Its API may change. + +Devup UI compiles for React Native in Metro, the bundler of React Native and +Expo. You keep importing `Box`, `Text`, `css`, `styled`, ... from +`@devup-ui/react`. At build time each element becomes a React Native component, +and its style props become style objects hoisted into one `StyleSheet.create` +per file. CSS is never parsed at runtime. + +## Setup + +```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 writes `df/theme.d.ts` and `df/native.d.ts` when it reads the config. +With them, theme tokens complete in your editor, and each component takes the +props of the React Native component it renders (`onPress`, `onChangeText`, +`testID`, ...). + +## Elements + +| Element | React Native | +| --------------------------------- | -------------------------------- | +| `Box`, `Flex`, `VStack`, `Center` | `View` | +| `Text` | `Text` | +| `Image` | `Image` (`src` becomes `source`) | +| `Input` | `TextInput` | +| `Button` | `Pressable` | + +## Differences from the web + +The same component code builds for both, but React Native has no CSS, so some +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. | +| 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. | +| 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 | +| `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 | +| styled-components and Emotion | `styled-components`, `@emotion/styled`, ... | `styled-components/native` and `@emotion/native` compile the same way. Their numbers are pixels, as those packages read them. | +| Unsupported properties | — | A property React Native has no style for (`gridTemplateColumns`, `float`, ...) is a build error | + +Build errors point at the file, line and column of the style, as on the web. + +## Expo web + +On the web, Expo bundles the app with Metro through +[react-native-web](https://necolas.github.io/react-native-web/), and the same +native output turns into CSS there. A site that is not an Expo app keeps using +the [Vite, Next.js, Webpack, Rsbuild or Bun plugin](/docs/installation), which +output atomic CSS instead. + +See the +[`@devup-ui/metro-plugin` README](https://github.com/dev-five-git/devup-ui/tree/main/packages/metro-plugin) +for every option and each feature in detail. diff --git a/e2e/exported-routes.ts b/e2e/exported-routes.ts index 855e4015a..e336225ab 100644 --- a/e2e/exported-routes.ts +++ b/e2e/exported-routes.ts @@ -89,6 +89,7 @@ const ENGLISH_EXPORTED_ROUTES = [ '/docs/migration/vanilla-extract', '/docs/overview', '/docs/quick-start', + '/docs/react-native', '/showcase', '/team', ] as const diff --git a/packages/metro-plugin/README.md b/packages/metro-plugin/README.md index 8a42d85f3..fda3842db 100644 --- a/packages/metro-plugin/README.md +++ b/packages/metro-plugin/README.md @@ -67,6 +67,8 @@ withDevupUI(config, { package: '@devup-ui/react', // devup.json, from the project root. Default: 'devup.json' devupFile: 'devup.json', + // Where the theme and React Native types are written. Default: 'df' + distDir: 'df', // Packages in node_modules that ship uncompiled Devup UI. Default: [] include: [], // Whether styles that need the React Native runtime may import it. @@ -80,6 +82,24 @@ withDevupUI(config, { }) ``` +## TypeScript + +When Metro reads the config, the plugin writes two declaration files into +`df` (the `distDir` option), which ignores itself in git: + +- `theme.d.ts`: the tokens of devup.json, as the web plugins write them, so + `bg="$primary"` and `typography="title"` complete and check. +- `native.d.ts`: it imports `@devup-ui/react/native/types`, so each + component takes the props of the React Native component it renders: + `Box`, `Flex`, `VStack`, `Center` and `Grid` take `View`'s (`onLayout`, + `testID`, ...), `Text` takes `Text`'s, `Image` takes `Image`'s, `Input` takes + `TextInput`'s (`onChangeText`, ...) and `Button` takes `Pressable`'s + (`onPress`, ...). Each also takes `className`, for `css()`. HTML props that + React Native lacks, such as `href` or `onInput`, become type errors. + +A tsconfig that names its files (`include`) must list `df/*.d.ts`. Expo's +default tsconfig includes every file of the project. + ## Themes `$` tokens of devup.json (colors, `length` and `shadow`) and `typography` diff --git a/packages/metro-plugin/src/__tests__/plugin.test.ts b/packages/metro-plugin/src/__tests__/plugin.test.ts index 55ecaa4e4..f8fbee424 100644 --- a/packages/metro-plugin/src/__tests__/plugin.test.ts +++ b/packages/metro-plugin/src/__tests__/plugin.test.ts @@ -1,8 +1,24 @@ -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' -import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test' +import * as pluginUtils from '@devup-ui/plugin-utils' +import { + afterEach, + beforeEach, + describe, + expect, + it, + type Mock, + spyOn, +} from 'bun:test' import { REANIMATED_PACKAGE, @@ -11,17 +27,22 @@ import { withDevupUI, } from '../plugin' import { readSettings, SETTINGS_ENV } from '../settings' +import { NATIVE_TYPES } from '../types' +const wasm = pluginUtils.loadCompiler('wasm') let root: string let previous: string | undefined +let selection: Mock beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'devup-metro-plugin-')) previous = process.env[SETTINGS_ENV] delete process.env[SETTINGS_ENV] + selection = spyOn(pluginUtils, 'loadCompiler').mockReturnValue(wasm) }) afterEach(() => { + selection.mockRestore() rmSync(root, { recursive: true, force: true }) if (previous === undefined) delete process.env[SETTINGS_ENV] else process.env[SETTINGS_ENV] = previous @@ -106,6 +127,35 @@ describe('withDevupUI', () => { devupFile: join(root, 'theme', 'devup.json'), engine: 'wasm', }) + expect(selection.mock.calls).toEqual([['wasm']]) + }) + + it('writes the types of the theme and of React Native into df', () => { + write( + 'devup.json', + JSON.stringify({ theme: { colors: { default: { primary: '#000' } } } }), + ) + withDevupUI({ + projectRoot: root, + transformer: { babelTransformerPath: '/up.js' }, + }) + expect(readFileSync(join(root, 'df', 'theme.d.ts'), 'utf-8')).toContain( + 'primary', + ) + expect(readFileSync(join(root, 'df', 'native.d.ts'), 'utf-8')).toBe( + NATIVE_TYPES, + ) + expect(readFileSync(join(root, 'df', '.gitignore'), 'utf-8')).toBe('*') + }) + + it('writes the types into the distDir option', () => { + withDevupUI( + { projectRoot: root, transformer: { babelTransformerPath: '/up.js' } }, + { distDir: 'types/devup' }, + ) + expect(existsSync(join(root, 'types', 'devup', 'theme.d.ts'))).toBe(true) + expect(existsSync(join(root, 'types', 'devup', 'native.d.ts'))).toBe(true) + expect(existsSync(join(root, 'df'))).toBe(false) }) it('resolves the upstreamTransformer option from the project root', () => { diff --git a/packages/metro-plugin/src/plugin.ts b/packages/metro-plugin/src/plugin.ts index 062ea148e..70bac22e6 100644 --- a/packages/metro-plugin/src/plugin.ts +++ b/packages/metro-plugin/src/plugin.ts @@ -13,6 +13,7 @@ import { readSettings, writeSettings, } from './settings' +import { writeTypes } from './types' export interface DevupUIMetroPluginOptions { /** @@ -24,6 +25,12 @@ export interface DevupUIMetroPluginOptions { package?: string /** Path of devup.json, from the project root. Defaults to `devup.json`. */ devupFile?: string + /** + * Where the TypeScript declarations are written, from the project root: + * the theme's tokens and the React Native props of each component. + * Defaults to `df`, as in the other plugins. + */ + distDir?: string /** * Packages in `node_modules` whose files are compiled as well: a library * that ships Devup UI components uncompiled. Each name matches that whole @@ -127,7 +134,8 @@ function upstreamTransformer( * Compile Devup UI for React Native in Metro: the config's Babel transformer * becomes Devup UI's, which compiles each file that imports Devup UI and then * hands the code to the transformer the config had (Expo's or React - * Native's). + * Native's). The TypeScript declarations of the theme and of the React Native + * props are written into `distDir`. * * ```js * // metro.config.js @@ -159,6 +167,12 @@ export function withDevupUI( engine: options.engine, } writeSettings(settings) + writeTypes({ + distDir: resolve(projectRoot, options.distDir ?? 'df'), + devupFile: settings.devupFile, + package: settings.package, + engine: settings.engine, + }) return { ...config, transformer: { diff --git a/packages/metro-plugin/src/types.ts b/packages/metro-plugin/src/types.ts new file mode 100644 index 000000000..3013e8349 --- /dev/null +++ b/packages/metro-plugin/src/types.ts @@ -0,0 +1,44 @@ +import { mkdirSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' + +import { + createThemeInterfaceArgs, + type DevupEngine, + loadCompiler, + loadDevupConfigSync, +} from '@devup-ui/plugin-utils' + +/** + * `native.d.ts`: it imports the declarations that type each component of + * `@devup-ui/react` as the React Native component it renders + */ +export const NATIVE_TYPES = "import '@devup-ui/react/native/types'\n" + +/** What the types of a project are written from */ +export interface TypesOptions { + /** The directory written, absolute */ + readonly distDir: string + /** devup.json, absolute */ + readonly devupFile: string + /** The package Devup UI is imported from */ + readonly package: string + readonly engine?: DevupEngine +} + +/** + * Write the TypeScript declarations of the project into `distDir`, as the web + * plugins do: `theme.d.ts`, the tokens of devup.json, and `native.d.ts`, which + * types the components for React Native. The directory ignores itself in git. + */ +export function writeTypes(options: TypesOptions): void { + const compiler = loadCompiler(options.engine) + compiler.registerTheme(loadDevupConfigSync(options.devupFile).theme ?? {}) + mkdirSync(options.distDir, { recursive: true }) + writeFileSync(join(options.distDir, '.gitignore'), '*', 'utf-8') + writeFileSync( + join(options.distDir, 'theme.d.ts'), + compiler.getThemeInterface(...createThemeInterfaceArgs(options.package)), + 'utf-8', + ) + writeFileSync(join(options.distDir, 'native.d.ts'), NATIVE_TYPES, 'utf-8') +} diff --git a/packages/react/package.json b/packages/react/package.json index 6d2b468b0..759ae00b0 100644 --- a/packages/react/package.json +++ b/packages/react/package.json @@ -21,8 +21,8 @@ "scripts": { "lint": "eslint && bun ../../node_modules/@typescript/native/bin/tsc --noEmit && bun run test:types", "build": "bun run test:types && bun ../../node_modules/@typescript/native/bin/tsc && vite build && rollup -c rollup.types.config.mjs && bun run test:published-types", - "test:types": "bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/tsconfig.json", - "test:published-types": "bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.bundler.json && bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.node16.json" + "test:types": "bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/tsconfig.json && bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/native/tsconfig.json", + "test:published-types": "bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.bundler.json && bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.node16.json && bun ../../node_modules/@typescript/native/bin/tsc -p type-tests/published/tsconfig.native.json" }, "publishConfig": { "access": "public" @@ -79,6 +79,9 @@ "types": "./dist/native/index.d.ts", "import": "./dist/native/index.js", "require": "./dist/native/index.cjs" + }, + "./native/types": { + "types": "./dist/native/types.d.ts" } }, "files": [ diff --git a/packages/react/rollup.types.config.mjs b/packages/react/rollup.types.config.mjs index ca2bcc427..c54a74e35 100644 --- a/packages/react/rollup.types.config.mjs +++ b/packages/react/rollup.types.config.mjs @@ -20,8 +20,8 @@ const entries = { } const shared = '_shared' -/** Declarations written by hand, which ambiently declare modules and stay as they are */ -const ambient = /^compat\/(?!index\.)[^/]+\.d\.ts$/ +/** Declarations written by hand, which declare or augment modules and stay as they are */ +const ambient = /^(compat\/(?!index\.)[^/]+|native\/types)\.d\.ts$/ function files(directory) { return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => { diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts index 1de5d171a..1afc6989f 100644 --- a/packages/react/src/index.ts +++ b/packages/react/src/index.ts @@ -9,7 +9,7 @@ export { Text } from './components/Text' export { ThemeScript } from './components/ThemeScript' export { VStack } from './components/VStack' export { useTheme } from './hooks/use-theme' -export type { DevupProps } from './types/props' +export type { DevupElementProps, DevupProps } from './types/props' export type { ResponsiveValue } from './types/responsive-value' export type { DevupCustomShorthands } from './types/shorthand' export type { DevupTheme } from './types/theme' diff --git a/packages/react/src/native/types.d.ts b/packages/react/src/native/types.d.ts new file mode 100644 index 000000000..eb30b594f --- /dev/null +++ b/packages/react/src/native/types.d.ts @@ -0,0 +1,39 @@ +/** + * Types `@devup-ui/react` for React Native: each component takes the props of + * the React Native component the build renders it as, instead of those of the + * HTML element it renders on the web. `@devup-ui/metro-plugin` imports this + * file from `/native.d.ts`; to opt in by hand, import it from a + * declaration file of the project: + * + * ```ts + * import '@devup-ui/react/native/types' + * ``` + */ +import type { + ImageProps, + PressableProps, + TextInputProps, + TextProps, + ViewProps, +} from 'react-native' + +/** What every element takes besides its component's props */ +interface DevupNativeElementProps { + /** The class of `css()`, whose styles the build gives the element */ + className?: string +} + +declare module '@devup-ui/react' { + interface DevupElementProps { + /** `Box`, `Flex`, `VStack`, `Center` and `Grid`: a `View` */ + div: ViewProps & DevupNativeElementProps + /** `Text`: a `Text` */ + span: TextProps & DevupNativeElementProps + /** `Image`: an `Image` */ + img: ImageProps & DevupNativeElementProps + /** `Input`: a `TextInput` */ + input: TextInputProps & DevupNativeElementProps + /** `Button`: a `Pressable` */ + button: PressableProps & DevupNativeElementProps + } +} diff --git a/packages/react/src/types/props/index.ts b/packages/react/src/types/props/index.ts index c2646b9b5..043bedb09 100644 --- a/packages/react/src/types/props/index.ts +++ b/packages/react/src/types/props/index.ts @@ -63,12 +63,28 @@ type DevupDefaultIntrinsicPropConflicts = | 'width' | keyof DevupCustomShorthands +/** + * The props a component takes, by the HTML element it renders on the web, in + * place of that element's: empty on the web, and filled by + * `@devup-ui/react/native/types` with the props of the React Native component + * each renders on React Native (`div` a `View`, `span` a `Text`, ...). + */ +// biome-ignore lint/suspicious/noEmptyInterface: public module augmentation point for React Native. +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export interface DevupElementProps {} + +/** The props of the element `T` a component renders */ +export type DevupIntrinsicProps = + T extends keyof DevupElementProps + ? DevupElementProps[T] + : React.ComponentProps + // Component declarations put this overload first for fast resolution and last // so Parameters keeps describing the default element. export type DevupDefaultComponentMergedProps< T extends keyof React.JSX.IntrinsicElements, -> = Omit, DevupDefaultIntrinsicPropConflicts> & { - props?: FilterChildren> +> = Omit, DevupDefaultIntrinsicPropConflicts> & { + props?: FilterChildren> } & DevupComponentProps export type DevupComponentBaseProps = diff --git a/packages/react/type-tests/native/app.tsx b/packages/react/type-tests/native/app.tsx new file mode 100644 index 000000000..118bdb76d --- /dev/null +++ b/packages/react/type-tests/native/app.tsx @@ -0,0 +1,28 @@ +// The components typed for React Native (`@devup-ui/react/native/types`): +// each takes the props of the React Native component it renders, and its +// style props as on the web +import { Box, Button, css, Flex, Image, Input, Text } from '@devup-ui/react' + +export const app = ( + {}} testID="card"> + + {}}> + title + + + text} + secureTextEntry + /> + + + +) + +// @ts-expect-error a View has no href +export const link = +// @ts-expect-error a TextInput reports its text with onChangeText +export const input = {}} /> diff --git a/packages/react/type-tests/native/tsconfig.json b/packages/react/type-tests/native/tsconfig.json new file mode 100644 index 000000000..ecdf8f0c4 --- /dev/null +++ b/packages/react/type-tests/native/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "paths": { + "@devup-ui/react": ["../../src/index.ts"], + "@devup-ui/react/*": ["../../src/*"] + } + }, + "files": ["../../src/native/types.d.ts", "app.tsx"], + "include": [] +} diff --git a/packages/react/type-tests/published/native.tsx b/packages/react/type-tests/published/native.tsx new file mode 100644 index 000000000..a6e001e12 --- /dev/null +++ b/packages/react/type-tests/published/native.tsx @@ -0,0 +1,16 @@ +// Type-checks a React Native project against the published declarations: the +// import `@devup-ui/metro-plugin` writes types each component as the React +// Native component it renders +import '@devup-ui/react/native/types' + +import { Box, Button, Input } from '@devup-ui/react' + +export const app = ( + {}} p={2}> + text} /> +