-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworddex.js
More file actions
1324 lines (1145 loc) · 50.9 KB
/
Copy pathworddex.js
File metadata and controls
1324 lines (1145 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// worddex.js - Handles WordDex Display, Search, and Sort
let currentSort = 'alpha';
let activeFilters = new Set();
let wordData = null;
// Remove duplicate declaration of EVO_COLORS if Evolution.colors is present
// We need to be careful not to redeclare if already in scope (though 'const' is block scoped, these are global scripts)
// Best approach: Use a different name for local fallback or check window
const EVO_COLORS_LOCAL = {
1: '#FF7043',
2: '#4FC3F7',
3: '#FFD700',
4: '#E1BEE7'
};
const EVO_STARS_LOCAL = {
1: '★',
2: '★★',
3: '★★★',
4: '✧'
};
const EVO_COLORS_REF = (typeof Evolution !== 'undefined' && Evolution.colors) ? Evolution.colors : EVO_COLORS_LOCAL;
const EVO_STARS_REF = (typeof Evolution !== 'undefined' && Evolution.stars) ? Evolution.stars : EVO_STARS_LOCAL;
let searchQuery = '';
const typeMap = {
noun: 'type_n',
verb: 'type_v',
adjective: 'type_adj',
adverb: 'type_adv',
pronoun: 'type_p',
preposition: 'type_pre',
conjunction: 'type_conj',
interjection: 'type_interj'
};
const rarityOrder = {
common: 1,
uncommon: 2,
rare: 3,
epic: 4,
legendary: 5,
mythic: 6,
god: 7
};
const rarityColors = {
common: '#ebebeb',
uncommon: '#a1ff96',
rare: '#96c7ff',
epic: '#b996ff',
legendary: '#fffa96',
mythic: '#ff6969',
god: 'linear-gradient(45deg, #ff0000, #ff7f00, #ffff00, #00ff00, #0000ff, #4b0082, #9400d3)'
};
function escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
function sortEntries(entries, sortType) {
switch(sortType) {
case 'alpha':
return entries.sort((a, b) => a[0].localeCompare(b[0]));
case 'recent':
return entries.sort((a, b) => {
const timeA = a[1].timestamp || 0;
const timeB = b[1].timestamp || 0;
return timeB - timeA;
});
case 'rarity':
return entries.sort((a, b) => {
const rarityA = rarityOrder[a[1].rarity] ?? 3;
const rarityB = rarityOrder[b[1].rarity] ?? 3;
if (rarityA !== rarityB) {
return rarityA - rarityB;
}
return a[0].localeCompare(b[0]);
});
case 'tag':
return entries.sort((a, b) => {
const tagsA = a[1].tags || [];
const tagsB = b[1].tags || [];
// Put tagged items first
if (tagsA.length > 0 && tagsB.length === 0) return -1;
if (tagsA.length === 0 && tagsB.length > 0) return 1;
// Sort by first tag alpha
if (tagsA.length > 0 && tagsB.length > 0) {
const tagComp = tagsA[0].localeCompare(tagsB[0]);
if (tagComp !== 0) return tagComp;
}
return a[0].localeCompare(b[0]);
});
default:
return entries;
}
}
function displayWordDex(sortType = 'alpha') {
// Save Persistent Sort
chrome.storage.local.set({ lastSort: currentSort });
chrome.storage.local.get(["wordDex", "achievements", "streakData", "badges"], (data) => {
if (chrome.runtime.lastError) {
console.error('Storage error:', chrome.runtime.lastError);
displayError("Error loading word collection. Please try again.");
return;
}
try {
const dex = data.wordDex || {};
const stats = data.achievements || {};
const dexDiv = document.getElementById("dex");
const statsDiv = document.getElementById("stats");
if (!dexDiv || !statsDiv) {
console.error('Required DOM elements not found');
return;
}
wordData = dex;
dexDiv.innerHTML = '';
let entries = Object.entries(dex);
// Filter by Search Query
if (searchQuery) {
entries = entries.filter(([word, info]) => {
const searchLower = searchQuery.toLowerCase();
return word.toLowerCase().includes(searchLower) ||
(info.origin && info.origin.toLowerCase().includes(searchLower));
});
}
// Filter by Tags (Multi-select OR logic)
if (activeFilters.size > 0) {
entries = entries.filter(([word, info]) => {
// Check if word has ANY of the active filters
// 1. Check Rarity
if (info.rarity && activeFilters.has(info.rarity)) return true;
// 2. Check Tags
if (info.tags) {
return info.tags.some(tag => activeFilters.has(tag));
}
return false;
});
}
// Show filter indicator if any filter is active
if (activeFilters.size > 0) {
const filterMsg = document.createElement('div');
filterMsg.className = 'filter-indicator';
const filterNames = Array.from(activeFilters).map(filter => {
// Check if it's a rarity or type and translate
const lower = filter.toLowerCase();
const rarityKey = lower.toUpperCase(); // COMMON, RARE, etc.
// Map full type name to key
if (typeMap[lower]) {
return t(typeMap[lower]);
}
// Check Rarities
const rarities = ['common', 'uncommon', 'rare', 'epic', 'legendary', 'mythic', 'god'];
if (rarities.includes(lower)) {
return t(rarityKey);
}
return filter;
}).join(', ');
const displayNames = filterNames.length > 30 ? filterNames.substring(0, 30) + '...' : filterNames;
filterMsg.innerHTML = `<span>${t('filterByTag')}: <strong>${displayNames}</strong></span> <button id="clearFilters">${t('clearFilter')}</button>`;
dexDiv.appendChild(filterMsg);
// We need to attach event after appending
setTimeout(() => {
const clearBtn = document.getElementById('clearFilters');
if(clearBtn) clearBtn.onclick = () => {
activeFilters.clear();
displayWordDex(currentSort);
};
}, 0);
}
entries = sortEntries(entries, sortType);
// Variables for grouping
let lastGroup = null;
if (entries.length === 0 && searchQuery) {
dexDiv.innerHTML = `<p style="color: gray; text-align: center; padding: 20px;">${t('noSearchResults')}</p>`;
} else if (entries.length === 0) {
dexDiv.innerHTML = `<p style="color: gray; text-align: center; padding: 20px;">${t('noWordsMessage')}</p>`;
} else {
// --- Rarity Styles ---
// (rarityColors is now global)
// Helper to get specialized card class/style
const getCardStyle = (tags, evolution) => {
let classes = '';
if (tags) {
if (tags.includes('tech')) classes += ' tech-card';
else if (tags.includes('bio')) classes += ' bio-card';
else if (tags.includes('chem')) classes += ' chem-card';
else if (tags.includes('astro')) classes += ' astro-card';
}
if (evolution && evolution.stage > 0) {
classes += ` evo-stage-${evolution.stage}`;
}
return classes;
};
entries.forEach(([word, info]) => {
if (!info || typeof info !== 'object') {
console.warn(`Invalid data for word: ${word}`);
return;
}
// Handle Group Headers for Tag Sort
if (sortType === 'tag') {
const currentTags = info.tags || [];
// Use first tag as group, or 'Untagged'
const groupName = currentTags.length > 0 ? currentTags[0] : 'Untagged';
if (groupName !== lastGroup) {
const header = document.createElement('div');
header.className = 'dex-group-header';
if (groupName === 'Untagged') header.classList.add('untagged');
header.textContent = groupName === 'Untagged' ? 'Untagged' : groupName; // Could translate 'Untagged'
dexDiv.appendChild(header);
lastGroup = groupName;
}
}
const div = document.createElement("div");
div.className = "word-entry" + getCardStyle(info.tags, info.evolution);
div.style.position = 'relative';
div.style.paddingRight = '60px'; // Prevent text overlap with delete button
// specialized background logic for Tech and Chem (Refactored to CSS classes)
// Classes .tech-card and .chem-card are now applied in getCardStyle based on tags
// Just need to apply overrides that are dynamic or not covered by standard CSS
/* Inline styles removed in favor of CSS classes in popup.html */
// Evolution Glow Override
// REFACTOR: Use text-shadow Aura instead of box-shadow Border
if (info.evolution && info.evolution.stage > 0) {
const evoColor = EVO_COLORS_REF[info.evolution.stage] || '#CD7F32'; // Use shared constant
// Apply aura to the title text
// We need to wait for wordStrong to be created? No, we can set style on it later.
// Actually, wordStrong is created below. Let's set a flag or style it after creation.
// Remove old box-shadow logic if present (it was applied to 'div')
div.style.boxShadow = 'none';
// Add a subtle background tint if not Tech/Chem
if (!info.tags || (!info.tags.includes('tech') && !info.tags.includes('chem'))) {
// Very subtle gradient to hint at evolution without overwhelming
div.style.background = `linear-gradient(135deg, rgba(255,255,255,0.8) 0%, ${evoColor}22 100%)`;
}
}
const rarity = info.rarity || 'common';
const origin = info.origin || info.definition || 'No information available';
const wordStrong = document.createElement('strong');
// Name + Stars
let displayName = word;
if (info.evolution && info.evolution.stage > 0) {
const stars = EVO_STARS_REF[info.evolution.stage] || '★'.repeat(info.evolution.stage);
displayName += ` ${stars}`;
// AURA EFFECT
const evoColor = EVO_COLORS_REF[info.evolution.stage] || '#CD7F32';
// Multiple shadows for "Aura" effect
wordStrong.style.textShadow = `0 0 5px ${evoColor}, 0 0 10px ${evoColor}, 0 0 20px ${evoColor}66`;
// Make text slightly larger or bolder?
wordStrong.style.fontWeight = '900';
}
wordStrong.textContent = displayName;
wordStrong.style.overflowWrap = 'anywhere'; // Ensure long words wrap
wordStrong.style.display = 'block'; // Ensure it takes width to wrap properly
// Default color logic moved below to avoid override
// wordStrong.style.color = rarityColors[rarity] || '#6b5b95';
// if (rarity === 'common') {
// wordStrong.style.color = '#9b9b9b';
// }
// Project Moon Character Colors
const pmColors = {
'yisang': '#d4dfe8',
'faust': '#ffbfb4',
'donquixote': '#FFEF23',
'ryoshu': '#cf0000',
'meursault': '#293b95',
'honglu': '#5BFFDE',
'heathcliff': '#4e3076',
'ishmael': '#ff9500',
'rodya': '#820000',
'dante': '#b01c37',
'sinclair': '#8b9c15',
'outis': '#325339',
'gregor': '#69350b'
};
const lowerWord = word.toLowerCase();
if (pmColors[lowerWord]) {
const charColor = pmColors[lowerWord];
// Force override with !important logic via inline styles
wordStrong.style.setProperty('color', charColor, 'important');
div.style.borderLeft = `4px solid ${charColor}`;
// Use a stronger gradient to make it visible
div.style.background = `linear-gradient(90deg, ${charColor}33 0%, transparent 100%)`; // 33 = 20% opacity
// Add subtle text shadow for lighter colors to ensure readability
if (['yisang', 'faust', 'donquixote', 'honglu'].includes(lowerWord)) {
wordStrong.style.textShadow = '0px 0px 2px rgba(0,0,0,0.5)';
}
} else {
// Apply standard rarity color only if NOT a PM character
wordStrong.style.color = rarityColors[rarity] || '#6b5b95';
if (rarity === 'common') {
wordStrong.style.color = '#9b9b9b';
}
}
if (word.toLowerCase() === 'lingomon' || rarity === 'god') {
wordStrong.style.backgroundImage = 'linear-gradient(45deg, red, orange, yellow, green, blue, indigo, violet)';
wordStrong.style.backgroundSize = '200% auto';
wordStrong.style.webkitBackgroundClip = 'text';
wordStrong.style.webkitTextFillColor = 'transparent';
wordStrong.style.animation = 'rainbow 2s linear infinite';
wordStrong.style.textShadow = 'none';
if (!document.getElementById('rainbow-style')) {
const style = document.createElement('style');
style.id = 'rainbow-style';
style.innerHTML = `
@keyframes rainbow {
to { background-position: 200% center; }
}
`;
document.head.appendChild(style);
}
}
// Custom color for Heathcliff - REMOVED (Handled by pmColors now)
/*
if (word.toLowerCase() === 'heathcliff') {
wordStrong.style.color = '#4e3076';
// Also style the border of the card?
div.style.borderLeft = '4px solid #4e3076';
div.style.background = 'linear-gradient(90deg, rgba(78, 48, 118, 0.1) 0%, transparent 100%)';
}
*/
// Inline Tag Container
const metaRow = document.createElement('div');
metaRow.style.display = 'flex';
metaRow.style.alignItems = 'center';
metaRow.style.gap = '8px';
metaRow.style.marginTop = '2px';
// Rarity Badge (Styled like a tag)
const rarityBadge = document.createElement('span');
rarityBadge.className = 'tag-badge rarity-badge';
rarityBadge.textContent = t(rarity.toUpperCase());
rarityBadge.style.fontWeight = 'bold';
if (rarity === 'god') {
rarityBadge.classList.add('rainbow-text');
// Border handled by CSS class now
} else {
const rColor = rarityColors[rarity] || '#9b8bb5';
rarityBadge.style.color = rColor;
rarityBadge.style.borderColor = rColor;
// Light background tint based on rarity color?
// For now just white/dark background with colored text/border
rarityBadge.style.background = 'transparent';
}
metaRow.appendChild(rarityBadge);
// SOURCE BADGE (New for v1.8.1) - No Emojis Version
if (info.frequencySource) {
const sourceBadge = document.createElement('span');
sourceBadge.className = 'tag-badge source-badge';
sourceBadge.style.fontSize = '9px';
sourceBadge.style.opacity = '0.8';
let sourceText = info.frequencySource;
if (sourceText.includes('stack_exchange')) {
sourceText = 'StackOverflow';
sourceBadge.style.background = '#ffe0b2'; // Orange tint
sourceBadge.style.color = '#e65100';
sourceBadge.style.borderColor = '#ffcc80';
} else if (sourceText.includes('bio_api')) {
sourceText = 'GBIF';
sourceBadge.style.background = '#e8f5e9'; // Green tint
sourceBadge.style.color = '#2e7d32';
sourceBadge.style.borderColor = '#a5d6a7';
} else if (sourceText.includes('chem_api')) {
sourceText = 'PubChem';
sourceBadge.style.background = '#fffde7'; // Yellow tint
sourceBadge.style.color = '#fbc02d';
sourceBadge.style.borderColor = '#fff59d';
} else if (sourceText.includes('astro_api')) {
sourceText = 'SolarData';
sourceBadge.style.background = '#f3e5f5'; // Purple tint
sourceBadge.style.color = '#7b1fa2';
sourceBadge.style.borderColor = '#ce93d8';
} else if (sourceText.includes('project_moon')) {
sourceText = 'Project Moon';
sourceBadge.style.background = '#ffe5b8'; // Deep Indigo
sourceBadge.style.color = '#ede7f6';
sourceBadge.style.borderColor = '#b39ddb';
} else if (sourceText.includes('easter_egg')) {
sourceText = 'Easter Egg';
sourceBadge.style.background = '#fff8e1';
sourceBadge.style.color = '#ff6f00';
sourceBadge.style.borderColor = '#ffca28';
} else if (sourceText.includes('tech_api')) {
sourceText = 'TechDict';
}
sourceBadge.textContent = sourceText;
sourceBadge.title = `Data Source: ${info.frequencySource}`;
metaRow.appendChild(sourceBadge);
}
// Tag Management Section
const tagContainer = document.createElement('div');
tagContainer.className = 'inline-tag-container';
// Evolve Button (If Eligible)
// We need to check if Evolution global is available OR check logic manually here
// But wait, info.evolution.canEvolve might be stale if we just bumped level via script without updating flag
// So let's double check eligibility
let showEvolveBtn = false;
if (info.evolution) {
if (info.evolution.canEvolve) showEvolveBtn = true;
else {
// Fallback check
const stg = info.evolution.stage || 0;
const lvl = info.srs ? info.srs.level : 0;
// SRS 1 -> Evo 1 (Bronze)
if (stg < 1 && lvl >= 1) showEvolveBtn = true;
// SRS 3 -> Evo 2 (Silver)
if (stg < 2 && lvl >= 3) showEvolveBtn = true;
// SRS 5 -> Evo 3 (Gold)
if (stg < 3 && lvl >= 5) showEvolveBtn = true;
}
}
if (showEvolveBtn) {
const evolveBtn = document.createElement('button');
evolveBtn.textContent = t('evolve');
evolveBtn.className = 'tag-badge';
// Determine next stage color
const nextStage = (info.evolution ? info.evolution.stage : 0) + 1;
const nextColor = EVO_COLORS_REF[nextStage] || '#FFD700'; // Default gold if unknown
// REMOVED Gradient, used Solid Color for flat look
evolveBtn.style.background = nextColor;
// Dark text for lighter backgrounds (Silver/Gold), White for darker (Bronze)?
// Actually Bronze #CD7F32 is darkish, Silver #BCC6CC is light, Gold #FEDA75 is light.
// Let's use a text shadow or adjust color.
evolveBtn.style.color = '#333';
if (nextStage === 1) evolveBtn.style.color = 'white'; // Bronze looks better with white text
evolveBtn.style.fontWeight = 'bold';
evolveBtn.style.border = 'none';
evolveBtn.style.cursor = 'pointer';
evolveBtn.style.animation = 'pulse 1s infinite';
evolveBtn.style.marginLeft = '8px'; // Spacing
evolveBtn.onclick = async (e) => {
e.stopPropagation();
if (typeof confirmEvolution !== 'undefined') {
confirmEvolution(word, info);
}
};
metaRow.appendChild(evolveBtn);
}
if (info.evolution?.stage === 3 && info.familyId) {
const familyWords = Object.entries(wordData || {})
.filter(([w, entry]) => entry.familyId === info.familyId && entry.evolution?.stage === 3);
if (familyWords.length >= 5) {
const fusionBtn = document.createElement('button');
fusionBtn.textContent = t('familyFusion');
fusionBtn.className = 'tag-badge';
fusionBtn.style.background = '#E1BEE7';
fusionBtn.style.color = '#333';
fusionBtn.style.fontWeight = 'bold';
fusionBtn.style.animation = 'pulse 1s infinite';
fusionBtn.onclick = (e) => {
e.stopPropagation();
if (typeof window.AscensionModal !== 'undefined') {
window.AscensionModal.confirmFusion(word, info);
}
};
metaRow.appendChild(fusionBtn);
}
}
const refreshInlineTags = () => {
tagContainer.innerHTML = '';
if (info.tags) {
info.tags.forEach(tag => {
const badge = document.createElement('span');
badge.className = 'tag-badge';
badge.textContent = tag;
badge.title = 'Click to remove';
badge.style.cursor = 'pointer';
badge.onclick = (e) => {
e.stopPropagation();
if(confirm(`Remove tag "${tag}"?`)) {
removeTagGlobal(word, tag);
}
};
tagContainer.appendChild(badge);
});
}
const addBtn = document.createElement('button');
addBtn.className = 'tag-plus-btn';
addBtn.textContent = '+';
addBtn.onclick = (e) => {
e.stopPropagation();
// Switch to input
const input = document.createElement('input');
input.className = 'inline-tag-input';
input.placeholder = 'Tag...';
input.setAttribute('list', 'existingTags');
// Auto-focus and handle save
input.onblur = () => {
const val = input.value.trim();
if (val) addTagGlobal(word, val);
else refreshInlineTags(); // Revert
};
input.onkeydown = (ev) => {
if (ev.key === 'Enter') {
const val = input.value.trim();
if (val) addTagGlobal(word, val);
else refreshInlineTags();
}
if (ev.key === 'Escape') refreshInlineTags();
};
tagContainer.innerHTML = ''; // Clear badges momentarily
tagContainer.appendChild(input);
input.focus();
};
tagContainer.appendChild(addBtn);
};
refreshInlineTags();
metaRow.appendChild(tagContainer);
const originDiv = document.createElement('div');
originDiv.className = 'word-info';
// Enhanced Origin Display
let originText = origin.length > 150 ? origin.substring(0, 150) + '...' : origin;
let originHtml = escapeHtml(originText).replace(/\n/g, '<br>');
originDiv.innerHTML = originHtml;
// Special Text Color for Tech Cards (Ensure description is legible)
// Handled via CSS .tech-card .word-info now
/*
if (info.tags && info.tags.includes('tech')) {
originDiv.style.color = '#e0f7fa'; // Light cyan for description text (readable on black)
originDiv.style.textShadow = 'none'; // No glow on body text for readability
}
*/
const frequencyDiv = document.createElement('div');
frequencyDiv.className = 'frequency-info';
frequencyDiv.style.fontSize = '11px';
frequencyDiv.style.marginTop = '4px';
// Tags Display (Removed - now inline)
/*
if (info.tags && info.tags.length > 0) {
const tagsDiv = document.createElement('div');
tagsDiv.className = 'word-tags';
info.tags.forEach(tag => {
const badge = document.createElement('span');
badge.className = 'tag-badge';
badge.textContent = tag;
tagsDiv.appendChild(badge);
});
div.appendChild(tagsDiv);
}
*/
if (info.frequency !== undefined && info.frequency !== null) {
const freqDisplay = info.frequency >= 1
? info.frequency.toFixed(2)
: info.frequency.toFixed(4);
const sourceMap = {
'api': t('sourceAPI'),
'local': t('sourceLocalDB'),
'korean-api': t('sourceKoreanAPI')
};
const sourceLabel = sourceMap[info.frequencySource] || t('sourceAPI');
if (currentLanguage === 'ko') {
frequencyDiv.textContent = `${t('frequency')}: ${t('perMillion')} ${freqDisplay} (${sourceLabel})`;
} else {
frequencyDiv.textContent = `${t('frequency')}: ${freqDisplay} ${t('perMillion')} (${sourceLabel})`;
}
frequencyDiv.title = `Source: ${info.frequencySource || 'unknown'}`;
} else {
frequencyDiv.textContent = `${t('frequency')}: ${t('frequencyNA')}`;
frequencyDiv.style.fontStyle = 'italic';
}
const deleteBtn = document.createElement('button');
deleteBtn.textContent = t('deleteButton');
deleteBtn.className = 'delete-btn';
deleteBtn.style.position = 'absolute';
deleteBtn.style.top = '10px';
deleteBtn.style.right = '0px';
deleteBtn.style.background = 'transparent';
deleteBtn.style.border = 'none';
deleteBtn.style.cursor = 'pointer';
deleteBtn.style.fontSize = '16px';
deleteBtn.style.color = '#ff4444';
deleteBtn.style.fontWeight = 'bold';
deleteBtn.style.opacity = '0.5';
deleteBtn.style.transition = 'opacity 0.2s';
deleteBtn.onmouseover = () => deleteBtn.style.opacity = '1';
deleteBtn.onmouseout = () => deleteBtn.style.opacity = '0.5';
deleteBtn.onclick = (e) => {
e.stopPropagation();
deleteWord(word, rarity);
};
const infoBtn = document.createElement('button');
infoBtn.textContent = t('infoButton');
infoBtn.className = 'info-btn';
// Style like delete button (text, transparent bg)
infoBtn.style.background = 'transparent';
infoBtn.style.border = 'none';
infoBtn.style.cursor = 'pointer';
infoBtn.style.fontSize = '11px'; // Slightly smaller than title
infoBtn.style.color = '#888';
infoBtn.style.fontWeight = 'bold';
infoBtn.style.padding = '0';
infoBtn.style.marginTop = '4px';
infoBtn.style.marginBottom = '2px';
infoBtn.style.display = 'block'; // Ensure it sits on its own line
infoBtn.style.opacity = '0.8';
infoBtn.style.transition = 'opacity 0.2s, color 0.2s';
infoBtn.onmouseover = () => {
infoBtn.style.opacity = '1';
infoBtn.style.color = '#555';
};
infoBtn.onmouseout = () => {
infoBtn.style.opacity = '0.8';
infoBtn.style.color = '#888';
};
infoBtn.onclick = (e) => {
e.stopPropagation();
showWordContext(word, info);
};
div.appendChild(wordStrong);
div.appendChild(metaRow);
div.appendChild(infoBtn); // Inserted before description
div.appendChild(originDiv);
div.appendChild(frequencyDiv);
div.appendChild(deleteBtn);
dexDiv.appendChild(div);
});
}
// Display stats using global function from stats.js
const total = entries.length;
const commonCount = stats.common || 0;
const uncommonCount = stats.uncommon || 0;
const rareCount = stats.rare || 0;
const epicCount = stats.epic || 0;
const legendaryCount = stats.legendary || 0;
const mythicCount = stats.mythic || 0;
const streakData = data.streakData || { currentStreak: 0, longestStreak: 0 };
statsDiv.innerHTML = '';
const statsStrong = document.createElement('strong');
statsStrong.textContent = t('collectionStats');
const statsP = document.createElement('p');
statsP.style.margin = '8px 0 0 0';
statsP.appendChild(statsStrong);
statsP.appendChild(document.createElement('br'));
statsP.appendChild(document.createTextNode(`${t('totalWords')}: ${total}`));
statsP.appendChild(document.createElement('br'));
statsP.appendChild(document.createElement('br'));
// Streak display
const streakSpan = document.createElement('span');
streakSpan.style.fontWeight = 'bold';
streakSpan.className = 'streak-text';
streakSpan.style.color = streakData.currentStreak >= 7 ? '#fffa96' : streakData.currentStreak >= 3 ? '#96c7ff' : '';
const dayText = streakData.currentStreak !== 1 ? t('days') : t('day');
streakSpan.textContent = `${t('streak')}: ${streakData.currentStreak} ${dayText}`;
statsP.appendChild(streakSpan);
statsP.appendChild(document.createElement('br'));
if (streakData.longestStreak > 0) {
const longestDayText = streakData.longestStreak !== 1 ? t('days') : t('day');
statsP.appendChild(document.createTextNode(`${t('longest')}: ${streakData.longestStreak} ${longestDayText}`));
statsP.appendChild(document.createElement('br'));
}
statsP.appendChild(document.createElement('br'));
statsP.appendChild(document.createTextNode(`${t('COMMON')}: ${commonCount}`));
statsP.appendChild(document.createElement('br'));
statsP.appendChild(document.createTextNode(`${t('UNCOMMON')}: ${uncommonCount}`));
statsP.appendChild(document.createElement('br'));
statsP.appendChild(document.createTextNode(`${t('RARE')}: ${rareCount}`));
statsP.appendChild(document.createElement('br'));
statsP.appendChild(document.createTextNode(`${t('EPIC')}: ${epicCount}`));
statsP.appendChild(document.createElement('br'));
statsP.appendChild(document.createTextNode(`${t('LEGENDARY')}: ${legendaryCount}`));
statsP.appendChild(document.createElement('br'));
statsP.appendChild(document.createTextNode(`${t('MYTHIC')}: ${mythicCount}`));
statsDiv.appendChild(statsP);
if (typeof displayCharts !== 'undefined') {
displayCharts(data.wordDex || {}, stats);
}
if (typeof displayBadges !== 'undefined') {
displayBadges(data.badges || { main: [], hidden: [] });
}
} catch (err) {
console.error('Error displaying word dex:', err);
displayError("Error displaying words. Please try refreshing.");
}
});
}
function showWordContext(word, info) {
// Create Modal
const overlay = document.createElement('div');
overlay.style.position = 'fixed';
overlay.style.top = '0';
overlay.style.left = '0';
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.background = 'rgba(0,0,0,0.5)';
overlay.style.zIndex = '10000';
overlay.style.display = 'flex';
overlay.style.alignItems = 'center';
overlay.style.justifyContent = 'center';
overlay.onclick = (e) => {
if (e.target === overlay) overlay.remove();
};
const modal = document.createElement('div');
modal.style.background = '#fff';
modal.style.padding = '24px';
modal.style.borderRadius = '16px';
modal.style.maxWidth = '90%';
modal.style.width = '400px';
modal.style.boxShadow = '0 10px 25px rgba(0,0,0,0.2)';
modal.style.fontFamily = 'inherit';
modal.style.position = 'relative';
const closeBtn = document.createElement('button');
closeBtn.innerHTML = '×';
closeBtn.style.position = 'absolute';
closeBtn.style.top = '12px';
closeBtn.style.right = '12px';
closeBtn.style.background = 'none';
closeBtn.style.border = 'none';
closeBtn.style.fontSize = '24px';
closeBtn.style.cursor = 'pointer';
closeBtn.style.color = '#999';
closeBtn.onclick = () => overlay.remove();
const title = document.createElement('h2');
title.textContent = word;
title.style.margin = '0 0 16px 0';
title.style.color = rarityColors[info.rarity] || '#333';
if (info.rarity === 'god') {
title.style.backgroundImage = rarityColors[info.rarity];
title.style.backgroundSize = '200% auto';
title.style.webkitBackgroundClip = 'text';
title.style.webkitTextFillColor = 'transparent';
title.style.animation = 'rainbow 2s linear infinite';
}
const details = document.createElement('div');
details.style.fontSize = '14px';
details.style.lineHeight = '1.6';
details.style.color = '#555';
const formatDate = (ts) => {
if (!ts) return 'Unknown';
return new Date(ts).toLocaleDateString() + ' ' + new Date(ts).toLocaleTimeString();
};
const firstDate = formatDate(info.firstCaught || info.timestamp);
const lastDate = formatDate(info.timestamp);
const caughtOn = info.caughtOn || 'Unknown';
// Highlight word in context
let contextHtml = '<em>No context available.</em>';
if (info.context) {
// Escape HTML first
const escapedContext = escapeHtml(info.context);
// Create regex to match word (case insensitive)
const regex = new RegExp(`(${word})`, 'gi');
let highlightStyle = `color: ${rarityColors[info.rarity] || '#000'}; font-weight: bold;`;
if (info.rarity === 'god') {
// For god tier text, we can't easily do gradient text in inline replacement without more complex HTML
// So just use a fallback color or simple style
highlightStyle = `color: #ff00ff; font-weight: bold; text-shadow: 0 0 5px rgba(255,0,255,0.3);`;
}
contextHtml = escapedContext.replace(regex, `<span style="${highlightStyle}">$1</span>`);
}
details.innerHTML = `
<div style="margin-bottom: 8px;"><strong>First Caught:</strong> ${firstDate}</div>
<div style="margin-bottom: 8px;"><strong>Last Caught:</strong> ${lastDate}</div>
<div style="margin-bottom: 16px;"><strong>Caught On:</strong> ${caughtOn}</div>
<div style="background: #f5f5f5; padding: 12px; border-radius: 8px; border-left: 4px solid ${rarityColors[info.rarity] || '#ccc'};">
<strong>Context:</strong><br/>
<span style="font-style: italic;">"${contextHtml}"</span>
</div>
`;
// Tag Management Section
const tagContainer = document.createElement('div');
tagContainer.className = 'tag-input-container';
const tagList = document.createElement('div');
tagList.className = 'tag-list';
const renderTags = () => {
tagList.innerHTML = '';
const currentTags = info.tags || [];
currentTags.forEach(tag => {
const chip = document.createElement('div');
chip.className = 'tag-chip';
chip.innerHTML = `${tag} <button data-tag="${tag}">×</button>`;
chip.querySelector('button').onclick = () => removeTag(word, tag);
tagList.appendChild(chip);
});
};
renderTags();
const addRow = document.createElement('div');
addRow.className = 'tag-add-row';
const input = document.createElement('input');
input.id = 'newTagInput';
input.placeholder = 'Add tag...';
input.setAttribute('list', 'existingTags'); // Datalist for suggestions
const addBtn = document.createElement('button');
addBtn.id = 'addTagBtn';
addBtn.textContent = 'Add';
addBtn.onclick = () => {
const newTag = input.value.trim();
if(newTag) {
addTag(word, newTag);
input.value = '';
}
};
addRow.appendChild(input);
addRow.appendChild(addBtn);
tagContainer.appendChild(tagList);
tagContainer.appendChild(addRow);
details.appendChild(tagContainer);
modal.appendChild(closeBtn);
modal.appendChild(title);
modal.appendChild(details);
overlay.appendChild(modal);
document.body.appendChild(overlay);
// Populate Datalist for Autocomplete
chrome.storage.local.get(['wordDex'], (data) => {
const allTags = new Set();
Object.values(data.wordDex || {}).forEach(w => {
if(w.tags) w.tags.forEach(t => allTags.add(t));
});
let datalist = document.getElementById('existingTags');
if(!datalist) {
datalist = document.createElement('datalist');
datalist.id = 'existingTags';
document.body.appendChild(datalist);
}
datalist.innerHTML = '';
allTags.forEach(tag => {
const option = document.createElement('option');
option.value = tag;
datalist.appendChild(option);
});
});
// Tag Actions
const addTag = (targetWord, tag) => {
chrome.storage.local.get(['wordDex'], (data) => {
const dex = data.wordDex || {};
if(dex[targetWord]) {
if(!dex[targetWord].tags) dex[targetWord].tags = [];
if(!dex[targetWord].tags.includes(tag)) {
dex[targetWord].tags.push(tag);
chrome.storage.local.set({ wordDex: dex }, () => {
info.tags = dex[targetWord].tags; // Update local reference
renderTags();
displayWordDex(currentSort); // Update background list
});
}
}
});
};
const removeTag = (targetWord, tag) => {
chrome.storage.local.get(['wordDex'], (data) => {
const dex = data.wordDex || {};
if(dex[targetWord] && dex[targetWord].tags) {
dex[targetWord].tags = dex[targetWord].tags.filter(t => t !== tag);
chrome.storage.local.set({ wordDex: dex }, () => {
info.tags = dex[targetWord].tags; // Update local reference
renderTags();
displayWordDex(currentSort);
});
}
});
};
}
function displayError(message) {
const dexDiv = document.getElementById("dex");
if (dexDiv) {
dexDiv.innerHTML = `<p style="color: red; text-align: center; padding: 20px;">${escapeHtml(message)}</p>`;
}
}
function setupSortButtons() {
// Restore persistent sort
chrome.storage.local.get(['lastSort'], (data) => {
if (data.lastSort) {
currentSort = data.lastSort;
updateActiveSortButton(currentSort);
// Don't call displayWordDex here, popup initialization calls it globally
}
});
const buttons = document.querySelectorAll('.sort-btn');
buttons.forEach(btn => {
btn.addEventListener('click', () => {