-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmentionsEditor.js
More file actions
1378 lines (1242 loc) · 52.9 KB
/
Copy pathmentionsEditor.js
File metadata and controls
1378 lines (1242 loc) · 52.9 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
/**
* MentionsEditor
* Displays a scrollable, scored list of candidate mentions for a target person,
* with a detail panel showing the score breakdown and all mention fields,
* and a footer "Add to person" action.
*
* Usage:
* const editor = new MentionsEditor(document.getElementById('mentions-editor'), {
* criteria: { ... }, // optional override of default weights
* onAdd: (personId, mentionId) => {...} // called when "Add to person" is clicked
* });
* editor.load(targetPerson, sources);
*/
class MentionsEditor {
static FIELD_LABELS = {
mention_id: "Mention ID",
source: "Source",
full_name: "Full name",
first_name: "First name",
middle_name: "Middle name",
last_name: "Last name",
birth_year: "Birth year",
death_year: "Death year",
gender: "Gender",
legal_status: "Legal status",
is_enslaver: "Is enslaver",
norm_occupation: "Norm occupation",
location_id: "Location ID",
enslaver_id: "Enslaver ID",
household_id: "Household ID",
family_id: "Family ID",
confidence: "Confidence"
};
static FACTOR_LABELS = {
smartName: "Smart name",
exactLastName: "Exact last",
fuzzyLastName: "Fuzzy last",
rarityLastName: "Rare last",
exactFirstName: "Exact first",
fuzzyFirstName: "Fuzzy first",
rarityFirstName: "Rare first",
exactNysiisLast: "NYSIIS",
fuzzyNysiisLast: "Fuzzy",
rarityNysiisLast: "Rare",
exactSoundexLast: "Soundex",
fuzzySoundexLast: "Fuzzy",
raritySoundexLast: "Rare",
birthYear: "Birth Year",
deathYear: "Death Year",
familyMember: "Relative match",
householdContinuity: "Family",
familyBoost: "Family Boost",
race: "Race",
gender: "Gender",
suffix: "Suffix",
middle_name: "Middle name",
norm_first_name: "Nick name",
enslaverHolding: "Enslaver holding",
proximityFit: "Nearness fit",
cohortFit: "Cohort fit"
};
static FACTOR_COLORS = {
smartName: 'c-blue',
exactLastName: 'c-teal',
fuzzyLastName: 'c-teal',
rarityLastName: 'c-teal',
exactFirstName: 'c-purple',
fuzzyFirstName: 'c-purple',
rarityFirstName: 'c-purple',
exactNysiisLast: 'c-coral',
fuzzyNysiisLast: 'c-coral',
rarityNysiisLast: 'c-coral',
exactSoundexLast: 'c-coral',
fuzzySoundexLast: 'c-coral',
raritySoundexLast: 'c-coral',
birthYear: 'c-blue',
deathYear: 'c-blue',
familyMember: 'c-purple',
householdContinuity: 'c-purple',
familyBoost: 'c-green',
knockout: 'c-pink',
race: 'c-pink',
gender: 'c-pink',
suffix: 'c-pink',
middle_name: 'c-purple',
norm_first_name: 'c-purple',
enslaverHolding: 'c-amber',
proximityFit: 'c-teal',
cohortFit: 'c-blue'
};
static RAMP = {
'c-purple': ['#EEEDFE', '#26215C'],
'c-teal': ['#E1F5EE', '#04342C'],
'c-coral': ['#FAECE7', '#4A1B0C'],
'c-pink': ['#FBEAF0', '#4B1528'],
'c-gray': ['#F1EFE8', '#2C2C2A'],
'c-blue': ['#E6F1FB', '#042C53'],
'c-amber': ['#FCEFD9', '#4A2E07'],
'c-green': ['#E5F4E9', '#0F3D1F']
};
/**
* @param {HTMLElement} container - element to render into
* @param {Object} options
* @param {Function} [options.onAdd] - callback(personId, mentionId)
* @param {Function} [options.onRemove] - callback(personId, mentionId)
*/
constructor(container, options = {}) {
app.mentionsEditor = this;
this.container = container;
this.onAdd = options.onAdd || (() => { });
this.onRemove = options.onRemove || null;
this.targetPerson = null;
this.sources = [];
this.isSearchResult = false;
this.matches = []; // [{ id, score, mention, factors }]
this.currentMentionId = null;
this._renderShell();
}
// ---------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------
/**
* Load a target person and a list of sources, build the match list, and render.
* @param {Object} targetPerson - person object matching Person data format
* @param {Array} sources - list of source identifiers/types to search
* @param {Array} [mentions] - optional pre-fetched mention list (skips fetchAssertions)
*/
async load(targetPerson, sources, mentions = null, factors = null) {
this.targetPerson = targetPerson;
this.sources = sources;
this.factors = factors;
this.currentMentionId = null;
this.isSearchResult = !!((factors && factors.length > 0) || (mentions && mentions.length > 0));
let candidateMentions = mentions;
if (!this.isSearchResult) {
const globalApp = window.app || (typeof app !== 'undefined' ? app : null);
let person = targetPerson;
let personId = null;
if (globalApp && globalApp.curPerson !== undefined && globalApp.curPerson !== -1 && window.treeApp && window.treeApp.state && window.treeApp.state.nodes) {
const node = window.treeApp.state.nodes[globalApp.curPerson];
if (node) personId = node.person_id;
}
if (!personId && window.treeApp && window.treeApp.state && window.treeApp.state.selectedPid) {
personId = window.treeApp.state.selectedPid;
}
if (!personId && targetPerson) {
personId = targetPerson.person_id;
}
if (personId && globalApp && globalApp.curTree && globalApp.curTree.persons) {
const persons = globalApp.curTree.persons;
const found = Array.isArray(persons) ? persons.find(p => p.person_id === personId) : persons[personId];
if (found) person = found;
}
const associatedIds = person.mentions || [];
candidateMentions = associatedIds
.map(id => {
if (typeof id === 'object') return id;
if (!globalApp || !globalApp.mentions) return null;
return globalApp.mentions.find(m => m.mention_id === id);
})
.filter(Boolean);
}
this.matches = this._buildMatchList(candidateMentions);
if (this.matches.length > 0) {
this.currentMentionId = this.matches[0].mention.mention_id;
}
this._renderList();
this._renderDetail();
this.scrollToTop();
setTimeout(() => this.scrollToTop(), 10);
setTimeout(() => this.scrollToTop(), 50);
}
scrollToTop() {
if (this.listEl) this.listEl.scrollTop = 0;
if (this.detailEl) this.detailEl.scrollTop = 0;
if (this.container) this.container.scrollTop = 0;
const containerParent = document.getElementById('right-panel-content');
if (containerParent) containerParent.scrollTop = 0;
const mentionsContainer = document.getElementById('mentions-editor-container');
if (mentionsContainer) mentionsContainer.scrollTop = 0;
}
/** Returns the currently selected mention object, or null. */
getCurrentMention() {
const match = this.matches.find(m => m.mention.mention_id === this.currentMentionId);
return match ? match.mention : null;
}
// ---------------------------------------------------------------------
// Scoring
// ---------------------------------------------------------------------
_buildMatchList(mentions) {
const results = [];
const seenIds = new Set();
for (const mention of mentions) {
if (!seenIds.has(mention.mention_id)) {
seenIds.add(mention.mention_id);
results.push({
id: mention.mention_id,
score: mention.score || 0,
mention: mention,
factors: mention.factors || {}
});
}
}
// Group-match results (see Score.SearchGroupMatch) flag a holding the tree
// already links via a known enslaver relationship — keep it pinned first
// regardless of its probabilistic score, since it's not a candidate to rank,
// it's already-established evidence to surface. No-op for regular results,
// which never set _knownLink.
results.sort((a, b) => {
const aKnown = Boolean(a.mention._knownLink);
const bKnown = Boolean(b.mention._knownLink);
if (aKnown !== bKnown) return aKnown ? -1 : 1;
return b.score - a.score;
});
// When showing search results with active factors, filter out non-matching mentions (score <= 0 means no factor matched)
if (this.isSearchResult && this.factors && this.factors.length > 0) {
const hasActiveFactors = this.factors.some(f => {
const cmp = Array.isArray(f.compare) ? f.compare.find(x => x !== 'rare') : f.compare;
return cmp && cmp !== 'ignore';
});
if (hasActiveFactors) {
const positiveResults = results.filter(r => r.score > 0);
if (positiveResults.length > 0) return positiveResults;
}
}
return results;
}
// ---------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------
_renderShell() {
this.container.classList.add('mentions-editor');
this.container.innerHTML = `
<div class="me-panel">
<div class="me-header">
<div>
<p class="me-target-summary"></p>
</div>
<span class="me-count"></span>
</div>
<div class="me-body">
<div class="me-match-list"></div>
<div class="me-detail-panel"></div>
</div>
<div class="me-footer">
<button type="button" class="me-add-person-btn" disabled>Add person to tree</button>
<button type="button" class="me-context-btn" disabled>See context</button>
<button type="button" class="me-add-btn" disabled>Add mention to person</button>
</div>
</div>
<style>${MentionsEditor._css()}</style>
`;
this.listEl = this.container.querySelector('.me-match-list');
this.detailEl = this.container.querySelector('.me-detail-panel');
this.countEl = this.container.querySelector('.me-count');
this.targetSummaryEl = this.container.querySelector('.me-target-summary');
this.addBtn = this.container.querySelector('.me-add-btn');
this.contextBtn = this.container.querySelector('.me-context-btn');
this.addPersonBtn = this.container.querySelector('.me-add-person-btn');
this.addBtn.addEventListener('click', () => this._handleAdd());
this.addPersonBtn.addEventListener('click', () => this._handleAddPerson());
this.contextBtn.addEventListener('click', () => {
if (typeof ShowSource === 'function') {
ShowSource(this.currentMentionId);
} else {
// Fallback: switch to Context tab
$('#right-panel-content .tab-btn[data-target="sources-editor-container"]').click();
}
});
}
_handleAddPerson() {
if (!this.currentMentionId || !window.app || !window.treeApp) return;
const mention = window.app.mentions.find(m => m.mention_id === this.currentMentionId);
if (!mention) return;
const pid = 'P' + Date.now();
const mid = this.currentMentionId;
const targetP = this.targetPerson || (window.app && window.app.targetPerson);
const anchorPid = (targetP && targetP.person_id) || window.treeApp.state.selectedPid;
let relation = (window.app && window.app.curRelation) ? window.app.curRelation : null;
if (relation === 'inFamilyOf' || relation === 'inHouseholdOf') {
relation = null;
}
// Compare birth years to determine predicate if not an explicit kinship relation
if (!relation && targetP) {
const targetBirth = parseInt(String(targetP.birth_year || '').split(':')[0], 10);
const mentionBirth = parseInt(String(mention.birth_year || '').split(':')[0], 10);
if (!isNaN(targetBirth) && !isNaN(mentionBirth)) {
const diff = mentionBirth - targetBirth;
if (Math.abs(diff) <= 13) {
relation = 'isSpouseOf';
} else if (diff > 13) {
relation = 'isChildOf';
} else if (diff < -13) {
relation = 'isParentOf';
}
}
}
// Look up relationship assertion from expand view if relation not resolved by birth years
if (!relation && targetP && targetP.mentions && window.app && window.app.expand) {
for (const tmid of targetP.mentions) {
const view = window.app.expand.viewFor(tmid);
if (view && view.results) {
const match = view.results.find(r => r.mention_id === mid);
if (match && match.predicate && match.predicate !== 'inFamilyOf' && match.predicate !== 'inHouseholdOf') {
relation = match.predicate;
break;
}
}
}
}
if (!relation) {
relation = 'isChildOf';
}
// Reset transient curRelation and targetPerson after use
if (window.app) {
window.app.curRelation = null;
window.app.targetPerson = null;
}
let initX = 200, initY = 200;
if (anchorPid && window.treeApp) {
const sourceNode = window.treeApp.GetNode(anchorPid);
if (sourceNode) {
if (relation === 'isChildOf') {
initY = sourceNode.y + 250;
const spouses = window.treeApp.state.triplets.filter(t => t.predicate === 'isSpouseOf' && (t.subject === anchorPid || t.object === anchorPid));
if (spouses.length > 0) {
const spouseId = spouses[0].subject === anchorPid ? spouses[0].object : spouses[0].subject;
const spouseNode = window.treeApp.GetNode(spouseId);
if (spouseNode) {
initX = (sourceNode.x + spouseNode.x) / 2;
} else {
initX = sourceNode.x;
}
} else {
initX = sourceNode.x;
}
} else if (relation === 'isParentOf') {
initY = Math.max(0, sourceNode.y - 250);
initX = sourceNode.x;
} else {
initY = sourceNode.y;
initX = sourceNode.x + 220;
}
}
}
const fmt = (val) => val ? `${val}:${mid}` : null;
const getVal = (key) => {
return mention[key];
};
const newPerson = {
person_id: pid,
mentions: [mid],
first_name: fmt(getVal('first_name')),
middle_name: fmt(getVal('middle_name')),
last_name: fmt(getVal('last_name')),
suffix: fmt(getVal('suffix')),
birth_year: fmt(getVal('birth_year')),
death_year: fmt(getVal('death_year')),
gender: fmt(getVal('gender')),
race: fmt(getVal('race')),
anchor: anchorPid ? `${relation}:${anchorPid}` : null,
x: initX,
y: initY,
moved: false,
verity: 2
};
if (!window.app.curTree.persons) window.app.curTree.persons = [];
window.app.curTree.persons.push(newPerson);
window.treeApp.AddNode(newPerson);
window.app.rebuildAllRelationships();
if (typeof window.treeApp.ApplyLayout === 'function') {
window.treeApp.ApplyLayout(true);
}
window.treeApp.RenderNodes();
window.treeApp.RenderEdges();
if (typeof window.treeApp.ResetLayout === 'function') {
window.treeApp.ResetLayout();
}
window.app.selectNodeAndShowEditor(pid, 'person-editor-container');
}
_renderList() {
const target = this.targetPerson;
const toTitleCase = (str) => {
if (!str) return '';
return str.toLowerCase().split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
};
const fname = target ? toTitleCase((target.norm_first_name || target.first_name || '').split(':')[0]) : '';
const mname = target ? toTitleCase((target.middle_name || '').split(':')[0]) : '';
const lname = target ? toTitleCase((target.last_name || '').split(':')[0]) : '';
let fullDisplay = [fname, mname, lname].filter(Boolean).join(' ').trim();
if (!fullDisplay && target && target.full_name) {
fullDisplay = toTitleCase(target.full_name.split(':')[0]);
}
if (target) {
const byear = target.birth_year ? String(target.birth_year).split(':')[0] : '?';
const yearStr = byear !== '?' ? `(b. ${MentionsEditor._esc(byear)})` : '';
this.targetSummaryEl.innerHTML = `<div style="display: flex; align-items: center;">${MentionsEditor._getGenderSVG(target.gender, 24, 'green')} <span style="transform: translateY(2px); margin-left: 2px;">${MentionsEditor._esc(fullDisplay)} ${yearStr}</span></div>`;
} else {
this.targetSummaryEl.innerHTML = '';
}
this.countEl.textContent = this.matches.length > 80 ? `Showing top 80 matches` : `${this.matches.length} matches`;
if (this.matches.length === 0) {
this.listEl.innerHTML = `<div class="me-empty">No matches found.</div>`;
return;
}
const matchesToRender = this.matches.slice(0, 80);
// 1850/1860 slave schedules record the enslaved but not who held them by name
// in the row itself — the enslaver is only recoverable via Score's lookup
// (wasEnslavedBy assertion, or same-household head='t' row). Surface it in the
// result row so it doesn't require opening the detail panel.
const globalApp = window.app || (typeof app !== 'undefined' ? app : null);
const isSlaveScheduleSource = (src) => {
if (globalApp && globalApp.score && typeof globalApp.score.isSlaveScheduleSource === 'function') {
return globalApp.score.isSlaveScheduleSource(src);
}
const norm = String(src || '').toUpperCase().replace(/[^A-Z0-9]/g, '');
return norm.includes('SS1850') || norm.includes('SS1860');
};
this.listEl.innerHTML = matchesToRender.map(match => {
const m = match.mention;
const active = m.mention_id === this.currentMentionId;
const sourceLabel = `${m.source_type || ''}`;
// Build the display name cleanly
let displayFirst = m.norm_first_name || m.first_name || '';
let displayMid = m.middle_name || '';
let displayLast = m.last_name || '';
let matchName = [displayFirst, displayMid, displayLast].filter(Boolean).join(' ');
if (!matchName && m.full_name) {
matchName = m.full_name;
}
let enslaverRow = '';
if (isSlaveScheduleSource(m.source) && globalApp && globalApp.score && typeof globalApp.score._getEnslaverName === 'function') {
const enslaverName = globalApp.score._getEnslaverName(m);
if (enslaverName) {
enslaverRow = `<p class="me-match-enslaver">Enslaver: <span class="me-enslaver-name">${MentionsEditor._esc(toTitleCase(enslaverName))}</span></p>`;
}
}
return `
<div class="me-match-item ${active ? 'me-active' : ''}" data-id="${m.mention_id}">
<div class="me-match-row">
<span class="me-match-name">${MentionsEditor._esc(matchName)}
<span class="me-match-score">${Math.round(match.score * 10)}</span>
</span>
<span class="me-source-badge">${MentionsEditor._esc(sourceLabel)}</span>
</div>
<p class="me-match-years">${m.death_year ? `${m.birth_year ?? '?'} – ${m.death_year}` : (m.birth_year ?? '?')}</p>
${enslaverRow}
<p class="me-match-narrative">${MentionsEditor._esc(m.narrative || '')}</p>
</div>
`;
}).join('');
this.listEl.querySelectorAll('.me-match-item').forEach(el => {
el.addEventListener('click', () => {
const id = el.dataset.id;
// mention_id may be numeric or string; compare loosely
this.currentMentionId = this.matches.find(m => String(m.mention.mention_id) === String(id)).mention.mention_id;
this._renderList();
this._renderDetail();
this.detailEl.scrollTop = 0;
});
});
}
_renderDetail() {
const match = this.matches.find(m => m.mention.mention_id === this.currentMentionId);
if (!match) {
this.detailEl.innerHTML = `<div class="me-empty">Select a mention to view details.</div>`;
this.addBtn.disabled = true;
if (this.contextBtn) this.contextBtn.disabled = true;
if (this.addPersonBtn) this.addPersonBtn.disabled = true;
return;
}
const m = match.mention;
const sourceLabel = m.source ? String(m.source).replace(/_/g, '-') : '';
const isScan = Boolean(m.isScanResult || (m.why && m.why.candidates !== undefined) || m.candidates !== undefined);
if (this.targetPerson && this.targetPerson.person_id === -1) {
this.addBtn.style.display = 'none';
if (this.addPersonBtn) this.addPersonBtn.style.display = 'none';
} else {
this.addBtn.style.display = '';
if (this.addPersonBtn) this.addPersonBtn.style.display = '';
}
this.addBtn.disabled = false;
if (this.contextBtn) this.contextBtn.disabled = false;
if (this.addPersonBtn) {
this.addPersonBtn.disabled = false;
let isAlreadyInTree = false;
const globalApp = window.app || (typeof app !== 'undefined' ? app : null);
if (globalApp && globalApp.curTree && globalApp.curTree.persons) {
const persons = Array.isArray(globalApp.curTree.persons) ? globalApp.curTree.persons : Object.values(globalApp.curTree.persons);
isAlreadyInTree = persons.some(p => Array.isArray(p.mentions) && p.mentions.includes(this.currentMentionId));
}
if (isAlreadyInTree) {
this.addPersonBtn.style.visibility = 'hidden';
} else {
this.addPersonBtn.style.visibility = 'visible';
}
}
if (isScan) {
this.addBtn.textContent = `Search in ${sourceLabel || m.source}`;
this.addBtn.style.display = '';
this.addBtn.disabled = false;
if (this.addPersonBtn) this.addPersonBtn.style.display = 'none';
} else if (this.isSearchResult) {
this.addBtn.textContent = "Add mention to person";
} else {
this.addBtn.textContent = "Remove mention from person";
}
const score = Math.round(match.score * 10);
const isSmartNameOn = (window.PersonEditor && window.PersonEditor.userSettings)
? window.PersonEditor.userSettings.useSmartName
: $('#vpe-smart-name-cb').is(':checked');
const nameKeys = [
'exactLastName', 'fuzzyLastName', 'rarityLastName',
'exactFirstName', 'fuzzyFirstName', 'rarityFirstName',
'exactNysiisLast', 'fuzzyNysiisLast', 'rarityNysiisLast',
'exactSoundexLast', 'fuzzySoundexLast', 'raritySoundexLast'
];
const factorToFieldMap = {
exactLastName: 'last_name',
fuzzyLastName: 'last_name',
rarityLastName: 'last_name',
exactFirstName: 'first_name',
fuzzyFirstName: 'first_name',
rarityFirstName: 'first_name',
exactNysiisLast: 'nysiis_last_name',
fuzzyNysiisLast: 'nysiis_last_name',
rarityNysiisLast: 'nysiis_last_name',
exactSoundexLast: 'soundex_last_name',
fuzzySoundexLast: 'soundex_last_name',
raritySoundexLast: 'soundex_last_name',
suffix: 'suffix',
birthYear: 'birth_year',
deathYear: 'death_year',
familyBoost: 'family_boost'
};
const pillsHtml = Object.keys(MentionsEditor.FACTOR_LABELS).map(key => {
if (key === 'householdContinuity') return '';
if (isSmartNameOn && !this.isSearchResult) {
if ((nameKeys.includes(key) && key !== 'rarityLastName') || key === 'suffix') return '';
} else if (this.factors && this.factors.length > 0) {
const fieldKey = factorToFieldMap[key];
if (fieldKey) {
const factorConfig = this.factors.find(f => f.field === fieldKey);
if (factorConfig && factorConfig.compare === 'ignore') return '';
}
}
const factor = match.factors[key];
if (!factor || !factor.value) return '';
const value = Math.round(factor.value * 10);
if (value === 0) return '';
let label = factor.label || MentionsEditor.FACTOR_LABELS[key];
if (key === 'rarityFirstName') {
if (value < 0) label = "Common first";
else if (value === 1 || value === 2) label = "Uncommon first";
else label = "Rare first";
} else if (key === 'rarityLastName') {
if (value < 0) label = "Common last";
else if (value === 1 || value === 2) label = "Uncommon last";
else label = "Rare last";
} else if (key === 'rarityNysiisLast' || key === 'raritySoundexLast') {
if (value < 0) label = "Common";
else if (value === 1 || value === 2) label = "Uncommon";
else label = "Rare";
}
const sign = value > 0 ? '+' : '';
const colorKey = MentionsEditor.FACTOR_COLORS[key] || 'c-gray';
const ramp = MentionsEditor.RAMP[colorKey];
const bg = ramp[0];
const text = ramp[1];
let tooltip = '';
if ((key === 'householdContinuity' || key === 'familyBoost') && factor.matches && factor.matches.length > 0) {
const names = factor.matches.map(m => m.name).join(', ');
tooltip = ` title="Matched family: ${names}"`;
} else if (key === 'knockout') {
tooltip = ` title="${MentionsEditor._esc(factor.reason)}"`;
label = `Knockout: ${factor.reason}`;
value = ''; // Don't show -999 on the pill
}
const displayVal = value !== '' ? ` ${sign}${value}` : '';
return `<span class="me-pill" style="background: ${bg}; color: ${text}; border: 1px solid ${text}22; font-weight: 500;"${tooltip}>${label}${displayVal}</span>`;
}).join('');
const fieldRows = Object.keys(MentionsEditor.FIELD_LABELS).map(key => {
if (key === 'source') return '';
const label = MentionsEditor.FIELD_LABELS[key];
let val = match.mention[key];
if (key.toLowerCase().includes('is_enslave') || key.toLowerCase().includes('isenslave')) {
if (!val) return '';
const strVal = String(val).toLowerCase();
if (strVal !== 't' && strVal !== 'true') return '';
}
if (key === 'gender' && val && val !== '') val = String(val)[0].toUpperCase();
if (val === undefined || val === null || val === '') return '';
return `
<tr>
<td class="me-field-label">${label}</td>
<td class="me-field-value">${MentionsEditor._esc(String(val))}</td>
</tr>
`;
}).join('');
const toTitleCase = (str) => {
if (!str) return '';
return str.toLowerCase().split(' ').map(w => w.charAt(0).toUpperCase() + w.slice(1)).join(' ');
};
let familyHtml = '';
const groupFactor = match.factors && (match.factors.householdContinuity || match.factors.familyBoost);
if (groupFactor && groupFactor.matches) {
const familyMatches = groupFactor.matches;
if (familyMatches.length > 0) {
const famRows = familyMatches.map((f, i) => {
let fullName = f.name || 'Relative';
let byear = '?', dyear = '?';
let enslaverName = f.enslaver_name || f.enslaver || '';
const globalApp = window.app || (typeof app !== 'undefined' ? app : null);
if (globalApp && globalApp.mentions) {
const fMention = globalApp.mentions.find(m => m.mention_id === f.mention_id);
if (fMention) {
let displayFirst = fMention.norm_first_name || fMention.first_name || '';
let displayMid = fMention.middle_name || '';
let displayLast = fMention.last_name || '';
fullName = [displayFirst, displayMid, displayLast].filter(Boolean).join(' ');
if (!fullName && fMention.full_name) {
fullName = fMention.full_name;
}
if (fMention.birth_year) byear = String(fMention.birth_year).split(':')[0];
if (fMention.death_year) dyear = String(fMention.death_year).split(':')[0];
if (!enslaverName && globalApp.score && typeof globalApp.score._getEnslaverName === 'function') {
enslaverName = globalApp.score._getEnslaverName(fMention);
}
}
}
fullName = toTitleCase(fullName.trim() || 'Relative');
let dateStr = '';
if (byear !== '?') {
dateStr = ` (b. ${MentionsEditor._esc(byear)})`;
}
let enslaverStr = '';
if (enslaverName) {
enslaverStr = ` <span class="me-enslaver-name" style="color: #856404; background-color: #fff3cd; border: 1px solid #ffeeba; padding: 1px 6px; border-radius: 3px; font-size: 11px; margin-left: 6px; font-weight: 500;">Enslaver: ${MentionsEditor._esc(toTitleCase(enslaverName))}</span>`;
}
const borderStyle = i < familyMatches.length - 1 ? 'border-bottom: 1px solid rgba(0,0,0,0.05);' : '';
return `
<div class="me-family-row" data-id="${MentionsEditor._esc(f.mention_id)}" style="display: flex; justify-content: space-between; align-items: center; padding: 4px 6px; ${borderStyle} font-size: 13px; cursor: pointer; border-radius: 4px; transition: background-color 0.15s;">
<span>${MentionsEditor._esc(fullName)}${dateStr}${enslaverStr}</span>
<span style="color: #666; font-family: monospace; text-align: right;">${MentionsEditor._esc(f.mention_id)}</span>
</div>
`;
}).join('');
familyHtml = `
<div style="margin-top: 16px;">
<p class="me-raw-label" style="font-weight: 600; font-size: 11px; color: #666; margin-top: 0; margin-bottom: 8px;">FAMILY / GROUP MEMBERS</p>
<div class="me-family-block" style="border: 1px solid #e0e0e0; border-radius: 6px; background-color: #f4f7fa; padding: 8px 6px;">
<div>${famRows}</div>
</div>
</div>
`;
}
}
// Group Match panel (see Score.SearchGroupMatch / GroupMatch.md) — shows the
// GroupMatcher audit trail (component scores + which household members were
// assigned to which) for a slave-schedule holding matched against the target
// person's 1870 family group, instead of the regular per-field factor pills.
let groupMatchHtml = '';
if (match.mention.groupMatch) {
const gm = match.mention.groupMatch;
const comps = gm.components || {};
const compRows = Object.entries(comps).map(([k, v]) => {
const label = k.replace(/([A-Z])/g, ' $1').replace(/^./, str => str.toUpperCase());
const valDisplay = typeof v === 'number' ? v.toFixed(3) : String(v);
return `
<div style="display: flex; justify-content: space-between; font-size: 12px; padding: 2px 4px; border-bottom: 1px solid rgba(0,0,0,0.03);">
<span style="color: #666;">${MentionsEditor._esc(label)}</span>
<span style="font-weight: 500;">${MentionsEditor._esc(valDisplay)}</span>
</div>
`;
}).join('');
const assignRows = (gm.assignments || []).map((a, idx) => {
const borderStyle = idx < gm.assignments.length - 1 ? 'border-bottom: 1px solid rgba(0,0,0,0.05);' : '';
return `
<div style="display: flex; justify-content: space-between; padding: 6px 4px; ${borderStyle} font-size: 12px;">
<div style="display: flex; flex-direction: column;">
<span style="font-weight: 600; color: #333;">${MentionsEditor._esc(a.family)}</span>
<span style="color: #666; font-size: 11px;">Matched to: ${MentionsEditor._esc(a.holding)}</span>
</div>
<div style="align-self: center; font-weight: bold; color: #2e7d4f;">
${Math.round(a.sim * 100)}%
</div>
</div>
`;
}).join('');
const excusalRows = (gm.excusals || []).filter(e => e.weight > 0).map((e, idx, arr) => {
const borderStyle = idx < arr.length - 1 ? 'border-bottom: 1px solid rgba(0,0,0,0.05);' : '';
return `
<div style="display: flex; justify-content: space-between; padding: 4px; ${borderStyle} font-size: 12px;">
<span>${MentionsEditor._esc(e.person)}</span>
<span style="color: #999;">${MentionsEditor._esc(e.code)} (${e.weight})</span>
</div>
`;
}).join('');
const knownBanner = match.mention._knownLink
? `<div style="background:#e6f4ea; border:1px solid #b7dfc0; color:#1e5c2e; border-radius:6px; padding:8px 10px; font-size:12px; margin-bottom:12px;">
Already linked to this person in the family tree. The group-match probability below reflects demographic evidence only — it may be low even for a confirmed relationship (e.g. the enslaved person's own age wasn't recorded in this holding).
</div>`
: '';
groupMatchHtml = `
<div class="me-gm-block" style="margin-top: 16px; border-top: 1px solid var(--me-border); padding-top: 12px;">
<div class="me-gm-header" style="display: flex; align-items: center; cursor: pointer; margin-bottom: 8px; user-select: none;">
<p class="me-raw-label" style="margin: 0; font-weight: 600; font-size: 11px; text-transform: uppercase; color: #666;">Group Match${match.mention._knownLink ? ' — Known Link' : ''}</p>
<span class="me-gm-toggle-icon" style="font-size: 10px; color: #999; margin-left: 6px; transition: transform 0.2s; display: inline-block;">▶</span>
</div>
<div class="me-gm-content" style="display: none;">
${knownBanner}
<div style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px; margin-bottom: 12px;">
<div style="font-size: 12px; font-weight: bold; margin-bottom: 6px; color: #1e293b;">Match Components</div>
<div>${compRows}</div>
</div>
<div style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px; margin-bottom: 12px;">
<div style="font-size: 12px; font-weight: bold; margin-bottom: 6px; color: #1e293b;">Roster Assignments (${gm.assignments ? gm.assignments.length : 0})</div>
<div>${assignRows || '<div style="font-size: 12px; color: #666; font-style: italic;">No assignments</div>'}</div>
</div>
<div style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 10px;">
<div style="font-size: 12px; font-weight: bold; margin-bottom: 6px; color: #1e293b;">Excusals (penalized absences)</div>
<div>${excusalRows || '<div style="font-size: 12px; color: #666; font-style: italic;">None</div>'}</div>
</div>
</div>
</div>
`;
}
// Why / Evidence Breakdown panel (from search.js)
let whyHtml = '';
const whyData = match.mention.why || match.why || (match.factors && match.factors.rung ? match.factors : null);
if (whyData && typeof whyData === 'object') {
const status = match.mention.status || whyData.status || (match.score >= 0.8 ? 'MATCH' : 'MAYBE');
const statusColor = status === 'MATCH' ? '#2e7d4f' : '#b45309';
const statusBg = status === 'MATCH' ? '#e6f4ea' : '#fef3c7';
const margin = whyData.margin != null ? `+${(whyData.margin * 100).toFixed(1)}%` : null;
const paths = Array.isArray(whyData.paths) ? whyData.paths.join(', ') : '';
const rows = [];
if (isScan) {
if (whyData.label || whyData.source) {
rows.push({ label: 'Source', val: whyData.label ? `${whyData.label} (${whyData.source})` : whyData.source });
}
if (whyData.year) {
rows.push({ label: 'Year', val: String(whyData.year) });
}
if (whyData.candidates !== undefined) {
rows.push({ label: 'Candidates Found', val: String(whyData.candidates) });
}
if (whyData.best_rough != null) {
rows.push({ label: 'Best Rough Score', val: `${Math.round(whyData.best_rough * 100)}%` });
}
if (whyData.blocked_reason) {
rows.push({ label: 'Blocked Reason', val: whyData.blocked_reason });
}
} else {
if (whyData.rung) {
rows.push({ label: 'Name Agreement', val: `Rung: ${whyData.rung}` });
}
if (whyData.birth) {
const b = whyData.birth;
const diffStr = (typeof b === 'object' && b.diff != null) ? ` (Δ ${b.diff} yr${b.diff === 1 ? '' : 's'})` : '';
const bScore = (typeof b === 'object' && b.score != null) ? `${Math.round(b.score * 100)}%` : String(b);
rows.push({ label: 'Birth Window Fit', val: `${bScore}${diffStr}` });
}
if (whyData.gender != null) {
rows.push({ label: 'Gender Fit', val: typeof whyData.gender === 'number' ? `${Math.round(whyData.gender * 100)}%` : String(whyData.gender) });
}
if (whyData.race != null) {
rows.push({ label: 'Race Fit', val: typeof whyData.race === 'number' ? `${Math.round(whyData.race * 100)}%` : String(whyData.race) });
}
if (whyData.family != null || whyData.household != null) {
const fVal = whyData.family != null ? whyData.family : whyData.household;
rows.push({ label: 'Household / Kin', val: `${Math.round(fVal * 100)}%` });
}
if (whyData.enslaver && whyData.enslaver.strength > 0) {
rows.push({ label: 'Enslaver Holding Fit', val: `${Math.round(whyData.enslaver.strength * 100)}% (${whyData.enslaver.holding || ''})` });
}
if (whyData.proximity && whyData.proximity.strength > 0) {
rows.push({ label: 'Enumeration Proximity', val: `${Math.round(whyData.proximity.strength * 100)}%` });
}
if (whyData.cohort && whyData.cohort.strength > 0) {
rows.push({ label: 'Cohort Profile Fit', val: `${Math.round(whyData.cohort.strength * 100)}%` });
}
if (paths) {
rows.push({ label: 'Retrieval Paths', val: paths });
}
}
const breakdownRows = rows.map(r => `
<div style="display: flex; justify-content: space-between; font-size: 12px; padding: 4px 6px; border-bottom: 1px solid rgba(0,0,0,0.04);">
<span style="color: #666; font-weight: 500;">${MentionsEditor._esc(r.label)}</span>
<span style="font-weight: 600; color: #1e293b;">${MentionsEditor._esc(r.val)}</span>
</div>
`).join('');
const sectionTitle = isScan ? 'Scan Evidence' : 'Match Evidence (Why)';
whyHtml = `
<div class="me-why-block" style="margin-top: 16px; border-top: 1px solid var(--me-border); padding-top: 12px;">
<div class="me-why-header" style="display: flex; align-items: center; justify-content: space-between; cursor: pointer; margin-bottom: 8px; user-select: none;">
<div style="display: flex; align-items: center; gap: 6px;">
<p class="me-raw-label" style="margin: 0; font-weight: 600; font-size: 11px; text-transform: uppercase; color: #666;">${MentionsEditor._esc(sectionTitle)}</p>
<span class="me-why-toggle-icon" style="font-size: 10px; color: #999; transition: transform 0.2s; display: inline-block;">▼</span>
</div>
<div style="display: flex; gap: 6px; align-items: center;">
<span style="background: ${statusBg}; color: ${statusColor}; border-radius: 4px; padding: 1px 6px; font-size: 11px; font-weight: 700;">${MentionsEditor._esc(status)}</span>
${margin ? `<span style="font-size: 11px; color: #666;">margin: ${MentionsEditor._esc(margin)}</span>` : ''}
</div>
</div>
<div class="me-why-content" style="display: block;">
<div style="background-color: #f8fafc; border: 1px solid #e2e8f0; border-radius: 8px; padding: 6px 8px;">
${breakdownRows || '<div style="font-size: 12px; color: #666; font-style: italic;">No breakdown available</div>'}
</div>
</div>
</div>
`;
}
let combinedBottomHtml = '';
if (familyHtml) {
combinedBottomHtml += `<div style="height: 1px; background: #e0e0e0; margin: 24px 0 0 0;"></div>`;
combinedBottomHtml += familyHtml;
}
if (whyHtml) {
combinedBottomHtml += whyHtml;
}
if (groupMatchHtml) {
combinedBottomHtml += groupMatchHtml;
}
let scanActionHtml = '';
if (isScan) {
scanActionHtml = `
<div style="margin: 16px 0 12px 0;">
<button type="button" class="me-search-source-btn" style="background:#0078d7; color:white; border:none; border-radius:6px; padding:12px 18px; font-size:14px; font-weight:bold; cursor:pointer; width:100%; display:flex; align-items:center; justify-content:center; gap:8px; box-shadow:0 1px 3px rgba(0,0,0,0.15); transition: background 0.2s;">
🔍 Search Candidates in ${MentionsEditor._esc(sourceLabel || m.source)}
</button>
</div>
`;
}
this.detailEl.innerHTML = `
<div class="me-score-row" style="display: flex; justify-content: space-between; align-items: baseline; width: 100%;">
<div>
<span class="me-score-value">${score}</span>
<span class="me-score-label">match score</span>
</div>
<div style="font-weight: bold; font-size: 18px;">
${MentionsEditor._esc(sourceLabel)}
</div>
</div>
<div class="me-factor-pills">${pillsHtml}</div>
<div class="me-narrative-block">
<p>${MentionsEditor._esc(match.mention.narrative || '')}</p>
</div>
<table class="me-field-table">${fieldRows}</table>
${combinedBottomHtml}
${scanActionHtml}
`;
this.detailEl.querySelectorAll('.me-family-row').forEach(el => {
el.addEventListener('mouseenter', (e) => e.currentTarget.style.backgroundColor = '#e2e8f0');
el.addEventListener('mouseleave', (e) => e.currentTarget.style.backgroundColor = 'transparent');
el.addEventListener('click', (e) => {
const id = e.currentTarget.getAttribute('data-id');
const globalApp = window.app || (typeof app !== 'undefined' ? app : null);
if (globalApp && typeof globalApp.editMention === 'function') {
globalApp.editMention(id);
}
});
});
const rawHeader = this.detailEl.querySelector('.me-raw-header');
if (rawHeader) {
rawHeader.addEventListener('click', () => {
const rawJson = this.detailEl.querySelector('.me-raw-json');
const icon = this.detailEl.querySelector('.me-raw-toggle-icon');
if (rawJson.style.display === 'none') {
rawJson.style.display = 'block';
icon.style.transform = 'rotate(90deg)';
} else {
rawJson.style.display = 'none';
icon.style.transform = 'rotate(0deg)';
}
});
}
const whyHeader = this.detailEl.querySelector('.me-why-header');
if (whyHeader) {
whyHeader.addEventListener('click', () => {
const whyContent = this.detailEl.querySelector('.me-why-content');
const icon = this.detailEl.querySelector('.me-why-toggle-icon');
if (whyContent.style.display === 'none') {
whyContent.style.display = 'block';
icon.textContent = '▼';
} else {
whyContent.style.display = 'none';
icon.textContent = '▶';
}
});
}
const gmHeader = this.detailEl.querySelector('.me-gm-header');
if (gmHeader) {
gmHeader.addEventListener('click', () => {
const gmContent = this.detailEl.querySelector('.me-gm-content');
const icon = this.detailEl.querySelector('.me-gm-toggle-icon');