Leaderboard

A weekly league leaderboard for a running club: the podium blocks rise one after another on a spring with the winner crowned last, and every score counts up on load and each time you switch Friends, City or Global or This week and All time, while the list re-orders with layout animation and the promotion and demotion lines slide into place. Your own row docks to the edge of the screen while it is scrolled out of view and settles back into its place; tap any row to open a mini profile with this week's daily bars, streak and a Cheer button that bursts into confetti, and tap the league badge or the live countdown for a draggable sheet on leagues and rewards.

leaderboardrankingpodiumleaguefitnessrunninggamificationsticky rowanimationreanimated
Paste into Claude Code Cursor Codex Lovable RapidNative
Live preview · follows the site themeOpen full screen

Details

File
components/patterns/leaderboard.tsx
Lines
1522
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/leaderboard.tsx
1import { useEffect, useId, useMemo, useRef, useState, type ComponentRef, type ReactNode } from 'react';
2import {
3 Image,
4 PanResponder,
5 Pressable,
6 ScrollView,
7 StyleSheet,
8 Text,
9 View,
10 useColorScheme,
11 useWindowDimensions,
12 type LayoutChangeEvent,
13 type StyleProp,
14 type TextStyle,
15 type ViewStyle,
16} from 'react-native';
17import Animated, {
18 cancelAnimation,
19 Easing,
20 FadeIn,
21 FadeInDown,
22 FadeInUp,
23 FadeOut,
24 interpolate,
25 interpolateColor,
26 LinearTransition,
27 runOnJS,
28 useAnimatedReaction,
29 useAnimatedScrollHandler,
30 useAnimatedStyle,
31 useSharedValue,
32 withDelay,
33 withRepeat,
34 withSequence,
35 withSpring,
36 withTiming,
37 ZoomIn,
38 type SharedValue,
39} from 'react-native-reanimated';
40import { LinearGradient } from 'expo-linear-gradient';
41import { useSafeAreaInsets } from 'react-native-safe-area-context';
42import Svg, { Circle, Defs, Line, LinearGradient as SvgLinearGradient, Path, RadialGradient, Rect, Stop } from 'react-native-svg';
43import { ArrowDown, ArrowUp, Check, Clock3, Flame, Gauge, Minus, PartyPopper, X } from 'lucide-react-native';
44
45// ─── Brand ──────────────────────────────────────────────────────────────────
46// The club's ink and name. Every accent colour below derives from these, so changing them rebrands the screen.
47// Medals, leagues and the up / down zones keep their own colours: they mean something, they are not the brand.
48
49const ACCENT = '#2B2D42';
50const ACCENT_DARK = '#4A4C5C'; // the ink as a fill on dark backgrounds, lifted so it reads against black
51const ON_ACCENT = '#FFFFFF'; // text and icons on an ink fill
52const APP_NAME = 'Pacemark';
53
54/** `hex` at `alpha` opacity, as rgba(). */
55function tint(hex: string, alpha: number) {
56 const n = parseInt(hex.slice(1), 16);
57 return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
58}
59
60/** `hex` mixed toward black (amount > 0) or white (amount < 0); amount from -1 to 1. */
61function shade(hex: string, amount: number) {
62 const n = parseInt(hex.slice(1), 16);
63 const target = amount < 0 ? 255 : 0;
64 const p = Math.abs(amount);
65 const c = (v: number) => Math.round(v + (target - v) * p).toString(16).padStart(2, '0');
66 return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`.toUpperCase();
67}
68
69// ─── Sample data ────────────────────────────────────────────────────────────
70
71const photo = (id: string, w = 200) => `https://images.unsplash.com/photo-${id}?w=${w}&q=80&fit=crop`;
72
73type Scope = 'friends' | 'city' | 'global';
74type Span = 'week' | 'all';
75
76type Runner = {
77 id: string;
78 name: string;
79 photo?: string;
80 tone?: number; // initials colour, for runners without a photo
81 days: number[]; // km run each day of this league week, Friday to today
82 allTime: number; // km
83 move: Record<Span, number>; // places moved since yesterday
84 streak: number; // weeks in a row on goal
85 pace: string; // average min per km
86};
87
88const ME_ID = 'ava';
89const LEAGUE = 2; // index in LEAGUES: Granite
90const WEEK = { number: 48, range: 'Nov 27 to Dec 3' };
91// League weeks run Friday to Thursday. Today is Tuesday, so Wednesday and Thursday are still to come.
92const DAYS = ['F', 'S', 'S', 'M', 'T', 'W', 'T'];
93const TODAY = 4;
94// Seconds until the week locks: 2d 14h 08m, plus 47 s so the minute never ticks while the screen settles.
95const ENDS_IN = ((2 * 24 + 14) * 60 + 8) * 60 + 47;
96const WEEK_SECONDS = 7 * 24 * 3600;
97const GROUP = 15; // runners per league group
98const UP = 5; // the top five move up a league
99const DROP = 3; // the bottom three drop one
100const UPDATED = 'Updated 2 min ago';
101
102const RUNNER_LIST: Runner[] = [
103 // Friends
104 { id: 'sofia', name: 'Sofia Reyes', photo: photo('1494790108377-be9c29b29330'), days: [12.4, 0, 21.1, 8.2, 6.5], allTime: 1912, move: { week: 1, all: 0 }, streak: 23, pace: '4:58' },
105 { id: 'liam', name: 'Liam Novak', photo: photo('1500648767791-00dcc994a43e'), days: [10.0, 15.2, 0, 9.8, 9.1], allTime: 2240, move: { week: -1, all: 0 }, streak: 9, pace: '5:06' },
106 { id: 'elena', name: 'Elena Marsh', photo: photo('1438761681033-6461ffad8d80'), days: [8.1, 6.0, 14.5, 0, 12.0], allTime: 1388, move: { week: 2, all: 1 }, streak: 15, pace: '5:12' },
107 { id: 'daniel', name: 'Daniel Okafor', photo: photo('1463453091185-61582044d556'), days: [7.4, 10.2, 5.8, 9.0, 4.3], allTime: 2615, move: { week: -1, all: 0 }, streak: 31, pace: '5:20' },
108 { id: 'noah', name: 'Noah Haddad', photo: photo('1506794778202-cad84cf45f1d'), days: [0, 18.4, 6.1, 5.5, 5.9], allTime: 980, move: { week: 3, all: 0 }, streak: 4, pace: '5:31' },
109 { id: 'zoe', name: 'Zoe Parker', photo: photo('1544005313-94ddf0286df2'), days: [6.2, 8.8, 0, 11.3, 7.6], allTime: 1104, move: { week: -2, all: -1 }, streak: 6, pace: '5:44' },
110 { id: 'marcus', name: 'Marcus Tan', photo: photo('1507003211169-0a1dd7228f2d'), days: [9.5, 0, 12.0, 6.4, 5.4], allTime: 1766, move: { week: -1, all: 0 }, streak: 11, pace: '5:02' },
111 { id: 'maya', name: 'Maya Chen', tone: 0, days: [5.0, 7.5, 10.1, 0, 9.8], allTime: 845, move: { week: 1, all: 0 }, streak: 8, pace: '5:49' },
112 { id: 'lena', name: 'Lena Ortiz', tone: 1, days: [4.2, 12.3, 5.6, 6.0, 3.9], allTime: 1240, move: { week: 0, all: 0 }, streak: 19, pace: '5:37' },
113 { id: 'ava', name: 'Ava Brooks', photo: photo('1580489944761-15a19d654956'), days: [6.8, 0, 11.2, 7.4, 5.7], allTime: 1326, move: { week: 3, all: 1 }, streak: 12, pace: '5:24' },
114 { id: 'sam', name: 'Sam Whitaker', tone: 3, days: [3.1, 9.0, 0, 7.2, 4.1], allTime: 690, move: { week: -2, all: 0 }, streak: 3, pace: '6:05' },
115 { id: 'iris', name: 'Iris Bauer', tone: 4, days: [5.5, 0, 6.8, 4.0, 2.6], allTime: 512, move: { week: -1, all: -1 }, streak: 5, pace: '6:12' },
116 { id: 'ravi', name: 'Ravi Menon', tone: 5, days: [2.0, 6.1, 0, 5.5, 3.0], allTime: 1480, move: { week: 0, all: 0 }, streak: 2, pace: '5:58' },
117 { id: 'grace', name: 'Grace Liu', tone: 6, days: [4.0, 0, 5.2, 3.3, 0], allTime: 402, move: { week: -1, all: 0 }, streak: 1, pace: '6:30' },
118 { id: 'theo', name: 'Theo Brandt', tone: 7, days: [0, 6.0, 0, 3.1, 0], allTime: 1610, move: { week: -2, all: 0 }, streak: 1, pace: '5:51' },
119 // City
120 { id: 'owen', name: 'Owen Hart', photo: photo('1539571696357-5a69c17a67c6'), days: [14.0, 11.2, 0, 16.5, 10.3], allTime: 2940, move: { week: 1, all: 1 }, streak: 27, pace: '4:41' },
121 { id: 'ben', name: 'Ben Carver', photo: photo('1599566150163-29194dcaad36'), days: [9.2, 12.0, 8.8, 0, 13.1], allTime: 3120, move: { week: -1, all: 0 }, streak: 40, pace: '4:52' },
122 { id: 'priya', name: 'Priya Raman', photo: photo('1488426862026-3ee34a7d66df'), days: [11.5, 0, 13.4, 9.9, 7.0], allTime: 1705, move: { week: 2, all: 0 }, streak: 14, pace: '5:08' },
123 { id: 'tess', name: 'Tess Rowan', tone: 2, days: [6.0, 9.5, 7.2, 0, 8.1], allTime: 1180, move: { week: -1, all: 0 }, streak: 7, pace: '5:46' },
124 { id: 'nadia', name: 'Nadia Farouk', tone: 6, days: [5.1, 0, 10.4, 6.6, 5.0], allTime: 870, move: { week: 1, all: 0 }, streak: 3, pace: '5:55' },
125 { id: 'chloe', name: 'Chloe Dumas', tone: 4, days: [7.7, 4.4, 0, 8.0, 4.8], allTime: 640, move: { week: -2, all: 0 }, streak: 6, pace: '6:01' },
126 { id: 'jonah', name: 'Jonah Pike', tone: 5, days: [0, 8.1, 4.9, 0, 6.2], allTime: 455, move: { week: 0, all: 0 }, streak: 2, pace: '6:18' },
127 { id: 'ruth', name: 'Ruth Adeyemi', tone: 7, days: [3.6, 5.0, 0, 4.4, 2.1], allTime: 2410, move: { week: -1, all: 0 }, streak: 33, pace: '6:22' },
128 { id: 'felix', name: 'Felix Grant', tone: 0, days: [0, 4.2, 3.0, 0, 3.4], allTime: 1560, move: { week: -3, all: 0 }, streak: 1, pace: '6:40' },
129 // Global
130 { id: 'yara', name: 'Yara Haddad', photo: photo('1531746020798-e6953c6e8e04'), days: [22.4, 30.5, 14.0, 24.2, 18.6], allTime: 7925, move: { week: 0, all: 1 }, streak: 58, pace: '3:48' },
131 { id: 'mateo', name: 'Mateo Rossi', photo: photo('1527980965255-d3b416303d12'), days: [20.0, 28.8, 0, 26.0, 21.4], allTime: 8610, move: { week: 1, all: 0 }, streak: 44, pace: '3:55' },
132 { id: 'lucas', name: 'Lucas Ferreira', photo: photo('1570295999919-56ceb5ecca61'), days: [18.6, 22.0, 16.4, 12.5, 20.3], allTime: 6880, move: { week: -1, all: 0 }, streak: 36, pace: '4:02' },
133 { id: 'kenji', name: 'Kenji Watanabe', tone: 3, days: [16.2, 25.4, 10.0, 0, 21.9], allTime: 9840, move: { week: 0, all: 0 }, streak: 71, pace: '3:51' },
134 { id: 'freya', name: 'Freya Olsen', photo: photo('1554151228-14d9def656e4'), days: [14.0, 0, 21.3, 18.2, 15.0], allTime: 5410, move: { week: 2, all: 0 }, streak: 29, pace: '4:10' },
135 { id: 'amara', name: 'Amara Okoye', tone: 1, days: [12.4, 19.8, 8.0, 14.6, 9.5], allTime: 7140, move: { week: -1, all: 0 }, streak: 52, pace: '4:05' },
136 { id: 'oskar', name: 'Oskar Lindqvist', photo: photo('1535713875002-d1d0cf377fde'), days: [15.5, 0, 18.0, 13.4, 12.2], allTime: 4315, move: { week: 1, all: 1 }, streak: 18, pace: '4:18' },
137 { id: 'hana', name: 'Hana Kobayashi', tone: 6, days: [10.0, 16.5, 9.2, 12.0, 6.8], allTime: 4760, move: { week: -2, all: 0 }, streak: 24, pace: '4:22' },
138 { id: 'diego', name: 'Diego Alvarez', photo: photo('1547425260-76bcadfb4f2c'), days: [11.2, 14.0, 0, 15.6, 9.9], allTime: 3980, move: { week: 0, all: -1 }, streak: 13, pace: '4:31' },
139 { id: 'ingrid', name: 'Ingrid Solberg', tone: 2, days: [9.4, 12.6, 7.7, 0, 13.0], allTime: 5020, move: { week: 1, all: 0 }, streak: 21, pace: '4:27' },
140 { id: 'elif', name: 'Elif Demir', tone: 4, days: [8.0, 0, 13.5, 9.1, 7.4], allTime: 3105, move: { week: -1, all: 0 }, streak: 9, pace: '4:44' },
141 { id: 'tomas', name: 'Tomás Vidal', tone: 5, days: [7.2, 10.4, 5.6, 0, 7.0], allTime: 1980, move: { week: -2, all: 0 }, streak: 4, pace: '4:58' },
142 { id: 'sipho', name: 'Sipho Ndlovu', tone: 0, days: [6.0, 8.2, 0, 7.5, 6.1], allTime: 2870, move: { week: 0, all: 0 }, streak: 6, pace: '5:03' },
143 { id: 'rhys', name: 'Rhys Morgan', tone: 7, days: [0, 9.0, 5.5, 4.0, 6.4], allTime: 2450, move: { week: -1, all: 0 }, streak: 2, pace: '5:15' },
144];
145
146const RUNNERS = RUNNER_LIST.reduce<Record<string, Runner>>((all, r) => ({ ...all, [r.id]: r }), {});
147
148const SCOPES: Record<Scope, string[]> = {
149 friends: ['sofia', 'liam', 'elena', 'daniel', 'noah', 'zoe', 'marcus', 'maya', 'lena', 'ava', 'sam', 'iris', 'ravi', 'grace', 'theo'],
150 city: ['owen', 'sofia', 'ben', 'priya', 'elena', 'noah', 'marcus', 'lena', 'ava', 'tess', 'nadia', 'chloe', 'jonah', 'ruth', 'felix'],
151 global: ['yara', 'mateo', 'lucas', 'kenji', 'freya', 'amara', 'oskar', 'hana', 'diego', 'ingrid', 'elif', 'ava', 'tomas', 'sipho', 'rhys'],
152};
153
154const SCOPE_TABS: { id: Scope; label: string }[] = [
155 { id: 'friends', label: 'Friends' },
156 { id: 'city', label: 'City' },
157 { id: 'global', label: 'Global' },
158];
159
160const SPANS: { id: Span; label: string }[] = [
161 { id: 'week', label: 'This week' },
162 { id: 'all', label: 'All time' },
163];
164
165// Stone leagues, lowest first. Each has its own stone colours, like a medal.
166type League = { name: string; light: string; deep: string; mark: string };
167const LEAGUES: League[] = [
168 { name: 'Pebble', light: '#E6DED4', deep: '#9A8C7C', mark: '#FFFFFF' },
169 { name: 'Sandstone', light: '#F4D29E', deep: '#BC7A3A', mark: '#FFFFFF' },
170 { name: 'Granite', light: '#C9CED7', deep: '#5F6776', mark: '#FFFFFF' },
171 { name: 'Marble', light: '#FFFFFF', deep: '#C4BDB0', mark: '#958B7D' },
172 { name: 'Basalt', light: '#7C818B', deep: '#2C2F36', mark: '#FFFFFF' },
173 { name: 'Obsidian', light: '#58565F', deep: '#0E0E11', mark: '#E9E8EE' },
174];
175
176// ─── Palette ────────────────────────────────────────────────────────────────
177
178// Medals bring the colour. They stay the same in both themes and for every brand.
179const MEDALS = [
180 { label: '1st', base: '#F5B93E', light: '#FFE39C', deep: '#B47B08', ink: '#3A2600' },
181 { label: '2nd', base: '#C4CCD7', light: '#F3F6FA', deep: '#7E8999', ink: '#222833' },
182 { label: '3rd', base: '#DD8D57', light: '#F8C9A3', deep: '#9A5225', ink: '#341603' },
183];
184const STREAK = '#FF8A3D';
185const CONFETTI = [MEDALS[0].base, '#FF7A59', '#3FB6E8', '#5BCB7A', MEDALS[1].light, MEDALS[2].base];
186// Initials discs for runners without a photo: one colour each, the same in both themes.
187const TONES = ['#E8735A', '#2F9E8F', '#D49A2A', '#4F86E8', '#C9577E', '#5E9F45', '#8A6AD4', '#2E9FC4'];
188const TONE_FILLS = TONES.map((t) => [shade(t, -0.22), t] as const);
189
190// Ink surfaces: the hero, the compact bar and the user's own row.
191const INK_MUTED = tint(ON_ACCENT, 0.64);
192const INK_SOFT = tint(ON_ACCENT, 0.12);
193const INK_LINE = tint(ON_ACCENT, 0.1);
194const INK_BAR = tint(ON_ACCENT, 0.22);
195const INK_TRACK = tint(ON_ACCENT, 0.07);
196const GAIN_ON_INK = '#5EE3A1';
197const LOSS_ON_INK = '#FF9086';
198const HERO_GRADIENT = [shade(ACCENT, -0.09), ACCENT, shade(ACCENT, 0.18)] as const;
199const BLOCK_GRADIENT = [tint(ON_ACCENT, 0.16), tint(ON_ACCENT, 0.03)] as const;
200const BLOCK_GRADIENT_WIN = [tint(ON_ACCENT, 0.24), tint(ON_ACCENT, 0.05)] as const;
201
202const TABULAR = { fontVariant: ['tabular-nums' as const] };
203const COLUMN = 520; // widest the screen gets on tablets and the web
204const ROW = 64; // a ranked row's slot
205const CARD_H = 60; // the row card inside it
206const PANEL = 122; // the mini profile under an open row
207const ZONE = 40; // a promotion or demotion line
208const BAR_H = 50; // the compact bar under the status bar
209const PODIUM_H = 236;
210const PLOT = 54; // the mini profile's day bars
211const FADE = 22; // the soft edge on the strip behind the docked row
212const COUNT_MS = 750;
213const RISE = { damping: 13, stiffness: 165, mass: 0.75 };
214const SLIDE = { damping: 18, stiffness: 230, mass: 0.7 };
215const POP = { damping: 12, stiffness: 260, mass: 0.6 };
216const PRESS = { damping: 16, stiffness: 320, mass: 0.6 };
217const SHEET = { damping: 22, stiffness: 230, mass: 0.9 };
218const OPEN = { duration: 280, easing: Easing.out(Easing.cubic) };
219const MOVE = LinearTransition.duration(300);
220
221function usePalette() {
222 const dark = useColorScheme() === 'dark';
223 return {
224 dark,
225 bg: dark ? '#000000' : '#F2F2F5',
226 raised: dark ? '#151518' : '#FFFFFF',
227 rowClear: dark ? 'rgba(21, 21, 24, 0)' : 'rgba(255, 255, 255, 0)',
228 fg: dark ? '#F4F4F6' : '#121216',
229 muted: dark ? '#8B8B94' : '#6C6C76',
230 faint: dark ? '#3A3A41' : '#C6C6CE',
231 line: dark ? '#26262C' : '#ECECF0',
232 bar: dark ? '#2C2C33' : '#E4E4EA',
233 // The ink as a fill (buttons, the user's row) and as a bright mark on dark surfaces.
234 fill: dark ? ACCENT_DARK : ACCENT,
235 mark: dark ? shade(ACCENT_DARK, -0.55) : ACCENT,
236 gain: dark ? '#3DD68C' : '#12924A',
237 loss: dark ? '#FF6B5E' : '#D93D31',
238 gainSoft: dark ? 'rgba(61, 214, 140, 0.14)' : 'rgba(18, 146, 74, 0.1)',
239 lossSoft: dark ? 'rgba(255, 107, 94, 0.14)' : 'rgba(217, 61, 49, 0.09)',
240 backdrop: dark ? 'rgba(0, 0, 0, 0.72)' : 'rgba(14, 14, 24, 0.45)',
241 };
242}
243type Palette = ReturnType<typeof usePalette>;
244
245// ─── Ranking ────────────────────────────────────────────────────────────────
246
247type Entry = { runner: Runner; score: number; rank: number };
248type Zone = 'up' | 'drop' | null;
249type Item = { kind: 'row'; entry: Entry } | { kind: 'zone'; zone: 'up' | 'drop' };
250
251const weekOf = (r: Runner) => Math.round(r.days.reduce((a, b) => a + b, 0) * 10) / 10;
252const firstName = (name: string) => name.split(' ')[0];
253const shortName = (name: string) => {
254 const [a, b] = name.split(' ');
255 return b ? `${a} ${b[0]}.` : a;
256};
257const initials = (name: string) =>
258 name
259 .split(' ')
260 .map((w) => w[0])
261 .slice(0, 2)
262 .join('');
263const ordinal = (n: number) => `${n}${n % 10 === 1 && n !== 11 ? 'st' : n % 10 === 2 && n !== 12 ? 'nd' : n % 10 === 3 && n !== 13 ? 'rd' : 'th'}`;
264const comma = (n: number) => Math.round(n).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
265/** Weekly distances keep one decimal; all-time totals are whole kilometres. */
266const fmt = (n: number, span: Span) => (span === 'week' ? n.toFixed(1) : comma(n));
267
268function rankFor(scope: Scope, span: Span): Entry[] {
269 return SCOPES[scope]
270 .map((id) => RUNNERS[id])
271 .map((runner) => ({ runner, score: span === 'week' ? weekOf(runner) : runner.allTime, rank: 0 }))
272 .sort((a, b) => b.score - a.score)
273 .map((e, i) => ({ ...e, rank: i + 1 }));
274}
275
276/** Promotion and demotion only exist for the live week. */
277function zoneOf(rank: number, span: Span): Zone {
278 if (span !== 'week') return null;
279 if (rank <= UP) return 'up';
280 if (rank > GROUP - DROP) return 'drop';
281 return null;
282}
283
284/** The list under the podium, from 4th down, with the zone lines in place. */
285function itemsFor(ranked: Entry[], span: Span): Item[] {
286 const out: Item[] = [];
287 ranked.slice(3).forEach((entry) => {
288 if (span === 'week' && entry.rank === GROUP - DROP + 1) out.push({ kind: 'zone', zone: 'drop' });
289 out.push({ kind: 'row', entry });
290 if (span === 'week' && entry.rank === UP) out.push({ kind: 'zone', zone: 'up' });
291 });
292 return out;
293}
294
295// ─── Small pieces ───────────────────────────────────────────────────────────
296
297function Tap({ label, onPress, children, to = 0.96, flex, style }: { label: string; onPress?: () => void; children: ReactNode; to?: number; flex?: boolean; style?: StyleProp<ViewStyle> }) {
298 const scale = useSharedValue(1);
299 const anim = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));
300 return (
301 <Pressable
302 role="button"
303 aria-label={label}
304 onPress={onPress}
305 onPressIn={() => (scale.value = withSpring(to, PRESS))}
306 onPressOut={() => (scale.value = withSpring(1, PRESS))}
307 style={flex ? styles.fill : undefined}
308 >
309 <Animated.View style={[style, anim]}>{children}</Animated.View>
310 </Pressable>
311 );
312}
313
314/** A round photo that fades in over a tinted disc once it has loaded. */
315function Photo({ uri, alt, size, under }: { uri: string; alt: string; size: number; under: string }) {
316 const shown = useSharedValue(0);
317 const style = useAnimatedStyle(() => ({ opacity: shown.value }));
318 return (
319 <View style={[styles.face, { width: size, height: size, borderRadius: size / 2, backgroundColor: under }]}>
320 <Animated.View style={[styles.fill, style]}>
321 <Image source={{ uri }} alt={alt} resizeMode="cover" style={styles.faceImage} onLoad={() => (shown.value = withTiming(1, { duration: 320 }))} />
322 </Animated.View>
323 </View>
324 );
325}
326
327/** The runner's photo, or their initials on their own colour. */
328function Face({ runner, size, under }: { runner: Runner; size: number; under: string }) {
329 if (runner.photo) return <Photo uri={runner.photo} alt={runner.name} size={size} under={under} />;
330 const [from, to] = TONE_FILLS[runner.tone ?? 0];
331 return (
332 <View aria-label={runner.name} style={[styles.face, styles.center, { width: size, height: size, borderRadius: size / 2 }]}>
333 <LinearGradient colors={[from, to]} start={{ x: 0.2, y: 0 }} end={{ x: 0.8, y: 1 }} style={StyleSheet.absoluteFill} />
334 <Text style={[styles.initials, { fontSize: Math.round(size * 0.36) }]}>{initials(runner.name)}</Text>
335 </View>
336 );
337}
338
339/** Counts from zero to the value, easing out, every time `run` changes. */
340function Count({ value, span, run, delay = 0, style }: { value: number; span: Span; run: number; delay?: number; style: StyleProp<TextStyle> }) {
341 const [shown, setShown] = useState(0);
342 useEffect(() => {
343 let raf = 0;
344 let start = 0;
345 setShown(0);
346 const tick = () => {
347 const t = Math.min(1, (Date.now() - start) / COUNT_MS);
348 setShown(value * (1 - Math.pow(1 - t, 3)));
349 if (t < 1) raf = requestAnimationFrame(tick);
350 };
351 const timer = setTimeout(() => {
352 start = Date.now();
353 raf = requestAnimationFrame(tick);
354 }, delay);
355 return () => {
356 clearTimeout(timer);
357 cancelAnimationFrame(raf);
358 };
359 }, [value, run, delay]);
360 return <Text style={style}>{fmt(shown, span)}</Text>;
361}
362
363/** Time left until `end`. Only this text re-renders each second. */
364function Countdown({ end, seconds, style }: { end: number; seconds?: boolean; style: StyleProp<TextStyle> }) {
365 const [now, setNow] = useState(() => Date.now());
366 useEffect(() => {
367 const id = setInterval(() => setNow(Date.now()), 1000);
368 return () => clearInterval(id);
369 }, []);
370 const s = Math.max(0, Math.floor((end - now) / 1000));
371 const pad = (n: number) => String(n).padStart(2, '0');
372 const text = `${Math.floor(s / 86400)}d ${Math.floor((s % 86400) / 3600)}h ${pad(Math.floor((s % 3600) / 60))}m${seconds ? ` ${pad(s % 60)}s` : ''}`;
373 return <Text style={style}>{text}</Text>;
374}
375
376function LiveDot() {
377 const t = useSharedValue(0);
378 useEffect(() => {
379 t.value = withRepeat(withTiming(1, { duration: 1700, easing: Easing.out(Easing.quad) }), -1);
380 return () => cancelAnimation(t);
381 }, [t]);
382 const ring = useAnimatedStyle(() => ({ opacity: 0.7 * (1 - t.value), transform: [{ scale: 1 + t.value * 1.8 }] }));
383 return (
384 <View style={styles.live}>
385 <Animated.View style={[StyleSheet.absoluteFill, styles.liveRing, ring]} />
386 <View style={styles.liveDot} />
387 </View>
388 );
389}
390
391// A rounded hexagon cut from the league's stone, flecked like granite, with a peak in the middle.
392const HEX = 'M24 3 L43 14 L43 38 L24 49 L5 38 L5 14 Z';
393const HEX_INNER = 'M24 8.5 L38.2 16.7 L38.2 35.3 L24 43.5 L9.8 35.3 L9.8 16.7 Z';
394const PEAK = 'M14.5 33 L21.5 22.5 L25.2 27.6 L28.3 24 L33.5 33 Z';
395const SPECKS: [number, number, number][] = [
396 [15, 18, 1.1], [31, 15, 0.9], [36, 24, 1.2], [12.5, 28, 0.9], [19, 39, 1.1],
397 [33, 38, 0.8], [26, 12.5, 0.7], [17, 24, 0.6], [37.5, 31, 0.7], [27, 42, 0.9],
398];
399
400function LeagueBadge({ league, size }: { league: League; size: number }) {
401 const id = `badge${useId().replace(/[^a-zA-Z0-9]/g, '')}`;
402 return (
403 <Svg width={size} height={(size * 52) / 48} viewBox="0 0 48 52">
404 <Defs>
405 <SvgLinearGradient id={id} x1="0" y1="0" x2="1" y2="1">
406 <Stop offset="0" stopColor={league.light} />
407 <Stop offset="1" stopColor={league.deep} />
408 </SvgLinearGradient>
409 </Defs>
410 <Path d={HEX} fill={`url(#${id})`} stroke={league.deep} strokeWidth={2.5} strokeLinejoin="round" />
411 {SPECKS.map(([cx, cy, r], i) => (
412 <Circle key={i} cx={cx} cy={cy} r={r} fill={i % 2 ? league.deep : '#FFFFFF'} opacity={i % 2 ? 0.5 : 0.4} />
413 ))}
414 <Path d={HEX_INNER} fill="none" stroke="#FFFFFF" strokeOpacity={0.45} strokeWidth={1.3} strokeLinejoin="round" />
415 <Path d={PEAK} fill={league.mark} opacity={0.95} />
416 </Svg>
417 );
418}
419
420function Crown({ size }: { size: number }) {
421 const id = `crown${useId().replace(/[^a-zA-Z0-9]/g, '')}`;
422 const gold = MEDALS[0];
423 return (
424 <Svg width={size} height={size * 0.8} viewBox="0 0 30 24">
425 <Defs>
426 <SvgLinearGradient id={id} x1="0" y1="0" x2="0" y2="1">
427 <Stop offset="0" stopColor={gold.light} />
428 <Stop offset="1" stopColor={gold.base} />
429 </SvgLinearGradient>
430 </Defs>
431 <Path d="M4 19 L2.2 7.5 L9.5 12.2 L15 3.4 L20.5 12.2 L27.8 7.5 L26 19 Z" fill={`url(#${id})`} stroke={gold.deep} strokeWidth={1.1} strokeLinejoin="round" />
432 <Rect x={4} y={19.6} width={22} height={3.2} rx={1.6} fill={gold.deep} />
433 <Circle cx={2.2} cy={7.5} r={2} fill={gold.light} stroke={gold.deep} strokeWidth={0.8} />
434 <Circle cx={15} cy={3.2} r={2.2} fill={gold.light} stroke={gold.deep} strokeWidth={0.8} />
435 <Circle cx={27.8} cy={7.5} r={2} fill={gold.light} stroke={gold.deep} strokeWidth={0.8} />
436 <Circle cx={15} cy={14.6} r={1.7} fill="#FFFFFF" opacity={0.9} />
437 </Svg>
438 );
439}
440
441function Sparkle({ size, t, phase, style }: { size: number; t: SharedValue<number>; phase: number; style: StyleProp<ViewStyle> }) {
442 const anim = useAnimatedStyle(() => {
443 const k = (t.value + phase) % 1;
444 const glow = k < 0.5 ? k * 2 : (1 - k) * 2;
445 return { opacity: 0.25 + glow * 0.75, transform: [{ scale: 0.6 + glow * 0.5 }, { rotate: `${k * 90}deg` }] };
446 });
447 return (
448 <Animated.View style={[styles.sparkle, style, anim]}>
449 <Svg width={size} height={size} viewBox="0 0 12 12">
450 <Path d="M6 0 C6.6 3.6 8.4 5.4 12 6 C8.4 6.6 6.6 8.4 6 12 C5.4 8.4 3.6 6.6 0 6 C3.6 5.4 5.4 3.6 6 0 Z" fill={MEDALS[0].light} />
451 </Svg>
452 </Animated.View>
453 );
454}
455
456// ─── Header controls ────────────────────────────────────────────────────────
457
458type Box = { x: number; w: number };
459
460/** Slides an indicator to the measured box of the selected option. */
461function useSlide(box: Box | undefined) {
462 const x = useSharedValue(0);
463 const w = useSharedValue(0);
464 useEffect(() => {
465 if (!box) return;
466 if (w.value === 0) {
467 x.value = box.x;
468 w.value = box.w;
469 return;
470 }
471 x.value = withSpring(box.x, SLIDE);
472 w.value = withSpring(box.w, SLIDE);
473 // eslint-disable-next-line react-hooks/exhaustive-deps
474 }, [box?.x, box?.w]);
475 return useAnimatedStyle(() => ({ width: w.value, opacity: w.value > 0 ? 1 : 0, transform: [{ translateX: x.value }] }));
476}
477
478function ScopeTabs({ value, onChange }: { value: Scope; onChange: (s: Scope) => void }) {
479 const [boxes, setBoxes] = useState<Partial<Record<Scope, Box>>>({});
480 const line = useSlide(boxes[value]);
481 return (
482 <View role="tablist" aria-label="Leaderboard" style={styles.tabs}>
483 {SCOPE_TABS.map((t) => {
484 const on = t.id === value;
485 return (
486 <Pressable
487 key={t.id}
488 role="tab"
489 aria-selected={on}
490 onPress={() => onChange(t.id)}
491 onLayout={(e: LayoutChangeEvent) => {
492 const { x, width } = e.nativeEvent.layout;
493 setBoxes((b) => (b[t.id]?.x === x && b[t.id]?.w === width ? b : { ...b, [t.id]: { x, w: width } }));
494 }}
495 style={styles.tab}
496 >
497 <Text style={[styles.tabLabel, { color: on ? ON_ACCENT : INK_MUTED }]}>{t.label}</Text>
498 </Pressable>
499 );
500 })}
501 <Animated.View style={[styles.tabLine, line]} />
502 </View>
503 );
504}
505
506function SpanToggle({ value, onChange }: { value: Span; onChange: (s: Span) => void }) {
507 const [boxes, setBoxes] = useState<Partial<Record<Span, Box>>>({});
508 const thumb = useSlide(boxes[value]);
509 return (
510 <View role="radiogroup" aria-label="Time range" style={styles.span}>
511 <Animated.View style={[styles.spanThumb, thumb]} />
512 {SPANS.map((s) => {
513 const on = s.id === value;
514 return (
515 <Pressable
516 key={s.id}
517 role="radio"
518 aria-checked={on}
519 onPress={() => onChange(s.id)}
520 onLayout={(e: LayoutChangeEvent) => {
521 const { x, width } = e.nativeEvent.layout;
522 setBoxes((b) => (b[s.id]?.x === x && b[s.id]?.w === width ? b : { ...b, [s.id]: { x, w: width } }));
523 }}
524 style={styles.spanOption}
525 >
526 <Text style={[styles.spanLabel, { color: on ? ACCENT : INK_MUTED }]}>{s.label}</Text>
527 </Pressable>
528 );
529 })}
530 </View>
531 );
532}
533
534// ─── Podium: blocks rise one after another, the winner last ─────────────────
535
536type Spot = { place: number; avatar: number; block: number };
537const SPOTS: Spot[] = [
538 { place: 2, avatar: 56, block: 66 },
539 { place: 1, avatar: 70, block: 94 },
540 { place: 3, avatar: 56, block: 48 },
541];
542const GLOW = 150;
543
544/** The winner's crown, glow and sparkles, all riding on the block's rise. */
545function WinnerFlair({ rise, width, ring }: { rise: SharedValue<number>; width: number; ring: number }) {
546 const bob = useSharedValue(0);
547 const twinkle = useSharedValue(0);
548 useEffect(() => {
549 bob.value = withRepeat(withTiming(1, { duration: 1500, easing: Easing.inOut(Easing.sin) }), -1, true);
550 twinkle.value = withRepeat(withTiming(1, { duration: 2200, easing: Easing.linear }), -1);
551 return () => {
552 cancelAnimation(bob);
553 cancelAnimation(twinkle);
554 };
555 }, [bob, twinkle]);
556 const crown = useAnimatedStyle(() => {
557 const k = interpolate(rise.value, [0.75, 1], [0, 1], 'clamp');
558 return {
559 opacity: k,
560 transform: [{ translateY: (1 - k) * 10 - bob.value * 2.5 }, { scale: 0.4 + 0.6 * k }, { rotate: `${interpolate(k, [0, 1], [-34, -9])}deg` }],
561 };
562 });
563 const glow = useAnimatedStyle(() => ({ opacity: interpolate(rise.value, [0.5, 1], [0, 1], 'clamp') }));
564 return (
565 <>
566 <Animated.View style={[styles.glow, { left: (width - GLOW) / 2, top: 20 + ring / 2 - GLOW / 2 }, glow]}>
567 <Svg width={GLOW} height={GLOW}>
568 <Defs>
569 <RadialGradient id="winnerGlow" cx="50%" cy="50%" r="50%">
570 <Stop offset="0" stopColor={MEDALS[0].base} stopOpacity={0.42} />
571 <Stop offset="1" stopColor={MEDALS[0].base} stopOpacity={0} />
572 </RadialGradient>
573 </Defs>
574 <Circle cx={GLOW / 2} cy={GLOW / 2} r={GLOW / 2} fill="url(#winnerGlow)" />
575 </Svg>
576 </Animated.View>
577 <Sparkle size={10} t={twinkle} phase={0} style={{ left: width / 2 - 40, top: 8 }} />
578 <Sparkle size={7} t={twinkle} phase={0.45} style={{ left: width / 2 + 30, top: 2 }} />
579 <Sparkle size={6} t={twinkle} phase={0.75} style={{ left: width / 2 + 40, top: 30 }} />
580 <Animated.View style={[styles.crown, crown]}>
581 <Crown size={30} />
582 </Animated.View>
583 </>
584 );
585}
586
587function PodiumSlot({ entry, span, run, spot, width }: { entry: Entry; span: Span; run: number; spot: Spot; width: number }) {
588 const medal = MEDALS[spot.place - 1];
589 const order = 3 - spot.place; // third rises first, the winner last
590 const [shown, setShown] = useState({ entry, span, run });
591 const rise = useSharedValue(0);
592 const press = useSharedValue(1);
593 const booted = useRef(false);
594 useEffect(() => {
595 if (!booted.current) {
596 booted.current = true;
597 rise.value = withDelay(200 + order * 120, withSpring(1, RISE));
598 return;
599 }
600 // The block sinks, the new runner takes the spot out of sight, and it rises again.
601 rise.value = withSequence(withTiming(0, { duration: 180, easing: Easing.in(Easing.quad) }), withDelay(order * 110, withSpring(1, RISE)));
602 const id = setTimeout(() => setShown({ entry, span, run }), 190);
603 return () => clearTimeout(id);
604 // eslint-disable-next-line react-hooks/exhaustive-deps
605 }, [run]);
606
607 const block = useAnimatedStyle(() => ({ height: spot.block * Math.max(0, rise.value) }));
608 const top = useAnimatedStyle(() => ({
609 opacity: interpolate(rise.value, [0, 0.45], [0, 1], 'clamp'),
610 transform: [{ scale: interpolate(rise.value, [0, 1], [0.6, 1]) }],
611 }));
612 const face = useAnimatedStyle(() => ({ transform: [{ scale: press.value }] }));
613 const r = shown.entry.runner;
614 const ring = spot.avatar + 12;
615 const winner = spot.place === 1;
616 const score = fmt(shown.entry.score, shown.span);
617 return (
618 <View style={[styles.slot, { width }]}>
619 <Animated.View style={[styles.slotTop, top]}>
620 {winner && <WinnerFlair rise={rise} width={width} ring={ring} />}
621 <Pressable
622 role="button"
623 aria-label={`${r.name}, ${medal.label} place, ${score} km`}
624 onPressIn={() => (press.value = withSpring(0.92, PRESS))}
625 onPressOut={() => (press.value = withSpring(1, POP))}
626 style={winner ? styles.winnerFace : null}
627 >
628 <Animated.View style={[styles.ring, { width: ring, height: ring, borderRadius: ring / 2, borderColor: medal.base }, face]}>
629 <Face runner={r} size={spot.avatar} under={INK_SOFT} />
630 </Animated.View>
631 <View style={[styles.medal, { left: ring / 2 - 12 }]}>
632 <LinearGradient colors={[medal.light, medal.base]} start={{ x: 0.2, y: 0 }} end={{ x: 0.8, y: 1 }} style={StyleSheet.absoluteFill} />
633 <Text style={[styles.medalText, { color: medal.ink }]}>{spot.place}</Text>
634 </View>
635 </Pressable>
636 <Text numberOfLines={1} style={styles.podiumName}>
637 {r.id === ME_ID ? 'You' : shortName(r.name)}
638 </Text>
639 </Animated.View>
640 <Animated.View style={[styles.block, block]}>
641 <LinearGradient colors={winner ? BLOCK_GRADIENT_WIN : BLOCK_GRADIENT} style={StyleSheet.absoluteFill} />
642 <LinearGradient colors={[medal.base, medal.light, medal.base]} start={{ x: 0, y: 0.5 }} end={{ x: 1, y: 0.5 }} style={styles.lip} />
643 <View style={styles.blockScore}>
644 <Count value={shown.entry.score} span={shown.span} run={shown.run} delay={shown.run === 0 ? 220 + order * 120 : order * 110} style={[winner ? styles.blockValueWin : styles.blockValue, TABULAR]} />
645 <Text style={styles.blockUnit}>km</Text>
646 </View>
647 </Animated.View>
648 </View>
649 );
650}
651
652/** Faint running-track lanes behind the podium. */
653function Lanes({ width }: { width: number }) {
654 return (
655 <Svg width={width} height={PODIUM_H} style={styles.lanes}>
656 {[0, 1, 2].map((i) => {
657 const inset = 14 + i * 15;
658 const h = 360 - i * 30;
659 return <Rect key={i} x={inset} y={58 + i * 15} width={width - inset * 2} height={h} rx={h / 2} fill="none" stroke={INK_LINE} strokeWidth={1.2} />;
660 })}
661 </Svg>
662 );
663}
664
665function Podium({ ranked, span, run, column }: { ranked: Entry[]; span: Span; run: number; column: number }) {
666 const slot = Math.floor((column - 32 - 12) / 3);
667 return (
668 <View style={styles.podium}>
669 <Lanes width={column} />
670 {SPOTS.map((spot) => (
671 <PodiumSlot key={spot.place} entry={ranked[spot.place - 1]} span={span} run={run} spot={spot} width={slot} />
672 ))}
673 </View>
674 );
675}
676
677// ─── A ranked row ───────────────────────────────────────────────────────────
678
679function Trend({ move, me, pal }: { move: number; me: boolean; pal: Palette }) {
680 if (move === 0) {
681 return (
682 <View aria-label="No change" style={styles.trend}>
683 <View style={[styles.trendFlat, { backgroundColor: me ? INK_MUTED : pal.faint }]} />
684 </View>
685 );
686 }
687 const up = move > 0;
688 const color = up ? (me ? GAIN_ON_INK : pal.gain) : me ? LOSS_ON_INK : pal.loss;
689 return (
690 <View aria-label={`${up ? 'Up' : 'Down'} ${Math.abs(move)}`} style={styles.trend}>
691 <View style={up ? null : styles.flip}>
692 <Svg width={7} height={6} viewBox="0 0 7 6">
693 <Path d="M3.5 0.4 L6.8 5.6 L0.2 5.6 Z" fill={color} />
694 </Svg>
695 </View>
696 <Text style={[styles.trendText, { color }, TABULAR]}>{Math.abs(move)}</Text>
697 </View>
698 );
699}
700
701/** Rank, face, name and score: shared by the list row and the docked copy of the user's row. */
702function RowBody({ entry, span, run, delay, me, pal }: { entry: Entry; span: Span; run: number; delay: number; me: boolean; pal: Palette }) {
703 const r = entry.runner;
704 const zone = zoneOf(entry.rank, span);
705 const fg = me ? ON_ACCENT : pal.fg;
706 const muted = me ? INK_MUTED : pal.muted;
707 const rankColor = me ? ON_ACCENT : zone === 'up' ? pal.gain : zone === 'drop' ? pal.loss : pal.fg;
708 const streaky = r.streak >= 5;
709 return (
710 <View style={styles.row}>
711 <View style={styles.rankCol}>
712 <Text style={[styles.rank, { color: rankColor }, TABULAR]}>{entry.rank}</Text>
713 <Trend move={r.move[span]} me={me} pal={pal} />
714 </View>
715 <Face runner={r} size={42} under={me ? INK_SOFT : pal.bar} />
716 <View style={styles.who}>
717 <View style={styles.nameLine}>
718 <Text numberOfLines={1} style={[styles.name, { color: fg }]}>
719 {r.name}
720 </Text>
721 {me && (
722 <View style={styles.youChip}>
723 <Text style={styles.youText}>You</Text>
724 </View>
725 )}
726 </View>
727 <View style={styles.subLine}>
728 {streaky && <Flame size={12} color={STREAK} fill={STREAK} strokeWidth={2} />}
729 <Text numberOfLines={1} style={[styles.sub, { color: muted }]}>
730 {streaky ? `${r.streak}-week streak` : `${r.pace} /km pace`}
731 </Text>
732 </View>
733 </View>
734 <View style={styles.scoreCol}>
735 <Count value={entry.score} span={span} run={run} delay={delay} style={[styles.score, { color: fg }, TABULAR]} />
736 <Text style={[styles.unit, { color: muted }]}>km</Text>
737 </View>
738 </View>
739 );
740}
741
742function DayBar({ km, best, index, open, me, pal }: { km: number | undefined; best: number; index: number; open: boolean; me: boolean; pal: Palette }) {
743 const grow = useSharedValue(0);
744 useEffect(() => {
745 grow.value = open ? withDelay(110 + index * 45, withSpring(1, { damping: 14, stiffness: 190, mass: 0.7 })) : withTiming(0, { duration: 160 });
746 }, [open, index, grow]);
747 const future = index > TODAY;
748 const rest = !future && !km;
749 const h = future ? 0 : rest ? 4 : Math.max(8, ((km ?? 0) / best) * PLOT);
750 const bar = useAnimatedStyle(() => ({ height: h * Math.max(0, grow.value) }));
751 const label = useAnimatedStyle(() => ({ opacity: interpolate(grow.value, [0.6, 1], [0, 1], 'clamp') }));
752 const today = index === TODAY;
753 const isBest = !future && km === best;
754 const color = today ? (me ? ON_ACCENT : pal.mark) : me ? INK_BAR : pal.bar;
755 return (
756 <View style={styles.day}>
757 <View style={styles.dayPlot}>
758 {isBest && (
759 <Animated.Text style={[styles.dayBest, { color: me ? ON_ACCENT : pal.fg }, TABULAR, label]}>{km?.toFixed(1)}</Animated.Text>
760 )}
761 {future ? (
762 <View style={[styles.dayFuture, { borderColor: me ? INK_BAR : pal.faint }]} />
763 ) : (
764 <Animated.View style={[styles.dayBar, { backgroundColor: rest ? (me ? INK_BAR : pal.faint) : color }, bar]} />
765 )}
766 </View>
767 <Text style={[styles.dayLabel, { color: today ? (me ? ON_ACCENT : pal.fg) : me ? INK_MUTED : pal.muted, fontWeight: today ? '800' : '600' }]}>{DAYS[index]}</Text>
768 </View>
769 );
770}
771
772// Confetti for a cheer, flung out in a wide oval and pulled down a little as it fades.
773const BURST = Array.from({ length: 16 }, (_, i) => {
774 const angle = (i / 16) * Math.PI * 2 + (i % 2 ? 0.18 : -0.08);
775 const reach = 1 + ((i * 7) % 3) * 0.24;
776 return { x: Math.cos(angle) * 66 * reach, y: Math.sin(angle) * 30 * reach - 8, size: 4 + (i % 3) * 1.5, round: i % 3 !== 1, color: CONFETTI[i % CONFETTI.length] };
777});
778
779function Particle({ p, t }: { p: (typeof BURST)[number]; t: SharedValue<number> }) {
780 const h = p.round ? p.size : p.size * 1.9;
781 const style = useAnimatedStyle(() => ({
782 opacity: interpolate(t.value, [0, 0.06, 0.65, 1], [0, 1, 1, 0]),
783 transform: [{ translateX: p.x * t.value }, { translateY: p.y * t.value + 24 * t.value * t.value }, { rotate: `${t.value * 240}deg` }, { scale: 1 - 0.4 * t.value }],
784 }));
785 return <Animated.View style={[styles.particle, { width: p.size, height: h, borderRadius: p.round ? p.size / 2 : 1.5, marginLeft: -p.size / 2, marginTop: -h / 2, backgroundColor: p.color }, style]} />;
786}
787
788function CheerButton({ name, cheered, onCheer, pal }: { name: string; cheered: boolean; onCheer: () => void; pal: Palette }) {
789 const done = useSharedValue(cheered ? 1 : 0);
790 const burst = useSharedValue(0);
791 const press = useSharedValue(1);
792 const fire = () => {
793 if (cheered) {
794 press.value = withSequence(withTiming(0.95, { duration: 80 }), withSpring(1, POP));
795 return;
796 }
797 burst.value = 0;
798 burst.value = withTiming(1, { duration: 850, easing: Easing.out(Easing.cubic) });
799 press.value = withSequence(withTiming(0.88, { duration: 90 }), withSpring(1, POP));
800 done.value = withTiming(1, { duration: 300, easing: Easing.out(Easing.cubic) });
801 onCheer();
802 };
803 const from = pal.fill;
804 const to = pal.gainSoft;
805 const body = useAnimatedStyle(() => ({ backgroundColor: interpolateColor(done.value, [0, 1], [from, to]), transform: [{ scale: press.value }] }));
806 const idle = useAnimatedStyle(() => ({ opacity: 1 - done.value, transform: [{ translateY: -16 * done.value }] }));
807 const sent = useAnimatedStyle(() => ({ opacity: done.value, transform: [{ translateY: 16 * (1 - done.value) }] }));
808 const ripple = useAnimatedStyle(() => ({ opacity: interpolate(burst.value, [0, 0.04, 1], [0, 0.6, 0]), transform: [{ scaleX: 1 + burst.value * 0.3 }, { scaleY: 1 + burst.value * 0.9 }] }));
809 return (
810 <View style={styles.cheerWrap}>
811 {BURST.map((p, i) => (
812 <Particle key={i} p={p} t={burst} />
813 ))}
814 <Animated.View style={[StyleSheet.absoluteFill, styles.cheerRipple, { borderColor: pal.gain }, ripple]} />
815 <Pressable role="button" aria-label={cheered ? `You cheered ${name}` : `Cheer ${name}`} aria-pressed={cheered} onPress={fire}>
816 <Animated.View style={[styles.cheer, body]}>
817 <Animated.View style={[styles.cheerLabel, idle]}>
818 <PartyPopper size={15} color={ON_ACCENT} strokeWidth={2.2} />
819 <Text style={[styles.cheerText, { color: ON_ACCENT }]}>Cheer</Text>
820 </Animated.View>
821 <Animated.View style={[StyleSheet.absoluteFill, styles.cheerLabel, sent]}>
822 <Check size={15} color={pal.gain} strokeWidth={3} />
823 <Text style={[styles.cheerText, { color: pal.gain }]}>Cheered</Text>
824 </Animated.View>
825 </Animated.View>
826 </Pressable>
827 </View>
828 );
829}
830
831/** This week's daily bars, streak and pace, with Cheer (or, on your own row, the gap to the next place). */
832function MiniProfile({ entry, span, me, open, cheered, ahead, onCheer, pal }: MiniProps) {
833 const r = entry.runner;
834 const fg = me ? ON_ACCENT : pal.fg;
835 const muted = me ? INK_MUTED : pal.muted;
836 const best = Math.max(...r.days);
837 return (
838 <View style={[styles.mini, { borderTopColor: me ? INK_LINE : pal.line }]}>
839 <View style={styles.week}>
840 <View style={styles.weekHead}>
841 <Text style={[styles.miniLabel, { color: muted }]}>This week</Text>
842 <Text style={[styles.miniValue, { color: fg }, TABULAR]}>{weekOf(r).toFixed(1)} km</Text>
843 </View>
844 <View style={styles.bars}>
845 {DAYS.map((d, i) => (
846 <DayBar key={i} km={r.days[i]} best={best} index={i} open={open} me={me} pal={pal} />
847 ))}
848 </View>
849 </View>
850 <View style={styles.side}>
851 <View style={styles.stat}>
852 <Flame size={14} color={STREAK} fill={STREAK} strokeWidth={2} />
853 <Text numberOfLines={1} style={[styles.statText, { color: fg }]}>
854 {r.streak}-week streak
855 </Text>
856 </View>
857 <View style={styles.stat}>
858 <Gauge size={14} color={muted} strokeWidth={2.2} />
859 <Text numberOfLines={1} style={[styles.statText, { color: fg }]}>
860 {r.pace} <Text style={{ color: muted }}>/km avg</Text>
861 </Text>
862 </View>
863 {me ? (
864 <View style={styles.ahead}>
865 <ArrowUp size={12} color={ON_ACCENT} strokeWidth={2.8} />
866 <Text numberOfLines={1} style={styles.aheadText}>
867 {ahead ? `${fmt(ahead.gap, span)} km to pass ${ahead.name}` : 'You lead the board'}
868 </Text>
869 </View>
870 ) : (
871 <CheerButton name={firstName(r.name)} cheered={cheered} onCheer={onCheer} pal={pal} />
872 )}
873 </View>
874 </View>
875 );
876}
877
878type MiniProps = { entry: Entry; span: Span; me: boolean; open: boolean; cheered: boolean; ahead: { name: string; gap: number } | null; onCheer: () => void; pal: Palette };
879type RankRowProps = MiniProps & { run: number; delay: number; onToggle: () => void };
880
881/** Tap a row and it opens in place into a mini profile. */
882function RankRow({ entry, span, run, delay, me, open, cheered, ahead, onToggle, onCheer, pal }: RankRowProps) {
883 const p = useSharedValue(open ? 1 : 0);
884 const press = useSharedValue(1);
885 // The panel mounts as the row opens and leaves once it has closed; it clips only while it moves.
886 const [mounted, setMounted] = useState(open);
887 const [clip, setClip] = useState(!open);
888 useEffect(() => {
889 p.value = withTiming(open ? 1 : 0, OPEN);
890 if (open) {
891 setMounted(true);
892 const t = setTimeout(() => setClip(false), OPEN.duration + 30);
893 return () => clearTimeout(t);
894 }
895 setClip(true);
896 const t = setTimeout(() => setMounted(false), OPEN.duration + 30);
897 return () => clearTimeout(t);
898 }, [open, p]);
899 const rest = me ? pal.fill : pal.rowClear;
900 const lift = me ? pal.fill : pal.raised;
901 const card = useAnimatedStyle(() => ({ backgroundColor: interpolateColor(p.value, [0, 1], [rest, lift]), transform: [{ scale: press.value }] }));
902 const panel = useAnimatedStyle(() => ({ height: PANEL * p.value, opacity: interpolate(p.value, [0.3, 1], [0, 1], 'clamp') }));
903 const r = entry.runner;
904 const move = r.move[span];
905 const label = `${ordinal(entry.rank)}, ${me ? 'you' : r.name}, ${fmt(entry.score, span)} km, ${move === 0 ? 'no change' : `${move > 0 ? 'up' : 'down'} ${Math.abs(move)}`}`;
906 return (
907 <Animated.View style={[styles.card, card]}>
908 <Pressable
909 role="button"
910 aria-expanded={open}
911 aria-label={label}
912 onPress={onToggle}
913 onPressIn={() => (press.value = withSpring(0.98, PRESS))}
914 onPressOut={() => (press.value = withSpring(1, PRESS))}
915 >
916 <RowBody entry={entry} span={span} run={run} delay={delay} me={me} pal={pal} />
917 </Pressable>
918 {mounted && (
919 <Animated.View style={[styles.panel, clip ? styles.clip : null, panel]}>
920 <MiniProfile entry={entry} span={span} me={me} open={open} cheered={cheered} ahead={ahead} onCheer={onCheer} pal={pal} />
921 </Animated.View>
922 )}
923 </Animated.View>
924 );
925}
926
927function Dash({ color }: { color: string }) {
928 return (
929 <View style={styles.dash}>
930 <Svg width="100%" height={2}>
931 <Line x1="1" y1="1" x2="100%" y2="1" stroke={color} strokeWidth={1.6} strokeDasharray="2 5" strokeLinecap="round" strokeOpacity={0.7} />
932 </Svg>
933 </View>
934 );
935}
936
937function ZoneLine({ zone, pal }: { zone: 'up' | 'drop'; pal: Palette }) {
938 const up = zone === 'up';
939 const color = up ? pal.gain : pal.loss;
940 const next = LEAGUES[LEAGUE + (up ? 1 : -1)].name;
941 return (
942 <View role="separator" style={styles.zone}>
943 <Dash color={color} />
944 <View style={[styles.zonePill, { backgroundColor: up ? pal.gainSoft : pal.lossSoft }]}>
945 {up ? <ArrowUp size={12} color={color} strokeWidth={2.8} /> : <ArrowDown size={12} color={color} strokeWidth={2.8} />}
946 <Text style={[styles.zoneText, { color }]}>{up ? `Top ${UP} move up to ${next}` : `Bottom ${DROP} drop to ${next}`}</Text>
947 </View>
948 <Dash color={color} />
949 </View>
950 );
951}
952
953// ─── League sheet: drag it down, tap outside or press Got it to close ───────
954
955const RULES = [
956 { kind: 'up', title: `Top ${UP} move up`, body: `Race in ${LEAGUES[LEAGUE + 1].name} League next week` },
957 { kind: 'stay', title: `${ordinal(UP + 1)} to ${ordinal(GROUP - DROP)} stay`, body: `Keep your place in ${LEAGUES[LEAGUE].name}` },
958 { kind: 'drop', title: `Bottom ${DROP} drop`, body: `Back down to ${LEAGUES[LEAGUE - 1].name} League` },
959 { kind: 'medal', title: 'Top 3 earn medals', body: 'First place wears the crown all next week' },
960] as const;
961
962function LeagueSheet({ open, onClose, end, left, column, bottom, maxHeight, pal }: { open: boolean; onClose: () => void; end: number; left: number; column: number; bottom: number; maxHeight: number; pal: Palette }) {
963 const [mounted, setMounted] = useState(false);
964 const t = useSharedValue(0);
965 const drag = useSharedValue(0);
966 const fill = useSharedValue(0);
967 const close = useRef(onClose);
968 close.current = onClose;
969
970 useEffect(() => {
971 if (open) {
972 setMounted(true);
973 drag.value = 0;
974 t.value = withSpring(1, SHEET);
975 fill.value = 0;
976 fill.value = withDelay(280, withTiming(1, { duration: 900, easing: Easing.out(Easing.cubic) }));
977 return;
978 }
979 t.value = withTiming(0, { duration: 240, easing: Easing.in(Easing.cubic) });
980 const id = setTimeout(() => setMounted(false), 260);
981 return () => clearTimeout(id);
982 }, [open, t, drag, fill]);
983
984 const pan = useMemo(
985 () =>
986 PanResponder.create({
987 onStartShouldSetPanResponder: () => true,
988 onMoveShouldSetPanResponder: (_e, g) => Math.abs(g.dy) > 4,
989 onPanResponderMove: (_e, g) => {
990 drag.value = g.dy > 0 ? g.dy : g.dy * 0.2;
991 },
992 onPanResponderRelease: (_e, g) => {
993 if (g.dy > 110 || g.vy > 0.9) close.current();
994 else drag.value = withSpring(0, POP);
995 },
996 onPanResponderTerminate: () => {
997 drag.value = withSpring(0, POP);
998 },
999 }),
1000 [drag]
1001 );
1002
1003 const backdrop = useAnimatedStyle(() => ({ opacity: Math.max(0, Math.min(1, t.value)) * (1 - Math.min(0.6, Math.max(0, drag.value) / 500)) }));
1004 const sheet = useAnimatedStyle(() => ({ transform: [{ translateY: (1 - t.value) * 760 + drag.value }] }));
1005 const remaining = Math.max(0, (end - Date.now()) / 1000);
1006 const elapsed = 1 - remaining / WEEK_SECONDS;
1007 const bar = useAnimatedStyle(() => ({ width: `${elapsed * fill.value * 100}%` }));
1008 if (!mounted) return null;
1009 const league = LEAGUES[LEAGUE];
1010 const rungW = (column - 40) / LEAGUES.length;
1011
1012 return (
1013 <View style={[StyleSheet.absoluteFill, { pointerEvents: open ? 'auto' : 'none' }]}>
1014 <Animated.View style={[StyleSheet.absoluteFill, { backgroundColor: pal.backdrop }, backdrop]}>
1015 <Pressable aria-label="Close league info" onPress={onClose} style={styles.fill} />
1016 </Animated.View>
1017 <Animated.View role="dialog" aria-label={`${league.name} League`} style={[styles.sheet, { left, width: column, maxHeight: maxHeight + 40, backgroundColor: pal.raised, paddingBottom: bottom + 56 }, sheet]}>
1018 <View {...pan.panHandlers} style={styles.sheetDrag}>
1019 <View style={[styles.grabber, { backgroundColor: pal.faint }]} />
1020 <View style={styles.sheetHead}>
1021 <LeagueBadge league={league} size={52} />
1022 <View style={styles.fill}>
1023 <Text style={[styles.sheetTitle, { color: pal.fg }]}>{league.name} League</Text>
1024 <Text style={[styles.sheetSub, { color: pal.muted }]}>
1025 League {LEAGUE + 1} of {LEAGUES.length} · {GROUP} runners · Week {WEEK.number}
1026 </Text>
1027 </View>
1028 </View>
1029 </View>
1030 <View style={styles.sheetClose}>
1031 <Tap label="Close" onPress={onClose} to={0.88}>
1032 <View style={[styles.round, { backgroundColor: pal.bg }]}>
1033 <X size={17} color={pal.fg} strokeWidth={2.4} />
1034 </View>
1035 </Tap>
1036 </View>
1037
1038 <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.sheetBody}>
1039 <Animated.View entering={FadeInDown.delay(120).duration(360)} style={[styles.timeCard, { backgroundColor: pal.bg }]}>
1040 <View style={styles.timeTop}>
1041 <Text style={[styles.timeLabel, { color: pal.muted }]}>Week {WEEK.number} ends in</Text>
1042 <Text style={[styles.timeLabel, { color: pal.muted }]}>Day {TODAY + 1} of 7</Text>
1043 </View>
1044 <Countdown end={end} seconds style={[styles.timeBig, { color: pal.fg }, TABULAR]} />
1045 <View style={[styles.track, { backgroundColor: pal.bar }]}>
1046 <Animated.View style={[styles.trackFill, { backgroundColor: pal.mark }, bar]} />
1047 </View>
1048 <Text style={[styles.timeFoot, { color: pal.muted }]}>Results lock Thursday at midnight. New groups start Friday.</Text>
1049 </Animated.View>
1050
1051 <Text style={[styles.sheetSection, { color: pal.muted }]}>How it works</Text>
1052 {RULES.map((rule, i) => {
1053 const tone = rule.kind === 'up' ? pal.gain : rule.kind === 'drop' ? pal.loss : pal.muted;
1054 const wash = rule.kind === 'up' ? pal.gainSoft : rule.kind === 'drop' ? pal.lossSoft : pal.bg;
1055 return (
1056 <Animated.View key={rule.kind} entering={FadeInDown.delay(180 + i * 60).duration(340)} style={styles.rule}>
1057 <View style={[styles.ruleIcon, { backgroundColor: wash }]}>
1058 {rule.kind === 'up' && <ArrowUp size={17} color={tone} strokeWidth={2.6} />}
1059 {rule.kind === 'stay' && <Minus size={17} color={tone} strokeWidth={2.6} />}
1060 {rule.kind === 'drop' && <ArrowDown size={17} color={tone} strokeWidth={2.6} />}
1061 {rule.kind === 'medal' && (
1062 <View style={styles.medalStack}>
1063 {MEDALS.map((m, k) => (
1064 <View key={m.label} style={[styles.miniMedal, { backgroundColor: m.base, borderColor: pal.bg, marginLeft: k ? -5 : 0 }]} />
1065 ))}
1066 </View>
1067 )}
1068 </View>
1069 <View style={styles.fill}>
1070 <Text style={[styles.ruleTitle, { color: pal.fg }]}>{rule.title}</Text>
1071 <Text style={[styles.ruleBody, { color: pal.muted }]}>{rule.body}</Text>
1072 </View>
1073 </Animated.View>
1074 );
1075 })}
1076
1077 <Text style={[styles.sheetSection, { color: pal.muted }]}>{`The ${APP_NAME} ladder`}</Text>
1078 <View style={styles.ladder}>
1079 <View style={[styles.ladderTrack, { left: rungW / 2, right: rungW / 2, backgroundColor: pal.bar }]}>
1080 <View style={[styles.ladderFill, { width: `${(LEAGUE / (LEAGUES.length - 1)) * 100}%`, backgroundColor: pal.mark }]} />
1081 </View>
1082 {LEAGUES.map((l, i) => {
1083 const here = i === LEAGUE;
1084 return (
1085 <Animated.View key={l.name} entering={ZoomIn.delay(300 + i * 70).springify().damping(13)} style={[styles.rung, { width: rungW, opacity: i > LEAGUE ? 0.42 : 1 }]}>
1086 <View style={[styles.rungBadge, here && { borderColor: pal.mark, backgroundColor: pal.raised }]}>
1087 <LeagueBadge league={l} size={here ? 34 : 28} />
1088 </View>
1089 <Text numberOfLines={1} style={[styles.rungName, { color: here ? pal.fg : pal.muted, fontWeight: here ? '800' : '600' }]}>
1090 {l.name}
1091 </Text>
1092 {here && <Text style={[styles.rungYou, { color: pal.mark }]}>You</Text>}
1093 </Animated.View>
1094 );
1095 })}
1096 </View>
1097
1098 <Tap label="Got it" onPress={onClose} to={0.97}>
1099 <View style={[styles.gotIt, { backgroundColor: pal.fill }]}>
1100 <Text style={styles.gotItText}>Got it</Text>
1101 </View>
1102 </Tap>
1103 </ScrollView>
1104 </Animated.View>
1105 </View>
1106 );
1107}
1108
1109// ─── Screen ─────────────────────────────────────────────────────────────────
1110
1111export default function LeaderboardScreen() {
1112 const pal = usePalette();
1113 const insets = useSafeAreaInsets();
1114 const { width, height } = useWindowDimensions();
1115 const column = Math.min(width, COLUMN);
1116 const [scope, setScope] = useState<Scope>('friends');
1117 const [span, setSpan] = useState<Span>('week');
1118 const [run, setRun] = useState(0);
1119 const [openId, setOpenId] = useState<string | null>(null);
1120 const [cheered, setCheered] = useState<string[]>([]);
1121 const [sheet, setSheet] = useState(false);
1122 const [docked, setDocked] = useState(false);
1123 const [compact, setCompact] = useState(false);
1124 const [viewH, setViewH] = useState(height);
1125 // The week's end is fixed when the screen opens. Replace with the league's real close time.
1126 const [end] = useState(() => Date.now() + ENDS_IN * 1000);
1127 // Rows stagger in once; after that, rows a new board brings in simply fade in.
1128 const [settled, setSettled] = useState(false);
1129 useEffect(() => {
1130 const t = setTimeout(() => setSettled(true), 1400);
1131 return () => clearTimeout(t);
1132 }, []);
1133
1134 // Replace with your leaderboard query for the chosen scope and time range.
1135 const ranked = useMemo(() => rankFor(scope, span), [scope, span]);
1136 const items = useMemo(() => itemsFor(ranked, span), [ranked, span]);
1137 const meAt = ranked.findIndex((e) => e.runner.id === ME_ID);
1138 const meEntry = meAt >= 0 ? ranked[meAt] : null;
1139 const ahead = meEntry && meAt > 0 ? { name: firstName(ranked[meAt - 1].runner.name), gap: ranked[meAt - 1].score - meEntry.score } : null;
1140
1141 const pick = (nextScope: Scope, nextSpan: Span) => {
1142 if (nextScope === scope && nextSpan === span) return;
1143 setScope(nextScope);
1144 setSpan(nextSpan);
1145 setRun((r) => r + 1);
1146 setOpenId(null);
1147 };
1148
1149 // Where the user's row sits in the list, from the fixed row, line and panel heights.
1150 const userIndex = items.findIndex((it) => it.kind === 'row' && it.entry.runner.id === ME_ID);
1151 const openIndex = items.findIndex((it) => it.kind === 'row' && it.entry.runner.id === openId);
1152 let offset = 0;
1153 for (let i = 0; i < userIndex; i++) offset += items[i].kind === 'row' ? ROW : ZONE;
1154 if (openIndex >= 0 && openIndex < userIndex) offset += PANEL;
1155
1156 const scrollY = useSharedValue(0);
1157 const listTop = useSharedValue(0);
1158 const heroH = useSharedValue(420);
1159 const userY = useSharedValue(offset);
1160 const viewHeight = useSharedValue(height);
1161 const hasRow = useSharedValue(userIndex >= 0 ? 1 : 0);
1162 const listTopRef = useRef(0);
1163 const list = useRef<ComponentRef<typeof ScrollView>>(null);
1164 useEffect(() => {
1165 // Rides along with the rows' reorder and with any panel opening above it.
1166 userY.value = withTiming(offset, { duration: 300, easing: Easing.out(Easing.cubic) });
1167 }, [offset, userY]);
1168 useEffect(() => {
1169 hasRow.value = userIndex >= 0 ? 1 : 0;
1170 }, [userIndex, hasRow]);
1171
1172 const onScroll = useAnimatedScrollHandler((e) => {
1173 scrollY.value = e.contentOffset.y;
1174 });
1175
1176 // The user's row docks under the compact bar or above the home indicator when it leaves the screen,
1177 // and sits back in its place in the list as soon as it scrolls into view.
1178 const topLimit = insets.top + BAR_H + 8;
1179 const bottomGap = insets.bottom + 10;
1180 const barBottom = insets.top + BAR_H;
1181 useAnimatedReaction(
1182 () => {
1183 const y = listTop.value + userY.value + 2 - scrollY.value;
1184 return hasRow.value === 1 && listTop.value > 0 && (y < topLimit || y > viewHeight.value - bottomGap - CARD_H);
1185 },
1186 (now, before) => {
1187 if (now !== before) runOnJS(setDocked)(now);
1188 }
1189 );
1190 const dockStyle = useAnimatedStyle(() => {
1191 const y = listTop.value + userY.value + 2 - scrollY.value;
1192 const hi = viewHeight.value - bottomGap - CARD_H;
1193 const out = hasRow.value === 1 && listTop.value > 0 && (y < topLimit || y > hi);
1194 return { opacity: out ? 1 : 0, transform: [{ translateY: Math.min(Math.max(y, topLimit), hi) }] };
1195 });
1196 // An opaque strip behind the docked row, so the list never shows around it.
1197 const backBottom = useAnimatedStyle(() => ({ opacity: listTop.value + userY.value + 2 - scrollY.value > viewHeight.value - bottomGap - CARD_H ? 1 : 0 }));
1198 const backTop = useAnimatedStyle(() => ({ opacity: listTop.value + userY.value + 2 - scrollY.value < topLimit ? 1 : 0 }));
1199
1200 // The compact bar slides down, opaque, as the hero's last edge leaves under the status bar.
1201 useAnimatedReaction(
1202 () => scrollY.value > heroH.value - barBottom - 24,
1203 (now, before) => {
1204 if (now !== before) runOnJS(setCompact)(now);
1205 }
1206 );
1207 const barStyle = useAnimatedStyle(() => {
1208 const at = heroH.value - barBottom;
1209 const k = interpolate(scrollY.value, [at - 56, at - 6], [0, 1], 'clamp');
1210 return { opacity: k > 0 ? 1 : 0, transform: [{ translateY: (k - 1) * (barBottom + 16) }] };
1211 });
1212
1213 const showMe = () => {
1214 const y = listTopRef.current + offset - (viewH - CARD_H) / 2;
1215 list.current?.scrollTo({ y: Math.max(0, y), animated: true });
1216 setOpenId(ME_ID);
1217 };
1218 const toggle = (id: string) => setOpenId((o) => (o === id ? null : id));
1219 const cheer = (id: string) => setCheered((all) => (all.includes(id) ? all : [...all, id]));
1220 const rowDelay = (i: number) => (run === 0 ? 300 + Math.min(i, 6) * 30 : Math.min(i, 8) * 30);
1221 const league = LEAGUES[LEAGUE];
1222 const info = () => setSheet(true);
1223 const clearBg = tint(pal.bg, 0);
1224
1225 return (
1226 <View
1227 onLayout={(e: LayoutChangeEvent) => {
1228 const h = e.nativeEvent.layout.height;
1229 setViewH(h);
1230 viewHeight.value = h;
1231 }}
1232 style={[styles.screen, { backgroundColor: pal.bg }]}
1233 >
1234 <View style={[styles.column, { width: column }]}>
1235 <Animated.ScrollView ref={list} onScroll={onScroll} scrollEventThrottle={16} showsVerticalScrollIndicator={false} contentContainerStyle={{ paddingBottom: insets.bottom + 30 }}>
1236 {/* Ink above the hero, so pulling down past the top never shows a gap */}
1237 <View style={styles.overscroll} />
1238
1239 {/* Hero: league, countdown, tabs and the podium */}
1240 <View onLayout={(e: LayoutChangeEvent) => (heroH.value = e.nativeEvent.layout.height)} style={[styles.hero, { paddingTop: insets.top + 6 }]}>
1241 <LinearGradient colors={HERO_GRADIENT} style={StyleSheet.absoluteFill} />
1242 <Animated.View entering={FadeInDown.delay(40).duration(420)} style={styles.head}>
1243 <Tap label={`${league.name} League. How leagues work`} onPress={info} to={0.97} flex style={styles.headLeft}>
1244 <Animated.View entering={ZoomIn.delay(80).springify().damping(12)}>
1245 <LeagueBadge league={league} size={44} />
1246 </Animated.View>
1247 <View style={styles.fill}>
1248 <Text numberOfLines={1} style={styles.leagueName}>
1249 {league.name} League
1250 </Text>
1251 <Text numberOfLines={1} style={styles.leagueSub}>
1252 Week {WEEK.number} · {WEEK.range}
1253 </Text>
1254 </View>
1255 </Tap>
1256 <Tap label="Time left this week. How leagues work" onPress={info} to={0.94} style={styles.timer}>
1257 <View style={styles.timerTop}>
1258 <LiveDot />
1259 <Text style={styles.timerLabel}>Ends in</Text>
1260 </View>
1261 <Countdown end={end} style={[styles.timerValue, TABULAR]} />
1262 </Tap>
1263 </Animated.View>
1264 <Animated.View entering={FadeInDown.delay(120).duration(420)} style={styles.controls}>
1265 <ScopeTabs value={scope} onChange={(s) => pick(s, span)} />
1266 <SpanToggle value={span} onChange={(s) => pick(scope, s)} />
1267 </Animated.View>
1268 <Podium ranked={ranked} span={span} run={run} column={column} />
1269 </View>
1270
1271 {/* The ranked list from 4th down */}
1272 <View
1273 onLayout={(e: LayoutChangeEvent) => {
1274 listTop.value = e.nativeEvent.layout.y;
1275 listTopRef.current = e.nativeEvent.layout.y;
1276 }}
1277 style={styles.list}
1278 >
1279 {items.map((it, i) => {
1280 const enter = settled ? FadeIn.duration(260) : FadeInDown.delay(300 + Math.min(i, 8) * 45).duration(380);
1281 if (it.kind === 'zone') {
1282 return (
1283 <Animated.View key={`zone-${it.zone}`} layout={MOVE} entering={enter} exiting={FadeOut.duration(150)}>
1284 <ZoneLine zone={it.zone} pal={pal} />
1285 </Animated.View>
1286 );
1287 }
1288 const id = it.entry.runner.id;
1289 return (
1290 <Animated.View key={id} layout={MOVE} entering={enter} exiting={FadeOut.duration(150)} style={openId === id ? styles.lifted : null}>
1291 <RankRow
1292 entry={it.entry}
1293 span={span}
1294 run={run}
1295 delay={rowDelay(i)}
1296 me={id === ME_ID}
1297 open={openId === id}
1298 cheered={cheered.includes(id)}
1299 ahead={ahead}
1300 onToggle={() => toggle(id)}
1301 onCheer={() => cheer(id)}
1302 pal={pal}
1303 />
1304 </Animated.View>
1305 );
1306 })}
1307 </View>
1308 <Text style={[styles.footer, { color: pal.muted }]}>
1309 {UPDATED} · {ranked.length} runners
1310 </Text>
1311 </Animated.ScrollView>
1312
1313 {/* Compact bar: opaque, under the status bar, once the hero has scrolled away */}
1314 <Animated.View style={[styles.compact, { height: barBottom, paddingTop: insets.top, pointerEvents: compact ? 'auto' : 'none' }, barStyle]}>
1315 <Tap label={`${league.name} League. How leagues work`} onPress={info} to={0.98} style={styles.compactRow}>
1316 <LeagueBadge league={league} size={26} />
1317 <Text numberOfLines={1} style={styles.compactTitle}>
1318 {league.name} League
1319 </Text>
1320 <View style={styles.compactTimer}>
1321 <Clock3 size={13} color={INK_MUTED} strokeWidth={2.4} />
1322 <Countdown end={end} style={[styles.compactTime, TABULAR]} />
1323 </View>
1324 </Tap>
1325 </Animated.View>
1326
1327 {/* The user's own row, docked while its place in the list is off screen */}
1328 {meEntry && userIndex >= 0 && (
1329 <Animated.View aria-hidden={!docked} style={[styles.dock, { pointerEvents: docked ? 'auto' : 'none' }, dockStyle]}>
1330 <Animated.View style={[styles.backBottom, { height: FADE + 12 + CARD_H + bottomGap + 6 }, backBottom]}>
1331 <LinearGradient colors={[clearBg, pal.bg]} style={styles.backFade} />
1332 <View style={[styles.fill, { backgroundColor: pal.bg }]} />
1333 </Animated.View>
1334 <Animated.View style={[styles.backTop, { top: barBottom - topLimit, height: topLimit - barBottom + CARD_H + 10 + FADE }, backTop]}>
1335 <View style={[styles.fill, { backgroundColor: pal.bg }]} />
1336 <LinearGradient colors={[pal.bg, clearBg]} style={styles.backFade} />
1337 </Animated.View>
1338 <Animated.View entering={FadeInUp.delay(700).duration(400)}>
1339 <Pressable
1340 role="button"
1341 aria-label={`You are ${ordinal(meEntry.rank)} with ${fmt(meEntry.score, span)} km. Show your row`}
1342 onPress={showMe}
1343 style={[styles.dockCard, { backgroundColor: pal.fill }, pal.dark ? styles.dockShadowDark : styles.dockShadowLight]}
1344 >
1345 <RowBody entry={meEntry} span={span} run={run} delay={rowDelay(userIndex)} me pal={pal} />
1346 </Pressable>
1347 </Animated.View>
1348 </Animated.View>
1349 )}
1350 </View>
1351
1352 <LeagueSheet open={sheet} onClose={() => setSheet(false)} end={end} left={(width - column) / 2} column={column} bottom={insets.bottom} maxHeight={viewH - insets.top - 8} pal={pal} />
1353 </View>
1354 );
1355}
1356
1357// ─── Styles ─────────────────────────────────────────────────────────────────
1358
1359const styles = StyleSheet.create({
1360 screen: { flex: 1, overflow: 'hidden' },
1361 column: { flex: 1, alignSelf: 'center' },
1362 fill: { flex: 1 },
1363 center: { alignItems: 'center', justifyContent: 'center' },
1364 clip: { overflow: 'hidden' },
1365 round: { width: 34, height: 34, borderRadius: 17, alignItems: 'center', justifyContent: 'center' },
1366
1367 // Faces
1368 face: { overflow: 'hidden' },
1369 faceImage: { width: '100%', height: '100%' },
1370 initials: { color: '#FFFFFF', fontWeight: '700', letterSpacing: 0.2 },
1371
1372 // Hero
1373 overscroll: { position: 'absolute', left: 0, right: 0, top: -800, height: 800, backgroundColor: ACCENT },
1374 hero: { backgroundColor: ACCENT, borderBottomLeftRadius: 30, borderBottomRightRadius: 30, overflow: 'hidden' },
1375 head: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 18, height: 56 },
1376 headLeft: { flexDirection: 'row', alignItems: 'center', gap: 11 },
1377 leagueName: { color: ON_ACCENT, fontSize: 21, fontWeight: '800', letterSpacing: -0.5 },
1378 leagueSub: { color: INK_MUTED, fontSize: 13, fontWeight: '500', marginTop: 1 },
1379 timer: { alignItems: 'flex-end', backgroundColor: INK_SOFT, borderRadius: 14, paddingHorizontal: 11, paddingTop: 6, paddingBottom: 7 },
1380 timerTop: { flexDirection: 'row', alignItems: 'center', gap: 6 },
1381 timerLabel: { color: INK_MUTED, fontSize: 10.5, fontWeight: '700', letterSpacing: 0.8, textTransform: 'uppercase' },
1382 timerValue: { color: ON_ACCENT, fontSize: 16, fontWeight: '800', letterSpacing: -0.3, marginTop: 1 },
1383 live: { width: 7, height: 7, alignItems: 'center', justifyContent: 'center' },
1384 liveDot: { width: 7, height: 7, borderRadius: 3.5, backgroundColor: GAIN_ON_INK },
1385 liveRing: { borderRadius: 3.5, backgroundColor: GAIN_ON_INK },
1386
1387 // Tabs and time range
1388 controls: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 18, marginTop: 10 },
1389 tabs: { flexDirection: 'row', gap: 20, height: 36 },
1390 tab: { justifyContent: 'center', height: 36 },
1391 tabLabel: { fontSize: 15.5, fontWeight: '700', letterSpacing: -0.2 },
1392 tabLine: { position: 'absolute', left: 0, bottom: 0, height: 3, borderRadius: 2, backgroundColor: ON_ACCENT },
1393 span: { flexDirection: 'row', height: 32, padding: 3, borderRadius: 16, backgroundColor: INK_SOFT },
1394 spanThumb: { position: 'absolute', left: 0, top: 3, bottom: 3, borderRadius: 13, backgroundColor: ON_ACCENT },
1395 spanOption: { paddingHorizontal: 11, justifyContent: 'center', borderRadius: 13 },
1396 spanLabel: { fontSize: 12.5, fontWeight: '700' },
1397
1398 // Podium
1399 podium: { height: PODIUM_H, marginTop: 6, flexDirection: 'row', alignItems: 'flex-end', justifyContent: 'center', gap: 6 },
1400 lanes: { position: 'absolute', left: 0, top: 0 },
1401 slot: { alignItems: 'center', justifyContent: 'flex-end' },
1402 slotTop: { alignItems: 'center', paddingBottom: 10 },
1403 winnerFace: { marginTop: 20 },
1404 ring: { borderWidth: 2.5, padding: 3.5, backgroundColor: ACCENT },
1405 medal: { position: 'absolute', bottom: -10, width: 24, height: 24, borderRadius: 12, borderWidth: 2.5, borderColor: ACCENT, overflow: 'hidden', alignItems: 'center', justifyContent: 'center' },
1406 medalText: { fontSize: 12, fontWeight: '900' },
1407 podiumName: { color: ON_ACCENT, fontSize: 13.5, fontWeight: '700', marginTop: 16, maxWidth: '100%' },
1408 crown: { position: 'absolute', top: -6, zIndex: 2 },
1409 glow: { position: 'absolute' },
1410 sparkle: { position: 'absolute' },
1411 block: { alignSelf: 'stretch', borderTopLeftRadius: 16, borderTopRightRadius: 16, overflow: 'hidden' },
1412 lip: { position: 'absolute', left: 0, right: 0, top: 0, height: 3 },
1413 blockScore: { flexDirection: 'row', alignItems: 'baseline', justifyContent: 'center', gap: 3, paddingTop: 12 },
1414 blockValue: { color: ON_ACCENT, fontSize: 18, fontWeight: '800', letterSpacing: -0.4 },
1415 blockValueWin: { color: ON_ACCENT, fontSize: 22, fontWeight: '800', letterSpacing: -0.6 },
1416 blockUnit: { color: INK_MUTED, fontSize: 11.5, fontWeight: '600' },
1417
1418 // List
1419 list: { paddingTop: 12 },
1420 lifted: { zIndex: 2 },
1421 card: { marginHorizontal: 12, marginVertical: 2, borderRadius: 18 },
1422 row: { height: CARD_H, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, gap: 10 },
1423 rankCol: { width: 26, alignItems: 'center', gap: 2 },
1424 rank: { fontSize: 16, fontWeight: '800', letterSpacing: -0.3 },
1425 trend: { height: 12, flexDirection: 'row', alignItems: 'center', gap: 2 },
1426 trendFlat: { width: 8, height: 2, borderRadius: 1 },
1427 trendText: { fontSize: 10.5, fontWeight: '700' },
1428 flip: { transform: [{ rotate: '180deg' }] },
1429 who: { flex: 1, minWidth: 0, marginLeft: 2 },
1430 nameLine: { flexDirection: 'row', alignItems: 'center', gap: 7 },
1431 name: { fontSize: 15.5, fontWeight: '700', letterSpacing: -0.2, flexShrink: 1 },
1432 youChip: { height: 18, paddingHorizontal: 7, borderRadius: 9, justifyContent: 'center', backgroundColor: tint(ON_ACCENT, 0.18) },
1433 youText: { color: ON_ACCENT, fontSize: 10.5, fontWeight: '800', letterSpacing: 0.4, textTransform: 'uppercase' },
1434 subLine: { flexDirection: 'row', alignItems: 'center', gap: 4, marginTop: 2 },
1435 sub: { fontSize: 12.5, fontWeight: '500' },
1436 scoreCol: { flexDirection: 'row', alignItems: 'baseline', gap: 3, paddingRight: 4 },
1437 score: { fontSize: 17, fontWeight: '800', letterSpacing: -0.4 },
1438 unit: { fontSize: 12, fontWeight: '600' },
1439 footer: { textAlign: 'center', fontSize: 12.5, marginTop: 18 },
1440
1441 // Mini profile
1442 panel: {},
1443 mini: { height: PANEL, flexDirection: 'row', gap: 12, marginHorizontal: 10, paddingTop: 11, paddingBottom: 12, borderTopWidth: StyleSheet.hairlineWidth },
1444 week: { flex: 1 },
1445 weekHead: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'baseline' },
1446 miniLabel: { fontSize: 11.5, fontWeight: '700', letterSpacing: 0.5, textTransform: 'uppercase' },
1447 miniValue: { fontSize: 12.5, fontWeight: '700' },
1448 bars: { flex: 1, flexDirection: 'row', alignItems: 'flex-end', marginTop: 2 },
1449 day: { flex: 1, alignItems: 'center' },
1450 dayPlot: { height: PLOT + 13, justifyContent: 'flex-end', alignItems: 'center' },
1451 dayBar: { width: 14, borderRadius: 5 },
1452 dayFuture: { width: 14, height: 12, borderRadius: 4, borderWidth: 1.2, borderStyle: 'dashed' },
1453 dayBest: { fontSize: 9.5, fontWeight: '800', marginBottom: 3 },
1454 dayLabel: { fontSize: 10.5, marginTop: 4 },
1455 side: { width: 150, justifyContent: 'space-between' },
1456 stat: { flexDirection: 'row', alignItems: 'center', gap: 6 },
1457 statText: { fontSize: 12.5, fontWeight: '600', flexShrink: 1 },
1458 ahead: { height: 34, borderRadius: 12, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 4, paddingHorizontal: 6, backgroundColor: tint(ON_ACCENT, 0.14) },
1459 aheadText: { color: ON_ACCENT, fontSize: 11.5, fontWeight: '700', flexShrink: 1 },
1460
1461 // Cheer
1462 cheerWrap: { height: 34 },
1463 cheer: { height: 34, borderRadius: 12, overflow: 'hidden', justifyContent: 'center' },
1464 cheerLabel: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 6 },
1465 cheerText: { fontSize: 13.5, fontWeight: '800', letterSpacing: -0.1 },
1466 cheerRipple: { borderRadius: 12, borderWidth: 2, pointerEvents: 'none' },
1467 particle: { position: 'absolute', left: '50%', top: '50%', pointerEvents: 'none' },
1468
1469 // Zones
1470 zone: { height: ZONE, flexDirection: 'row', alignItems: 'center', gap: 8, paddingHorizontal: 20 },
1471 dash: { flex: 1, height: 2 },
1472 zonePill: { height: 24, borderRadius: 12, paddingHorizontal: 10, flexDirection: 'row', alignItems: 'center', gap: 5 },
1473 zoneText: { fontSize: 12, fontWeight: '700' },
1474
1475 // Compact bar and dock
1476 compact: { position: 'absolute', left: 0, right: 0, top: 0, backgroundColor: ACCENT, boxShadow: '0px 6px 18px rgba(0, 0, 0, 0.18)' },
1477 compactRow: { height: BAR_H, flexDirection: 'row', alignItems: 'center', gap: 10, paddingHorizontal: 18 },
1478 compactTitle: { flex: 1, color: ON_ACCENT, fontSize: 16.5, fontWeight: '800', letterSpacing: -0.3 },
1479 compactTimer: { flexDirection: 'row', alignItems: 'center', gap: 5, height: 28, paddingHorizontal: 10, borderRadius: 14, backgroundColor: INK_SOFT },
1480 compactTime: { color: ON_ACCENT, fontSize: 13, fontWeight: '700' },
1481 dock: { position: 'absolute', left: 12, right: 12, top: 0, height: CARD_H },
1482 backBottom: { position: 'absolute', left: -12, right: -12, top: -(FADE + 12) },
1483 backTop: { position: 'absolute', left: -12, right: -12 },
1484 backFade: { height: FADE },
1485 dockCard: { height: CARD_H, borderRadius: 18 },
1486 dockShadowLight: { boxShadow: `0px 12px 28px ${tint(ACCENT, 0.34)}, 0px 2px 6px ${tint(ACCENT, 0.18)}` },
1487 dockShadowDark: { boxShadow: '0px 0px 0px 1px rgba(255, 255, 255, 0.1), 0px 14px 30px rgba(0, 0, 0, 0.7)' },
1488
1489 // League sheet
1490 sheet: { position: 'absolute', bottom: -40, borderTopLeftRadius: 28, borderTopRightRadius: 28, overflow: 'hidden' },
1491 sheetDrag: { paddingTop: 10, paddingHorizontal: 20, paddingBottom: 6 },
1492 grabber: { alignSelf: 'center', width: 40, height: 5, borderRadius: 3 },
1493 sheetHead: { flexDirection: 'row', alignItems: 'center', gap: 14, marginTop: 14, paddingRight: 44 },
1494 sheetTitle: { fontSize: 22, fontWeight: '800', letterSpacing: -0.6 },
1495 sheetSub: { fontSize: 13.5, marginTop: 2 },
1496 sheetClose: { position: 'absolute', top: 26, right: 18 },
1497 sheetBody: { paddingHorizontal: 20, paddingTop: 10 },
1498 timeCard: { borderRadius: 20, padding: 16 },
1499 timeTop: { flexDirection: 'row', justifyContent: 'space-between' },
1500 timeLabel: { fontSize: 12.5, fontWeight: '600' },
1501 timeBig: { fontSize: 32, fontWeight: '800', letterSpacing: -1, marginTop: 4 },
1502 track: { height: 6, borderRadius: 3, marginTop: 12, overflow: 'hidden' },
1503 trackFill: { height: 6, borderRadius: 3 },
1504 timeFoot: { fontSize: 12.5, marginTop: 10, lineHeight: 17 },
1505 sheetSection: { fontSize: 12, fontWeight: '700', letterSpacing: 0.6, textTransform: 'uppercase', marginTop: 20, marginBottom: 8 },
1506 rule: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingVertical: 6 },
1507 ruleIcon: { width: 38, height: 38, borderRadius: 12, alignItems: 'center', justifyContent: 'center' },
1508 ruleTitle: { fontSize: 15, fontWeight: '700', letterSpacing: -0.2 },
1509 ruleBody: { fontSize: 13, marginTop: 1 },
1510 medalStack: { flexDirection: 'row' },
1511 miniMedal: { width: 13, height: 13, borderRadius: 6.5, borderWidth: 1.5 },
1512 ladder: { flexDirection: 'row', alignItems: 'flex-start', paddingTop: 2 },
1513 ladderTrack: { position: 'absolute', top: 22, height: 3, borderRadius: 2, overflow: 'hidden' },
1514 ladderFill: { height: 3 },
1515 rung: { alignItems: 'center' },
1516 rungBadge: { width: 46, height: 46, borderRadius: 23, borderWidth: 2, borderColor: 'transparent', alignItems: 'center', justifyContent: 'center' },
1517 rungName: { fontSize: 11, marginTop: 4 },
1518 rungYou: { fontSize: 10, fontWeight: '800', letterSpacing: 0.5, textTransform: 'uppercase', marginTop: 1 },
1519 gotIt: { height: 52, borderRadius: 16, alignItems: 'center', justifyContent: 'center', marginTop: 22 },
1520 gotItText: { color: ON_ACCENT, fontSize: 16, fontWeight: '800', letterSpacing: -0.2 },
1521});

More screens like this.

All Lists & Search