|
| 1 | +import type React from 'react'; |
| 2 | +import { useCallback, useMemo, useState } from 'react'; |
| 3 | +import { |
| 4 | + Button, |
| 5 | + ScrollView, |
| 6 | + StyleSheet, |
| 7 | + Switch, |
| 8 | + Text, |
| 9 | + View, |
| 10 | +} from 'react-native'; |
| 11 | +import Animated, { interpolateColor } from 'react-native-reanimated'; |
| 12 | +import { |
| 13 | + createWorkletRuntime, |
| 14 | + runOnRuntimeAsync, |
| 15 | + runOnUIAsync, |
| 16 | + scheduleOnRN, |
| 17 | + type WorkletRuntime, |
| 18 | +} from 'react-native-worklets'; |
| 19 | + |
| 20 | +interface Card { |
| 21 | + id: string; |
| 22 | + value: number; |
| 23 | +} |
| 24 | + |
| 25 | +type RuntimeType = 'ui' | 'worker'; |
| 26 | + |
| 27 | +const NUM_COLUMNS = 10; |
| 28 | +const NUM_ROWS = 18; |
| 29 | +const TOTAL_CARDS = NUM_COLUMNS * NUM_ROWS; |
| 30 | + |
| 31 | +const generateCards = (): Card[] => { |
| 32 | + return Array.from({ length: TOTAL_CARDS }, (_, i) => ({ |
| 33 | + id: `card-${i}`, |
| 34 | + value: Math.floor(Math.random() * 1000), // Random value for sorting |
| 35 | + })); |
| 36 | +}; |
| 37 | + |
| 38 | +const sortCardsWorklet = (currentCards: Card[]): Card[] => { |
| 39 | + 'worklet'; |
| 40 | + const sorted = [...currentCards].sort((a, b) => a.value - b.value); |
| 41 | + return sorted; |
| 42 | +}; |
| 43 | + |
| 44 | +const shuffleCardsWorklet = (currentCards: Card[]): Card[] => { |
| 45 | + 'worklet'; |
| 46 | + const shuffled = [...currentCards]; |
| 47 | + for (let i = shuffled.length - 1; i > 0; i--) { |
| 48 | + const j = Math.floor(Math.random() * (i + 1)); |
| 49 | + [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; |
| 50 | + } |
| 51 | + return shuffled; |
| 52 | +}; |
| 53 | + |
| 54 | +const RunOnAsyncExample: React.FC = () => { |
| 55 | + const [cards, setCards] = useState<Card[]>(generateCards()); |
| 56 | + const [isSorting, setIsSorting] = useState(false); |
| 57 | + const [isShuffling, setIsShuffling] = useState(false); |
| 58 | + const [runtimeType, setRuntimeType] = useState<RuntimeType>('ui'); |
| 59 | + |
| 60 | + // Create a worker runtime for background processing |
| 61 | + const workerRuntime: WorkletRuntime = useMemo( |
| 62 | + () => createWorkletRuntime({ name: 'CardSorterWorker' }), |
| 63 | + [] |
| 64 | + ); |
| 65 | + |
| 66 | + const getRuntimeLabel = useCallback( |
| 67 | + () => (runtimeType === 'ui' ? 'UI Runtime' : 'Worker Runtime'), |
| 68 | + [runtimeType] |
| 69 | + ); |
| 70 | + |
| 71 | + const handleSortPress = useCallback(async () => { |
| 72 | + setIsSorting(true); |
| 73 | + console.log(`Starting sort on ${getRuntimeLabel()}...`); |
| 74 | + try { |
| 75 | + let sortedCards: Card[]; |
| 76 | + if (runtimeType === 'ui') { |
| 77 | + sortedCards = await runOnUIAsync(sortCardsWorklet, cards); |
| 78 | + } else { |
| 79 | + sortedCards = await runOnRuntimeAsync( |
| 80 | + workerRuntime, |
| 81 | + sortCardsWorklet, |
| 82 | + cards |
| 83 | + ); |
| 84 | + } |
| 85 | + setCards(sortedCards); |
| 86 | + setIsSorting(false); |
| 87 | + console.log(`Sorting complete on ${getRuntimeLabel()}.`); |
| 88 | + } catch (e) { |
| 89 | + console.error(`Failed to sort cards on ${getRuntimeLabel()}:`, e); |
| 90 | + scheduleOnRN(setIsSorting, false); |
| 91 | + } |
| 92 | + }, [cards, getRuntimeLabel, runtimeType, workerRuntime]); |
| 93 | + |
| 94 | + const handleShufflePress = useCallback(async () => { |
| 95 | + setIsShuffling(true); |
| 96 | + console.log(`Starting shuffle on ${getRuntimeLabel()}...`); |
| 97 | + try { |
| 98 | + let shuffledCards: Card[]; |
| 99 | + if (runtimeType === 'ui') { |
| 100 | + shuffledCards = await runOnUIAsync(shuffleCardsWorklet, cards); |
| 101 | + } else { |
| 102 | + shuffledCards = await runOnRuntimeAsync( |
| 103 | + workerRuntime, |
| 104 | + shuffleCardsWorklet, |
| 105 | + cards |
| 106 | + ); |
| 107 | + } |
| 108 | + setCards(shuffledCards); |
| 109 | + setIsShuffling(false); |
| 110 | + console.log(`Shuffling complete on ${getRuntimeLabel()}.`); |
| 111 | + } catch (e) { |
| 112 | + console.error(`Failed to shuffle cards on ${getRuntimeLabel()}:`, e); |
| 113 | + scheduleOnRN(setIsShuffling, false); |
| 114 | + } |
| 115 | + }, [cards, getRuntimeLabel, runtimeType, workerRuntime]); |
| 116 | + |
| 117 | + return ( |
| 118 | + <View style={styles.container}> |
| 119 | + <View style={styles.runtimeSelector}> |
| 120 | + <Text style={styles.runtimeLabel}>UI Runtime</Text> |
| 121 | + <Switch |
| 122 | + value={runtimeType === 'worker'} |
| 123 | + onValueChange={(value) => setRuntimeType(value ? 'worker' : 'ui')} |
| 124 | + /> |
| 125 | + <Text style={styles.runtimeLabel}>Worker Runtime</Text> |
| 126 | + </View> |
| 127 | + <Text style={styles.currentRuntime}>Current: {getRuntimeLabel()}</Text> |
| 128 | + <View style={styles.buttonContainer}> |
| 129 | + <Button |
| 130 | + title={isSorting ? 'Sorting...' : `Sort Cards`} |
| 131 | + onPress={() => { |
| 132 | + handleSortPress().catch(() => {}); |
| 133 | + }} |
| 134 | + disabled={isSorting || isShuffling} |
| 135 | + /> |
| 136 | + <Button |
| 137 | + title={isShuffling ? 'Shuffling...' : `Shuffle Cards`} |
| 138 | + onPress={() => { |
| 139 | + handleShufflePress().catch(() => {}); |
| 140 | + }} |
| 141 | + disabled={isSorting || isShuffling} |
| 142 | + /> |
| 143 | + </View> |
| 144 | + <ScrollView contentContainerStyle={styles.gridContainer}> |
| 145 | + {cards.map((card) => { |
| 146 | + const backgroundColor = interpolateColor( |
| 147 | + card.value, |
| 148 | + [0, 1000], |
| 149 | + ['#008000', '#000080'] // dark green to dark blue |
| 150 | + ); |
| 151 | + return ( |
| 152 | + <Animated.View |
| 153 | + key={card.id} |
| 154 | + style={[styles.card, { backgroundColor }]}> |
| 155 | + <Text style={styles.cardText}>{card.value}</Text> |
| 156 | + </Animated.View> |
| 157 | + ); |
| 158 | + })} |
| 159 | + </ScrollView> |
| 160 | + </View> |
| 161 | + ); |
| 162 | +}; |
| 163 | + |
| 164 | +const styles = StyleSheet.create({ |
| 165 | + container: { |
| 166 | + flex: 1, |
| 167 | + padding: 10, |
| 168 | + }, |
| 169 | + runtimeSelector: { |
| 170 | + flexDirection: 'row', |
| 171 | + alignItems: 'center', |
| 172 | + justifyContent: 'center', |
| 173 | + marginBottom: 10, |
| 174 | + }, |
| 175 | + runtimeLabel: { |
| 176 | + marginHorizontal: 10, |
| 177 | + fontSize: 14, |
| 178 | + }, |
| 179 | + currentRuntime: { |
| 180 | + textAlign: 'center', |
| 181 | + marginBottom: 10, |
| 182 | + fontWeight: 'bold', |
| 183 | + }, |
| 184 | + buttonContainer: { |
| 185 | + justifyContent: 'space-around', |
| 186 | + }, |
| 187 | + gridContainer: { |
| 188 | + flexDirection: 'row', |
| 189 | + flexWrap: 'wrap', |
| 190 | + justifyContent: 'center', |
| 191 | + marginTop: 20, |
| 192 | + }, |
| 193 | + card: { |
| 194 | + width: `${100 / NUM_COLUMNS - 2}%`, |
| 195 | + aspectRatio: 1, |
| 196 | + margin: '1%', |
| 197 | + justifyContent: 'center', |
| 198 | + alignItems: 'center', |
| 199 | + borderRadius: 5, |
| 200 | + }, |
| 201 | + cardText: { |
| 202 | + fontSize: 12, |
| 203 | + color: 'white', |
| 204 | + }, |
| 205 | +}); |
| 206 | + |
| 207 | +export default RunOnAsyncExample; |
0 commit comments