We're live on Product Hunt, support us.Upvote

Offline mode

A field-inspection list that keeps working without signal: an offline banner slides down under the header with a pulsing connection glyph and a retry button whose draining countdown backs off from 5 to 10 to 20 seconds, cached rows keep their photos while the rest dim, and edits made offline (tick, rename in place, quick add) collect in a queue pill that opens into a list with undo per change. Going back online turns the banner green and ticks each change to a check in order, pauses on an "Edited on another device" conflict with Keep mine or Keep theirs, then collapses with "All changes saved"; each row has a save-for-offline toggle with a download progress ring, and pulling to refresh while offline shakes a "Can't refresh while offline" note.

offlinesyncconnectivityqueueconflictdownloadpull to refreshbanneranimationreanimated
Paste into Claude Code Cursor Codex Lovable RapidNative

Or let your agent fetch it: connect the gluestack MCP server, then ask for offline-mode.

Live preview · follows the site themeOpen full screen

Details

File
components/patterns/offline-mode.tsx
Lines
1686
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/offline-mode.tsx
1import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
2import {
3 Image,
4 KeyboardAvoidingView,
5 PanResponder,
6 Platform,
7 Pressable,
8 ScrollView,
9 StyleSheet,
10 Text,
11 TextInput,
12 View,
13 useColorScheme,
14 useWindowDimensions,
15 type LayoutChangeEvent,
16 type StyleProp,
17 type ViewStyle,
18} from 'react-native';
19import Animated, {
20 cancelAnimation,
21 Easing,
22 FadeIn,
23 FadeInDown,
24 FadeInUp,
25 FadeOut,
26 FadeOutUp,
27 interpolateColor,
28 LinearTransition,
29 useAnimatedProps,
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, Path } from 'react-native-svg';
43import {
44 ArrowDown,
45 ArrowDownToLine,
46 Camera,
47 Check,
48 ChevronDown,
49 ChevronUp,
50 Clock,
51 CloudDownload,
52 CloudOff,
53 Ellipsis,
54 HardDrive,
55 ImageOff,
56 MapPin,
57 Pencil,
58 Plus,
59 RotateCcw,
60 RotateCw,
61 TriangleAlert,
62 Undo2,
63 WifiOff,
64} from 'lucide-react-native';
65
66// ─── Brand ──────────────────────────────────────────────────────────────────
67// The screen's accent and name. Every accent colour below derives from these, so changing them rebrands the screen.
68
69const ACCENT = '#F59E0B';
70const ACCENT_DARK = '#FBBF24'; // the accent as text on dark backgrounds
71const ON_ACCENT = '#2A1A00'; // text and icons on an accent fill
72const APP_NAME = 'Fieldbook';
73
74/** `hex` at `alpha` opacity, as rgba(). */
75function tint(hex: string, alpha: number) {
76 const n = parseInt(hex.slice(1), 16);
77 return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`;
78}
79
80/** `hex` mixed toward black (amount > 0) or white (amount < 0); amount from -1 to 1. */
81function shade(hex: string, amount: number) {
82 const n = parseInt(hex.slice(1), 16);
83 const target = amount < 0 ? 255 : 0;
84 const p = Math.abs(amount);
85 const c = (v: number) => Math.round(v + (target - v) * p).toString(16).padStart(2, '0');
86 return `#${c((n >> 16) & 255)}${c((n >> 8) & 255)}${c(n & 255)}`.toUpperCase();
87}
88
89/** `hex` with its hue turned by `deg` degrees and its HSL lightness and saturation moved by `light` / `sat` (-1 to 1).
90 * For accent-related colours of a different hue (an amber-to-coral gradient from one accent). */
91function spin(hex: string, deg: number, light = 0, sat = 0) {
92 const n = parseInt(hex.slice(1), 16);
93 const r = ((n >> 16) & 255) / 255;
94 const g = ((n >> 8) & 255) / 255;
95 const b = (n & 255) / 255;
96 const max = Math.max(r, g, b);
97 const min = Math.min(r, g, b);
98 const d = max - min;
99 const s = Math.min(1, Math.max(0, (d === 0 ? 0 : d / (1 - Math.abs(max + min - 1))) + sat));
100 const l = Math.min(1, Math.max(0, (max + min) / 2 + light));
101 const h0 = d === 0 ? 0 : max === r ? ((g - b) / d + 6) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4;
102 const h = (((h0 * 60 + deg) % 360) + 360) % 360;
103 const a = s * Math.min(l, 1 - l);
104 const f = (m: number) => {
105 const k = (m + h / 30) % 12;
106 return Math.round(255 * (l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1)))).toString(16).padStart(2, '0');
107 };
108 return `#${f(0)}${f(8)}${f(4)}`.toUpperCase();
109}
110
111/** `hex` with its hue turned by `deg` and saturation moved by `sat`, at an exact HSL `lightness` (0 to 1).
112 * For surfaces that must stay as dark or as pale as designed whatever the accent: dark-theme backdrops, pale washes,
113 * cards on them and the ink that sits on them. */
114function tone(hex: string, deg: number, lightness: number, sat = 0) {
115 const n = parseInt(hex.slice(1), 16);
116 const r = (n >> 16) & 255; const g = (n >> 8) & 255; const b = n & 255;
117 return spin(hex, deg, lightness - (Math.max(r, g, b) + Math.min(r, g, b)) / 510, sat);
118}
119
120// ─── Sample data ────────────────────────────────────────────────────────────
121
122const photo = (id: string, w = 160) => `https://images.unsplash.com/photo-${id}?w=${w}&q=80&fit=crop`;
123
124const PROJECT = 'Harbor Point · Block C';
125const WALK_DATE = 'Thu 4 Dec';
126const LAST_SAVED = '12 min ago';
127// Automatic retries back off: 5 s, then 10 s, then every 20 s.
128const DELAYS = [5, 10, 20];
129// The screen opens part way into the second wait, so the banner shows a running countdown.
130const START_STEP = 1;
131const START_LEFT = 7;
132
133type Section = 'upper' | 'lower';
134
135type Item = {
136 id: string;
137 title: string;
138 place: string;
139 photos: number;
140 mb: number;
141 saved: boolean; // kept on this phone for offline use
142 done: boolean;
143 section: Section;
144 photo?: string;
145 alt?: string;
146};
147
148const SECTIONS: { id: Section; title: string }[] = [
149 { id: 'upper', title: 'Levels 2 and 3' },
150 { id: 'lower', title: 'Basement and exterior' },
151];
152
153const ITEMS: Item[] = [
154 { id: 'crack', title: 'Crack above stair 2 door', place: 'Level 3 lobby', photos: 0, mb: 0, saved: true, done: false, section: 'upper' },
155 { id: 'exit', title: 'Fire exit signage', place: 'Level 2 corridor', photos: 6, mb: 18, saved: true, done: true, section: 'upper', photo: photo('1497366754035-f200968a6e72'), alt: 'A long glass-walled corridor' },
156 { id: 'smoke', title: 'Smoke detector test', place: 'Unit 302', photos: 4, mb: 9, saved: true, done: true, section: 'upper', photo: photo('1585128792020-803d29415281'), alt: 'A bright living room with a wooden sideboard' },
157 { id: 'stair', title: 'Stair 2 landing finishes', place: 'Stair core 2', photos: 11, mb: 31, saved: false, done: false, section: 'upper', photo: photo('1517581177682-a085bb7ffb15'), alt: 'A room mid-renovation with exposed brick' },
158 { id: 'rail', title: 'Balcony railing, Unit 304', place: 'Unit 304 balcony', photos: 8, mb: 24, saved: true, done: false, section: 'upper', photo: photo('1545324418-cc1a3fa10c00'), alt: 'Apartment balconies against a clear sky' },
159 { id: 'ramp', title: 'P1 ramp rebar spacing', place: 'Parking level P1', photos: 14, mb: 42, saved: false, done: false, section: 'lower', photo: photo('1504307651254-35680f356dfd'), alt: 'Workers tying rebar on a concrete deck' },
160 { id: 'panel', title: 'Electrical panel labels', place: 'Basement plant room', photos: 5, mb: 12, saved: true, done: true, section: 'lower', photo: photo('1621905252507-b35492cc74b4'), alt: 'An electrician in a hard hat beside a wall meter' },
161 { id: 'window', title: 'Window seals, east facade', place: 'Levels 1 to 6', photos: 9, mb: 27, saved: false, done: false, section: 'lower', photo: photo('1509644851169-2acc08aa25b5'), alt: 'A tall window with a deep sill' },
162 { id: 'scaffold', title: 'Scaffold tags, north side', place: 'North elevation', photos: 3, mb: 7, saved: true, done: false, section: 'lower', photo: photo('1531834685032-c34bf0d84c77'), alt: 'Workers on a scaffold beside a concrete frame' },
163];
164
165type ChangeKind = 'done' | 'undone' | 'rename' | 'add';
166type ChangeStatus = 'waiting' | 'sending' | 'saved' | 'conflict';
167type Change = { id: string; itemId: string; kind: ChangeKind; at: string; from?: string; status: ChangeStatus; note?: string };
168
169// Edits made on site since the signal dropped, oldest first: they upload in this order.
170const QUEUE: Change[] = [
171 { id: 'q1', itemId: 'smoke', kind: 'done', at: '9 min ago', status: 'waiting' },
172 { id: 'q2', itemId: 'rail', kind: 'rename', from: 'Balcony railing height', at: '6 min ago', status: 'waiting' },
173 { id: 'q3', itemId: 'crack', kind: 'add', at: '2 min ago', status: 'waiting' },
174];
175
176// A teammate renamed the railing item while this phone was offline, so uploading the local rename meets a conflict.
177const CONFLICT = { itemId: 'rail', who: 'Dana Ortiz', device: 'tablet', title: 'Railing height recheck', when: '4 min ago' };
178
179// ─── Palette ────────────────────────────────────────────────────────────────
180
181const COLUMN = 520; // widest the screen gets on tablets and the web
182const PILL_H = 46;
183const PILL_W = 278;
184const PULL_AT = 58; // how far the list has to be pulled before letting go refreshes
185const PULL_HOLD = 50; // where the list rests while the pull message shows
186const HOLD_MS = 4500; // the first countdown waits this long before ticking, so the still shows a whole second
187const ON_STATUS = '#FFFFFF'; // icons and text on the green and red status fills
188const SPRING = { damping: 16, stiffness: 220, mass: 0.7 };
189const MOVE = LinearTransition.duration(260);
190const NO_OUTLINE = Platform.OS === 'web' ? ({ outlineStyle: 'none' } as object) : null;
191// A mouse drag that pulls the list should not select its text on the web.
192const NO_SELECT = Platform.OS === 'web' ? ({ userSelect: 'none' } as object) : null;
193
194function usePalette() {
195 const dark = useColorScheme() === 'dark';
196 return {
197 dark,
198 bg: dark ? '#1C1C1E' : '#F5F4F0',
199 bgClear: dark ? 'rgba(28, 28, 30, 0)' : 'rgba(245, 244, 240, 0)',
200 card: dark ? '#26262A' : '#FFFFFF',
201 raised: dark ? '#2E2E33' : '#FFFFFF',
202 fg: dark ? '#F2F2F0' : '#1B1A17',
203 muted: dark ? '#9C9CA3' : '#736F67',
204 faint: dark ? '#64646B' : '#B3AFA6',
205 line: dark ? '#36363B' : '#EAE8E2',
206 chip: dark ? '#36363B' : '#EFEDE8',
207 track: dark ? '#404046' : '#E2DFD8',
208 skeleton: dark ? '#303035' : '#EEECE7',
209 shine: dark ? '#3C3C42' : '#E2DFD8',
210 scrim: dark ? 'rgba(12, 12, 14, 0.5)' : 'rgba(34, 30, 24, 0.2)',
211 toast: dark ? '#3E3E44' : '#2A2824',
212 toastFg: dark ? '#F2F2F0' : '#FFFFFF',
213 accentText: dark ? ACCENT_DARK : shade(ACCENT, 0.45),
214 accentSoft: dark ? tint(ACCENT, 0.16) : tint(ACCENT, 0.14),
215 // The offline banner: a warm wash of the accent, kept as pale (or as dark) as designed whatever the accent.
216 bannerOff: dark ? tone(ACCENT, 0, 0.19, -0.5) : tone(ACCENT, 0, 0.93, 0),
217 bannerOffLine: dark ? tint(ACCENT, 0.26) : tint(ACCENT, 0.34),
218 bannerSub: dark ? tone(ACCENT, 0, 0.76, -0.45) : tone(ACCENT, 0, 0.3, -0.35),
219 retryBg: dark ? tone(ACCENT, 0, 0.25, -0.5) : '#FFFFFF',
220 retryTrack: dark ? tint(ACCENT, 0.22) : tint(ACCENT, 0.24),
221 bannerOn: dark ? '#203026' : '#E8F5EC',
222 bannerOnLine: dark ? 'rgba(74, 222, 128, 0.24)' : 'rgba(22, 163, 74, 0.26)',
223 bannerTrack: dark ? 'rgba(255, 255, 255, 0.08)' : 'rgba(22, 101, 52, 0.1)',
224 good: dark ? '#4ADE80' : '#15803D',
225 goodFill: dark ? '#22A559' : '#16A34A',
226 bad: dark ? '#FF7B7B' : '#D93636',
227 badFill: dark ? '#E5484D' : '#DC2F2F',
228 badSoft: dark ? 'rgba(255, 107, 107, 0.12)' : 'rgba(220, 47, 47, 0.06)',
229 badLine: dark ? 'rgba(255, 107, 107, 0.26)' : 'rgba(220, 47, 47, 0.2)',
230 trayShadow: dark ? '0px 12px 32px rgba(0, 0, 0, 0.4), 0px 0px 0px 1px rgba(255, 255, 255, 0.07)' : '0px 12px 32px rgba(40, 32, 18, 0.18)',
231 menuShadow: dark ? '0px 14px 36px rgba(0, 0, 0, 0.45), 0px 0px 0px 1px rgba(255, 255, 255, 0.07)' : '0px 14px 36px rgba(40, 32, 18, 0.16), 0px 0px 0px 1px rgba(40, 32, 18, 0.05)',
232 };
233}
234type Palette = ReturnType<typeof usePalette>;
235
236// ─── Helpers ────────────────────────────────────────────────────────────────
237
238const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
239const first = (name: string) => name.split(' ')[0];
240const rubber = (dy: number) => 130 * (1 - Math.exp(-dy / 190));
241
242function describe(ch: Change) {
243 if (ch.note) return ch.note;
244 if (ch.kind === 'done') return 'Marked done';
245 if (ch.kind === 'undone') return 'Marked not done';
246 if (ch.kind === 'rename') return `Renamed from “${ch.from}”`;
247 return 'Added';
248}
249
250const RANK: Record<ChangeStatus, number> = { saved: 1, waiting: 2, sending: 3, conflict: 4 };
251
252// ─── Small pieces ───────────────────────────────────────────────────────────
253
254function Spinner({ color, size = 16 }: { color: string; size?: number }) {
255 const r = useSharedValue(0);
256 useEffect(() => {
257 r.value = withRepeat(withTiming(360, { duration: 760, easing: Easing.linear }), -1);
258 return () => cancelAnimation(r);
259 }, [r]);
260 const style = useAnimatedStyle(() => ({ transform: [{ rotate: `${r.value}deg` }] }));
261 return <Animated.View style={[styles.spinner, { width: size, height: size, borderRadius: size / 2, borderColor: tint(color, 0.25), borderTopColor: color }, style]} />;
262}
263
264/** A thumbnail that pulses as a tinted placeholder, then fades in once loaded. */
265function Photo({ uri, alt, c }: { uri: string; alt: string; c: Palette }) {
266 const shown = useSharedValue(0);
267 const pulse = useSharedValue(0.4);
268 useEffect(() => {
269 pulse.value = withRepeat(withSequence(withTiming(1, { duration: 700 }), withTiming(0.4, { duration: 700 })), -1);
270 return () => cancelAnimation(pulse);
271 }, [pulse]);
272 const image = useAnimatedStyle(() => ({ opacity: shown.value }));
273 const placeholder = useAnimatedStyle(() => ({ opacity: (1 - shown.value) * pulse.value }));
274 return (
275 <View style={[styles.thumb, { backgroundColor: c.skeleton }]}>
276 <Animated.View style={[StyleSheet.absoluteFill, { backgroundColor: c.shine }, placeholder]} />
277 <Animated.View style={[StyleSheet.absoluteFill, image]}>
278 <Image
279 source={{ uri }}
280 alt={alt}
281 resizeMode="cover"
282 style={styles.thumbImage}
283 onLoad={() => {
284 cancelAnimation(pulse);
285 shown.value = withTiming(1, { duration: 320 });
286 }}
287 />
288 </Animated.View>
289 </View>
290 );
291}
292
293function Tap({ children, label, onPress, style, expanded }: { children: ReactNode; label: string; onPress?: () => void; style?: StyleProp<ViewStyle>; expanded?: boolean }) {
294 const scale = useSharedValue(1);
295 const anim = useAnimatedStyle(() => ({ transform: [{ scale: scale.value }] }));
296 return (
297 <Pressable
298 role="button"
299 aria-label={label}
300 aria-expanded={expanded}
301 hitSlop={6}
302 onPress={onPress}
303 onPressIn={() => (scale.value = withSpring(0.92, SPRING))}
304 onPressOut={() => (scale.value = withSpring(1, SPRING))}
305 >
306 <Animated.View style={[style, anim]}>{children}</Animated.View>
307 </Pressable>
308 );
309}
310
311function Toggle({ on, label, onPress, c }: { on: boolean; label: string; onPress: () => void; c: Palette }) {
312 const t = useSharedValue(on ? 1 : 0);
313 useEffect(() => {
314 t.value = withSpring(on ? 1 : 0, { damping: 15, stiffness: 260, mass: 0.6 });
315 }, [on, t]);
316 const off = c.track;
317 const track = useAnimatedStyle(() => ({ backgroundColor: interpolateColor(t.value, [0, 1], [off, ACCENT]) }));
318 const knob = useAnimatedStyle(() => ({ transform: [{ translateX: t.value * 18 }] }));
319 return (
320 <Pressable role="switch" aria-checked={on} aria-label={label} onPress={onPress} hitSlop={8}>
321 <Animated.View style={[styles.switch, track]}>
322 <Animated.View style={[styles.knob, knob]} />
323 </Animated.View>
324 </Pressable>
325 );
326}
327
328// ─── Connection glyph: the arcs pulse outward while searching, the slash retracts once connected ─
329
330const AnimatedPath = Animated.createAnimatedComponent(Path);
331const AnimatedCircle = Animated.createAnimatedComponent(Circle);
332const ARCS = ['M8.6 16.2a4.8 4.8 0 0 1 6.8 0', 'M5.2 12.7a9.6 9.6 0 0 1 13.6 0', 'M1.9 9.2a14.4 14.4 0 0 1 20.2 0'];
333const SLASH_LEN = 24.1;
334
335function Arc({ d, index, scan, link, color }: { d: string; index: number; scan: SharedValue<number>; link: SharedValue<number>; color: string }) {
336 const props = useAnimatedProps(() => {
337 const t = scan.value * 1.6 - index * 0.28;
338 const wave = Math.max(0, 1 - Math.abs(t - 0.3) / 0.3);
339 return { strokeOpacity: (0.3 + 0.7 * wave) * (1 - link.value) + link.value };
340 });
341 return <AnimatedPath d={d} stroke={color} strokeWidth={2.3} strokeLinecap="round" fill="none" animatedProps={props} />;
342}
343
344function SignalGlyph({ scan, link, color }: { scan: SharedValue<number>; link: SharedValue<number>; color: string }) {
345 const slash = useAnimatedProps(() => ({ strokeDashoffset: SLASH_LEN * link.value, strokeOpacity: 1 - link.value }));
346 return (
347 <Svg width={22} height={22} viewBox="0 0 24 24">
348 {ARCS.map((d, i) => (
349 <Arc key={d} d={d} index={i} scan={scan} link={link} color={color} />
350 ))}
351 <Circle cx={12} cy={19.6} r={1.5} fill={color} />
352 <AnimatedPath d="M3.5 3.5 L20.5 20.5" stroke={color} strokeWidth={2.3} strokeLinecap="round" fill="none" strokeDasharray={`${SLASH_LEN} ${SLASH_LEN}`} animatedProps={slash} />
353 </Svg>
354 );
355}
356
357type Phase = 'offline' | 'syncing' | 'conflict' | 'saved' | 'hidden';
358
359function GlyphTile({ phase, fail, c }: { phase: Phase; fail: number; c: Palette }) {
360 const scan = useSharedValue(0);
361 const link = useSharedValue(phase === 'offline' ? 0 : 1);
362 const mode = useSharedValue(0);
363 const done = useSharedValue(0);
364 const shake = useSharedValue(0);
365 useEffect(() => {
366 scan.value = withRepeat(withTiming(1, { duration: 1700, easing: Easing.linear }), -1);
367 return () => cancelAnimation(scan);
368 }, [scan]);
369 useEffect(() => {
370 if (phase === 'hidden') return;
371 link.value = withTiming(phase === 'offline' ? 0 : 1, { duration: 520, easing: Easing.out(Easing.cubic) });
372 mode.value = withTiming(phase === 'offline' ? 0 : phase === 'conflict' ? 2 : 1, { duration: 400 });
373 done.value = withTiming(phase === 'saved' ? 1 : 0, { duration: 280 });
374 }, [phase, link, mode, done]);
375 useEffect(() => {
376 if (!fail) return;
377 shake.value = withSequence(withTiming(-4, { duration: 50 }), withTiming(4, { duration: 70 }), withTiming(-3, { duration: 70 }), withTiming(0, { duration: 60 }));
378 }, [fail, shake]);
379 const green = c.goodFill;
380 const red = c.badFill;
381 const tile = useAnimatedStyle(() => ({
382 backgroundColor: interpolateColor(mode.value, [0, 1, 2], [ACCENT, green, red]),
383 transform: [{ translateX: shake.value }, { rotate: `${shake.value * 1.5}deg` }],
384 }));
385 const glyph = useAnimatedStyle(() => ({ opacity: 1 - done.value, transform: [{ scale: 1 - done.value * 0.4 }] }));
386 const tick = useAnimatedStyle(() => ({ opacity: done.value, transform: [{ scale: 0.4 + done.value * 0.6 }] }));
387 return (
388 <Animated.View style={[styles.tile, tile]}>
389 <Animated.View style={glyph}>
390 <SignalGlyph scan={scan} link={link} color={phase === 'offline' ? ON_ACCENT : ON_STATUS} />
391 </Animated.View>
392 <Animated.View style={[StyleSheet.absoluteFill, styles.center, tick]}>
393 <Check size={20} color={ON_STATUS} strokeWidth={3} />
394 </Animated.View>
395 </Animated.View>
396 );
397}
398
399// ─── Banner: slides down under the header, retries on a backing-off countdown ─
400
401const RETRY_R = 8.5;
402const RETRY_LEN = 2 * Math.PI * RETRY_R;
403
404function OfflineBody({ hold, savedAgo, onFail, c }: { hold: boolean; savedAgo: string; onFail: () => void; c: Palette }) {
405 const [step, setStep] = useState(hold ? START_STEP : 0);
406 const [left, setLeft] = useState(hold ? START_LEFT : DELAYS[0]);
407 const [held, setHeld] = useState(hold);
408 const [checking, setChecking] = useState(false);
409 const [note, setNote] = useState(false);
410 const fill = useSharedValue(left / DELAYS[step]);
411 const failRef = useRef(onFail);
412 useEffect(() => {
413 failRef.current = onFail;
414 }, [onFail]);
415
416 // One tick a second. At zero it checks, fails (the network is off) and waits longer before the next try.
417 useEffect(() => {
418 if (checking) {
419 const t = setTimeout(() => {
420 const next = Math.min(step + 1, DELAYS.length - 1);
421 setChecking(false);
422 setStep(next);
423 setLeft(DELAYS[next]);
424 setNote(true);
425 failRef.current();
426 }, 1400);
427 return () => clearTimeout(t);
428 }
429 const t = setTimeout(
430 () => {
431 setHeld(false);
432 if (left <= 1) setChecking(true);
433 else setLeft(left - 1);
434 },
435 held ? HOLD_MS : 1000
436 );
437 return () => clearTimeout(t);
438 }, [checking, held, left, step]);
439
440 // The button's fill drains across each second.
441 useEffect(() => {
442 const total = DELAYS[step];
443 if (checking) {
444 fill.value = withTiming(0, { duration: 180 });
445 return;
446 }
447 if (held) {
448 fill.value = left / total;
449 return;
450 }
451 fill.value = withSequence(
452 withTiming(left / total, { duration: fill.value < left / total - 0.15 ? 260 : 0 }),
453 withTiming((left - 1) / total, { duration: 1000, easing: Easing.linear })
454 );
455 }, [left, held, checking, step, fill]);
456
457 useEffect(() => {
458 if (!note) return;
459 const t = setTimeout(() => setNote(false), 2800);
460 return () => clearTimeout(t);
461 }, [note]);
462
463 const drain = useAnimatedProps(() => ({ strokeDashoffset: RETRY_LEN * (1 - Math.max(0, Math.min(1, fill.value))) }));
464 const retry = () => {
465 if (checking) return;
466 setHeld(false);
467 setChecking(true);
468 };
469
470 return (
471 <View style={styles.bannerRow}>
472 <View style={styles.bannerText}>
473 <Text style={[styles.bannerTitle, { color: c.fg }]}>You're offline</Text>
474 <Animated.Text key={note ? 'note' : 'saved'} entering={FadeIn.duration(220)} style={[styles.bannerSub, { color: c.bannerSub }]}>
475 {note ? 'Still no signal. Retrying less often.' : `Showing what was saved ${savedAgo}.`}
476 </Animated.Text>
477 </View>
478 <Pressable
479 role="button"
480 aria-label={checking ? 'Checking the connection' : `Retry now. Next automatic try in ${left} seconds`}
481 aria-busy={checking}
482 onPress={retry}
483 style={({ pressed }) => [styles.retry, { backgroundColor: c.retryBg, borderColor: c.bannerOffLine, opacity: pressed ? 0.75 : 1 }]}
484 >
485 {checking ? (
486 <View style={styles.retryRing}>
487 <Spinner color={c.accentText} size={16} />
488 </View>
489 ) : (
490 <View style={styles.retryRing}>
491 <View style={styles.ringRotate}>
492 <Svg width={21} height={21} viewBox="0 0 21 21">
493 <Circle cx={10.5} cy={10.5} r={RETRY_R} stroke={c.retryTrack} strokeWidth={2.2} fill="none" />
494 <AnimatedCircle cx={10.5} cy={10.5} r={RETRY_R} stroke={c.accentText} strokeWidth={2.2} strokeLinecap="round" fill="none" strokeDasharray={`${RETRY_LEN} ${RETRY_LEN}`} animatedProps={drain} />
495 </Svg>
496 </View>
497 <RotateCw size={9} color={c.accentText} strokeWidth={3} />
498 </View>
499 )}
500 {checking ? (
501 <Text style={[styles.retryLabel, { color: c.accentText }]}>Checking</Text>
502 ) : (
503 <View style={styles.retryRow}>
504 <Text style={[styles.retryLabel, { color: c.accentText }]}>Retry in</Text>
505 <View style={styles.retryDigits}>
506 <Animated.Text key={`${step}-${left}`} entering={held ? undefined : FadeInUp.duration(200)} style={[styles.retryLabel, styles.tabular, { color: c.accentText }]}>
507 {left}s
508 </Animated.Text>
509 </View>
510 </View>
511 )}
512 </Pressable>
513 </View>
514 );
515}
516
517function SyncBody({ phase, total, done, c }: { phase: Phase; total: number; done: number; c: Palette }) {
518 const changes = plural(total, 'change');
519 const title = phase === 'saved' ? (total ? 'All changes saved' : 'Back online') : phase === 'conflict' ? 'Back online' : `Back online, syncing ${changes}`;
520 const sub =
521 phase === 'saved'
522 ? total
523 ? `${changes} synced just now`
524 : 'Everything is up to date'
525 : phase === 'conflict'
526 ? '1 change needs your decision'
527 : `${done} of ${total} saved`;
528 return (
529 <View style={styles.bannerRow}>
530 <View style={styles.bannerText}>
531 <Text numberOfLines={2} style={[styles.bannerTitle, { color: c.fg }]}>
532 {title}
533 </Text>
534 <Animated.Text key={sub} entering={FadeIn.duration(200)} style={[styles.bannerSub, styles.tabular, { color: phase === 'conflict' ? c.bad : c.muted }]}>
535 {sub}
536 </Animated.Text>
537 </View>
538 {phase === 'syncing' ? <Spinner color={c.good} size={18} /> : null}
539 </View>
540 );
541}
542
543function Banner({ phase, savedAgo, total, done, c }: { phase: Phase; savedAgo: string; total: number; done: number; c: Palette }) {
544 const open = useSharedValue(0);
545 const h = useSharedValue(0);
546 const mode = useSharedValue(phase === 'offline' ? 0 : 1);
547 const bar = useSharedValue(0);
548 const measured = useRef(false);
549 const booted = useRef(false);
550 const [session, setSession] = useState(0);
551 const [failTick, setFailTick] = useState(0);
552 const [last, setLast] = useState(phase);
553 // The body keeps showing the last visible phase while the banner collapses.
554 const [shown, setShown] = useState<Phase>(phase === 'hidden' ? 'offline' : phase);
555 if (last !== phase) {
556 if (phase === 'offline') setSession((s) => s + 1);
557 if (phase !== 'hidden') setShown(phase);
558 setLast(phase);
559 }
560
561 useEffect(() => {
562 const show = phase !== 'hidden';
563 open.value = withDelay(
564 booted.current ? 0 : 240,
565 withTiming(show ? 1 : 0, { duration: show ? 480 : 380, easing: show ? Easing.out(Easing.cubic) : Easing.inOut(Easing.cubic) })
566 );
567 booted.current = true;
568 if (show) mode.value = withTiming(phase === 'offline' ? 0 : 1, { duration: 420 });
569 }, [phase, open, mode]);
570 useEffect(() => {
571 bar.value = withTiming(total ? done / total : 1, { duration: 380, easing: Easing.out(Easing.cubic) });
572 }, [done, total, bar]);
573
574 const off = c.bannerOff;
575 const on = c.bannerOn;
576 const offLine = c.bannerOffLine;
577 const onLine = c.bannerOnLine;
578 const wrap = useAnimatedStyle(() => ({ height: h.value * open.value }));
579 const card = useAnimatedStyle(() => ({
580 opacity: Math.min(1, open.value * 1.6),
581 transform: [{ translateY: (open.value - 1) * 26 }],
582 backgroundColor: interpolateColor(mode.value, [0, 1], [off, on]),
583 borderColor: interpolateColor(mode.value, [0, 1], [offLine, onLine]),
584 }));
585 const barStyle = useAnimatedStyle(() => ({ width: `${bar.value * 100}%` }));
586
587 const onLayout = (e: LayoutChangeEvent) => {
588 const v = e.nativeEvent.layout.height;
589 if (!measured.current) {
590 h.value = v;
591 measured.current = true;
592 } else h.value = withTiming(v, { duration: 260, easing: Easing.out(Easing.cubic) });
593 };
594
595 return (
596 <Animated.View aria-hidden={phase === 'hidden'} style={[styles.bannerWrap, wrap]}>
597 <View onLayout={onLayout} style={styles.bannerMeasure}>
598 <Animated.View role={phase === 'hidden' ? undefined : 'alert'} style={[styles.banner, card]}>
599 <GlyphTile phase={phase} fail={failTick} c={c} />
600 <View style={styles.flex}>
601 {shown === 'offline' ? (
602 <Animated.View key={`off${session}`} entering={session ? FadeIn.duration(260) : undefined}>
603 <OfflineBody hold={session === 0} savedAgo={savedAgo} onFail={() => setFailTick((t) => t + 1)} c={c} />
604 </Animated.View>
605 ) : (
606 <Animated.View key={shown} entering={FadeIn.duration(240)}>
607 <SyncBody phase={shown} total={total} done={done} c={c} />
608 </Animated.View>
609 )}
610 </View>
611 {shown !== 'offline' ? (
612 <View style={[styles.bannerTrack, { backgroundColor: c.bannerTrack }]}>
613 <Animated.View style={[styles.bannerBar, { backgroundColor: c.goodFill }, barStyle]} />
614 </View>
615 ) : null}
616 </Animated.View>
617 </View>
618 </Animated.View>
619 );
620}
621
622// ─── Rows: done box, cached photo, rename in place, save for offline ────────
623
624function CheckBox({ on, locked, label, onPress, c }: { on: boolean; locked: boolean; label: string; onPress: () => void; c: Palette }) {
625 const pop = useSharedValue(1);
626 const fill = useSharedValue(on ? 1 : 0);
627 const booted = useRef(false);
628 useEffect(() => {
629 if (!booted.current) {
630 booted.current = true;
631 return;
632 }
633 fill.value = withTiming(on ? 1 : 0, { duration: 160 });
634 pop.value = withSequence(withTiming(0.8, { duration: 90 }), withTiming(1, { duration: 280, easing: Easing.out(Easing.back(3)) }));
635 }, [on, fill, pop]);
636 const box = useAnimatedStyle(() => ({ transform: [{ scale: pop.value }] }));
637 const inner = useAnimatedStyle(() => ({ opacity: fill.value, transform: [{ scale: 0.55 + fill.value * 0.45 }] }));
638 return (
639 <Pressable role="checkbox" aria-checked={on} aria-disabled={locked} aria-label={label} hitSlop={8} onPress={onPress} style={styles.checkHit}>
640 <Animated.View style={[styles.check, { borderColor: on ? ACCENT : c.faint, opacity: locked ? 0.45 : 1 }, box]}>
641 <Animated.View style={[styles.checkFill, inner]}>
642 <Check size={14} color={ON_ACCENT} strokeWidth={3.4} />
643 </Animated.View>
644 </Animated.View>
645 </Pressable>
646 );
647}
648
649const RING_R = 12;
650const RING_LEN = 2 * Math.PI * RING_R;
651
652type SaveState = 'saved' | 'none' | 'loading';
653
654function SaveToggle({ state, offline, mb, title, onPress, onDone, c }: { state: SaveState; offline: boolean; mb: number; title: string; onPress: () => void; onDone: () => void; c: Palette }) {
655 const p = useSharedValue(0);
656 const pop = useSharedValue(1);
657 const prev = useRef(state);
658 const doneRef = useRef(onDone);
659 useEffect(() => {
660 doneRef.current = onDone;
661 }, [onDone]);
662 useEffect(() => {
663 const was = prev.current;
664 prev.current = state;
665 if (state === 'loading') {
666 // Downloads move in bursts: quick start, a slower middle, then the last photos.
667 const dur = 900 + mb * 32;
668 p.value = 0;
669 p.value = withSequence(
670 withTiming(0.38, { duration: dur * 0.28, easing: Easing.out(Easing.quad) }),
671 withTiming(0.64, { duration: dur * 0.4, easing: Easing.inOut(Easing.quad) }),
672 withTiming(1, { duration: dur * 0.32, easing: Easing.in(Easing.quad) })
673 );
674 const t = setTimeout(() => doneRef.current(), dur + 140);
675 return () => {
676 clearTimeout(t);
677 cancelAnimation(p);
678 };
679 }
680 if (state === 'saved' && was === 'loading') {
681 pop.value = withSequence(withTiming(1.25, { duration: 120 }), withTiming(1, { duration: 280, easing: Easing.out(Easing.back(2.6)) }));
682 }
683 }, [state, mb, p, pop]);
684 const arc = useAnimatedProps(() => ({ strokeDashoffset: RING_LEN * (1 - p.value) }));
685 const popStyle = useAnimatedStyle(() => ({ transform: [{ scale: pop.value }] }));
686 const label = state === 'loading' ? `Saving ${title} for offline. Tap to cancel` : state === 'saved' ? `${title} is saved for offline. Tap to remove` : `Save ${title} for offline`;
687 return (
688 <Pressable role="switch" aria-checked={state === 'saved'} aria-label={label} hitSlop={6} onPress={onPress} style={styles.saveHit}>
689 {state === 'loading' ? (
690 <Animated.View entering={FadeIn.duration(140)} style={styles.ring}>
691 <View style={styles.ringRotate}>
692 <Svg width={30} height={30} viewBox="0 0 30 30">
693 <Circle cx={15} cy={15} r={RING_R} stroke={c.track} strokeWidth={2.6} fill="none" />
694 <AnimatedCircle cx={15} cy={15} r={RING_R} stroke={ACCENT} strokeWidth={2.6} strokeLinecap="round" fill="none" strokeDasharray={`${RING_LEN} ${RING_LEN}`} animatedProps={arc} />
695 </Svg>
696 </View>
697 <View style={[styles.ringStop, { backgroundColor: c.accentText }]} />
698 </Animated.View>
699 ) : (
700 <Animated.View style={[styles.saveDot, state === 'saved' ? { backgroundColor: c.accentSoft, borderColor: 'transparent' } : { borderColor: offline ? c.line : c.faint }, popStyle]}>
701 <ArrowDownToLine size={15} color={state === 'saved' ? c.accentText : offline ? c.faint : c.muted} strokeWidth={2.5} />
702 </Animated.View>
703 )}
704 </Pressable>
705 );
706}
707
708function StatusLine({ change, locked, loading, mb, c }: { change?: Change; locked: boolean; loading: boolean; mb: number; c: Palette }) {
709 let icon: ReactNode = null;
710 let text = '';
711 let color = c.muted;
712 if (change?.status === 'conflict') {
713 icon = <TriangleAlert size={12} color={c.bad} strokeWidth={2.6} />;
714 text = 'Edited on another device';
715 color = c.bad;
716 } else if (change?.status === 'sending') {
717 icon = <Spinner color={c.good} size={11} />;
718 text = 'Syncing';
719 color = c.good;
720 } else if (change?.status === 'saved') {
721 icon = <Check size={12} color={c.good} strokeWidth={3} />;
722 text = 'Synced';
723 color = c.good;
724 } else if (change) {
725 icon = <Clock size={12} color={c.accentText} strokeWidth={2.6} />;
726 text = 'Waiting to sync';
727 color = c.accentText;
728 } else if (loading) {
729 icon = <ArrowDownToLine size={12} color={c.accentText} strokeWidth={2.6} />;
730 text = `Saving for offline · ${mb} MB`;
731 color = c.accentText;
732 } else if (locked) {
733 icon = <CloudOff size={12} color={c.muted} strokeWidth={2.4} />;
734 text = 'Not available offline';
735 }
736 if (!text) return null;
737 return (
738 <Animated.View key={text} entering={FadeIn.duration(200)} style={styles.status}>
739 {icon}
740 <Text numberOfLines={1} style={[styles.statusText, { color }]}>
741 {text}
742 </Text>
743 </Animated.View>
744 );
745}
746
747type RowProps = {
748 item: Item;
749 delay: number;
750 offline: boolean;
751 change?: Change;
752 loading: boolean;
753 editing: boolean;
754 last: boolean;
755 onToggle: () => void;
756 onSave: () => void;
757 onSaveDone: () => void;
758 onRenameStart: () => void;
759 onRenameEnd: (title: string) => void;
760 onBlocked: (message: string) => void;
761 c: Palette;
762};
763
764function Row({ item, delay, offline, change, loading, editing, last, onToggle, onSave, onSaveDone, onRenameStart, onRenameEnd, onBlocked, c }: RowProps) {
765 const locked = offline && !item.saved;
766 const shake = useSharedValue(0);
767 const [draft, setDraft] = useState(item.title);
768 const nudge = (message: string) => {
769 shake.value = withSequence(withTiming(-6, { duration: 50 }), withTiming(6, { duration: 70 }), withTiming(-4, { duration: 70 }), withTiming(3, { duration: 60 }), withTiming(0, { duration: 50 }));
770 onBlocked(message);
771 };
772 const lockedMessage = 'Not saved for offline. Save it next time you have signal.';
773 const rowStyle = useAnimatedStyle(() => ({ transform: [{ translateX: shake.value }] }));
774 const meta = item.photos ? `${item.place} · ${plural(item.photos, 'photo')}` : `${item.place} · No photos yet`;
775 const commit = () => onRenameEnd(draft);
776
777 return (
778 <Animated.View entering={FadeInDown.delay(delay).duration(360)} exiting={FadeOut.duration(180)} layout={MOVE}>
779 <Animated.View style={[styles.row, rowStyle]}>
780 <CheckBox on={item.done} locked={locked} label={`${item.title}: ${item.done ? 'done' : 'not done'}`} onPress={() => (locked ? nudge(lockedMessage) : onToggle())} c={c} />
781 <Pressable aria-label={locked ? `${item.title}, not available offline` : item.title} onPress={() => (locked ? nudge(lockedMessage) : undefined)} style={styles.rowMain}>
782 <View style={{ opacity: locked ? 0.55 : 1 }}>
783 {!item.photo ? (
784 <View style={[styles.thumb, styles.center, { backgroundColor: c.accentSoft }]}>
785 <Camera size={18} color={c.accentText} strokeWidth={2.1} />
786 </View>
787 ) : locked ? (
788 <View style={[styles.thumb, styles.center, { backgroundColor: c.skeleton }]}>
789 <ImageOff size={17} color={c.faint} strokeWidth={2} />
790 </View>
791 ) : (
792 <Photo uri={item.photo} alt={item.alt ?? item.title} c={c} />
793 )}
794 </View>
795 <View style={styles.rowText}>
796 {editing ? (
797 <TextInput
798 value={draft}
799 onChangeText={setDraft}
800 autoFocus
801 selectTextOnFocus
802 maxLength={60}
803 returnKeyType="done"
804 onSubmitEditing={commit}
805 onBlur={commit}
806 selectionColor={ACCENT}
807 aria-label={`Rename ${item.title}`}
808 style={[styles.rowTitle, styles.rowInput, { color: c.fg, borderBottomColor: ACCENT }, NO_OUTLINE]}
809 />
810 ) : (
811 <Pressable
812 role="button"
813 aria-label={`Rename ${item.title}`}
814 onPress={() => {
815 if (locked) return nudge(lockedMessage);
816 setDraft(item.title);
817 onRenameStart();
818 }}
819 >
820 <Text numberOfLines={1} style={[styles.rowTitle, { color: locked || item.done ? c.muted : c.fg }]}>
821 {item.title}
822 </Text>
823 </Pressable>
824 )}
825 <Text numberOfLines={1} style={[styles.rowMeta, { color: locked ? c.faint : c.muted }]}>
826 {meta}
827 </Text>
828 <StatusLine change={change} locked={locked} loading={loading} mb={item.mb} c={c} />
829 </View>
830 </Pressable>
831 <SaveToggle
832 state={loading ? 'loading' : item.saved ? 'saved' : 'none'}
833 offline={offline}
834 mb={item.mb}
835 title={item.title}
836 onPress={() => (locked ? nudge('Connect to save this for offline.') : onSave())}
837 onDone={onSaveDone}
838 c={c}
839 />
840 </Animated.View>
841 {!last ? <View style={[styles.rowLine, { backgroundColor: c.line }]} /> : null}
842 </Animated.View>
843 );
844}
845
846// ─── Sync tray: the queue pill opens into the list of pending edits ─────────
847
848function ConflictCard({ title, onKeep, c }: { title: string; onKeep: (mine: boolean) => void; c: Palette }) {
849 return (
850 <Animated.View entering={FadeInDown.duration(260)} style={[styles.conflict, { backgroundColor: c.badSoft, borderColor: c.badLine }]}>
851 <View style={styles.conflictHead}>
852 <TriangleAlert size={14} color={c.bad} strokeWidth={2.5} />
853 <Text style={[styles.conflictTitle, { color: c.bad }]}>Edited on another device</Text>
854 </View>
855 <View style={styles.versions}>
856 <View style={[styles.version, { backgroundColor: c.card, borderColor: c.line }]}>
857 <Text style={[styles.versionLabel, { color: c.muted }]}>Yours · this phone</Text>
858 <Text numberOfLines={1} style={[styles.versionValue, { color: c.fg }]}>
859 {title}
860 </Text>
861 </View>
862 <View style={[styles.version, { backgroundColor: c.card, borderColor: c.line }]}>
863 <Text style={[styles.versionLabel, { color: c.muted }]}>
864 {first(CONFLICT.who)} · {CONFLICT.device} · {CONFLICT.when}
865 </Text>
866 <Text numberOfLines={1} style={[styles.versionValue, { color: c.fg }]}>
867 {CONFLICT.title}
868 </Text>
869 </View>
870 </View>
871 <View style={styles.conflictActions}>
872 <Pressable role="button" aria-label="Keep my version" onPress={() => onKeep(true)} style={({ pressed }) => [styles.keep, styles.keepMine, { opacity: pressed ? 0.8 : 1 }]}>
873 <Text style={[styles.keepLabel, { color: ON_ACCENT }]}>Keep mine</Text>
874 </Pressable>
875 <Pressable
876 role="button"
877 aria-label={`Keep ${first(CONFLICT.who)}'s version`}
878 onPress={() => onKeep(false)}
879 style={({ pressed }) => [styles.keep, { backgroundColor: c.card, borderColor: c.line, opacity: pressed ? 0.7 : 1 }]}
880 >
881 <Text style={[styles.keepLabel, { color: c.fg }]}>Keep theirs</Text>
882 </Pressable>
883 </View>
884 </Animated.View>
885 );
886}
887
888function ChangeRow({ change, item, onUndo, onResolve, c }: { change: Change; item?: Item; onUndo: () => void; onResolve: (mine: boolean) => void; c: Palette }) {
889 const Icon = change.kind === 'done' ? Check : change.kind === 'undone' ? RotateCcw : change.kind === 'rename' ? Pencil : Plus;
890 return (
891 <Animated.View entering={FadeIn.duration(220)} exiting={FadeOut.duration(160)} layout={MOVE} style={styles.change}>
892 <View style={styles.changeTop}>
893 <View style={[styles.changeIcon, { backgroundColor: c.chip }]}>
894 <Icon size={14} color={c.fg} strokeWidth={2.5} />
895 </View>
896 <View style={styles.flex}>
897 <Text numberOfLines={1} style={[styles.changeTitle, { color: c.fg }]}>
898 {item?.title ?? 'Removed item'}
899 </Text>
900 <View style={styles.changeSubRow}>
901 {change.status === 'waiting' ? <Clock size={11} color={c.muted} strokeWidth={2.6} style={styles.noShrink} /> : null}
902 <Text numberOfLines={1} style={[styles.changeSub, { color: c.muted }]}>
903 {describe(change)} · {change.at}
904 </Text>
905 </View>
906 </View>
907 <View style={styles.changeEnd}>
908 {change.status === 'waiting' ? (
909 <Pressable role="button" aria-label={`Undo: ${describe(change)}, ${item?.title ?? ''}`} onPress={onUndo} hitSlop={6} style={({ pressed }) => [styles.undo, { backgroundColor: c.chip, opacity: pressed ? 0.7 : 1 }]}>
910 <Undo2 size={13} color={c.fg} strokeWidth={2.5} />
911 <Text style={[styles.undoLabel, { color: c.fg }]}>Undo</Text>
912 </Pressable>
913 ) : change.status === 'sending' ? (
914 <Spinner color={c.good} size={18} />
915 ) : change.status === 'saved' ? (
916 <Animated.View entering={ZoomIn.duration(260)} style={[styles.doneDot, { backgroundColor: c.goodFill }]}>
917 <Check size={13} color={ON_STATUS} strokeWidth={3.4} />
918 </Animated.View>
919 ) : (
920 <TriangleAlert size={18} color={c.bad} strokeWidth={2.4} />
921 )}
922 </View>
923 </View>
924 {change.status === 'conflict' && item ? <ConflictCard title={item.title} onKeep={onResolve} c={c} /> : null}
925 </Animated.View>
926 );
927}
928
929type TrayProps = {
930 queue: Change[];
931 items: Item[];
932 online: boolean;
933 phase: Phase;
934 open: boolean;
935 width: number;
936 maxList: number;
937 onToggle: () => void;
938 onUndo: (ch: Change) => void;
939 onResolve: (ch: Change, mine: boolean) => void;
940 c: Palette;
941};
942
943function SyncTray({ queue, items, online, phase, open, width, maxList, onToggle, onUndo, onResolve, c }: TrayProps) {
944 const vis = useSharedValue(0);
945 const op = useSharedValue(0);
946 const listH = useSharedValue(0);
947 const good = useSharedValue(0);
948 const measured = useRef(false);
949 const booted = useRef(false);
950 const visible = queue.length > 0;
951 useEffect(() => {
952 vis.value = withDelay(booted.current ? 0 : 640, withTiming(visible ? 1 : 0, { duration: visible ? 460 : 260, easing: visible ? Easing.out(Easing.back(1.6)) : Easing.in(Easing.quad) }));
953 booted.current = true;
954 }, [visible, vis]);
955 useEffect(() => {
956 op.value = withTiming(open ? 1 : 0, { duration: 340, easing: Easing.out(Easing.cubic) });
957 }, [open, op]);
958 useEffect(() => {
959 good.value = withTiming(phase === 'saved' ? 1 : 0, { duration: 300 });
960 }, [phase, good]);
961
962 const full = width;
963 const green = c.goodFill;
964 const box = useAnimatedStyle(() => ({
965 width: PILL_W + (full - PILL_W) * op.value,
966 height: PILL_H + listH.value * op.value,
967 opacity: Math.min(1, Math.max(0, vis.value)),
968 transform: [{ translateY: (1 - vis.value) * 40 }, { scale: 0.9 + 0.1 * vis.value }],
969 }));
970 const head = useAnimatedStyle(() => ({ backgroundColor: interpolateColor(good.value, [0, 1], [ACCENT, green]) }));
971 const chevron = useAnimatedStyle(() => ({ transform: [{ rotate: `${op.value * 180}deg` }] }));
972
973 const total = queue.length;
974 const saved = queue.filter((q) => q.status === 'saved').length;
975 const waiting = total - saved;
976 const label = !online
977 ? `${plural(waiting, 'change')} waiting to sync`
978 : phase === 'conflict'
979 ? '1 change needs you'
980 : phase === 'syncing'
981 ? `Syncing ${Math.min(saved + 1, total)} of ${total}`
982 : 'All changes saved';
983 const ink = phase === 'saved' ? ON_STATUS : ON_ACCENT;
984 const icon =
985 phase === 'saved' ? (
986 <Check size={17} color={ink} strokeWidth={3} />
987 ) : phase === 'syncing' ? (
988 <Spinner color={ink} size={15} />
989 ) : phase === 'conflict' ? (
990 <TriangleAlert size={16} color={ink} strokeWidth={2.5} />
991 ) : (
992 <Clock size={16} color={ink} strokeWidth={2.5} />
993 );
994
995 const onLayout = (e: LayoutChangeEvent) => {
996 const v = e.nativeEvent.layout.height;
997 if (!measured.current) {
998 listH.value = v;
999 measured.current = true;
1000 } else listH.value = withTiming(v, { duration: 260, easing: Easing.out(Easing.cubic) });
1001 };
1002
1003 return (
1004 <Animated.View style={[styles.tray, { backgroundColor: c.raised, boxShadow: c.trayShadow, pointerEvents: visible ? 'auto' : 'none' }, box]}>
1005 <Pressable role="button" aria-expanded={open} aria-label={`${label}. ${open ? 'Hide' : 'Show'} the list`} onPress={onToggle}>
1006 <Animated.View style={[styles.trayHead, head]}>
1007 {icon}
1008 <Animated.Text key={label} entering={FadeIn.duration(180)} numberOfLines={1} style={[styles.trayLabel, styles.tabular, { color: ink }]}>
1009 {label}
1010 </Animated.Text>
1011 <Animated.View style={chevron}>
1012 <ChevronUp size={18} color={ink} strokeWidth={2.5} />
1013 </Animated.View>
1014 </Animated.View>
1015 </Pressable>
1016 <ScrollView onLayout={onLayout} style={[styles.trayScroll, { maxHeight: maxList }]} contentContainerStyle={styles.trayList} showsVerticalScrollIndicator={false}>
1017 <Text style={[styles.trayIntro, { color: c.muted }]}>
1018 {online ? 'Sending in the order you made them.' : `Kept on this phone. ${APP_NAME} sends them in order once you have signal again.`}
1019 </Text>
1020 {queue.map((ch) => (
1021 <ChangeRow key={ch.id} change={ch} item={items.find((i) => i.id === ch.itemId)} onUndo={() => onUndo(ch)} onResolve={(mine) => onResolve(ch, mine)} c={c} />
1022 ))}
1023 </ScrollView>
1024 </Animated.View>
1025 );
1026}
1027
1028// ─── Overflow menu: the simulated connection switch ─────────────────────────
1029
1030type MenuProps = {
1031 top: number;
1032 online: boolean;
1033 unsaved: Item[];
1034 savedCount: number;
1035 savedMb: number;
1036 onNet: () => void;
1037 onSaveAll: () => void;
1038 onClose: () => void;
1039 c: Palette;
1040};
1041
1042function Menu({ top, online, unsaved, savedCount, savedMb, onNet, onSaveAll, onClose, c }: MenuProps) {
1043 const pendingMb = unsaved.reduce((s, i) => s + i.mb, 0);
1044 return (
1045 <>
1046 <Pressable aria-label="Close menu" onPress={onClose} style={styles.menuScrim} />
1047 <Animated.View entering={FadeInUp.duration(200)} exiting={FadeOut.duration(140)} role="menu" style={[styles.menu, { top, backgroundColor: c.raised, boxShadow: c.menuShadow }]}>
1048 <View style={styles.menuRow}>
1049 <View style={[styles.menuIcon, { backgroundColor: c.accentSoft }]}>
1050 <WifiOff size={16} color={c.accentText} strokeWidth={2.3} />
1051 </View>
1052 <View style={styles.flex}>
1053 <Text style={[styles.menuTitle, { color: c.fg }]}>Simulate offline</Text>
1054 <Text style={[styles.menuSub, { color: c.muted }]}>{online ? 'Drop the connection to try it' : 'Turn off to reconnect'}</Text>
1055 </View>
1056 <Toggle on={!online} label="Simulate offline" onPress={onNet} c={c} />
1057 </View>
1058 <View style={[styles.menuLine, { backgroundColor: c.line }]} />
1059 <Pressable role="menuitem" aria-label="Save all for offline" onPress={onSaveAll} style={({ pressed }) => [styles.menuRow, { backgroundColor: pressed ? c.chip : 'transparent' }]}>
1060 <View style={[styles.menuIcon, { backgroundColor: c.chip }]}>
1061 <CloudDownload size={16} color={online ? c.fg : c.faint} strokeWidth={2.2} />
1062 </View>
1063 <View style={styles.flex}>
1064 <Text style={[styles.menuTitle, { color: online ? c.fg : c.muted }]}>Save all for offline</Text>
1065 <Text style={[styles.menuSub, { color: c.muted }]}>
1066 {!unsaved.length ? 'Everything is on this phone' : online ? `${plural(unsaved.length, 'inspection')} · ${pendingMb} MB` : 'Needs a connection'}
1067 </Text>
1068 </View>
1069 </Pressable>
1070 <View style={[styles.menuLine, { backgroundColor: c.line }]} />
1071 <View style={styles.menuRow}>
1072 <View style={[styles.menuIcon, { backgroundColor: c.chip }]}>
1073 <HardDrive size={16} color={c.fg} strokeWidth={2.2} />
1074 </View>
1075 <View style={styles.flex}>
1076 <Text style={[styles.menuTitle, { color: c.fg }]}>Kept by {APP_NAME}</Text>
1077 <Text style={[styles.menuSub, styles.tabular, { color: c.muted }]}>
1078 {plural(savedCount, 'inspection')} · {savedMb} MB on this phone
1079 </Text>
1080 </View>
1081 </View>
1082 </Animated.View>
1083 </>
1084 );
1085}
1086
1087// ─── Pull to refresh ────────────────────────────────────────────────────────
1088
1089type PullMode = 'idle' | 'pulling' | 'refreshing' | 'blocked' | 'done';
1090
1091function PullIndicator({ pull, shake, mode, armed, c }: { pull: SharedValue<number>; shake: SharedValue<number>; mode: PullMode; armed: boolean; c: Palette }) {
1092 const style = useAnimatedStyle(() => ({
1093 opacity: Math.max(0, Math.min(1, (pull.value - 12) / 26)),
1094 transform: [{ translateX: shake.value }, { translateY: Math.min(0, pull.value - PULL_HOLD) * 0.4 }],
1095 }));
1096 const blocked = mode === 'blocked';
1097 const text = blocked ? "Can't refresh while offline" : mode === 'refreshing' ? 'Refreshing' : mode === 'done' ? 'Up to date' : armed ? 'Release to refresh' : 'Pull to refresh';
1098 return (
1099 <Animated.View aria-hidden={mode === 'idle'} role={blocked ? 'alert' : undefined} style={[styles.pull, { backgroundColor: c.card, borderColor: blocked ? c.bannerOffLine : c.line }, style]}>
1100 {blocked ? (
1101 <CloudOff size={15} color={c.accentText} strokeWidth={2.4} />
1102 ) : mode === 'refreshing' ? (
1103 <Spinner color={c.muted} size={14} />
1104 ) : mode === 'done' ? (
1105 <Check size={15} color={c.good} strokeWidth={3} />
1106 ) : (
1107 <View style={{ transform: [{ rotate: armed ? '180deg' : '0deg' }] }}>
1108 <ArrowDown size={15} color={c.muted} strokeWidth={2.4} />
1109 </View>
1110 )}
1111 <Text style={[styles.pullText, { color: blocked ? c.fg : c.muted }]}>{text}</Text>
1112 </Animated.View>
1113 );
1114}
1115
1116// ─── Screen ─────────────────────────────────────────────────────────────────
1117
1118export default function OfflineModeScreen() {
1119 const c = usePalette();
1120 const insets = useSafeAreaInsets();
1121 const { width, height } = useWindowDimensions();
1122 const column = Math.min(width, COLUMN);
1123
1124 const [items, setItems] = useState(ITEMS);
1125 const [queue, setQueue] = useState(QUEUE);
1126 const [online, setOnline] = useState(false);
1127 const [sync, setSync] = useState<'idle' | 'running' | 'saved'>('idle');
1128 const [conflictOpen, setConflictOpen] = useState(true);
1129 const [savedAgo, setSavedAgo] = useState(LAST_SAVED);
1130 const [trayOpen, setTrayOpen] = useState(false);
1131 const [menuOpen, setMenuOpen] = useState(false);
1132 const [loading, setLoading] = useState<Record<string, boolean>>({});
1133 const [editing, setEditing] = useState<string | null>(null);
1134 const [newTitle, setNewTitle] = useState('');
1135 const [toast, setToast] = useState<{ id: number; text: string } | null>(null);
1136 const [composerH, setComposerH] = useState(72);
1137 const [pullMode, setPullModeState] = useState<PullMode>('idle');
1138 const [armed, setArmed] = useState(false);
1139 const booted = useRef(false);
1140 const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
1141
1142 useEffect(() => {
1143 booted.current = true;
1144 const list = timers.current;
1145 return () => list.forEach(clearTimeout);
1146 }, []);
1147 const later = (fn: () => void, ms: number) => {
1148 timers.current.push(setTimeout(fn, ms));
1149 };
1150
1151 // ── Toasts
1152 useEffect(() => {
1153 if (!toast) return;
1154 const t = setTimeout(() => setToast(null), 2400);
1155 return () => clearTimeout(t);
1156 }, [toast]);
1157 const say = (text: string) => setToast({ id: Date.now(), text });
1158
1159 // ── The queue: edits made offline wait here; opposite edits cancel out, and a new item carries its own state.
1160 const record = (itemId: string, kind: ChangeKind, from?: string, to?: string) => {
1161 setQueue((q) => {
1162 const live = q.filter((ch) => ch.itemId === itemId && ch.status !== 'saved');
1163 if (kind !== 'add' && live.some((ch) => ch.kind === 'add')) return q;
1164 if (kind === 'done' || kind === 'undone') {
1165 const prev = live.find((ch) => ch.kind === 'done' || ch.kind === 'undone');
1166 if (prev) return q.filter((ch) => ch !== prev);
1167 }
1168 if (kind === 'rename') {
1169 const prev = live.find((ch) => ch.kind === 'rename');
1170 if (prev) return prev.from === to ? q.filter((ch) => ch !== prev) : q.map((ch) => (ch === prev ? { ...ch, at: 'Just now' } : ch));
1171 }
1172 return [...q, { id: `c${Date.now()}`, itemId, kind, from, at: 'Just now', status: 'waiting' }];
1173 });
1174 };
1175
1176 const undo = (ch: Change) => {
1177 setItems((list) => {
1178 if (ch.kind === 'add') return list.filter((i) => i.id !== ch.itemId);
1179 return list.map((i) => (i.id !== ch.itemId ? i : ch.kind === 'rename' ? { ...i, title: ch.from ?? i.title } : { ...i, done: ch.kind === 'undone' }));
1180 });
1181 setQueue((q) => q.filter((x) => x.id !== ch.id));
1182 };
1183
1184 const setStatus = (id: string, status: ChangeStatus, note?: string) => setQueue((q) => q.map((ch) => (ch.id === id ? { ...ch, status, note: note ?? ch.note } : ch)));
1185
1186 const resolve = (ch: Change, mine: boolean) => {
1187 if (!mine) setItems((list) => list.map((i) => (i.id === ch.itemId ? { ...i, title: CONFLICT.title } : i)));
1188 setConflictOpen(false);
1189 setStatus(ch.id, 'saved', mine ? 'Kept your name' : `Took ${first(CONFLICT.who)}'s name`);
1190 };
1191
1192 // ── Sync: one change at a time, oldest first. The rename meets the teammate's edit and waits for a decision.
1193 useEffect(() => {
1194 if (!online || sync !== 'running') return;
1195 const next = queue.find((ch) => ch.status !== 'saved');
1196 if (!next) {
1197 const t = setTimeout(() => setSync('saved'), 450);
1198 return () => clearTimeout(t);
1199 }
1200 if (next.status === 'conflict') return;
1201 if (next.status === 'waiting') {
1202 const t = setTimeout(() => setStatus(next.id, 'sending'), 260);
1203 return () => clearTimeout(t);
1204 }
1205 const clash = conflictOpen && next.kind === 'rename' && next.itemId === CONFLICT.itemId;
1206 const t = setTimeout(() => setStatus(next.id, clash ? 'conflict' : 'saved'), clash ? 820 : 720);
1207 return () => clearTimeout(t);
1208 }, [online, sync, queue, conflictOpen]);
1209
1210 useEffect(() => {
1211 if (sync !== 'saved') return;
1212 const a = setTimeout(() => setTrayOpen(false), 1000);
1213 const b = setTimeout(() => {
1214 setSync('idle');
1215 setQueue((q) => q.filter((ch) => ch.status !== 'saved'));
1216 setSavedAgo('just now');
1217 // Anything the teammate changed comes down with the sync.
1218 if (conflictOpen) {
1219 setItems((list) => list.map((i) => (i.id === CONFLICT.itemId ? { ...i, title: CONFLICT.title } : i)));
1220 setConflictOpen(false);
1221 }
1222 }, 2000);
1223 return () => {
1224 clearTimeout(a);
1225 clearTimeout(b);
1226 };
1227 }, [sync, conflictOpen]);
1228
1229 const goOnline = () => {
1230 setOnline(true);
1231 if (queue.length) {
1232 setSync('running');
1233 setTrayOpen(true);
1234 } else setSync('saved');
1235 };
1236 const goOffline = () => {
1237 setOnline(false);
1238 setSync('idle');
1239 setQueue((q) => q.filter((ch) => ch.status !== 'saved').map((ch) => ({ ...ch, status: 'waiting' as const })));
1240 setLoading({});
1241 setTrayOpen(false);
1242 };
1243 const toggleNet = () => {
1244 if (online) goOffline();
1245 else goOnline();
1246 later(() => setMenuOpen(false), 380);
1247 };
1248
1249 // ── Item actions
1250 const toggleDone = (item: Item) => {
1251 setItems((list) => list.map((i) => (i.id === item.id ? { ...i, done: !i.done } : i)));
1252 if (!online) record(item.id, item.done ? 'undone' : 'done');
1253 };
1254 const endRename = (item: Item, next: string) => {
1255 setEditing(null);
1256 const t = next.trim();
1257 if (!t || t === item.title) return;
1258 setItems((list) => list.map((i) => (i.id === item.id ? { ...i, title: t } : i)));
1259 if (!online) record(item.id, 'rename', item.title, t);
1260 };
1261 const toggleSave = (item: Item) => {
1262 if (loading[item.id]) {
1263 setLoading((l) => ({ ...l, [item.id]: false }));
1264 return;
1265 }
1266 if (!online) {
1267 say("Downloads stay on this phone while you're offline.");
1268 return;
1269 }
1270 if (item.saved) {
1271 setItems((list) => list.map((i) => (i.id === item.id ? { ...i, saved: false } : i)));
1272 say(item.mb ? `Removed from this phone · ${item.mb} MB freed` : 'Removed from this phone');
1273 } else setLoading((l) => ({ ...l, [item.id]: true }));
1274 };
1275 const finishSave = (id: string) => {
1276 setLoading((l) => ({ ...l, [id]: false }));
1277 setItems((list) => list.map((i) => (i.id === id ? { ...i, saved: true } : i)));
1278 };
1279 const unsaved = items.filter((i) => !i.saved && i.mb > 0);
1280 const saveAll = () => {
1281 if (!online) {
1282 say('Saving for offline needs a connection.');
1283 return;
1284 }
1285 setLoading((l) => ({ ...l, ...Object.fromEntries(unsaved.map((i) => [i.id, true])) }));
1286 later(() => setMenuOpen(false), 240);
1287 };
1288 const add = () => {
1289 const t = newTitle.trim();
1290 if (!t) return;
1291 const id = `n${Date.now()}`;
1292 setItems((list) => [{ id, title: t, place: 'Level 3', photos: 0, mb: 0, saved: true, done: false, section: 'upper' }, ...list]);
1293 if (!online) record(id, 'add');
1294 setNewTitle('');
1295 };
1296
1297 // ── Pull to refresh: a PanResponder takes over a downward drag when the list is at the top.
1298 const scrollY = useRef(0);
1299 const pull = useSharedValue(0);
1300 const pullShake = useSharedValue(0);
1301 const pullModeRef = useRef<PullMode>('idle');
1302 const armedRef = useRef(false);
1303 const setPullMode = (m: PullMode) => {
1304 pullModeRef.current = m;
1305 setPullModeState(m);
1306 };
1307 const release = (d: number) => {
1308 setArmed(false);
1309 armedRef.current = false;
1310 if (d < PULL_AT) {
1311 pull.value = withSpring(0, SPRING);
1312 setPullMode('idle');
1313 return;
1314 }
1315 pull.value = withTiming(PULL_HOLD, { duration: 220, easing: Easing.out(Easing.cubic) });
1316 if (!online) {
1317 setPullMode('blocked');
1318 pullShake.value = withDelay(
1319 150,
1320 withSequence(withTiming(-8, { duration: 55 }), withTiming(8, { duration: 70 }), withTiming(-6, { duration: 70 }), withTiming(4, { duration: 70 }), withTiming(0, { duration: 60 }))
1321 );
1322 later(() => (pull.value = withTiming(0, { duration: 320, easing: Easing.inOut(Easing.cubic) })), 1800);
1323 later(() => setPullMode('idle'), 2150);
1324 } else {
1325 setPullMode('refreshing');
1326 later(() => {
1327 setPullMode('done');
1328 setSavedAgo('just now');
1329 }, 1100);
1330 later(() => (pull.value = withTiming(0, { duration: 320, easing: Easing.inOut(Easing.cubic) })), 1800);
1331 later(() => setPullMode('idle'), 2150);
1332 }
1333 };
1334 const releaseRef = useRef(release);
1335 useEffect(() => {
1336 releaseRef.current = release;
1337 });
1338 const pan = useMemo(
1339 () =>
1340 PanResponder.create({
1341 onMoveShouldSetPanResponderCapture: (_e, g) => pullModeRef.current === 'idle' && scrollY.current <= 1 && g.dy > 8 && g.dy > Math.abs(g.dx) * 1.4,
1342 onPanResponderGrant: () => {
1343 pullModeRef.current = 'pulling';
1344 setPullModeState('pulling');
1345 },
1346 onPanResponderMove: (_e, g) => {
1347 const d = rubber(Math.max(0, g.dy));
1348 pull.value = d;
1349 const on = d >= PULL_AT;
1350 if (on !== armedRef.current) {
1351 armedRef.current = on;
1352 setArmed(on);
1353 }
1354 },
1355 onPanResponderRelease: (_e, g) => releaseRef.current(rubber(Math.max(0, g.dy))),
1356 onPanResponderTerminate: () => releaseRef.current(0),
1357 onPanResponderTerminationRequest: () => false,
1358 }),
1359 [pull]
1360 );
1361 const listShift = useAnimatedStyle(() => ({ transform: [{ translateY: pull.value }] }));
1362
1363 // ── Derived state
1364 const offline = !online;
1365 const syncedN = queue.filter((ch) => ch.status === 'saved').length;
1366 const phase: Phase = offline ? 'offline' : sync === 'running' ? (queue.some((ch) => ch.status === 'conflict') ? 'conflict' : 'syncing') : sync === 'saved' ? 'saved' : 'hidden';
1367 const changeFor = useMemo(() => {
1368 const m: Record<string, Change> = {};
1369 for (const ch of queue) {
1370 const cur = m[ch.itemId];
1371 if (!cur || RANK[ch.status] > RANK[cur.status]) m[ch.itemId] = ch;
1372 }
1373 return m;
1374 }, [queue]);
1375 const doneN = items.filter((i) => i.done).length;
1376 const savedItems = items.filter((i) => i.saved);
1377 const savedMb = savedItems.reduce((s, i) => s + i.mb, 0);
1378 let order = 0;
1379
1380 return (
1381 <View style={[styles.screen, { backgroundColor: c.bg }]}>
1382 <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.column}>
1383 {/* Header: opaque, under the status bar */}
1384 <Animated.View entering={FadeIn.duration(320)} style={[styles.header, { paddingTop: insets.top + 6, backgroundColor: c.bg }]}>
1385 <View style={styles.headerTop}>
1386 <Pressable role="button" aria-label={`Project: ${PROJECT}. Switch project`} style={({ pressed }) => [styles.project, { backgroundColor: c.chip, opacity: pressed ? 0.7 : 1 }]}>
1387 <MapPin size={13} color={c.accentText} strokeWidth={2.5} />
1388 <Text numberOfLines={1} style={[styles.projectLabel, { color: c.fg }]}>
1389 {PROJECT}
1390 </Text>
1391 <ChevronDown size={14} color={c.muted} strokeWidth={2.4} />
1392 </Pressable>
1393 <View style={styles.headerActions}>
1394 <Tap label="More options" expanded={menuOpen} onPress={() => setMenuOpen((o) => !o)} style={[styles.more, { backgroundColor: c.chip }]}>
1395 <Ellipsis size={19} color={c.fg} strokeWidth={2.4} />
1396 </Tap>
1397 </View>
1398 </View>
1399 <View style={styles.titleRow}>
1400 <Text role="heading" style={[styles.title, { color: c.fg }]}>
1401 Inspections
1402 </Text>
1403 {phase === 'hidden' ? (
1404 <Animated.View entering={FadeIn.duration(260)} exiting={FadeOut.duration(160)} style={[styles.synced, { backgroundColor: c.chip }]}>
1405 <View style={[styles.syncedDot, { backgroundColor: c.goodFill }]} />
1406 <Text style={[styles.syncedLabel, { color: c.muted }]}>Synced {savedAgo}</Text>
1407 </Animated.View>
1408 ) : null}
1409 </View>
1410 <Text style={[styles.subtitle, styles.tabular, { color: c.muted }]}>
1411 {WALK_DATE} walkthrough · {doneN} of {items.length} checked
1412 </Text>
1413 </Animated.View>
1414
1415 <Banner phase={phase} savedAgo={savedAgo} total={queue.length} done={syncedN} c={c} />
1416
1417 {/* The list, with the pull indicator behind it */}
1418 <View style={styles.listArea}>
1419 <PullIndicator pull={pull} shake={pullShake} mode={pullMode} armed={armed} c={c} />
1420 <Animated.View style={[styles.flex, NO_SELECT, listShift]} {...pan.panHandlers}>
1421 <ScrollView
1422 onScroll={(e) => {
1423 scrollY.current = e.nativeEvent.contentOffset.y;
1424 }}
1425 scrollEventThrottle={16}
1426 bounces={false}
1427 keyboardShouldPersistTaps="handled"
1428 showsVerticalScrollIndicator={false}
1429 contentContainerStyle={[styles.listContent, { paddingBottom: PILL_H + 28 }]}
1430 >
1431 {SECTIONS.map((s, si) => {
1432 const rows = items.filter((i) => i.section === s.id);
1433 if (!rows.length) return null;
1434 const kept = rows.filter((i) => i.saved).length;
1435 return (
1436 <Animated.View key={s.id} entering={FadeInDown.delay(booted.current ? 0 : 200 + si * 160).duration(360)} layout={MOVE} style={styles.section}>
1437 <View style={styles.sectionHead}>
1438 <Text style={[styles.sectionTitle, { color: c.fg }]}>{s.title}</Text>
1439 <View style={styles.sectionMeta}>
1440 <ArrowDownToLine size={12} color={c.muted} strokeWidth={2.5} />
1441 <Text style={[styles.sectionMetaText, styles.tabular, { color: c.muted }]}>
1442 {kept} of {rows.length} on this phone
1443 </Text>
1444 </View>
1445 </View>
1446 <View style={[styles.card, { backgroundColor: c.card, borderColor: c.line }]}>
1447 {rows.map((item, i) => {
1448 const n = order++;
1449 return (
1450 <Row
1451 key={item.id}
1452 item={item}
1453 delay={booted.current ? 0 : 260 + n * 45}
1454 offline={offline}
1455 change={changeFor[item.id]}
1456 loading={!!loading[item.id]}
1457 editing={editing === item.id}
1458 last={i === rows.length - 1}
1459 onToggle={() => toggleDone(item)}
1460 onSave={() => toggleSave(item)}
1461 onSaveDone={() => finishSave(item.id)}
1462 onRenameStart={() => setEditing(item.id)}
1463 onRenameEnd={(t) => endRename(item, t)}
1464 onBlocked={say}
1465 c={c}
1466 />
1467 );
1468 })}
1469 </View>
1470 </Animated.View>
1471 );
1472 })}
1473 </ScrollView>
1474 </Animated.View>
1475 {/* The open sync tray dims the list (not the banner, which tells the sync story); tapping outside closes it */}
1476 {trayOpen && queue.length ? (
1477 <Animated.View entering={FadeIn.duration(220)} exiting={FadeOut.duration(200)} style={[StyleSheet.absoluteFill, styles.trayScrim, { backgroundColor: c.scrim }]}>
1478 <Pressable aria-label="Close the sync list" onPress={() => setTrayOpen(false)} style={styles.flex} />
1479 </Animated.View>
1480 ) : null}
1481 {toast ? (
1482 <Animated.View key={toast.id} entering={FadeInUp.duration(220)} exiting={FadeOutUp.duration(180)} role="alert" style={[styles.toast, { backgroundColor: c.toast }]}>
1483 <CloudOff size={15} color={c.toastFg} strokeWidth={2.3} />
1484 <Text style={[styles.toastText, { color: c.toastFg }]}>{toast.text}</Text>
1485 </Animated.View>
1486 ) : null}
1487 </View>
1488
1489 {/* Content fades out under the floating queue pill */}
1490 <LinearGradient colors={[c.bgClear, c.bg]} style={[styles.fade, { bottom: composerH }]} />
1491
1492 {/* Quick add: works offline, the new item joins the queue */}
1493 <View
1494 onLayout={(e: LayoutChangeEvent) => setComposerH(e.nativeEvent.layout.height)}
1495 style={[styles.composer, { paddingBottom: insets.bottom + 10, backgroundColor: c.bg, borderTopColor: c.line }]}
1496 >
1497 <View style={[styles.field, { backgroundColor: c.card, borderColor: c.line }]}>
1498 <Plus size={18} color={c.muted} strokeWidth={2.3} />
1499 <TextInput
1500 value={newTitle}
1501 onChangeText={setNewTitle}
1502 onSubmitEditing={add}
1503 returnKeyType="done"
1504 maxLength={60}
1505 placeholder={online ? 'Add a check item' : 'Add a check, saved on this phone'}
1506 placeholderTextColor={c.muted}
1507 selectionColor={ACCENT}
1508 aria-label="New check item"
1509 style={[styles.fieldInput, { color: c.fg }, NO_OUTLINE]}
1510 />
1511 <Pressable
1512 role="button"
1513 aria-label="Add check item"
1514 aria-disabled={!newTitle.trim()}
1515 onPress={add}
1516 style={({ pressed }) => [styles.addButton, { backgroundColor: newTitle.trim() ? ACCENT : c.chip, opacity: pressed ? 0.8 : 1 }]}
1517 >
1518 <Text style={[styles.addLabel, { color: newTitle.trim() ? ON_ACCENT : c.faint }]}>Add</Text>
1519 </Pressable>
1520 </View>
1521 </View>
1522
1523 <View style={[styles.traySlot, { bottom: composerH + 12 }]}>
1524 <SyncTray
1525 queue={queue}
1526 items={items}
1527 online={online}
1528 phase={phase}
1529 open={trayOpen && queue.length > 0}
1530 width={column - 24}
1531 maxList={Math.min(400, height * 0.5)}
1532 onToggle={() => setTrayOpen((o) => !o)}
1533 onUndo={undo}
1534 onResolve={resolve}
1535 c={c}
1536 />
1537 </View>
1538
1539 {menuOpen ? (
1540 <Menu
1541 top={insets.top + 52}
1542 online={online}
1543 unsaved={unsaved}
1544 savedCount={savedItems.length}
1545 savedMb={savedMb}
1546 onNet={toggleNet}
1547 onSaveAll={saveAll}
1548 onClose={() => setMenuOpen(false)}
1549 c={c}
1550 />
1551 ) : null}
1552 </KeyboardAvoidingView>
1553 </View>
1554 );
1555}
1556
1557// ─── Styles ─────────────────────────────────────────────────────────────────
1558
1559const styles = StyleSheet.create({
1560 screen: { flex: 1, overflow: 'hidden' },
1561 column: { flex: 1, width: '100%', maxWidth: COLUMN, alignSelf: 'center' },
1562 flex: { flex: 1 },
1563 center: { alignItems: 'center', justifyContent: 'center' },
1564 tabular: { fontVariant: ['tabular-nums'] },
1565 noShrink: { flexShrink: 0 },
1566 spinner: { borderWidth: 2 },
1567
1568 // Header
1569 header: { paddingHorizontal: 20, paddingBottom: 12, zIndex: 2 },
1570 headerTop: { height: 44, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 10 },
1571 project: { height: 32, borderRadius: 16, paddingLeft: 10, paddingRight: 9, flexDirection: 'row', alignItems: 'center', gap: 6, flexShrink: 1 },
1572 projectLabel: { fontSize: 13.5, fontWeight: '600', flexShrink: 1 },
1573 headerActions: { flexDirection: 'row', alignItems: 'center', gap: 8 },
1574 synced: { height: 28, borderRadius: 14, paddingHorizontal: 10, flexDirection: 'row', alignItems: 'center', gap: 6 },
1575 syncedDot: { width: 7, height: 7, borderRadius: 4 },
1576 syncedLabel: { fontSize: 12.5, fontWeight: '600' },
1577 more: { width: 36, height: 36, borderRadius: 18, alignItems: 'center', justifyContent: 'center' },
1578 titleRow: { marginTop: 8, flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', gap: 10 },
1579 title: { fontSize: 31, lineHeight: 36, fontWeight: '800', letterSpacing: -0.9 },
1580 subtitle: { marginTop: 2, fontSize: 14, fontWeight: '500' },
1581
1582 // Banner
1583 bannerWrap: { overflow: 'hidden', zIndex: 1 },
1584 bannerMeasure: { position: 'absolute', left: 0, right: 0, top: 0, paddingHorizontal: 16, paddingBottom: 10 },
1585 banner: { flexDirection: 'row', alignItems: 'center', gap: 12, borderRadius: 18, borderWidth: 1, paddingLeft: 12, paddingRight: 10, paddingVertical: 12, overflow: 'hidden' },
1586 tile: { width: 40, height: 40, borderRadius: 13, alignItems: 'center', justifyContent: 'center' },
1587 bannerRow: { flexDirection: 'row', alignItems: 'center', gap: 10 },
1588 bannerText: { flex: 1, minWidth: 0 },
1589 bannerTitle: { fontSize: 15, lineHeight: 20, fontWeight: '700', letterSpacing: -0.2 },
1590 bannerSub: { marginTop: 1, fontSize: 13, lineHeight: 18 },
1591 retry: { width: 128, height: 36, borderRadius: 18, borderWidth: 1, flexDirection: 'row', alignItems: 'center', paddingLeft: 8, gap: 6 },
1592 retryRing: { width: 21, height: 21, alignItems: 'center', justifyContent: 'center' },
1593 retryRow: { flexDirection: 'row', alignItems: 'center', gap: 3 },
1594 retryDigits: { minWidth: 24, height: 18, overflow: 'hidden', justifyContent: 'center' },
1595 retryLabel: { fontSize: 13.5, lineHeight: 18, fontWeight: '700' },
1596 bannerTrack: { position: 'absolute', left: 0, right: 0, bottom: 0, height: 3 },
1597 bannerBar: { height: 3, borderTopRightRadius: 2, borderBottomRightRadius: 2 },
1598
1599 // List
1600 listArea: { flex: 1 },
1601 listContent: { paddingHorizontal: 16, paddingTop: 2 },
1602 section: { marginBottom: 18 },
1603 sectionHead: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: 4, marginBottom: 8 },
1604 sectionTitle: { fontSize: 15, fontWeight: '700', letterSpacing: -0.2 },
1605 sectionMeta: { flexDirection: 'row', alignItems: 'center', gap: 4 },
1606 sectionMetaText: { fontSize: 12.5, fontWeight: '500' },
1607 card: { borderRadius: 20, borderWidth: StyleSheet.hairlineWidth, overflow: 'hidden' },
1608 row: { flexDirection: 'row', alignItems: 'center', paddingLeft: 12, paddingRight: 8, paddingVertical: 11 },
1609 rowMain: { flex: 1, flexDirection: 'row', alignItems: 'center', gap: 12, minWidth: 0 },
1610 rowText: { flex: 1, minWidth: 0 },
1611 rowTitle: { fontSize: 15.5, lineHeight: 20, fontWeight: '600', letterSpacing: -0.2 },
1612 rowInput: { padding: 0, margin: 0, borderBottomWidth: 1.5, paddingBottom: 1 },
1613 rowMeta: { marginTop: 2, fontSize: 13, lineHeight: 17 },
1614 rowLine: { height: StyleSheet.hairlineWidth, marginLeft: 104 },
1615 thumb: { width: 46, height: 46, borderRadius: 12, overflow: 'hidden' },
1616 thumbImage: { width: '100%', height: '100%' },
1617 status: { marginTop: 5, flexDirection: 'row', alignItems: 'center', gap: 5 },
1618 statusText: { fontSize: 12.5, fontWeight: '600', flexShrink: 1 },
1619
1620 // Done box and save toggle
1621 checkHit: { width: 34, height: 44, justifyContent: 'center' },
1622 check: { width: 22, height: 22, borderRadius: 7, borderWidth: 2 },
1623 checkFill: { position: 'absolute', left: -2, top: -2, right: -2, bottom: -2, borderRadius: 7, backgroundColor: ACCENT, alignItems: 'center', justifyContent: 'center' },
1624 saveHit: { width: 42, height: 44, alignItems: 'center', justifyContent: 'center' },
1625 saveDot: { width: 30, height: 30, borderRadius: 15, borderWidth: 1.5, alignItems: 'center', justifyContent: 'center' },
1626 ring: { width: 30, height: 30, alignItems: 'center', justifyContent: 'center' },
1627 ringRotate: { position: 'absolute', transform: [{ rotate: '-90deg' }] },
1628 ringStop: { width: 8, height: 8, borderRadius: 2 },
1629
1630 // Pull to refresh and toast
1631 pull: { position: 'absolute', top: 8, alignSelf: 'center', height: 34, borderRadius: 17, borderWidth: 1, paddingHorizontal: 14, flexDirection: 'row', alignItems: 'center', gap: 7 },
1632 pullText: { fontSize: 13.5, fontWeight: '600' },
1633 toast: { position: 'absolute', top: 6, alignSelf: 'center', maxWidth: '92%', minHeight: 38, borderRadius: 19, paddingHorizontal: 14, paddingVertical: 9, flexDirection: 'row', alignItems: 'center', gap: 8, pointerEvents: 'none' },
1634 toastText: { fontSize: 13.5, lineHeight: 18, fontWeight: '600', flexShrink: 1 },
1635
1636 // Composer
1637 fade: { position: 'absolute', left: 0, right: 0, height: PILL_H + 34, pointerEvents: 'none' },
1638 composer: { paddingHorizontal: 16, paddingTop: 10, borderTopWidth: StyleSheet.hairlineWidth },
1639 field: { height: 50, borderRadius: 25, borderWidth: StyleSheet.hairlineWidth, flexDirection: 'row', alignItems: 'center', paddingLeft: 16, paddingRight: 6, gap: 10 },
1640 fieldInput: { flex: 1, height: '100%', fontSize: 15.5, minWidth: 0 },
1641 addButton: { height: 38, paddingHorizontal: 16, borderRadius: 19, alignItems: 'center', justifyContent: 'center' },
1642 addLabel: { fontSize: 14.5, fontWeight: '700' },
1643
1644 // Sync tray
1645 trayScrim: { zIndex: 10 },
1646 traySlot: { position: 'absolute', left: 0, right: 0, alignItems: 'center', pointerEvents: 'box-none', zIndex: 11 },
1647 tray: { borderRadius: 23, overflow: 'hidden' },
1648 trayHead: { height: PILL_H, flexDirection: 'row', alignItems: 'center', gap: 9, paddingLeft: 16, paddingRight: 14 },
1649 trayLabel: { flex: 1, fontSize: 14.5, fontWeight: '700', letterSpacing: -0.1 },
1650 trayScroll: { flexGrow: 0, flexShrink: 0 },
1651 trayList: { paddingHorizontal: 14, paddingTop: 12, paddingBottom: 8 },
1652 trayIntro: { fontSize: 12.5, lineHeight: 17, marginBottom: 4 },
1653 change: { paddingVertical: 9 },
1654 changeTop: { flexDirection: 'row', alignItems: 'center', gap: 11 },
1655 changeIcon: { width: 30, height: 30, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },
1656 changeTitle: { fontSize: 14.5, fontWeight: '600', letterSpacing: -0.1 },
1657 changeSubRow: { marginTop: 2, flexDirection: 'row', alignItems: 'center', gap: 4 },
1658 changeSub: { fontSize: 12.5, flexShrink: 1 },
1659 changeEnd: { minWidth: 30, alignItems: 'flex-end' },
1660 undo: { height: 30, borderRadius: 15, paddingHorizontal: 11, flexDirection: 'row', alignItems: 'center', gap: 5 },
1661 undoLabel: { fontSize: 13, fontWeight: '700' },
1662 doneDot: { width: 22, height: 22, borderRadius: 11, alignItems: 'center', justifyContent: 'center' },
1663 conflict: { marginTop: 10, borderRadius: 14, borderWidth: 1, padding: 12 },
1664 conflictHead: { flexDirection: 'row', alignItems: 'center', gap: 6 },
1665 conflictTitle: { fontSize: 13.5, fontWeight: '700' },
1666 versions: { marginTop: 9, gap: 6 },
1667 version: { borderRadius: 10, borderWidth: StyleSheet.hairlineWidth, paddingHorizontal: 10, paddingVertical: 7 },
1668 versionLabel: { fontSize: 11.5, fontWeight: '600' },
1669 versionValue: { marginTop: 1, fontSize: 14, fontWeight: '600' },
1670 conflictActions: { marginTop: 10, flexDirection: 'row', gap: 8 },
1671 keep: { flex: 1, height: 38, borderRadius: 19, borderWidth: 1, alignItems: 'center', justifyContent: 'center' },
1672 keepMine: { backgroundColor: ACCENT, borderColor: ACCENT },
1673 keepLabel: { fontSize: 14, fontWeight: '700' },
1674
1675 // Menu and switch
1676 menuScrim: { position: 'absolute', left: -1000, right: -1000, top: -1000, bottom: -1000, zIndex: 20 },
1677 menu: { position: 'absolute', zIndex: 21, right: 16, width: 292, borderRadius: 18, paddingVertical: 6, overflow: 'hidden' },
1678 menuRow: { flexDirection: 'row', alignItems: 'center', gap: 12, paddingHorizontal: 14, paddingVertical: 10 },
1679 menuIcon: { width: 32, height: 32, borderRadius: 10, alignItems: 'center', justifyContent: 'center' },
1680 menuTitle: { fontSize: 14.5, fontWeight: '600' },
1681 menuSub: { marginTop: 1, fontSize: 12.5 },
1682 menuLine: { height: StyleSheet.hairlineWidth, marginLeft: 58 },
1683 switch: { width: 44, height: 26, borderRadius: 13, padding: 2, justifyContent: 'center' },
1684 knob: { width: 22, height: 22, borderRadius: 11, backgroundColor: '#FFFFFF', boxShadow: '0px 1px 3px rgba(0, 0, 0, 0.25)' },
1685});

More screens like this.

All Feedback & States