-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule.php
More file actions
2537 lines (2101 loc) · 92.3 KB
/
Copy pathmodule.php
File metadata and controls
2537 lines (2101 loc) · 92.3 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
<?php
/**
* Potts Relationship Context for webtrees.
*
* Shows how the current individual relates to a selected reference person.
*
* @license GPL-3.0-or-later
*/
declare(strict_types=1);
use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\Contracts\UserInterface;
use Fisharebest\Webtrees\Fact;
use Fisharebest\Webtrees\FlashMessages;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\Individual;
use Fisharebest\Webtrees\GedcomRecord;
use Fisharebest\Webtrees\Module\AbstractModule;
use Fisharebest\Webtrees\Module\ModuleConfigInterface;
use Fisharebest\Webtrees\Module\ModuleConfigTrait;
use Fisharebest\Webtrees\Module\ModuleCustomInterface;
use Fisharebest\Webtrees\Module\ModuleCustomTrait;
use Fisharebest\Webtrees\Module\ModuleGlobalInterface;
use Fisharebest\Webtrees\Module\ModuleGlobalTrait;
use Fisharebest\Webtrees\Module\RelationshipsChartModule;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\Services\IndividualFactsService;
use Fisharebest\Webtrees\Services\RelationshipService;
use Fisharebest\Webtrees\Services\TreeService;
use Fisharebest\Webtrees\Tree;
use Fisharebest\Webtrees\Validator;
use Illuminate\Support\Collection;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
return new class extends AbstractModule implements ModuleCustomInterface, ModuleConfigInterface, ModuleGlobalInterface {
use ModuleCustomTrait;
use ModuleConfigTrait;
use ModuleGlobalTrait;
private const VERSION = '1.0.0-beta.1';
private const PREF_SHOW_FACT_LABELS = 'show_fact_relationships';
private const PREF_SHOW_FACTS_SUMMARY = 'show_facts_summary';
private const PREF_SHOW_RELATIONSHIP_PATH = 'show_relationship_path';
private const PREF_USE_ACCOUNT_INDIVIDUAL = 'use_account_individual';
private const PREF_USE_FAVOURITE_INDIVIDUAL = 'use_favourite_individual';
private const PREF_PUBLIC_REFERENCE_XREF = 'public_reference_xref';
private const PREF_FALLBACK_TREE_ROOT = 'fallback_tree_root';
private const PREF_MAX_GENERATIONS = 'max_generations';
private const PREF_LABEL_STYLE = 'label_style';
private const PREF_CARD_STYLE = 'card_style';
private const PREF_SUMMARY_POSITION = 'summary_position';
private const SUMMARY_POSITION_FACTS_PANEL = 'facts-panel';
private const SUMMARY_POSITION_ABOVE_TABS = 'above-tabs';
private const SUMMARY_POSITION_NEAR_TITLE = 'near-title';
private const SUMMARY_POSITION_OFF = 'off';
private const LABEL_STYLE_COMPACT = 'compact';
private const LABEL_STYLE_SENTENCE = 'sentence';
private const CARD_STYLE_THEME = 'theme';
private const CARD_STYLE_POTTS = 'potts';
/** @var array<string,string> */
private const BOOLEAN_PREFERENCES = [
self::PREF_SHOW_FACT_LABELS => '1',
self::PREF_SHOW_FACTS_SUMMARY => '1',
self::PREF_SHOW_RELATIONSHIP_PATH => '1',
self::PREF_USE_ACCOUNT_INDIVIDUAL => '1',
self::PREF_USE_FAVOURITE_INDIVIDUAL => '1',
self::PREF_FALLBACK_TREE_ROOT => '1',
];
public function title(): string
{
return I18N::translate('Potts Relationship Context');
}
public function description(): string
{
return I18N::translate('Shows relationship context between the current individual, the logged-in user and close-relative events.');
}
public function customModuleAuthorName(): string
{
return 'Jason Potts';
}
public function customModuleVersion(): string
{
return self::VERSION;
}
public function headContent(): string
{
$html = '<style>' . $this->styleCss() . '</style>';
if (!$this->isIndividualPageRequest() || $this->isRelationshipsChartRequest()) {
return $html;
}
$individual = $this->currentIndividualFromRequest();
if (!$individual instanceof Individual) {
$html .= $this->statusScript(array_merge([
'enabled' => true,
'version' => self::VERSION,
'serverError' => 'individual-not-found',
], $this->requestDiagnostics()));
return $html;
}
$reference = $this->referenceIndividual($individual->tree());
if (!$reference['individual'] instanceof Individual) {
$html .= $this->statusScript([
'enabled' => true,
'version' => self::VERSION,
'serverError' => 'reference-not-found',
'currentXref' => $individual->xref(),
'currentName' => strip_tags($individual->fullName()),
]);
return $html;
}
$reference_individual = $reference['individual'];
$relationship = $this->relationshipName($reference_individual, $individual);
$relationship_found = $relationship !== '';
if (!$relationship_found) {
$relationship = I18N::translate('relationship not found');
}
$config = [
'enabled' => true,
'version' => self::VERSION,
'currentXref' => $individual->xref(),
'currentName' => strip_tags($individual->fullName()),
'referenceXref' => $reference_individual->xref(),
'referenceName' => strip_tags($reference_individual->fullName()),
'referenceMode' => $reference['mode'],
'referenceIsLoggedInUser' => $reference['mode'] === 'account',
'relationship' => $relationship,
'relationshipFound' => $relationship_found,
'relationshipPathUrl' => $relationship_found ? $this->relationshipPathUrl($reference_individual, $individual) : '',
'showRelationshipPath' => $this->boolPreference(self::PREF_SHOW_RELATIONSHIP_PATH),
'showFactLabels' => $this->boolPreference(self::PREF_SHOW_FACT_LABELS),
'showFactsSummary' => $this->boolPreference(self::PREF_SHOW_FACTS_SUMMARY),
'summaryPosition' => $this->summaryPosition(),
'cardStyle' => $this->cardStyle(),
'labelStyle' => $this->labelStyle(),
'factRelationships' => $this->factRelationshipRows($individual),
];
return $html . $this->injectionScript($config);
}
public function bodyContent(): string
{
return '';
}
/**
* @param array<string,mixed> $config
*/
private function statusScript(array $config): string
{
$json = json_encode($config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR);
return '<script>window.pottsRelationshipContextStatus=' . $json . ';</script>';
}
/**
* @param array<string,mixed> $config
*/
private function injectionScript(array $config): string
{
$json = json_encode($config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_THROW_ON_ERROR);
$script = <<<'JS'
(function(){
const config = CONFIG_PLACEHOLDER;
const status = Object.assign({insertedFactLabels:0}, config);
window.pottsRelationshipContextStatus = status;
function normalise(text) {
return String(text || '').replace(/\s+/g, ' ').trim().toLowerCase();
}
function possessive(name) {
name = String(name || '').trim();
if (!name) {
return '';
}
return /s$/i.test(name) ? name + '’' : name + '’s';
}
function displayRelationship(relationship, capitalise) {
let text = String(relationship || '').replace(/[-_]+/g, ' ').replace(/\s+/g, ' ').trim();
if (!text) {
return '';
}
text = text.toLowerCase();
if (capitalise) {
return text.charAt(0).toUpperCase() + text.slice(1);
}
return text;
}
function relationshipSummarySentence() {
const currentName = String(config.currentName || 'This person').trim();
const relationship = displayRelationship(config.relationship, false);
if (!config.relationshipFound || !relationship || relationship === 'relationship not found') {
if (config.referenceIsLoggedInUser) {
return 'No relationship could be found between you and ' + currentName + '.';
}
if (config.referenceName) {
return 'No relationship could be found between ' + currentName + ' and ' + config.referenceName + '.';
}
return 'No relationship could be found for ' + currentName + '.';
}
if (relationship === 'self' || config.currentXref === config.referenceXref) {
return config.referenceIsLoggedInUser ? 'This is you.' : currentName + ' is the selected reference person.';
}
if (config.referenceIsLoggedInUser) {
return currentName + ' is your ' + relationship + '.';
}
if (config.referenceName) {
return currentName + ' is ' + possessive(config.referenceName) + ' ' + relationship + '.';
}
return currentName + ' is the reference person’s ' + relationship + '.';
}
function factsSummaryStorageKey() {
return 'pottsRelationshipContext.showFactsSummary';
}
function factsSummaryVisible() {
if (!config.showFactsSummary) {
return false;
}
try {
const stored = window.localStorage ? window.localStorage.getItem(factsSummaryStorageKey()) : null;
if (stored === '0') {
return false;
}
if (stored === '1') {
return true;
}
} catch (e) {
// Ignore local-storage failures.
}
return true;
}
function setFactsSummaryVisible(visible) {
document.querySelectorAll('[data-potts-relationship-context="facts-summary"]').forEach(function(element){
element.hidden = !visible;
});
document.querySelectorAll('[data-potts-relationship-context="facts-summary-toggle"]').forEach(function(input){
input.checked = visible;
});
try {
if (window.localStorage) {
window.localStorage.setItem(factsSummaryStorageKey(), visible ? '1' : '0');
}
} catch (e) {
// Ignore local-storage failures.
}
}
function pottsModernThemeActive() {
if (document.querySelector('.potts-individual-tab-panel,[class*="potts-individual"],[class*="potts-modern"]')) {
return true;
}
const identity = [
document.documentElement.className || '',
document.body ? document.body.className || '' : '',
document.body ? document.body.id || '' : ''
].concat(Array.from(document.querySelectorAll('link[rel="stylesheet"]')).map(function(link){
return link.href || '';
})).join(' ');
return /potts[\s_-]*modern/i.test(identity);
}
function makeFactsSummary() {
const summary = document.createElement('section');
summary.className = 'potts-relationship-context-facts-summary';
const usePottsStyle = config.cardStyle === 'potts'
|| (config.cardStyle === 'theme' && pottsModernThemeActive());
summary.classList.add(usePottsStyle
? 'potts-relationship-context-style-potts'
: 'potts-relationship-context-style-theme');
summary.setAttribute('data-potts-relationship-context', 'facts-summary');
summary.setAttribute('aria-label', config.relationshipFound ? 'Relationship context' : 'No relationship found');
if (!config.relationshipFound) {
summary.classList.add('potts-relationship-context-no-relationship');
}
const icon = document.createElement('div');
icon.className = 'potts-relationship-context-summary-icon';
icon.setAttribute('aria-hidden', 'true');
icon.textContent = config.relationshipFound ? '↔' : '?';
const body = document.createElement('div');
body.className = 'potts-relationship-context-summary-body';
const label = document.createElement('div');
label.className = 'potts-relationship-context-summary-label';
label.textContent = config.referenceIsLoggedInUser
? 'Relationship to you'
: 'Relationship to ' + (config.referenceName || 'the reference person');
const text = document.createElement('div');
text.className = 'potts-relationship-context-summary-text';
text.textContent = relationshipSummarySentence();
body.appendChild(label);
body.appendChild(text);
if (config.relationshipFound && config.showRelationshipPath && config.relationshipPathUrl && config.referenceXref !== config.currentXref) {
const pathLink = document.createElement('a');
pathLink.className = 'potts-relationship-context-path-link';
pathLink.href = config.relationshipPathUrl;
pathLink.textContent = 'View relationship path';
pathLink.setAttribute('aria-label', 'View the relationship path between ' + config.referenceName + ' and ' + config.currentName);
body.appendChild(pathLink);
}
summary.appendChild(icon);
summary.appendChild(body);
summary.hidden = !factsSummaryVisible();
return summary;
}
function elementRect(element) {
try {
return element.getBoundingClientRect();
} catch (e) {
return {width:0,height:0,top:0,left:0};
}
}
function phraseCount(text, phrases) {
return phrases.filter(function(phrase){ return text.indexOf(phrase) !== -1; }).length;
}
function factsControlScore(element, phrases) {
if (!element || ignoredElement(element)) {
return -1;
}
const text = normalise(element.textContent || '');
if (!text || text.length > 1200) {
return -1;
}
const matchedCount = phraseCount(text, phrases);
if (matchedCount === 0) {
return -1;
}
const rect = elementRect(element);
let score = matchedCount * 1000;
score += Math.min(rect.width || 0, 1200);
// The actual webtrees control strip is usually a wide, shallow beige bar.
// Prefer that over the individual checkbox label or a narrow left column.
if ((rect.width || 0) > 450) {
score += 900;
}
if ((rect.height || 0) > 0 && (rect.height || 0) < 120) {
score += 250;
}
if (element.matches && element.matches('label,span,input')) {
score -= 900;
}
if (element.querySelectorAll && element.querySelectorAll('input[type="checkbox"]').length >= 2) {
score += 400;
}
return score;
}
function findFactsControlBar() {
const phrases = ['events of close relatives', 'historic events', 'associated events'];
const roots = candidateRoots();
let best = null;
let bestScore = -1;
for (const root of roots) {
const elements = [root].concat(Array.from(root.querySelectorAll('div,section,form,p,label,span')));
for (const element of elements) {
if (ignoredElement(element)) {
continue;
}
const text = normalise(element.textContent || '');
if (!phrases.some(function(phrase){ return text.indexOf(phrase) !== -1; })) {
continue;
}
let current = element;
let depth = 0;
while (current && current !== document.body && depth < 8) {
if (ignoredElement(current)) {
break;
}
const score = factsControlScore(current, phrases) - (depth * 5);
if (score > bestScore) {
best = current;
bestScore = score;
}
const parent = current.parentElement;
if (!parent || ignoredElement(parent)) {
break;
}
const parentText = normalise(parent.textContent || '');
if (parentText.length > 1800) {
break;
}
current = parent;
depth++;
}
}
}
if (best) {
const bestRect = elementRect(best);
if ((bestRect.width || 0) < 450) {
let current = best.parentElement;
let depth = 0;
while (current && current !== document.body && depth < 8) {
if (ignoredElement(current)) {
break;
}
const text = normalise(current.textContent || '');
const rect = elementRect(current);
if (phraseCount(text, phrases) > 0 && text.length < 2200 && (rect.width || 0) > (bestRect.width || 0)) {
best = current;
}
if ((rect.width || 0) >= 650 && phraseCount(text, phrases) > 0 && text.length < 2200) {
break;
}
current = current.parentElement;
depth++;
}
}
}
return best;
}
function addFactsSummaryToggle(bar, wideArea) {
if (!bar || document.querySelector('[data-potts-relationship-context="facts-summary-toggle"]')) {
return;
}
const label = document.createElement('label');
label.className = 'potts-relationship-context-toggle-label';
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = factsSummaryVisible();
checkbox.setAttribute('data-potts-relationship-context', 'facts-summary-toggle');
checkbox.addEventListener('change', function(){
setFactsSummaryVisible(checkbox.checked);
});
label.appendChild(checkbox);
label.appendChild(document.createTextNode(' Relationship'));
bar.appendChild(label);
}
function ensureFactsSummaryToggle() {
const controlBar = findFactsControlBar();
if (!controlBar) {
return;
}
const filterCell = controlBar.closest('td,th') || controlBar;
const filterRow = filterCell.closest ? filterCell.closest('tr') : null;
addFactsSummaryToggle(filterCell, filterRow || filterCell);
}
function insertFactsSummaryInFactsPanel(summary) {
const controlBar = findFactsControlBar();
if (!controlBar) {
return false;
}
const filterCell = controlBar.closest('td,th');
const filterRow = filterCell ? filterCell.closest('tr') : null;
if (!filterCell || !filterRow || !filterRow.parentNode) {
return false;
}
addFactsSummaryToggle(filterCell, filterRow);
summary.classList.add('potts-relationship-context-summary-in-controls');
// Facts are rendered as a two-column HTML table. A section cannot be a
// direct child of TR, so give the summary its own valid full-width row.
const summaryRow = document.createElement('tr');
summaryRow.className = 'potts-relationship-context-summary-row';
summaryRow.setAttribute('data-potts-relationship-context', 'facts-summary-row');
const summaryCell = document.createElement('td');
summaryCell.className = 'potts-relationship-context-summary-cell';
const table = filterRow.closest('table');
let columnCount = Math.max(2, filterRow.cells ? filterRow.cells.length : 0);
if (table) {
Array.from(table.rows || []).some(function(row){
if (row !== filterRow && row.cells && row.cells.length > 1) {
columnCount = Math.max(columnCount, row.cells.length);
return true;
}
return false;
});
}
summaryCell.colSpan = columnCount;
summaryCell.appendChild(summary);
summaryRow.appendChild(summaryCell);
filterRow.insertAdjacentElement('afterend', summaryRow);
status.summaryWideAreaWidth = Math.round(elementRect(summaryCell).width || 0);
status.summaryControlWidth = Math.round(elementRect(filterCell).width || 0);
status.summaryHostWidth = Math.round(elementRect(summary).width || 0);
return true;
}
function insertFactsSummaryNearTitle(summary) {
const heading = findHeading();
if (!heading) {
return false;
}
summary.classList.remove('col-12', 'w-100');
summary.classList.add('potts-relationship-context-summary-near-title');
const target = heading.closest('.wt-page-title,.individual-header,.wt-individual-header') || heading;
target.insertAdjacentElement('afterend', summary);
return true;
}
function insertFactsSummaryAboveTabs(summary) {
const tabs = findTabsAnchor();
if (!tabs || !tabs.parentNode) {
return false;
}
tabs.insertAdjacentElement('beforebegin', summary);
return true;
}
function insertFactsSummary() {
if (!config.showFactsSummary || config.summaryPosition === 'off') {
return;
}
// Keep the visitor control available regardless of where the summary
// itself is placed. Repeated runs also catch tabs rendered slightly later.
ensureFactsSummaryToggle();
if (document.querySelector('[data-potts-relationship-context="facts-summary"]')) {
return;
}
const summary = makeFactsSummary();
summary.classList.add('col-12', 'w-100');
let inserted = false;
if (config.summaryPosition === 'near-title') {
inserted = insertFactsSummaryNearTitle(summary);
} else if (config.summaryPosition === 'above-tabs') {
inserted = insertFactsSummaryAboveTabs(summary);
} else {
inserted = insertFactsSummaryInFactsPanel(summary);
}
status.insertedFactsSummary = inserted;
if (!inserted && summary.parentNode) {
summary.parentNode.removeChild(summary);
}
}
function findHeading() {
const selectors = [
'.wt-page-title',
'.individual-header h1',
'.wt-individual-header h1',
'main h1',
'#content h1',
'h1'
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element) {
return element;
}
}
return null;
}
function findTabsAnchor() {
const selectors = [
'.wt-tabs',
'.wt-page-tabs',
'.wt-individual-tabs',
'.nav-tabs',
'.nav-pills',
'[role="tablist"]'
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element && !ignoredElement(element)) {
return element;
}
}
return null;
}
function likelyLeftTile(element) {
if (!element) {
return null;
}
function className(el) {
return String(el && el.className || '');
}
function looksLikeTile(el) {
if (!el) {
return false;
}
const cls = className(el);
const text = normalise(el.textContent || '');
return /\bcol-(sm|md|lg|xl)-[234]\b/.test(cls)
|| cls.indexOf('fact-label') !== -1
|| cls.indexOf('fact-title') !== -1
|| cls.indexOf('wt-fact-label') !== -1
|| text.length < 180;
}
// Prefer the first column of the fact/event row. This avoids adding labels to the right-hand detail column.
let current = element;
let depth = 0;
while (current && current !== document.body && depth < 8) {
const children = Array.from(current.children || []);
const cls = className(current);
const rowLike = cls.indexOf('row') !== -1
|| cls.indexOf('wt-fact') !== -1
|| cls.indexOf('fact') !== -1
|| cls.indexOf('event') !== -1
|| children.some(function(child){ return /\bcol-(sm|md|lg|xl)-\d+\b/.test(className(child)); });
if (current !== element && rowLike && children.length > 1 && children[0] && !children[0].contains(element) && looksLikeTile(children[0])) {
return children[0];
}
current = current.parentElement;
depth++;
}
const selectors = [
'.wt-fact-label',
'.fact_LABEL',
'.fact-label',
'.wt-fact-title',
'[class*="fact-label"]',
'[class*="fact-title"]',
'.col-sm-3',
'.col-md-3',
'.col-lg-3',
'.col-xl-3'
];
for (const selector of selectors) {
const match = element.closest(selector) || element.querySelector(selector);
if (match) {
return match;
}
}
const row = element.closest('.row,.wt-fact,.fact,.event,[class*="fact"],[class*="event"]');
if (row) {
const columns = Array.from(row.children || []);
if (columns.length > 1 && looksLikeTile(columns[0])) {
return columns[0];
}
return row;
}
return element;
}
function candidateRoots() {
const selectors = [
'#personal_facts',
'[id*="personal_facts"]',
'#facts-content',
'#facts',
'.wt-facts',
'.wt-fact-list',
'.tab-content',
'.tab-pane',
'main',
'#content'
];
const roots = [];
for (const selector of selectors) {
document.querySelectorAll(selector).forEach(function(element){
if (!roots.includes(element)) {
roots.push(element);
}
});
}
return roots.length ? roots : [document.body];
}
function ignoredElement(element) {
if (!element || !element.closest) {
return false;
}
return !!element.closest('.wt-family-navigator,.family-navigator,[class*="family-navigator"],[class*="relationship"],[class*="sidebar"],aside,nav,header,footer,.dropdown-menu,.wt-page-options,.wt-page-title');
}
function candidateElements() {
const selectors = [
'.wt-fact',
'.fact',
'.event',
'.row',
'[class*="fact"]',
'[class*="event"]',
'[class*="timeline"]'
];
const elements = [];
candidateRoots().forEach(function(root){
selectors.forEach(function(selector){
root.querySelectorAll(selector).forEach(function(element){
const text = normalise(element.textContent || '');
// Very large containers can contain several facts plus the family navigator.
// Matching those can place a relationship label on the first tile on the page.
if (text.length > 1200 || ignoredElement(element)) {
return;
}
if (!elements.includes(element)) {
elements.push(element);
}
});
});
});
// Prefer the smallest matching element so the label is attached to the actual fact row, not a parent wrapper.
elements.sort(function(a, b){
return normalise(a.textContent || '').length - normalise(b.textContent || '').length;
});
return elements;
}
function containsText(haystack, needle) {
needle = normalise(needle);
return !!needle && normalise(haystack).indexOf(needle) !== -1;
}
function isGenericAlias(alias) {
alias = normalise(alias);
return ['birth', 'christening', 'baptism', 'death', 'burial', 'marriage', 'occupation', 'residence', 'census'].indexOf(alias) !== -1;
}
function rowKey(row) {
return String(row.rowKey || [row.category, row.subjectXref, row.label, row.date, row.relationship].join('|'));
}
function candidateIsRightSideDetail(element, tile) {
if (!element || !tile) {
return false;
}
if (element === tile || tile.contains(element)) {
return false;
}
const tileText = normalise(tile.textContent || '');
const elementText = normalise(element.textContent || '');
return tileText && elementText && elementText.length > tileText.length * 2;
}
function matchesRow(elementText, row) {
const text = normalise(elementText);
if (!text || text.length > 1200 || text.indexOf('family navigator') !== -1) {
return false;
}
const subjectName = normalise(row.subjectName || '');
const date = normalise(row.date || '');
const label = normalise(row.label || '');
const relationship = normalise(row.relationship || '');
// A close-relative or associate event must identify the other person.
// This avoids placing a relationship label on ordinary personal facts such as the viewed person's own birth.
if (subjectName && text.indexOf(subjectName) === -1) {
return false;
}
if (date && text.indexOf(date) === -1) {
return false;
}
if (label && text.indexOf(label) !== -1) {
return true;
}
if (relationship && text.indexOf(relationship) !== -1) {
return true;
}
const aliases = Array.isArray(row.aliases) ? row.aliases : [];
return aliases.some(function(alias){
alias = normalise(alias);
return alias && !isGenericAlias(alias) && text.indexOf(alias) !== -1;
});
}
function renderedRelationshipAlreadyShown(elements, row) {
const subjectName = normalise(row.subjectName || '');
const relationship = normalise(String(row.relationship || '').replace(/[-_]+/g, ' '));
if (!subjectName || !relationship) {
return false;
}
const kinshipTerms = [
'father', 'mother', 'parent', 'grandfather', 'grandmother', 'grandparent',
'brother', 'sister', 'sibling', 'son', 'daughter', 'child',
'husband', 'wife', 'spouse', 'uncle', 'aunt', 'nephew', 'niece',
'cousin', 'grandson', 'granddaughter', 'grandchild', 'in law'
].filter(function(term){ return relationship.indexOf(term) !== -1; });
return elements.some(function(element){
const text = normalise(element.textContent || '').replace(/[-_]+/g, ' ');
if (!text || text.length > 1200 || text.indexOf(subjectName) === -1) {
return false;
}
if (text.indexOf(relationship) !== -1) {
return true;
}
return kinshipTerms.some(function(term){
return text.indexOf(term) !== -1;
});
});
}
function relationshipLabelsIn(tile) {
return Array.from(tile.querySelectorAll('[data-potts-relationship-context="fact"]'));
}
function ageElementIn(tile) {
return tile.querySelector('.potts-fact-age-slot,.potts-fact-age-inline,[data-potts-fact-age-badge]');
}
function controlElementIn(tile) {
return Array.from(tile.children || []).find(function(child){
if (child.matches && child.matches('[data-potts-relationship-context="fact"],.potts-fact-age-slot,.potts-fact-age-inline,[data-potts-fact-age-badge]')) {
return false;
}
const text = normalise(child.textContent || '');
return text.length < 20 && !!child.querySelector('a,button,.btn,.dropdown,.icon');
});
}
function placeLabelInTile(tile, label) {
const age = ageElementIn(tile);
if (age && age.parentNode === tile) {
tile.insertBefore(label, age);
return;
}
const controls = controlElementIn(tile);
if (controls && controls.parentNode === tile) {
tile.insertBefore(label, controls);
return;
}
tile.appendChild(label);
}
function tidyExistingLabels() {
document.querySelectorAll('[data-potts-relationship-context="fact"]').forEach(function(label){
const tile = likelyLeftTile(label);
if (!tile) {
return;
}
placeLabelInTile(tile, label);
});
}
function insertLabelIntoTile(tile, label) {
placeLabelInTile(tile, label);
}
function insertFactLabels() {
if (!config.showFactLabels || !Array.isArray(config.factRelationships)) {
return;
}
const elements = candidateElements();
let inserted = 0;
config.factRelationships.forEach(function(row){
if (!row || !row.relationship || !row.subjectName) {
return;
}
const key = rowKey(row);
if (document.querySelector('[data-potts-relationship-row-key="' + CSS.escape(key) + '"]')) {
return;
}
if (renderedRelationshipAlreadyShown(elements, row)) {
status.nativeRelationshipLabels = (status.nativeRelationshipLabels || 0) + 1;
return;
}
for (const element of elements) {
if (element.querySelector && element.querySelector('[data-potts-relationship-context="fact"]')) {
continue;
}
if (!matchesRow(element.textContent || '', row)) {
continue;
}
const tile = likelyLeftTile(element);
if (!tile || tile.querySelector('[data-potts-relationship-context="fact"]')) {
continue;
}
if (candidateIsRightSideDetail(element, tile)) {
// Use the matched row to find the left tile, but never place the label in the detail column.
}
const label = document.createElement('div');
label.className = 'potts-relationship-context-fact-label';
label.setAttribute('data-potts-relationship-context', 'fact');
label.setAttribute('data-potts-relationship-row-key', key);
label.textContent = row.displayText || ('Relationship: ' + row.relationship);
insertLabelIntoTile(tile, label);
inserted++;
break;
}
});
status.insertedFactLabels = document.querySelectorAll('[data-potts-relationship-context="fact"]').length || inserted;
}
function run() {