Repository navigation
Expand file tree
/
Copy pathApp.tsx
More file actions
6418 lines (6080 loc) · 252 KB
/
Copy pathApp.tsx
File metadata and controls
6418 lines (6080 loc) · 252 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useEffect, useMemo, useRef } from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
ScrollView,
SafeAreaView,
StatusBar,
Platform,
Alert,
Keyboard,
KeyboardAvoidingView,
Animated,
Easing,
Modal,
AppState,
Dimensions,
BackHandler,
Linking,
PanResponder
} from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Calendar } from 'react-native-calendars';
import Constants from 'expo-constants';
import * as Updates from 'expo-updates';
import { Menu, Settings as SettingsIcon, LogOut, X, Heart, Check, Square, CheckSquare, Home, FileText, Wallet, Activity, ListChecks, MessageSquareWarning, ChevronLeft, Plus, Send, BookOpen, Sparkles, ScrollText, CalendarHeart, Flame, Footprints, Trophy, ArrowUpRight, ArrowDownLeft, BellRing, BatteryWarning, Pencil } from 'lucide-react-native';
import Svg, { Defs, LinearGradient as SvgLinearGradient, RadialGradient, Rect, Stop } from 'react-native-svg';
import * as Notifications from 'expo-notifications';
import { TodoRecurrence, AppUpdate, Milestone, MilestoneRecurrence } from './src/types';
import { useAuth } from './src/hooks/useAuth';
import { useRealtimeNotes } from './src/hooks/useRealtimeNotes';
import { useMood } from './src/hooks/useMood';
import { useTodos } from './src/hooks/useTodos';
import { usePeriods } from './src/hooks/usePeriods';
import { useComplaints } from './src/hooks/useComplaints';
import { useMilestones } from './src/hooks/useMilestones';
import { useSteps } from './src/hooks/useSteps';
import { Skeleton } from './src/components/common/Skeleton';
import { HubSkeleton } from './src/components/common/HubSkeleton';
import { Avatar } from './src/components/common/Avatar';
import { GlassBacking, GlassCard } from './src/components/common/GlassCard';
import { StepGraph } from './src/components/common/StepGraph';
import { configureNotificationsAsync, PRIORITY_CHANNEL } from './src/services/notification';
import { cancelScheduledNotificationsByPrefix, scheduleLocalNotification } from './src/services/notification';
import { supabase } from './src/services/supabase';
import { IS_DEMO } from './src/demo/config';
import { applyPendingUpdate, checkAndApplyUpdate, fetchAppUpdates, fetchUpdateInBackground, getLastSeenUpdateAt, markUpdatesSeen, unseenUpdates } from './src/services/updates';
import { claimNotification, getOrCreateBaseline, pruneNotifiedMarkers } from './src/services/notifyOnce';
import { withLock } from './src/utils/asyncLock';
import { parseLocalDate } from './src/utils/dateUtils';
import { directionFor, useTransactions } from './src/hooks/useTransactions';
import { pickProfilePhoto } from './src/services/profilePhoto';
import { openSettings as openListenerSettings, requestIgnoreBatteryOptimizations } from './modules/notification-listener';
import {
daysUntilNext,
elapsedAt,
formatElapsed,
nextOccurrence,
occursOn,
} from './src/utils/milestoneMath';
import { BucketListItem, MedicalRecord } from './src/types';
import { getWordOfDay } from './src/constants/vocabulary';
import { ChatMessage, chatWithAI, generateIdeas } from './src/services/groq';
import { useFonts } from 'expo-font';
import { Fraunces_600SemiBold } from '@expo-google-fonts/fraunces/600SemiBold';
import { Fraunces_700Bold } from '@expo-google-fonts/fraunces/700Bold';
import { Manrope_400Regular } from '@expo-google-fonts/manrope/400Regular';
import { Manrope_500Medium } from '@expo-google-fonts/manrope/500Medium';
import { Manrope_600SemiBold } from '@expo-google-fonts/manrope/600SemiBold';
import { Manrope_700Bold } from '@expo-google-fonts/manrope/700Bold';
import { Manrope_800ExtraBold } from '@expo-google-fonts/manrope/800ExtraBold';
import { alpha, FONTS, PALETTE, THEME } from './src/constants/theme';
import { SPRING, projectMomentum } from './src/constants/motion';
import { useReducedMotion } from './src/hooks/useReducedMotion';
// Quick emoji reactions available on each shared note.
const NOTE_REACTIONS = ['❤️', '😂', '👍', '🥺', '🔥'] as const;
/**
* Idea starters. A blank prompt box is the hardest question in the app, so
* these give the feature an obvious first move. Phrased as things someone
* would actually ask, not as feature names.
*/
const IDEA_STARTERS = [
'Date ideas this weekend',
'A cheap night in',
'Gift ideas',
'Something to cheer her up',
] as const;
// Emoji palette offered when creating a milestone.
const MILESTONE_EMOJIS = ['💛', '💍', '🌹', '🎉', '✈️', '🏡', '🎂', '⭐'] as const;
const PHASE_COLORS = THEME.colors.phase;
/**
* Payment apps, by package name. Anything not listed still logs correctly —
* the label just falls back to nothing rather than showing a raw package.
*/
const PAYMENT_APPS: Record<string, string> = {
'com.google.android.apps.nbu.paisa.user': 'Google Pay',
'com.phonepe.app': 'PhonePe',
'net.one97.paytm': 'Paytm',
'com.paypal.android.p2pmobile': 'PayPal',
'com.sbi.lotusintouch': 'SBI',
// Synthetic: a bank SMS rather than an app notification. The couple's own
// bank texts every UPI transfer, which makes this the common case.
'android.sms': 'Bank SMS',
};
/** Extra names to match a payment against, beyond the partner's profile name. */
const PARTNER_ALIAS_KEY = 'novia.payments.partnerAliases';
/**
* Indian digit grouping — 1,00,000 rather than 100,000.
*
* Worth the eight lines: these are rupee amounts read by two people in India,
* and western grouping is the kind of small wrongness that makes an app feel
* like it was built for somewhere else.
*/
function formatAmount(value: number): string {
const fixed = value % 1 === 0 ? String(Math.round(value)) : value.toFixed(2);
const [whole, fraction] = fixed.split('.');
const last3 = whole.slice(-3);
const rest = whole.slice(0, -3);
const grouped = rest ? `${rest.replace(/\B(?=(\d{2})+(?!\d))/g, ',')},${last3}` : last3;
return fraction ? `${grouped}.${fraction}` : grouped;
}
/**
* The hub greeting. Morning until noon, afternoon until five, evening after —
* and the small hours get "evening" too rather than a "good night" that reads
* like a farewell to someone who just opened the app.
*/
function greetingForHour(hour: number): string {
if (hour >= 5 && hour < 12) return 'Good Morning';
// Both bounds, not just the upper one: `hour < 17` alone sweeps up 1am as
// afternoon, because the morning test above has already failed by then.
if (hour >= 12 && hour < 17) return 'Good Afternoon';
return 'Good Evening';
}
/** 'Today' / 'Yesterday' / '8 Sep' — the heading a run of payments sits under. */
function formatDayLabel(iso: string): string {
const date = new Date(iso);
const today = new Date();
const startOf = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
const days = Math.round((startOf(today) - startOf(date)) / 86_400_000);
if (days === 0) return 'Today';
if (days === 1) return 'Yesterday';
return date.toLocaleDateString(undefined, { day: 'numeric', month: 'short' });
}
function formatClock(iso: string): string {
return new Date(iso).toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
}
/**
* The ground: one neon-orange source burning in the top-left corner, falling
* away along the diagonal into black.
*
* Three details do most of the work:
*
* The light is anchored *off-canvas* (cx -6%, cy -4%) rather than at the
* corner. A radial gradient centred exactly on the corner puts its hottest,
* flattest point on screen and reads as a sticker; pushing the origin just
* outside means only the falloff is visible, which is what an actual light
* source spilling in from beyond the frame looks like.
*
* The stops are front-loaded — most of the drop happens in the first 30% —
* because linear falloff over a whole screen reads as a wash rather than as
* light. And a single dim ember at the far corner keeps the diagonal from
* dying into flat black, so the ground still has somewhere to go.
*
* There is deliberately no grain overlay. One was tried twice — an SVG
* feTurbulence filter (which react-native-svg does not implement on native, so
* it rendered nothing at all) and then a tiled noise texture (which did render,
* and looked worse). On this backdrop the gradient reads cleaner without it.
*/
function SpaceBackdrop() {
return (
<Svg pointerEvents="none" style={StyleSheet.absoluteFill} width="100%" height="100%" viewBox="0 0 390 844" preserveAspectRatio="xMidYMid slice">
<Defs>
{/* Key light: neon orange spilling in from beyond the top-left corner */}
<RadialGradient id="cornerBurn" cx="-8%" cy="-5%" r="175%" fx="-8%" fy="-5%">
<Stop offset="0%" stopColor={PALETTE.accent} stopOpacity="0.98" />
<Stop offset="16%" stopColor={PALETTE.accent} stopOpacity="0.72" />
<Stop offset="31%" stopColor={PALETTE.accent} stopOpacity="0.42" />
<Stop offset="46%" stopColor={PALETTE.accent} stopOpacity="0.22" />
<Stop offset="62%" stopColor={PALETTE.accentHot} stopOpacity="0.10" />
<Stop offset="80%" stopColor={PALETTE.accentHot} stopOpacity="0.035" />
<Stop offset="100%" stopColor={PALETTE.ground} stopOpacity="0" />
</RadialGradient>
{/* A last ember at the far corner, so the diagonal has an end and not
just an absence. Barely perceptible on its own. */}
<RadialGradient id="farEmber" cx="104%" cy="102%" r="72%" fx="104%" fy="102%">
<Stop offset="0%" stopColor={PALETTE.accentHot} stopOpacity="0.10" />
<Stop offset="46%" stopColor={PALETTE.accentHot} stopOpacity="0.03" />
<Stop offset="100%" stopColor={PALETTE.ground} stopOpacity="0" />
</RadialGradient>
{/* Bottom fade so content sinks away behind the floating tab dock */}
<SvgLinearGradient id="bottomFade" x1="0%" y1="100%" x2="0%" y2="0%">
<Stop offset="0%" stopColor={PALETTE.ground} stopOpacity="1.0" />
<Stop offset="28%" stopColor={PALETTE.ground} stopOpacity="1.0" />
<Stop offset="38%" stopColor={PALETTE.ground} stopOpacity="0.95" />
<Stop offset="55%" stopColor={PALETTE.ground} stopOpacity="0.40" />
<Stop offset="80%" stopColor={PALETTE.ground} stopOpacity="0" />
</SvgLinearGradient>
</Defs>
{/* Black base layer */}
<Rect width="390" height="844" fill={PALETTE.ground} />
{/* The diagonal: burn in the top-left, ember in the bottom-right */}
<Rect width="390" height="844" fill="url(#cornerBurn)" />
<Rect width="390" height="844" fill="url(#farEmber)" />
{/* Bottom atmospheric fade covering the area below the pill taskbar */}
<Rect width="390" height="844" fill="url(#bottomFade)" />
</Svg>
);
}
const AnimatedTouchable = Animated.createAnimatedComponent(TouchableOpacity);
/**
* PressableScale — a touchable that gently springs inward on press.
* Gives every interactive glass surface a soft, tactile neumorphic response.
*
* Two details that separate this from a plain TouchableOpacity:
*
* The scale fires on press *down*, not on release. The instant feedback is the
* whole point — waiting for touch-up to acknowledge a press is the single
* loudest way an interface reads as laggy, and no amount of animation polish
* afterwards recovers it.
*
* Both directions use the same critically-damped spring. The release used to
* bounce (`bounciness: 7`), but a finger lifting off carries no momentum into
* the element, so the overshoot was decoration pretending to be physics. Bounce
* belongs on motion a gesture actually threw — see SPRING.flick.
*
* The default hitSlop is deliberate: the touch target should extend past the
* visible bounds, so a press that lands a few pixels off still reads as a hit.
*/
const PRESS_HIT_SLOP = { top: 10, bottom: 10, left: 10, right: 10 };
function PressableScale({
children,
onPress,
onLongPress,
style,
scaleTo = 0.96,
disabled = false,
activeOpacity = 0.92,
hitSlop = PRESS_HIT_SLOP,
}: {
children: React.ReactNode;
onPress?: () => void;
onLongPress?: () => void;
style?: any;
scaleTo?: number;
disabled?: boolean;
activeOpacity?: number;
hitSlop?: any;
}) {
const scale = useRef(new Animated.Value(1)).current;
const pressIn = () =>
Animated.spring(scale, { toValue: scaleTo, useNativeDriver: true, ...SPRING.press }).start();
const pressOut = () =>
Animated.spring(scale, { toValue: 1, useNativeDriver: true, ...SPRING.press }).start();
return (
<AnimatedTouchable
activeOpacity={activeOpacity}
onPress={onPress}
onLongPress={onLongPress}
onPressIn={pressIn}
onPressOut={pressOut}
disabled={disabled}
hitSlop={hitSlop}
style={[style, { transform: [{ scale }] }]}
>
{children}
</AnimatedTouchable>
);
}
/**
* SubmitButton — a primary action button that guards against double-submits.
*
* Every send/save handler here does a network round-trip (a Supabase insert)
* before the UI updates. With a plain TouchableOpacity, a second tap during that
* window fires the same insert again — the reported "send it twice" bug — and the
* button feels dead ("delay in sending"). This wraps the async onPress: re-taps
* are ignored while one is in flight (a synchronous ref guard, so it holds even
* against a fast double-tap within one frame), and the button dims to show it's
* working. Drop-in replacement for the primaryButton TouchableOpacity.
*/
function SubmitButton({
children,
onPress,
style,
disabled = false,
activeOpacity = 0.85,
}: {
children: React.ReactNode;
onPress?: () => void | Promise<unknown>;
style?: any;
disabled?: boolean;
activeOpacity?: number;
}) {
const inFlight = useRef(false);
const [busy, setBusy] = useState(false);
const mounted = useRef(true);
// The primary CTA was the *least* responsive control in the app: every glass
// surface sprang under the finger via PressableScale, while the button you
// actually came to press only dimmed. Same press spring, same instant
// acknowledgement — the dim on top now reads as "working", not as the only
// feedback there is.
const scale = useRef(new Animated.Value(1)).current;
useEffect(() => () => { mounted.current = false; }, []);
const springTo = (toValue: number) =>
Animated.spring(scale, { toValue, useNativeDriver: true, ...SPRING.press }).start();
const handlePress = async () => {
if (inFlight.current || disabled) return;
inFlight.current = true;
setBusy(true);
try {
await onPress?.();
} finally {
inFlight.current = false;
if (mounted.current) setBusy(false);
}
};
return (
<AnimatedTouchable
style={[style, busy && { opacity: 0.6 }, { transform: [{ scale }] }]}
onPress={handlePress}
onPressIn={() => springTo(0.97)}
onPressOut={() => springTo(1)}
disabled={disabled || busy}
activeOpacity={activeOpacity}
hitSlop={PRESS_HIT_SLOP}
>
{children}
</AnimatedTouchable>
);
}
/**
* Animation budget
* ----------------
* Every animation in this file drives ONLY `opacity` and `transform`, with
* `useNativeDriver: true`. Those two properties can be handed to the platform's
* animation system and run on the UI thread, so they keep ticking at 60fps even
* while JS is busy with a Supabase round-trip or a re-render.
*
* Deliberately avoided, because they are the usual causes of jank:
* - animating width/height/margin/padding/top/left (layout properties cannot
* use the native driver; every frame round-trips through JS and re-runs
* Yoga layout)
* - animating backgroundColor/shadow (same problem, plus shadow re-rasterises)
* - Animated.Value listeners that call setState per frame (a full React
* render every 16ms)
*
* Looping animations also pause when their screen isn't mounted, so background
* tabs cost nothing.
*/
/**
* FadeInUp — a staggered entrance for list and card content.
*
* `index` offsets the start so items cascade instead of appearing as one block.
* The stagger is capped: past ~8 items the delay stops growing, otherwise the
* last card in a long ledger would sit blank for over a second.
*/
const FadeInUp = React.memo(function FadeInUp({
children,
index = 0,
distance = 16,
style,
}: {
children: React.ReactNode;
index?: number;
distance?: number;
style?: any;
}) {
const anim = useRef(new Animated.Value(0)).current;
const reducedMotion = useReducedMotion();
useEffect(() => {
const animation = Animated.timing(anim, {
toValue: 1,
duration: 420,
delay: Math.min(index, 8) * 55,
easing: Easing.out(Easing.cubic),
useNativeDriver: true,
});
animation.start();
// Stop on unmount so a fast tab switch doesn't leave orphaned animations
// writing to a detached view.
return () => animation.stop();
}, [anim, index]);
// Reduced motion keeps the fade — it still communicates "this is arriving" —
// and drops only the travel, which is the part that provokes motion
// sensitivity. Cutting the animation entirely would lose the staggering that
// tells you the cards are a sequence, not one wall of content.
const travel = reducedMotion ? 0 : distance;
return (
<Animated.View
style={[
style,
{
opacity: anim,
transform: [
{ translateY: anim.interpolate({ inputRange: [0, 1], outputRange: [travel, 0] }) },
],
},
]}
>
{children}
</Animated.View>
);
});
/**
* Breathing — an extremely slow opacity pulse.
*
* Used on the ambient backdrop glow to keep the screen feeling alive. One
* native-driven opacity loop costs essentially nothing; the same effect via a
* colour or size animation would not.
*/
function Breathing({
children,
from = 0.55,
to = 1,
duration = 4200,
style,
}: {
children: React.ReactNode;
from?: number;
to?: number;
duration?: number;
style?: any;
}) {
const anim = useRef(new Animated.Value(0)).current;
const reducedMotion = useReducedMotion();
useEffect(() => {
// A full-viewport brightness oscillation with a ~10s period sits squarely in
// the band that provokes motion sensitivity — a slow ambient pulse is the
// textbook case for honouring reduce-motion. Hold it at the bright end so
// the backdrop keeps its intended look, just without the breathing.
if (reducedMotion) {
anim.setValue(1);
return;
}
const loop = Animated.loop(
Animated.sequence([
Animated.timing(anim, { toValue: 1, duration, easing: Easing.inOut(Easing.sin), useNativeDriver: true }),
Animated.timing(anim, { toValue: 0, duration, easing: Easing.inOut(Easing.sin), useNativeDriver: true }),
])
);
loop.start();
return () => loop.stop();
}, [anim, duration, reducedMotion]);
return (
<Animated.View
style={[style, { opacity: anim.interpolate({ inputRange: [0, 1], outputRange: [from, to] }) }]}
pointerEvents="none"
>
{children}
</Animated.View>
);
}
/**
* Shimmer — a slow highlight that sweeps across a glass surface.
*
* Self-measuring: drop it inside any container that sets `overflow: 'hidden'`
* and it fills the parent, so no dimensions need threading through.
*
* Only translateX is animated, so the sweep runs on the UI thread. The long
* trailing delay keeps it a periodic accent rather than a distraction — a
* constantly-moving highlight reads cheap and burns battery for nothing.
*/
function Shimmer({ delay = 0, period = 5200 }: { delay?: number; period?: number }) {
const anim = useRef(new Animated.Value(0)).current;
const [size, setSize] = useState({ width: 0, height: 0 });
const reducedMotion = useReducedMotion();
useEffect(() => {
if (size.width === 0 || reducedMotion) return;
const loop = Animated.loop(
Animated.sequence([
Animated.delay(delay),
Animated.timing(anim, {
toValue: 1,
duration: 1500,
easing: Easing.inOut(Easing.quad),
useNativeDriver: true,
}),
Animated.delay(period),
// Snap back invisibly; resetting via setValue would need a JS frame.
Animated.timing(anim, { toValue: 0, duration: 0, useNativeDriver: true }),
])
);
loop.start();
return () => loop.stop();
}, [anim, delay, period, size.width, reducedMotion]);
const band = Math.max(size.height * 1.6, 48);
// Pure decoration with no informational job — under reduce-motion it simply
// shouldn't exist, rather than being animated more gently.
if (reducedMotion) return null;
return (
<View
pointerEvents="none"
style={StyleSheet.absoluteFill}
onLayout={(e) => setSize({ width: e.nativeEvent.layout.width, height: e.nativeEvent.layout.height })}
>
{size.width > 0 && (
<Animated.View
style={{
position: 'absolute',
top: -size.height,
bottom: -size.height,
width: band,
backgroundColor: alpha(THEME.ink[95], 0.07),
transform: [
{
translateX: anim.interpolate({
inputRange: [0, 1],
outputRange: [-band, size.width + band],
}),
},
{ rotate: '14deg' },
],
}}
/>
)}
</View>
);
}
/**
* AnimatedBar — a progress fill that grows from the left.
*
* The obvious implementation animates `width: '42%'`, but width is a layout
* property: it can't use the native driver, so every frame crosses the bridge
* and re-runs layout on the whole subtree. Instead the fill is laid out at full
* width and squashed with `scaleX`.
*
* scaleX scales about the centre, which would make the bar grow from the middle
* outward. Translating by (scale - 1) * width / 2 pins the left edge in place;
* both values are interpolated from the same driver so they stay in lockstep.
*
* The driver holds the *progress itself* (0..1), not a generic 0→1 ramp. An
* earlier version always animated the driver to 1 and folded `target` into the
* output range: once it had reached 1, a new target only changed the range, so
* every later value snapped into place instead of sliding — the step bars never
* animated after their first paint. Animating the driver *to* the target keeps
* the interpolations constant and makes each update a real transition from
* wherever the bar currently sits.
*
* And it's a spring, not a 900ms easing curve, because the value behind it
* moves on its own schedule: a step count arrives from a partner's phone
* whenever it arrives, sometimes twice within a second. A timing curve
* re-targeted mid-flight restarts from the head of its easing, so the bar
* visibly stutters; a spring re-targets from its current position *and*
* current velocity, so consecutive updates read as one continuous movement.
*/
function AnimatedBar({
progress,
color,
trackStyle,
fillStyle,
}: {
progress: number; // 0..1
color: string;
trackStyle?: any;
fillStyle?: any;
}) {
const anim = useRef(new Animated.Value(0)).current;
const [width, setWidth] = useState(0);
const reducedMotion = useReducedMotion();
const target = Math.max(0, Math.min(1, Number.isFinite(progress) ? progress : 0));
useEffect(() => {
if (width === 0) return; // wait for measurement, otherwise the maths is meaningless
if (reducedMotion) {
anim.setValue(target);
return;
}
const animation = Animated.spring(anim, {
toValue: target,
useNativeDriver: true,
...SPRING.move,
});
animation.start();
return () => animation.stop();
}, [anim, width, target, reducedMotion]);
return (
<View
style={[styles.progressBarBg, trackStyle]}
onLayout={(e) => setWidth(e.nativeEvent.layout.width)}
>
{width > 0 && (
<Animated.View
style={[
styles.progressBarFill,
fillStyle,
{
width: '100%',
backgroundColor: color,
transform: [
// p → (p - 1) * width / 2, i.e. -width/2 at empty, 0 at full.
{ translateX: anim.interpolate({ inputRange: [0, 1], outputRange: [-width / 2, 0] }) },
{ scaleX: anim },
],
},
]}
/>
)}
</View>
);
}
/**
* ScreenTransition — replays a soft fade + rise whenever its `key` changes.
* Wrap tab content and key it on the active tab for seamless screen swaps.
*/
function ScreenTransition({ children }: { children: React.ReactNode }) {
const anim = useRef(new Animated.Value(0)).current;
const reducedMotion = useReducedMotion();
useEffect(() => {
anim.setValue(0);
Animated.timing(anim, {
toValue: 1,
duration: 440,
easing: Easing.out(Easing.cubic),
useNativeDriver: true,
}).start();
}, []);
// A whole screen rising and scaling is the largest single movement in the
// app; under reduce-motion it becomes a plain cross-fade, which still marks
// the screen change without the travel.
const travel = reducedMotion ? 0 : 18;
const from = reducedMotion ? 1 : 0.985;
return (
<Animated.View
style={{
opacity: anim,
transform: [
{ translateY: anim.interpolate({ inputRange: [0, 1], outputRange: [travel, 0] }) },
{ scale: anim.interpolate({ inputRange: [0, 1], outputRange: [from, 1] }) },
],
}}
>
{children}
</Animated.View>
);
}
/**
* How far the floating tab bar sits above the very bottom of the screen.
*
* On Android with edge-to-edge the app window spans behind the system nav, so we
* estimate the nav-bar height from the gap between the physical screen and the
* app window (works for 3-button navigation); gesture-nav phones report ~0 and
* get a small fixed gap. This keeps the dock clear of the nav area on a Vivo
* 3-button setup while sitting low on the S23's gesture bar — without pulling in
* react-native-safe-area-context (a native module that would force a rebuild and
* break OTA). iOS's home indicator is handled by the SafeAreaView wrapper.
*/
const ANDROID_NAV_INSET =
Platform.OS === 'android'
? Math.max(
0,
Math.round(
Dimensions.get('screen').height -
Dimensions.get('window').height -
(StatusBar.currentHeight || 0)
)
)
: 0;
const TAB_BAR_BOTTOM = Platform.OS === 'android' ? Math.max(ANDROID_NAV_INSET + 6, 22) : 24;
/**
* AnimatedTabBar — frosted glass pill dock with a sliding accent indicator
* that glides between tabs, plus per-item press springs.
*/
const TAB_ICONS: Record<string, React.ComponentType<{ size?: number; color?: string; strokeWidth?: number }>> = {
hub: Home,
notes: FileText,
finances: Wallet,
ai: Sparkles,
health: Activity,
menu: Menu,
};
// Hub sub-screens reachable from Hub cards (not on the tab bar). The device
// back button and their on-screen back rows both return from these to the Hub.
const HUB_SUBSCREENS = ['todos', 'milestones', 'complaints', 'bucket', 'health'];
/**
* The menu is full-screen, so the panel's width is the window's.
*
* Shared by the panel style, the slide transform and the drag maths, which is
* why this one line is most of what "make it full screen" means. The gesture
* needs no re-tuning: it works in progress units, so a wider panel is simply a
* longer drag for the same fraction.
*
* Read once at module load, like ANDROID_NAV_INSET above — the app is
* portrait-locked, so there is no rotation for this to go stale against.
*/
const DRAWER_WIDTH = Dimensions.get('window').width;
/** The credit line in the menu footer links here. */
const DEVELOPER_URL = 'https://www.adarsharavind.com';
function AnimatedTabBar<T extends string>({
tabs,
activeTab,
onChange,
}: {
tabs: readonly T[];
activeTab: T;
onChange: (t: T) => void;
}) {
const INNER_PAD = 6;
const [barW, setBarW] = useState(0);
// activeTab may be a Hub sub-screen (todos/complaints/bucket/location) that
// isn't on the bar — indexOf is -1 then, so we hide the sliding indicator.
const activeIndex = tabs.indexOf(activeTab);
const onBar = activeIndex >= 0;
const indicator = useRef(new Animated.Value(onBar ? activeIndex : 0)).current;
const slotW = barW > 0 ? (barW - INNER_PAD * 2) / tabs.length : 0;
const reducedMotion = useReducedMotion();
useEffect(() => {
if (!onBar) return;
if (reducedMotion) {
indicator.setValue(activeIndex);
return;
}
// Critically damped, not the old bounciness: 9. A tab is selected by a tap,
// and a tap imparts no momentum for the indicator to overshoot with — the
// bounce was the indicator claiming physics that never happened. It now
// glides and stops exactly where the finger said.
Animated.spring(indicator, {
toValue: activeIndex,
useNativeDriver: true,
...SPRING.snap,
}).start();
}, [activeIndex, onBar, indicator, reducedMotion]);
const translateX = indicator.interpolate({
inputRange: tabs.map((_, i) => i),
outputRange: tabs.map((_, i) => INNER_PAD + i * slotW),
});
return (
<View style={[styles.tabBar, { bottom: TAB_BAR_BOTTOM }]} onLayout={(e) => setBarW(e.nativeEvent.layout.width)}>
<GlassBacking radius={34} tier="chrome" />
{slotW > 0 && onBar && (
<Animated.View
pointerEvents="none"
style={[
styles.tabIndicator,
{ width: slotW, transform: [{ translateX }] },
]}
/>
)}
{tabs.map((tab) => {
const isActive = activeTab === tab;
const Icon = TAB_ICONS[tab] || Home;
return (
<PressableScale
key={tab}
scaleTo={0.9}
style={styles.tabItem}
onPress={() => onChange(tab)}
>
<Icon
size={24}
color={isActive ? THEME.colors.primary : alpha(THEME.ink[95], 0.55)}
strokeWidth={isActive ? 2.5 : 2}
/>
</PressableScale>
);
})}
</View>
);
}
/**
* A bucket-list row that acknowledges the tap and commits it at the same time.
*
* This used to run a six-step, 720ms blink and fire onToggle() in the
* completion callback — the outcome was gated behind the decoration, so ticking
* an item took the better part of a second and re-tapping during the blink did
* nothing. Feedback and commit are now concurrent: the checkbox flips on the
* frame you lift your finger (the parent updates optimistically), and a single
* confirming pulse plays over the top rather than three flashes demanding
* attention the action doesn't warrant.
*/
const BlinkingBucketRow = ({ item, getCreatorName, onToggle, onDelete }: { item: any; getCreatorName: (creatorId?: string | null) => string; onToggle: () => void; onDelete: () => void }) => {
const blinkAnim = React.useRef(new Animated.Value(1)).current;
const scale = React.useRef(new Animated.Value(1)).current;
const reducedMotion = useReducedMotion();
const handlePress = () => {
onToggle();
if (reducedMotion) return;
Animated.sequence([
Animated.timing(blinkAnim, { toValue: 0.45, duration: 90, useNativeDriver: true }),
Animated.spring(blinkAnim, { toValue: 1, useNativeDriver: true, ...SPRING.snap }),
]).start();
};
const springTo = (toValue: number) =>
Animated.spring(scale, { toValue, useNativeDriver: true, ...SPRING.press }).start();
return (
<Animated.View style={{ opacity: blinkAnim, transform: [{ scale }] }}>
<TouchableOpacity
style={[
styles.bucketRow,
]}
onPress={handlePress}
onPressIn={() => springTo(0.98)}
onPressOut={() => springTo(1)}
activeOpacity={0.7}
>
<View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
<View style={{ flexDirection: 'row', alignItems: 'center', flex: 1, paddingRight: 8 }}>
{item.is_completed ? (
<CheckSquare size={18} color={THEME.colors.primary} strokeWidth={2} />
) : (
<Square size={18} color={alpha(THEME.ink[95], 0.5)} strokeWidth={2} />
)}
<Text style={[styles.bucketText, item.is_completed && styles.strikethrough, { marginLeft: 8 }]}>
{item.title}
</Text>
</View>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={[styles.metaLine, { fontSize: 10, opacity: 0.6, marginRight: 12 }]}>By {getCreatorName(item.created_by)}</Text>
<TouchableOpacity
onPress={(e) => {
e.stopPropagation();
onDelete();
}}
style={{
width: 26,
height: 26,
borderRadius: 13,
backgroundColor: alpha(THEME.colors.danger, 0.16),
alignItems: 'center',
justifyContent: 'center',
}}
>
<X size={12} color={THEME.colors.danger} strokeWidth={2.5} />
</TouchableOpacity>
</View>
</View>
{item.description ? (
<Text style={[styles.bucketDescription, { opacity: 0.85, fontSize: 12, marginTop: 4 }]}>
{item.description}
</Text>
) : null}
</TouchableOpacity>
</Animated.View>
);
};
export default function App() {
const [activeTab, setActiveTab] = useState<'hub' | 'notes' | 'finances' | 'health' | 'ai' | 'bucket' | 'todos' | 'complaints' | 'milestones'>('hub');
// Typefaces. Only the six weights the design actually uses are loaded — each
// extra static face is ~95 KB of bundle for no visual gain.
const [fontsLoaded, fontError] = useFonts({
Fraunces_600SemiBold,
Fraunces_700Bold,
Manrope_400Regular,
Manrope_500Medium,
Manrope_600SemiBold,
Manrope_700Bold,
Manrope_800ExtraBold,
});
// Custom hooks
const {
session,
loading: authLoading,
profile,
partnerProfile,
coupleId,
signUp,
signIn,
signOut,
pairPartner,
updateDisplayName,
updateAvatar,
unpairPartner
} = useAuth();
const userId = session?.user?.id || null;
// Auth local state
const [authEmail, setAuthEmail] = useState('');
const [authPassword, setAuthPassword] = useState('');
const [authDisplayName, setAuthDisplayName] = useState('');
const [isSignUpMode, setIsSignUpMode] = useState(false);
// Pairing local state
const [partnerIdInput, setPartnerIdInput] = useState('');
const handleAuthSubmit = async () => {
if (!authEmail.trim() || !authPassword.trim()) {
Alert.alert("Error", "Please fill in all fields.");
return;
}
if (isSignUpMode) {
if (!authDisplayName.trim()) {
Alert.alert("Error", "Please enter a display name.");
return;
}
await signUp(authEmail, authPassword, authDisplayName);
} else {
await signIn(authEmail, authPassword);
}
};
const handlePairSubmit = async () => {
if (!partnerIdInput.trim()) {
Alert.alert("Error", "Please enter your partner's User ID.");
return;
}
await pairPartner(partnerIdInput.trim());
};
const { notes, isPartnerTyping, setTyping: setNoteTyping, addNote, removeNote, toggleReaction } = useRealtimeNotes(coupleId, userId);
const { currentMood, partnerMood, partnerName, updateMood } = useMood(coupleId, userId);
const { todos, addTodo, toggleTodo, deleteTodo } = useTodos(coupleId, userId);
const { records, predictions, addPeriodLog, refreshPeriods } = usePeriods(coupleId);
const {
complaints,
loading: complaintsLoading,
addComplaint,
addReply,
setStatus: setComplaintStatus,
deleteComplaint,
repliesFor,
} = useComplaints(coupleId, userId);
const { milestones, addMilestone, deleteMilestone } = useMilestones(coupleId, userId);
const {
mySteps,
partnerSteps,
series: stepSeries,
status: stepsStatus,
loading: stepsLoading,
leader: stepLeader,
partnerSynced: stepsPartnerSynced,
season: stepSeason,
streakHolder: stepStreakHolder,
streakCount: stepStreakCount,
forfeit: stepForfeit,
setForfeit: setStepForfeit,
requestAccess: requestStepAccess,
} = useSteps(coupleId, userId, partnerProfile?.id);
// --- Detected payments ---
/**
* Extra names to match against, kept on the device.
*
* The name a payment app shows is whatever the bank has on file, and it is
* routinely not the name in the app's profile — "P Sharma", a maiden name,
* an initial. Rather than guess at those, the screen lets the user add the
* name they actually see, which is the only reliable source for it.
*/
const [customAliases, setCustomAliases] = useState<string[]>([]);
const [aliasSheetOpen, setAliasSheetOpen] = useState(false);
const [aliasDraft, setAliasDraft] = useState('');
useEffect(() => {
AsyncStorage.getItem(PARTNER_ALIAS_KEY)
.then((raw) => {
if (raw) setCustomAliases(JSON.parse(raw));