diff --git a/docs/guides/accessibility-labels.md b/docs/guides/accessibility-labels.md index 3d342fe..9bc1a89 100644 --- a/docs/guides/accessibility-labels.md +++ b/docs/guides/accessibility-labels.md @@ -71,7 +71,7 @@ function Asset({ title }: { title: string }) { }); return ( -
+
{title}
); @@ -94,6 +94,145 @@ function ContentRow({ title }: { title: string }) { } ``` +**Try it live:** navigate the assets with the arrow keys. The panel shows exactly what `onUtterText` receives — region labels are announced the first time focus enters a region, then only the leaf label while you stay inside it. + + + +```tsx +import React, { useEffect, useState } from 'react'; +import { init, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; +import { + useFocusable, + FocusContext +} from '@noriginmedia/norigin-spatial-navigation-react'; + +// The library calls onUtterText with the string to speak; forward it to React. + +let onUtter: ((text: string) => void) | null = null; +init({ + debug: false, + visualDebug: false, + onUtterText: (text) => onUtter?.(text) +}); + +function Asset({ title }: { title: string }) { + const { ref, focused } = useFocusable({ accessibilityLabel: title }); + return ( +
+ {title} +
+ ); +} + +function ContentRow({ + title, + rowKey, + assets +}: { + title: string; + rowKey: string; + assets: string[]; +}) { + const { ref, focusKey } = useFocusable({ + focusKey: rowKey, + accessibilityLabel: title + }); + return ( + +
+

{title}

+
+ {assets.map((a) => ( + + ))} +
+
+
+ ); +} + +function Content() { + const { ref, focusKey } = useFocusable({ + focusKey: 'CONTENT', + accessibilityLabel: 'Recommended' + }); + return ( + +
+ + +
+
+ ); +} + +export default function App() { + const [log, setLog] = useState([]); + + useEffect(() => { + onUtter = (text) => setLog((prev) => [text, ...prev].slice(0, 6)); + setFocus('CONTENT'); // initial focus, captured now that onUtter is wired up + return () => { + onUtter = null; + }; + }, []); + + return ( +
+ +

+ onUtterText output (what a TTS engine would speak): +

+
+        {log.length ? log.join('\n') : '(navigate to hear regions announced)'}
+      
+
+ ); +} +``` + +
+ ### 3. Disable native `aria-*` if needed If your app previously used `aria-label`, `role="region"`, or similar attributes on focusable elements, the browser (and any native screen reader running over it) may also try to announce them. When routing through `onUtterText`, strip or disable those native attributes on the same elements to avoid double-speaking. diff --git a/docs/guides/event-callbacks.md b/docs/guides/event-callbacks.md index 992507d..0ea55c9 100644 --- a/docs/guides/event-callbacks.md +++ b/docs/guides/event-callbacks.md @@ -257,7 +257,7 @@ function Item({ id, title, isNew }: ItemProps) { }); return ( -
+
{title}
); @@ -266,6 +266,104 @@ function Item({ id, title, isNew }: ItemProps) { Without `extraProps`, you would need to wrap each callback in `useCallback` with the relevant dependencies to avoid stale values. +**Try it live:** use the arrow keys to move between items (fires `onFocus`) and press Enter to select one (fires `onEnterPress`). Each callback is logged on screen, with the latest `extraProps` values. + + + +```tsx +import React, { useState, useEffect } from 'react'; +import { init } from '@noriginmedia/norigin-spatial-navigation-core'; +import { + useFocusable, + FocusContext +} from '@noriginmedia/norigin-spatial-navigation-react'; + +init({ debug: false, visualDebug: false }); + +interface ItemProps { + id: string; + title: string; + isNew: boolean; + log: (msg: string) => void; +} + +function Item({ id, title, isNew, log }: ItemProps) { + const { ref, focused } = useFocusable({ + extraProps: { id, title, isNew, log }, + onFocus: (layout, props) => props.log(`onFocus → ${props.id}`), + onEnterPress: (props) => + props.log(`onEnterPress → ${props.title} (isNew: ${props.isNew})`) + }); + + return ( +
+ {title} + {isNew ? ' •' : ''} +
+ ); +} + +const ITEMS = [ + { id: 'a', title: 'Home', isNew: false }, + { id: 'b', title: 'Movies', isNew: true }, + { id: 'c', title: 'Series', isNew: false } +]; + +export default function App() { + const [logs, setLogs] = useState([]); + const log = (msg: string) => setLogs((prev) => [msg, ...prev].slice(0, 6)); + + const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'ROOT' }); + useEffect(() => { + focusSelf(); + }, [focusSelf]); + + return ( + +
+
+ {ITEMS.map((it) => ( + + ))} +
+

+ Arrow = onFocus, Enter = onEnterPress: +

+
+          {logs.length ? logs.join('\n') : '(events will appear here)'}
+        
+
+
+ ); +} +``` + +
+ --- ## Cleanup in `onArrowRelease` diff --git a/docs/guides/focus-boundaries.md b/docs/guides/focus-boundaries.md index c058c24..6f94975 100644 --- a/docs/guides/focus-boundaries.md +++ b/docs/guides/focus-boundaries.md @@ -69,7 +69,7 @@ function ConfirmButton({ ref={ref} style={{ padding: '12px 24px', - backgroundColor: focused ? '#0066cc' : '#444', + backgroundColor: focused ? '#7150DA' : '#444', color: 'white', border: 'none', borderRadius: '4px' @@ -129,6 +129,141 @@ function Modal({ onConfirm, onCancel }: ModalProps) { When the modal mounts, it calls `focusSelf()` to claim focus. Because `isFocusBoundary: true`, pressing any arrow key keeps focus inside the modal. When the modal unmounts, `autoRestoreFocus` (enabled by default) returns focus to the previously focused component. +**Try it live:** open the dialog, then mash the arrow keys — focus is trapped between Confirm/Cancel and can't escape to the trigger behind it. Press Enter to close and focus returns to the button. + + + +```tsx +import React, { useEffect, useState } from 'react'; +import { init, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; +import { + useFocusable, + FocusContext +} from '@noriginmedia/norigin-spatial-navigation-react'; + +init({ debug: false, visualDebug: false }); + +function ConfirmButton({ + label, + onPress +}: { + label: string; + onPress: () => void; +}) { + const { ref, focused } = useFocusable({ onEnterPress: () => onPress() }); + return ( + + ); +} + +function Modal({ + onConfirm, + onCancel +}: { + onConfirm: () => void; + onCancel: () => void; +}) { + const { ref, focusKey, focusSelf } = useFocusable({ + focusKey: 'MODAL', + isFocusBoundary: true, + trackChildren: true + }); + + useEffect(() => { + focusSelf(); + }, [focusSelf]); + + return ( +
+ +
+

Are you sure?

+
+ + +
+
+
+
+ ); +} + +function OpenButton({ onPress }: { onPress: () => void }) { + const { ref, focused } = useFocusable({ + focusKey: 'OPEN', + onEnterPress: () => onPress() + }); + return ( + + ); +} + +export default function App() { + const [open, setOpen] = useState(false); + useEffect(() => { + if (!open) setFocus('OPEN'); + }, [open]); + return ( +
+ setOpen(true)} /> + {open && ( + setOpen(false)} + onCancel={() => setOpen(false)} + /> + )} +
+ ); +} +``` + +
+ --- ## Partial Boundary Example diff --git a/docs/guides/focus-hierarchy.md b/docs/guides/focus-hierarchy.md index 81b9f59..ebc6131 100644 --- a/docs/guides/focus-hierarchy.md +++ b/docs/guides/focus-hierarchy.md @@ -36,7 +36,7 @@ function Card({ title }: { title: string }) { const { ref, focused } = useFocusable(); return ( -
+
{title}
); @@ -147,7 +147,7 @@ function ContentCard({ title }: { title: string }) { width: '160px', height: '90px', backgroundColor: '#714ADD', - outline: focused ? '3px solid white' : 'none', + outline: focused ? '3px solid #42fdac' : 'none', borderRadius: '4px', display: 'flex', alignItems: 'center', @@ -199,3 +199,110 @@ In this example: - Arrow left/right navigates between the two containers. - Arrow up/down navigates within the active container. - `hasFocusedChild` highlights the active sidebar. + +**Try it live:** click into the preview and use the arrow keys. Notice how the sidebar +highlights while any of its items is focused (`hasFocusedChild`), and how focus moves +between the two sibling containers. + + + +```tsx +import React, { useEffect } from 'react'; +import { init, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; +import { + useFocusable, + FocusContext +} from '@noriginmedia/norigin-spatial-navigation-react'; + +init({ debug: false, visualDebug: false }); + +function MenuItem({ label }: { label: string }) { + const { ref, focused } = useFocusable(); + return ( +
+ {label} +
+ ); +} + +function Sidebar() { + const { ref, focusKey, hasFocusedChild } = useFocusable({ + focusKey: 'SIDEBAR', + trackChildren: true + }); + return ( + +
+ + + +
+
+ ); +} + +function Card({ title }: { title: string }) { + const { ref, focused } = useFocusable(); + return ( +
+ {title} +
+ ); +} + +function ContentArea() { + const { ref, focusKey } = useFocusable({ focusKey: 'CONTENT' }); + return ( + +
+ + + +
+
+ ); +} + +export default function App() { + useEffect(() => { + setFocus('SIDEBAR'); + }, []); + return ( +
+ + +
+ ); +} +``` + +
diff --git a/docs/guides/programmatic-focus.md b/docs/guides/programmatic-focus.md index 3a1d6a0..d11da14 100644 --- a/docs/guides/programmatic-focus.md +++ b/docs/guides/programmatic-focus.md @@ -18,6 +18,118 @@ In addition to automatic directional navigation, you can move focus manually fro Core **`setFocus`** and **`navigateByDirection`** are asynchronous because the engine may await layout from your `layoutAdapter`. Use **`await`** when something must run after focus or navigation completes. In `useEffect` or other fire-and-forget call sites, **`void setFocus(...)`** is a common way to satisfy linters that flag floating promises. +**Try it live:** navigate the grid with the arrow keys, or use the buttons to call `setFocus` and `navigateByDirection` programmatically — the current focus key (`getCurrentFocusKey`) updates live. + + + +```tsx +import React, { useEffect, useState } from 'react'; +import { + init, + setFocus, + navigateByDirection, + getCurrentFocusKey +} from '@noriginmedia/norigin-spatial-navigation-core'; +import { + useFocusable, + FocusContext +} from '@noriginmedia/norigin-spatial-navigation-react'; + +init({ debug: false, visualDebug: false }); + +function Tile({ focusKey, label }: { focusKey: string; label: string }) { + const { ref, focused } = useFocusable({ focusKey }); + return ( +
+ {label} +
+ ); +} + +function Grid() { + const { ref, focusKey } = useFocusable({ focusKey: 'GRID' }); + return ( + +
+ {['A', 'B', 'C', 'D', 'E', 'F'].map((k) => ( + + ))} +
+
+ ); +} + +export default function App() { + const [current, setCurrent] = useState('(none)'); + + // Set initial focus, then poll the current focus key so arrow navigation shows too. + useEffect(() => { + setFocus('tile-A'); + }, []); + useEffect(() => { + const id = setInterval( + () => setCurrent(getCurrentFocusKey() || '(none)'), + 150 + ); + return () => clearInterval(id); + }, []); + + const btn = { padding: '6px 12px', cursor: 'pointer' } as const; + + return ( +
+ +

+ Current focus: {current} +

+
+ + + + +
+
+ ); +} +``` + +
+ --- ## `setFocus(focusKey, focusDetails?)` @@ -62,7 +174,10 @@ function PlayButton() { const { ref, focused } = useFocusable({ focusKey: 'PLAY_BUTTON' }); return ( - ); diff --git a/docs/guides/quick-start.md b/docs/guides/quick-start.md index 23df9b2..b998bc0 100644 --- a/docs/guides/quick-start.md +++ b/docs/guides/quick-start.md @@ -35,7 +35,7 @@ function Button({ label }: { label: string }) { ref={ref} style={{ padding: '16px 32px', - backgroundColor: focused ? '#0066cc' : '#333', + backgroundColor: focused ? '#7150DA' : '#333', color: 'white', borderRadius: '4px', cursor: 'pointer' @@ -99,6 +99,66 @@ function App() { export default App; ``` +**Try it live:** + + + +```tsx +import { init } from '@noriginmedia/norigin-spatial-navigation-core'; +import { + useFocusable, + FocusContext +} from '@noriginmedia/norigin-spatial-navigation-react'; +import { useEffect } from 'react'; + +init({ debug: false, visualDebug: false }); + +function Button({ label }: { label: string }) { + const { ref, focused } = useFocusable(); + return ( +
+ {label} +
+ ); +} + +function ButtonRow() { + const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'BUTTON_ROW' }); + useEffect(() => { + focusSelf(); + }, [focusSelf]); + return ( + +
+
+
+ ); +} + +export default function App() { + return ( +
+ +
+ ); +} +``` + +
+ ## What Happens Now 1. When `ButtonRow` mounts, `focusSelf()` routes focus to the first child `Button`. diff --git a/docs/guides/recipes.md b/docs/guides/recipes.md index 3cbb827..5964e87 100644 --- a/docs/guides/recipes.md +++ b/docs/guides/recipes.md @@ -12,38 +12,46 @@ Common implementation patterns for TV and directional-navigation applications. A content row that automatically scrolls when a child card gains focus. This is the core pattern for Netflix-style content carousels. -```typescript -import React, { useCallback, useRef } from 'react'; +**Try it live:** focus a card and press the left/right arrows — the row scrolls to keep the focused card in view. + + + +```tsx +import React, { useCallback, useRef, useEffect } from 'react'; +import { init } from '@noriginmedia/norigin-spatial-navigation-core'; +import type { FocusableComponentLayout } from '@noriginmedia/norigin-spatial-navigation-core'; import { useFocusable, - FocusContext, - FocusableComponentLayout + FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; -interface CardProps { +init({ debug: false, visualDebug: false }); + +function Card({ + title, + color, + onFocus +}: { title: string; color: string; onFocus: (layout: FocusableComponentLayout) => void; -} - -function Card({ title, color, onFocus }: CardProps) { +}) { const { ref, focused } = useFocusable({ onFocus }); - return (
{title} @@ -51,32 +59,26 @@ function Card({ title, color, onFocus }: CardProps) { ); } -interface ContentRowProps { +function ContentRow({ + title, + items +}: { title: string; items: { title: string; color: string }[]; -} - -function ContentRow({ title, items }: ContentRowProps) { +}) { const scrollRef = useRef(null); const { ref, focusKey } = useFocusable(); const onCardFocus = useCallback((layout: FocusableComponentLayout) => { - // Scroll so the focused card is visible - scrollRef.current?.scrollTo({ - left: layout.x, - behavior: 'smooth' - }); + scrollRef.current?.scrollTo({ left: layout.x, behavior: 'smooth' }); }, []); return ( -
-

{title}

+
+

{title}

-
+
{items.map((item) => ( ); } + +const ITEMS = [ + { title: 'Card 1', color: '#714ADD' }, + { title: 'Card 2', color: '#4e8cff' }, + { title: 'Card 3', color: '#e0518a' }, + { title: 'Card 4', color: '#3fb27f' }, + { title: 'Card 5', color: '#d98b3a' }, + { title: 'Card 6', color: '#8a5cf6' } +]; + +export default function App() { + const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'ROOT' }); + useEffect(() => { + focusSelf(); + }, [focusSelf]); + return ( + +
+ +
+
+ ); +} ``` + + --- ## Recipe 2: Sidebar Menu with Active Highlight A sidebar that highlights when any of its items is focused, using `hasFocusedChild`. -```typescript +**Try it live:** press up/down to move between items — the whole sidebar tints while it holds focus (`hasFocusedChild`). + + + +```tsx import React, { useEffect } from 'react'; +import { init } from '@noriginmedia/norigin-spatial-navigation-core'; import { useFocusable, FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; +init({ debug: false, visualDebug: false }); + const MENU_ITEMS = ['Home', 'Movies', 'Series', 'Sports', 'Settings']; function MenuItem({ label }: { label: string }) { const { ref, focused } = useFocusable(); - return (
{label} @@ -138,20 +174,20 @@ function Sidebar() { useEffect(() => { focusSelf(); - }, []); + }, [focusSelf]); return (
{MENU_ITEMS.map((label) => ( @@ -161,30 +197,57 @@ function Sidebar() { ); } + +export default function App() { + return ( +
+ +
+ Main content area +
+
+ ); +} ``` + + --- ## Recipe 3: Modal Dialog with Trapped Focus A confirmation modal that prevents focus from reaching the content behind it. -```typescript -import React, { useEffect } from 'react'; +**Try it live:** open the dialog, then try to arrow away — focus stays trapped between Confirm/Cancel. On close, `App` calls `setFocus('TRIGGER')` to return focus to the trigger. + + + +```tsx +import React, { useEffect, useState } from 'react'; +import { init, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; import { useFocusable, FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; -interface ModalButtonProps { +init({ debug: false, visualDebug: false }); + +function ModalButton({ + label, + primary, + onPress +}: { label: string; primary?: boolean; onPress: () => void; -} - -function ModalButton({ label, primary, onPress }: ModalButtonProps) { +}) { const { ref, focused } = useFocusable({ onEnterPress: () => onPress() }); - return ( + ); +} + +export default function App() { + const [open, setOpen] = useState(false); + useEffect(() => { + if (!open) setFocus('TRIGGER'); + }, [open]); + return ( +
+ setOpen(true)} /> + {open && ( + setOpen(false)} + onCancel={() => setOpen(false)} + /> + )} +
+ ); +} ``` +
+ --- ## Recipe 4: Progress Bar with Continuous Arrow Key Hold A seek bar that advances continuously while the right arrow key is held, and stops when released. -```typescript +**Try it live:** focus the bar, then hold the left/right arrow — the fill advances continuously and stops on release (`onArrowPress` / `onArrowRelease`). + + + +```tsx import React, { useEffect, useRef, useState } from 'react'; -import { useFocusable } from '@noriginmedia/norigin-spatial-navigation-react'; +import { init } from '@noriginmedia/norigin-spatial-navigation-core'; +import { + useFocusable, + FocusContext +} from '@noriginmedia/norigin-spatial-navigation-react'; + +init({ debug: false, visualDebug: false }); function SeekBar() { const [percent, setPercent] = useState(0); - const timerRef = useRef(null); + const timerRef = useRef | null>(null); const { ref, focused } = useFocusable({ onArrowPress: (direction) => { if (direction === 'right' && timerRef.current === null) { - timerRef.current = setInterval(() => { - setPercent((p) => Math.min(p + 5, 100)); - }, 100); + timerRef.current = setInterval( + () => setPercent((p) => Math.min(p + 5, 100)), + 100 + ); } if (direction === 'left' && timerRef.current === null) { - timerRef.current = setInterval(() => { - setPercent((p) => Math.max(p - 5, 0)); - }, 100); + timerRef.current = setInterval( + () => setPercent((p) => Math.max(p - 5, 0)), + 100 + ); } - // Return false to prevent navigating away while seeking if (direction === 'left' || direction === 'right') return false; return true; }, - onArrowRelease: (direction) => { if (direction === 'left' || direction === 'right') { - clearInterval(timerRef.current); + if (timerRef.current) clearInterval(timerRef.current); timerRef.current = null; } } }); - // Clean up on unmount - useEffect(() => { - return () => { - if (timerRef.current !== null) { - clearInterval(timerRef.current); - timerRef.current = null; - } - }; - }, []); + useEffect( + () => () => { + if (timerRef.current) clearInterval(timerRef.current); + timerRef.current = null; + }, + [] + ); return (
@@ -334,46 +455,79 @@ function SeekBar() { style={{ width: `${percent}%`, height: '100%', - backgroundColor: focused ? 'deepskyblue' : 'dodgerblue', - borderRadius: '10px', + backgroundColor: focused ? '#C64495' : '#7150DA', + borderRadius: 10, transition: 'background-color 0.15s' }} />
); } + +export default function App() { + const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'ROOT' }); + useEffect(() => { + focusSelf(); + }, [focusSelf]); + return ( + +
+

Hold ← / → to seek

+ +
+
+ ); +} ``` +
+ --- ## Recipe 5: Focusing a Dynamically Added Item When a new item is added to a list, focus it immediately. -```typescript +**Try it live:** navigate the items with up/down, then click **Add Item** — focus jumps to the freshly mounted row once it exists (`doesFocusableExist` + `setFocus`). + + + +```tsx import React, { useState, useEffect } from 'react'; import { + init, setFocus, doesFocusableExist } from '@noriginmedia/norigin-spatial-navigation-core'; - import { useFocusable, FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; +init({ debug: false, visualDebug: false }); + function ListItem({ id }: { id: string }) { const { ref, focused } = useFocusable({ focusKey: `item-${id}` }); - return (
Item {id} @@ -389,15 +543,14 @@ function DynamicList() { const addItem = () => { const newId = String(items.length + 1); setItems((prev) => [...prev, newId]); - setPendingFocusId(newId); // remember to focus after render + setPendingFocusId(newId); }; - // Focus the new item once it has mounted useEffect(() => { if (pendingFocusId !== null) { - const focusKey = `item-${pendingFocusId}`; - if (doesFocusableExist(focusKey)) { - setFocus(focusKey); + const key = `item-${pendingFocusId}`; + if (doesFocusableExist(key)) { + setFocus(key); setPendingFocusId(null); } } @@ -411,24 +564,52 @@ function DynamicList() { ))}
-
); } + +export default function App() { + useEffect(() => { + setFocus('DYNAMIC_LIST'); + }, []); + return ( +
+ +
+ ); +} ``` + + --- ## Recipe 6: Back Navigation with Focus Memory Save focus state when navigating forward, and restore it when going back. -```typescript +**Try it live:** move to any row and press Enter to open the detail screen, then press Enter on **Back**: focus returns to the row you came from. + + + +```tsx import React, { useState, useEffect } from 'react'; import { + init, getCurrentFocusKey, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; @@ -437,9 +618,47 @@ import { FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; -// Simple focus history stack +init({ debug: false, visualDebug: false }); + const focusHistory: string[] = []; +function Tile({ + focusKey, + label, + autoFocus, + onEnterPress +}: { + focusKey: string; + label: string; + autoFocus?: boolean; + onEnterPress?: () => void; +}) { + const { ref, focused, focusSelf } = useFocusable({ focusKey, onEnterPress }); + + // Claim focus as soon as this tile mounts (e.g. the Back button on a new screen). + useEffect(() => { + if (autoFocus) focusSelf(); + }, [autoFocus, focusSelf]); + + return ( +
+ {label} +
+ ); +} + function Screen({ screenKey, children @@ -447,12 +666,7 @@ function Screen({ screenKey: string; children: React.ReactNode; }) { - const { ref, focusKey, focusSelf } = useFocusable({ focusKey: screenKey }); - - useEffect(() => { - focusSelf(); - }, [screenKey]); - + const { ref, focusKey } = useFocusable({ focusKey: screenKey }); return (
{children}
@@ -460,11 +674,10 @@ function Screen({ ); } -function App() { +export default function App() { const [screen, setScreen] = useState<'home' | 'detail'>('home'); const navigateToDetail = () => { - // Save where we are before navigating away focusHistory.push(getCurrentFocusKey()); setScreen('detail'); }; @@ -473,74 +686,160 @@ function App() { setScreen('home'); const previousKey = focusHistory.pop(); if (previousKey) { - // Restore focus after the previous screen re-mounts + // Restore focus to where we were, once the home screen has re-mounted. setTimeout(() => setFocus(previousKey), 0); } }; - if (screen === 'detail') { - return ( - - -

Detail content here

-
- ); - } - return ( - - - +
+ {screen === 'home' ? ( + // `key` forces a clean remount so focus keys register from scratch. + +

Home

+ + + +
+ ) : ( + +

Detail

+ +

+ Press Enter on Back — focus returns to where you were. +

+
+ )} +
); } ``` +
+ --- ## Recipe 7: Vertical Scrolling Page with Multiple Rows A vertically scrolling page that auto-scrolls when the user navigates between rows. -```typescript +**Try it live:** press up/down to move between rows — the page scrolls vertically to keep the focused row in view (`onFocus` layout + `scrollTo`). + + + +```tsx import React, { useCallback, useRef, useEffect } from 'react'; +import { init } from '@noriginmedia/norigin-spatial-navigation-core'; +import type { FocusableComponentLayout } from '@noriginmedia/norigin-spatial-navigation-core'; import { useFocusable, - FocusContext, - FocusableComponentLayout + FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; -const ROWS = ['Recommended', 'Movies', 'Series', 'TV Channels', 'Sport']; +init({ debug: false, visualDebug: false }); + +const ROWS = [ + 'Recommended', + 'Movies', + 'Series', + 'TV Channels', + 'Sport', + 'Clips', + 'Sports', + 'Continue Watching', + 'News', + 'Kids', + 'Action', + 'Drama' +]; + +function Card({ + rowScrollRef, + onCardFocus, + autoFocus +}: { + rowScrollRef: React.RefObject; + onCardFocus: (layout: FocusableComponentLayout) => void; + autoFocus?: boolean; +}) { + const { ref, focused, focusSelf } = useFocusable({ + onFocus: (layout) => { + rowScrollRef.current?.scrollTo({ + left: Math.max(layout.x - 8, 0), + behavior: 'smooth' + }); + onCardFocus(layout); + } + }); + + useEffect(() => { + if (autoFocus) focusSelf(); + }, [autoFocus, focusSelf]); + + return ( +
+ ); +} function ContentRow({ title, - onFocus + onCardFocus, + firstRow }: { title: string; - onFocus: (layout: FocusableComponentLayout) => void; + onCardFocus: (layout: FocusableComponentLayout) => void; + firstRow?: boolean; }) { - const { ref, focusKey } = useFocusable({ onFocus }); + const { ref, focusKey } = useFocusable(); const scrollRef = useRef(null); - const onCardFocus = useCallback((layout: FocusableComponentLayout) => { - scrollRef.current?.scrollTo({ left: layout.x, behavior: 'smooth' }); - }, []); - return ( -
-

{title}

+
+

{title}

-
+
{Array.from({ length: 8 }, (_, i) => ( -
))}
@@ -552,14 +851,20 @@ function ContentRow({ function Page() { const pageRef = useRef(null); - const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'PAGE' }); + const { ref, focusKey } = useFocusable({ focusKey: 'PAGE' }); - const onRowFocus = useCallback((layout: FocusableComponentLayout) => { - pageRef.current?.scrollTo({ top: layout.y, behavior: 'smooth' }); - }, []); + const onCardFocus = useCallback((layout: FocusableComponentLayout) => { + const container = pageRef.current; + const node = layout.node; + if (!container || !node) return; - useEffect(() => { - focusSelf(); + const top = + node.getBoundingClientRect().top - + container.getBoundingClientRect().top + + container.scrollTop - + 40; + + container.scrollTo({ top, behavior: 'smooth' }); }, []); return ( @@ -572,13 +877,24 @@ function Page() { backgroundColor: '#221c35' }} > -
- {ROWS.map((title) => ( - +
+ {ROWS.map((title, idx) => ( + ))}
); } + +export default function App() { + return ; +} ``` + + diff --git a/docs/guides/rtl-support.md b/docs/guides/rtl-support.md index a2ba6a8..83dc186 100644 --- a/docs/guides/rtl-support.md +++ b/docs/guides/rtl-support.md @@ -62,6 +62,91 @@ function App({ language }: { language: string }) { } ``` +**Try it live:** focus an item and press the arrows, then toggle the direction. In LTR, `ArrowRight` moves to a higher number; after switching to RTL, the layout flips and the same key moves the other way — with no change to the component code. + + + +```tsx +import React, { useEffect, useState } from 'react'; +import { init, updateRtl } from '@noriginmedia/norigin-spatial-navigation-core'; +import { + useFocusable, + FocusContext +} from '@noriginmedia/norigin-spatial-navigation-react'; + +init({ rtl: false, debug: false, visualDebug: false }); + +function Item({ label }: { label: string }) { + const { ref, focused } = useFocusable(); + return ( +
+ {label} +
+ ); +} + +function Row() { + const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'ROW' }); + useEffect(() => { + focusSelf(); + }, [focusSelf]); + return ( + +
+ {['1', '2', '3', '4', '5'].map((n) => ( + + ))} +
+
+ ); +} + +export default function App() { + const [rtl, setRtl] = useState(false); + + useEffect(() => { + updateRtl(rtl); + document.documentElement.dir = rtl ? 'rtl' : 'ltr'; + }, [rtl]); + + return ( +
+ + +
+ ); +} +``` + +
+ ## RTL and Focus Hierarchy RTL mode affects only the interpretation of arrow key directions. The focus hierarchy, `FocusContext`, boundaries, and all other features work identically. Your component code does not need to change.