-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathTokensPanel.js
4821 lines (4446 loc) · 210 KB
/
TokensPanel.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
mytokens = [];
mytokensfolders = [];
tokens_rootfolders = [];
monster_search_filters = {};
encounter_monster_items = {}; // encounterId: SidebarTokenItem[]
cached_monster_items = {}; // monsterId: SidebarTokenItem
aoe_items = [];
open5e_monsters = [];
open5e_next = '';
cached_open5e_items = {};
async function getOpen5e(results = [], search = ''){
let ddbMonsterTypes = {
1: 'Aberration',
2: 'Beast',
3: 'Celestial',
4: 'Construct',
6: 'Dragon',
7: 'Elemental',
8: 'Fey',
9: 'Fiend',
10: 'Giant',
11: 'Humanoid',
13: 'Monstrosity',
14: 'Ooze',
15: 'Plant',
16: 'Undead'
}
const maxCR = (monster_search_filters?.challengeRatingMax) ? monster_search_filters?.challengeRatingMax : '';
const minCR = (monster_search_filters?.challengeRatingMin) ? monster_search_filters?.challengeRatingMin : '';
const monsterTypes = (monster_search_filters?.monsterTypes) ? monster_search_filters.monsterTypes.map(item=> item = ddbMonsterTypes[item]).toString() : '';
let api_url = `https://api.open5e.com/monsters/?slug__in=&slug__iexact=&slug=&name__iexact=&name=&cr=&cr__range=&cr__gt=${minCR}&cr__gte=&cr__lt=${maxCR}&cr__lte=&armor_class=&armor_class__range=&armor_class__gt=&armor_class__gte=&armor_class__lt=&armor_class__lte=&type__iexact=&type=&type__in=${monsterTypes}&type__icontains=&page_no=&page_no__range=&page_no__gt=&page_no__gte=&page_no__lt=&page_no__lte=&document__slug__iexact=&document__slug=&document__slug__in=&document__slug__not_in=&search=${search}`
let jsonData = {}
await $.getJSON(api_url, function(data){
jsonData = data;
});
for (let i = 0; i < jsonData.results.length; i++) {
jsonData.results[i] = convert_open5e_monsterData(jsonData.results[i])
}
results = results.concat(jsonData.results)
open5e_monsters = results;
open5e_next = jsonData.next;
inject_open5e_monster_list_items();
return open5e_monsters;
}
async function getGroupOpen5e(slugin){
let api_url = `https://api.open5e.com/monsters/?ordering=name&slug__in=${slugin}&slug__iexact=&slug=&name__iexact=&name=&cr=&cr__range=&cr__gt=&cr__gte=&cr__lt=&cr__lte=&armor_class=&armor_class__range=&armor_class__gt=&armor_class__gte=&armor_class__lt=&armor_class__lte=&type__iexact=&type=&type__in=&type__icontains=&page_no=&page_no__range=&page_no__gt=&page_no__gte=&page_no__lt=&page_no__lte=&document__slug__iexact=&document__slug=&document__slug__in=&document__slug__not_in=`
let jsonData = {}
await $.getJSON(api_url, function(data){
jsonData = data;
});
for (let i = 0; i < jsonData.results.length; i++) {
jsonData.results[i] = convert_open5e_monsterData(jsonData.results[i])
}
return jsonData.results;
}
async function getNextOpen5e(results = open5e_monsters, nextPage){
let jsonData = {}
await $.getJSON(nextPage, function(data){
jsonData = data;
});
results = results.concat(jsonData.results)
for (let i = 0; i < jsonData.results.length; i++) {
jsonData.results[i] = convert_open5e_monsterData(jsonData.results[i])
}
open5e_monsters = results;
open5e_next = jsonData.next;
return open5e_monsters;
}
/** Reads in tokendata, and writes to mytokens and mytokensfolders; marks tokendata objects with didMigrateToMyToken = false; */
function migrate_tokendata() {
let migratedFolders = [];
let migratedTokens = [];
const migrateFolderAtPath = function(oldFolderPath) {
let currentFolderPath = sanitize_folder_path(oldFolderPath);
let folder = convert_path(currentFolderPath);
if (folder.tokens) {
for(let tokenKey in folder.tokens) {
let oldToken = folder.tokens[tokenKey];
if (oldToken.didMigrateToMyToken === true) {
// this token has already been migrated no need to migrate it again
continue;
}
let newToken = {};
for (let k in oldToken) {
let v = oldToken[k];
if (k === "data-token-size") {
newToken.tokenSize = v;
} else if (k === "data-alternative-images") {
newToken.alternativeImages = v;
} else if (k.startsWith("data-")) {
newToken[k.replace("data-", "")] = v;
} else {
newToken[k] = v;
}
}
if (newToken.name === undefined) {
newToken.name = tokenKey;
}
newToken.folderPath = currentFolderPath;
newToken.image = parse_img(newToken.img);
delete newToken.img;
let existing = migratedTokens.find(t => t.name === newToken.name && t.folderPath === newToken.folderPath)
if (existing !== undefined) {
console.log("migrate_to_my_tokens not adding duplicate token", newToken);
} else {
console.log("migrate_to_my_tokens successfully migrated token", newToken, "from", oldToken);
migratedTokens.push(newToken);
}
oldToken.didMigrateToMyToken = true;
}
}
if (folder.folders) {
for (let folderKey in folder.folders) {
if (folderKey.includes("AboveVTT BUILTIN")) {
continue; // not migrating built in tokens
}
migratedFolders.push({ name: folderKey, folderPath: currentFolderPath, collapsed: true });
migrateFolderAtPath(`${currentFolderPath}/${folderKey}`);
}
}
}
migrateFolderAtPath(RootFolder.Root.path);
return migrate_convert_mytokens_to_customizations(migratedFolders, migratedTokens);
}
/** erases mytokens and mytokensfolders; marks tokendata objects with didMigrateToMyToken = false; */
function rollback_from_my_tokens() {
console.warn("rollback_from_my_tokens is no longer supported");
return;
console.group("rollback_from_my_tokens");
tokendata.didMigrateToMyToken = false;
mytokens = [];
mytokensfolders = [];
persist_my_tokens();
const rollbackFolderAtPath = function(oldFolderPath) {
let currentFolderPath = sanitize_folder_path(oldFolderPath);
let folder = convert_path(currentFolderPath);
console.log("attempting to roll back all tokens in folder", currentFolderPath, folder);
if (folder.tokens) {
for (let tokenKey in folder.tokens) {
let oldToken = folder.tokens[tokenKey];
oldToken.didMigrateToMyToken = false;
console.log("rolling back oldToken", oldToken);
}
}
for (let folderName in folder.folders) {
let nextFolderPath = `${currentFolderPath}/${folderName}`;
rollbackFolderAtPath(nextFolderPath);
}
};
rollbackFolderAtPath(RootFolder.Root.path);
persist_customtokens();
console.groupEnd();
}
function list_item_from_monster_id(monsterId) {
let found = cached_monster_items[monsterId];
if (found === undefined) {
found = window.monsterListItems.find(i => i.monsterData.id === monsterId);
}
if (found === undefined) {
for (let encounterId in encounter_monster_items) {
if (found === undefined) {
let encounterMonsters = encounter_monster_items[encounterId];
found = encounterMonsters.find(i => i.monsterData.id === monsterId);
}
}
}
return found;
}
function list_item_from_player_id(playerId) {
// TODO: use find find_pc_by_player_id here? It would add an "unknown player" to the list. This would be useful when allowing players to guest DM when other players have a private character sheet
let pc = window.pcs.find(p => p.sheet.includes(playerId));
if (pc === undefined) return undefined;
let fullPath = sanitize_folder_path(`${RootFolder.Players.path}/${pc.name}`);
return find_sidebar_list_item_from_path(fullPath);
}
function list_item_from_token(placedToken) {
let listItemPath = placedToken.options.listItemPath;
if (listItemPath !== undefined && listItemPath.length > 0) {
// this token was placed after we unified tokens
return find_sidebar_list_item_from_path(listItemPath);
}
if (placedToken.isMonster()) {
// we can't figure this one out synchronously
return list_item_from_monster_id(placedToken.options.monster);
} else if (placedToken.isPlayer()) {
return list_item_from_player_id(placedToken.options.id);
} else {
// need to migrate from the old custom_tokens
let tokenDataPath = placedToken.options.tokendatapath !== undefined ? placedToken.options.tokendatapath : "";
let tokenDataName = placedToken.options.tokendataname !== undefined ? placedToken.options.tokendataname : placedToken.options.name;
if (tokenDataPath.startsWith("/AboveVTT BUILTIN")) {
let convertedPath = tokenDataPath.replace("/AboveVTT BUILTIN", RootFolder.AboveVTT.path);
let fullPath = sanitize_folder_path(`${convertedPath}/${tokenDataName}`);
return find_sidebar_list_item_from_path(fullPath);
} else {
let fullPath = sanitize_folder_path(`${RootFolder.MyTokens.path}/${tokenDataPath}/${tokenDataName}`);
return find_sidebar_list_item_from_path(fullPath);
}
}
}
/**
* Finds a "Builtin Token" that matches the given path
* @param fullPath {string} the path of the "Builtin Token" you're looking for
* @returns {undefined|*} the "Builtin Token" object if found; else undefined
*/
function find_builtin_token(fullPath) {
if (!fullPath.startsWith(RootFolder.AboveVTT.path)) {
console.warn("find_builtin_token was called with the wrong token type.", fullPath, "should start with", RootFolder.AboveVTT.path);
return undefined;
}
console.group("find_builtin_token");
let found = builtInTokens.find(t => {
let dirtyPath = `${RootFolder.AboveVTT.path}${t.folderPath}/${t.name}`;
let fullTokenPath = sanitize_folder_path(dirtyPath);
console.debug("looking for: ", fullPath, dirtyPath, fullTokenPath, fullTokenPath === fullPath, t);
return fullTokenPath === fullPath;
});
console.debug("found: ", found);
console.groupEnd();
return found;
}
function backfill_mytoken_folders() {
mytokens.forEach(myToken => {
if (myToken.folderPath !== RootFolder.Root.path) {
// we split the path and backfill empty every folder along the way if needed. This is really important for folders that hold subfolders, but not items
let parts = myToken.folderPath.split("/");
let backfillPath = "";
parts.forEach(part => {
let fullBackfillPath = sanitize_folder_path(`${backfillPath}/${part}`);
if (fullBackfillPath !== RootFolder.Root.path && !mytokensfolders.find(fi => sanitize_folder_path(`${fi.folderPath}/${fi.name}`) === fullBackfillPath)) {
// we don't have this folder yet so add it
let newFolder = { folderPath: sanitize_folder_path(backfillPath), name: part, collapsed: true };
console.log("adding folder", newFolder);
mytokensfolders.push(newFolder);
} else {
console.log("not adding folder", fullBackfillPath);
}
backfillPath = fullBackfillPath;
});
}
});
}
/**
* iterates over all the token sources and replaces window.tokenListItems with new objects.
* token sources are window.pcs, mytokens, mytokensfolders, and builtInTokens
*/
function rebuild_token_items_list() {
if (!window.DM) return;
console.group("rebuild_token_items_list");
try {
backfill_mytoken_folders(); // just in case we're missing any folders
// Players
let tokenItems = window.pcs
.filter(pc => pc.sheet !== undefined && pc.sheet !== "")
.map(pc => SidebarListItem.PC(pc.sheet, pc.name, pc.image));
// My Tokens Folders
window.TOKEN_CUSTOMIZATIONS
.filter(tc => tc.tokenType === ItemType.Folder && tc.fullPath().startsWith(RootFolder.MyTokens.path))
.forEach(tc => {
tokenItems.push(SidebarListItem.Folder(tc.id, tc.folderPath(), tc.name(), tc.tokenOptions.collapsed, tc.parentId, ItemType.MyToken, tc.color))
})
// My Tokens
window.TOKEN_CUSTOMIZATIONS
.filter(tc => tc.tokenType === ItemType.MyToken)
.forEach(tc => tokenItems.push(SidebarListItem.MyToken(tc)))
// AboveVTT Tokens
let allBuiltinPaths = builtInTokens
.filter(item => item.folderPath !== RootFolder.Root.path && item.folderPath !== "" && item.folderPath !== undefined)
.map(item => item.folderPath);
let builtinPaths = [...new Set(allBuiltinPaths)];
for (let i = 0; i < builtinPaths.length; i++) {
let path = builtinPaths[i];
let pathComponents = path.split("/");
let folderName = pathComponents.pop();
let folderPath = pathComponents.join("/");
let builtinFolderPath = sanitize_folder_path(`${RootFolder.AboveVTT.path}/${folderPath}`);
tokenItems.push(
SidebarListItem.Folder(path_to_html_id(builtinFolderPath, folderName),
builtinFolderPath,
folderName,
true,
builtinFolderPath === RootFolder.AboveVTT.path ? RootFolder.AboveVTT.id : path_to_html_id(builtinFolderPath),
ItemType.BuiltinToken
)
);
}
for (let i = 0; i < builtInTokens.length; i++) {
tokenItems.push(SidebarListItem.BuiltinToken(builtInTokens[i]));
}
// Encounters and Encounter Monsters
for (const encounterId in window.EncounterHandler.encounters) {
let encounter = window.EncounterHandler.encounters[encounterId];
if (encounter.name === "AboveVTT") continue; // don't display our backing encounter
tokenItems.push(SidebarListItem.Encounter(encounter));
// encounter_monster_items[encounterId]?.forEach(monsterItem => tokenItems.push(monsterItem));
}
window.tokenListItems = tokenItems.concat(aoe_items);
rebuild_ddb_npcs();
update_token_folders_remembered_state();
console.groupEnd();
} catch (error) {
console.groupEnd();
console.error("rebuild_token_items_list caught an unexpected error", error);
}
}
/**
* replaces window.monsterListItems with a list of items where the item.name matches the searchTerm (case-insensitive)
* @param searchTerm {string} the search term that the user typed into the search input
*/
function filter_token_list(searchTerm) {
if (typeof searchTerm !== "string") {
searchTerm = "";
}
console.log("filter_token_list searchTerm", searchTerm)
$('.custom-token-list').hide();
redraw_token_list(searchTerm);
if (searchTerm.length > 0) {
let allFolders = tokensPanel.body.find(".folder");
allFolders.removeClass("collapsed"); // auto expand all folders
for (let i = 0; i < allFolders.length; i++) {
let currentFolder = $(allFolders[i]);
if (matches_full_path(currentFolder, RootFolder.Monsters.path) || matches_full_path(currentFolder, RootFolder.Open5e.path) ) {
// we always want the monsters folder to be open when searching
continue;
}
let nonFolderDescendents = currentFolder.find(".sidebar-list-item-row:not(.folder)");
if (nonFolderDescendents.length === 0) {
// hide folders without results in them
currentFolder.hide();
}
}
}
console.log("filter_token_list about to call inject_monster_tokens");
window.monsterListItems = []; // don't let this grow unbounded
window.open5eListItems = [];
open5e_monsters = [];
inject_monster_tokens(searchTerm, 0);
getOpen5e(open5e_monsters, searchTerm);
$('.custom-token-list').show();
}
/**
* Calls the DDB API to search for monsters matching the given searchTerm and injects the results into the sidebar panel
* @param searchTerm {string} the search term that the user typed into the search input
* @param skip {number} the pagination offset. This function will inject a "Load More" button with the skip details embedded. You don't need to pass anything for this.
*/
function inject_monster_tokens(searchTerm, skip, addedList=[]) {
console.log("inject_monster_tokens about to call search_monsters");
search_monsters(searchTerm, skip, function (monsterSearchResponse) {
let listItems = addedList;
let remainderItems = 0;
for (let i = 0; i < monsterSearchResponse.data.length; i++) {
if(listItems.length == 10){
remainderItems = 10 - i;
break;
}
let m = monsterSearchResponse.data[i];
let item = SidebarListItem.Monster(m)
if(window.ownedMonstersOnly && !item.monsterData.isReleased && item.monsterData.homebrewStatus != 1){
continue;
}
window.monsterListItems.push(item);
listItems.push(item);
}
console.log("search_monsters converted", listItems);
let monsterFolder = find_html_row_from_path(RootFolder.Monsters.path, tokensPanel.body);
if(listItems.length < 10 && monsterSearchResponse.pagination.total > (monsterSearchResponse.pagination.skip + 10)){
inject_monster_tokens(searchTerm, skip + 10, listItems);
}
else{
inject_monster_list_items(listItems);
if (searchTerm.length > 0) {
monsterFolder.removeClass("collapsed");
}
console.log("search_monster pagination ", monsterSearchResponse.pagination.total, monsterSearchResponse.pagination.skip, monsterSearchResponse.pagination.total > monsterSearchResponse.pagination.skip);
monsterFolder.find(".load-more-button").remove();
if (monsterSearchResponse.pagination.total > (monsterSearchResponse.pagination.skip - remainderItems + 10)) {
// add load more button
let loadMoreButton = $(`<button class="ddbeb-button load-more-button" data-skip="${monsterSearchResponse.pagination.skip}">Load More</button>`);
loadMoreButton.click(function(loadMoreClickEvent) {
console.log("load more!", loadMoreClickEvent);
let previousSkip = parseInt($(loadMoreClickEvent.currentTarget).attr("data-skip"));
inject_monster_tokens(searchTerm, previousSkip - remainderItems + 10);
});
monsterFolder.find(`> .folder-item-list`).append(loadMoreButton);
}
}
});
}
function inject_monster_list_items(listItems) {
let monsterFolder = find_html_row_from_path(RootFolder.Monsters.path, tokensPanel.body);
if (monsterFolder === undefined || monsterFolder.length === 0) {
console.warn("inject_monster_list_items failed to find the monsters folder");
return;
}
let list = monsterFolder.find(`> .folder-item-list`);
for (let i = 0; i < listItems.length; i++) {
let item = listItems[i];
let row = build_sidebar_list_row(item);
enable_draggable_token_creation(row);
list.append(row);
}
}
function inject_open5e_monster_list_items(listItems = open5e_monsters) {
let monsterFolder = find_html_row_from_path(RootFolder.Open5e.path, tokensPanel.body);
if (monsterFolder === undefined || monsterFolder.length === 0) {
console.warn("inject_monster_list_items failed to find the monsters folder");
return;
}
let list = monsterFolder.find(`> .folder-item-list`);
for (let i = 0; i < listItems.length; i++) {
let item = SidebarListItem.open5eMonster(listItems[i]);
window.open5eListItems.push(item);
let row = build_sidebar_list_row(item);
enable_draggable_token_creation(row);
list.append(row);
}
if(open5e_next){
// add load more button
let loadMoreButton = $(`<button class="ddbeb-button open5e-load-more load-more-button">Load More</button>`);
loadMoreButton.click(async function(loadMoreClickEvent) {
console.log("load more!", loadMoreClickEvent);
open5e_monsters = await getNextOpen5e(open5e_monsters, open5e_next);
$('.open5e-load-more').remove();
monsterFolder.find('.folder-item-list').empty();
inject_open5e_monster_list_items(open5e_monsters);
});
monsterFolder.find(`> .folder-item-list`).append(loadMoreButton);
}
}
/** Called on startup. It reads from localStorage, and initializes all the things needed for the TokensPanel to function properly */
function init_tokens_panel() {
console.log("init_tokens_panel");
tokens_rootfolders = [
SidebarListItem.Folder(RootFolder.Players.id, RootFolder.Root.path, RootFolder.Players.name, false, path_to_html_id(RootFolder.Root.path), ItemType.PC),
SidebarListItem.Folder(RootFolder.Monsters.id, RootFolder.Root.path, RootFolder.Monsters.name, false, path_to_html_id(RootFolder.Root.path), ItemType.Monster),
SidebarListItem.Folder(RootFolder.Open5e.id, RootFolder.Root.path, RootFolder.Open5e.name, false, path_to_html_id(RootFolder.Root.path), ItemType.Open5e),
SidebarListItem.Folder(RootFolder.MyTokens.id, RootFolder.Root.path, RootFolder.MyTokens.name, false, path_to_html_id(RootFolder.Root.path), ItemType.MyToken),
SidebarListItem.Folder(RootFolder.AboveVTT.id, RootFolder.Root.path, RootFolder.AboveVTT.name, false, path_to_html_id(RootFolder.Root.path), ItemType.BuiltinToken),
SidebarListItem.Folder(RootFolder.DDB.id, RootFolder.Root.path, RootFolder.DDB.name, false, path_to_html_id(RootFolder.Root.path), ItemType.DDBToken),
SidebarListItem.Folder(RootFolder.Encounters.id, RootFolder.Root.path, RootFolder.Encounters.name, false, path_to_html_id(RootFolder.Root.path), ItemType.Encounter),
SidebarListItem.Folder(RootFolder.Aoe.id, RootFolder.Root.path, RootFolder.Aoe.name, false, path_to_html_id(RootFolder.Root.path), ItemType.Aoe)
];
aoe_items = [
SidebarListItem.Aoe("square", 1, "acid"),
SidebarListItem.Aoe("circle", 1, "acid"),
SidebarListItem.Aoe("cone", 1, "acid"),
SidebarListItem.Aoe("line", 1, "acid")
]
hiddenFolderItems = (JSON.parse(localStorage.getItem(`${window.gameId}.hiddenFolderItems`)) != null) ? JSON.parse(localStorage.getItem(`${window.gameId}.hiddenFolderItems`)) : [];
if(localStorage.getItem('MyTokens') != null){
mytokens = $.parseJSON(localStorage.getItem('MyTokens'));
}
if(localStorage.getItem('MyTokensFolders') != null){
mytokensfolders = $.parseJSON(localStorage.getItem('MyTokensFolders'));
}
if(localStorage.getItem('CustomTokens') != null){
tokendata=$.parseJSON(localStorage.getItem('CustomTokens'));
}
$("#switch_tokens").click()
migrate_tokendata(tokendata);
migrate_token_customizations();
rebuild_token_items_list();
let header = tokensPanel.header;
// TODO: remove this warning once tokens are saved in the cloud
tokensPanel.updateHeader("Tokens");
add_expand_collapse_buttons_to_header(tokensPanel, true);
let searchInput = $(`<input name="token-search" type="search" style="width:96%;margin:2%" placeholder="search tokens">`);
searchInput.off("input").on("input", mydebounce(() => {
let textValue = tokensPanel.header.find("input[name='token-search']").val();
filter_token_list(textValue);
}, 500));
searchInput.off("keyup").on('keyup', function(event) {
if (event.key === "Escape") {
$(event.target).blur();
}
});
header.append(searchInput);
register_token_row_context_menu(); // context menu for each row
register_custom_token_image_context_menu(); // context menu for images within the customization modal
read_local_monster_search_filters();
window.monsterListItems = []; // don't let this grow unbounded
window.open5eListItems = [];
setTimeout(function () {
// give it a couple of second to make sure everything is rendered before fetching the base monsters
// this isn't ideal, but the loading screen is up for much longer anyway...
filter_token_list("");
}, 2000);
}
function redraw_token_list_item(item){
const row = build_sidebar_list_row(item);
let oldRow = $(`#${item.id}`);
if (oldRow.length === 0) {
oldRow = find_html_row_from_path(item.fullPath(), tokensPanel.body)
}
$(oldRow).replaceWith(row);
enable_draggable_token_creation(row);
}
/**
* clears and redraws the list of tokens in the sidebar
* @param searchTerm {string} the search term used to filter the list of tokens
* @param enableDraggable {boolean} whether or not to make items draggable. Defaults to true
*/
function redraw_token_list(searchTerm, enableDraggable = true) {
if (!window.DM) return;
if (!window.tokenListItems) {
// don't do anything on startup
return;
}
console.group("redraw_token_list");
update_token_folders_remembered_state();
let list = $(`<div class="custom-token-list"></div>`);
tokensPanel.body.find('.custom-token-list').remove();
tokensPanel.body.append(list);
let nameFilter = "";
if (searchTerm !== undefined && typeof searchTerm === "string") {
nameFilter = searchTerm.toLowerCase();
}
// first let's add our root folders
for (let i = 0; i < tokens_rootfolders.length; i++) {
let row = build_sidebar_list_row(tokens_rootfolders[i]);
list.append(row);
}
// now let's add all other folders without filtering by searchTerm because we need the folder to exist in order to add items into it
window.tokenListItems
.filter(item => item.isTypeFolder())
.sort(SidebarListItem.folderDepthComparator)
.forEach(item => {
let row = build_sidebar_list_row(item);
console.debug("appending item", item);
$(`#${item.parentId} > .folder-item-list`).append(row);
// find_html_row_from_path(item.folderPath, list).find(` > .folder-item-list`).append(row);
});
// now let's add all the other items
window.tokenListItems
.filter(item =>
!item.isTypeFolder() // we already added all folders so don't include them in this loop
&& item.nameOrContainingFolderMatches(nameFilter)
)
.sort(SidebarListItem.sortComparator)
.forEach(item => {
let row = build_sidebar_list_row(item);
if (enableDraggable === true && !item.isTypeEncounter()) {
enable_draggable_token_creation(row);
}
console.debug("appending item", item);
$(`#${item.parentId} > .folder-item-list`).append(row);
// find_html_row_from_path(item.folderPath, list).find(` > .folder-item-list`).append(row);
});
update_pc_token_rows();
inject_encounter_monsters();
if(!$('.reveal-hidden-button').hasClass('clicked')){
$(".sidebar-panel-content").find(".sidebar-panel-body .hidden-sidebar-item").toggleClass("temporary-visible", false);
}
else{
$(".sidebar-panel-content").find(".sidebar-panel-body .hidden-sidebar-item").toggleClass("temporary-visible", true);
}
console.groupEnd()
}
function get_helper_size(draggedItem){
const tokenSize = token_size_for_item(draggedItem);
const width = Math.round(window.CURRENT_SCENE_DATA.hpps) * tokenSize;
const height = Math.round(window.CURRENT_SCENE_DATA.vpps) * tokenSize;
const helperWidth = width / (1.0 / window.ZOOM);
const helperHeight = height / (1.0 / window.ZOOM);
return [helperWidth, helperHeight]
}
/**
* Enables dragging the given html and dropping it on a scene to create a token.
* The given html MUST be a decendent of an item marked with the class .list-item-identifier which is set by calling {set_full_path}
* @param html {*|jQuery|HTMLElement} the html that corresponds to an item (like a row in the list of tokens)
* @param specificImage {string} the url of the image to use. If nothing is provided, an image will be selected at random from the token's specified alternative-images.
*/
function enable_draggable_token_creation(html, specificImage = undefined) {
html.draggable({
appendTo: "body",
zIndex: 100000,
cursorAt: {top: 0, left: 0},
cancel: '.token-row-gear, .change-token-image-item, #context-menu-layer',
distance: 25,
helper: function(event) {
console.log("enable_draggable_token_creation helper");
let draggedRow = $(event.target).closest(".list-item-identifier");
let isPlayerSheetAoe = false
let playerAoe = undefined
if (draggedRow.hasClass("above-aoe")){
// this dragged item is a player sheet aoe button. look up teh shape in the sidepanel
isPlayerSheetAoe = true
// copy the dragged row before replacing it with the sidepanel row
playerAoe = draggedRow.clone()
draggedRow = find_html_row_from_path(draggedRow.attr("data-full-path"), tokensPanel.body)
}
let helper
if ($(event.target).hasClass("list-item-identifier")) {
draggedRow = $(event.target);
}
let draggedItem = find_sidebar_list_item(draggedRow);
if (!draggedItem.isTypeAoe()) {
let draggedItem = find_sidebar_list_item(draggedRow);
let helper = draggedRow.find(".token-image").clone();
if (specificImage !== undefined) {
helper.attr("src", specificImage);
} else {
helper.attr("src", random_image_for_item(draggedItem));
}
helper.addClass("draggable-token-creation");
return helper;
}
let [helperWidth, helperHeight] = get_helper_size(draggedItem)
// update the token menu with the dragged out of the modal
if (draggedRow.closest(".sidebar-modal").length > 0) {
draggedItem.style = draggedRow.attr("data-style").replaceAll("aoe-style-", "");
draggedItem.size = parseInt($("#aoe_feet_height").val()) / window.CURRENT_SCENE_DATA.fpsq;
redraw_token_list_item(draggedItem);
}
helper = draggedRow.find("[data-img]").clone();
[helperWidth, helperHeight] = get_helper_size(draggedItem)
if (isPlayerSheetAoe) {
let aoeItem = SidebarListItem.Aoe(
$(playerAoe).attr("data-shape"),
$(playerAoe).attr("data-size"),
$(playerAoe).attr("data-style")
)
$(helper).attr("data-style", aoeItem.style);
$(helper).attr("data-size", aoeItem.size);
$(helper).attr("class", `aoe-token-tileable aoe-style-${aoeItem.style} aoe-shape-${aoeItem.shape}`);
[helperWidth, helperHeight] = get_helper_size(aoeItem);
$(helper).attr("data-name-override", $(playerAoe).attr("data-name"));
} else {
const style = draggedRow.attr("data-style");
const shape = draggedRow.attr("data-shape");
$(helper).attr("data-style", style);
$(helper).attr("data-shape", shape);
$(helper).attr("data-size", draggedRow.attr("data-size"));
$(helper).attr("class", build_aoe_class_name(style, shape, ""));
}
// perform specific resizing based on shape
if (draggedItem.shape === "circle"){
helperWidth = helperWidth * 2
helperHeight = helperHeight * 2
}
else if (draggedItem.shape === "line"){
helperWidth = Math.round(window.CURRENT_SCENE_DATA.hpps) / (1.0 / window.ZOOM)
}
$(helper).css('width', `${helperWidth}px`);
$(helper).css('height', `${helperHeight}px`);
helper.addClass("draggable-token-creation");
return helper;
},
start: function (event, ui) {
console.log("enable_draggable_token_creation start");
let draggedRow = $(event.target).closest(".list-item-identifier");
if ($(event.target).hasClass("list-item-identifier")) {
draggedRow = $(event.target);
}
let draggedItem = find_sidebar_list_item(draggedRow);
if (!draggedItem.isTypeAoe()) {
const tokenSize = token_size_for_item(draggedItem);
const width = Math.round(window.CURRENT_SCENE_DATA.hpps) * tokenSize;
const helperWidth = width / (1.0 / window.ZOOM);
$(ui.helper).css({
'width': `${helperWidth}px`,
'max-width': `${helperWidth}px`,
'max-height': `${helperWidth}px`,
'min-width': `${helperWidth}px`,
'min-height': `${helperWidth}px`
});
}
$(this).draggable('instance').offset.click = {
left: Math.floor(ui.helper.width() / 2),
top: Math.floor(ui.helper.height() / 2)
};
},
drag: function (event, ui) {
if (event.shiftKey) {
$(ui.helper).css("opacity", 0.5);
} else {
$(ui.helper).css("opacity", 1);
}
},
stop: function (event, ui) {
// $( event.originalEvent.target ).one('click', function(e){ e.stopImmediatePropagation(); } );
event.stopPropagation(); // prevent the mouseup event from closing the modal
if ($(ui.helper).hasClass("drag-cancelled")) {
console.log("enable_draggable_token_creation cancelled");
return;
}
let droppedOn = document.elementFromPoint(event.clientX, event.clientY);
console.log("droppedOn", droppedOn);
if (droppedOn?.closest("#VTT")) {
// place a token where this was dropped
console.log("enable_draggable_token_creation stop");
let draggedRow = $(event.target).closest(".list-item-identifier");
if ($(event.target).hasClass("list-item-identifier")) {
draggedRow = $(event.target);
}
let draggedItem = find_sidebar_list_item(draggedRow);
let hidden = event.shiftKey ? true : undefined; // we only want to force hidden if the shift key is help. otherwise let the global and override settings handle it
let src = $(ui.helper).attr("src");
if (ui.helper.attr("data-shape") && ui.helper.attr("data-style")) {
src = build_aoe_img_name(ui.helper.attr("data-style"), ui.helper.attr("data-shape"));
}
create_and_place_token(draggedItem, hidden, src, event.pageX, event.pageY, false);
// create_and_place_token(draggedItem, hidden, src, event.pageX - ui.helper.width() / 2, event.pageY - ui.helper.height() / 2, false, ui.helper.attr("data-name-override"));
close_sidebar_modal();
} else {
console.log("Not dropping over element", droppedOn);
}
}
});
}
/** When new PC data comes in, this updates the rows with the data found in window.PLAYER_STATS */
function update_pc_token_rows() {
window.tokenListItems?.filter(listItem => listItem.isTypePC()).forEach(listItem => {
let row = find_html_row(listItem, tokensPanel.body);
if(childWindows['Players']){
let popoutPC = find_html_row(listItem, $(childWindows['Players'].document).find('body'));
if(popoutPC != false)
row = row.add(popoutPC);
}
if (listItem.sheet in window.TOKEN_OBJECTS) {
row.addClass("on-scene");
row.find("button.token-row-add").attr("title", `Locate Token on Scene`);
} else {
row.removeClass("on-scene");
row.find("button.token-row-add").attr("title", `Add Token to Scene`);
}
const playerId = getPlayerIDFromSheet(listItem.sheet);
const pc = find_pc_by_player_id(playerId, false);
if (pc !== undefined) {
const color = color_from_pc_object(pc);
pc.abilities.forEach(a => {
let abilityValue = row.find(`[data-ability='${a.name}']`);
abilityValue.find(".ability_modifier").text(a.modifier);
abilityValue.find(".ability_score").text(a.score);
});
let customizations = find_token_customization(listItem.type, listItem.id);
row.find(".token-image").attr('src', (customizations?.tokenOptions?.alternativeImages?.length>0) ? customizations?.tokenOptions?.alternativeImages[0] : pc.image);
row.find(".pinv-value").text(pc.passiveInvestigation);
row.find(".pins-value").text(pc.passiveInsight);
row.find(".walking-value").text(speed_from_pc_object(pc));
row.find(".ac-value").text(pc.armorClass);
row.find(".hp-value").text(pc.hitPointInfo.current || 0);
row.find(".max-hp-value").text(pc.hitPointInfo.maximum || 0);
let flyingSpeed = speed_from_pc_object(pc, "Flying");
row.find(".fly-value").text(flyingSpeed);
let climbingSpeed = speed_from_pc_object(pc, "Climbing");
row.find(".climb-value").text(climbingSpeed);
let swimmingSpeed = speed_from_pc_object(pc, "Swimming");
row.find(".swim-value").text(swimmingSpeed);
if(climbingSpeed > 0) {
row.find(".subtitle-attibute[title='Climb Speed']").show()
} else {
row.find(".subtitle-attibute[title='Climb Speed']").hide()
}
if(flyingSpeed > 0) {
row.find(".subtitle-attibute[title='Fly Speed']").show()
} else{
row.find(".subtitle-attibute[title='Fly Speed']").hide()
}
if(flyingSpeed > 0) {
row.find(".subtitle-attibute[title='Swim Speed']").show()
} else {
row.find(".subtitle-attibute[title='Swim Speed']").hide()
}
row.find(".player-card-footer").css("--player-border-color", color);
row.css("--player-border-color", color);
row.find(".subtitle-attibute .exhaustion-pip").toggleClass("filled", false);
if(pc.hitPointInfo.current > 0) {
row.find(".subtitle-attibute.hp-attribute").show();
row.find(".hp-attribute.death-saves.ct-health-summary__data").hide();
} else{
row.find(".hp-attribute.death-saves.ct-health-summary__data").show();
row.find(".subtitle-attibute.hp-attribute").hide();
row.find(`.ct-health-summary__deathsaves-mark`).toggleClass('ct-health-summary__deathsaves-mark--inactive', true);
row.find(`.ct-health-summary__deathsaves-mark`).toggleClass('ct-health-summary__deathsaves-mark--active', false);
for(let i = 0; i <= pc.deathSaveInfo.failCount; i++){
row.find(`.ct-health-summary__deathsaves--fail .ct-health-summary__deathsaves-mark:nth-of-type(${i})`).toggleClass("ct-health-summary__deathsaves-mark--active", true);
}
for(let i = 0; i <= pc.deathSaveInfo.successCount; i++){
row.find(`.ct-health-summary__deathsaves--success .ct-health-summary__deathsaves-mark:nth-of-type(${i})`).toggleClass("ct-health-summary__deathsaves-mark--active", true);
}
}
const exhaustionLevel = pc.conditions.find(c => c.name === "Exhaustion")?.level || 0;
for(let i = 0; i <= exhaustionLevel; i++){
row.find(`.subtitle-attibute .exhaustion-pip:nth-of-type(${i})`).toggleClass("filled", true);
}
if (pc.inspiration) {
row.find(".inspiration").show();
} else {
row.find(".inspiration").hide();
}
row.find('.moreInfo').remove();
let moreInfo = $(`<div class='moreInfo' style='font-size:12px;'>
${pc.castingInfo.saveDcs.length>0 ? `<div style='margin-top:5px'><strong style='margin-left:5px;'>Spell Save DCs</strong>${pc.castingInfo.saveDcs.map(a => `<div style='margin-left:15px'>${a.sources[0]}: ${a.value}</div>`).join('')}` : ``}
${pc.resistances.length>0 ? `<div style='margin-top:5px'><strong style='margin-left:5px;'>Resistances</strong><div style='margin-left:15px'>${pc.resistances.map(a => `${a.name}`).join(', ')}</div></div>` : ``}
${pc.immunities.length>0 ? `<div style='margin-top:5px'><strong style='margin-left:5px;'>Immunities</strong><div style='margin-left:15px'>${pc.immunities.map(a => `${a.name}`).join(', ')}</div></div>` : ``}
${pc.vulnerabilities.length>0 ? `<div style='margin-top:5px'><strong style='margin-left:5px;'>Vulnerabilities</strong><div style='margin-left:15px'>${pc.vulnerabilities.map(a => `${a.name}`).join(', ')}</div></div>` : ``}
${pc.senses.length>0 ? `<div style='margin-top:5px'><strong style='margin-left:5px;'>Senses</strong><div style='margin-left:15px'>${pc.senses.map(a => `${a.name} ${a.distance}`).join(', ')}</div></div>` : ``}
${pc.proficiencyGroups.length>0 ? `<div style='margin-top:5px'><strong style='margin-left:5px;'>Proficiencies</strong> ${pc.proficiencyGroups.map(a => `<div style='margin-left:15px'><strong>${a.group}:</strong> ${a.values == "" ? `None` : a.values}</div>`).join('')}</div>` : ``}
</div>`)
row.append(moreInfo);
update_player_online_indicator(playerId, pc.p2pConnected, color);
row.css("--player-border-color", color);
}
});
}
/**
* Creates a {Token} object and places it on the scene.
* @param listItem {SidebarListItem} the item to create a token from
* @param hidden {boolean} whether or not the created token should be hidden. Passing undefined will use whatever the global token setting is.
* @param specificImage {string} the image to use. if undefined, a random image will be used
* @param eventPageX {number} MouseEvent.pageX if supplied, the token will be placed at this x coordinate, else centered in the view
* @param eventPageY {number} MouseEvent.pageY if supplied, the token will be placed at this y coordinate, else centered in the view
* @param disableSnap {boolean} if true, tokens will not snap to the grid. This is false by default and only used when placing multiple tokens
* @param nameOverride {string} if present will override the list items name with this name. This is for dragging out player aoe tokens from sheets
*/
function create_and_place_token(listItem, hidden = undefined, specificImage= undefined, eventPageX = undefined, eventPageY = undefined, disableSnap = false, nameOverride = "", mapPoint=false, extraOptions=undefined) {
if (listItem === undefined) {
console.warn("create_and_place_token was called without a listItem");
return;
}
if (listItem.isTypeFolder() || listItem.isTypeEncounter()) {
let tokensToPlace = [];
if (listItem.isTypeFolder()) {
let fullPath = listItem.fullPath();
// find and place all items in this folder... but not subfolders
tokensToPlace = (listItem.fullPath().startsWith(RootFolder.Monsters.path) ? window.monsterListItems : window.tokenListItems)
.filter(item => !item.isTypeFolder()) // if we ever want to add everything at every subfolder depth, remove this line
.filter(item => item.folderPath === fullPath);
} else if (listItem.isTypeEncounter()) {
let encounterId = listItem.encounterId;
let encounterMonsterItems = encounter_monster_items[encounterId];
if (encounterMonsterItems === undefined || encounterMonsterItems.length === 0) {
let encounterRow = tokensPanel.body.find(`[data-encounter-id='${encounterId}']`);
encounterRow.find(".sidebar-list-item-row-item").addClass("button-loading");
refresh_encounter(encounterRow, listItem, function (response) {
encounterRow.find(".sidebar-list-item-row-item").removeClass("button-loading");
if (response === true) {
create_and_place_token(listItem, hidden, specificImage, eventPageX, eventPageY);
}
})
return;
}
window.EncounterHandler.encounters[encounterId].monsters.forEach(shortMonster => {
let matchingItem = encounterMonsterItems.find(item => item.monsterData.id === shortMonster.id);
// we only have one of each monster so make new ones
tokensToPlace.push(SidebarListItem.Monster(matchingItem.monsterData))
});
}
// What's the threshold we should prompt for?
if (tokensToPlace.length < 10 || confirm(`This will add ${tokensToPlace.length} tokens which could lead to unexpected results. Are you sure you want to add all of these tokens?`)) {
// place all tokens fanned out from the center of the view
let center = center_of_view();
let mapPoint = convert_point_from_view_to_map(center.x, center.y, false); // do our math on the map coordinate space
let gridSize = Math.min(window.CURRENT_SCENE_DATA.hpps, window.CURRENT_SCENE_DATA.vpps);
let distanceFromCenter = gridSize * Math.ceil(tokensToPlace.length / 8); // this creates a pretty decent spacing that grows with the size of the token list
tokensToPlace.forEach((item, index) => {
let radius = index / tokensToPlace.length;
let left = mapPoint.x + (distanceFromCenter * Math.cos(2 * Math.PI * radius));
let top = mapPoint.y + (distanceFromCenter * Math.sin(2 * Math.PI * radius));
let viewPoint = convert_point_from_map_to_view(left, top); // convert back to view coordinate space because `create_and_place_token` expects view coordinates to be passed in
create_and_place_token(item, hidden, undefined, viewPoint.x, viewPoint.y, true);
});
}
return;
}
let options = {...window.TOKEN_SETTINGS}
// set up whatever you need to. We'll override a few things after
let foundOptions = find_token_options_for_list_item(listItem);
options = {...options, ...foundOptions}; // we may need to put this in specific places within the switch statement below
options.name = listItem.name;
let tokenSizeSetting;
let tokenSize;
let hpVal;
let placedCount;
let color;
switch (listItem.type) {
case ItemType.Folder:
console.log("TODO: place all tokens in folder?", listItem);
break;
case ItemType.MyToken:
tokenSizeSetting = options.tokenSize;
tokenSize = parseInt(tokenSizeSetting);
if (tokenSizeSetting === undefined || typeof tokenSizeSetting !== 'number') {
tokenSize = 1;
// TODO: handle custom sizes
}
if(tokenSize <= 0.5){
options.tokenSize = 0.5;
}
else{
options.tokenSize = tokenSize;
}
placedCount = 1;
for (let tokenId in window.TOKEN_OBJECTS) {
if (window.TOKEN_OBJECTS[tokenId].options.itemId === listItem.id) {
placedCount++;
}
}
color = TOKEN_COLORS[(placedCount - 1) % 54];
options.color = `#${color}`;
switch (options['placeType']) {
case 'personality':
let personailityTrait = getPersonailityTrait()
console.log(`updating monster name with trait: ${personailityTrait}, and setting color: ${color}`);