From c827bf3536faf3f3a783f5d1fc35e9f58e86673a Mon Sep 17 00:00:00 2001 From: Bruno Aggierni Date: Mon, 7 Sep 2026 15:56:02 +0100 Subject: [PATCH 1/4] docs: add interactive Sandpack examples to guides --- docs/guides/accessibility-labels.md | 88 ++++- docs/guides/event-callbacks.md | 81 +++- docs/guides/focus-boundaries.md | 90 ++++- docs/guides/focus-hierarchy.md | 97 ++++- docs/guides/programmatic-focus.md | 76 +++- docs/guides/quick-start.md | 59 ++- docs/guides/recipes.md | 553 ++++++++++++++++------------ docs/guides/rtl-support.md | 62 ++++ 8 files changed, 873 insertions(+), 233 deletions(-) diff --git a/docs/guides/accessibility-labels.md b/docs/guides/accessibility-labels.md index 3d342fe..259d356 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,92 @@ 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..64c926a 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,85 @@ 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..58bb4a8 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,94 @@ 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..b8ef478 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,96 @@ 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..44bc09e 100644 --- a/docs/guides/programmatic-focus.md +++ b/docs/guides/programmatic-focus.md @@ -18,6 +18,80 @@ 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 +136,7 @@ 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..a41c7b2 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,9 +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(); }, []); +return ( + + +
+
+
+); +} + +export default function App() { +return ( + +
+ +
+); +} + +``` +
+ ## What Happens Now 1. When `ButtonRow` mounts, `focusSelf()` routes focus to the first child `Button`. 2. Pressing the right arrow key moves focus to the next `Button`. 3. The focused `Button` renders with a blue background; unfocused ones render dark. 4. Pressing enter on a focused `Button` would trigger `onEnterPress` if you configured it. +``` diff --git a/docs/guides/recipes.md b/docs/guides/recipes.md index 3cbb827..48782f0 100644 --- a/docs/guides/recipes.md +++ b/docs/guides/recipes.md @@ -12,38 +12,41 @@ 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 { useFocusable, FocusContext, - FocusableComponentLayout + FocusableComponentLayout, } 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,39 +54,25 @@ 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) => ( - + ))}
@@ -91,7 +80,29 @@ function ContentRow({ title, items }: ContentRowProps) { ); } + +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 ( + +
+ +
+
+ ); +} ``` + --- @@ -99,18 +110,23 @@ function ContentRow({ title, items }: ContentRowProps) { 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 + 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} @@ -133,25 +149,23 @@ function Sidebar() { focusKey: 'SIDEBAR', trackChildren: true, isFocusBoundary: true, - focusBoundaryDirections: ['left'] + focusBoundaryDirections: ['left'], }); - useEffect(() => { - focusSelf(); - }, []); + useEffect(() => { focusSelf(); }, [focusSelf]); return (
{MENU_ITEMS.map((label) => ( @@ -161,7 +175,17 @@ function Sidebar() { ); } + +export default function App() { + return ( +
+ +
Main content area
+
+ ); +} ``` + --- @@ -169,41 +193,38 @@ function Sidebar() { 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, and returns to the trigger on close (`autoRestoreFocus`). + + +```tsx +import React, { useEffect, useState } from 'react'; +import { init, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; import { useFocusable, - FocusContext + 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)} + /> + )} +
+ ); +} ``` +
--- @@ -275,74 +309,81 @@ function ConfirmModal({ message, onConfirm, onCancel }: ConfirmModalProps) { 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 (
-
+
); } + +export default function App() { + const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'ROOT' }); + useEffect(() => { focusSelf(); }, [focusSelf]); + return ( + +
+

Hold ← / → to seek

+ +
+
+ ); +} ``` + --- @@ -350,30 +391,30 @@ function SeekBar() { When a new item is added to a list, focus it immediately. -```typescript -import React, { useState, useEffect } from 'react'; -import { - setFocus, - doesFocusableExist -} from '@noriginmedia/norigin-spatial-navigation-core'; +**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 + 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 +430,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,14 +451,24 @@ function DynamicList() { ))}
-
); } + +export default function App() { + useEffect(() => { setFocus('DYNAMIC_LIST'); }, []); + return ( +
+ +
+ ); +} ``` + --- @@ -426,33 +476,54 @@ function DynamicList() { Save focus state when navigating forward, and restore it when going back. -```typescript +**Try it live:** focus a row and open the detail screen; pressing **Back** restores focus to where you left off. (The buttons are made focusable here so you can drive it with the keyboard.) + + +```tsx import React, { useState, useEffect } from 'react'; -import { - getCurrentFocusKey, - setFocus -} from '@noriginmedia/norigin-spatial-navigation-core'; +import { init, getCurrentFocusKey, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; import { useFocusable, - FocusContext + FocusContext, } from '@noriginmedia/norigin-spatial-navigation-react'; -// Simple focus history stack +init({ debug: false, visualDebug: false }); + const focusHistory: string[] = []; -function Screen({ - screenKey, - children -}: { - screenKey: string; - children: React.ReactNode; +function Tile({ focusKey, label, autoFocus, onEnterPress }: { + focusKey: string; + label: string; + autoFocus?: boolean; + onEnterPress?: () => void; }) { - const { ref, focusKey, focusSelf } = useFocusable({ focusKey: screenKey }); + 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(() => { - focusSelf(); - }, [screenKey]); + if (autoFocus) focusSelf(); + }, [autoFocus, focusSelf]); + return ( +
+ {label} +
+ ); +} + +function Screen({ screenKey, children }: { + screenKey: string; + children: React.ReactNode; +}) { + const { ref, focusKey } = useFocusable({ focusKey: screenKey }); return (
{children}
@@ -460,11 +531,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,27 +543,34 @@ 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.

+
+ )} +
); } ``` +
--- @@ -501,46 +578,65 @@ function App() { 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 { useFocusable, FocusContext, - FocusableComponentLayout + FocusableComponentLayout, } from '@noriginmedia/norigin-spatial-navigation-react'; -const ROWS = ['Recommended', 'Movies', 'Series', 'TV Channels', 'Sport']; +init({ debug: false, visualDebug: false }); -function ContentRow({ - title, - onFocus -}: { +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, 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,33 +648,38 @@ function ContentRow({ function Page() { const pageRef = useRef(null); - const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'PAGE' }); - - const onRowFocus = useCallback((layout: FocusableComponentLayout) => { - pageRef.current?.scrollTo({ top: layout.y, behavior: 'smooth' }); - }, []); + const { ref, focusKey } = useFocusable({ focusKey: 'PAGE' }); - useEffect(() => { - focusSelf(); + const onCardFocus = useCallback((layout: FocusableComponentLayout) => { + const container = pageRef.current; + const node = layout.node; + if (!container || !node) return; + + + const top = + node.getBoundingClientRect().top - + container.getBoundingClientRect().top + + container.scrollTop - + 40; + + container.scrollTo({ top, behavior: 'smooth' }); }, []); return ( -
-
- {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..c50877b 100644 --- a/docs/guides/rtl-support.md +++ b/docs/guides/rtl-support.md @@ -62,6 +62,68 @@ 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. From b24df7799b00f812fa16b57d12f8f9885b155b54 Mon Sep 17 00:00:00 2001 From: Bruno Aggierni Date: Mon, 7 Sep 2026 16:03:25 +0100 Subject: [PATCH 2/4] docs: add interactive Sandpack examples to guides --- docs/guides/accessibility-labels.md | 111 +++++-- docs/guides/event-callbacks.md | 45 ++- docs/guides/focus-boundaries.md | 87 ++++-- docs/guides/focus-hierarchy.md | 27 +- docs/guides/programmatic-focus.md | 73 ++++- docs/guides/quick-start.md | 69 +++-- docs/guides/recipes.md | 435 +++++++++++++++++++--------- docs/guides/rtl-support.md | 43 ++- 8 files changed, 633 insertions(+), 257 deletions(-) diff --git a/docs/guides/accessibility-labels.md b/docs/guides/accessibility-labels.md index 259d356..0ba2b9a 100644 --- a/docs/guides/accessibility-labels.md +++ b/docs/guides/accessibility-labels.md @@ -97,44 +97,69 @@ 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, + 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), + 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 }); +function ContentRow({ + title, + rowKey, + assets +}: { + title: string; + rowKey: string; + assets: string[]; +}) { + const { ref, focusKey } = useFocusable({ + focusKey: rowKey, + accessibilityLabel: title + }); return (

{title}

- {assets.map((a) => )} + {assets.map((a) => ( + + ))}
@@ -142,12 +167,23 @@ function ContentRow({ title, rowKey, assets }: { title: string; rowKey: string; } function Content() { - const { ref, focusKey } = useFocusable({ focusKey: 'CONTENT', accessibilityLabel: 'Recommended' }); + const { ref, focusKey } = useFocusable({ + focusKey: 'CONTENT', + accessibilityLabel: 'Recommended' + }); return (
- - + +
); @@ -159,25 +195,42 @@ export default function App() { 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 () => { + 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 @@ -202,16 +255,18 @@ This matches how a screen reader treats `aria-label` on `role="region"`: the reg Given this focus tree: ``` + Menu (label="Main Menu") - ├── Home (label="Home") - └── Library (label="Library") +├── Home (label="Home") +└── Library (label="Library") Content (label="Recommended") - ├── Row 1 (label="Movies") - │ ├── Asset 1 (label="Inception") - │ └── Asset 2 (label="Interstellar") - └── Row 2 (label="Series") - ├── Asset 3 (label="Breaking Bad") - └── Asset 4 (label="The Wire") +├── Row 1 (label="Movies") +│ ├── Asset 1 (label="Inception") +│ └── Asset 2 (label="Interstellar") +└── Row 2 (label="Series") +├── Asset 3 (label="Breaking Bad") +└── Asset 4 (label="The Wire") + ``` Navigating `Home` → `Inception` → `Interstellar` → `Breaking Bad` produces: diff --git a/docs/guides/event-callbacks.md b/docs/guides/event-callbacks.md index 64c926a..0ea55c9 100644 --- a/docs/guides/event-callbacks.md +++ b/docs/guides/event-callbacks.md @@ -269,12 +269,13 @@ Without `extraProps`, you would need to wrap each callback in `useCallback` with **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, + FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; init({ debug: false, visualDebug: false }); @@ -291,19 +292,24 @@ function Item({ id, title, isNew, log }: ItemProps) { extraProps: { id, title, isNew, log }, onFocus: (layout, props) => props.log(`onFocus → ${props.id}`), onEnterPress: (props) => - props.log(`onEnterPress → ${props.title} (isNew: ${props.isNew})`), + props.log(`onEnterPress → ${props.title} (isNew: ${props.isNew})`) }); return (
- {title}{isNew ? ' •' : ''} + {title} + {isNew ? ' •' : ''}
); } @@ -311,7 +317,7 @@ function Item({ id, title, isNew, log }: ItemProps) { const ITEMS = [ { id: 'a', title: 'Home', isNew: false }, { id: 'b', title: 'Movies', isNew: true }, - { id: 'c', title: 'Series', isNew: false }, + { id: 'c', title: 'Series', isNew: false } ]; export default function App() { @@ -319,11 +325,16 @@ export default function App() { const log = (msg: string) => setLogs((prev) => [msg, ...prev].slice(0, 6)); const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'ROOT' }); - useEffect(() => { focusSelf(); }, [focusSelf]); + useEffect(() => { + focusSelf(); + }, [focusSelf]); return ( -
+
{ITEMS.map((it) => ( @@ -332,10 +343,17 @@ export default function App() {

Arrow = onFocus, Enter = onEnterPress:

-
+        
           {logs.length ? logs.join('\n') : '(events will appear here)'}
         
@@ -343,6 +361,7 @@ export default function App() { ); } ``` + --- diff --git a/docs/guides/focus-boundaries.md b/docs/guides/focus-boundaries.md index 58bb4a8..6f94975 100644 --- a/docs/guides/focus-boundaries.md +++ b/docs/guides/focus-boundaries.md @@ -132,25 +132,36 @@ When the modal mounts, it calls `focusSelf()` to claim focus. Because `isFocusBo **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, + FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; init({ debug: false, visualDebug: false }); -function ConfirmButton({ label, onPress }: { label: string; onPress: () => void }) { +function ConfirmButton({ + label, + onPress +}: { + label: string; + onPress: () => void; +}) { const { ref, focused } = useFocusable({ onEnterPress: () => onPress() }); return ( - - - + + + +
); } ``` +
--- @@ -136,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 a41c7b2..b19c8f2 100644 --- a/docs/guides/quick-start.md +++ b/docs/guides/quick-start.md @@ -102,57 +102,61 @@ 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 { + 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} -
-); + display: 'inline-block' + }} + > + {label} +
+ ); } function ButtonRow() { -const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'BUTTON_ROW' }); -useEffect(() => { focusSelf(); }, []); -return ( - - -
-
-
-); + const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'BUTTON_ROW' }); + useEffect(() => { + focusSelf(); + }, []); + return ( + +
+
+
+ ); } export default function App() { -return ( - -
- -
-); + return ( +
+ +
+ ); } - ``` + ## What Happens Now @@ -161,4 +165,7 @@ return ( 2. Pressing the right arrow key moves focus to the next `Button`. 3. The focused `Button` renders with a blue background; unfocused ones render dark. 4. Pressing enter on a focused `Button` would trigger `onEnterPress` if you configured it. + +``` + ``` diff --git a/docs/guides/recipes.md b/docs/guides/recipes.md index 48782f0..68e81d4 100644 --- a/docs/guides/recipes.md +++ b/docs/guides/recipes.md @@ -15,18 +15,23 @@ A content row that automatically scrolls when a child card gains focus. This is **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 { useFocusable, FocusContext, - FocusableComponentLayout, + FocusableComponentLayout } from '@noriginmedia/norigin-spatial-navigation-react'; init({ debug: false, visualDebug: false }); -function Card({ title, color, onFocus }: { +function Card({ + title, + color, + onFocus +}: { title: string; color: string; onFocus: (layout: FocusableComponentLayout) => void; @@ -46,7 +51,7 @@ function Card({ title, color, onFocus }: { alignItems: 'center', justifyContent: 'center', color: 'white', - fontSize: 16, + fontSize: 16 }} > {title} @@ -54,7 +59,10 @@ function Card({ title, color, onFocus }: { ); } -function ContentRow({ title, items }: { +function ContentRow({ + title, + items +}: { title: string; items: { title: string; color: string }[]; }) { @@ -72,7 +80,12 @@ function ContentRow({ title, items }: {
{items.map((item) => ( - + ))}
@@ -87,21 +100,27 @@ const ITEMS = [ { title: 'Card 3', color: '#e0518a' }, { title: 'Card 4', color: '#3fb27f' }, { title: 'Card 5', color: '#d98b3a' }, - { title: 'Card 6', color: '#8a5cf6' }, + { title: 'Card 6', color: '#8a5cf6' } ]; export default function App() { const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'ROOT' }); - useEffect(() => { focusSelf(); }, [focusSelf]); + useEffect(() => { + focusSelf(); + }, [focusSelf]); return ( -
+
); } ``` + --- @@ -113,12 +132,13 @@ A sidebar that highlights when any of its items is focused, using `hasFocusedChi **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, + FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; init({ debug: false, visualDebug: false }); @@ -136,7 +156,7 @@ function MenuItem({ label }: { label: string }) { backgroundColor: focused ? '#6040a0' : 'transparent', borderRadius: 4, cursor: 'pointer', - fontSize: 18, + fontSize: 18 }} > {label} @@ -149,10 +169,12 @@ function Sidebar() { focusKey: 'SIDEBAR', trackChildren: true, isFocusBoundary: true, - focusBoundaryDirections: ['left'], + focusBoundaryDirections: ['left'] }); - useEffect(() => { focusSelf(); }, [focusSelf]); + useEffect(() => { + focusSelf(); + }, [focusSelf]); return ( @@ -165,7 +187,7 @@ function Sidebar() { transition: 'background-color 0.2s', display: 'flex', flexDirection: 'column', - gap: 8, + gap: 8 }} > {MENU_ITEMS.map((label) => ( @@ -178,13 +200,22 @@ function Sidebar() { export default function App() { return ( -
+
-
Main content area
+
+ Main content area +
); } ``` + --- @@ -196,17 +227,22 @@ A confirmation modal that prevents focus from reaching the content behind it. **Try it live:** open the dialog, then try to arrow away — focus stays trapped between Confirm/Cancel, and returns to the trigger on close (`autoRestoreFocus`). + ```tsx import React, { useEffect, useState } from 'react'; import { init, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; import { useFocusable, - FocusContext, + FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; init({ debug: false, visualDebug: false }); -function ModalButton({ label, primary, onPress }: { +function ModalButton({ + label, + primary, + onPress +}: { label: string; primary?: boolean; onPress: () => void; @@ -218,13 +254,19 @@ function ModalButton({ label, primary, onPress }: { onClick={onPress} style={{ padding: '12px 32px', - backgroundColor: focused ? (primary ? '#7150DA' : '#555') : (primary ? '#7e0ddb' : '#444'), + backgroundColor: focused + ? primary + ? '#7150DA' + : '#555' + : primary + ? '#7e0ddb' + : '#444', color: 'white', border: 'none', borderRadius: 6, fontSize: 16, cursor: 'pointer', - outline: focused ? '2px solid #42fdac' : 'none', + outline: focused ? '2px solid #42fdac' : 'none' }} > {label} @@ -232,7 +274,11 @@ function ModalButton({ label, primary, onPress }: { ); } -function ConfirmModal({ message, onConfirm, onCancel }: { +function ConfirmModal({ + message, + onConfirm, + onCancel +}: { message: string; onConfirm: () => void; onCancel: () => void; @@ -241,22 +287,42 @@ function ConfirmModal({ message, onConfirm, onCancel }: { focusKey: 'CONFIRM_MODAL', isFocusBoundary: true, trackChildren: true, - autoRestoreFocus: true, + autoRestoreFocus: true }); - useEffect(() => { focusSelf(); }, [focusSelf]); + useEffect(() => { + focusSelf(); + }, [focusSelf]); return ( -
+
-
-

{message}

+
+

+ {message} +

@@ -268,15 +334,23 @@ function ConfirmModal({ message, onConfirm, onCancel }: { } function TriggerButton({ onPress }: { onPress: () => void }) { - const { ref, focused } = useFocusable({ focusKey: 'TRIGGER', onEnterPress: () => onPress() }); + const { ref, focused } = useFocusable({ + focusKey: 'TRIGGER', + onEnterPress: () => onPress() + }); return (
@@ -460,14 +576,24 @@ function DynamicList() { } export default function App() { - useEffect(() => { setFocus('DYNAMIC_LIST'); }, []); + useEffect(() => { + setFocus('DYNAMIC_LIST'); + }, []); return ( -
+
); } ``` + --- @@ -479,19 +605,29 @@ Save focus state when navigating forward, and restore it when going back. **Try it live:** focus a row and open the detail screen; pressing **Back** restores focus to where you left off. (The buttons are made focusable here so you can drive it with the keyboard.) + ```tsx import React, { useState, useEffect } from 'react'; -import { init, getCurrentFocusKey, setFocus } from '@noriginmedia/norigin-spatial-navigation-core'; +import { + init, + getCurrentFocusKey, + setFocus +} from '@noriginmedia/norigin-spatial-navigation-core'; import { useFocusable, - FocusContext, + FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; init({ debug: false, visualDebug: false }); const focusHistory: string[] = []; -function Tile({ focusKey, label, autoFocus, onEnterPress }: { +function Tile({ + focusKey, + label, + autoFocus, + onEnterPress +}: { focusKey: string; label: string; autoFocus?: boolean; @@ -509,9 +645,13 @@ function Tile({ focusKey, label, autoFocus, onEnterPress }: { ref={ref} onClick={onEnterPress} style={{ - padding: '16px 20px', marginBottom: 8, borderRadius: 6, cursor: 'pointer', - color: 'white', backgroundColor: focused ? '#7150DA' : '#333', - outline: focused ? '2px solid #42fdac' : 'none', + padding: '16px 20px', + marginBottom: 8, + borderRadius: 6, + cursor: 'pointer', + color: 'white', + backgroundColor: focused ? '#7150DA' : '#333', + outline: focused ? '2px solid #42fdac' : 'none' }} > {label} @@ -519,7 +659,10 @@ function Tile({ focusKey, label, autoFocus, onEnterPress }: { ); } -function Screen({ screenKey, children }: { +function Screen({ + screenKey, + children +}: { screenKey: string; children: React.ReactNode; }) { @@ -549,7 +692,14 @@ export default function App() { }; return ( -
+
{screen === 'home' ? ( // `key` forces a clean remount so focus keys register from scratch. @@ -557,19 +707,31 @@ export default function App() { - + ) : (

Detail

- -

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

+ +

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

)}
); } ``` + --- @@ -581,6 +743,7 @@ A vertically scrolling page that auto-scrolls when the user navigates between ro **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'; @@ -595,91 +758,97 @@ 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; +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); - }, - }); +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]); +useEffect(() => { if (autoFocus) focusSelf(); }, [autoFocus, focusSelf]); - return ( -
- ); +); } function ContentRow({ title, onCardFocus, firstRow }: { - title: string; - onCardFocus: (layout: FocusableComponentLayout) => void; - firstRow?: boolean; +title: string; +onCardFocus: (layout: FocusableComponentLayout) => void; +firstRow?: boolean; }) { - const { ref, focusKey } = useFocusable(); - const scrollRef = useRef(null); - - return ( - -
-

{title}

-
-
- {Array.from({ length: 8 }, (_, i) => ( - - ))} -
-
-
-
- ); +const { ref, focusKey } = useFocusable(); +const scrollRef = useRef(null); + +return ( + + +
+

{title}

+
+
+{Array.from({ length: 8 }, (\_, i) => ( + +))} +
+
+
+
+); } function Page() { - const pageRef = useRef(null); - const { ref, focusKey } = useFocusable({ focusKey: 'PAGE' }); +const pageRef = useRef(null); +const { ref, focusKey } = useFocusable({ focusKey: 'PAGE' }); - const onCardFocus = useCallback((layout: FocusableComponentLayout) => { - const container = pageRef.current; - const node = layout.node; - if (!container || !node) return; +const onCardFocus = useCallback((layout: FocusableComponentLayout) => { +const container = pageRef.current; +const node = layout.node; +if (!container || !node) return; - const top = node.getBoundingClientRect().top - container.getBoundingClientRect().top + container.scrollTop - - 40; + 40; container.scrollTo({ top, behavior: 'smooth' }); - }, []); - return ( - -
-
- {ROWS.map((title, idx) => ( - - ))} -
-
-
- ); +}, []); + +return ( + + +
+
+{ROWS.map((title, idx) => ( + +))} +
+
+
+); } export default function App() { - return ; +return ; } + ``` + +``` diff --git a/docs/guides/rtl-support.md b/docs/guides/rtl-support.md index c50877b..83dc186 100644 --- a/docs/guides/rtl-support.md +++ b/docs/guides/rtl-support.md @@ -65,12 +65,13 @@ 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, + FocusContext } from '@noriginmedia/norigin-spatial-navigation-react'; init({ rtl: false, debug: false, visualDebug: false }); @@ -78,12 +79,21 @@ init({ rtl: false, debug: false, visualDebug: false }); function Item({ label }: { label: string }) { const { ref, focused } = useFocusable(); return ( -
+
{label}
); @@ -91,11 +101,15 @@ function Item({ label }: { label: string }) { function Row() { const { ref, focusKey, focusSelf } = useFocusable({ focusKey: 'ROW' }); - useEffect(() => { focusSelf(); }, [focusSelf]); + useEffect(() => { + focusSelf(); + }, [focusSelf]); return (
- {['1', '2', '3', '4', '5'].map((n) => )} + {['1', '2', '3', '4', '5'].map((n) => ( + + ))}
); @@ -110,7 +124,15 @@ export default function App() { }, [rtl]); return ( -
+