diff --git a/example/app/_layout.tsx b/example/app/_layout.tsx index 7eb28910..d0475288 100644 --- a/example/app/_layout.tsx +++ b/example/app/_layout.tsx @@ -21,10 +21,10 @@ import { catalogMeta } from '../src/metadata' import { site } from '../src/site' // Restore the persisted RTL preference on web before the first render. -// react-native-web ships `I18nManager` as a stub, so the document `dir` -// attribute is the one switch the browser and the library both read. The -// bundle runs after the HTML is parsed, so the attribute is in place before -// React mounts. +// The document `dir` attribute is the one switch that the browser, the web +// runtime, and the library all read. react-native-web ships `I18nManager` as +// a stub, so `forceRTL` can't be the switch there. The bundle runs after the +// HTML is parsed, so the attribute is in place before React mounts. if (Platform.OS === 'web' && typeof localStorage !== 'undefined') { try { const stored = localStorage.getItem('forceRTL') diff --git a/example/metro.config.js b/example/metro.config.js index 76980e62..23e68da9 100644 --- a/example/metro.config.js +++ b/example/metro.config.js @@ -1,6 +1,7 @@ const path = require('path') const fs = require('fs') const { getDefaultConfig } = require('expo/metro-config') +const { withRootNative } = require('@rootnative/web-expo/metro.cjs') const config = getDefaultConfig(__dirname) const workspaceRoot = path.resolve(__dirname, '..') @@ -73,4 +74,8 @@ config.resolver.resolveRequest = (context, moduleName, platform) => { return context.resolveRequest(context, moduleName, platform) } -module.exports = config +// On the web, send each `react-native` and react-native-web import to +// `@rootnative/web-expo`, so the example runs on the Root Native web runtime. +// react-native-web stays in the root tree for the web Jest projects, and this +// wrap keeps Metro away from it. +module.exports = withRootNative(config) diff --git a/example/package.json b/example/package.json index 3692d67b..f8395b27 100644 --- a/example/package.json +++ b/example/package.json @@ -22,6 +22,7 @@ "@rootnative/inertia": "0.0.26", "@rootnative/seo": "workspace:*", "@rootnative/utils": "workspace:*", + "@rootnative/web-expo": "~0.0.3", "expo": "~58.0.23", "expo-constants": "~58.0.15", "expo-font": "~58.0.11", @@ -37,7 +38,6 @@ "react-native-safe-area-context": "5.11.1", "react-native-screens": "~4.30.1", "react-native-svg": "15.16.0", - "react-native-web": "~0.21.4", "react-native-worklets": "0.13.0" }, "devDependencies": { diff --git a/packages/components/src/__tests__/web/rtl-swap.web.test.tsx b/packages/components/src/__tests__/web/rtl-swap.web.test.tsx new file mode 100644 index 00000000..1f462777 --- /dev/null +++ b/packages/components/src/__tests__/web/rtl-swap.web.test.tsx @@ -0,0 +1,292 @@ +/** + * A web runtime can follow the React Native rule for `left` and `right`. It + * has `I18nManager.doLeftAndRightSwapInRTL`, and while the flag is on it + * applies `left` to the start side, which is the right side in RTL. + * react-native-web has no flag and keeps both sides physical, so the + * components mirror a physical side by hand there. On a runtime that swaps, + * that second mirror moved each side back: the Slider filled from the left, + * and a connected ButtonGroup rounded its inner corners. + * + * These tests run on react-native-web with the flag added to its + * `I18nManager`. react-native-web doesn't swap, so the DOM shows the side that + * a component writes. A runtime that swaps moves a `left` here to the right + * side, so each RTL case expects the side of LTR, with no mirror by hand. + */ +import { lightTheme } from '@rootnative/core' +import { + resolveLogical, + resolveLogicalKey, + swapsLeftAndRight, + webKeepsPhysicalSides, +} from '@rootnative/utils' +import { act, screen } from '@testing-library/react' +import { I18nManager, Text } from 'react-native' +import { ButtonGroup } from '../../button-group' +import { Carousel } from '../../carousel' +import type { CarouselItemInfo } from '../../carousel' +import { resolveAnimatedInsetKey } from '../../internal/resolveAnimatedInsetKey' +import { resolveLogicalCornerKey } from '../../internal/resolveLogicalCornerKey' +import { LinearProgress } from '../../progress/LinearProgress' +import { physicalLeftStyle, sideEdgesOfStyleKeys } from '../../safe-area' +import { Slider } from '../../slider' +import { Tabs } from '../../tabs' +import { renderWeb } from './render-web' + +const i18n = I18nManager as unknown as { doLeftAndRightSwapInRTL?: boolean } + +function setSwapFlag(value: boolean) { + i18n.doLeftAndRightSwapInRTL = value +} + +function setRTL() { + document.documentElement.setAttribute('dir', 'rtl') +} + +/** + * The document and the `I18nManager` object are shared across tests in a + * file, so a leaked flag or `dir` changes each later test. Always clear both. + */ +afterEach(() => { + delete i18n.doLeftAndRightSwapInRTL + document.documentElement.removeAttribute('dir') +}) + +function fireLayout(node: Element, width: number) { + const handler = (node as Element & { __reactLayoutHandler?: unknown }) + .__reactLayoutHandler + if (typeof handler !== 'function') { + throw new Error('react-native-web set no layout handler on the node') + } + act(() => { + handler({ nativeEvent: { layout: { x: 0, y: 0, width, height: 48 } } }) + }) +} + +describe('the side helpers read the flag of the runtime', () => { + it('see no swap on react-native-web, which has no flag', () => { + setRTL() + expect(swapsLeftAndRight()).toBe(false) + expect(webKeepsPhysicalSides()).toBe(true) + }) + + it('see a swap under dir="rtl" while the flag is on', () => { + setSwapFlag(true) + setRTL() + expect(swapsLeftAndRight()).toBe(true) + expect(webKeepsPhysicalSides()).toBe(false) + }) + + it('see no swap in LTR', () => { + setSwapFlag(true) + expect(swapsLeftAndRight()).toBe(false) + expect(webKeepsPhysicalSides()).toBe(false) + }) + + it('keep the sides physical while the flag is off', () => { + setSwapFlag(false) + setRTL() + expect(swapsLeftAndRight()).toBe(false) + expect(webKeepsPhysicalSides()).toBe(true) + expect(resolveLogicalKey('start')).toBe('right') + }) +}) + +describe('a runtime that swaps gets each key with no mirror under dir="rtl"', () => { + beforeEach(() => { + setSwapFlag(true) + setRTL() + }) + + it('keeps the logical key of a one-sided inset', () => { + expect(resolveLogicalKey('start')).toBe('start') + expect(resolveLogical('marginEnd', 8)).toEqual({ marginEnd: 8 }) + }) + + it('keeps the logical key of a corner', () => { + expect(resolveLogicalCornerKey('borderTopStartRadius')).toBe( + 'borderTopStartRadius', + ) + }) + + it('gives an animated start inset the left key', () => { + expect(resolveAnimatedInsetKey('start')).toBe('left') + expect(resolveAnimatedInsetKey('end')).toBe('right') + }) + + it('puts a measured offset from the left edge into right', () => { + expect(sideEdgesOfStyleKeys()).toEqual(['right', 'left']) + expect(physicalLeftStyle(40)).toEqual({ right: 40 }) + }) +}) + +/** + * The thumb controls of a range Slider sit at the position of each value, + * from `left`. On react-native-web in RTL the Slider mirrors each position by + * hand. On a runtime that swaps, the platform mirrors it. + */ +describe('Slider mirrors the thumbs by hand only where the sides stay physical', () => { + function thumbLefts() { + const view = renderWeb( + , + ) + const track = [...view.container.querySelectorAll('*')].find( + (node) => + typeof (node as Element & { __reactLayoutHandler?: unknown }) + .__reactLayoutHandler === 'function', + ) + if (!track) throw new Error('the Slider set no layout handler') + fireLayout(track, 300) + const lefts = ['Price, Minimum', 'Price, Maximum'].map( + (label) => screen.getByLabelText(label).style.left, + ) + view.unmount() + return lefts + } + + it('on react-native-web and on a runtime that swaps', () => { + const ltr = thumbLefts() + expect(ltr.every((left) => left !== '')).toBe(true) + + setRTL() + const byHand = thumbLefts() + expect(byHand).not.toEqual(ltr) + + setSwapFlag(true) + expect(thumbLefts()).toEqual(ltr) + }) +}) + +describe('LinearProgress leaves the mirror of each left to a runtime that swaps', () => { + beforeEach(() => { + setSwapFlag(true) + setRTL() + }) + + function partsOf(bar: React.ReactElement) { + renderWeb(bar) + const root = screen.getByTestId('linear') + fireLayout(root, 200) + return Array.from(root.children) as HTMLElement[] + } + + // The values of the LTR case in `rtl.web.test.tsx`. + it('places the determinate bar as in LTR', () => { + const [active, inactive, stop] = partsOf( + , + ) + expect([active?.style.left, active?.style.width]).toEqual(['0px', '47px']) + expect([inactive?.style.left, inactive?.style.width]).toEqual([ + '51px', + '141px', + ]) + expect([stop?.style.left, stop?.style.right]).toEqual(['', '0px']) + }) + + it('places the indeterminate segment as in LTR', () => { + const [, segment] = partsOf() + expect(segment?.style.left).toBe('0px') + }) + + // A path is physical on each runtime, so the wave still flips. + it('still flips the wave', () => { + const [wave] = partsOf( + , + ) + expect(wave?.style.transform).toBe('scaleX(-1)') + }) +}) + +describe('ButtonGroup leaves the corners of a connected group to a runtime that swaps', () => { + it('rounds the outer corners as in LTR under dir="rtl"', () => { + setSwapFlag(true) + setRTL() + renderWeb( + , + ) + let node = screen.getByText('Day') as HTMLElement | null + while (node && !node.style.borderTopLeftRadius) node = node.parentElement + const style = (node as HTMLElement).style + expect([style.borderTopLeftRadius, style.borderBottomLeftRadius]).toEqual([ + `${lightTheme.shape.cornerFull}px`, + `${lightTheme.shape.cornerFull}px`, + ]) + }) +}) + +/** + * The indicator moves with a physical `translateX` from the physical left + * edge. The edge is `right: 0` where the platform applies `left` to the right + * side. + */ +describe('Tabs anchors the indicator for a runtime that swaps', () => { + it('at right: 0 under dir="rtl", with the offset from the right edge', () => { + setSwapFlag(true) + setRTL() + const items = [ + { value: 'flights', label: 'Flights' }, + { value: 'trips', label: 'Trips' }, + { value: 'explore', label: 'Explore' }, + ] + renderWeb( + , + ) + const tabs = screen.getAllByRole('tab') + for (const [index, tab] of tabs.entries()) { + fireLayout(tab, 120) + const label = screen.getByText(items[index]?.label ?? '') + fireLayout(label.parentElement as HTMLElement, 40) + } + fireLayout(tabs[0]?.parentElement as HTMLElement, 500) + const indicator = screen.getByTestId('tabs-indicator') + expect([indicator.style.left, indicator.style.right]).toEqual(['', '0px']) + // 500 - 16 - 240 + (120 - 40) / 2. + expect(indicator.style.transform).toBe('translateX(284px)') + }) +}) + +describe('Carousel measures the snap markers for a runtime that swaps', () => { + it('from the left under dir="rtl"', () => { + setSwapFlag(true) + setRTL() + const places = ['Cabin', 'Shore', 'Ridge', 'Dunes'] + renderWeb( + ) => {item}} + contentPadding={16} + testID="carousel" + />, + ) + fireLayout(screen.getByTestId('carousel'), 380) + const scroller = screen.getByTestId('carousel-scroll') + const markers = [...scroller.querySelectorAll('*')].filter( + (node) => getComputedStyle(node).getPropertyValue('scroll-snap-align'), + ) + const starts = markers.filter( + (node) => + getComputedStyle(node).getPropertyValue('scroll-snap-align') === + 'start', + ) + expect(starts.length).toBeGreaterThan(0) + expect(starts.every((node) => node.style.left !== '')).toBe(true) + expect(starts.every((node) => node.style.right === '')).toBe(true) + }) +}) diff --git a/packages/components/src/button-group/ButtonGroup.tsx b/packages/components/src/button-group/ButtonGroup.tsx index a02af840..27ed24d0 100644 --- a/packages/components/src/button-group/ButtonGroup.tsx +++ b/packages/components/src/button-group/ButtonGroup.tsx @@ -8,10 +8,10 @@ import { useAnimatedStyle, } from '@rootnative/inertia/reanimated' import { - isRTLDirection, renderIcon, resolveColorFromStyle, resolveLogicalKey, + webKeepsPhysicalSides, } from '@rootnative/utils' import { useCallback, useMemo, useState, type ReactElement } from 'react' import { @@ -268,7 +268,7 @@ function ButtonGroupItemImpl({ // Read on each render, not in a memo, so the corners follow a runtime change // of the document `dir`. See `mirrorItemCornerRadii`. - const mirrorsOnWeb = Platform.OS === 'web' && isRTLDirection() + const mirrorsOnWeb = webKeepsPhysicalSides() const unselectedRadii = useMemo(() => { const radii = getItemCornerRadii(theme, variant, size, index, total, false) return mirrorsOnWeb ? mirrorItemCornerRadii(radii) : radii diff --git a/packages/components/src/button-group/styles.ts b/packages/components/src/button-group/styles.ts index 5ded435c..4235f867 100644 --- a/packages/components/src/button-group/styles.ts +++ b/packages/components/src/button-group/styles.ts @@ -207,9 +207,10 @@ export interface ItemCornerRadii { */ /** * The radii of an item, mirrored left for right. The connected corners are - * physical keys. React Native swaps them in an RTL layout on native, and - * react-native-web never does, so under an RTL document on the web the first - * item, which sits at the right, needs the corners of the last. + * physical keys. React Native swaps them in an RTL layout on native, and so + * does a web runtime that swaps `left` and `right`. react-native-web never + * does, so under an RTL document there the first item, which sits at the + * right, needs the corners of the last. */ export function mirrorItemCornerRadii(radii: ItemCornerRadii): ItemCornerRadii { return { diff --git a/packages/components/src/carousel/Carousel.tsx b/packages/components/src/carousel/Carousel.tsx index 509e02f6..e430da46 100644 --- a/packages/components/src/carousel/Carousel.tsx +++ b/packages/components/src/carousel/Carousel.tsx @@ -12,7 +12,7 @@ import { useAnimatedStyle, useDerivedValue, } from '@rootnative/inertia/reanimated' -import { isRTLDirection } from '@rootnative/utils' +import { isRTLDirection, webKeepsPhysicalSides } from '@rootnative/utils' import { useCallback, useEffect, @@ -465,8 +465,9 @@ function WebSnapMarkers({ vertical: boolean }) { // react-native-web writes an inline `start` as `left` whatever the document - // direction is, so the markers take the physical side. - const startSide = isRTLDirection() ? 'right' : 'left' + // direction is, so the markers take a physical side. A web runtime that + // swaps puts `left` at the start in RTL itself. + const startSide = webKeepsPhysicalSides() ? 'right' : 'left' const endSide = startSide === 'left' ? 'right' : 'left' const at = (offset: number): ViewStyle => vertical ? { top: offset } : { [startSide]: offset } diff --git a/packages/components/src/internal/resolveAnimatedInsetKey.ts b/packages/components/src/internal/resolveAnimatedInsetKey.ts index 0ed78c13..6a8d5b10 100644 --- a/packages/components/src/internal/resolveAnimatedInsetKey.ts +++ b/packages/components/src/internal/resolveAnimatedInsetKey.ts @@ -1,19 +1,20 @@ -import { isRTLDirection } from '@rootnative/utils' +import { webKeepsPhysicalSides } from '@rootnative/utils' import { Platform } from 'react-native' /** * The key for a start or end inset in a Reanimated animated style. * * On the web, Reanimated writes each animated frame to `element.style` - * through react-native-web's `createReactDOMStyle`, which doesn't resolve a - * logical key. `start` is not a CSS property, so the browser drops the frame. - * So on the web this returns the physical key for the document direction, in - * LTR too, unlike `resolveLogicalKey`. Native returns the logical key, which - * React Native resolves. + * through the `createReactDOMStyle` of the runtime. react-native-web's + * doesn't resolve a logical key. `start` is not a CSS property, so the + * browser drops the frame. So on the web this returns a physical key, in LTR + * too, unlike `resolveLogicalKey`. A web runtime that swaps `left` and + * `right` applies `left` to the start side in RTL too. Native returns the + * logical key, which React Native resolves. */ export function resolveAnimatedInsetKey(key: 'start' | 'end'): string { if (Platform.OS !== 'web') return key - const isRTL = isRTLDirection() - if (key === 'start') return isRTL ? 'right' : 'left' - return isRTL ? 'left' : 'right' + const startSide = webKeepsPhysicalSides() ? 'right' : 'left' + if (key === 'start') return startSide + return startSide === 'left' ? 'right' : 'left' } diff --git a/packages/components/src/internal/resolveLogicalCornerKey.ts b/packages/components/src/internal/resolveLogicalCornerKey.ts index e61311de..96c3d3b3 100644 --- a/packages/components/src/internal/resolveLogicalCornerKey.ts +++ b/packages/components/src/internal/resolveLogicalCornerKey.ts @@ -1,5 +1,4 @@ -import { isRTLDirection } from '@rootnative/utils' -import { Platform } from 'react-native' +import { webKeepsPhysicalSides } from '@rootnative/utils' export type LogicalCornerKey = | 'borderTopStartRadius' @@ -27,11 +26,11 @@ const RTL_CORNER_KEYS: Record = { * * react-native-web resolves a start or end corner from its locale context, * which is LTR under `` too, also in a `StyleSheet.create` - * style. So on the web under an RTL document this returns the physical key. - * In each other case it returns the logical key, which keeps the precedence - * of a later style that sets the same key. + * style. So there, under an RTL document, this returns the physical key. In + * each other case it returns the logical key, which keeps the precedence of a + * later style that sets the same key. */ export function resolveLogicalCornerKey(key: LogicalCornerKey): string { - if (Platform.OS !== 'web' || !isRTLDirection()) return key + if (!webKeepsPhysicalSides()) return key return RTL_CORNER_KEYS[key] } diff --git a/packages/components/src/internal/swapsLeftAndRight.ts b/packages/components/src/internal/swapsLeftAndRight.ts deleted file mode 100644 index a5877aa1..00000000 --- a/packages/components/src/internal/swapsLeftAndRight.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { I18nManager, Platform } from 'react-native' - -/** - * Whether React Native applies `left` to the right side, and `right` to the - * left side. It does that on native in RTL, while - * `I18nManager.doLeftAndRightSwapInRTL` is on (the default). The web never - * swaps. - * - * A view placed with `left` mirrors with the layout there. A value that is - * physical does not: a `translateX`, or a coordinate inside an SVG. Use this - * to mirror such a value where the platform mirrors the rest. - */ -export function swapsLeftAndRight(): boolean { - return ( - Platform.OS !== 'web' && - I18nManager.isRTL && - I18nManager.doLeftAndRightSwapInRTL - ) -} diff --git a/packages/components/src/progress/LinearProgress.tsx b/packages/components/src/progress/LinearProgress.tsx index 27be54f4..58843004 100644 --- a/packages/components/src/progress/LinearProgress.tsx +++ b/packages/components/src/progress/LinearProgress.tsx @@ -9,12 +9,11 @@ import { useAnimatedProps, useAnimatedStyle, } from '@rootnative/inertia/reanimated' -import { isRTLDirection } from '@rootnative/utils' +import { swapsLeftAndRight, webKeepsPhysicalSides } from '@rootnative/utils' import { useMemo, useState } from 'react' import type { LayoutChangeEvent, ViewStyle } from 'react-native' -import { Platform, View } from 'react-native' +import { View } from 'react-native' import Svg, { Path } from 'react-native-svg' -import { swapsLeftAndRight } from '../internal/swapsLeftAndRight' import { useMaterialTheme } from '../internal/useMaterialTheme' import { PROGRESS_LINEAR_INDETERMINATE_WAVELENGTH, @@ -103,10 +102,11 @@ export function LinearProgress({ const segmentWidth = Math.max(width * INDETERMINATE_SEGMENT_RATIO, 0) // In native RTL, React Native applies `left` to the right side, so the - // views mirror. react-native-web keeps `left` physical, so on the web in - // RTL each `left` below is mirrored here. A `translateX` and an SVG path are - // physical on both: the slide changes its sign, and each wave flips. - const mirrorsLeftOnWeb = Platform.OS === 'web' && isRTLDirection() + // views mirror. A web runtime that swaps does the same. react-native-web + // keeps `left` physical, so there each `left` below is mirrored here in RTL. + // A `translateX` and an SVG path are physical on all of them: the slide + // changes its sign, and each wave flips. + const mirrorsLeftOnWeb = webKeepsPhysicalSides() const mirrored = swapsLeftAndRight() || mirrorsLeftOnWeb const slideSign = mirrored ? -1 : 1 const waveMirror = mirrored ? MIRRORED : undefined diff --git a/packages/components/src/safe-area.tsx b/packages/components/src/safe-area.tsx index 309a3eed..f140065a 100644 --- a/packages/components/src/safe-area.tsx +++ b/packages/components/src/safe-area.tsx @@ -1,6 +1,7 @@ +import { swapsLeftAndRight } from '@rootnative/utils' import { useContext, useMemo } from 'react' import type { ComponentProps, ComponentType, ReactNode } from 'react' -import { I18nManager, Platform, StyleSheet, View } from 'react-native' +import { Platform, StyleSheet, View } from 'react-native' import type { ViewProps } from 'react-native' import { SafeAreaInsetsContext, @@ -51,15 +52,11 @@ const SWAPPED_SIDES: readonly [SideEdge, SideEdge] = ['right', 'left'] * applies `paddingLeft` and `marginLeft` to the start edge, which is the * right side, while `I18nManager.doLeftAndRightSwapInRTL` is on (the default * on iOS and Android). With a cutout on one side only, as on Android, an - * unswapped inset pads the side without the cutout. react-native-web never - * swaps. + * unswapped inset pads the side without the cutout. On the web it depends on + * the runtime: see `swapsLeftAndRight`. */ export function sideEdgesOfStyleKeys(): readonly [SideEdge, SideEdge] { - const swaps = - Platform.OS !== 'web' && - I18nManager.isRTL && - I18nManager.doLeftAndRightSwapInRTL - return swaps ? SWAPPED_SIDES : UNSWAPPED_SIDES + return swapsLeftAndRight() ? SWAPPED_SIDES : UNSWAPPED_SIDES } /** diff --git a/packages/components/src/slider/Slider.tsx b/packages/components/src/slider/Slider.tsx index 4249a86c..14343496 100644 --- a/packages/components/src/slider/Slider.tsx +++ b/packages/components/src/slider/Slider.tsx @@ -1,6 +1,11 @@ import { useIconResolver } from '@rootnative/core' import { useAnimator, useMotionValue } from '@rootnative/inertia' -import { isFocusVisible, isRTLDirection, renderIcon } from '@rootnative/utils' +import { + isFocusVisible, + isRTLDirection, + renderIcon, + webKeepsPhysicalSides, +} from '@rootnative/utils' import { Fragment, useCallback, @@ -17,7 +22,7 @@ import type { PressableProps, TargetedEvent, } from 'react-native' -import { PanResponder, Platform, Pressable, View } from 'react-native' +import { PanResponder, Pressable, View } from 'react-native' // Sanctioned escape hatch: the slider's focus/label progress is routed // imperatively between two thumbs from one Pressable (`keyboardThumb`), a // shape inertia's gesture hooks don't express. `useAnimator` drives the raw @@ -182,11 +187,13 @@ export function Slider({ // Slots position with `left`. React Native swaps `left` to `start` in RTL // (`I18nManager.doLeftAndRightSwapInRTL`), so on native the platform // mirrors the rendered position and mirroring it here as well put the fill - // back on the left. react-native-web never swaps, so the web keeps the - // manual mirror. The segments follow the same rule: `computeSegments` puts - // the active side after the thumb only where this file mirrors. Gesture - // coordinates are physical on both, so `positionToValue` always mirrors. - const mirrorRenderedPosition = isRTL && Platform.OS === 'web' + // back on the left. A web runtime that swaps does the same. Only + // react-native-web keeps `left` physical, so only there does this file + // mirror. The segments follow the same rule: `computeSegments` puts the + // active side after the thumb only where this file mirrors. Gesture + // coordinates are physical on all of them, so `positionToValue` always + // mirrors. + const mirrorRenderedPosition = webKeepsPhysicalSides() const valueToPosition = useCallback( (v: number) => { const ratio = (v - minimumValue) / range diff --git a/packages/components/src/tabs/Tabs.tsx b/packages/components/src/tabs/Tabs.tsx index bc744b65..e25774a9 100644 --- a/packages/components/src/tabs/Tabs.tsx +++ b/packages/components/src/tabs/Tabs.tsx @@ -5,7 +5,7 @@ import { } from '@rootnative/inertia' import type { SharedValue } from '@rootnative/inertia' import { Animated, useAnimatedStyle } from '@rootnative/inertia/reanimated' -import { isRTLDirection } from '@rootnative/utils' +import { isRTLDirection, swapsLeftAndRight } from '@rootnative/utils' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import type { LayoutChangeEvent, @@ -16,7 +16,6 @@ import type { import { Platform, ScrollView, View } from 'react-native' import { Divider } from '../divider' import { pointerEvents } from '../internal/pointerEvents' -import { swapsLeftAndRight } from '../internal/swapsLeftAndRight' import { useMaterialTheme } from '../internal/useMaterialTheme' import { PRIMARY_INDICATOR_MIN_WIDTH, @@ -293,9 +292,10 @@ export function Tabs({ /** * The style that puts an absolute view at the physical left edge of its - * parent. In native RTL, React Native applies `left` to the right side, so - * the left edge is `right: 0` there. A plain `left: 0` put the indicator at - * the right edge, and its offset then moved it out of the row. + * parent. Where the platform applies `left` to the right side (native RTL, or + * a web runtime that swaps), the left edge is `right: 0`. A plain `left: 0` + * put the indicator at the right edge, and its offset then moved it out of + * the row. */ function physicalLeftEdge(): ViewStyle { return swapsLeftAndRight() ? { right: 0 } : { left: 0 } diff --git a/packages/utils/src/__tests__/rtl.test.ts b/packages/utils/src/__tests__/rtl.test.ts index b70b59d1..52d0aab2 100644 --- a/packages/utils/src/__tests__/rtl.test.ts +++ b/packages/utils/src/__tests__/rtl.test.ts @@ -3,7 +3,9 @@ import { resolveLogical, resolveLogicalKey, selectRTL, + swapsLeftAndRight, transformOrigin, + webKeepsPhysicalSides, } from '../rtl' function withRTL(isRTL: boolean, fn: () => void) { @@ -94,3 +96,47 @@ describe('resolveLogical on native', () => { }) }) }) + +describe('swapsLeftAndRight on native', () => { + function withSwapFlag(swap: boolean, fn: () => void) { + const original = I18nManager.doLeftAndRightSwapInRTL + Object.defineProperty(I18nManager, 'doLeftAndRightSwapInRTL', { + configurable: true, + value: swap, + }) + try { + fn() + } finally { + Object.defineProperty(I18nManager, 'doLeftAndRightSwapInRTL', { + configurable: true, + value: original, + }) + } + } + + it('swaps in RTL while the flag is on', () => { + withSwapFlag(true, () => { + withRTL(true, () => expect(swapsLeftAndRight()).toBe(true)) + }) + }) + + it('does not swap in RTL while the flag is off', () => { + withSwapFlag(false, () => { + withRTL(true, () => expect(swapsLeftAndRight()).toBe(false)) + }) + }) + + it('does not swap in LTR', () => { + withSwapFlag(true, () => { + withRTL(false, () => expect(swapsLeftAndRight()).toBe(false)) + }) + }) + + // The web half is in + // `packages/components/src/__tests__/web/rtl-swap.web.test.tsx`. + it('never asks for a mirror by hand', () => { + withSwapFlag(false, () => { + withRTL(true, () => expect(webKeepsPhysicalSides()).toBe(false)) + }) + }) +}) diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts index 58443b06..c97dbbe5 100644 --- a/packages/utils/src/index.ts +++ b/packages/utils/src/index.ts @@ -12,5 +12,7 @@ export { isRTLDirection, resolveLogical, resolveLogicalKey, + swapsLeftAndRight, + webKeepsPhysicalSides, } from './rtl' export type { LogicalStyleKey } from './rtl' diff --git a/packages/utils/src/rtl.ts b/packages/utils/src/rtl.ts index b2b81dbb..5c9a038d 100644 --- a/packages/utils/src/rtl.ts +++ b/packages/utils/src/rtl.ts @@ -83,7 +83,40 @@ export function isRTLDirection(): boolean { } /** - * The logical style keys that a style cannot carry on web under + * Whether the platform applies `left` to the right side, and `right` to the + * left side. React Native does that in an RTL layout while + * `I18nManager.doLeftAndRightSwapInRTL` is on (the default). + * + * On the web it depends on the runtime. react-native-web never swaps, and its + * `I18nManager` has no `doLeftAndRightSwapInRTL`. A web runtime that has the + * flag swaps as native does, under an RTL document. + * + * A view placed with `left` mirrors with the layout where this is true. A + * value that is physical does not: a `translateX`, a coordinate inside an SVG, + * or a position measured with `measureInWindow`. Use this to mirror such a + * value where the platform mirrors the rest. + */ +export function swapsLeftAndRight(): boolean { + if (Platform.OS !== 'web') { + return I18nManager.isRTL && I18nManager.doLeftAndRightSwapInRTL + } + // `=== true`, because the key is `undefined` on react-native-web. + return I18nManager.doLeftAndRightSwapInRTL === true && isRTL() +} + +/** + * Whether the layout is RTL on the web while `left` and `right` stay on their + * physical sides, as on react-native-web. Only then does a component mirror a + * physical side by hand. Native, and a web runtime that swaps (see + * `swapsLeftAndRight`), mirror the side for it, so a second mirror by hand + * moves the side back. + */ +export function webKeepsPhysicalSides(): boolean { + return Platform.OS === 'web' && isRTL() && !swapsLeftAndRight() +} + +/** + * The logical style keys that a style cannot carry on react-native-web under * ``. */ export type LogicalStyleKey = @@ -125,13 +158,15 @@ const RTL_PHYSICAL_KEYS: Record = { * * So on web under an RTL document this returns the physical key. In each other * case it returns the logical key itself: native resolves it, and on web in - * LTR react-native-web puts it on the correct side. The logical key keeps the - * precedence of a later style that sets the same key. react-native-web merges - * styles by key name, so a consumer `paddingStart` replaces a `paddingStart` - * of the library, but not a `paddingLeft`. + * LTR react-native-web puts it on the correct side. A web runtime that swaps + * `left` and `right` follows native here too, and resolves the key from the + * layout direction. The logical key keeps the precedence of a later style + * that sets the same key. react-native-web merges styles by key name, so a + * consumer `paddingStart` replaces a `paddingStart` of the library, but not a + * `paddingLeft`. */ export function resolveLogicalKey(key: LogicalStyleKey): string { - if (Platform.OS !== 'web' || !isRTL()) return key + if (!webKeepsPhysicalSides()) return key return RTL_PHYSICAL_KEYS[key] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 177a8735..b7515c33 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -121,6 +121,9 @@ importers: '@rootnative/utils': specifier: workspace:* version: link:../packages/utils + '@rootnative/web-expo': + specifier: ~0.0.3 + version: 0.0.3(@babel/core@7.29.0)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0))(react@19.3.0) expo: specifier: ~58.0.23 version: 58.0.23(@babel/core@7.29.0)(@expo/dom-webview@58.0.2)(@expo/metro-runtime@58.0.17)(expo-router@58.0.30)(react-dom@19.3.0(react@19.3.0))(react-native-web@0.21.4(react-dom@19.3.0(react@19.3.0))(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0)(typescript@6.0.3) @@ -166,9 +169,6 @@ importers: react-native-svg: specifier: 15.16.0 version: 15.16.0(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0) - react-native-web: - specifier: ~0.21.4 - version: 0.21.4(react-dom@19.3.0(react@19.3.0))(react@19.3.0) react-native-worklets: specifier: 0.13.0 version: 0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0) @@ -3226,6 +3226,28 @@ packages: '@testing-library/react-native': optional: true + '@rootnative/web-expo@0.0.3': + resolution: {integrity: sha512-oHhf9fNhATSDu0tEzM5dpOoaGmxbQRUvgusZPEyAVO7zi7QvynW4V71PSAH0dkpLNaKJTyqkuLu7IRHU1pa8Yg==} + peerDependencies: + react: 19.3.0 + react-dom: 19.3.0 + + '@rootnative/web@0.0.3': + resolution: {integrity: sha512-y/wktmf+xu1qrWYxknE4RTaXIO6UzsPUoCEtl3PnHmbfOgweRTOxytGKL36RlDobk/jRGkOOIp5Otb4dih7tow==} + peerDependencies: + '@babel/core': ^7.0.0 + react: 19.3.0 + react-dom: 19.3.0 + react-native-worklets: '>=0.5.0' + vite: ^8.0.0 + peerDependenciesMeta: + '@babel/core': + optional: true + react-native-worklets: + optional: true + vite: + optional: true + '@rtsao/scc@1.1.0': resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} @@ -14511,6 +14533,25 @@ snapshots: react-native-reanimated: 4.7.1(react-native-worklets@0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0) react-native-worklets: 0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0) + '@rootnative/web-expo@0.0.3(@babel/core@7.29.0)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0))(react@19.3.0)': + dependencies: + '@rootnative/web': 0.0.3(@babel/core@7.29.0)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0))(react@19.3.0) + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + transitivePeerDependencies: + - '@babel/core' + - react-native-worklets + - vite + + '@rootnative/web@0.0.3(@babel/core@7.29.0)(react-dom@19.3.0(react@19.3.0))(react-native-worklets@0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0))(react@19.3.0)': + dependencies: + '@react-native/normalize-colors': 0.88.1 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + optionalDependencies: + '@babel/core': 7.29.0 + react-native-worklets: 0.13.0(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(react-native@0.88.1(@babel/core@7.29.0)(@react-native/metro-config@0.88.1(@babel/core@7.29.0))(@types/react@19.3.0)(react@19.3.0))(react@19.3.0) + '@rtsao/scc@1.1.0': {} '@sec-ant/readable-stream@0.4.1': {} diff --git a/registry/components/bottom-sheet.json b/registry/components/bottom-sheet.json index b3e51386..92032fd4 100644 --- a/registry/components/bottom-sheet.json +++ b/registry/components/bottom-sheet.json @@ -14,7 +14,7 @@ "packages/components/src/internal/warnOnce.ts", "packages/components/src/safe-area.tsx" ], - "utils": ["color", "elevation"], + "utils": ["color", "elevation", "rtl"], "componentDependencies": ["portal"], "dependencies": { "@rootnative/core": ">=0.0.3 <0.1.0", diff --git a/registry/components/navigation-bar.json b/registry/components/navigation-bar.json index ba4cdc74..bca5a555 100644 --- a/registry/components/navigation-bar.json +++ b/registry/components/navigation-bar.json @@ -16,7 +16,7 @@ "packages/components/src/internal/warnOnce.ts", "packages/components/src/safe-area.tsx" ], - "utils": ["color", "elevation", "render-icon"], + "utils": ["color", "elevation", "render-icon", "rtl"], "componentDependencies": ["badge", "layout"], "dependencies": { "@rootnative/core": ">=0.0.3 <0.1.0", diff --git a/registry/components/portal.json b/registry/components/portal.json index 86ab1c4e..8c656d4b 100644 --- a/registry/components/portal.json +++ b/registry/components/portal.json @@ -14,7 +14,7 @@ "packages/components/src/internal/warnOnce.ts", "packages/components/src/safe-area.tsx" ], - "utils": [], + "utils": ["rtl"], "componentDependencies": [], "dependencies": { "@rootnative/core": ">=0.0.3 <0.1.0", diff --git a/registry/components/progress.json b/registry/components/progress.json index a345eff0..a824d412 100644 --- a/registry/components/progress.json +++ b/registry/components/progress.json @@ -9,7 +9,6 @@ "packages/components/src/progress/types.ts", "packages/components/src/progress/useWaveMotion.ts", "packages/components/src/progress/wave.ts", - "packages/components/src/internal/swapsLeftAndRight.ts", "packages/components/src/internal/useMaterialTheme.ts", "packages/components/src/internal/warnOnce.ts" ], diff --git a/registry/components/tabs.json b/registry/components/tabs.json index 2b8e7239..dd12f394 100644 --- a/registry/components/tabs.json +++ b/registry/components/tabs.json @@ -11,7 +11,6 @@ "packages/components/src/internal/focusOutline.ts", "packages/components/src/internal/pointerEvents.ts", "packages/components/src/internal/pressableKeyDown.ts", - "packages/components/src/internal/swapsLeftAndRight.ts", "packages/components/src/internal/useMaterialTheme.ts", "packages/components/src/internal/useStateLayer.ts", "packages/components/src/internal/warnOnce.ts" diff --git a/registry/utils.json b/registry/utils.json index f8b1c26c..cdb0d835 100644 --- a/registry/utils.json +++ b/registry/utils.json @@ -33,7 +33,9 @@ "selectRTL", "isRTLDirection", "resolveLogicalKey", - "resolveLogical" + "resolveLogical", + "swapsLeftAndRight", + "webKeepsPhysicalSides" ], "dependencies": {}, "typeExports": ["LogicalStyleKey"] diff --git a/scripts/build-registry.ts b/scripts/build-registry.ts index d8ae3d12..e81fe8d0 100644 --- a/scripts/build-registry.ts +++ b/scripts/build-registry.ts @@ -107,6 +107,8 @@ const UTIL_EXPORTS: Record = { 'isRTLDirection', 'resolveLogicalKey', 'resolveLogical', + 'swapsLeftAndRight', + 'webKeepsPhysicalSides', ], }