### Install app dependencies
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Run this command in the source code directory to install dependencies. Installation can take several minutes.
```bash
npm install
```
--------------------------------
### Start the Vega Virtual Device
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Run this command to start the Vega Virtual Device at the command prompt.
```bash
vega virtual-device start
```
--------------------------------
### useFocusGuideEventHandler Example
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/focusGuide/README.md
Use this hook to listen for TV remote events and update state. The handler receives an event object with details about the event.
```jsx
import React, { useState } from 'react';
import { Text, View } from 'react-native';
import { useFocusGuideEventHandler } from '@AppServices/focusGuide';
const TVRemoteHandler = () => {
const [lastEventType, setLastEventType] = useState(null);
const myTVEventHandler = (evt) => {
if (evt && evt.eventType) {
setLastEventType(evt.eventType);
}
};
useFocusGuideEventHandler(myTVEventHandler);
return (
Press a button on the TV remoteLast event: {lastEventType || 'None'}
);
};
```
--------------------------------
### Install @amazon-devices/keplerscript-netmgr-lib
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/netInfo/README.md
Install the required package to use the NetInfo Service. This is a prerequisite for the service to function.
```bash
npm install @amazon-devices/keplerscript-netmgr-lib
```
--------------------------------
### Run app on Vega Virtual Device (x86_64)
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Install and launch the app on the Vega Virtual Device for x86_64-based devices.
```bash
vega run-app build/x86_64-release/keplertvinterfaces_x86_64.vpkg
```
--------------------------------
### Example .env file
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/appConfig/README.md
Define environment variables in a .env file at the project root. Copy and adjust the existing .env.example file.
```bash
REACT_APP_DEBUG=true
REACT_APP_API_URL=https://api.example.com
```
--------------------------------
### makeListNavigationHintPropsGenerator usage example
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/a11y/README.md
Factory for hint props for components in order, wrapping `injectListNavigationHints`. The example shows creating a generator for vertical navigation guides and applying it to a button and a horizontal component group.
```typescript
// vertical navigation guides for screen sections
const screenA11yNavigationHintsGenerator =
makeListNavigationHintPropsGenerator(
[
btnChangeLanguageLabel,
t('my-screen-a11y-horiz-buttons-section-hint'),
],
{
directionLabels: {
previous: t('a11y-hint-direction-up'),
next: t('a11y-hint-direction-down'),
},
formatOtherItemNavigationHint: ({ item, direction }) =>
t('menu-item-use-direction-to-go-to-a11y-label')
.replace('', direction)
.replace('', item),
},
);
...
...
```
--------------------------------
### Run app on Vega Virtual Device (Mac M-series)
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Install and launch the app on the Vega Virtual Device for Mac M-series devices.
```bash
vega run-app build/aarch64-release/keplertvinterfaces_aarch64.vpkg
```
--------------------------------
### Example JSON translation file
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Example of a PUFF-J translation file with a direction field and resources. The 'test-id' resource uses a placeholder {username} for dynamic values.
```json
{
"dir" : "ltr",
"resources": {
"test-id": {
"note": "message for greeting",
"value": "Howdy {username}!"
},
"login-title": "Log In",
"login-password-label": "Password",
"login-email-label": "Email",
"login-button": "Log In"
}
}
```
--------------------------------
### Box usage example - MenuButton
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/components.md
Complete example of using the Box component in a TV application, including import and component definition.
```javascript
import { Box } from '@AppComponents/core/Box/Box';
export const MenuButton = ({ title, onPress, isActive }) => {
return (
{title}
);
};
```
--------------------------------
### Handle loading states properly
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Use usePosterRows to get loading flags. Render a footer with ActivityIndicator when fetching next page.
```javascript
const { rows, fetchNextPage, hasNextPage, isFetchingNextPage, isLoading } =
usePosterRows();
// Show loading indicator at the bottom while fetching more
const renderFooter = () => {
if (!isFetchingNextPage) return null;
return (
Loading more content...
);
};
```
--------------------------------
### Example usage of useFocusCollection
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/components.md
Example component using useFocusCollection to auto-focus the first item in a list on mount. Registers each item's ref and logs focus events.
```javascript
function MenuList({ items }) {
const { registerRef, focusItem } = useFocusCollection();
useEffect(() => {
// Auto-focus the first item when the list mounts
if (items.length > 0) {
focusItem(items[0].id);
}
}, []);
return (
{items.map(item => (
registerRef(item.id, ref)}
onFocus={() => console.log(`${item.title} focused`)}
>
{item.title}
))}
);
}
```
--------------------------------
### useFocusState Example
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/focusGuide/README.md
Use this hook to manage focus state in a component. It tracks whether a component is focused and provides handlers for focus and blur events.
```jsx
import React from 'react';
import { TextInput, Text, View } from 'react-native';
import { useFocusState } from '@AppServices/focusGuide';
const FocusExample = () => {
const { isFocused, handleBlur, handleFocus } = useFocusState({
initialState: false,
onFocus: () => console.log('Input focused'),
onBlur: () => console.log('Input blurred'),
});
return (
Is Focused: {isFocused ? 'Yes' : 'No'}
);
};
```
--------------------------------
### Run app on Vega OS Fire TV Stick
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Install and launch the app on your Vega OS Fire TV Stick.
```bash
vega run-app build/armv7-release/keplertvinterfaces_armv7.vpkg
```
--------------------------------
### Install @amazon-devices/react-native-device-info
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/deviceInfo/README.md
Install the required package to use the DeviceInfo service. Ensure the package is added to your project before using the service.
```bash
npm install @amazon-devices/react-native-device-info
```
--------------------------------
### Implement Grid with useFocusCollection
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
This example demonstrates how to use the useFocusCollection hook to manage focus within a FlatList grid. It includes registering item references and auto-focusing the first item upon mounting.
```javascript
import React, { useEffect } from 'react';
import {
View,
Text,
Pressable,
FlatList,
StyleSheet,
Dimensions,
} from 'react-native';
import { useFocusCollection } from '@AppSrc/hooks';
const { width } = Dimensions.get('window');
const COLUMNS = 3;
const ITEM_WIDTH = (width - 80) / COLUMNS;
export const ContentGrid = ({ items, onItemSelect }) => {
const { registerRef, focusItem, getCurrentFocused } = useFocusCollection();
// Auto-focus the first item when the grid mounts
useEffect(() => {
if (items.length > 0) {
focusItem(`grid-item-${items[0].id}`);
}
}, [items, focusItem]);
const renderItem = ({ item, index }) => {
const itemId = `grid-item-${item.id}`;
const isFocused = getCurrentFocused() === itemId;
return (
registerRef(itemId, ref)}
style={[styles.gridItem, isFocused && styles.focusedGridItem]}
onPress={() => onItemSelect(item)}
onFocus={() => console.log(`Item ${item.title} focused`)}
>
{item.title}
);
};
return (
item.id.toString()}
numColumns={COLUMNS}
style={styles.grid}
contentContainerStyle={styles.gridContent}
/>
);
};
const styles = StyleSheet.create({
// Style definitions...
});
```
--------------------------------
### injectListNavigationHints usage example
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/a11y/README.md
Maps an array to items with accessibility hints for navigation. The example shows rendering a menu list with direction labels and custom hint formatting, using the `hints` array to set `accessibilityHint`.
```typescript
import { injectListNavigationHints } from '@AppServices/a11y';
{injectListNavigationHints(menuItems, {
directionLabels: {
previous: t('a11y-hint-direction-up'),
next: t('a11y-hint-direction-down'),
},
formatOtherItemNavigationHint: ({ item: { label }, direction }) =>
t('menu-item-use-direction-to-go-to-a11y-label')
.replace('', direction)
.replace('', label),
firstItemAdditionalHint: t(
'menu-item-use-direction-to-go-to-a11y-label',
)
.replace('', t('a11y-hint-direction-up'))
.replace(
'',
t('menu-wrapper-a11y-label-profile-avatar'),
),
lastItemAdditionalHint: t(
'menu-item-use-direction-to-go-to-a11y-label',
)
.replace('', t('a11y-hint-direction-down'))
.replace('', t('close-menu-button-a11y-label')),
}).map(({ item: { label, onPress, icon }, hints }) => (
))}
```
--------------------------------
### Install @amazon-devices/react-native-async-storage__async-storage
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/storage/README.md
Required package for the DeviceStorage service. Install via npm.
```bash
npm install @amazon-devices/react-native-async-storage__async-storage
```
--------------------------------
### OptimizedPosterGrid with viewability tracking
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Use this FlashList example to implement an advanced layout with viewability tracking for performance optimization. It overrides item layout for hero and row types, tracks visible rows, and passes visibility state to PosterRow. Requires usePosterRowsWithSkeletonPreload hook and getCardHeight helper.
```javascript
import React, { useCallback, useState } from 'react';
import { FlashList } from '@amazon-devices/shopify__flash-list';
import { usePosterRowsWithSkeletonPreload } from '@AppSrc/hooks/usePosterRows';
export const OptimizedPosterGrid = () => {
const [visibleRowIndices, setVisibleRowIndices] = useState>(new Set());
const {
rows,
fetchNextPage,
hasNextPage,
isFetchingNextPage
} = usePosterRowsWithSkeletonPreload();
// Custom layout override for different row types
const overrideItemLayout = useCallback((layout, item) => {
if (item.type === 'hero') {
layout.size = 895; // Hero carousel height
} else {
// Calculate row height based on card size and layout
const cardHeight = getCardHeight(item.layoutConfig.size, item.layoutConfig.direction);
layout.size = cardHeight + 169; // Add padding and margins
}
}, []);
// Track which rows are currently visible for optimization
const handleViewableItemsChanged = useCallback(({ viewableItems }) => {
const newVisible = new Set();
for (const vi of viewableItems) {
if (vi.item.type === 'row') {
newVisible.add(vi.item.rowIndex);
}
}
setVisibleRowIndices(newVisible);
}, []);
const renderItem = useCallback(({ item }) => {
if (item.type === 'hero') {
return ;
}
return (
);
}, [visibleRowIndices]);
return (
item.type === 'hero' ? 'hero-carousel' : `row-${item.rowIndex}`
}
getItemType={(item) => item.type}
overrideItemLayout={overrideItemLayout}
onEndReached={() => hasNextPage && fetchNextPage()}
onEndReachedThreshold={0.5}
onViewableItemsChanged={handleViewableItemsChanged}
viewabilityConfig={{
itemVisiblePercentThreshold: 20,
minimumViewTime: 100,
}}
removeClippedSubviews={true}
drawDistance={Number.MAX_SAFE_INTEGER}
/>
);
};
```
--------------------------------
### Prioritize Image Loading Based on Context
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Calculates a priority level based on focus, visibility, next row, and scroll direction. Default priority is 3, focused items get 1, visible items get 2, and next row when scrolling down gets 2. Returns the prefetch call with the computed priority.
```javascript
const prioritizeImageLoading = (imageUrl, context) => {
const { isFocused, isVisible, isNextRow, userScrollDirection } = context;
let priority = 3; // Default priority
if (isFocused) {
priority = 1; // Highest priority for focused items
} else if (isVisible) {
priority = 2; // High priority for visible items
} else if (isNextRow && userScrollDirection === 'down') {
priority = 2; // Prefetch next row if scrolling down
}
return prefetch(imageUrl, priority);
};
```
--------------------------------
### Good focus styling example
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/components.md
Provides a StyleSheet example for clear visual focus indicators. The buttonFocused style uses a contrasting background, scale transform, and border to make the focused state highly visible.
```javascript
// Example of good focus styling
const styles = StyleSheet.create({
button: {
padding: 12,
backgroundColor: 'rgba(0, 0, 0, 0.5)',
borderRadius: 6,
},
buttonFocused: {
backgroundColor: '#0078D7',
transform: [{ scale: 1.1 }],
borderWidth: 2,
borderColor: 'white',
},
});
```
--------------------------------
### useTVFocus hook example
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Returns the TVFocus context, throwing an error if used outside a TVFocusProvider. Access the focus management system through this hook.
```javascript
export const useTVFocus = (): TVFocusContextType => {
const context = useContext(TVFocusContext);
if (!context) {
throw new Error('useTVFocus must be used within a TVFocusProvider');
}
return context;
};
```
--------------------------------
### Example usage of useFocusManager
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/components.md
Example component using useFocusManager to auto-focus a button and log focus changes. Attaches ref to TouchableOpacity and applies conditional styles based on isFocused.
```javascript
function FeaturedButton({ onPress }) {
const { ref, isFocused } = useFocusManager({
autoFocus: true,
onFocusChange: focused => console.log('Focus changed:', focused),
});
return (
Featured Content
);
}
```
--------------------------------
### Use with FocusGuideView for complex layouts
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Combine useTVFocus with FocusGuideView to create explicit focus paths for complex layouts. The example shows a FocusGuideView with destinations from getNativeDestinations and trapFocusLeft, wrapping a split layout with left and right panels.
```jsx
```
--------------------------------
### Usage of FocusGuideView with autoFocus and trapFocusRight
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/components.md
Shows how to use FocusGuideView to create a menu container with auto-focus and right-edge focus trapping. The example includes MenuButton components that navigate to different screens.
```javascript
navigate('Home')} />
navigate('Movies')} />
navigate('TVShows')} />
navigate('Settings')} />
```
--------------------------------
### FocusGuideView
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/focusGuide/README.md
A wrapper for TVFocusGuideView that provides autofocus, focus memory, trapping, and focus redirection for TV apps. It ensures focusable controls can be navigated to even if not directly in line with other controls.
```APIDOC
## FocusGuideView
### Description
A wrapper for TVFocusGuideView that helps write intuitive TV apps. It supports autofocus, focus memory, trapping, and focus redirection.
### Props
| Prop | Value | Description |
|---|---|---|
| destinations | any[]? | Array of Components to register as destinations of the FocusGuideView |
| autoFocus | boolean? | If true, TVFocusGuide will automatically manage focus. Redirects focus to first focusable child on first visit, remembers last focused child on subsequent visits. destinations prop takes precedence. |
| focusable | boolean? | When set to false, this view and all subviews will NOT be focusable. |
| trapFocus* (Up, Down, Left, Right) | - | Prevents focus escaping from the container for the given directions. |
```
--------------------------------
### FocusGuideView navigation example
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/components.md
Wraps the Grid in a FocusGuideView to enable automatic focus on the first item, prevent focus from moving off the right edge, and provide proper directional navigation.
```javascript
{/* Grid content */}
```
--------------------------------
### Optimize registration for many items
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
For large lists or grids, optimize registration by only registering visible items. The example shows using a ref to store visible item refs, registering/unregistering based on visibility, and cleaning up all registrations on unmount.
```javascript
// Better approach for many items
const visibleItemRefs = useRef({});
// Only register items that are currently visible
const handleItemVisible = (id, ref, isVisible) => {
if (isVisible) {
visibleItemRefs.current[id] = ref;
registerDestination(`item-${id}`, ref);
} else {
delete visibleItemRefs.current[id];
unregisterDestination(`item-${id}`);
}
};
// Clean up all registrations on unmount
useEffect(() => {
return () => {
Object.keys(visibleItemRefs.current).forEach(id => {
unregisterDestination(`item-${id}`);
});
};
}, []);
```
--------------------------------
### Add custom colors to palette.ts
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Example of adding custom colors to the palette.ts file. Includes transparent, focusPrimary, and gradientPrimary definitions.
```javascript
transparent: 'transparent',
focusPrimary: '#FDE8C7',
gradientPrimary: ['rgba(255, 255, 255, 0)', 'rgba(255, 255, 255, 0.8)'],
```
--------------------------------
### RNTL test example
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/test-utils/README.md
Imports render and fireEvent from '@testing-library/react-native' to render a component and query text. The test asserts that the element with text 'Hello, World!' is truthy.
```javascript
import { render, fireEvent } from '@testing-library/react-native';
import MyComponent from './MyComponent';
test('MyComponent renders correctly', () => {
const { getByText } = render();
const element = getByText('Hello, World!');
expect(element).toBeTruthy();
});
```
--------------------------------
### Basic hook usage with useImagePrefetchQueue
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Use this hook to manage image prefetching with concurrency control and priority-based queuing. The example shows prefetching visible images with high priority and remaining images with lower priority.
```javascript
import { useImagePrefetchQueue } from '@AppSrc/hooks/useImagePrefetchQueue';
export const ImageGallery = ({ images }) => {
const { prefetch, subscribe } = useImagePrefetchQueue(5);
const handleImageLoad = async imageUrl => {
try {
await prefetch(imageUrl);
console.log('Image prefetched successfully');
} catch (error) {
console.error('Failed to prefetch image:', error);
}
};
useEffect(() => {
// Prefetch visible images with high priority
images.slice(0, 3).forEach((image, index) => {
prefetch(image.url, 1); // Priority 1 (highest)
});
// Prefetch remaining images with lower priority
images.slice(3).forEach(image => {
prefetch(image.url, 3); // Priority 3 (lower)
});
}, [images, prefetch]);
return (
{images.map(image => (
))}
);
};
```
--------------------------------
### Combine with state management
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Integrate focus management with component state for cohesive UI behavior. The example shows using useState to track a selected item and updating it in a focus handler.
```javascript
const [selectedItem, setSelectedItem] = useState(null);
const handleItemFocus = itemId => {
setSelectedItem(itemId);
// Other focus-related state updates
};
```
--------------------------------
### useFocusGuideEventHandler
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/focusGuide/README.md
A wrapper for useTVEventHandler that listens for TV remote events such as button presses. It simplifies handling TV-specific needs in React Native apps.
```APIDOC
## useFocusGuideEventHandler
### Description
A wrapper for useTVEventHandler that listens for events from the TV remote, such as button presses. It's part of React Native's support for TV platforms.
### Parameters
- **handler** (Function) - Required - A callback function triggered when a TV event occurs. The function receives an event object with details about the event.
### Request Example
```jsx
import React, { useState } from 'react';
import { Text, View } from 'react-native';
import { useFocusGuideEventHandler } from '@AppServices/focusGuide';
const TVRemoteHandler = () => {
const [lastEventType, setLastEventType] = useState(null);
const myTVEventHandler = (evt) => {
if (evt && evt.eventType) {
setLastEventType(evt.eventType);
}
};
useFocusGuideEventHandler(myTVEventHandler);
return (
Press a button on the TV remoteLast event: {lastEventType || 'None'}
);
};
```
```
--------------------------------
### FlexibleCard component integration with usePosterRowsWithSkeletonPreload
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Defines a memoized PosterRow component that renders FlexibleCard items with skeleton support and visibility tracking. Also includes an EnhancedPosterGrid example that uses the pagination hook to feed rows into a FlashList, calling fetchNextPage on end reached.
```javascript
import React, { memo } from 'react';
import { usePosterRowsWithSkeletonPreload } from '@AppSrc/hooks/usePosterRows';
import { FlexibleCard } from '@AppComponents/FlexibleCard';
export const PosterRow = memo(
({ row, scrollVertically, visibleRowIndices }) => {
const isRowVisible = visibleRowIndices?.has(row.rowIndex) ?? false;
const renderCard = (item, index) => (
{
// Handle horizontal scrolling within the row
},
}}
/>
);
return (
{row.title}{row.data.map(renderCard)}
);
},
);
// Usage with the pagination hook
export const EnhancedPosterGrid = () => {
const { rows, fetchNextPage, hasNextPage, isPreloading } =
usePosterRowsWithSkeletonPreload();
return (
}
onEndReached={() => hasNextPage && fetchNextPage()}
/>
);
};
```
--------------------------------
### Define custom badge tokens for light and dark themes
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Create a file named [token_name].theme.ts (e.g., badge.theme.ts) and define custom tokens for light and dark themes. The example shows badgeTokensLight and badgeTokensDark, but note the source has a typo: the second export is also named badgeTokensLight instead of badgeTokensDark. The tokens use lightPalette and darkPalette for colors.
```typescript
export const badgeTokensLight: Partial = {
container: {
color: {
borderColor: 'transparent',
backgroundColor: lightPalette.background,
},
},
label: {
color: {
textColor: lightPalette.onBackground',
},
},
};
export const badgeTokensLight: Partial = {
container: {
color: {
borderColor: 'transparent',
backgroundColor: darkPalette.background,
},
},
label: {
color: {
textColor: darkPalette.onBackground',
},
},
};
```
--------------------------------
### nextFocus* Example: useNodeHandle hook and focusableComponent
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/focusGuide/README.md
Shows how to use nextFocus* props to override focus direction on TouchableOpacity components. The useNodeHandle hook gets the native tag via findNodeHandle. Setting a direction to the same component's handle blocks that keypress; undefined falls back to Cartesian focus strategy.
```jsx
const useNodeHandle = (ref) => {
const [nodeHandle, setNodeHandle] = React.useState(null);
React.useEffect(() => {
if (ref.current) {
setNodeHandle(findNodeHandle(ref.current));
}
}, [ref.current]);
return nodeHandle;
};
const focusableComponent = () => {
const ref1 = React.useRef(null);
const ref2 = React.useRef(null);
const ref3 = React.useRef(null);
const ref1Handle = useNodeHandle(ref1);
const ref2Handle = useNodeHandle(ref2);
const ref3Handle = useNodeHandle(ref3);
// Three focusable components explicitly define some or all of their
// directional overrides. Overrides that sets the next focus to the same
// component effectively act to block the button press. For components
// that have directions that are not explicitly declared or set to undefined,
// the fallback behavior of Cartesian focus strategy will be taken.
return (
{}}
// block 'up' presses
nextFocusUp={ref1Handle || undefined}
// block 'right' presses
nextFocusRight={ref1Handle || undefined}
// explicitly focus on Component 2 on 'left' press
nextFocusLeft={ref2Handle || undefined}
// explicitly focus on Component 3 on 'down' press
nextFocusDown={ref3Handle || undefined}>Component 1 {}}
// explicitly focus on Component 1 on 'right' press
nextFocusRight={ref1Handle || undefined}>Component 2 {}}
// explicitly focus on Component 1 on 'up' press
nextFocusUp={ref1Handle || undefined}>Component 3
);
};
```
--------------------------------
### Build the app to generate VPKG files
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Run this command to build the app and generate .vpkg files in the build folder.
```bash
npm run build:app
```
--------------------------------
### Basic menu with focus collection using useFocusCollection
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Shows how to use useFocusCollection to manage focus in a menu. Registers refs for menu items, auto-focuses the first item on mount, and applies a focused style based on the current focused item.
```javascript
import React, { useEffect } from 'react';
import { View, Text, Pressable, StyleSheet } from 'react-native';
import { useFocusCollection } from '@AppSrc/hooks';
const menuItems = [
{ id: 'home', label: 'Home' },
{ id: 'movies', label: 'Movies' },
{ id: 'shows', label: 'TV Shows' },
{ id: 'settings', label: 'Settings' },
];
export const MainMenu = () => {
const { registerRef, focusItem, getCurrentFocused } = useFocusCollection();
// Auto-focus the first item when the menu mounts
useEffect(() => {
focusItem('home');
}, [focusItem]);
return (
{menuItems.map(item => (
registerRef(item.id, ref)}
style={[
styles.menuItem,
getCurrentFocused() === item.id && styles.focusedMenuItem,
]}
onFocus={() => console.log(`${item.label} focused`)}
onPress={() => console.log(`${item.label} pressed`)}
>
{item.label}
))}
);
};
const styles = StyleSheet.create({
menu: {
padding: 20,
backgroundColor: '#1a1a1a',
},
menuItem: {
padding: 16,
marginVertical: 8,
borderRadius: 8,
backgroundColor: 'rgba(255, 255, 255, 0.1)',
},
focusedMenuItem: {
backgroundColor: '#0078D7',
transform: [{ scale: 1.05 }],
},
menuText: {
color: 'white',
fontSize: 18,
},
});
```
--------------------------------
### Run test suite
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Command to run the test suite.
```bash
npm test
```
--------------------------------
### usePosterRows configuration with useInfiniteQuery
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Configures useInfiniteQuery for paginated poster rows. Loads pages of 3 rows each (configurable via TOTAL_ROWS_PER_BATCH), provides initial data to prevent loading states on first render, and automatically determines when more pages are available.
```javascript
export const usePosterRows = () =>
useInfiniteQuery({
queryKey: ['posterRows'],
queryFn: ({ pageParam = 0 }) => {
const rows = getPosterRowsPage({
page: pageParam,
pageSize: TOTAL_ROWS_PER_BATCH,
});
return { rows, page: pageParam };
},
initialPageParam: 0,
getNextPageParam: lastPage =>
lastPage.rows.length < TOTAL_ROWS_PER_BATCH
? undefined
: lastPage.page + 1,
initialData: {
pages: [
{
rows: getPosterRowsPage({ page: 0, pageSize: TOTAL_ROWS_PER_BATCH }),
page: 0,
},
],
pageParams: [0],
},
});
```
--------------------------------
### Implement loading states for TV
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Shows how to display a full-screen loading indicator during initial load and a bottom loader with an ActivityIndicator and 'Loading more...' text during pagination loading.
```javascript
// Initial loading
if (isLoading) {
return ;
}
// Pagination loading (at bottom of content)
{
isFetchingNextPage && (
Loading more...
);
}
```
--------------------------------
### Use skeleton preloading for better UX
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Use usePosterRowsWithSkeletonPreload to show skeletons during initial load. Returns rows, fetchNextPage, and isPreloading.
```javascript
// Choose the enhanced hook for better user experience
const { rows, fetchNextPage, isPreloading } =
usePosterRowsWithSkeletonPreload();
// Show skeletons during initial load
if (isPreloading && rows.length === 0) {
return ;
}
```
--------------------------------
### Card carousel example using FlexibleCard
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/components.md
Complete example of a horizontal carousel using FlexibleCard. It uses a ScrollView with horizontal scrolling and a scrollToIndex function to scroll to a specific card. The component accepts a title and items array, rendering each item as a FlexibleCard with medium size, horizontal direction, and zoomIn animation.
```javascript
import React, { useRef } from 'react';
import { View, Text, ScrollView, StyleSheet } from 'react-native';
import { FlexibleCard } from '@AppComponents/FlexibleCard/FlexibleCard';
const CardCarousel = ({ title, items }) => {
const scrollViewRef = useRef(null);
const scrollToIndex = index => {
// Calculate scroll position based on card width and gap
const position = index * (400 + 20); // Medium card width + gap
scrollViewRef.current?.scrollTo({ x: position, animated: true });
};
return (
{title}
{items.map((item, index) => (
console.log('Selected:', item.title)}
scroll={{
horizontally: scrollToIndex,
}}
/>
))}
);
};
const styles = StyleSheet.create({
container: {
marginBottom: 40,
},
sectionTitle: {
fontSize: 28,
fontWeight: 'bold',
color: 'white',
marginBottom: 16,
marginLeft: 20,
},
scrollView: {
paddingLeft: 20,
},
cardsContainer: {
flexDirection: 'row',
alignItems: 'flex-start',
},
});
export default CardCarousel;
```
--------------------------------
### Query configuration for useInfiniteQuery
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Configuration object for useInfiniteQuery with queryKey, initialPageParam, queryFn, getNextPageParam, and caching settings. Uses paginatePosters and ITEMS_PER_PAGE.
```javascript
{
queryKey: ['verticalPosters'],
initialPageParam: 1,
queryFn: ({ pageParam }) => {
const allPosters = getVerticalPosters();
const paginatedPosters = paginatePosters(
allPosters,
pageParam,
ITEMS_PER_PAGE,
);
return {
items: paginatedPosters.map((imageUrl, index) => ({
id: `${(pageParam - 1) * ITEMS_PER_PAGE + index}`,
title: `Poster ${(pageParam - 1) * ITEMS_PER_PAGE + index + 1}`,
imageUrl,
})),
nextPage:
pageParam * ITEMS_PER_PAGE < allPosters.length
? pageParam + 1
: undefined,
};
},
getNextPageParam: lastPage => lastPage.nextPage,
staleTime: 1000 * 60 * 60 * 24,
gcTime: 1000 * 60 * 60 * 24,
}
```
--------------------------------
### usePosterRowsWithSkeletonPreload hook implementation
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Provides immediate visual feedback with skeleton placeholders while fetching real content in the background. Merges skeleton and real data based on availability, returning rows, pagination controls, and loading states. Uses useInfiniteQuery with a query key 'posterRows' and getPosterRowsPageWithSkeletons to generate pages.
```typescript
export const usePosterRowsWithSkeletonPreload = () => {
const [mergedRows, setMergedRows] = useState([]);
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,
isFetching,
status,
} = useInfiniteQuery({
queryKey: ['posterRows'],
queryFn: ({ pageParam = 0 }) => {
const { rows, skeletonRows } = getPosterRowsPageWithSkeletons({
page: pageParam,
pageSize: TOTAL_ROWS_PER_BATCH,
includeSkeletons: true,
});
return Promise.resolve({
real: rows,
skeleton: skeletonRows,
page: pageParam,
});
},
initialPageParam: 0,
getNextPageParam: lastPage =>
lastPage.real.length < TOTAL_ROWS_PER_BATCH
? undefined
: lastPage.page + 1,
});
// Merge skeleton and real data
useEffect(() => {
if (!data) return;
const allReal = data.pages.flatMap(p => p.real);
const allSkeletons = data.pages.flatMap(p => p.skeleton);
const merged = allSkeletons
.filter(s => s.rowIndex < TOTAL_POSTER_ROWS)
.map((skeletonRow, index) => {
const realRow = allReal[index];
return realRow?.data.some(item => !item.isSkeleton)
? realRow
: skeletonRow;
});
setMergedRows(merged);
}, [data]);
return {
rows: mergedRows,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,
isFetching,
isPreloading: isLoading,
status,
};
};
```
--------------------------------
### Memoize getNativeDestinations result
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
If calling getNativeDestinations frequently, memoize the result with useMemo. The example shows memoizing the destinations array and passing it to FocusGuideView.
```javascript
const memoizedDestinations = useMemo(
() => getNativeDestinations(['menu', 'content']),
[getNativeDestinations, destinations],
);
return (
{/* Content */}
);
```
--------------------------------
### Clean project and clear cache
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Run these commands to clean all cache files in the project and rebuild. Useful when changes to patches or package.json require a clean build.
```bash
npm run clean
npm cache clean --force
watchman watch-del-all
rm -fr $TMPDIR/haste-map-*
rm -rf $TMPDIR/metro-cache
npm install
npm start -- --reset-cache
```
--------------------------------
### Pre-load next page with FlatList onEndReached
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Configures FlatList or ScrollView to start loading when the user is halfway through current content using onEndReachedThreshold={0.5}.
```javascript
// In your FlatList or ScrollView
```
--------------------------------
### Get API key with getApiKey
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/appConfig/README.md
Retrieves the API key required for authenticating API calls based on the current environment.
```typescript
import { getApiKey } from '@AppServices/appConfig';
const apiKey = getApiKey();
```
--------------------------------
### useTVFocus implementation: context and type definitions
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Defines the TVFocusContext and its type, including DestinationMap and TVFocusContextType. This is the foundation for the focus registry system. The context is created with createContext and defaults to null.
```javascript
import type { RefObject } from 'react';
import React, { createContext, useContext, useState } from 'react';
import type { View } from 'react-native';
import { findNodeHandle } from 'react-native';
type DestinationMap = Record | null>;
interface TVFocusContextType {
destinations: DestinationMap;
registerDestination: (key: string, ref: RefObject | null) => void;
unregisterDestination: (key: string) => void;
getNativeDestinations: (keys: string[]) => (number | null)[];
}
const TVFocusContext = createContext(null);
```
--------------------------------
### Box with next focus directions
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/components.md
Guides users with explicit navigation paths using nextFocus props for directional navigation.
```javascript
Content
```
--------------------------------
### Error handling with onError callback
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/storage/README.md
Each DeviceStorage method accepts an optional onError callback that receives an error message. Example usage with saveStorage.
```typescript
const handleError = (error: string) => {
console.error(error);
};
// Example usage with error handling
await saveStorage('example-key', { sampleData: true }, handleError);
```
--------------------------------
### Enhanced grid with loading states and error handling using useVerticalPosters
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/docs/hooks.md
Extends the basic grid with error handling, empty state, and pagination loader. Shows a retry button on error and displays 'No content available' when items are empty.
```javascript
import React from 'react';
import { View, Text, ActivityIndicator, TouchableOpacity } from 'react-native';
import { useVerticalPosters } from '@AppSrc/hooks';
import { Grid } from '@AppComponents/Grid';
export const EnhancedPosterGallery = () => {
const {
items,
isLoading,
isFetching,
hasNextPage,
fetchNextPage,
isFetchingNextPage,
isError,
error,
} = useVerticalPosters();
const handleLoadMore = React.useCallback(() => {
if (hasNextPage && !isFetching) {
void fetchNextPage();
}
}, [hasNextPage, isFetching, fetchNextPage]);
if (isLoading) {
return (
Loading content...
);
}
if (isError) {
return (
Something went wrong
{error?.message || 'Failed to load content'}
fetchNextPage()}
>
Retry
);
}
return (
{items.length === 0 ? (
No content available
) : (
<>
{isFetchingNextPage && (
Loading more...
)}
>
)}
);
};
const styles = StyleSheet.create({
// Style definitions...
});
```
--------------------------------
### Get API base URL with getApiBaseUrl
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/appConfig/README.md
Retrieves the base URL for API requests based on the current environment. Logs the URL.
```typescript
import { getApiBaseUrl } from '@AppServices/appConfig';
const apiUrl = getApiBaseUrl();
console.log('API Base URL:', apiUrl);
```
--------------------------------
### Get Synchronous Network State
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/src/services/netInfo/README.md
Retrieves the last known network state from the service's internal state. Optionally, you can force a refresh of the state.
```typescript
import { getNetInfoStateSync } from './NetInfoService';
// Get the last known network state without refreshing
const lastKnownState = getNetInfoStateSync();
console.log('Last Known Network State:', lastKnownState);
// Get the network state and force a refresh
const refreshedState = getNetInfoStateSync(true);
console.log('Refreshed Synchronous Network State:', refreshedState);
```
--------------------------------
### npm run i18n:sync command
Source: https://github.com/amazonappdev/vega-tv-interfaces-sample/blob/main/README.md
Command to copy translation keys from the default language file to other translation files.
```bash
npm run i18n:sync
```