forked from cyruzzo/AboveVTT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Journal.js
3004 lines (2560 loc) · 113 KB
/
Journal.js
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
/**
* JournalManager (WIP)
* Is the tab on the sidebar that allows you to write notes
* Requires journalPanel = new Sidebar();
* All of its DOM elements attach to journalPanel tree
* Also holds notes attached to tokens
*
*/
cached_journal_items = {};
class JournalManager{
constructor(gameid){
this.gameid=gameid;
let promises = [];
let objectStore = gameIndexedDb.transaction(["journalData"]).objectStore(`journalData`)
promises.push(new Promise((resolve) => {
objectStore.get(`Journal`).onsuccess = (event) => {
if(event?.target?.result?.journalData){
this.notes = event?.target?.result?.journalData
}
else {
if (window.DM && (localStorage.getItem('Journal' + gameid) != null)) {
this.notes = $.parseJSON(localStorage.getItem('Journal' + gameid));
}
else{
this.notes={};
}
}
let statBlockPromise = new Promise((resolve) => {
let globalObjectStore = globalIndexedDB.transaction(["journalData"]).objectStore(`journalData`)
globalObjectStore.get(`JournalStatblocks`).onsuccess = (event) => {
if(event?.target?.result?.journalData){
this.notes = {
...this.notes,
...event?.target?.result?.journalData
}
}
else {
if(window.DM && (localStorage.getItem('JournalStatblocks') != null && localStorage.getItem('JournalStatblocks') != 'undefined')){
this.notes = {
...this.notes,
...$.parseJSON(localStorage.getItem('JournalStatblocks'))
}
}
}
resolve(true);
}
})
statBlockPromise.then(()=>{resolve(true)});
}
}))
promises.push(new Promise((resolve) => {
objectStore.get(`JournalChapters`).onsuccess = (event) => {
if(event?.target?.result?.journalData){
this.chapters = event?.target?.result?.journalData;
}
else{
if (window.DM && (localStorage.getItem('JournalChapters' + gameid) != null)) {
this.chapters = $.parseJSON(localStorage.getItem('JournalChapters' + gameid));
}
else{
this.chapters=[];
}
}
resolve(true);
}
}))
Promise.all(promises).then(() => {
if(is_abovevtt_page()){
this.build_journal();
}
if(window.DM && !is_gamelog_popout()){
// also sync the journal
window.JOURNAL?.sync();
}
});
}
persist(){
if(window.DM){
if(!this.statBlocks)
this.statBlocks = Object.fromEntries(Object.entries(this.notes).filter(([key, value]) => this.notes[key].statBlock == true));
let statBlocks = this.statBlocks
let chapters = this.chapters
let journal = Object.fromEntries(Object.entries(this.notes).filter(([key, value]) => this.notes[key].statBlock != true))
let storeImage = gameIndexedDb.transaction([`journalData`], "readwrite")
let objectStore = storeImage.objectStore(`journalData`)
let globalObjectStore = globalIndexedDB.transaction(["journalData"], "readwrite").objectStore(`journalData`)
let deleteRequest = globalObjectStore.delete(`JournalStatblocks`);
deleteRequest.onsuccess = (event) => {
const objectStoreRequest = globalObjectStore.add({journalId: `JournalStatblocks`, 'journalData': statBlocks});
};
deleteRequest.onerror = (event) => {
const objectStoreRequest = globalObjectStore.add({journalId: `JournalStatblocks`, 'journalData': statBlocks});
};
let journalDeleteRequest = objectStore.delete(`Journal`);
journalDeleteRequest.onsuccess = (event) => {
const objectStoreRequest = objectStore.add({journalId: `Journal`, 'journalData': journal});
};
journalDeleteRequest.onerror = (event) => {
const objectStoreRequest = objectStore.add({journalId: `Journal`, 'journalData': journal});
};
let chapterDeleteRequest = objectStore.delete(`JournalChapters`);
chapterDeleteRequest.onsuccess = (event) => {
const objectStoreRequest = objectStore.add({journalId: `JournalChapters`, 'journalData': chapters});
};
journalDeleteRequest.onerror = (event) => {
const objectStoreRequest = objectStore.add({journalId: `JournalChapters`, 'journalData': chapters});
};
try{
localStorage.setItem('JournalStatblocks', JSON.stringify(statBlocks)); //hold onto these until 1.27 then we can clear them.
localStorage.setItem('Journal' + this.gameid, JSON.stringify(journal));
localStorage.setItem('JournalChapters' + this.gameid, JSON.stringify(chapters));
}
catch(e){
console.warn('localStorage Journal Storage Failed', e)
}
}
}
sync(){
let self=this;
if(window.DM){
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
let sendNotes = [];
for(let i in self.notes){
if(self.notes[i].player){
self.notes[i].id = i;
sendNotes.push(self.notes[i])
}
}
self.sendNotes(sendNotes)
}
}
sendNotes(sendNotes){
let self=this;
if(sendNotes.length > 1 && JSON.stringify(sendNotes).length > 128000) {
let sendNotes1 = sendNotes.slice(0, parseInt(sendNotes.length/2))
let sendNotes2 = sendNotes.slice(parseInt(sendNotes.length/2), sendNotes.length)
self.sendNotes(sendNotes1);
self.sendNotes(sendNotes2);
}
else{
window.MB.sendMessage('custom/myVTT/notesSync',{
notes: sendNotes
});
}
}
build_journal(){
console.log('build_journal');
let self=this;
journalPanel.body.empty();
const row_add_chapter=$("<div class='row-add-chapter'></div>");
const input_add_chapter=$("<input type='text' placeholder='New folder name' class='input-add-chapter'>");
input_add_chapter.on('keypress',function(e){
if (e.which==13 && input_add_chapter.val() !== ""){
self.chapters.push({
title: input_add_chapter.val(),
collapsed: false,
notes: [],
});
self.persist();
self.build_journal();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
$(this).val('');
}
});
const btn_add_chapter=$("<button id='btn_add_chapter'>Add Folder</button>");
btn_add_chapter.click(function() {
if (input_add_chapter.val() == "") {
return;
}
self.chapters.push({
title: input_add_chapter.val(),
collapsed: false,
notes: []
});
self.persist();
self.build_journal();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
});
if(window.DM) {
row_add_chapter.append(input_add_chapter);
row_add_chapter.append(btn_add_chapter);
journalPanel.body.append(row_add_chapter);
}
// Create a chapter list that sorts journal-chapters with drag and drop
const chapter_list=$(`<ul class='folder-item-list'></ul>`);
chapter_list.sortable({
items: '.folder',
refreshPositions: true,
update: function(event, ui) {
// Find the old index of the dragged element
const old_index = self.chapters.findIndex(function(chapter) {
return chapter.id == ui.item.attr('data-id')
});
// Find the new index of the dragged element
const new_index = (old_index != -1) ? ui.item.index() : self.chapters.length-1;
// Move the dragged element to the new index
self.chapters.splice(new_index, 0, self.chapters.splice(old_index, 1)[0]);
self.persist();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
self.build_journal();
}
});
chapter_list.droppable({
accept: '#journal-panel .folder>.folder',
greedy: true,
tolerance: 'pointer',
drop: function(e,ui) {
let folderIndex = ui.draggable.attr('data-index');
if(self.chapters[folderIndex].parentID){
delete self.chapters[folderIndex].parentID;
}else{
// Find the new index of the dragged element
const new_index = (folderIndex != -1) ? ui.item.index() : self.chapters.length-1;
// Move the dragged element to the new index
self.chapters.splice(new_index, 0, self.chapters.splice(folderIndex, 1)[0]);
}
self.persist();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
self.build_journal();
}
});
journalPanel.body.append(chapter_list);
let chaptersWithLaterParents = [];
for(let i=0; i<self.chapters.length;i++){
if(!self.chapters[i].id){
self.chapters[i].id = uuid();
}
// A chapter title can be clicked to expand/collapse the chapter notes
let section_chapter=$(`
<div data-index='${i}' data-id='${self.chapters[i].id}' class='sidebar-list-item-row list-item-identifier folder ${self.chapters[i]?.collapsed ? 'collapsed' : ''}'></div>
`);
// Create a sortale list of notes
const note_list=$("<ul class='note-list'></ul>");
section_chapter.droppable({
accept: '#journal-panel .folder',
greedy: true,
tolerance: 'pointer',
drop: function(e,ui) {
let targetID = $(this).attr('data-id');
let targetIndex = $(this).attr('data-index');
let folderIndex = ui.draggable.attr('data-index');
if(self.chapters[folderIndex].id == targetID)
return;
self.chapters[folderIndex].parentID = targetID;
const new_index = targetIndex+1;
// Move the dragged element to the new index
self.chapters.splice(new_index, 0, self.chapters.splice(folderIndex, 1)[0]);
self.persist();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
self.build_journal();
}
})
let sender;
// Make the section_chapter sortable
section_chapter.sortable({
refreshPositions: true,
connectWith: "#journal-panel .folder",
items: '.sidebar-list-item-row',
receive: function(event, ui) {
// Called only in case B (with !!sender == true)
sender = ui.sender;
let sender_index = sender.attr('data-index');
let new_folder_index = ui.item.parent().closest('.folder').attr('data-index');
const old_index = self.chapters[sender_index].notes.findIndex(function(note) {
return note == ui.item.attr('data-id');
});
// Find the new index of the dragged element
const new_index = (old_index != -1) ? ui.item.index() : self.chapters.length-1;
// Move the dragged element to the new index
self.chapters[new_folder_index].notes.splice(new_index, 0, self.chapters[sender_index].notes.splice(old_index, 1)[0]);
self.persist();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
self.build_journal();
event.preventDefault();
},
update: function(event, ui) {
// Find the old index of the dragged element
if(sender==undefined){
if(ui.item.hasClass('folder')){
const old_index = self.chapters.findIndex(function(chapter) {
return chapter.id == ui.item.attr('data-id')
});
const new_index = ui.item.next().hasClass('folder') ? ui.item.next().attr('data-index') : ui.item.prev().attr('data-index') ;
self.chapters.splice(new_index, 0, self.chapters.splice(old_index, 1)[0]);
}
else{
const old_index = self.chapters[i].notes.findIndex(function(note) {
return note == ui.item.attr('data-id')
});
// Find the new index of the dragged element
const new_index = ui.item.index();
// Move the dragged element to the new index
self.chapters[i].notes.splice(new_index, 0, self.chapters[i].notes.splice(old_index, 1)[0]);
}
self.persist();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
self.build_journal();
}
}
});
let folderIcon = $(`<div class="sidebar-list-item-row-img"><img src="${window.EXTENSION_PATH}assets/folder.svg" class="token-image"></div>`)
let row_chapter_title=$("<div class='row-chapter'></div>");
let chapter_title=$(`<div class='journal-chapter-title' title='${self.chapters[i].title}'/>`);
chapter_title.text(self.chapters[i].title);
// If the user clicks the chapter title, expand/collapse the chapter notes
chapter_title.click(function(){
section_chapter.toggleClass('collapsed');
self.chapters[i].collapsed = !self.chapters[i].collapsed;
self.persist();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
});
let add_note_btn=$("<button class='token-row-button' ><span class='material-symbols-outlined'>add_notes</span></button>");
add_note_btn.click(function(){
let new_noteid=uuid();
const input_add_note=$("<input type='text' class='input-add-chapter' placeholder='New note title'>");
let note_added = false;
input_add_note.keydown(function(e){
if(e.keyCode == 13 && input_add_note.val() !== ""){
note_added = true;
let new_note_title=input_add_note.val();
self.notes[new_noteid]={
title: new_note_title,
text: "",
player: false,
plain: ""
};
self.chapters[i].notes.push(new_noteid);
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
self.edit_note(new_noteid);
self.persist();
self.build_journal();
}
if(e.keyCode==27){
self.build_journal();
}
});
input_add_note.blur(function(event){
if(!note_added) {
let e = $.Event('keydown');
e.keyCode = 13;
input_add_note.trigger(e);
}
});
row_notes_entry.empty();
const save_note_btn=$("<button class='btn-chapter-icon'><img src='"+window.EXTENSION_PATH+"assets/icons/save.svg'></button>");
row_notes_entry.append(save_note_btn);
row_notes_entry.append(input_add_note);
input_add_note.focus();
});
let add_fold_btn=$("<button class='token-row-button'><span class='material-icons'>create_new_folder</span></button>");
add_fold_btn.click(function(){
self.chapters.push({
title: "New Folder",
collapsed: false,
notes: [],
parentID: $(this).closest('.folder[data-id]').attr('data-id')
});
self.persist();
self.build_journal();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
});
row_chapter_title.append(folderIcon);
row_chapter_title.append(chapter_title);
if(window.DM) {
row_chapter_title.append(add_note_btn, add_fold_btn);
}
let containsPlayerNotes = false;
for(let n=0; n<self.chapters[i].notes.length;n++){
let note_id=self.chapters[i].notes[n];
if(self.notes[note_id]?.player == true || (self.notes[note_id]?.player instanceof Array && self.notes[note_id].player?.includes(`${window.myUser}`))){
containsPlayerNotes = true;
}
}
if(window.DM || containsPlayerNotes) {
section_chapter.append(row_chapter_title);
} else {
section_chapter.append(row_chapter_title);
section_chapter.hide();
}
if(!self.chapters[i].parentID){
chapter_list.append(section_chapter);
}
else{
let parentFolder = chapter_list.find(`.folder[data-id='${self.chapters[i].parentID}']`);
let parentID = self.chapters[i]?.parentID
if(self.chapters[i].id == self.chapters.filter(d => d.id == parentID)[0].parentID){
delete self.chapters[i].parentID
}
if(parentFolder.length == 0){
self.chapters.splice(self.chapters.length-1, 0, self.chapters.splice(i, 1)[0]);
i -= 1;
continue;
}
let containsPlayerNotes = false;
for(let n=0; n<self.chapters[i].notes.length;n++){
let note_id=self.chapters[i].notes[n];
if(self.notes[note_id]?.player == true || (self.notes[note_id]?.player instanceof Array && self.notes[note_id]?.player.includes(`${window.myUser}`))){
containsPlayerNotes = true;
}
}
if(window.DM || containsPlayerNotes) {
parentFolder.append(section_chapter);
parentFolder.show();
parentFolder.parents().show();
} else {
parentFolder.append(section_chapter);
section_chapter.hide();
}
}
journalPanel.body.append(chapter_list);
for(let n=0; n<self.chapters[i].notes.length;n++){
let note_id=self.chapters[i].notes[n];
if(! (note_id in self.notes))
continue;
if( (! window.DM) && (self.notes[note_id]?.player == false || (self.notes[note_id]?.player instanceof Array && !self.notes[note_id]?.player.includes(`${window.myUser}`))) )
continue;
let prependIcon = (self.notes[note_id].player && window.DM) ? $(`<span class="material-symbols-outlined" style='font-size:12px'>share</span>`) : '';
let entry=$(`<div class='sidebar-list-item-row-item sidebar-list-item-row' data-id='${note_id}'></div>`);
let entry_title=$(`<div class='sidebar-list-item-row-details sidebar-list-item-row-details-title' title='${self.notes[note_id].title}'></div>`);
entry_title.text(self.notes[note_id].title);
if(!self.notes[note_id].ddbsource){
entry_title.click(function(){
self.display_note(note_id);
});
}
else{
entry_title.click(function(){
render_source_chapter_in_iframe(self.notes[note_id].ddbsource);
});
}
let rename_btn = $("<button class='token-row-button'><img src='"+window.EXTENSION_PATH+"assets/icons/rename-icon.svg'></button>");
rename_btn.click(function(){
//Convert the note title to an input field and focus it
const input_note_title=$(`
<input type='text' class='input-add-chapter' value='${self.notes[note_id].title}'>
`);
input_note_title.keypress(function(e){
if (e.which == 13 && input_note_title.val() !== "") {
self.notes[note_id].title = input_note_title.val();
self.sendNotes([self.notes[note_id]]);
self.persist();
self.build_journal();
}
// If the user presses escape, cancel the edit
if (e.which == 27) {
self.build_journal();
}
});
input_note_title.off('click').on('click', function(e){
e.stopPropagation();
})
input_note_title.blur(function(event){
let e = $.Event('keypress');
e.which = 13;
input_note_title.trigger(e);
});
entry_title.empty();
entry_title.append(input_note_title);
entry_title.append(edit_btn);
input_note_title.focus();
// Convert the edit button to a save button
rename_btn.empty();
rename_btn.append(`
<img src='${window.EXTENSION_PATH}assets/icons/save.svg'>
`);
});
let edit_btn=$("<button class='token-row-button'><span class='material-symbols-outlined'>edit_note</span></button>");
edit_btn.click(function(){
window.JOURNAL.edit_note(note_id);
});
let note_index=n;
entry.append(prependIcon);
entry.append(entry_title);
if(window.DM){
if(!self.notes[note_id].ddbsource){
entry.append(edit_btn);
}
}
note_list.append(entry);
}
// Create an add note button, when clicked, insert an input field above the button.
// When the user presses enter, create a new note and insert it into the chapter.
// If the user presses escape, cancel the edit.
// If the user clicks outside the input field, cancel the edit.
const row_notes_entry = $("<div class='row-notes-entry'/>");
if(window.DM){
let entry=$("<div class='journal-note-entry'></div>");
entry.append(row_notes_entry);
note_list.append(entry);
}
section_chapter.append(note_list);
}
if(!window.journalsortable)
$('#journal-panel .ui-sortable').sortable('disable');
let sort_button = $(`<button class="token-row-button reorder-button" title="Reorder Journal"><span class="material-icons">reorder</span></button>`);
sort_button.on('click', function(){
if($('#journal-panel .ui-sortable-disabled').length > 0){
$('#journal-panel .ui-sortable').sortable('enable');
window.journalsortable = true;
}
else{
$('#journal-panel .ui-sortable').sortable('disable');
window.journalsortable = false;
}
});
if(window.DM){
let chapterImport = $(`<select id='ddb-source-journal-import'><option value=''>Select a source to import</option></select>`);
chapterImport.append($(`<option value='/magic-items'>Magic Items</option>`));
chapterImport.append($(`<option value='/feats'>Feats</option>`));
chapterImport.append($(`<option value='/spells'>Spells</option>`));
for(let source in window.ddbConfigJson.sources){
const currentSource = window.ddbConfigJson.sources[source]
if(currentSource.sourceURL == '')
continue;
const sourcetitle = currentSource.description;
const sourceValue = currentSource.sourceURL.replaceAll(/sources\//gi, '');
chapterImport.append($(`<option value='${sourceValue}'>${sourcetitle}</option>`));
}
chapterImport.on('change', function(){
let source = this.value;
if (source == '/magic-items' || source == '/feats' || source == '/spells'){
let new_noteid=uuid();
let new_note_title = source.replaceAll(/-/g, ' ')
.replaceAll(/\//g, '')
.replaceAll(/\b\w/g, l => l.toUpperCase());
self.notes[new_noteid]={
title: new_note_title,
text: "",
player: false,
plain: "",
ddbsource: `https://dndbeyond.com${source}`
};
let chapter = self.chapters.find(x => x.title == 'Compendium')
if(!chapter){
self.chapters.push({
title: 'Compendium',
collapsed: false,
notes: [],
});
chapter = self.chapters[self.chapters.length-1];
}
chapter.notes.push(new_noteid);
self.persist();
self.build_journal();
}
else{
self.chapters.push({
title: window.ddbConfigJson.sources.find(d=> d.sourceURL.includes(source))?.description,
collapsed: false,
notes: [],
});
window.ScenesHandler.build_adventures(function() {
window.ScenesHandler.build_chapters(source, function(){
for(let chapter in window.ScenesHandler.sources[source].chapters){
let new_noteid=uuid();
let new_note_title = window.ScenesHandler.sources[source].chapters[chapter].title;
self.notes[new_noteid]={
title: new_note_title,
text: "",
player: false,
plain: "",
ddbsource: window.ScenesHandler.sources[source].chapters[chapter].url
};
self.chapters[self.chapters.length-1].notes.push(new_noteid);
}
self.persist();
self.build_journal();
});
});
}
})
$('#journal-panel .sidebar-panel-body').prepend(sort_button, chapterImport);
$.contextMenu({
selector: "#journal-panel .row-chapter",
build: function(element, e) {
let menuItems = {};
let i = window.JOURNAL.chapters.findIndex(d=>d.id==$(element).closest('[data-id]').attr('data-id'))
menuItems["rename"] = {
name: "Rename",
callback: function(itemKey, opt, originalEvent) {
let input_chapter_title=$(`<input type='text' class='input-add-chapter' value='${self.chapters[i].title}'>`);
input_chapter_title.keypress(function(e){
if (e.which == 13 && input_chapter_title.val() !== "") {
self.chapters[i].title = input_chapter_title.val();
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
self.persist();
self.build_journal();
}
// If the user presses escape, cancel the edit
if (e.which == 27) {
self.build_journal();
}
});
input_chapter_title.off('click.prevent').on('click.prevent', function(e){
e.stopPropagation();
})
input_chapter_title.blur(function(){
let e = $.Event('keypress');
e.which = 13;
input_chapter_title.trigger(e);
});
let row_chapter_title = $(element).find('.journal-chapter-title');
row_chapter_title.empty();
row_chapter_title.append(input_chapter_title);
input_chapter_title.focus();
}
};
menuItems['export'] = {
name: "Export Folder",
callback: function (itemKey, opt, e) {
let folder_export = function(notes, chapters) {
build_import_loading_indicator('Preparing Export File');
let DataFile = {
version: 2,
scenes: [{}],
tokencustomizations: [],
notes: {},
journalchapters: [],
soundpads: {}
};
let currentdate = new Date();
let datetime = `${currentdate.getFullYear()}-${(currentdate.getMonth()+1)}-${currentdate.getDate()}`
DataFile.notes = notes;
DataFile.journalchapters = chapters;
download(b64EncodeUnicode(JSON.stringify(DataFile,null,"\t")),`${window.CAMPAIGN_INFO.name}-${datetime}-note.abovevtt`,"text/plain");
$(".import-loading-indicator").remove();
}
let exportNoteChapters = function(chapterId, chaptertoExport){
for(let i = 0; i<self.chapters.length; i++){
if(self.chapters[i].parentID == chapterId){
exportNoteChapters(self.chapters[i].id, chaptertoExport);
chaptertoExport.push(self.chapters[i]);
}
}
};
let notesToExport = function(chapters, notes){
for(let k in chapters){
for(let j in chapters[k].notes){
let noteId = chapters[k].notes[j];
notes[noteId] = self.notes[chapters[k].notes[j]];
}
}
}
let currentChapter = {...window.JOURNAL.chapters[i]};
delete currentChapter.parentID;
let chaptersArray = [currentChapter];
exportNoteChapters(window.JOURNAL.chapters[i].id, chaptersArray)
let notesObject = {};
notesToExport(chaptersArray, notesObject);
folder_export(notesObject, chaptersArray);
}
};
menuItems["delete"] = {
name: "Delete",
callback: function(itemKey, opt, originalEvent) {
if(confirm("Delete this chapter and all the contained notes?")){
for(let k=0;k<self.chapters[i].notes.length;k++){
let nid=self.chapters[i].notes[k];
delete self.notes[nid];
}
self.chapters = self.chapters.filter(d => d.id != self.chapters[i].id)
$(element).closest('.folder').find('.folder').each(function(){
let folderId = $(this).attr('data-id');
let chapter = self.chapters.filter(d => d.id == folderId)[0];
for(let k=0;k<chapter.notes.length;k++){
let nid=chapter.notes[k];
delete self.notes[nid];
}
self.chapters = self.chapters.filter(d => d.id != folderId)
})
window.MB.sendMessage('custom/myVTT/JournalChapters',{
chapters: self.chapters
});
self.persist();
self.build_journal();
}
}
};
if (Object.keys(menuItems).length === 0) {
menuItems["not-allowed"] = {
name: "You are not allowed to configure this item",
disabled: true
};
}
return { items: menuItems };
}
});
$.contextMenu({
selector: "#journal-panel .note-list .sidebar-list-item-row",
build: function(element, e) {
let menuItems = {};
let note_id = $(element).closest('[data-id]').attr('data-id');
let i = window.JOURNAL.chapters.findIndex(d=>d.id==$(element).closest('.folder[data-id]').attr('data-id'))
let note_index =window.JOURNAL.chapters[i].notes.indexOf(note_id)
menuItems["rename"] = {
name: "Rename",
callback: function(itemKey, opt, originalEvent) {
//Convert the note title to an input field and focus it
const input_note_title=$(`
<input type='text' class='input-add-chapter' value='${self.notes[note_id].title}'>
`);
input_note_title.keypress(function(e){
if (e.which == 13 && input_note_title.val() !== "") {
self.notes[note_id].title = input_note_title.val();
self.sendNotes([self.notes[note_id]]);
self.persist();
self.build_journal();
}
// If the user presses escape, cancel the edit
if (e.which == 27) {
self.build_journal();
}
});
input_note_title.off('click').on('click', function(e){
e.stopPropagation();
})
input_note_title.blur(function(event){
let e = $.Event('keypress');
e.which = 13;
input_note_title.trigger(e);
});
let entry_title = $(element).find('.sidebar-list-item-row-details-title');
entry_title.append(input_note_title);
input_note_title.focus();
}
};
menuItems["copyLink"] = {
name: "Copy Note Link",
callback: function(itemKey, opt, originalEvent) {
let copyLink = `[note]${note_id};${self.notes[note_id].title}[/note]`
navigator.clipboard.writeText(copyLink);
}
};
menuItems['export'] = {
name: "Export Note",
callback: function (itemKey, opt, e) {
let note_export = function(notes, chapters) {
build_import_loading_indicator('Preparing Export File');
let DataFile = {
version: 2,
scenes: [{}],
tokencustomizations: [],
notes: {},
journalchapters: [],
soundpads: {}
};
let currentdate = new Date();
let datetime = `${currentdate.getFullYear()}-${(currentdate.getMonth()+1)}-${currentdate.getDate()}`
DataFile.notes = notes;
DataFile.journalchapters = chapters;
download(b64EncodeUnicode(JSON.stringify(DataFile,null,"\t")),`${window.CAMPAIGN_INFO.name}-${datetime}-note.abovevtt`,"text/plain");
$(".import-loading-indicator").remove();
}
let exportNote = {};
exportNote[note_id] = self.notes[note_id];
let currentChapter = {...window.JOURNAL.chapters[i]};
delete currentChapter.parentID;
let chapterToExport = [currentChapter];
note_export(exportNote, chapterToExport);
}
};
menuItems["delete"] = {
name: "Delete",
callback: function(itemKey, opt, originalEvent) {
if(confirm("Delete this note?")){
console.log("deleting note_index"+note_index);
self.chapters[i].notes.splice(note_index,1);
delete self.notes[note_id];
self.build_journal();
self.persist();
window.MB.sendMessage('custom/myVTT/JournalChapters', {
chapters: self.chapters
});
}
}
};
if (Object.keys(menuItems).length === 0) {
menuItems["not-allowed"] = {
name: "You are not allowed to configure this item",
disabled: true
};
}
return { items: menuItems };
}
});
}
}
display_note(id, statBlock = false){
let self=this;
let note=$("<div class='note'></div>");
note.attr('title',self.notes[id].title);
if(window.DM){
let visibility_container=$("<div class='visibility-container'/>");