An address book with a large title that collapses into a compact bar, live search that picks out the matching part of each name, and alphabetical sections whose headers pin as you scroll. An A to Z rail jumps to a letter with a pop-up bubble (tap or drag), rows open in place to reveal Call, Message, Video and Mail, and starring someone slides them into the Favourites row.

Details
1import { useEffect, useMemo, useRef, useState, type ComponentRef, type ReactNode } from 'react';2import { Image, Platform, Pressable, ScrollView, StyleSheet, Text, TextInput, View, useColorScheme, type GestureResponderEvent, type LayoutChangeEvent } from 'react-native';3import Animated, {4 cancelAnimation,5 Easing,6 FadeIn,7 FadeInDown,8 FadeOut,9 interpolate,10 interpolateColor,11 LinearTransition,12 useAnimatedScrollHandler,13 useAnimatedStyle,14 useSharedValue,15 withDelay,16 withRepeat,17 withSequence,18 withSpring,19 withTiming,20 ZoomIn,21 ZoomOut,22 type SharedValue,23} from 'react-native-reanimated';24import { LinearGradient } from 'expo-linear-gradient';25import { useSafeAreaInsets } from 'react-native-safe-area-context';26import {27 ChevronUp,28 Mail,29 MessageCircle,30 Phone,31 Search,32 SearchX,33 Settings,34 Star,35 UserPlus,36 UsersRound,37 Video,38 X,39 type LucideIcon,40} from 'lucide-react-native';4142// ─── Brand ──────────────────────────────────────────────────────────────────43// The screen's accent. Every accent colour below derives from these, so changing them rebrands the screen.4445const ACCENT = '#1064FF';46const ACCENT_DARK = '#4C8DFF'; // the accent on dark backgrounds47const ON_ACCENT = '#FFFFFF'; // text and icons on an accent fill4849/** `hex` at `alpha` opacity, as rgba(). */50function tint(hex: string, alpha: number) {51 const n = parseInt(hex.slice(1), 16);52 return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;53}5455// ─── Sample data ────────────────────────────────────────────────────────────5657const photo = (id: string) => `https://images.unsplash.com/photo-${id}?w=200&q=80&fit=crop`;5859const ME = { name: 'Maya Chen', avatar: photo('1534528741775-53994a69daeb') };6061const TINT = {62 violet: ['#A78BFA', '#7C3AED'],63 sky: ['#38BDF8', '#0284C7'],64 amber: ['#FBBF24', '#EA7A0C'],65 rose: ['#FB7185', '#E11D48'],66 emerald: ['#34D399', '#059669'],67 indigo: ['#818CF8', '#4F46E5'],68 teal: ['#2DD4BF', '#0D9488'],69 pink: ['#F472B6', '#DB2777'],70 slate: ['#94A3B8', '#475569'],71} as const;7273type Contact = {74 id: string;75 name: string;76 /** A role or a phone number, whichever you know the person by. */77 detail: string;78 photo?: string;79 tint?: readonly [string, string];80 online?: boolean;81};8283const CONTACTS: Contact[] = [84 { id: 'aisha', name: 'Aisha Rahman', detail: 'Paediatric nurse', tint: TINT.violet },85 { id: 'andre', name: 'Andre Silva', detail: '+1 415 555 0114', tint: TINT.sky },86 { id: 'ben', name: 'Ben Whitaker', detail: 'Landlord, Alder St', tint: TINT.slate },87 { id: 'carmen', name: 'Carmen Ortiz', detail: '+1 510 555 0147', tint: TINT.emerald },88 { id: 'chloe', name: 'Chloe Bennett', detail: 'Flatmate', photo: photo('1524504388940-b1c1722653e1'), online: true },89 { id: 'daniel', name: 'Daniel Kim', detail: 'Engineering lead', tint: TINT.indigo },90 { id: 'elena', name: 'Elena Novak', detail: '+44 20 7946 0958', photo: photo('1544005313-94ddf0286df2') },91 { id: 'emma', name: 'Emma Lindqvist', detail: 'Illustrator', photo: photo('1438761681033-6461ffad8d80') },92 { id: 'felix', name: 'Felix Brandt', detail: 'Climbing partner', tint: TINT.rose },93 { id: 'hannah', name: 'Hannah Brooks', detail: 'Trail guide', photo: photo('1517841905240-472988babdf9') },94 { id: 'isla', name: 'Isla Morgan', detail: 'Dentist, Harbour Dental', tint: TINT.teal },95 { id: 'james', name: 'James Carter', detail: 'Contracts lawyer', photo: photo('1500648767791-00dcc994a43e'), online: true },96 { id: 'leo', name: 'Leo Fischer', detail: 'Photographer', photo: photo('1539571696357-5a69c17a67c6') },97 { id: 'marcus', name: 'Marcus Reyes', detail: 'Personal trainer', photo: photo('1507003211169-0a1dd7228f2d'), online: true },98 { id: 'noor', name: 'Noor Abbasi', detail: '+1 628 555 0190', tint: TINT.teal },99 { id: 'omar', name: 'Omar Haddad', detail: 'Product designer', photo: photo('1506794778202-cad84cf45f1d') },100 { id: 'priya', name: 'Priya Nair', detail: 'UX researcher', photo: photo('1531746020798-e6953c6e8e04') },101 { id: 'ravi', name: 'Ravi Kapoor', detail: '+1 212 555 0176', tint: TINT.pink },102 { id: 'sofia', name: 'Sofia Martinez', detail: '+1 415 555 0132', photo: photo('1494790108377-be9c29b29330'), online: true },103 { id: 'tomas', name: 'Tomás Vidal', detail: 'Neighbour, flat 2A', tint: TINT.amber },104 { id: 'wen', name: 'Wen Li', detail: 'Accountant', tint: TINT.indigo },105 { id: 'yuki', name: 'Yuki Tanaka', detail: '+81 3 5550 1234', tint: TINT.rose },106 { id: 'zoe', name: 'Zoe Castellanos', detail: 'Yoga instructor', photo: photo('1580489944761-15a19d654956') },107];108109// Newest first, so a freshly starred person arrives at the front of the row.110const FAVOURITES = ['sofia', 'james', 'marcus', 'elena', 'priya'];111112const UNREAD_CHATS = 5;113114const TABS: { id: string; icon: LucideIcon }[] = [115 { id: 'Chats', icon: MessageCircle },116 { id: 'Calls', icon: Phone },117 { id: 'Contacts', icon: UsersRound },118 { id: 'Settings', icon: Settings },119];120121const INDEX = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ#'.split('');122123// ─── Helpers ────────────────────────────────────────────────────────────────124125// Lower case with accents removed, one character per character, so a match maps straight back onto the name.126const fold = (s: string) =>127 Array.from(s, (ch) => ch.normalize('NFD')[0])128 .join('')129 .toLowerCase();130const first = (name: string) => name.split(' ')[0];131const letterOf = (name: string) => {132 const l = fold(name)[0].toUpperCase();133 return l >= 'A' && l <= 'Z' ? l : '#';134};135136type Section = { letter: string; items: Contact[] };137138function toSections(list: Contact[]): Section[] {139 const out: Section[] = [];140 for (const contact of list) {141 const letter = letterOf(contact.name);142 const last = out[out.length - 1];143 if (last && last.letter === letter) last.items.push(contact);144 else out.push({ letter, items: [contact] });145 }146 return out;147}148149// ─── Palette ────────────────────────────────────────────────────────────────150151const ONLINE = '#22C55E';152const ALERT = '#FF3B5C';153const GOLD = '#F5A524';154const POP = { damping: 14, stiffness: 280, mass: 0.6 };155const TABULAR = { fontVariant: ['tabular-nums' as const] };156const MOVE = LinearTransition.duration(260);157const WEB = Platform.OS === 'web';158159const BAR = 44;160const TAB_BAR = 56;161const ROW = 60;162const PANEL = 82;163const HEAD = 28;164const FAV_LABEL = 32;165const FAV_ROW = 84;166const LETTER = 16;167const RAIL = 22;168// Everything in the list stops short of the index rail.169const GUTTER = 30;170171function usePalette() {172 const dark = useColorScheme() === 'dark';173 return {174 dark,175 bg: dark ? '#000000' : '#FFFFFF',176 fg: dark ? '#FAFAFA' : '#0A0A0A',177 muted: dark ? '#8E8E93' : '#6E6E76',178 faint: dark ? '#5C5C63' : '#A9A9B2',179 line: dark ? '#1F1F23' : '#ECECEF',180 chip: dark ? '#1A1A1D' : '#F1F1F3',181 press: dark ? '#131315' : '#F5F5F7',182 // Section headers and the expanded row sit one step off the background.183 band: dark ? '#0D0D0F' : '#F6F6F8',184 raised: dark ? '#0F0F12' : '#F7F8FB',185 skeleton: dark ? '#141416' : '#F1F1F3',186 shine: dark ? '#26262A' : '#E2E2E6',187 // Accent as text or a glyph; filled shapes use ACCENT itself under white text.188 accent: dark ? ACCENT_DARK : ACCENT,189 wash: dark ? tint(ACCENT_DARK, 0.17) : tint(ACCENT, 0.09),190 gold: dark ? '#FBBF24' : '#B45309',191 goldWash: dark ? '#F5A52430' : '#F5A52426',192 };193}194195// ─── Small pieces ───────────────────────────────────────────────────────────196197function Tap({ children, label, onPress, to = 0.9 }: { children: ReactNode; label: string; onPress?: () => void; to?: number }) {198 const scale = useSharedValue(1);199 const style = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));200 return (201 <Pressable202 role="button"203 aria-label={label}204 onPress={onPress}205 hitSlop={6}206 onPressIn={() => (scale.value = withSpring(to, POP))}207 onPressOut={() => (scale.value = withSpring(1, POP))}208 >209 <Animated.View style={style}>{children}</Animated.View>210 </Pressable>211 );212}213214/** A round photo that pulses as a placeholder, then fades in once it has loaded. */215function Face({ uri, size, alt = '' }: { uri: string; size: number; alt?: string }) {216 const c = usePalette();217 const shown = useSharedValue(0);218 const pulse = useSharedValue(0.4);219 useEffect(() => {220 pulse.value = withRepeat(withSequence(withTiming(1, { duration: 700 }), withTiming(0.4, { duration: 700 })), -1);221 return () => cancelAnimation(pulse);222 }, [pulse]);223 const image = useAnimatedStyle(() => ({ opacity: shown.value }));224 const placeholder = useAnimatedStyle(() => ({ opacity: (1 - shown.value) * pulse.value }));225 return (226 <View style={[styles.face, { width: size, height: size, borderRadius: size / 2, backgroundColor: c.skeleton }]}>227 <Animated.View style={[StyleSheet.absoluteFill, { backgroundColor: c.shine }, placeholder]} />228 <Animated.View style={[styles.faceImageWrap, image]}>229 <Image230 source={{ uri }}231 alt={alt}232 resizeMode="cover"233 style={styles.faceImage}234 onLoad={() => {235 cancelAnimation(pulse);236 shown.value = withTiming(1, { duration: 320 });237 }}238 />239 </Animated.View>240 </View>241 );242}243244function Initials({ name, tint, size }: { name: string; tint: readonly [string, string]; size: number }) {245 const letters = name246 .split(' ')247 .map((w) => w[0])248 .slice(0, 2)249 .join('');250 return (251 <LinearGradient colors={tint} start={{ x: 0, y: 0 }} end={{ x: 1, y: 1 }} style={[styles.initials, { width: size, height: size, borderRadius: size / 2 }]}>252 <Text style={[styles.initialsText, { fontSize: size * 0.36 }]}>{letters}</Text>253 </LinearGradient>254 );255}256257function Avatar({ contact, size }: { contact: Contact; size: number }) {258 return contact.photo ? <Face uri={contact.photo} size={size} /> : <Initials name={contact.name} tint={contact.tint ?? [ACCENT, ACCENT]} size={size} />;259}260261// ─── Search ─────────────────────────────────────────────────────────────────262263function SearchField({ value, onChange }: { value: string; onChange: (v: string) => void }) {264 const c = usePalette();265 const [focused, setFocused] = useState(false);266 const ring = useSharedValue(0);267 useEffect(() => {268 ring.value = withTiming(focused ? 1 : 0, { duration: 180 });269 }, [focused, ring]);270 const box = useAnimatedStyle(() => ({ borderColor: interpolateColor(ring.value, [0, 1], [c.chip, c.accent]) }));271 return (272 <Animated.View style={[styles.search, { backgroundColor: c.chip }, box]}>273 <Search size={17} color={focused ? c.accent : c.muted} strokeWidth={2.2} />274 <TextInput275 value={value}276 onChangeText={onChange}277 onFocus={() => setFocused(true)}278 onBlur={() => setFocused(false)}279 placeholder="Search contacts"280 placeholderTextColor={c.muted}281 selectionColor={c.accent}282 aria-label="Search contacts"283 autoCapitalize="none"284 autoCorrect={false}285 returnKeyType="search"286 style={[styles.searchInput, { color: c.fg }, Platform.OS === 'web' ? ({ outlineStyle: 'none' } as object) : null]}287 />288 {value ? (289 <Animated.View entering={ZoomIn.duration(140)}>290 <Pressable role="button" aria-label="Clear search" hitSlop={10} onPress={() => onChange('')} style={[styles.searchClear, { backgroundColor: c.faint }]}>291 <X size={12} color={c.chip} strokeWidth={3.2} />292 </Pressable>293 </Animated.View>294 ) : null}295 </Animated.View>296 );297}298299// ─── Favourites ─────────────────────────────────────────────────────────────300301function Favourite({ contact, onPress }: { contact: Contact; onPress: () => void }) {302 const c = usePalette();303 return (304 <Tap label={`${contact.name}, favourite`} onPress={onPress} to={0.93}>305 <View style={styles.fav}>306 <View style={styles.favAvatar}>307 <Avatar contact={contact} size={58} />308 <View style={[styles.favBadge, { backgroundColor: c.bg }]}>309 <Star size={13} color={GOLD} fill={GOLD} strokeWidth={2} />310 </View>311 </View>312 <Text numberOfLines={1} style={[styles.favName, { color: c.fg }]}>313 {first(contact.name)}314 </Text>315 </View>316 </Tap>317 );318}319320function Favourites({ people, settled, onOpen }: { people: Contact[]; settled: boolean; onOpen: (id: string) => void }) {321 const c = usePalette();322 const row = useRef<ComponentRef<typeof ScrollView>>(null);323 const count = people.length;324 const before = useRef(count);325 // A new favourite lands at the front, so bring the front back into view.326 useEffect(() => {327 if (count > before.current) row.current?.scrollTo({ x: 0, animated: true });328 before.current = count;329 }, [count]);330 return (331 <View>332 <View style={styles.favHeader}>333 <Star size={12} color={c.muted} fill={c.muted} strokeWidth={2} />334 <Text role="heading" style={[styles.favHeading, { color: c.muted }]}>335 FAVOURITES336 </Text>337 </View>338 <View style={styles.favRow}>339 {count === 0 ? (340 <Animated.View entering={FadeIn.delay(160).duration(240)} style={[styles.favEmpty, { borderColor: c.line }]}>341 <Star size={15} color={c.faint} strokeWidth={2.2} />342 <Text style={[styles.favEmptyText, { color: c.muted }]}>Star someone to keep them here</Text>343 </Animated.View>344 ) : (345 <ScrollView ref={row} horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={styles.favList}>346 {people.map((p) => (347 <Animated.View key={p.id} layout={MOVE} entering={settled ? ZoomIn.duration(260) : undefined} exiting={ZoomOut.duration(180)}>348 <Favourite contact={p} onPress={() => onOpen(p.id)} />349 </Animated.View>350 ))}351 </ScrollView>352 )}353 {/* The row fades out before the index rail instead of being cut by it */}354 <LinearGradient pointerEvents="none" colors={[`${c.bg}00`, c.bg]} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={styles.favFade} />355 </View>356 </View>357 );358}359360// ─── A contact row: tap it and it opens in place ────────────────────────────361362/** The name, with the part that matches the search picked out. */363function Name({ name, query }: { name: string; query: string }) {364 const c = usePalette();365 const at = query ? fold(name).indexOf(query) : -1;366 const style = [styles.name, { color: c.fg, fontWeight: at < 0 ? ('600' as const) : ('500' as const) }];367 if (at < 0)368 return (369 <Text numberOfLines={1} style={style}>370 {name}371 </Text>372 );373 const chars = Array.from(name);374 const end = at + query.length;375 return (376 <Text numberOfLines={1} style={style}>377 {chars.slice(0, at).join('')}378 <Text style={[styles.nameMatch, { color: c.accent }]}>{chars.slice(at, end).join('')}</Text>379 {chars.slice(end).join('')}380 </Text>381 );382}383384function QuickButton({ icon: Icon, label }: { icon: LucideIcon; label: string }) {385 const c = usePalette();386 return (387 <Tap label={label}>388 <View style={[styles.quick, { backgroundColor: c.chip }]}>389 <Icon size={17} color={c.accent} strokeWidth={2.2} />390 </View>391 </Tap>392 );393}394395function Action({ icon: Icon, label, name }: { icon: LucideIcon; label: string; name: string }) {396 const c = usePalette();397 return (398 <View style={styles.action}>399 {/* Start the call, open the thread or compose the email from here. */}400 <Tap label={`${label} ${name}`}>401 <View style={styles.actionBody}>402 <View style={[styles.actionIcon, { backgroundColor: c.wash }]}>403 <Icon size={19} color={c.accent} strokeWidth={2.2} />404 </View>405 <Text style={[styles.actionLabel, { color: c.fg }]}>{label}</Text>406 </View>407 </Tap>408 </View>409 );410}411412function StarToggle({ name, on, onChange }: { name: string; on: boolean; onChange: () => void }) {413 const c = usePalette();414 const scale = useSharedValue(1);415 const style = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));416 return (417 <View style={styles.action}>418 <Pressable419 role="switch"420 aria-checked={on}421 aria-label={`Favourite ${name}`}422 hitSlop={6}423 onPress={() => {424 scale.value = withSequence(withTiming(on ? 0.82 : 1.28, { duration: 130, easing: Easing.out(Easing.quad) }), withTiming(1, { duration: 240, easing: Easing.out(Easing.back(2.4)) }));425 onChange();426 }}427 style={styles.actionBody}428 >429 <View style={[styles.starIcon, { borderColor: on ? 'transparent' : c.line, backgroundColor: on ? c.goldWash : 'transparent' }]}>430 <Animated.View style={style}>431 <Star size={20} color={on ? GOLD : c.muted} fill={on ? GOLD : 'transparent'} strokeWidth={2.1} />432 </Animated.View>433 </View>434 <Text style={[styles.starLabel, { color: on ? c.gold : c.muted, fontWeight: on ? '600' : '500' }]}>{on ? 'Starred' : 'Favourite'}</Text>435 </Pressable>436 </View>437 );438}439440type RowProps = { contact: Contact; query: string; open: boolean; starred: boolean; divider: boolean; onToggle: () => void; onStar: () => void };441442function ContactRow({ contact, query, open, starred, divider, onToggle, onStar }: RowProps) {443 const c = usePalette();444 const [pressed, setPressed] = useState(false);445 // The actions mount as the row opens and leave once it has closed.446 const [mounted, setMounted] = useState(open);447 const p = useSharedValue(open ? 1 : 0);448 useEffect(() => {449 p.value = withTiming(open ? 1 : 0, { duration: open ? 280 : 220, easing: Easing.out(Easing.cubic) });450 if (open) {451 setMounted(true);452 return;453 }454 const t = setTimeout(() => setMounted(false), 240);455 return () => clearTimeout(t);456 }, [open, p]);457458 const ground = useAnimatedStyle(() => ({ backgroundColor: interpolateColor(p.value, [0, 1], [c.bg, c.raised]) }));459 const panel = useAnimatedStyle(() => ({ height: PANEL * p.value, opacity: interpolate(p.value, [0.35, 1], [0, 1], 'clamp') }));460 const lift = useAnimatedStyle(() => ({ transform: [{ translateY: interpolate(p.value, [0, 1], [-10, 0]) }] }));461 const quick = useAnimatedStyle(() => ({ opacity: interpolate(p.value, [0, 0.5], [1, 0], 'clamp'), transform: [{ scale: interpolate(p.value, [0, 1], [1, 0.8]) }] }));462 const chevron = useAnimatedStyle(() => ({ opacity: interpolate(p.value, [0.5, 1], [0, 1], 'clamp'), transform: [{ rotate: `${interpolate(p.value, [0, 1], [180, 0])}deg` }] }));463 const ring = pressed ? c.press : open ? c.raised : c.bg;464 const name = first(contact.name);465466 return (467 <Animated.View style={ground}>468 {pressed ? <View style={[StyleSheet.absoluteFill, { backgroundColor: c.press }]} /> : null}469 <View style={styles.row}>470 <Pressable471 role="button"472 aria-expanded={open}473 aria-label={`${contact.name}, ${contact.detail}${starred ? ', favourite' : ''}`}474 onPress={onToggle}475 onPressIn={() => setPressed(true)}476 onPressOut={() => setPressed(false)}477 style={styles.rowPress}478 >479 <View style={styles.rowAvatar}>480 <Avatar contact={contact} size={44} />481 {contact.online ? <View style={[styles.onlineDot, { borderColor: ring }]} /> : null}482 </View>483 <View style={styles.rowText}>484 <View style={styles.rowNameLine}>485 <Name name={contact.name} query={query} />486 {starred ? (487 <Animated.View entering={ZoomIn.duration(220)} exiting={ZoomOut.duration(140)}>488 <Star size={12} color={GOLD} fill={GOLD} strokeWidth={2} />489 </Animated.View>490 ) : null}491 </View>492 <Text numberOfLines={1} style={[styles.rowDetail, { color: c.muted }, TABULAR]}>493 {contact.detail}494 </Text>495 </View>496 </Pressable>497 <View style={styles.rowEnd}>498 <Animated.View aria-hidden={open} pointerEvents={open ? 'none' : 'auto'} style={[styles.quickRow, quick]}>499 <QuickButton icon={Phone} label={`Call ${name}`} />500 <QuickButton icon={MessageCircle} label={`Message ${name}`} />501 </Animated.View>502 <Animated.View pointerEvents="none" style={[styles.chevron, chevron]}>503 <ChevronUp size={20} color={c.faint} strokeWidth={2.4} />504 </Animated.View>505 </View>506 </View>507 <Animated.View style={[styles.clip, panel]}>508 {mounted ? (509 <Animated.View style={[styles.panel, lift]}>510 <Action icon={Phone} label="Call" name={name} />511 <Action icon={MessageCircle} label="Message" name={name} />512 <Action icon={Video} label="Video" name={name} />513 <Action icon={Mail} label="Mail" name={name} />514 <View style={[styles.panelRule, { backgroundColor: c.line }]} />515 <StarToggle name={name} on={starred} onChange={onStar} />516 </Animated.View>517 ) : null}518 </Animated.View>519 {divider ? <View style={[styles.divider, { backgroundColor: c.line }]} /> : null}520 </Animated.View>521 );522}523524function SectionHeader({ letter, index, tops, scrollY }: { letter: string; index: number; tops: SharedValue<number[]>; scrollY: SharedValue<number> }) {525 const c = usePalette();526 // Native slides a pinned header out as the next one arrives. On web the two would overlap, so the push is done here.527 const push = useAnimatedStyle(() => {528 const next = tops.value[index + 1];529 const gap = !WEB || next === undefined ? HEAD : next - scrollY.value;530 return { transform: [{ translateY: Math.min(0, Math.max(-HEAD, gap - HEAD)) }] };531 });532 return (533 <Animated.View style={[styles.sectionHeader, { backgroundColor: c.band }, push]}>534 <Text role="heading" style={[styles.sectionLetter, { color: c.muted }]}>535 {letter}536 </Text>537 </Animated.View>538 );539}540541// ─── Index rail: tap or drag a letter to jump to its section ────────────────542543function IndexRail({ live, onPick }: { live: Set<string>; onPick: (letter: string) => void }) {544 const c = usePalette();545 const rail = useRef<ComponentRef<typeof View>>(null);546 const frame = useRef({ y: 0, h: INDEX.length * LETTER });547 const last = useRef('');548 const timer = useRef<ReturnType<typeof setTimeout> | null>(null);549 const [letter, setLetter] = useState('A');550 const [hot, setHot] = useState(false);551 const y = useSharedValue(0);552 const on = useSharedValue(0);553 useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);554555 const pick = (l: string | undefined, dragging = false) => {556 if (!l || !live.has(l) || (dragging && l === last.current)) return;557 last.current = l;558 setLetter(l);559 setHot(true);560 y.value = INDEX.indexOf(l) * LETTER;561 on.value = withSequence(withTiming(1, { duration: 180, easing: Easing.out(Easing.back(1.8)) }), withDelay(650, withTiming(0, { duration: 200 })));562 if (timer.current) clearTimeout(timer.current);563 timer.current = setTimeout(() => setHot(false), 900);564 onPick(l);565 };566 // The rail owns the touch, so a finger can slide down it; the letter under it is worked out from where it is.567 const under = (e: GestureResponderEvent) => INDEX[Math.floor(((e.nativeEvent.pageY - frame.current.y) / frame.current.h) * INDEX.length)];568 const bubble = useAnimatedStyle(() => {569 const k = Math.max(0, on.value);570 return { opacity: Math.min(1, k * 1.6), transform: [{ translateY: y.value }, { translateX: (1 - k) * 12 }, { scale: 0.55 + 0.45 * k }] };571 });572573 return (574 <View pointerEvents="box-none" style={styles.railWrap}>575 <View576 ref={rail}577 role="navigation"578 aria-label="Jump to a letter"579 onLayout={() => rail.current?.measureInWindow((_x: number, top: number, _w: number, height: number) => (frame.current = { y: top, h: height || frame.current.h }))}580 onStartShouldSetResponderCapture={() => true}581 onResponderGrant={(e) => pick(under(e))}582 onResponderMove={(e) => pick(under(e), true)}583 onResponderRelease={() => (last.current = '')}584 onResponderTerminate={() => (last.current = '')}585 style={styles.rail}586 >587 {INDEX.map((l) => {588 const enabled = live.has(l);589 const lit = hot && l === letter;590 return (591 // The press reaches assistive tech and keyboards; touches are handled by the rail above.592 <Pressable key={l} role="button" aria-label={`Jump to ${l === '#' ? 'other' : l}`} aria-disabled={!enabled} disabled={!enabled} onPress={() => pick(l)} style={styles.railItem}>593 <View style={[styles.railDot, { backgroundColor: lit ? ACCENT : 'transparent' }]}>594 <Text style={[styles.railLetter, { color: lit ? ON_ACCENT : enabled ? c.accent : c.faint, opacity: enabled ? 1 : 0.55 }]}>{l}</Text>595 </View>596 </Pressable>597 );598 })}599 <Animated.View pointerEvents="none" style={[styles.bubble, bubble]}>600 {/* A drop with its point towards the rail */}601 <View style={[StyleSheet.absoluteFill, styles.bubbleDrop]} />602 <Text style={styles.bubbleLetter}>{letter}</Text>603 </Animated.View>604 </View>605 </View>606 );607}608609// ─── Empty state ────────────────────────────────────────────────────────────610611function Empty({ query, onReset }: { query: string; onReset: () => void }) {612 const c = usePalette();613 return (614 <View style={styles.empty}>615 <View style={[styles.emptyIcon, { backgroundColor: c.chip }]}>616 <SearchX size={27} color={c.muted} strokeWidth={1.9} />617 </View>618 <Text style={[styles.emptyTitle, { color: c.fg }]}>No contacts found</Text>619 <Text numberOfLines={2} style={[styles.emptyText, { color: c.muted }]}>620 Nobody here is called “{query}”. Check the spelling or try a shorter name.621 </Text>622 <Pressable623 role="button"624 aria-label="Clear the search"625 onPress={onReset}626 style={({ pressed }) => [styles.emptyButton, { backgroundColor: c.wash, opacity: pressed ? 0.6 : 1 }]}627 >628 <Text style={[styles.emptyButtonLabel, { color: c.accent }]}>Clear search</Text>629 </Pressable>630 </View>631 );632}633634// ─── Tab bar ────────────────────────────────────────────────────────────────635636function TabBar() {637 const c = usePalette();638 const insets = useSafeAreaInsets();639 // Replace with your navigator's tab bar.640 const [tab, setTab] = useState('Contacts');641 return (642 <View role="tablist" style={[styles.tabBar, { paddingBottom: insets.bottom, backgroundColor: c.bg, borderTopColor: c.line }]}>643 {TABS.map(({ id, icon: Icon }) => {644 const selected = tab === id;645 const badge = id === 'Chats' && UNREAD_CHATS > 0;646 return (647 <Pressable key={id} role="tab" aria-label={badge ? `${id}, ${UNREAD_CHATS} unread` : id} aria-selected={selected} onPress={() => setTab(id)} style={styles.tab}>648 <View>649 <Icon size={24} color={selected ? c.accent : c.muted} strokeWidth={selected ? 2.4 : 2} />650 {badge ? (651 <View style={[styles.badge, { borderColor: c.bg }]}>652 <Text style={[styles.badgeText, TABULAR]}>{UNREAD_CHATS}</Text>653 </View>654 ) : null}655 </View>656 <Text style={[styles.tabLabel, { fontWeight: selected ? '700' : '500', color: selected ? c.accent : c.muted }]}>{id}</Text>657 </Pressable>658 );659 })}660 </View>661 );662}663664// ─── Screen ─────────────────────────────────────────────────────────────────665666export default function ContactsListScreen() {667 const c = usePalette();668 const insets = useSafeAreaInsets();669 // Replace with your contacts query or the device address book.670 const contacts = useMemo(() => [...CONTACTS].sort((a, b) => fold(a.name).localeCompare(fold(b.name))), []);671 const [favourites, setFavourites] = useState(FAVOURITES);672 const [query, setQuery] = useState('');673 const [expanded, setExpanded] = useState<string | null>(null);674 // Rows stagger in once; after that, rows a search brings back simply fade in.675 const [settled, setSettled] = useState(false);676 useEffect(() => {677 const t = setTimeout(() => setSettled(true), 1200);678 return () => clearTimeout(t);679 }, []);680681 const q = fold(query.trim());682 const searching = q.length > 0;683 const sections = useMemo(() => toSections(q ? contacts.filter((p) => fold(p.name).includes(q)) : contacts), [contacts, q]);684 const shown = sections.reduce((n, s) => n + s.items.length, 0);685 const live = useMemo(() => new Set(sections.map((s) => s.letter)), [sections]);686 const starred = useMemo(() => favourites.map((id) => contacts.find((p) => p.id === id)).filter((p): p is Contact => !!p), [favourites, contacts]);687688 const toggleStar = (id: string) => setFavourites((all) => (all.includes(id) ? all.filter((f) => f !== id) : [id, ...all]));689690 // Where each section starts, from heights the list reports as it lays out.691 const list = useRef<ComponentRef<typeof ScrollView>>(null);692 const topHeight = useRef(0);693 const bodyHeight = useRef<Record<string, number>>({});694 const sectionAt = (letter: string) => sections.findIndex((s) => s.letter === letter);695 const offsetOf = (letter: string) => {696 let y = topHeight.current;697 for (const s of sections) {698 if (s.letter === letter) break;699 y += HEAD + (bodyHeight.current[s.letter] ?? s.items.length * ROW);700 }701 return y;702 };703 const tops = useSharedValue<number[]>([]);704 const measure = () => {705 const next = sections.map((s) => offsetOf(s.letter));706 if (next.length !== tops.value.length || next.some((y, i) => y !== tops.value[i])) tops.value = next;707 };708 useEffect(measure);709 const jump = (letter: string) => list.current?.scrollTo({ y: offsetOf(letter), animated: false });710 // A favourite opens its row in the list. The row that was open above it is about to give its height back.711 const reveal = (id: string) => {712 const person = contacts.find((p) => p.id === id);713 if (!person) return;714 const letter = letterOf(person.name);715 const open = contacts.find((p) => p.id === expanded);716 const closing = open && open.id !== id && sectionAt(letterOf(open.name)) < sectionAt(letter) ? PANEL : 0;717 setExpanded(id);718 list.current?.scrollTo({ y: Math.max(0, offsetOf(letter) - closing), animated: true });719 };720721 const scrollY = useSharedValue(0);722 const onScroll = useAnimatedScrollHandler((e) => {723 scrollY.value = e.contentOffset.y;724 });725 // The large title leaves under the bar as the bar's own title and hairline arrive.726 const largeTitle = useAnimatedStyle(() => ({727 opacity: interpolate(scrollY.value, [0, 40], [1, 0], 'clamp'),728 transform: [{ scale: interpolate(scrollY.value, [-120, 0], [1.1, 1], 'clamp') }],729 }));730 const hairline = useAnimatedStyle(() => ({ opacity: interpolate(scrollY.value, [8, 36], [0, 1], 'clamp') }));731 const barTitle = useAnimatedStyle(() => ({732 opacity: interpolate(scrollY.value, [30, 56], [0, 1], 'clamp'),733 transform: [{ translateY: interpolate(scrollY.value, [30, 56], [6, 0], 'clamp') }],734 }));735736 // Favourites step aside while a search is on.737 const room = useSharedValue(1);738 useEffect(() => {739 room.value = withTiming(searching ? 0 : 1, { duration: 240, easing: Easing.out(Easing.cubic) });740 }, [searching, room]);741 const favouritesBox = useAnimatedStyle(() => ({ height: (FAV_LABEL + FAV_ROW) * room.value, opacity: room.value }));742743 const rise = (i: number) => FadeInDown.delay(60 + i * 70).duration(420);744 const sectionIn = (i: number) => (settled ? FadeIn.duration(200) : FadeInDown.delay(200 + Math.min(i, 5) * 60).duration(380));745 const countLabel = `${contacts.length} contacts`;746747 // The scroll view's children stay a flat list, so every section header has an index it can stick by.748 const children: ReactNode[] = [749 <View750 key="top"751 onLayout={(e: LayoutChangeEvent) => {752 topHeight.current = e.nativeEvent.layout.height;753 measure();754 }} style={styles.top}>755 <Animated.View entering={FadeIn.duration(400)} style={[styles.largeTitle, largeTitle]}>756 <Text role="heading" style={[styles.title, { color: c.fg }]}>757 Contacts758 </Text>759 <View style={styles.countRow}>760 <Text style={[styles.count, { color: c.muted }, TABULAR]}>{countLabel} · </Text>761 <Animated.Text key={favourites.length} entering={FadeInDown.duration(220)} style={[styles.count, { color: c.muted }, TABULAR]}>762 {favourites.length}763 </Animated.Text>764 <Text style={[styles.count, { color: c.muted }]}> {favourites.length === 1 ? 'favourite' : 'favourites'}</Text>765 </View>766 </Animated.View>767 <Animated.View entering={rise(0)} style={styles.searchSlot}>768 <SearchField769 value={query}770 onChange={(v) => {771 setQuery(v);772 setExpanded(null);773 }}774 />775 </Animated.View>776 <Animated.View entering={rise(1)}>777 <Animated.View style={[styles.clip, favouritesBox]}>778 <Favourites people={starred} settled={settled} onOpen={reveal} />779 </Animated.View>780 </Animated.View>781 </View>,782 ];783 const sticky: number[] = [];784 sections.forEach((s, si) => {785 sticky.push(children.length);786 children.push(787 <Animated.View key={`head-${s.letter}`} entering={sectionIn(si)}>788 <SectionHeader letter={s.letter} index={si} tops={tops} scrollY={scrollY} />789 </Animated.View>,790 <Animated.View key={`body-${s.letter}`} entering={sectionIn(si)} onLayout={(e: LayoutChangeEvent) => {791 bodyHeight.current[s.letter] = e.nativeEvent.layout.height;792 measure();793 }}794 >795 {s.items.map((p, i) => (796 <ContactRow797 key={p.id}798 contact={p}799 query={q}800 open={expanded === p.id}801 starred={favourites.includes(p.id)}802 divider={i < s.items.length - 1}803 onToggle={() => setExpanded((id) => (id === p.id ? null : p.id))}804 onStar={() => toggleStar(p.id)}805 />806 ))}807 </Animated.View>808 );809 });810 children.push(811 shown === 0 ? (812 <Animated.View key="empty" entering={FadeIn.delay(120).duration(280)}>813 <Empty query={query.trim()} onReset={() => setQuery('')} />814 </Animated.View>815 ) : (816 <Text key="end" style={[styles.end, { color: c.faint }, TABULAR]}>817 {searching ? `${shown} of ${countLabel}` : countLabel}818 </Text>819 )820 );821822 return (823 <View style={[styles.screen, { backgroundColor: c.bg }]}>824 {/* Header bar: opaque, under the status bar. The list starts below it, so section headers pin to its lower edge. */}825 <View style={[styles.header, { paddingTop: insets.top, backgroundColor: c.bg }]}>826 <View style={styles.bar}>827 <Tap label={`${ME.name}, your profile`}>828 <Face uri={ME.avatar} size={32} />829 </Tap>830 <View pointerEvents="none" style={[StyleSheet.absoluteFill, styles.barCenter]}>831 <Animated.View style={[styles.barTitle, barTitle]}>832 <Text style={[styles.barTitleText, { color: c.fg }]}>Contacts</Text>833 <Text style={[styles.barCount, { color: c.muted }, TABULAR]}>{countLabel}</Text>834 </Animated.View>835 </View>836 {/* Push your new contact form from here. */}837 <Tap label="Add contact">838 <View style={[styles.quick, { backgroundColor: c.wash }]}>839 <UserPlus size={18} color={c.accent} strokeWidth={2.2} />840 </View>841 </Tap>842 </View>843 <Animated.View style={[styles.hairline, { backgroundColor: c.line }, hairline]} />844 </View>845846 <View style={styles.screen}>847 <Animated.ScrollView848 ref={list}849 onScroll={onScroll}850 scrollEventThrottle={16}851 showsVerticalScrollIndicator={false}852 keyboardShouldPersistTaps="handled"853 stickyHeaderIndices={sticky}854 contentContainerStyle={styles.listContent}855 >856 {children}857 </Animated.ScrollView>858 <IndexRail live={live} onPick={jump} />859 </View>860861 <TabBar />862 </View>863 );864}865866// ─── Styles ─────────────────────────────────────────────────────────────────867868const styles = StyleSheet.create({869 screen: { flex: 1 },870 clip: { overflow: 'hidden' },871872 // Avatars873 face: { overflow: 'hidden' },874 faceImageWrap: { flex: 1 },875 faceImage: { width: '100%', height: '100%' },876 initials: { alignItems: 'center', justifyContent: 'center' },877 initialsText: { color: '#fff', fontWeight: '700', letterSpacing: 0.3 },878879 // Header880 header: { zIndex: 2 },881 bar: { height: BAR, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 16 },882 barCenter: { alignItems: 'center', justifyContent: 'center' },883 barTitle: { alignItems: 'center' },884 barTitleText: { fontSize: 16, lineHeight: 20, fontWeight: '600', letterSpacing: -0.2 },885 barCount: { fontSize: 11.5, lineHeight: 14 },886 hairline: { height: 1 },887 top: { paddingTop: 2, paddingBottom: 8 },888 largeTitle: { marginHorizontal: 16, transformOrigin: 'left center' },889 title: { fontSize: 34, lineHeight: 41, fontWeight: '800', letterSpacing: -1 },890 countRow: { flexDirection: 'row', alignItems: 'center' },891 count: { fontSize: 14 },892 listContent: { paddingBottom: 24 },893894 // Search895 searchSlot: { marginTop: 12, marginLeft: 16, marginRight: GUTTER },896 search: { height: 40, borderRadius: 12, borderWidth: 1.5, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 11, gap: 8 },897 searchInput: { flex: 1, height: '100%', padding: 0, fontSize: 16 },898 searchClear: { width: 19, height: 19, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },899900 // Favourites901 fav: { width: 62, alignItems: 'center' },902 favAvatar: { width: 58, height: 58 },903 favBadge: { position: 'absolute', right: -3, bottom: -3, width: 22, height: 22, borderRadius: 11, alignItems: 'center', justifyContent: 'center' },904 favName: { marginTop: 6, fontSize: 12.5, fontWeight: '500' },905 favHeader: { height: FAV_LABEL, flexDirection: 'row', alignItems: 'flex-end', gap: 6, paddingHorizontal: 16, paddingBottom: 8 },906 favHeading: { fontSize: 12.5, fontWeight: '600', letterSpacing: 0.5 },907 favRow: { height: FAV_ROW, marginRight: GUTTER },908 favEmpty: {909 height: 58,910 marginLeft: 16,911 borderRadius: 14,912 borderWidth: 1,913 borderStyle: 'dashed',914 flexDirection: 'row',915 alignItems: 'center',916 justifyContent: 'center',917 gap: 8,918 },919 favEmptyText: { fontSize: 13.5 },920 favList: { paddingLeft: 14, paddingRight: 22, gap: 2 },921 favFade: { position: 'absolute', top: 0, bottom: 0, right: 0, width: 22 },922923 // Contact row924 name: { flexShrink: 1, fontSize: 16, letterSpacing: -0.2 },925 nameMatch: { fontWeight: '800' },926 quick: { width: 36, height: 36, borderRadius: 18, alignItems: 'center', justifyContent: 'center' },927 action: { flex: 1, alignItems: 'center' },928 actionBody: { alignItems: 'center', gap: 5 },929 actionIcon: { width: 44, height: 44, borderRadius: 22, alignItems: 'center', justifyContent: 'center' },930 actionLabel: { fontSize: 11.5, fontWeight: '500' },931 starIcon: { width: 44, height: 44, borderRadius: 22, borderWidth: 1.5, alignItems: 'center', justifyContent: 'center' },932 starLabel: { fontSize: 11.5 },933 row: { height: ROW, flexDirection: 'row', alignItems: 'center', paddingLeft: 16, paddingRight: GUTTER },934 rowPress: { flex: 1, height: ROW, flexDirection: 'row', alignItems: 'center', gap: 12 },935 rowAvatar: { width: 44, height: 44 },936 onlineDot: { position: 'absolute', right: -1, bottom: -1, width: 14, height: 14, borderRadius: 7, backgroundColor: ONLINE, borderWidth: 2.5 },937 rowText: { flex: 1, gap: 2, paddingRight: 8 },938 rowNameLine: { flexDirection: 'row', alignItems: 'center', gap: 5 },939 rowDetail: { fontSize: 13.5 },940 rowEnd: { justifyContent: 'center' },941 quickRow: { flexDirection: 'row', gap: 8 },942 chevron: { position: 'absolute', right: 6 },943 panel: { height: PANEL, flexDirection: 'row', alignItems: 'flex-start', paddingTop: 4, paddingLeft: 8, paddingRight: GUTTER - 6 },944 panelRule: { width: 1, height: 44 },945 divider: { position: 'absolute', left: 72, right: GUTTER, bottom: 0, height: 1 },946 sectionHeader: { height: HEAD, justifyContent: 'center', paddingHorizontal: 16 },947 sectionLetter: { fontSize: 13, fontWeight: '700', letterSpacing: 0.4 },948 end: { paddingTop: 20, textAlign: 'center', fontSize: 13 },949950 // Index rail951 railWrap: { position: 'absolute', top: 0, bottom: 0, right: 0, justifyContent: 'center' },952 rail: { width: RAIL, height: INDEX.length * LETTER },953 railItem: { height: LETTER, alignItems: 'center', justifyContent: 'center' },954 railDot: { width: LETTER, height: LETTER, borderRadius: LETTER / 2, alignItems: 'center', justifyContent: 'center' },955 railLetter: { fontSize: 10.5, lineHeight: 13, fontWeight: '700' },956 bubble: { position: 'absolute', right: RAIL + 10, top: (LETTER - 54) / 2, width: 54, height: 54, alignItems: 'center', justifyContent: 'center' },957 bubbleDrop: { backgroundColor: ACCENT, borderRadius: 27, borderBottomRightRadius: 5, transform: [{ rotate: '-45deg' }] },958 bubbleLetter: { color: ON_ACCENT, fontSize: 25, fontWeight: '800' },959960 // Empty state961 empty: { alignItems: 'center', paddingTop: 56, paddingHorizontal: 40 },962 emptyIcon: { width: 64, height: 64, borderRadius: 32, alignItems: 'center', justifyContent: 'center' },963 emptyTitle: { marginTop: 16, fontSize: 18, fontWeight: '700', letterSpacing: -0.3 },964 emptyText: { marginTop: 6, fontSize: 14.5, lineHeight: 20, textAlign: 'center' },965 emptyButton: { marginTop: 18, height: 38, paddingHorizontal: 18, borderRadius: 19, justifyContent: 'center' },966 emptyButtonLabel: { fontSize: 14.5, fontWeight: '600' },967968 // Tab bar969 tabBar: { borderTopWidth: 1, flexDirection: 'row' },970 tab: { flex: 1, height: TAB_BAR, alignItems: 'center', justifyContent: 'center', gap: 3 },971 badge: {972 position: 'absolute',973 top: -5,974 left: 13,975 minWidth: 18,976 height: 18,977 borderRadius: 9,978 paddingHorizontal: 4,979 backgroundColor: ALERT,980 borderWidth: 2,981 alignItems: 'center',982 justifyContent: 'center',983 },984 badgeText: { color: '#fff', fontSize: 10, fontWeight: '800' },985 tabLabel: { fontSize: 10.5 },986});