Photo picker

A media picker for attaching photos to a post or chat: tiles cascade in over tinted placeholders, a tapped photo shrinks inside an accent ring while its numbered badge springs in, and deselecting renumbers the rest. A tray slides up with the picks in order (tap one to remove it) and an Add button carrying the live count, the album menu drops from the top bar and re-cascades the grid, an eleventh pick shakes with a hint, and holding a photo zooms it into a preview.

photo pickergallerymediamulti-selectalbumsattachmentanimationreanimated
Paste into Claude Code Cursor Codex Lovable RapidNative
Live preview · follows the site themeOpen full screen

Details

File
components/patterns/photo-picker.tsx
Lines
767
Stack
React Native, StyleSheet
Packages
expo-linear-gradient, lucide-react-native, react-native-reanimated, react-native-safe-area-context, react-native-svg, react-native-worklets
Platforms
iOS, Android, Web

Using gluestack-ui?

Optional. The screen is plain React Native; these components can stand in for its primitives.

components/patterns/photo-picker.tsx
1import { useEffect, useRef, useState, type ComponentRef, type ReactNode } from 'react';
2import { Image, Pressable, ScrollView, StyleSheet, Text, View, useColorScheme, useWindowDimensions } from 'react-native';
3import Animated, {
4 Easing,
5 LinearTransition,
6 ZoomIn,
7 ZoomOut,
8 useAnimatedStyle,
9 useSharedValue,
10 withDelay,
11 withSequence,
12 withSpring,
13 withTiming,
14} from 'react-native-reanimated';
15import { LinearGradient } from 'expo-linear-gradient';
16import { useSafeAreaInsets } from 'react-native-safe-area-context';
17import { Camera, Check, ChevronDown, Play, X } from 'lucide-react-native';
18
19// ─── Brand ──────────────────────────────────────────────────────────────────
20// The picker's accent. Every accent colour below derives from these, so changing them rebrands the screen.
21
22const ACCENT = '#FF3D71';
23const ACCENT_DARK = '#FF5C87'; // the accent on dark backgrounds
24const ON_ACCENT = '#FFFFFF'; // text and icons on an accent fill
25
26/** `hex` at `alpha` opacity, as rgba(). */
27function tint(hex: string, alpha: number) {
28 const n = parseInt(hex.slice(1), 16);
29 return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
30}
31
32/** `hex` mixed toward black (amount > 0) or white (amount < 0); amount from -1 to 1. */
33function shade(hex: string, amount: number) {
34 const n = parseInt(hex.slice(1), 16);
35 const target = amount < 0 ? 255 : 0;
36 const p = Math.abs(amount);
37 const c = (v: number) => Math.round(v + (target - v) * p).toString(16).padStart(2, '0');
38 return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`.toUpperCase();
39}
40
41// ─── Sample data ────────────────────────────────────────────────────────────
42
43type Photo = { id: string; label: string; taken: string; tint: string; duration?: string };
44
45// `tint` is the placeholder shown until the photo has loaded; `duration` marks a video.
46const LIBRARY: Record<string, Photo> = {
47 lake: { id: '1501785888041-af3ef285b470', label: 'Rowing boat on a turquoise mountain lake', taken: 'Today, 9:41', tint: '#3FA7A3' },
48 pancakes: { id: '1567620905732-2d1ec7ab7445', label: 'Stack of pancakes with syrup', taken: 'Today, 8:12', tint: '#3A3A3F' },
49 hiker: { id: '1501555088652-021faa106b9b', label: 'Hiker with a yellow backpack in a valley', taken: 'Yesterday, 16:30', tint: '#7E9A63' },
50 cubes: { id: '1479839672679-a46483c0e7c8', label: 'White cubic building against a pale sky', taken: 'Yesterday, 11:04', tint: '#C9D8E0' },
51 beach: { id: '1507525428034-b723cf961d3e', label: 'Waves on a beach at sunrise', taken: 'Yesterday, 6:52', tint: '#B9D4D6' },
52 bowl: { id: '1512621776951-a57141f2eefd', label: 'Colourful vegetable bowl', taken: 'Sunday, 13:20', tint: '#A9B77C' },
53 stars: { id: '1519681393784-d120267933ba', label: 'Starry sky over a snowy ridge', taken: 'Saturday, 23:48', tint: '#2A3B63', duration: '0:24' },
54 cabin: { id: '1518780664697-55e3ad937233', label: 'Red cabin on a hillside', taken: 'Saturday, 15:09', tint: '#D8D6D0' },
55 alley: { id: '1527631746610-bca00a040d60', label: 'Traveller walking down a narrow street', taken: 'Saturday, 10:31', tint: '#7B5E4E' },
56 moraine: { id: '1493246507139-91e8fad9978e', label: 'Peaks reflected in a lake at dusk', taken: 'Friday, 20:15', tint: '#4E7F96' },
57 coffee: { id: '1495474472287-4d71bcdd2085', label: 'Three cups of coffee held together', taken: 'Friday, 9:02', tint: '#6B4A36' },
58 towers: { id: '1486406146926-c627a92ad1ab', label: 'Glass towers seen from the street', taken: '14 Nov, 17:40', tint: '#5B6F82' },
59 falls: { id: '1433086966358-54859d0ed716', label: 'Waterfall under a stone bridge', taken: '12 Nov, 12:26', tint: '#4C6B3A', duration: '1:07' },
60 pizza: { id: '1565299624946-b28f40a0ae38', label: 'Sliced pizza on a wooden board', taken: '11 Nov, 19:55', tint: '#8A4B2A' },
61 clouds: { id: '1506905925346-21bda4d32df4', label: 'Mountain tops above the clouds', taken: '9 Nov, 6:18', tint: '#6C7FA3' },
62 skyline: { id: '1480714378408-67cf0d13bc1b', label: 'City skyline in low sun', taken: '8 Nov, 16:47', tint: '#A98B6A' },
63 toast: { id: '1482049016688-2d3e1b311543', label: 'Eggs and avocado on a dark plate', taken: '8 Nov, 10:10', tint: '#3B2F2A' },
64 surf: { id: '1505142468610-359e7d316be0', label: 'Surf breaking on a beach from above', taken: '5 Nov, 14:33', tint: '#2F7F8C', duration: '0:09' },
65 forest: { id: '1441974231531-c6227db76b6e', label: 'Sunlit path through a forest', taken: '3 Nov, 8:44', tint: '#5E6B36' },
66 dinner: { id: '1414235077428-338989a2e8c0', label: 'Plated dinner on a set table', taken: '1 Nov, 20:21', tint: '#7A5A3C' },
67 hills: { id: '1472214103451-9374bd1c798e', label: 'Green hills at sunset', taken: '29 Oct, 18:02', tint: '#5E9A2E' },
68 road: { id: '1500530855697-b586d89ba3ee', label: 'Empty road through red rock', taken: '27 Oct, 7:36', tint: '#8A4F45' },
69 facets: { id: '1487958449943-2429e8be8625', label: 'Angular white building', taken: '24 Oct, 12:00', tint: '#C8D2D8' },
70 salad: { id: '1540189549336-e6e99c3679fe', label: 'Green salad on a black plate', taken: '21 Oct, 13:15', tint: '#2E3A40' },
71 steak: { id: '1504674900247-0877df9cc836', label: 'Dinner plates seen from above', taken: '19 Oct, 19:30', tint: '#6E6A66' },
72 boat: { id: '1476514525535-07fb3b4ae5f1', label: 'Bow of a wooden boat on a lake', taken: '14 Oct, 11:11', tint: '#7FA3A0' },
73 glass: { id: '1511818966892-d7d671e672a2', label: 'Mirrored office towers under cloud', taken: '10 Oct, 15:25', tint: '#6A7078' },
74};
75type Key = keyof typeof LIBRARY;
76
77const ALBUMS: { id: string; name: string; keys: Key[] }[] = [
78 {
79 id: 'recents',
80 name: 'Recents',
81 keys: ['lake', 'pancakes', 'hiker', 'cubes', 'beach', 'bowl', 'stars', 'cabin', 'alley', 'moraine', 'coffee', 'towers', 'falls', 'pizza', 'clouds', 'skyline', 'toast', 'surf', 'forest', 'dinner', 'hills', 'road', 'facets'],
82 },
83 { id: 'favorites', name: 'Favorites', keys: ['moraine', 'cabin', 'stars', 'hiker', 'beach', 'hills', 'lake', 'forest'] },
84 { id: 'trips', name: 'Trips', keys: ['hiker', 'alley', 'boat', 'road', 'falls', 'clouds', 'lake', 'surf', 'moraine', 'skyline', 'cabin'] },
85 { id: 'food', name: 'Food and drink', keys: ['pancakes', 'bowl', 'pizza', 'coffee', 'toast', 'dinner', 'steak', 'salad'] },
86 { id: 'architecture', name: 'Architecture', keys: ['cubes', 'towers', 'facets', 'skyline', 'glass'] },
87 { id: 'videos', name: 'Videos', keys: ['stars', 'falls', 'surf'] },
88];
89
90const MAX = 10; // the most items one post can carry
91// The picker opens with three photos chosen so the preview is populated. Start from an empty array in your app.
92const PRESELECTED: Key[] = ['lake', 'beach', 'bowl'];
93
94const src = (key: Key, px: number) => `https://images.unsplash.com/photo-${LIBRARY[key].id}?w=${px}&q=80&fit=crop`;
95
96// ─── Palette ────────────────────────────────────────────────────────────────
97
98const COLUMNS = 3;
99const GAP = 2;
100const COLUMN_MAX = 520; // on tablets and the web the picker stays a centred column
101const BAR_H = 52;
102const THUMB = 52;
103const SUCCESS = '#16A34A';
104const POP = { damping: 11, stiffness: 300, mass: 0.6 };
105const PRESS = { damping: 16, stiffness: 320, mass: 0.6 };
106const SOFT = { damping: 20, stiffness: 240, mass: 0.8 };
107
108function usePalette() {
109 const dark = useColorScheme() === 'dark';
110 const accent = dark ? ACCENT_DARK : ACCENT;
111 return {
112 dark,
113 bg: dark ? '#000000' : '#FFFFFF',
114 surface: dark ? '#1A1A1D' : '#F4F4F5',
115 raised: dark ? '#1F1F23' : '#FFFFFF',
116 fg: dark ? '#FAFAFA' : '#0A0A0A',
117 muted: dark ? '#8E8E93' : '#71717A',
118 faint: dark ? '#4A4A50' : '#C4C4CA',
119 border: dark ? '#2A2A2E' : '#E4E4E7',
120 track: dark ? '#2C2C31' : '#E4E4E7',
121 pressed: dark ? '#2A2A2F' : '#F0F0F2',
122 accent,
123 accentSoft: dark ? tint(ACCENT_DARK, 0.2) : tint(ACCENT, 0.12),
124 accentPressed: shade(accent, 0.12),
125 cameraTop: dark ? '#26262B' : '#EDEDF0',
126 cameraBottom: dark ? '#141416' : '#DCDCE1',
127 error: dark ? '#FF6B6B' : '#DC2F35',
128 backdrop: dark ? 'rgba(0,0,0,0.6)' : 'rgba(10,10,10,0.38)',
129 };
130}
131type Palette = ReturnType<typeof usePalette>;
132
133// ─── Small controls ─────────────────────────────────────────────────────────
134
135function PressableScale({ children, onPress, label, to = 0.96, disabled }: { children: ReactNode; onPress?: () => void; label: string; to?: number; disabled?: boolean }) {
136 const scale = useSharedValue(1);
137 const style = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));
138 return (
139 <Pressable
140 role="button"
141 aria-label={label}
142 aria-disabled={disabled}
143 disabled={disabled}
144 onPress={onPress}
145 onPressIn={() => (scale.value = withSpring(to, PRESS))}
146 onPressOut={() => (scale.value = withSpring(1, PRESS))}
147 >
148 <Animated.View style={style}>{children}</Animated.View>
149 </Pressable>
150 );
151}
152
153/** A photo that fades in over its tinted placeholder once it has loaded. */
154function FadeImage({ uri, label, color }: { uri: string; label: string; color: string }) {
155 const o = useSharedValue(0);
156 const style = useAnimatedStyle(() => ({ opacity: o.value }));
157 return (
158 <View style={[styles.fill, { backgroundColor: color }]}>
159 <Animated.View style={[styles.fill, style]}>
160 <Image source={{ uri }} alt={label} resizeMode="cover" onLoad={() => (o.value = withTiming(1, { duration: 360 }))} style={styles.fill} />
161 </Animated.View>
162 </View>
163 );
164}
165
166// ─── Grid tiles ─────────────────────────────────────────────────────────────
167
168/** The selection mark: an empty ring until picked, then the pick's number springs in. A new number pops again. */
169function OrderBadge({ order, color }: { order: number; color: string }) {
170 const s = useSharedValue(0);
171 const shown = useRef(order);
172 if (order > 0) shown.current = order;
173 useEffect(() => {
174 if (order > 0) {
175 s.value = 0.3;
176 s.value = withSpring(1, POP);
177 } else {
178 s.value = withTiming(0, { duration: 140 });
179 }
180 }, [order, s]);
181 const fill = useAnimatedStyle(() => ({ opacity: Math.min(1, s.value * 2), transform: [{ scale: s.value }] }));
182 return (
183 <View pointerEvents="none" style={styles.badge}>
184 <View style={styles.badgeRing} />
185 <Animated.View style={[styles.badgeFill, { backgroundColor: color }, fill]}>
186 <Text style={styles.badgeText}>{shown.current || ''}</Text>
187 </Animated.View>
188 </View>
189 );
190}
191
192type TileProps = { photo: Key; index: number; order: number; nudge: number; onToggle: (key: Key) => void; onPreview: (key: Key) => void; pal: Palette };
193
194function PhotoTile({ photo, index, order, nudge, onToggle, onPreview, pal }: TileProps) {
195 const item = LIBRARY[photo];
196 const selected = order > 0;
197 const enter = useSharedValue(0);
198 const sel = useSharedValue(selected ? 1 : 0);
199 const press = useSharedValue(0);
200 const x = useSharedValue(0);
201
202 // Tiles arrive in a short cascade, on load and again whenever the album changes.
203 useEffect(() => {
204 enter.value = withDelay(40 + index * 24, withTiming(1, { duration: 360, easing: Easing.out(Easing.cubic) }));
205 }, [enter, index]);
206 useEffect(() => {
207 sel.value = withSpring(selected ? 1 : 0, { damping: 14, stiffness: 260, mass: 0.6 });
208 }, [selected, sel]);
209 // Tapping a photo past the limit shakes it instead of selecting it.
210 useEffect(() => {
211 if (!nudge) return;
212 x.value = withSequence(withTiming(-6, { duration: 50 }), withTiming(6, { duration: 60 }), withTiming(-4, { duration: 60 }), withTiming(4, { duration: 60 }), withTiming(0, { duration: 50 }));
213 }, [nudge, x]);
214
215 const cell = useAnimatedStyle(() => ({
216 opacity: enter.value,
217 transform: [{ translateX: x.value }, { translateY: (1 - enter.value) * 14 }, { scale: 0.92 + enter.value * 0.08 }],
218 }));
219 const inner = useAnimatedStyle(() => ({
220 borderRadius: sel.value * 14,
221 transform: [{ scale: 1 - sel.value * 0.14 - press.value * 0.04 }],
222 }));
223 const ring = useAnimatedStyle(() => ({ opacity: sel.value, borderRadius: sel.value * 14 + 4 }));
224
225 return (
226 <Animated.View style={[styles.cell, cell]}>
227 <Pressable
228 role="checkbox"
229 aria-checked={selected}
230 aria-label={`${item.duration ? 'Video' : 'Photo'}: ${item.label}`}
231 onPress={() => onToggle(photo)}
232 onLongPress={() => onPreview(photo)}
233 delayLongPress={320}
234 onPressIn={() => (press.value = withSpring(1, PRESS))}
235 onPressOut={() => (press.value = withSpring(0, PRESS))}
236 style={[styles.fill, { backgroundColor: pal.accentSoft }]}
237 >
238 <Animated.View style={[styles.tileInner, inner]}>
239 <FadeImage uri={src(photo, 400)} label={item.label} color={item.tint} />
240 {item.duration ? (
241 <>
242 <LinearGradient pointerEvents="none" colors={['rgba(0,0,0,0)', 'rgba(0,0,0,0.5)']} style={styles.tileShade} />
243 <View pointerEvents="none" style={styles.duration}>
244 <Play size={9} color="#FFFFFF" fill="#FFFFFF" />
245 <Text style={styles.durationText}>{item.duration}</Text>
246 </View>
247 </>
248 ) : null}
249 </Animated.View>
250 {/* The ring sits just outside the shrunken photo, on the tile's accent wash. */}
251 <Animated.View pointerEvents="none" style={[styles.ring, { borderColor: pal.accent }, ring]} />
252 <OrderBadge order={order} color={pal.accent} />
253 </Pressable>
254 </Animated.View>
255 );
256}
257
258function CameraTile({ index, pal }: { index: number; pal: Palette }) {
259 const enter = useSharedValue(0);
260 const press = useSharedValue(0);
261 useEffect(() => {
262 enter.value = withDelay(40 + index * 24, withTiming(1, { duration: 360, easing: Easing.out(Easing.cubic) }));
263 }, [enter, index]);
264 const cell = useAnimatedStyle(() => ({ opacity: enter.value, transform: [{ scale: 0.92 + enter.value * 0.08 }] }));
265 const icon = useAnimatedStyle(() => ({ transform: [{ scale: 1 - press.value * 0.12 }] }));
266 return (
267 <Animated.View style={[styles.cell, cell]}>
268 <Pressable
269 role="button"
270 aria-label="Take a photo"
271 onPressIn={() => (press.value = withSpring(1, PRESS))}
272 onPressOut={() => (press.value = withSpring(0, PRESS))}
273 style={styles.fill}
274 >
275 <LinearGradient colors={[pal.cameraTop, pal.cameraBottom]} style={styles.fill} />
276 {(['cornerTL', 'cornerTR', 'cornerBL', 'cornerBR'] as const).map((k) => (
277 <View key={k} pointerEvents="none" style={[styles.corner, styles[k], { borderColor: pal.faint }]} />
278 ))}
279 <Animated.View pointerEvents="none" style={[styles.cameraBody, icon]}>
280 <View style={[styles.cameraIcon, { backgroundColor: pal.raised }, pal.dark ? styles.liftDark : styles.liftLight]}>
281 <Camera size={22} color={pal.fg} strokeWidth={2} />
282 </View>
283 <Text style={[styles.cameraLabel, { color: pal.muted }]}>Camera</Text>
284 </Animated.View>
285 </Pressable>
286 </Animated.View>
287 );
288}
289
290// ─── Album menu: drops from the top bar, rows with a cover, a count and a tick ─
291
292function AlbumMenu({ open, current, onPick, onClose, top, pal }: { open: boolean; current: string; onPick: (id: string) => void; onClose: () => void; top: number; pal: Palette }) {
293 const [mounted, setMounted] = useState(false);
294 const t = useSharedValue(0);
295 useEffect(() => {
296 if (!open) {
297 t.value = withTiming(0, { duration: 180, easing: Easing.in(Easing.cubic) });
298 const id = setTimeout(() => setMounted(false), 200);
299 return () => clearTimeout(id);
300 }
301 setMounted(true);
302 t.value = withSpring(1, SOFT);
303 }, [open, t]);
304 const backdrop = useAnimatedStyle(() => ({ opacity: Math.min(1, t.value) }));
305 const panel = useAnimatedStyle(() => ({
306 opacity: Math.min(1, t.value * 1.4),
307 transform: [{ translateY: (1 - t.value) * -14 }, { scale: 0.94 + t.value * 0.06 }],
308 }));
309 if (!mounted) return null;
310 return (
311 <View style={[styles.overlay, { top }]} pointerEvents={open ? 'auto' : 'none'}>
312 <Animated.View style={[StyleSheet.absoluteFill, { backgroundColor: pal.backdrop }, backdrop]}>
313 <Pressable aria-label="Close albums" onPress={onClose} style={styles.fill} />
314 </Animated.View>
315 <Animated.View role="menu" aria-label="Albums" style={[styles.menu, { backgroundColor: pal.raised, borderColor: pal.border }, panel]}>
316 {ALBUMS.map((album, i) => {
317 const active = album.id === current;
318 const videos = album.id === 'videos';
319 return (
320 <Pressable
321 key={album.id}
322 role="menuitem"
323 aria-label={`${album.name}, ${album.keys.length} items`}
324 aria-selected={active}
325 onPress={() => onPick(album.id)}
326 style={({ pressed }) => [styles.menuRow, pressed && { backgroundColor: pal.pressed }]}
327 >
328 <View style={styles.cover}>
329 <FadeImage uri={src(album.keys[0], 160)} label={`${album.name} cover`} color={LIBRARY[album.keys[0]].tint} />
330 </View>
331 <View style={[styles.menuText, i > 0 && styles.menuRule, i > 0 && { borderTopColor: pal.border }]}>
332 <View style={styles.menuTitles}>
333 <Text style={[styles.menuName, { color: pal.fg }]}>{album.name}</Text>
334 <Text style={[styles.menuCount, { color: pal.muted }]}>
335 {album.keys.length} {videos ? 'videos' : 'items'}
336 </Text>
337 </View>
338 {active ? (
339 <Animated.View entering={ZoomIn.springify().damping(13)} style={[styles.menuTick, { backgroundColor: pal.accent }]}>
340 <Check size={13} color={ON_ACCENT} strokeWidth={3.2} />
341 </Animated.View>
342 ) : null}
343 </View>
344 </Pressable>
345 );
346 })}
347 </Animated.View>
348 </View>
349 );
350}
351
352// ─── Preview: hold a photo to see it larger ─────────────────────────────────
353
354function Preview({ photo, order, onClose, onToggle, width, pal }: { photo: Key | null; order: number; onClose: () => void; onToggle: (key: Key) => void; width: number; pal: Palette }) {
355 const [shown, setShown] = useState<Key | null>(null);
356 const t = useSharedValue(0);
357 useEffect(() => {
358 if (!photo) {
359 t.value = withTiming(0, { duration: 200, easing: Easing.in(Easing.cubic) });
360 const id = setTimeout(() => setShown(null), 220);
361 return () => clearTimeout(id);
362 }
363 setShown(photo);
364 t.value = withSpring(1, { damping: 17, stiffness: 220, mass: 0.8 });
365 }, [photo, t]);
366 const backdrop = useAnimatedStyle(() => ({ opacity: Math.min(1, t.value) }));
367 const card = useAnimatedStyle(() => ({
368 opacity: Math.min(1, t.value * 1.6),
369 transform: [{ translateY: (1 - t.value) * 24 }, { scale: 0.82 + t.value * 0.18 }],
370 }));
371 if (!shown) return null;
372 const item = LIBRARY[shown];
373 const selected = order > 0;
374 const w = width - 32;
375 return (
376 <View style={[StyleSheet.absoluteFill, styles.preview]} pointerEvents={photo ? 'auto' : 'none'}>
377 <Animated.View style={[StyleSheet.absoluteFill, styles.previewBackdrop, backdrop]}>
378 <Pressable aria-label="Close preview" onPress={onClose} style={styles.fill} />
379 </Animated.View>
380 <Animated.View role="dialog" aria-label={item.label} style={[styles.previewCard, { width: w, backgroundColor: pal.raised }, card]}>
381 <View style={[styles.previewPhoto, { height: Math.round(w * 1.12) }]}>
382 <FadeImage key={shown} uri={src(shown, 900)} label={item.label} color={item.tint} />
383 {item.duration ? (
384 <View pointerEvents="none" style={styles.previewPlay}>
385 <Play size={26} color="#FFFFFF" fill="#FFFFFF" />
386 </View>
387 ) : null}
388 <View style={styles.previewClose}>
389 <PressableScale label="Close" onPress={onClose} to={0.9}>
390 <View style={styles.previewCloseDisc}>
391 <X size={18} color="#FFFFFF" strokeWidth={2.4} />
392 </View>
393 </PressableScale>
394 </View>
395 </View>
396 <View style={styles.previewFoot}>
397 <View style={styles.previewText}>
398 <Text numberOfLines={1} style={[styles.previewTitle, { color: pal.fg }]}>
399 {item.label}
400 </Text>
401 <Text style={[styles.previewMeta, { color: pal.muted }]}>
402 {item.taken}
403 {item.duration ? ` · Video ${item.duration}` : ''}
404 </Text>
405 </View>
406 <PressableScale label={selected ? 'Remove from selection' : 'Select'} onPress={() => onToggle(shown)}>
407 <View style={[styles.previewPick, selected ? { backgroundColor: pal.accent, borderColor: pal.accent } : { borderColor: pal.border }]}>
408 {selected ? <Check size={15} color={ON_ACCENT} strokeWidth={3} /> : null}
409 <Text style={[styles.previewPickLabel, { color: selected ? ON_ACCENT : pal.fg }]}>{selected ? `Selected ${order}` : 'Select'}</Text>
410 </View>
411 </PressableScale>
412 </View>
413 </Animated.View>
414 </View>
415 );
416}
417
418// ─── Tray: the picks in order, and the button that adds them ────────────────
419
420function AddButton({ count, done, onPress, pal }: { count: number; done: boolean; onPress: () => void; pal: Palette }) {
421 const pop = useSharedValue(1);
422 const shown = useRef(count);
423 if (count > 0) shown.current = count;
424 useEffect(() => {
425 pop.value = 0.5;
426 pop.value = withSpring(1, POP);
427 }, [count, pop]);
428 const number = useAnimatedStyle(() => ({ transform: [{ scale: pop.value }] }));
429 return (
430 <PressableScale label={`Add ${shown.current} to post`} onPress={onPress} disabled={done || count === 0}>
431 {done ? (
432 <View style={[styles.add, styles.addDone]}>
433 <Animated.View entering={ZoomIn.springify().damping(11)}>
434 <Check size={20} color="#FFFFFF" strokeWidth={3} />
435 </Animated.View>
436 <Text style={styles.addLabel}>Added</Text>
437 </View>
438 ) : (
439 <View style={[styles.add, { backgroundColor: pal.accent, shadowColor: pal.accent, shadowOpacity: 0.34, shadowRadius: 14, shadowOffset: { width: 0, height: 6 } }]}>
440 <Text style={styles.addLabel}>Add</Text>
441 <Animated.View style={[styles.addCount, number]}>
442 <Text style={[styles.addCountText, { color: pal.accent }]}>{shown.current}</Text>
443 </Animated.View>
444 </View>
445 )}
446 </PressableScale>
447 );
448}
449
450function Tray({ picks, done, onRemove, onAdd, bottom, pal }: { picks: Key[]; done: boolean; onRemove: (key: Key) => void; onAdd: () => void; bottom: number; pal: Palette }) {
451 const open = picks.length > 0;
452 const height = THUMB + 28 + bottom;
453 const t = useSharedValue(open ? 1 : 0);
454 const strip = useRef<ComponentRef<typeof ScrollView>>(null);
455 const before = useRef(picks.length);
456 useEffect(() => {
457 t.value = withSpring(open ? 1 : 0, SOFT);
458 }, [open, t]);
459 // A new pick scrolls the strip to show it.
460 useEffect(() => {
461 if (picks.length > before.current) setTimeout(() => strip.current?.scrollToEnd({ animated: true }), 60);
462 before.current = picks.length;
463 }, [picks.length]);
464 const style = useAnimatedStyle(() => ({ transform: [{ translateY: (1 - t.value) * (height + 24) }] }));
465 return (
466 <Animated.View
467 aria-label="Selected items"
468 pointerEvents={open ? 'auto' : 'none'}
469 style={[styles.tray, { backgroundColor: pal.bg, borderTopColor: pal.border, paddingBottom: bottom + 12 }, pal.dark ? styles.trayDark : styles.trayLight, style]}
470 >
471 <ScrollView ref={strip} horizontal showsHorizontalScrollIndicator={false} style={styles.strip} contentContainerStyle={styles.stripContent}>
472 {picks.map((key, i) => (
473 <Animated.View key={key} entering={ZoomIn.springify().damping(13).stiffness(260)} exiting={ZoomOut.duration(140)} layout={LinearTransition.springify().damping(18).stiffness(220)}>
474 <Pressable role="button" aria-label={`Remove item ${i + 1}: ${LIBRARY[key].label}`} onPress={() => onRemove(key)} style={({ pressed }) => [styles.thumbSlot, { opacity: pressed ? 0.6 : 1 }]}>
475 <View style={styles.thumb}>
476 <FadeImage uri={src(key, 160)} label={LIBRARY[key].label} color={LIBRARY[key].tint} />
477 </View>
478 <View style={[styles.thumbRemove, { backgroundColor: pal.fg, borderColor: pal.bg }]}>
479 <X size={10} color={pal.bg} strokeWidth={3.4} />
480 </View>
481 </Pressable>
482 </Animated.View>
483 ))}
484 </ScrollView>
485 <AddButton count={picks.length} done={done} onPress={onAdd} pal={pal} />
486 </Animated.View>
487 );
488}
489
490// ─── Screen ─────────────────────────────────────────────────────────────────
491
492const CAMERA = 'camera' as const;
493
494export default function PhotoPickerScreen() {
495 const c = usePalette();
496 const insets = useSafeAreaInsets();
497 const { width } = useWindowDimensions();
498 const column = Math.min(width, COLUMN_MAX);
499 const [albumId, setAlbumId] = useState(ALBUMS[0].id);
500 const [menuOpen, setMenuOpen] = useState(false);
501 const [picks, setPicks] = useState<Key[]>(PRESELECTED);
502 const [preview, setPreview] = useState<Key | null>(null);
503 const [nudge, setNudge] = useState<{ key: Key; n: number } | null>(null);
504 const [overLimit, setOverLimit] = useState(false);
505 const [done, setDone] = useState(false);
506 const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
507 const limitTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
508 const grid = useRef<ComponentRef<typeof ScrollView>>(null);
509 const chevron = useSharedValue(0);
510 const hintX = useSharedValue(0);
511
512 useEffect(
513 () => () => {
514 timers.current.forEach(clearTimeout);
515 if (limitTimer.current) clearTimeout(limitTimer.current);
516 },
517 []
518 );
519 useEffect(() => {
520 chevron.value = withSpring(menuOpen ? 1 : 0, SOFT);
521 }, [menuOpen, chevron]);
522
523 const album = ALBUMS.find((a) => a.id === albumId) ?? ALBUMS[0];
524 const cells: (Key | typeof CAMERA)[] = [CAMERA, ...album.keys];
525 const rows: (Key | typeof CAMERA | null)[][] = [];
526 for (let i = 0; i < cells.length; i += COLUMNS) {
527 const row: (Key | typeof CAMERA | null)[] = cells.slice(i, i + COLUMNS);
528 while (row.length < COLUMNS) row.push(null);
529 rows.push(row);
530 }
531
532 // Deselecting drops the photo from the list, so every later pick moves up a number.
533 const toggle = (key: Key) => {
534 if (done) return;
535 if (picks.includes(key)) {
536 setPicks((p) => p.filter((k) => k !== key));
537 setOverLimit(false);
538 return;
539 }
540 if (picks.length >= MAX) {
541 setNudge((s) => ({ key, n: (s?.n ?? 0) + 1 }));
542 setOverLimit(true);
543 hintX.value = withSequence(withTiming(-7, { duration: 50 }), withTiming(7, { duration: 60 }), withTiming(-5, { duration: 60 }), withTiming(5, { duration: 60 }), withTiming(0, { duration: 50 }));
544 if (limitTimer.current) clearTimeout(limitTimer.current);
545 limitTimer.current = setTimeout(() => setOverLimit(false), 2600);
546 return;
547 }
548 setPicks((p) => [...p, key]);
549 };
550
551 const pickAlbum = (id: string) => {
552 setMenuOpen(false);
553 if (id === albumId) return;
554 setAlbumId(id);
555 grid.current?.scrollTo({ y: 0, animated: false });
556 };
557
558 // Replace with handing the picks to your composer and closing the picker.
559 const add = () => {
560 if (!picks.length || done) return;
561 setDone(true);
562 setMenuOpen(false);
563 timers.current.push(setTimeout(() => setPicks([]), 1100));
564 timers.current.push(setTimeout(() => setDone(false), 1500));
565 };
566
567 const chevronStyle = useAnimatedStyle(() => ({ transform: [{ rotate: `${chevron.value * 180}deg` }] }));
568 const hintStyle = useAnimatedStyle(() => ({ transform: [{ translateX: hintX.value }] }));
569
570 const count = picks.length;
571 const canAdd = count > 0 && !done;
572 const hint = overLimit ? `Up to ${MAX} items. Remove one first.` : count === 0 ? 'Tap to select, hold to preview' : `${count} of ${MAX} selected`;
573 const trayHeight = THUMB + 28 + insets.bottom;
574
575 return (
576 <View style={[styles.screen, { backgroundColor: c.bg }]}>
577 <View style={[styles.column, { width: column }]}>
578 {/* Opaque top bar: Cancel, the album switcher, Add */}
579 <View style={[styles.bar, { marginTop: insets.top }]}>
580 <Pressable role="button" aria-label="Cancel" hitSlop={8} style={({ pressed }) => [styles.barSide, { opacity: pressed ? 0.5 : 1 }]}>
581 <Text style={[styles.barAction, { color: c.fg }]}>Cancel</Text>
582 </Pressable>
583 <PressableScale label={`Album: ${album.name}`} onPress={() => setMenuOpen((v) => !v)}>
584 <View aria-expanded={menuOpen} style={[styles.switcher, { backgroundColor: c.surface }]}>
585 <Text style={[styles.switcherLabel, { color: c.fg }]}>{album.name}</Text>
586 <Animated.View style={chevronStyle}>
587 <ChevronDown size={16} color={c.fg} strokeWidth={2.6} />
588 </Animated.View>
589 </View>
590 </PressableScale>
591 <Pressable
592 role="button"
593 aria-label="Add"
594 aria-disabled={!canAdd}
595 disabled={!canAdd}
596 hitSlop={8}
597 onPress={add}
598 style={({ pressed }) => [styles.barSide, styles.barEnd, { opacity: pressed ? 0.5 : 1 }]}
599 >
600 <Text style={[styles.barAction, styles.barAdd, { color: canAdd ? c.accent : c.faint }]}>Add</Text>
601 </Pressable>
602 </View>
603
604 {/* How many are picked, as a sentence and as ten segments */}
605 <View style={[styles.hintRow, { borderBottomColor: c.border }]}>
606 <Animated.Text role={overLimit ? 'alert' : undefined} numberOfLines={1} style={[styles.hint, { color: overLimit ? c.error : c.muted }, hintStyle]}>
607 {hint}
608 </Animated.Text>
609 <View style={styles.meter} aria-label={`${count} of ${MAX} selected`}>
610 {Array.from({ length: MAX }, (_, i) => (
611 <View key={i} style={[styles.meterDot, { backgroundColor: i < count ? (overLimit ? c.error : c.accent) : c.track }]} />
612 ))}
613 </View>
614 </View>
615
616 <ScrollView ref={grid} showsVerticalScrollIndicator={false} contentContainerStyle={[styles.grid, { paddingBottom: count > 0 ? trayHeight + GAP : insets.bottom + GAP }]}>
617 {rows.map((row, r) => (
618 <View key={`${album.id}-${r}`} style={styles.gridRow}>
619 {row.map((cell, i) => {
620 const index = r * COLUMNS + i;
621 if (cell === null) return <View key={`gap-${i}`} style={styles.cell} />;
622 if (cell === CAMERA) return <CameraTile key={`${album.id}-camera`} index={index} pal={c} />;
623 return (
624 <PhotoTile
625 key={`${album.id}-${cell}`}
626 photo={cell}
627 index={index}
628 order={picks.indexOf(cell) + 1}
629 nudge={nudge?.key === cell ? nudge.n : 0}
630 onToggle={toggle}
631 onPreview={setPreview}
632 pal={c}
633 />
634 );
635 })}
636 </View>
637 ))}
638 <Text style={[styles.gridFoot, { color: c.muted }]}>
639 {album.keys.length} items in {album.name}
640 </Text>
641 </ScrollView>
642
643 <Tray picks={picks} done={done} onRemove={toggle} onAdd={add} bottom={insets.bottom} pal={c} />
644 <AlbumMenu open={menuOpen} current={albumId} onPick={pickAlbum} onClose={() => setMenuOpen(false)} top={insets.top + BAR_H} pal={c} />
645 <Preview photo={preview} order={preview ? picks.indexOf(preview) + 1 : 0} onClose={() => setPreview(null)} onToggle={toggle} width={column} pal={c} />
646 </View>
647 </View>
648 );
649}
650
651// ─── Styles ─────────────────────────────────────────────────────────────────
652
653const styles = StyleSheet.create({
654 screen: { flex: 1, alignItems: 'center' },
655 column: { flex: 1, overflow: 'hidden' },
656 fill: { flex: 1 },
657
658 // Top bar
659 bar: { height: BAR_H, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 16 },
660 barSide: { width: 76, height: 40, justifyContent: 'center' },
661 barEnd: { alignItems: 'flex-end' },
662 barAction: { fontSize: 16.5, letterSpacing: -0.2 },
663 barAdd: { fontWeight: '700' },
664 switcher: { height: 38, borderRadius: 19, paddingLeft: 16, paddingRight: 12, flexDirection: 'row', alignItems: 'center', gap: 4 },
665 switcherLabel: { fontSize: 16.5, fontWeight: '700', letterSpacing: -0.3 },
666
667 // Selection hint and meter
668 hintRow: { height: 38, paddingHorizontal: 16, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 12, borderBottomWidth: StyleSheet.hairlineWidth },
669 hint: { flex: 1, fontSize: 13.5, fontWeight: '500', letterSpacing: -0.1, fontVariant: ['tabular-nums'] },
670 meter: { flexDirection: 'row', gap: 3 },
671 meterDot: { width: 9, height: 4, borderRadius: 2 },
672
673 // Grid
674 grid: { paddingTop: GAP, gap: GAP },
675 gridRow: { flexDirection: 'row', gap: GAP },
676 cell: { flex: 1, aspectRatio: 1, overflow: 'hidden' },
677 tileInner: { flex: 1, overflow: 'hidden' },
678 ring: { position: 'absolute', top: '4%', left: '4%', right: '4%', bottom: '4%', borderWidth: 2.5 },
679 tileShade: { position: 'absolute', left: 0, right: 0, bottom: 0, height: 44 },
680 duration: { position: 'absolute', left: 8, bottom: 7, flexDirection: 'row', alignItems: 'center', gap: 4 },
681 durationText: { color: '#FFFFFF', fontSize: 12, fontWeight: '700', fontVariant: ['tabular-nums'] },
682 gridFoot: { paddingVertical: 18, textAlign: 'center', fontSize: 13 },
683
684 // Selection badge
685 badge: { position: 'absolute', top: 7, right: 7, width: 26, height: 26 },
686 badgeRing: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, borderRadius: 13, borderWidth: 1.5, borderColor: 'rgba(255,255,255,0.92)', backgroundColor: 'rgba(0,0,0,0.16)' },
687 badgeFill: {
688 position: 'absolute', top: 0, left: 0, right: 0, bottom: 0,
689 borderRadius: 13,
690 borderWidth: 2,
691 borderColor: '#FFFFFF',
692 alignItems: 'center',
693 justifyContent: 'center',
694 shadowColor: '#000',
695 shadowOpacity: 0.25,
696 shadowRadius: 4,
697 shadowOffset: { width: 0, height: 2 },
698 },
699 badgeText: { color: ON_ACCENT, fontSize: 13, fontWeight: '800', fontVariant: ['tabular-nums'] },
700
701 // Camera tile
702 cameraBody: { position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, alignItems: 'center', justifyContent: 'center', gap: 8 },
703 cameraIcon: { width: 48, height: 48, borderRadius: 24, alignItems: 'center', justifyContent: 'center' },
704 liftLight: { shadowColor: '#000', shadowOpacity: 0.1, shadowRadius: 8, shadowOffset: { width: 0, height: 3 } },
705 liftDark: { shadowColor: '#000', shadowOpacity: 0.4, shadowRadius: 8, shadowOffset: { width: 0, height: 3 } },
706 cameraLabel: { fontSize: 12.5, fontWeight: '600' },
707 corner: { position: 'absolute', width: 14, height: 14 },
708 cornerTL: { top: 10, left: 10, borderTopWidth: 2, borderLeftWidth: 2, borderTopLeftRadius: 5 },
709 cornerTR: { top: 10, right: 10, borderTopWidth: 2, borderRightWidth: 2, borderTopRightRadius: 5 },
710 cornerBL: { bottom: 10, left: 10, borderBottomWidth: 2, borderLeftWidth: 2, borderBottomLeftRadius: 5 },
711 cornerBR: { bottom: 10, right: 10, borderBottomWidth: 2, borderRightWidth: 2, borderBottomRightRadius: 5 },
712
713 // Album menu
714 overlay: { position: 'absolute', left: 0, right: 0, bottom: 0 },
715 menu: {
716 marginHorizontal: 12,
717 marginTop: 4,
718 borderRadius: 22,
719 borderWidth: StyleSheet.hairlineWidth,
720 paddingVertical: 6,
721 overflow: 'hidden',
722 transformOrigin: 'top center',
723 shadowColor: '#000',
724 shadowOpacity: 0.22,
725 shadowRadius: 28,
726 shadowOffset: { width: 0, height: 16 },
727 },
728 menuRow: { flexDirection: 'row', alignItems: 'center', paddingLeft: 12, gap: 12 },
729 cover: { width: 50, height: 50, borderRadius: 12, overflow: 'hidden' },
730 menuText: { flex: 1, height: 64, flexDirection: 'row', alignItems: 'center', paddingRight: 16, gap: 12 },
731 menuRule: { borderTopWidth: StyleSheet.hairlineWidth },
732 menuTitles: { flex: 1 },
733 menuName: { fontSize: 16, fontWeight: '600', letterSpacing: -0.2 },
734 menuCount: { marginTop: 2, fontSize: 13, fontVariant: ['tabular-nums'] },
735 menuTick: { width: 22, height: 22, borderRadius: 11, alignItems: 'center', justifyContent: 'center' },
736
737 // Preview
738 preview: { alignItems: 'center', justifyContent: 'center' },
739 previewBackdrop: { backgroundColor: 'rgba(0,0,0,0.78)' },
740 previewCard: { borderRadius: 26, overflow: 'hidden' },
741 previewPhoto: { overflow: 'hidden' },
742 previewPlay: { position: 'absolute', top: '50%', left: '50%', width: 64, height: 64, marginTop: -32, marginLeft: -32, borderRadius: 32, paddingLeft: 4, backgroundColor: 'rgba(0,0,0,0.45)', alignItems: 'center', justifyContent: 'center' },
743 previewClose: { position: 'absolute', top: 12, right: 12 },
744 previewCloseDisc: { width: 36, height: 36, borderRadius: 18, backgroundColor: 'rgba(0,0,0,0.5)', alignItems: 'center', justifyContent: 'center' },
745 previewFoot: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 16, paddingVertical: 14 },
746 previewText: { flex: 1, minWidth: 0 },
747 previewTitle: { fontSize: 15.5, fontWeight: '600', letterSpacing: -0.2 },
748 previewMeta: { marginTop: 3, fontSize: 13, fontVariant: ['tabular-nums'] },
749 previewPick: { height: 40, borderRadius: 20, borderWidth: 1.5, paddingHorizontal: 16, flexDirection: 'row', alignItems: 'center', gap: 6 },
750 previewPickLabel: { fontSize: 14.5, fontWeight: '700', letterSpacing: -0.1, fontVariant: ['tabular-nums'] },
751
752 // Tray
753 tray: { position: 'absolute', left: 0, right: 0, bottom: 0, flexDirection: 'row', alignItems: 'center', paddingTop: 12, paddingRight: 16, gap: 12, borderTopWidth: StyleSheet.hairlineWidth },
754 trayLight: { shadowColor: '#000', shadowOpacity: 0.08, shadowRadius: 16, shadowOffset: { width: 0, height: -6 } },
755 trayDark: { shadowColor: '#000', shadowOpacity: 0.5, shadowRadius: 16, shadowOffset: { width: 0, height: -6 } },
756 strip: { flex: 1 },
757 stripContent: { paddingLeft: 16, paddingRight: 4, gap: 10, alignItems: 'center' },
758 thumbSlot: { width: THUMB + 4, height: THUMB + 4, paddingTop: 4, paddingRight: 4 },
759 thumb: { width: THUMB, height: THUMB, borderRadius: 13, overflow: 'hidden' },
760 thumbRemove: { position: 'absolute', top: 0, right: 0, width: 19, height: 19, borderRadius: 9.5, borderWidth: 2, alignItems: 'center', justifyContent: 'center' },
761 add: { height: 50, borderRadius: 25, paddingLeft: 20, paddingRight: 14, flexDirection: 'row', alignItems: 'center', gap: 8 },
762 addDone: { backgroundColor: SUCCESS, paddingRight: 20, shadowColor: SUCCESS, shadowOpacity: 0.34, shadowRadius: 14, shadowOffset: { width: 0, height: 6 } },
763 addLabel: { color: ON_ACCENT, fontSize: 16.5, fontWeight: '700', letterSpacing: -0.2 },
764 addCount: { minWidth: 26, height: 26, borderRadius: 13, paddingHorizontal: 7, backgroundColor: ON_ACCENT, alignItems: 'center', justifyContent: 'center' },
765 addCountText: { fontSize: 14, fontWeight: '800', fontVariant: ['tabular-nums'] },
766});

More screens like this.

All Social & Feeds