diff --git a/package.json b/package.json index 042a141..e42e7c4 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "android": "expo run:android", "ios": "expo run:ios", "lint": "expo lint", + "test": "node --test tests/*.test.cjs", "postinstall": "patch-package" }, "dependencies": { @@ -77,6 +78,7 @@ "eslint-plugin-prettier": "^5.5.5", "prettier": "^3.8.3", "prettier-plugin-tailwindcss": "^0.7.3", + "react-test-renderer": "19.2.3", "typescript": "~6.0.3" }, "private": true, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 71302c7..fdb8eaf 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -201,6 +201,9 @@ importers: prettier-plugin-tailwindcss: specifier: ^0.7.3 version: 0.7.4(prettier@3.8.3) + react-test-renderer: + specifier: 19.2.3 + version: 19.2.3(react@19.2.3) typescript: specifier: ~6.0.3 version: 6.0.3 @@ -4572,6 +4575,11 @@ packages: '@types/react': optional: true + react-test-renderer@19.2.3: + resolution: {integrity: sha512-TMR1LnSFiWZMJkCgNf5ATSvAheTT2NvKIwiVwdBPHxjBI7n/JbWd4gaZ16DVd9foAXdvDz+sB5yxZTwMjPRxpw==} + peerDependencies: + react: ^19.2.3 + react@19.2.3: resolution: {integrity: sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==} engines: {node: '>=0.10.0'} @@ -10066,6 +10074,12 @@ snapshots: optionalDependencies: '@types/react': 19.2.15 + react-test-renderer@19.2.3(react@19.2.3): + dependencies: + react: 19.2.3 + react-is: 19.2.6 + scheduler: 0.27.0 + react@19.2.3: {} reflect.getprototypeof@1.0.10: diff --git a/src/components/CourseFrame.tsx b/src/components/CourseFrame.tsx index 8911746..ff761da 100644 --- a/src/components/CourseFrame.tsx +++ b/src/components/CourseFrame.tsx @@ -1,9 +1,98 @@ -import { useMemo, useRef, useState } from "react"; -import { PanResponder, Platform, View } from "react-native"; +import { useMemo, useState } from "react"; +import { Platform, View, type ViewStyle } from "react-native"; +import { Gesture, GestureDetector } from "react-native-gesture-handler"; +import Animated, { + useAnimatedStyle, + useSharedValue, + type SharedValue, +} from "react-native-reanimated"; +import { scheduleOnRN } from "react-native-worklets"; import { useSafeAreaInsets } from "react-native-safe-area-context"; import { useCourseLayout } from "@/src/providers/courseLayoutProvider"; import CourseThreadList from "@/src/components/CourseThreadList"; +function clampSidebarFraction(fraction: number) { + "worklet"; + return Math.min(0.5, Math.max(0.2, fraction)); +} + +function CoursePaneDivider({ + paneWidth, + sidebarFraction, + visible, +}: { + paneWidth: SharedValue; + sidebarFraction: SharedValue; + visible: boolean; +}) { + const dragStartFraction = useSharedValue(0.4); + const [percent, setPercent] = useState(40); + + const dividerGesture = useMemo( + () => + Gesture.Pan() + .enabled(visible) + .minDistance(0) + .maxPointers(1) + .onBegin(() => { + dragStartFraction.set(sidebarFraction.get()); + }) + .onUpdate((event) => { + const width = paneWidth.get(); + if (width > 0) { + sidebarFraction.set( + clampSidebarFraction( + dragStartFraction.get() + event.translationX / width, + ), + ); + } + }) + .onFinalize(() => { + // React only needs the settled accessibility value, not every frame. + scheduleOnRN(setPercent, Math.round(sidebarFraction.get() * 100)); + }), + [dragStartFraction, paneWidth, sidebarFraction, visible], + ); + + return ( + + { + const action = event.nativeEvent.actionName; + if (action !== "increment" && action !== "decrement") return; + const fraction = clampSidebarFraction( + sidebarFraction.get() + (action === "increment" ? 0.05 : -0.05), + ); + sidebarFraction.set(fraction); + setPercent(Math.round(fraction * 100)); + }} + hitSlop={{ left: 10, right: 10 }} + className="items-center justify-center bg-black" + style={{ width: 24, display: visible ? "flex" : "none" }} + > + + + + ); +} + export default function CourseFrame({ children, header, @@ -14,88 +103,39 @@ export default function CourseFrame({ const { courseId, isWide, isFullscreen } = useCourseLayout(); const insets = useSafeAreaInsets(); const showCourseLayout = isWide && courseId !== null; - const [paneWidth, setPaneWidth] = useState(0); - const [sidebarFraction, setSidebarFraction] = useState(0.4); - const currentFraction = useRef(0.4); - const dragStartFraction = useRef(0.4); - - function resizeSidebar(fraction: number) { - const clamped = Math.min(0.5, Math.max(0.2, fraction)); - currentFraction.current = clamped; - setSidebarFraction(clamped); - } - - const dividerGesture = useMemo( - () => - // eslint-disable-next-line react-hooks/refs -- PanResponder stores these callbacks; refs are only read during gestures. - PanResponder.create({ - onStartShouldSetPanResponder: () => true, - onMoveShouldSetPanResponder: () => true, - onPanResponderGrant: () => { - dragStartFraction.current = currentFraction.current; - }, - onPanResponderMove: (_, gesture) => { - if (paneWidth > 0) { - resizeSidebar(dragStartFraction.current + gesture.dx / paneWidth); - } - }, - }), - [paneWidth], - ); + const paneWidth = useSharedValue(0); + const sidebarFraction = useSharedValue(0.4); + const sidebarStyle = useAnimatedStyle(() => ({ + width: `${sidebarFraction.get() * 100}%`, + })); return ( {showCourseLayout && header} setPaneWidth(event.nativeEvent.layout.width)} + onLayout={(event) => paneWidth.set(event.nativeEvent.layout.width)} > {showCourseLayout && ( - - - - )} - {showCourseLayout && !isFullscreen && ( - { - if (event.nativeEvent.actionName === "increment") - resizeSidebar(currentFraction.current + 0.05); - if (event.nativeEvent.actionName === "decrement") - resizeSidebar(currentFraction.current - 0.05); - }} - hitSlop={{ left: 10, right: 10 }} - className="items-center justify-center bg-black" - style={{ width: 24 }} > - - + + )} + {/* Keep this container and navigator mounted through every layout change. */} { + counts.sidebarMounts++; + }, []); + return React.createElement("Sidebar"); + } + + function Navigator() { + React.useEffect(() => { + counts.navigatorMounts++; + }, []); + return React.createElement("Navigator"); + } + + function useSharedValue(initial) { + return React.useState(() => { + let value = initial; + return { + get: () => value, + set: (next) => { + value = next; + }, + }; + })[0]; + } + + const mocks = { + "react-native": { + View: "View", + Platform: { OS: "android" }, + PanResponder: { create: (handlers) => ({ panHandlers: handlers }) }, + }, + "react-native-safe-area-context": { useSafeAreaInsets: () => insets }, + "@/src/providers/courseLayoutProvider": { useCourseLayout: () => layout }, + "@/src/components/CourseThreadList": { __esModule: true, default: Sidebar }, + "react-native-gesture-handler": { + GestureDetector: ({ children }) => children, + Gesture: { + Pan: () => { + const handlers = {}; + const gesture = {}; + for (const name of ["onBegin", "onUpdate", "onFinalize"]) { + gesture[name] = (handler) => { + handlers[name] = handler; + return gesture; + }; + } + gesture.enabled = (enabled) => { + handlers.enabled = enabled; + return gesture; + }; + for (const name of ["minDistance", "maxPointers"]) { + gesture[name] = () => gesture; + } + gestures.push(handlers); + return gesture; + }, + }, + }, + "react-native-reanimated": { + __esModule: true, + default: { View: "AnimatedView" }, + useSharedValue, + useAnimatedStyle: (read) => ({ read }), + }, + "react-native-worklets": { + scheduleOnRN: (callback, ...args) => + scheduled.push(() => callback(...args)), + }, + }; + const filename = path.resolve("src/components/CourseFrame.tsx"); + const code = ts.transpileModule(fs.readFileSync(filename, "utf8"), { + compilerOptions: { + jsx: ts.JsxEmit.ReactJSX, + module: ts.ModuleKind.CommonJS, + esModuleInterop: true, + target: ts.ScriptTarget.ES2022, + }, + }).outputText; + const module = { exports: {} }; + vm.runInNewContext( + code, + { + exports: module.exports, + require: (name) => mocks[name] ?? require(name), + }, + { filename }, + ); + const Frame = module.exports.default; + const children = React.createElement(Navigator); + const header = React.createElement("Header"); + let renderer; + const render = () => + React.createElement( + React.Profiler, + { + id: "frame", + onRender: () => counts.commits++, + }, + React.createElement(Frame, { header }, children), + ); + act(() => { + renderer = create(render()); + }); + + const divider = () => + renderer.root.findByProps({ accessibilityRole: "adjustable" }); + const measure = (width) => + act(() => { + renderer.root + .findAllByType("View") + .find((node) => node.props.onLayout) + .props.onLayout({ nativeEvent: { layout: { width } } }); + }); + const begin = () => + act(() => { + if (gestures.length) gestures.at(-1).onBegin(); + else divider().props.onPanResponderGrant(); + }); + const move = (dx) => + act(() => { + if (gestures.length) gestures.at(-1).onUpdate({ translationX: dx }); + else divider().props.onPanResponderMove(null, { dx }); + }); + const finish = (success = true) => + act(() => { + gestures.at(-1)?.onFinalize({}, success); + while (scheduled.length) scheduled.shift()(); + }); + const fraction = () => { + const pane = renderer.root.findByProps({ + className: + "border-r border-gray-200 bg-white dark:border-neutral-700 dark:bg-black", + }); + const styles = [pane.props.style].flat(); + const width = styles + .map((style) => (style.read ? style.read().width : style.width)) + .find((value) => value !== undefined); + return Math.round(Number.parseFloat(width) * 1e10) / 1e12; + }; + return { + counts, + layout, + measure, + begin, + move, + finish, + fraction, + divider, + gestureEnabled: () => gestures.at(-1).enabled, + update: () => act(() => renderer.update(render())), + close: () => act(() => renderer.unmount()), + }; +} + +test("120 resize updates do not reconcile the frame or sidebar", (t) => { + const f = fixture(); + t.after(f.close); + f.measure(1000); + const before = { ...f.counts }; + f.measure(900); + f.measure(1000); + assert.equal(f.counts.commits, before.commits); + f.begin(); + for (let i = 1; i <= 120; i++) f.move(-i); + const dragCommits = f.counts.commits - before.commits; + const sidebarRenders = f.counts.sidebar - before.sidebar; + t.diagnostic(JSON.stringify({ dragCommits, sidebarRenders })); + assert.equal(dragCommits, 0); + assert.equal(sidebarRenders, 0); + assert.equal(f.fraction(), 0.28); + f.finish(); + assert.equal(f.counts.commits - before.commits, 1); + assert.equal(f.counts.sidebar - before.sidebar, 0); + assert.equal(f.divider().props.accessibilityValue.now, 28); +}); + +test("resize bounds, repeated drags, cancellation and accessibility share the live size", (t) => { + const f = fixture(); + t.after(f.close); + f.begin(); + f.move(100); + assert.equal(f.fraction(), 0.4, "ignore moves before layout is measured"); + f.finish(); + f.measure(1000); + f.begin(); + f.move(-1000); + assert.equal(f.fraction(), 0.2); + f.finish(false); + assert.equal(f.divider().props.accessibilityValue.now, 20); + act(() => + f.divider().props.onAccessibilityAction({ + nativeEvent: { actionName: "increment" }, + }), + ); + assert.equal(f.fraction(), 0.25); + f.measure(800); + f.begin(); + f.move(80); + assert.equal(f.fraction(), 0.35); + f.move(1000); + assert.equal(f.fraction(), 0.5); + f.finish(); + act(() => + f.divider().props.onAccessibilityAction({ + nativeEvent: { actionName: "increment" }, + }), + ); + assert.equal(f.fraction(), 0.5); + act(() => + f.divider().props.onAccessibilityAction({ + nativeEvent: { actionName: "decrement" }, + }), + ); + assert.equal(f.fraction(), 0.45); + assert.equal(f.divider().props.accessibilityValue.now, 45); +}); + +test("fullscreen and compact layouts preserve the navigator and resized pane", (t) => { + const f = fixture(); + t.after(f.close); + f.measure(1000); + f.begin(); + f.move(-100); + f.finish(); + f.layout.isFullscreen = true; + f.update(); + assert.equal(f.divider().props.style.display, "none"); + assert.equal(f.gestureEnabled(), false); + assert.equal(f.counts.sidebarMounts, 1); + f.layout.isFullscreen = false; + f.update(); + assert.equal(f.gestureEnabled(), true); + assert.equal(f.divider().props.accessibilityValue.now, 30); + assert.equal(f.fraction(), 0.3); + f.layout.isWide = false; + f.update(); + assert.equal(f.divider().props.style.display, "none"); + assert.equal(f.gestureEnabled(), false); + f.layout.isWide = true; + f.update(); + assert.equal(f.counts.navigatorMounts, 1); + assert.equal(f.fraction(), 0.3); + f.layout.courseId = 2; + f.update(); + assert.equal(f.counts.sidebarMounts, 3); + assert.equal(f.counts.navigatorMounts, 1); +});