-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPersonDetail.tsx
More file actions
1334 lines (1212 loc) · 53.6 KB
/
PersonDetail.tsx
File metadata and controls
1334 lines (1212 loc) · 53.6 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 { useEffect, useState, useCallback, useRef } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { Briefcase, Users, ExternalLink, GitBranch, Loader2, User, BookOpen, Heart, TreeDeciduous, Calendar, MapPin, Check, X, Copy } from 'lucide-react';
import toast from 'react-hot-toast';
import type { PersonWithId, PathResult, DatabaseInfo, PersonAugmentation } from '@fsf/shared';
import { api, PersonOverrides, PersonClaim } from '../../services/api';
import { FavoriteButton } from '../favorites/FavoriteButton';
import { useSidebar } from '../../context/SidebarContext';
import { EditableField } from '../ui/EditableField';
import { EditableDate } from '../ui/EditableDate';
import type { ListItem } from '../ui/EditableList';
import type { VitalEventOverrides } from './VitalEventCard';
import { UploadToFamilySearchDialog } from './UploadToFamilySearchDialog';
import { UploadToAncestryDialog } from './UploadToAncestryDialog';
import { ProviderDataTable } from './ProviderDataTable';
import { LinkPlatformDialog } from './LinkPlatformDialog';
import { RelationshipModal } from './RelationshipModal';
import type { RelationshipType } from './RelationshipModal';
import { PersonAuditIssues } from './PersonAuditIssues';
interface CachedLineage {
path: PathResult;
timestamp: number;
}
function getLineageCacheKey(dbId: string, personId: string): string {
return `fsf-lineage-${dbId}-${personId}`;
}
function getCachedLineage(dbId: string, personId: string): PathResult | null {
const key = getLineageCacheKey(dbId, personId);
const cached = localStorage.getItem(key);
if (!cached) return null;
let data: CachedLineage;
try {
data = JSON.parse(cached);
} catch {
localStorage.removeItem(key);
return null;
}
// Cache for 24 hours
if (Date.now() - data.timestamp > 24 * 60 * 60 * 1000) {
localStorage.removeItem(key);
return null;
}
return data.path;
}
function setCachedLineage(dbId: string, personId: string, path: PathResult): void {
const key = getLineageCacheKey(dbId, personId);
const data: CachedLineage = { path, timestamp: Date.now() };
localStorage.setItem(key, JSON.stringify(data));
}
function getRelationshipLabel(generations: number): string {
if (generations === 0) return 'Self';
if (generations === 1) return 'Parent';
if (generations === 2) return 'Grandparent';
if (generations === 3) return 'Great-Grandparent';
// 4+ generations: 2nd great, 3rd great, etc.
const greats = generations - 2;
const ordinal = getOrdinal(greats);
return `${ordinal} Great-Grandparent`;
}
function getOrdinal(n: number): string {
const s = ['th', 'st', 'nd', 'rd'];
const v = n % 100;
return n + (s[(v - 20) % 10] || s[v] || s[0]);
}
function InlineAddInput({ onAdd, onCancel, placeholder }: { onAdd: (value: string) => void; onCancel: () => void; placeholder: string }) {
const [value, setValue] = useState('');
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => { inputRef.current?.focus(); }, []);
const handleSubmit = () => {
if (value.trim()) {
onAdd(value.trim());
}
};
return (
<div className="flex items-center gap-1 mt-1.5">
<input
ref={inputRef}
type="text"
value={value}
onChange={(e) => setValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleSubmit();
if (e.key === 'Escape') onCancel();
}}
placeholder={placeholder}
className="flex-1 px-2 py-0.5 bg-app-bg border border-app-accent rounded text-app-text text-xs focus:outline-none focus:ring-1 focus:ring-app-accent"
/>
<button onClick={handleSubmit} className="p-0.5 text-app-success hover:bg-app-success/10 rounded" title="Add">
<Check size={14} />
</button>
<button onClick={onCancel} className="p-0.5 text-app-error hover:bg-app-error/10 rounded" title="Cancel">
<X size={14} />
</button>
</div>
);
}
// Compact family member card with photo
interface FamilyMemberCardProps {
id: string;
person: PersonWithId | undefined;
dbId: string;
hasPhoto: boolean;
gender?: 'male' | 'female';
}
function FamilyMemberCard({ id, person, dbId, hasPhoto, gender }: FamilyMemberCardProps) {
const displayName = person?.name || id.slice(0, 8);
const firstName = displayName.split(' ')[0];
const lifespan = person?.lifespan;
// Use person's gender if available, otherwise use the passed gender prop
const effectiveGender = person?.gender || gender;
return (
<Link
to={`/person/${dbId}/${id}`}
className="flex items-center gap-2 p-1.5 rounded-lg bg-app-bg/50 hover:bg-app-hover transition-colors group min-w-0"
>
{/* Photo or placeholder */}
{hasPhoto ? (
<img
src={api.getPhotoUrl(id)}
alt={displayName}
className="w-8 h-8 rounded-full object-cover flex-shrink-0"
/>
) : (
<div className="w-8 h-8 rounded-full bg-app-card flex items-center justify-center flex-shrink-0">
<User size={14} className="text-app-text-subtle" />
</div>
)}
{/* Name and lifespan */}
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1">
<span className="text-xs font-medium text-app-text truncate group-hover:text-app-accent">
{firstName}
</span>
{effectiveGender && effectiveGender !== 'unknown' && (
<span className={`text-[10px] ${effectiveGender === 'male' ? 'text-app-male' : 'text-app-female'}`}>
{effectiveGender === 'male' ? '♂' : '♀'}
</span>
)}
</div>
{lifespan && (
<span className="text-[10px] text-app-text-subtle truncate block">
{lifespan}
</span>
)}
</div>
</Link>
);
}
export function PersonDetail() {
const { dbId, personId } = useParams<{ dbId: string; personId: string }>();
const navigate = useNavigate();
const { refreshDatabases, expandDatabase } = useSidebar();
const [person, setPerson] = useState<PersonWithId | null>(null);
const [parentData, setParentData] = useState<Record<string, PersonWithId>>({});
const [spouseData, setSpouseData] = useState<Record<string, PersonWithId>>({});
const [childData, setChildData] = useState<Record<string, PersonWithId>>({});
const [familyPhotos, setFamilyPhotos] = useState<Record<string, boolean>>({});
const [database, setDatabase] = useState<DatabaseInfo | null>(null);
const [lineage, setLineage] = useState<PathResult | null>(null);
const [augmentation, setAugmentation] = useState<PersonAugmentation | null>(null);
const [photoStatus, setPhotoStatus] = useState<Record<string, boolean>>({});
const [photoVersion, setPhotoVersion] = useState(0); // For cache busting
const [loading, setLoading] = useState(true);
const [lineageLoading, setLineageLoading] = useState(false);
const [scrapeLoading, setScrapeLoading] = useState(false);
// Platform linking dialog state
const [linkingPlatform, setLinkingPlatform] = useState<'wikipedia' | 'ancestry' | 'wikitree' | 'linkedin' | null>(null);
const [linkingLoading, setLinkingLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Canonical ID and external identities
const [canonicalId, setCanonicalId] = useState<string | null>(null);
const [externalIdentities, setExternalIdentities] = useState<Array<{ source: string; externalId: string; url?: string }>>([]);
const [fetchingPhotoFrom, setFetchingPhotoFrom] = useState<string | null>(null);
const [makeRootLoading, setMakeRootLoading] = useState(false);
const [syncLoading, setSyncLoading] = useState(false);
const [showUploadDialog, setShowUploadDialog] = useState(false);
const [showAncestryUploadDialog, setShowAncestryUploadDialog] = useState(false);
const [relationshipModalType, setRelationshipModalType] = useState<RelationshipType | null>(null);
const [hintsProcessing, setHintsProcessing] = useState(false);
// Local overrides state
const [overrides, setOverrides] = useState<PersonOverrides | null>(null);
const [claims, setClaims] = useState<PersonClaim[]>([]);
// Inline-add state for aliases and occupations
const [addingAlias, setAddingAlias] = useState(false);
const [addingOccupation, setAddingOccupation] = useState(false);
useEffect(() => {
if (!dbId || !personId) return;
const controller = new AbortController();
const { signal } = controller;
setLoading(true);
setLineage(null);
setAugmentation(null);
setPhotoStatus({});
setParentData({});
setSpouseData({});
setChildData({});
setFamilyPhotos({});
setLinkingPlatform(null);
setLinkingLoading(false);
setCanonicalId(null);
setExternalIdentities([]);
setOverrides(null);
setClaims([]);
// Load canonical ID and external identities
api.getIdentities(dbId, personId).then(data => {
if (signal.aborted) return;
setCanonicalId(data.canonicalId);
setExternalIdentities(data.identities);
}).catch(() => null);
// Load overrides and claims (separate from main data)
api.getPersonOverrides(dbId, personId).then(data => {
if (signal.aborted) return;
setOverrides(data);
}).catch(() => null);
api.getPersonClaims(dbId, personId).then(data => {
if (signal.aborted) return;
setClaims(data);
}).catch(() => []);
Promise.all([
api.getPerson(dbId, personId),
api.getDatabase(dbId),
api.getScrapedData(personId).catch(() => null),
api.hasPhoto(personId).catch(() => ({ exists: false })),
api.getAugmentation(personId).catch(() => null),
api.hasWikiPhoto(personId).catch(() => ({ exists: false })),
api.hasAncestryPhoto(personId).catch(() => ({ exists: false })),
api.hasWikiTreePhoto(personId).catch(() => ({ exists: false })),
api.hasLinkedInPhoto(personId).catch(() => ({ exists: false })),
])
.then(async ([personData, dbData, _scraped, photoCheck, augment, wikiPhotoCheck, ancestryPhotoCheck, wikiTreePhotoCheck, linkedInPhotoCheck]) => {
if (signal.aborted) return;
setPerson(personData);
setDatabase(dbData);
setPhotoStatus({
primary: photoCheck?.exists ?? false,
fs: (photoCheck as { exists: boolean; fsExists?: boolean })?.fsExists ?? false,
wiki: wikiPhotoCheck?.exists ?? false,
ancestry: ancestryPhotoCheck?.exists ?? false,
wikitree: wikiTreePhotoCheck?.exists ?? false,
linkedin: linkedInPhotoCheck?.exists ?? false,
});
setAugmentation(augment);
// Collect all family member IDs for batch photo check
const validParentIds = personData.parents.filter((id): id is string => id != null);
const allFamilyIds: string[] = [
...validParentIds,
...(personData.spouses || []),
...personData.children,
];
// Fetch parent data
if (validParentIds.length > 0) {
const parentResults = await Promise.all(
validParentIds.map((pid: string) => api.getPerson(dbId, pid).catch(() => null))
);
if (signal.aborted) return;
const parents: Record<string, PersonWithId> = {};
parentResults.forEach((p: PersonWithId | null, idx: number) => {
if (p) parents[validParentIds[idx]] = p;
});
setParentData(parents);
}
// Fetch spouse data
if (personData.spouses && personData.spouses.length > 0) {
const spouseResults = await Promise.all(
personData.spouses.map((sid: string) => api.getPerson(dbId, sid).catch(() => null))
);
if (signal.aborted) return;
const spouses: Record<string, PersonWithId> = {};
spouseResults.forEach((s: PersonWithId | null, idx: number) => {
if (s && personData.spouses) spouses[personData.spouses[idx]] = s;
});
setSpouseData(spouses);
}
// Fetch children data
if (personData.children.length > 0) {
const childResults = await Promise.all(
personData.children.map((cid: string) => api.getPerson(dbId, cid).catch(() => null))
);
if (signal.aborted) return;
const children: Record<string, PersonWithId> = {};
childResults.forEach((c: PersonWithId | null, idx: number) => {
if (c) children[personData.children[idx]] = c;
});
setChildData(children);
}
// Check photos for all family members (batch)
if (allFamilyIds.length > 0) {
const photoChecks = await Promise.all(
allFamilyIds.map((id: string) => api.hasPhoto(id).then(r => ({ id, exists: r?.exists ?? false })).catch(() => ({ id, exists: false })))
);
if (signal.aborted) return;
const photos: Record<string, boolean> = {};
photoChecks.forEach(({ id, exists }) => { photos[id] = exists; });
setFamilyPhotos(photos);
}
// Check for cached lineage
const cached = getCachedLineage(dbId, personId);
if (cached) {
setLineage(cached);
}
})
.catch(err => {
if (signal.aborted) return;
setError(err.message);
})
.finally(() => {
if (!signal.aborted) setLoading(false);
});
return () => controller.abort();
}, [dbId, personId]);
const calculateLineage = async () => {
if (!dbId || !personId || !database?.rootId) return;
if (database.rootId === personId) return;
setLineageLoading(true);
const result = await api.findPath(dbId, personId, database.rootId, 'shortest')
.catch(() => null);
if (result) {
setLineage(result);
setCachedLineage(dbId, personId, result);
}
setLineageLoading(false);
};
const handleScrape = async () => {
if (!personId) return;
setScrapeLoading(true);
const data = await api.scrapePerson(personId)
.catch(err => {
toast.error(err.message);
return null;
});
if (data) {
setPhotoStatus(prev => ({ ...prev, primary: !!data.photoPath }));
toast.success('Person data scraped successfully');
}
setScrapeLoading(false);
};
const handleLinkPlatform = async (platform: 'wikipedia' | 'ancestry' | 'wikitree' | 'linkedin', url: string) => {
if (!personId || !url.trim()) return;
setLinkingLoading(true);
const linkFn = platform === 'wikipedia' ? api.linkWikipedia
: platform === 'ancestry' ? api.linkAncestry
: platform === 'linkedin' ? api.linkLinkedIn
: api.linkWikiTree;
const data = await linkFn(personId, url.trim())
.catch(err => {
toast.error(err.message);
return null;
});
if (data) {
setAugmentation(data);
// Check for photo from the linked platform
const photoCheckFn = platform === 'wikipedia' ? api.hasWikiPhoto
: platform === 'ancestry' ? api.hasAncestryPhoto
: platform === 'linkedin' ? api.hasLinkedInPhoto
: api.hasWikiTreePhoto;
const photoExists = await photoCheckFn(personId).catch(() => ({ exists: false }));
const photoKey = platform === 'wikipedia' ? 'wiki'
: platform === 'ancestry' ? 'ancestry'
: platform === 'linkedin' ? 'linkedin'
: 'wikitree';
setPhotoStatus(prev => ({ ...prev, [photoKey]: photoExists?.exists ?? false }));
setLinkingPlatform(null);
toast.success(`${platform.charAt(0).toUpperCase() + platform.slice(1)} linked successfully`);
}
setLinkingLoading(false);
};
const handleFetchPhotoFromPlatform = async (platform: string) => {
if (!personId) return;
setFetchingPhotoFrom(platform);
const data = await api.fetchPhotoFromPlatform(personId, platform)
.catch(err => {
toast.error(err.message);
return null;
});
if (data) {
setAugmentation(data);
await refreshPhotoState();
toast.success(`Photo fetched from ${platform}`);
}
setFetchingPhotoFrom(null);
};
const handleMakeRoot = async () => {
if (!personId) return;
setMakeRootLoading(true);
const newRoot = await api.createRoot(personId).catch(err => {
toast.error(err.message);
return null;
});
if (newRoot) {
toast.success(`"${newRoot.rootName}" is now a root entry point`);
// Refresh sidebar to show the new root database
await refreshDatabases();
// Expand the new database in the sidebar
expandDatabase(newRoot.id);
// Navigate to the new root's person page
navigate(`/person/${newRoot.id}/${personId}`);
}
setMakeRootLoading(false);
};
const handleSyncFromFamilySearch = async () => {
if (!dbId || !personId) return;
setSyncLoading(true);
const result = await api.syncFromFamilySearch(dbId, personId).catch(err => {
toast.error(err.message);
return null;
});
if (result) {
if (result.wasRedirected) {
// Person was merged/redirected on FamilySearch
toast.success(
`Person was merged on FamilySearch: ${result.originalFsId} → ${result.newFsId}${result.survivingPersonName ? ` (${result.survivingPersonName})` : ''}. ID mappings updated.`,
{ duration: 6000 }
);
// Refresh the identities to show the updated FamilySearch ID
api.getIdentities(dbId, personId).then(data => {
setCanonicalId(data.canonicalId);
setExternalIdentities(data.identities);
}).catch(() => null);
} else {
toast.success('Person is up to date with FamilySearch');
}
// Also scrape photo from FamilySearch as part of download
const scrapeToastId = toast.loading('Scraping FamilySearch page for photo...');
const scrapeData = await api.scrapePerson(personId).catch(err => {
toast.error(`Scraping failed: ${err.message}`, { id: scrapeToastId });
return null;
});
if (scrapeData) {
const parts: string[] = [];
if (scrapeData.fullName) parts.push(`Name: ${scrapeData.fullName}`);
if (scrapeData.birthDate) parts.push(`Birth: ${scrapeData.birthDate}`);
if (scrapeData.deathDate) parts.push(`Death: ${scrapeData.deathDate}`);
if (scrapeData.photoPath) {
setPhotoStatus(prev => ({ ...prev, primary: true, fs: true }));
setPhotoVersion(Date.now()); // Bust browser cache to show new photo
parts.push('Photo downloaded');
}
if (parts.length > 0) {
toast.success(`Scraped: ${parts.join(', ')}`, { id: scrapeToastId, duration: 5000 });
} else {
toast.dismiss(scrapeToastId);
toast('No additional data found on FamilySearch page', { icon: 'ℹ️' });
}
}
}
setSyncLoading(false);
};
const handleProcessAncestryHints = async () => {
if (!dbId || !personId) return;
setHintsProcessing(true);
const result = await api.processAncestryHints(dbId, personId).catch(err => {
toast.error(`Failed to process hints: ${err.message}`);
return null;
});
if (result) {
if (result.hintsProcessed > 0) {
toast.success(`Processed ${result.hintsProcessed} free hints on Ancestry`);
// Refresh data from Ancestry after processing hints
await handleRefreshProvider('ancestry');
} else if (result.hintsFound === 0) {
toast('No free hints available', { icon: 'ℹ️' });
} else if (result.errors.length > 0) {
toast.error(`Hints processing failed: ${result.errors[0]}`);
}
}
setHintsProcessing(false);
};
const handleRefreshProvider = async (provider: 'ancestry' | 'wikitree' | 'familysearch') => {
if (!dbId || !personId) return;
await api.refreshFromProvider(dbId, personId, provider).catch(() => null);
};
// =============================================================================
// LOCAL OVERRIDE HANDLERS
// =============================================================================
const refreshOverrides = useCallback(async () => {
if (!dbId || !personId) return;
const [newOverrides, newClaims] = await Promise.all([
api.getPersonOverrides(dbId, personId).catch(() => null),
api.getPersonClaims(dbId, personId).catch(() => []),
]);
if (newOverrides) setOverrides(newOverrides);
setClaims(newClaims);
}, [dbId, personId]);
// Refresh photo state after setting a new primary photo
const refreshPhotoState = useCallback(async () => {
if (!personId) return;
const [photoCheck, wikiPhotoCheck, ancestryPhotoCheck, wikiTreePhotoCheck, linkedInPhotoCheck] = await Promise.all([
api.hasPhoto(personId).catch(() => ({ exists: false })),
api.hasWikiPhoto(personId).catch(() => ({ exists: false })),
api.hasAncestryPhoto(personId).catch(() => ({ exists: false })),
api.hasWikiTreePhoto(personId).catch(() => ({ exists: false })),
api.hasLinkedInPhoto(personId).catch(() => ({ exists: false })),
]);
setPhotoStatus({
primary: photoCheck?.exists ?? false,
fs: (photoCheck as { exists: boolean; fsExists?: boolean })?.fsExists ?? false,
wiki: wikiPhotoCheck?.exists ?? false,
ancestry: ancestryPhotoCheck?.exists ?? false,
wikitree: wikiTreePhotoCheck?.exists ?? false,
linkedin: linkedInPhotoCheck?.exists ?? false,
});
// Increment photo version to bust browser cache
setPhotoVersion(Date.now());
}, [personId]);
const handleSavePersonField = useCallback(async (fieldName: string, value: string, originalValue: string | null) => {
if (!dbId || !personId) return;
await api.setPersonOverride(dbId, personId, {
entityType: 'person',
fieldName,
value,
originalValue,
});
await refreshOverrides();
// Refresh person data to show new values
const newPerson = await api.getPerson(dbId, personId);
if (newPerson) setPerson(newPerson);
toast.success('Saved');
}, [dbId, personId, refreshOverrides]);
const handleRevertPersonField = useCallback(async (fieldName: string) => {
if (!dbId || !personId) return;
await api.revertPersonOverride(dbId, personId, {
entityType: 'person',
fieldName,
});
await refreshOverrides();
toast.success('Reverted to original');
}, [dbId, personId, refreshOverrides]);
const handleSaveVitalEventField = useCallback(async (eventType: string, fieldName: string, value: string, originalValue: string | null) => {
if (!dbId || !personId) return;
await api.setPersonOverride(dbId, personId, {
entityType: 'vital_event',
fieldName: `${eventType}_${fieldName}`,
value,
originalValue,
});
await refreshOverrides();
toast.success('Saved');
}, [dbId, personId, refreshOverrides]);
const handleRevertVitalEventField = useCallback(async (eventType: string, fieldName: string) => {
if (!dbId || !personId) return;
await api.revertPersonOverride(dbId, personId, {
entityType: 'vital_event',
fieldName: `${eventType}_${fieldName}`,
});
await refreshOverrides();
toast.success('Reverted to original');
}, [dbId, personId, refreshOverrides]);
const handleAddClaim = useCallback(async (predicate: string, value: string) => {
if (!dbId || !personId) return;
await api.addPersonClaim(dbId, personId, predicate, value);
await refreshOverrides();
// Refresh person data
const newPerson = await api.getPerson(dbId, personId);
if (newPerson) setPerson(newPerson);
toast.success('Added');
}, [dbId, personId, refreshOverrides]);
const handleDeleteClaim = useCallback(async (claimId: string) => {
if (!dbId || !personId) return;
await api.deletePersonClaim(dbId, personId, claimId);
await refreshOverrides();
// Refresh person data
const newPerson = await api.getPerson(dbId, personId);
if (newPerson) setPerson(newPerson);
toast.success('Deleted');
}, [dbId, personId, refreshOverrides]);
// Called when a field value is applied from provider data (e.g., "Use" button)
const handleFieldApplied = useCallback(async () => {
await refreshOverrides();
// Refresh person data to show the new value in the SparseTree row
if (!dbId || !personId) return;
const newPerson = await api.getPerson(dbId, personId);
if (newPerson) setPerson(newPerson);
}, [dbId, personId, refreshOverrides]);
// =============================================================================
// HELPER FUNCTIONS FOR OVERRIDES
// =============================================================================
// Get override for a person field
const getPersonOverride = (fieldName: string) => {
return overrides?.personOverrides?.find(o => o.fieldName === fieldName);
};
// Get override for a vital event field (stored as eventType_fieldName, e.g., birth_date)
const getVitalEventOverride = (eventType: string, fieldName: string) => {
return overrides?.eventOverrides?.find(o => o.fieldName === `${eventType}_${fieldName}`);
};
// Build VitalEventOverrides object for a given event type
const buildVitalEventOverrides = (eventType: string): VitalEventOverrides => {
const dateOverride = getVitalEventOverride(eventType, 'date');
const placeOverride = getVitalEventOverride(eventType, 'place');
return {
date: dateOverride ? {
value: dateOverride.overrideValue,
originalValue: dateOverride.originalValue,
isOverridden: true,
} : undefined,
place: placeOverride ? {
value: placeOverride.overrideValue,
originalValue: placeOverride.originalValue,
isOverridden: true,
} : undefined,
};
};
// Build ListItem array from claims for EditableList
const buildClaimsListItems = (predicate: string): ListItem[] => {
return claims
.filter(c => c.predicate === predicate)
.map(c => ({
id: c.claimId,
value: c.value,
source: c.source,
isOverridden: c.isOverridden,
originalValue: c.originalValue,
}));
};
if (loading) {
return <div className="text-center py-8 text-app-text-muted">Loading person...</div>;
}
if (error || !person) {
return <div className="text-center py-8 text-app-error">Error: {error || 'Person not found'}</div>;
}
const isRoot = database?.rootId === personId;
const generations = lineage ? lineage.path.length - 1 : 0;
const relationship = isRoot ? 'Root Person (You)' : lineage ? getRelationshipLabel(generations) : null;
// Photo priority: Primary (user-selected) > Ancestry > WikiTree > LinkedIn > Wiki > FamilySearch
// Add cache-busting timestamp to force refresh after changing photos
const cacheBuster = photoVersion > 0 ? photoVersion : undefined;
// Photo priority: Primary > Ancestry > WikiTree > LinkedIn > Wiki
const photoUrl = photoStatus.primary
? api.getPhotoUrl(personId!, cacheBuster)
: photoStatus.ancestry
? api.getAncestryPhotoUrl(personId!, cacheBuster)
: photoStatus.wikitree
? api.getWikiTreePhotoUrl(personId!, cacheBuster)
: photoStatus.linkedin
? api.getLinkedInPhotoUrl(personId!, cacheBuster)
: photoStatus.wiki
? api.getWikiPhotoUrl(personId!, cacheBuster)
: null;
// Get primary description from augmentation
const wikiDescription = augmentation?.descriptions?.find(d => d.source === 'wikipedia')?.text;
// Get Wikipedia platform info
const wikiPlatform = augmentation?.platforms?.find(p => p.platform === 'wikipedia');
// Helper to format ID for display (show abbreviated)
const formatIdForDisplay = (id: string) => {
if (id.length > 12) return `${id.slice(0, 8)}...`;
return id;
};
// Get external ID by source
const getExternalId = (source: string) => {
return externalIdentities.find(i => i.source === source)?.externalId;
};
const fsId = getExternalId('familysearch') || person?.externalId;
const ancestryId = getExternalId('ancestry');
const wikiTreeId = getExternalId('wikitree');
return (
<div className="h-full flex flex-col p-6">
{/* Header - Mobile-friendly layout */}
<div className="mb-4">
{/* Mobile: stacked, Desktop: side-by-side */}
<div className="flex flex-col sm:flex-row gap-4">
{/* Profile Photo */}
<div className="flex-shrink-0 flex justify-center sm:justify-start">
{photoUrl ? (
<img
src={photoUrl}
alt={person.name}
className="w-28 h-28 sm:w-24 sm:h-24 rounded-lg object-cover border border-app-border"
/>
) : (
<div className="w-28 h-28 sm:w-24 sm:h-24 rounded-lg bg-app-card border border-app-border flex items-center justify-center">
<User size={36} className="text-app-text-subtle" />
</div>
)}
</div>
{/* Name, lifespan, and IDs */}
<div className="flex-1 min-w-0 text-center sm:text-left">
{/* Name row */}
<div className="flex flex-wrap items-center justify-center sm:justify-start gap-2 mb-1">
<EditableField
value={getPersonOverride('display_name')?.overrideValue ?? person.name}
originalValue={person.name}
isOverridden={!!getPersonOverride('display_name')}
onSave={async (value) => { await handleSavePersonField('display_name', value, person.name); }}
onRevert={async () => { await handleRevertPersonField('display_name'); }}
displayClassName="text-xl sm:text-2xl font-bold"
inputClassName="text-xl sm:text-2xl font-bold"
placeholder="Enter name..."
className="flex-shrink min-w-0"
/>
{person.gender && person.gender !== 'unknown' && (
<span className={`px-2 py-0.5 rounded text-xs ${
person.gender === 'male' ? 'bg-app-male-subtle text-app-male' : 'bg-app-female-subtle text-app-female'
}`}>
{person.gender === 'male' ? 'M' : 'F'}
</span>
)}
<FavoriteButton dbId={dbId!} personId={personId!} personName={person.name} />
</div>
{/* Lifespan */}
<p className="text-sm text-app-text-muted mb-2">
{person.lifespan.endsWith('-') ? `${person.lifespan}Living` : person.lifespan}
</p>
{/* IDs - compact grid on mobile */}
<div className="flex flex-wrap items-center justify-center sm:justify-start gap-2 text-xs">
{canonicalId && (
<button
onClick={() => { navigator.clipboard.writeText(canonicalId); toast.success('Copied ID'); }}
className="font-mono flex items-center gap-0.5 text-app-text-subtle hover:text-app-text transition-colors"
title={`Copy ${canonicalId}`}
>
{formatIdForDisplay(canonicalId)}
<Copy size={10} />
</button>
)}
{fsId && (
<a
href={`https://www.familysearch.org/tree/person/details/${fsId}`}
target="_blank"
rel="noopener noreferrer"
className="text-sky-600 dark:text-sky-400 hover:underline flex items-center gap-0.5"
>
FS: {fsId}
<ExternalLink size={10} />
</a>
)}
{ancestryId && (
<button
onClick={() => { navigator.clipboard.writeText(ancestryId); toast.success('Copied Ancestry ID'); }}
className="text-emerald-600 dark:text-emerald-400 flex items-center gap-0.5 hover:underline"
title={`Copy ${ancestryId}`}
>
Anc: {ancestryId.length > 10 ? `${ancestryId.slice(0, 8)}...` : ancestryId}
<Copy size={10} />
</button>
)}
{wikiTreeId && (
<button
onClick={() => { navigator.clipboard.writeText(wikiTreeId); toast.success('Copied WikiTree ID'); }}
className="text-purple-600 dark:text-purple-400 flex items-center gap-0.5 hover:underline"
title={`Copy ${wikiTreeId}`}
>
WT: {wikiTreeId}
<Copy size={10} />
</button>
)}
</div>
</div>
</div>
{/* Action buttons - below on mobile, separate row */}
<div className="flex flex-wrap items-center justify-center sm:justify-start gap-2 mt-3 pt-3 border-t border-app-border/50 sm:border-0 sm:pt-0 sm:mt-2">
{isRoot && (
<span className="px-2 py-1 bg-app-success/20 text-app-success rounded text-xs font-medium">
Root Person
</span>
)}
{lineage && !isRoot && (
<span className="px-2 py-1 bg-app-accent/20 text-app-accent rounded text-xs font-medium">
{relationship}
</span>
)}
{!lineage && !isRoot && (
<button
onClick={calculateLineage}
disabled={lineageLoading}
className="px-2 py-1 bg-app-accent/20 text-app-accent rounded text-xs font-medium hover:bg-app-accent/30 transition-colors disabled:opacity-50 flex items-center gap-1"
>
{lineageLoading ? (
<Loader2 size={12} className="animate-spin" />
) : (
<GitBranch size={12} />
)}
Lineage
</button>
)}
{!isRoot && (
<button
onClick={handleMakeRoot}
disabled={makeRootLoading}
className="flex items-center gap-1 px-2 py-1 bg-app-success/20 text-app-success rounded text-xs hover:bg-app-success/30 transition-colors disabled:opacity-50"
title="Make this person a root entry point"
>
{makeRootLoading ? (
<Loader2 size={12} className="animate-spin" />
) : (
<TreeDeciduous size={12} />
)}
Root
</button>
)}
<Link
to={`/tree/${dbId}/${personId}`}
className="px-2 py-1 text-app-text-muted hover:text-app-accent hover:bg-app-hover rounded flex items-center gap-1 text-xs transition-colors"
>
<GitBranch size={12} />
Tree
</Link>
</div>
</div>
{/* Main content - compact layout */}
<div className="flex-1 space-y-3">
{/* Compact Vital Events + Family */}
<div className="bg-app-card rounded-lg border border-app-border p-3">
{/* Vital Events - stack on mobile, row on desktop */}
<div className="flex flex-col sm:flex-row sm:flex-wrap gap-2 sm:gap-x-6 sm:gap-y-2 text-sm">
{/* Birth */}
<div className="flex items-center gap-2">
<Calendar size={14} className="text-app-success shrink-0" />
<span className="text-app-text-muted">Birth:</span>
<EditableDate
value={buildVitalEventOverrides('birth').date?.value ?? person.birth?.date}
originalValue={person.birth?.date}
isOverridden={buildVitalEventOverrides('birth').date?.isOverridden ?? false}
onSave={(value) => handleSaveVitalEventField('birth', 'date', value, person.birth?.date ?? null)}
onRevert={() => handleRevertVitalEventField('birth', 'date')}
emptyText="—"
compact
/>
{person.birth?.place && (
<span className="text-app-text-subtle text-xs truncate max-w-[150px]" title={person.birth.place}>
• {person.birth.place}
</span>
)}
</div>
{/* Death */}
<div className="flex items-center gap-2">
<Calendar size={14} className="text-app-error shrink-0" />
<span className="text-app-text-muted">Death:</span>
<EditableDate
value={buildVitalEventOverrides('death').date?.value ?? person.death?.date}
originalValue={person.death?.date}
isOverridden={buildVitalEventOverrides('death').date?.isOverridden ?? false}
onSave={(value) => handleSaveVitalEventField('death', 'date', value, person.death?.date ?? null)}
onRevert={() => handleRevertVitalEventField('death', 'date')}
emptyText="Living"
compact
/>
{person.death?.place && (
<span className="text-app-text-subtle text-xs truncate max-w-[150px]" title={person.death.place}>
• {person.death.place}
</span>
)}
</div>
{/* Burial */}
{(person.burial?.date || person.burial?.place) && (
<div className="flex items-center gap-2">
<MapPin size={14} className="text-app-text-muted shrink-0" />
<span className="text-app-text-muted">Burial:</span>
{person.burial?.date && (
<span className="text-app-text text-sm">{person.burial.date}</span>
)}
{person.burial?.place && (
<span className="text-app-text-subtle text-xs truncate max-w-[150px]" title={person.burial.place}>
{person.burial.date ? '• ' : ''}{person.burial.place}
</span>
)}
</div>
)}
</div>
{/* Family - Parents/Spouses/Children as compact cards */}
<div className="mt-3 pt-3 border-t border-app-border/50 grid grid-cols-1 md:grid-cols-3 gap-3">
{/* Parents */}
<div className="flex flex-wrap items-start gap-2 md:flex-col md:items-start md:gap-2 md:bg-app-bg/30 md:border md:border-app-border/50 md:rounded-lg md:p-2">
<div className="flex items-center justify-between gap-2 text-xs text-app-text-muted w-16 shrink-0 pt-2 md:w-full md:pt-0 md:pb-1 md:border-b md:border-app-border/40">
<div className="flex items-center gap-1">
<Users size={12} />
Parents
</div>
{person.parents.filter(id => id != null).length < 2 && (
<button
type="button"
className="text-[10px] text-app-accent hover:underline"
title="Add or link a parent"
onClick={() => {
const hasFather = person.parents[0] != null;
setRelationshipModalType(hasFather ? 'mother' : 'father');
}}
>
+ Add
</button>
)}
</div>
{person.parents.some(id => id != null) ? (
<div className="flex flex-wrap gap-1.5 flex-1">
{person.parents.map((parentId, idx) => parentId ? (
<FamilyMemberCard
key={parentId}
id={parentId}
person={parentData[parentId]}
dbId={dbId!}
hasPhoto={familyPhotos[parentId] ?? false}
gender={parentData[parentId]?.gender === 'male' ? 'male' : parentData[parentId]?.gender === 'female' ? 'female' : (idx === 0 ? 'male' : 'female')}