-
-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathScriptureViewSofria.svelte
More file actions
2711 lines (2637 loc) · 120 KB
/
ScriptureViewSofria.svelte
File metadata and controls
2711 lines (2637 loc) · 120 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
<!--
@component
A component for displaying scripture.
TODO:
- find a way to scroll smoothly, as CSS only option does not work as expected.
- save graft info so that references can be handled
- parse introduction for references
LOGGING:
- add logs entry to local storage with this value (and change 1 to 0 to disable topic)
{ "scripture" : {"root": 1, "docResult": 1, "document":1, "paragraph": 1, "phrase" :1 , "chapter": 1, "verses": 1, "text": 1, "sequence": 1, "wrapper":1, "milestone":1, "blockGraft": 1, "inlineGraft": 1, "mark": 1, "meta": 1, "row": 1} }
-->
<script lang="ts">
/* eslint-disable svelte/no-dom-manipulating */
import { base } from '$app/paths';
import { scriptureConfig } from '$assets/config';
import { hasAudioPlayed, seekToVerse } from '$lib/data/audio';
import {
addPlanProgressItem,
deleteAllProgressItemsForPlan,
getFirstIncompleteDay,
getNextPlanReference
} from '$lib/data/planProgressItems';
import { addPlanState, getLastPlanState } from '$lib/data/planStates';
import { loadDocSetIfNotLoaded } from '$lib/data/scripture';
import {
audioPlayer,
currentPlanData,
currentPlanState,
footnotes,
language,
logs,
modal,
ModalType,
plan,
refs,
t,
userSettings
} from '$lib/data/stores';
import { gotoRoute } from '$lib/navigate';
import type { SABProskomma } from '$lib/sab-proskomma';
import { getFeatureValueBoolean, getFeatureValueString } from '$lib/scripts/configUtils';
import { checkForMilestoneLinks } from '$lib/scripts/milestoneLinks';
import * as numerals from '$lib/scripts/numeralSystem';
import { parsePhrase, prepareAudioPhraseEndChars } from '$lib/scripts/parsePhrase';
import {
generateHTML,
getDisplayString,
handleHeaderLinkPressed,
isBibleBook
} from '$lib/scripts/scripture-reference-utils';
import { getReferenceFromString } from '$lib/scripts/scripture-reference-utils-common';
import { ciEquals, isDefined, isNotBlank, splitString } from '$lib/scripts/stringUtils';
import {
deselectAllElements,
onClickText,
updateSelections
} from '$lib/scripts/verseSelectUtil';
import { addVideoLinks, createVideoBlock, createVideoBlockFromUrl } from '$lib/video';
import { SofriaRenderFromProskomma } from 'proskomma-json-tools';
import { onDestroy, onMount } from 'svelte';
import { fromStore } from 'svelte/store';
const illustrations = import.meta.glob('./*', {
import: 'default',
eager: true,
query: '?url',
base: '/src/gen-assets/illustrations'
}) as Record<string, string>;
let {
audioPhraseEndChars,
bodyFontSize,
bodyLineHeight,
bookmarks,
notes,
highlights,
maxSelections,
redLetters,
references,
glossary,
selectedVerses,
themeColors,
verseLayout,
viewShowBibleImages,
viewShowBibleVideos,
viewShowIllustrations,
viewShowVerses,
viewShowGlossaryWords,
font,
proskomma
}: {
audioPhraseEndChars: string;
bodyFontSize: any;
bodyLineHeight: any;
bookmarks: any;
notes: any;
highlights: any;
maxSelections: any;
redLetters: boolean;
references: any;
glossary: any;
selectedVerses: any;
themeColors: any;
verseLayout: any;
viewShowBibleImages: string;
viewShowBibleVideos: string;
viewShowIllustrations: boolean;
viewShowVerses: boolean;
viewShowGlossaryWords: boolean;
font: string;
proskomma: SABProskomma;
} = $props();
const scriptureLogs = $derived.by(() =>
$userSettings['scripture-logs']
? {
root: 1,
docResult: 1,
document: 1,
paragraph: 1,
phrase: 1,
chapter: 1,
verses: 1,
text: 1,
sequence: 1,
wrapper: 1,
milestone: 1,
blockGraft: 1,
inlineGraft: 1,
mark: 1,
meta: 1,
row: 1,
placement: 1
}
: $logs['scripture']
);
let container: HTMLElement = $state();
let displayingIntroduction = $state(false);
const fnc = 'abcdefghijklmnopqrstuvwxyz';
/** calculate letter index from number
*
* 0-25 => a-z; 26+ => aa, ab, ... zz
*/
function createLetterIndex(index: number) {
return (
(index >= fnc.length ? fnc.charAt(Math.floor(index / fnc.length) - 1) : '') +
fnc.charAt(index % fnc.length)
);
}
let planDivObserver = $state(null); // To store the observer instance
let planObservationCompleted = $state(false);
// Function to observe the visibility of the plan div
function observeVisibility() {
if (planDivObserver) {
planDivObserver.disconnect(); // Disconnect any previous observer before creating a new one
planDivObserver = null; // Clear the observer reference
}
if (planDivInChapter() && !$plan.completed) {
const target = document.getElementById('PLAN-next');
if (target) {
planObservationCompleted = false;
planDivObserver = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting && !planObservationCompleted) {
$plan.completed = true;
planObservationCompleted = true;
planDivObserver.disconnect(); // Stop observing after it becomes visible
planDivObserver = null; // Clear the observer reference after disconnecting
addPlanProgressItem({
id: $plan.planId,
day: $plan.planDay,
itemIndex: $plan.planEntry
});
if (lastPlanReference) {
addPlanState({
id: $plan.planId,
state: 'completed'
});
deleteAllProgressItemsForPlan($plan.planId);
}
}
});
},
{
threshold: 0.1 // Adjust as needed
}
);
planDivObserver.observe(target);
}
}
}
onMount(() => {
if (planDivInChapter) {
observeVisibility();
}
});
onDestroy(() => {
if (planDivObserver) {
planDivObserver.disconnect();
planDivObserver = null;
}
});
function escapeSpecialChars(separators: string) {
return separators.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&');
}
const seprgx2 = (inputChars: string) => {
let separators = prepareAudioPhraseEndChars(inputChars);
let result = '(';
for (let i = 0; i < separators.length; i++) {
if (i > 0) {
result += '|';
}
result += escapeSpecialChars(separators[i]);
}
result += ')';
const regEx = new RegExp(result, 'g');
return regEx;
};
const seprgx = $derived(seprgx2(audioPhraseEndChars));
const onlySpaces = (str) => {
return str.trim().length === 0;
};
let nextPlanDay = $state(null);
let lastPlanReference = $state();
$effect(() => {
if ($currentPlanData && $plan.planDay) {
getFirstIncompleteDay($currentPlanData, $plan.planDay).then((day) => {
nextPlanDay = day;
if ($plan.planId) {
// The first is true before the end of plan div becomes visible
// When it becomes visible, the records are deleted and nextPlanDay
// is 1 but the plan status is now completed. So must check both
// to know if the reference being viewed is the last.
if ($plan.planNextReference === '' && nextPlanDay === -1) {
lastPlanReference = true;
} else {
getLastPlanState($plan.planId).then((state) => {
lastPlanReference = state === 'completed';
});
}
}
});
} else {
nextPlanDay = null;
}
});
const stateSelectedVerses = fromStore(selectedVerses);
$effect(() => {
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
stateSelectedVerses.current;
updateSelections(selectedVerses);
});
const countSubheadingPrefixes = (subHeadings: [string], labelPrefix: string) => {
let result = 0;
for (let i in subHeadings) {
if (subHeadings[i] === labelPrefix) {
result++;
}
}
return result;
};
const phraseTerminated = (phrase) => {
return phrase.match(seprgx) != null;
};
const currentTextType = (workspace) => {
return workspace.textType[workspace.textType.length - 1];
};
const startPhrase = (workspace, indexOption = 'advance') => {
if (scriptureLogs?.phrase) {
console.log('Start phrase!!!');
}
// Add pending phrase to the paragraph before starting
// new ones
if (workspace.phraseDiv != null) {
if (workspace.phraseDiv.innerText.length === 0) {
if (indexOption === 'advance') {
indexOption = 'keep';
}
} else {
appendPhrase(workspace);
}
}
const div = document.createElement('div');
if (!workspace.introductionGraft) {
switch (indexOption) {
case 'reset':
workspace.currentPhraseIndex = 0;
break;
case 'advance':
workspace.currentPhraseIndex++;
break;
default:
break;
}
const phraseIndex = createLetterIndex(workspace.currentPhraseIndex);
div.id = workspace.currentVerse + phraseIndex;
div.setAttribute('data-verse', workspace.currentVerse);
div.setAttribute('data-phrase', phraseIndex);
div.classList.add('txs', 'seltxt', 'scroll-item');
} else {
div.id = '+' + parseInt(workspace.introductionIndex);
div.classList.add('txs');
workspace.introductionIndex++;
}
return div.cloneNode(true);
};
const addTableText = (workspace, text) => {
if (workspace.inRow) {
if (workspace.textType.includes('usfm') && workspace.usfmWrapperType === 'xt') {
const references = text.split('; ');
for (let i = 0; i < references.length; i++) {
var spanV = document.createElement('span');
spanV.classList.add('reflink');
const refText = generateHTML(text, 'header-ref');
spanV.innerHTML = refText;
spanV.addEventListener('click', onClick, false);
workspace.tableCellElement.appendChild(spanV);
if (i < references.length - 1) {
appendTextToElement(workspace.tableCellElement, '; ');
}
}
} else {
const div = addTextNode(workspace.tableCellElement, text, workspace);
workspace.tableCellElement = div.cloneNode(true);
}
}
};
const getFootnoteCallerCharacter = (workspace, text, textType) => {
let callerType = 'default';
let callerSymbol = text;
let callerCustomSymbol = '';
let callerNoCallerToAuto = false;
switch (textType) {
case 'xref':
callerType = getFeatureValueString(
'crossref-caller-type',
references.collection,
references.book
);
callerCustomSymbol = getFeatureValueString(
'crossref-caller-symbol',
references.collection,
references.book
);
callerNoCallerToAuto = getFeatureValueBoolean(
'crossref-caller-no-caller-to-auto',
references.collection,
references.book
);
break;
default:
callerType = getFeatureValueString(
'footnote-caller-type',
references.collection,
references.book
);
callerCustomSymbol = getFeatureValueString(
'footnote-caller-symbol',
references.collection,
references.book
);
callerNoCallerToAuto = getFeatureValueBoolean(
'footnote-caller-no-caller-to-auto',
references.collection,
references.book
);
break;
}
if (callerType === 'custom-symbol') {
// Use whatever is specified as the custom symbol, even '-' or '+'
// This matches native app. Sigh.
return callerCustomSymbol;
} else if (callerType === 'abc') {
callerSymbol = '+';
} else if (callerNoCallerToAuto && callerSymbol === '-') {
callerSymbol = '+';
}
if (callerSymbol === '-') {
callerSymbol = null;
}
if (callerSymbol === '+') {
callerSymbol = createLetterIndex(workspace.footnoteIndex);
workspace.footnoteIndex++;
}
return callerSymbol;
};
const appendTextToElement = (element: HTMLElement, text: string) => {
element.innerHTML = element.innerHTML + text;
};
const addGraftText = (workspace, text, textType, usfmType) => {
if (workspace.textType.includes(textType)) {
if (isDefined(workspace.footnoteDiv)) {
if (workspace.textType.includes('note_caller')) {
const caller = getFootnoteCallerCharacter(workspace, text, textType);
if (!caller) {
// Do not include the footnote
workspace.foootnoteSpan = null;
} else {
// Assign the caller to the footnote sup
const elements = workspace.footnoteSpan.querySelectorAll('sup.footnote');
if (elements && elements.length > 0) {
elements[0].innerHTML = caller;
}
}
} else {
const div = addTextNode(workspace.footnoteDiv, text, workspace);
workspace.footnoteDiv = div.cloneNode(true);
}
}
} else {
console.warn('%s ignored: %s', usfmType, text);
}
};
const fixText = (text) => {
if (text === '| default=""') {
// HACK: Proskomma adds default="" to anonymous bars in text
// See https://community.scripture.software.sil.org/t/issues-with-cross-references-in-pwa-modern/4476
text = '| ';
}
return text;
};
const addText = (workspace, text) => {
text = fixText(text);
if (scriptureLogs?.text) {
console.log('Adding text:', text);
}
if (!onlySpaces(text)) {
let phrases = [];
if (!workspace.introductionGraft && references.hasAudio) {
phrases = parsePhrase(text, seprgx);
} else {
// Don't parse introduction or if there is no audio.
// Each paragraph is a single div.
phrases[0] = text;
}
for (let i = 0; i < phrases.length; i++) {
if (workspace.lastPhraseTerminated) {
if (scriptureLogs?.text) {
console.log('Add text start phrase (terminated)');
}
workspace.phraseDiv = startPhrase(workspace);
}
if (workspace.phraseDiv === null) {
if (scriptureLogs?.text) {
console.log('Add text start phrase (null)');
}
workspace.phraseDiv = startPhrase(workspace, 'keep');
}
let div = workspace.phraseDiv.cloneNode(true);
const phrase = phrases[i];
div = addTextNode(div, phrase, workspace);
if (i < phrases.length - 1) {
workspace.phraseDiv = div.cloneNode(true);
if (scriptureLogs?.text) {
console.log('Add text start phrase');
}
workspace.phraseDiv = startPhrase(workspace);
} else {
workspace.phraseDiv = div.cloneNode(true);
}
}
workspace.lastPhraseTerminated =
phrases.length > 0 ? phraseTerminated(phrases[phrases.length - 1]) : false;
}
return;
};
const usfmSpan = (parent: any, spanClass: string, phrase: string, lemma: string = '') => {
const spanElement = document.createElement('span');
let child;
spanElement.classList.add(spanClass);
switch (spanClass) {
case 'xt': {
spanElement.innerHTML = phrase;
break;
}
case 'glossary': {
const aElement = document.createElement('a');
let matchWord = phrase;
if (isNotBlank(lemma)) {
matchWord = lemma;
}
aElement.setAttribute('match', matchWord.trim());
aElement.setAttribute('href', ' ');
aElement.classList.add('glossary');
appendTextToElement(aElement, phrase);
spanElement.appendChild(aElement);
break;
}
default: {
appendTextToElement(spanElement, phrase);
break;
}
}
parent.appendChild(spanElement);
return parent;
};
const addTextNode = (div: any, phrase: string, workspace: any) => {
const usfmWrapperType = workspace.usfmWrapperType;
if (usfmWrapperType) {
switch (usfmWrapperType) {
case 'wj': {
if (workspace.showWordsOfJesus) {
div = usfmSpan(div, usfmWrapperType, phrase);
} else {
appendTextToElement(div, phrase);
}
break;
}
case 'w': {
const lemma = workspace.lemma;
if (viewShowGlossaryWords) {
div = usfmSpan(div, 'glossary', phrase, lemma);
} else {
div = usfmSpan(div, usfmWrapperType, phrase);
}
break;
}
default: {
div = usfmSpan(div, usfmWrapperType, phrase);
break;
}
}
} else {
appendTextToElement(div, phrase);
}
return div;
};
const processText = (introductionGraft, showIntroduction, titleGraft) => {
let returnValue = false;
if (introductionGraft == showIntroduction || (titleGraft && showIntroduction)) {
returnValue = true;
}
return returnValue;
};
function appendPhrase(workspace) {
workspace.lastPhrase = workspace.phraseDiv.getAttribute('data-phrase');
if (versePerLine) {
workspace.verseDiv.appendChild(workspace.phraseDiv.cloneNode(true));
} else {
workspace.paragraphDiv.appendChild(workspace.phraseDiv.cloneNode(true));
}
}
function addVerseNumber(workspace: any, element: any, showVerseNumbers: boolean) {
if (showVerseNumbers === true) {
const spanV = document.createElement('span');
spanV.classList.add('v');
// 'number' can be a range of verse numbers
spanV.innerText = numerals.formatNumberRange(
numeralSystem,
element.atts['number'],
direction
);
const spanVsp = document.createElement('span');
spanVsp.classList.add('vsp');
spanVsp.innerText = '\u00A0'; //  
workspace.phraseDiv.appendChild(spanV);
workspace.phraseDiv.appendChild(spanVsp);
}
}
function handleVerseLabel(element, showVerseNumbers, workspace) {
if (workspace.firstVerse === true && workspace.chapterNumText !== '') {
const div = document.createElement('div');
const chapterNumberFormatSetting = getFeatureValueString(
'chapter-number-format',
references.collection,
references.book
);
if (chapterNumberFormatSetting === 'drop-cap') {
workspace.paragraphDiv.className = 'm';
div.classList.add('c-drop');
// SAB is statically generating div.c-drop: { float: left|right; } based on settings than can change
// So override that style based on the current directin of the text
div.style.float = direction.toLowerCase() === 'ltr' ? 'left' : 'right';
div.innerText = workspace.chapterNumText;
workspace.paragraphDiv.appendChild(div);
if (!scriptureConfig.mainFeatures['hide-verse-number-1']) {
addVerseNumber(workspace, element, showVerseNumbers);
}
} else {
// chapter at top of page
div.classList.add('c');
div.innerText = workspace.chapterNumText;
workspace.root.appendChild(div);
addVerseNumber(workspace, element, showVerseNumbers);
}
} else {
addVerseNumber(workspace, element, showVerseNumbers);
}
workspace.firstVerse = false;
}
// handles clicks on verse numbers
function audioClickHandler(click) {
if (!hasAudioPlayed()) {
return;
}
const element = click.target.textContent;
const verseSelection = document.querySelector('[data-verse="' + element + '"]');
const verseId = verseSelection.getAttribute('id');
seekToVerse(verseId);
}
// handles clicks on in-text notation superscripts
function footnoteClickHandler(event) {
if ($footnotes.length === 0) {
event.stopPropagation();
const root = event.target.parentNode.parentNode;
const footnote = root.querySelector(`div#${root.getAttribute('data-graft')}`);
const workingSpan = footnote.cloneNode(true);
const spans = workingSpan.querySelectorAll('span.xt');
// Loop through each span and modify its inner HTML
spans.forEach((span) => {
span.innerHTML = generateHTML(span.innerHTML, ''); // Change inner HTML as needed
});
const parsed = workingSpan.innerHTML;
footnotes.push(parsed);
}
}
// handles clicks on in text markdown reference links
function referenceLinkClickHandler(event: any) {
const linkRef = event.target.getAttribute('ref');
const splitRef = splitString(linkRef, '.');
const splitSet = splitRef[0];
const refBook = splitRef[1];
const splitChapter = splitRef[2];
const splitVerse = splitRef[3];
let refDocSet = currentDocSet;
const refBc = scriptureConfig.bookCollections?.find((x) => x.id === splitSet);
if (refBc) {
refDocSet = refBc.languageCode + '_' + refBc.id;
} else {
// Invalid collection
return;
}
refs.set({ docSet: refDocSet, book: refBook, chapter: splitChapter, verse: splitVerse });
return;
}
async function headerLinkClickReference(event: any) {
event.stopPropagation();
let start = JSON.parse(event.target.getAttribute('data-start-ref'));
let end =
event.target.getAttribute('data-end-ref') === 'undefined'
? undefined
: JSON.parse(event.target.getAttribute('data-end-ref'));
if (scriptureConfig.mainFeatures['scripture-refs-display'] === 'viewer') {
navigate(start);
} else {
const footnoteHTML = await handleHeaderLinkPressed(start, end, themeColors);
footnotes.push(footnoteHTML);
}
}
function glossaryClickHandler(event: any) {
event.stopPropagation();
event.preventDefault();
const glossaryLink = event.target.getAttribute('match');
glossary.then((glossaryResults) => {
if (isDefined(glossaryResults.data.docSets[0].document)) {
glossaryResults.data.docSets[0].document.mainBlocks.forEach((block) => {
if (ciEquals(block.key, glossaryLink)) {
if ($footnotes.length === 0) {
const glossaryDiv = document.createElement('div');
glossaryDiv.classList.add('txs');
const glossarySpan = document.createElement('span');
glossarySpan.classList.add('k');
const titleText = document.createTextNode(glossaryLink);
glossarySpan.append(block.key);
glossaryDiv.append(glossarySpan);
const blockText = block.text.slice(glossaryLink.length);
appendTextToElement(glossaryDiv, blockText);
const glossaryHTML = glossaryDiv.outerHTML;
footnotes.push(glossaryHTML);
}
}
});
}
});
}
function remoteAudioClipHandler(event: any) {
event.stopPropagation();
const address = event.target.getAttribute('filelink');
const el = document.querySelector(`audio[id="${address}" ]`);
if (el) {
const urlString = el.getAttribute('src');
const audio = new Audio(urlString);
audio.play();
}
}
function navigate(reference) {
refs.set({
docSet: reference.docSet,
book: reference.book,
chapter: reference.chapter,
verse: reference.verse
});
footnotes.reset();
}
function addNotesDiv(workspace) {
const notesSpan = document.createElement('span');
notesSpan.id = 'notes' + workspace.currentVerse;
let el = workspace.paragraphDiv?.querySelector(
`div[data-verse="${workspace.currentVerse}"][data-phrase=${workspace.lastPhrase}]`
);
if (el === null) {
// Try finding if it is already attached to root
el = workspace.root.querySelector(
`div[data-verse="${workspace.currentVerse}"][data-phrase=${workspace.lastPhrase}]`
);
}
el?.parentNode.insertBefore(notesSpan, el.nextSibling);
}
const noteSvg = () => {
return '<svg fill="#000000" style="display:inline" xmlns="http://www.w3.org/2000/svg" height="16" width="16" viewBox="0 0 96 96"><path d="M 21.07 74.80 L 8.76 87.35 Q 8.00 88.12 8.00 87.03 Q 8.00 52.12 8.00 18.00 Q 8.00 7.73 18.00 7.80 Q 48.00 8.00 78.00 8.00 Q 88.27 8.00 88.18 18.00 Q 88.00 40.13 88.09 62.25 Q 88.13 72.31 78.00 72.22 C 72.03 72.17 25.23 70.89 23.56 72.37 Q 22.78 73.07 21.07 74.80 Z M 72.00 21.60 A 0.60 0.60 0.0 0 0 71.40 21.00 L 24.60 21.00 A 0.60 0.60 0.0 0 0 24.00 21.60 L 24.00 28.40 A 0.60 0.60 0.0 0 0 24.60 29.00 L 71.40 29.00 A 0.60 0.60 0.0 0 0 72.00 28.40 L 72.00 21.60 Z M 72.00 35.60 A 0.60 0.60 0.0 0 0 71.40 35.00 L 24.60 35.00 A 0.60 0.60 0.0 0 0 24.00 35.60 L 24.00 42.40 A 0.60 0.60 0.0 0 0 24.60 43.00 L 71.40 43.00 A 0.60 0.60 0.0 0 0 72.00 42.40 L 72.00 35.60 Z M 60.00 49.60 A 0.60 0.60 0.0 0 0 59.40 49.00 L 24.60 49.00 A 0.60 0.60 0.0 0 0 24.00 49.60 L 24.00 56.40 A 0.60 0.60 0.0 0 0 24.60 57.00 L 59.40 57.00 A 0.60 0.60 0.0 0 0 60.00 56.40 L 60.00 49.60 Z"</path></svg>';
};
function editNote(note) {
modal.open(ModalType.Note, note);
}
function addNotedVerses(notesInChapter) {
notesInChapter.then((notes) => {
for (var k = 0; k < notes.length; k++) {
const note = notes[k];
const bookmarksSpan = document.getElementById('bookmarks' + note.verse);
if (!bookmarksSpan) {
console.warn('No bookmarks span for verse %s', note.verse);
continue;
}
const existingNoteSpan = document.getElementById('note' + k);
if (!existingNoteSpan) {
let noteSpan = document.createElement('span');
noteSpan.id = 'note' + k;
noteSpan.innerHTML = noteSvg();
noteSpan.onclick = (event) => editNote(note);
bookmarksSpan.appendChild(noteSpan);
}
}
});
}
function addBookmarksDiv(workspace) {
const bookmarksSpan = document.createElement('span');
bookmarksSpan.id = 'bookmarks' + workspace.currentVerse;
let el = workspace.paragraphDiv?.querySelector(
`div[data-verse="${workspace.currentVerse}"][data-phrase=${workspace.lastPhrase}]`
);
if (el === null) {
// Try finding if it is already attached to root
el = workspace.root.querySelector(
`div[data-verse="${workspace.currentVerse}"][data-phrase=${workspace.lastPhrase}]`
);
}
el?.parentNode.insertBefore(bookmarksSpan, el.nextSibling);
}
const bookmarkSvg = () => {
return '<svg fill="#b10000" style="display:inline" xmlns="http://www.w3.org/2000/svg" height="16" width="16" viewBox="0 0 24 24"><path d="M5 21V5q0-.825.588-1.413Q6.175 3 7 3h10q.825 0 1.413.587Q19 4.175 19 5v16l-7-3Z"/></svg>';
};
function addBookmarkedVerses(bookmarksInChapter) {
bookmarksInChapter.then((bookmarks) => {
for (var j = 0; j < bookmarks.length; j++) {
const bookmarksSpan = document.getElementById('bookmarks' + bookmarks[j].verse);
if (!bookmarksSpan) {
console.warn('No bookmarks span for verse %s', bookmarks[j].verse);
continue;
}
const existingBookmarkSpan = document.getElementById('bookmark' + j);
if (!existingBookmarkSpan) {
let bookmarkSpan = document.createElement('span');
bookmarkSpan.id = 'bookmark' + j;
bookmarkSpan.innerHTML = bookmarkSvg();
bookmarksSpan.appendChild(bookmarkSpan);
}
}
});
}
function addHighlightedVerses(highlightsInChapter) {
highlightsInChapter.then((highlights) => {
for (let i = 0; i < highlights.length; i++) {
//Skip this entry if the the next is a highlight for the same verse
if (i < highlights.length - 1) {
if (highlights[i].verse === highlights[i + 1].verse) {
continue;
}
}
let elements = container?.querySelectorAll(
`div[data-verse="${highlights[i].verse}"]`
);
for (const element of elements) {
const penClass = 'hlp' + highlights[i].penColor;
element.classList.add(penClass);
}
}
});
}
function createFootnoteDiv(workspace, element) {
let footnoteSpan = null;
let footnoteId = `X-${workspace.footnoteIdIndex + 1}`;
workspace.footnoteIdIndex++;
let footnoteDiv = document.createElement('div');
footnoteDiv.id = footnoteId;
footnoteDiv.style.display = 'none';
footnoteDiv.setAttribute('type', element.subType);
footnoteSpan = document.createElement('span');
footnoteSpan.setAttribute('data-graft', footnoteId);
const a = document.createElement('a');
const sup = document.createElement('sup');
sup.classList.add('footnote');
a.appendChild(sup);
a.classList.add('cursor-pointer');
footnoteSpan.appendChild(a);
if (scriptureLogs?.footnote) {
console.log('Create Footnote %o %o', footnoteSpan, footnoteDiv);
}
return [footnoteSpan, footnoteDiv];
}
const planDivInChapter = () => {
let planEntryInChapter = false;
// If plan entry is -1, there is no active entry
if ($plan.planEntry !== -1) {
if (
$plan.planBookId === references.book &&
$plan.planChapter.toString() === references.chapter
) {
planEntryInChapter = true;
}
}
return planEntryInChapter;
};
function addPlanDiv(workspace, verseNumber) {
if (planDivInChapter() && matchesVerse($plan.planToVerse, verseNumber)) {
const planDiv = document.createElement('div');
planDiv.id = 'plan-progress';
planDiv.classList.add('plan-progress-block');
if (lastPlanReference) {
// plan is complete once this item finishes
appendPlanProgressTextDiv(
planDiv,
'plan-progress-title',
'',
$t['Plans_Progress_Congratulations'],
false
);
appendPlanProgressTextDiv(
planDiv,
'plan-progress-info',
'',
$t['Plans_Progress_Plan_Completed'],
false
);
appendPlanProgressTextDiv(
planDiv,
'plan-progress-info',
'',
$currentPlanData.title[$language] ?? $currentPlanData.title.default ?? '',
false
);
appendPlanProgressTextDiv(
planDiv,
'plan-progress-button',
'PLAN-next',
$t['Plans_Button_View_Plans'],
true
);
} else {
appendPlanProgressTextDiv(
planDiv,
'plan-progress-info',
'',
$t['Plans_Progress_Item_Completed'],
false
);
appendPlanProgressTextDiv(
planDiv,
'plan-progress-reference',
'',
getPlanReferenceString($plan.planReference),
false
);
const hr = document.createElement('hr');
if ($plan.planNextReference === '') {
// No more entries for current day
appendPlanProgressTextDiv(
planDiv,
'plan-progress-button',
'PLAN-next',
$t['Plans_Button_View_Plan'],
true
);
} else {
planDiv.append(hr);
appendPlanProgressTextDiv(
planDiv,
'plan-progress-info',
'',
$t['Plans_Progress_Next_Reading'],
false
);
appendPlanProgressTextDiv(
planDiv,
'plan-progress-reference',
'',
getPlanReferenceString($plan.planNextReference),
false
);
appendPlanProgressTextDiv(
planDiv,
'plan-progress-button',
'PLAN-next',
$t['Button_Next'],
true
);
}
}
workspace.root.appendChild(workspace.paragraphDiv);
workspace.root.appendChild(planDiv);
workspace.paragraphDiv = document.createElement('div');
workspace.paragraphDiv.classList.add('p');
} else if (planDivInChapter() === false && $plan.completed === true) {
// If we are no longer in the plan chapter and the plan section
// has been read, clear plan so that the plan item will not
// appear if you go back to that chapter
$plan = {
planId: '',
planDay: 0,
planEntry: -1,
planBookId: '',
planChapter: 0,
planFromVerse: 0,
planToVerse: 0,
planReference: '',
planNextReference: '',
completed: false
};
}
}
function appendPlanProgressTextDiv(
progressDiv: HTMLDivElement,
divClass: string,
divId: string,
stringId: string,
addClick: boolean
) {
const textDiv = document.createElement('div');
if (divId !== '') {
textDiv.id = divId;
}
if (addClick) {
textDiv.onclick = (event) => planClicked();
}
textDiv.classList.add(divClass);
appendTextToElement(textDiv, stringId);
progressDiv.append(textDiv);
}
function getPlanReferenceString(ref) {
let currentBookCollectionId = references.collection;
const [collection, book, fromChapter, toChapter, verseRanges] = getReferenceFromString(ref);
const displayString = getDisplayString(
currentBookCollectionId,
book,
toChapter,
verseRanges
);
return displayString;
}
async function gotoPlanReference() {
let currentBookCollectionId = references.collection;
const [collection, book, fromChapter, toChapter, verseRanges] = getReferenceFromString(
$plan.planNextReference
);
const [fromVerse, toVerse, separator] = verseRanges[0];
let destinationVerse = fromVerse === -1 ? 1 : fromVerse;
if ($currentPlanData) {
const item = $currentPlanData.items[$plan.planDay - 1];
const [nextReference, nextIndex] = await getNextPlanReference(
$plan.planId,
item,
$plan.planNextReferenceIndex
);
const newEntry = $plan.planNextReferenceIndex;
const newReference = $plan.planNextReference;
$plan = {
planId: $plan.planId,
planDay: $plan.planDay,