-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.user.js
More file actions
2128 lines (1834 loc) · 87 KB
/
script.user.js
File metadata and controls
2128 lines (1834 loc) · 87 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
// ==UserScript==
// @name JPDB Immersion Kit Examples Fork
// @version 1.16.1
// @description Fork of awoo's JPDB Immersion Kit Examples script
// @namespace jpdb-imkit-fork
// @match https://jpdb.io/review*
// @match https://jpdb.io/vocabulary/*
// @match https://jpdb.io/kanji/*
// @match https://jpdb.io/search*
// @grant GM_addElement
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @updateURL https://raw.githubusercontent.com/6a67/jpdb-imkit-fork/main/script.user.js
// @license MIT
// ==/UserScript==
(function () {
'use strict';
const CONFIG = {
// IMAGE_WIDTH: '400px',
IMAGE_HEIGHT: '200px',
WIDE_MODE: true,
SOUND_VOLUME: 80,
ENABLE_EXAMPLE_TRANSLATION: true,
SENTENCE_FONT_SIZE: '120%',
TRANSLATION_FONT_SIZE: '85%',
COLORED_SENTENCE_TEXT: true,
// AUTO_PLAY_SOUND: true,
AUTO_PLAY_ON_REVEAL: false,
AUTO_PLAY_ON_CHANGE: true,
NUMBER_OF_PRELOADS: 1,
MINIMUM_EXAMPLE_LENGTH: 0,
SHOW_FURIGANA: true,
PREFERRED_DECK_NAMES: '',
NUMBER_OF_PREFERRED_EXAMPLES: 10,
// This currently hides the whole section
// making it impossible to reveal the section
// from a Kanji card
// This should be fixed in the future
DISABLE_FOR_KANJI_CARDS: false,
// Setting the host for the API manually to allow
// for a proxy that caches the responses and
// returns cold responses
// Not needed anymore as the preload is fixed
API_HOST: 'https://api.immersionkit.com',
};
const EDITABLE_STRING_KEYS = new Set(['API_HOST', 'PREFERRED_DECK_NAMES']);
const state = {
currentExampleIndex: 0,
examples: [],
apiDataFetched: false,
vocab: '',
embedAboveSubsectionMeanings: false,
preloadedIndices: new Set(),
currentAudio: null,
exactSearch: false,
error: false,
currentlyPlayingAudio: false
};
function getSpecificStyles(selector) {
const styles = {};
for (const sheet of document.styleSheets) {
try {
for (const rule of sheet.cssRules) {
if (rule.selectorText === selector) {
for (let i = 0; i < rule.style.length; i++) {
const property = rule.style[i];
styles[property] = rule.style.getPropertyValue(property);
}
}
}
} catch (e) {
// Ignore errors from accessing cross-origin stylesheets
}
}
return styles;
}
function copyStylesToClass(sourceSelector, targetClassName, skip = []) {
const styles = getSpecificStyles(sourceSelector);
let styleString = `.${targetClassName} {`;
for (const [property, value] of Object.entries(styles)) {
if (skip.includes(property)) continue;
styleString += `${property}: ${value}; `;
}
styleString += '}';
GM_addStyle(styleString);
}
function shuffleWithinRange(array, range = 7) {
let result = [...array];
for (let i = 0; i < result.length; i++) {
const shift = Math.floor(Math.random() * (2 * range + 1)) - range;
let newPos = i + shift;
newPos = Math.max(0, Math.min(newPos, result.length - 1));
if (newPos !== i) {
const element = result.splice(i, 1)[0];
result.splice(newPos, 0, element);
}
}
return result;
}
function getElementByOriginalIndex(originalIndex) {
return state.examples.find((element) => element.originalIndex === originalIndex);
}
function moveToFront(list, element) {
const index = list.indexOf(element);
if (index > -1) {
list.splice(index, 1);
list.unshift(element);
}
return list;
}
function sortPreferredDecksFirst(examples) {
const preferredDeckNames = CONFIG.PREFERRED_DECK_NAMES.split(',').map((deckName) => deckName.trim());
if (!preferredDeckNames.length) {
return examples;
}
const preferredExamples = [];
const otherExamples = [];
for (const example of examples) {
if (preferredExamples.length < CONFIG.NUMBER_OF_PREFERRED_EXAMPLES && preferredDeckNames.includes(example.deck_name)) {
preferredExamples.push(example);
} else {
otherExamples.push(example);
}
}
return [...preferredExamples, ...otherExamples];
}
// IndexedDB Manager
const IndexedDBManager = {
MAX_ENTRIES: 1000,
EXPIRATION_TIME: 30 * 24 * 60 * 60 * 1000, // 30 days in milliseconds
open() {
return new Promise((resolve, reject) => {
const request = indexedDB.open('ImmersionKitDB', 1);
request.onupgradeneeded = function (event) {
const db = event.target.result;
if (!db.objectStoreNames.contains('dataStore')) {
db.createObjectStore('dataStore', { keyPath: 'keyword' });
}
};
request.onsuccess = function (event) {
resolve(event.target.result);
};
request.onerror = function (event) {
reject('IndexedDB error: ' + event.target.errorCode);
};
});
},
get(db, keyword) {
return new Promise((resolve, reject) => {
const transaction = db.transaction(['dataStore'], 'readonly');
const store = transaction.objectStore('dataStore');
const request = store.get(keyword);
request.onsuccess = async function(event) {
const result = event.target.result;
if (result) {
const isExpired = Date.now() - result.timestamp >= this.EXPIRATION_TIME;
const validationError = validateApiResponse(result.data);
if (isExpired) {
console.log(`Deleting entry for keyword "${keyword}" because it is expired.`);
await this.deleteEntry(db, keyword);
resolve(null);
} else if (validationError) {
console.log(`Deleting entry for keyword "${keyword}" due to validation error: ${validationError}`);
await this.deleteEntry(db, keyword);
resolve(null);
} else {
resolve(result.data);
}
} else {
resolve(null);
}
}.bind(this);
request.onerror = function (event) {
reject('IndexedDB get error: ' + event.target.errorCode);
};
});
},
deleteEntry(db, keyword) {
return new Promise((resolve, reject) => {
const transaction = db.transaction(['dataStore'], 'readwrite');
const store = transaction.objectStore('dataStore');
const request = store.delete(keyword);
request.onsuccess = () => resolve();
request.onerror = (e) => reject('IndexedDB delete error: ' + e.target.errorCode);
});
},
getAll(db) {
return new Promise((resolve, reject) => {
const transaction = db.transaction(['dataStore'], 'readonly');
const store = transaction.objectStore('dataStore');
const entries = [];
store.openCursor().onsuccess = function (event) {
const cursor = event.target.result;
if (cursor) {
entries.push(cursor.value);
cursor.continue();
} else {
resolve(entries);
}
};
store.openCursor().onerror = function (event) {
reject('Failed to retrieve entries via cursor: ' + event.target.errorCode);
};
});
},
save(db, keyword, data) {
return new Promise(async (resolve, reject) => {
try {
const validationError = validateApiResponse(data);
if (validationError) {
console.log(`Invalid data detected: ${validationError}. Not saving to IndexedDB.`);
resolve();
return;
}
const entries = await this.getAll(db);
const transaction = db.transaction(['dataStore'], 'readwrite');
const store = transaction.objectStore('dataStore');
if (entries.length >= this.MAX_ENTRIES) {
// Sort entries by timestamp and delete oldest ones
entries.sort((a, b) => a.timestamp - b.timestamp);
const entriesToDelete = entries.slice(0, entries.length - this.MAX_ENTRIES + 1);
// Delete old entries
entriesToDelete.forEach((entry) => {
store.delete(entry.keyword).onerror = function () {
console.error('Failed to delete entry:', entry.keyword);
};
});
}
// Add the new entry
const addRequest = store.put({ keyword, data, timestamp: Date.now() });
addRequest.onsuccess = () => resolve();
addRequest.onerror = (e) => reject('IndexedDB save error: ' + e.target.errorCode);
transaction.oncomplete = function () {
console.log('IndexedDB updated successfully.');
};
transaction.onerror = function(event) {
reject('IndexedDB update failed: ' + event.target.errorCode);
};
} catch (error) {
reject(`Error in saveToIndexedDB: ${error}`);
}
});
},
delete() {
return new Promise((resolve, reject) => {
const request = indexedDB.deleteDatabase('ImmersionKitDB');
request.onsuccess = function () {
console.log('IndexedDB deleted successfully');
resolve();
};
request.onerror = function (event) {
console.error('Error deleting IndexedDB:', event.target.errorCode);
reject('Error deleting IndexedDB: ' + event.target.errorCode);
};
request.onblocked = function () {
console.warn('Delete operation blocked. Please close all other tabs with this site open and try again.');
reject('Delete operation blocked');
};
});
},
};
// API FUNCTIONS=====================================================================================================================
function getImmersionKitData(vocab, exactSearch) {
return new Promise(async (resolve, reject) => {
const searchVocab = exactSearch ? `「${vocab}」` : vocab;
const url = `${CONFIG.API_HOST}/look_up_dictionary?keyword=${encodeURIComponent(searchVocab)}&sort=shortness&min_length=${
CONFIG.MINIMUM_EXAMPLE_LENGTH
}`;
const maxRetries = 5;
let attempt = 0;
async function fetchData() {
try {
const db = await IndexedDBManager.open();
const cachedData = await IndexedDBManager.get(db, searchVocab);
if (cachedData && Array.isArray(cachedData.data) && cachedData.data.length > 0) {
console.log('Data retrieved from IndexedDB');
state.examples = cachedData.data[0].examples;
// add to each example its original index
state.examples.forEach((example, index) => {
example.originalIndex = index;
});
state.examples = shuffleWithinRange(state.examples, Math.floor(state.examples.length * 0.04) + 1);
state.examples = sortPreferredDecksFirst(state.examples);
state.apiDataFetched = true;
resolve();
} else {
console.log(`Calling API for: ${searchVocab}`);
GM_xmlhttpRequest({
method: 'GET',
url: url,
onload: async function (response) {
if (response.status === 200) {
const jsonData = parseJSON(response.responseText);
console.log('API JSON Received');
console.log(url);
const validationError = validateApiResponse(jsonData);
if (!validationError) {
state.examples = jsonData.data[0].examples;
state.examples.forEach((example, index) => {
example.originalIndex = index;
});
state.examples = shuffleWithinRange(state.examples, Math.floor(state.examples.length * 0.04) + 1);
state.examples = sortPreferredDecksFirst(state.examples);
state.apiDataFetched = true;
await IndexedDBManager.save(db, searchVocab, jsonData);
resolve();
} else {
attempt++;
if (attempt < maxRetries) {
console.log(`Validation error: ${validationError}. Retrying... (${attempt}/${maxRetries})`);
fetchData();
} else {
reject(`Invalid API response after ${maxRetries} attempts: ${validationError}`);
state.error = true;
embedImageAndPlayAudio(); //update displayed text
}
}
} else {
reject(`API call failed with status: ${response.status}`);
}
},
onerror: function (error) {
reject(`An error occurred: ${error}`);
},
});
}
} catch (error) {
reject(`Error: ${error}`);
}
}
fetchData();
});
}
function parseJSON(responseText) {
try {
return JSON.parse(responseText);
} catch (e) {
console.error('Error parsing JSON:', e);
return null;
}
}
function validateApiResponse(jsonData) {
state.error = false;
if (!jsonData) {
return 'Not a valid JSON';
}
if (!jsonData.data || !jsonData.data[0] || !jsonData.data[0].examples) {
return 'Missing required data fields';
}
const categoryCount = jsonData.data[0].category_count;
if (!categoryCount) {
return 'Missing category count';
}
// Check if all category counts are zero
const allZero = Object.values(categoryCount).every(count => count === 0);
if (allZero) {
return 'Blank API';
}
return null; // No error
}
//FAVORITE DATA FUNCTIONS=====================================================================================================================
function getStoredData(key) {
// Retrieve the stored value from localStorage using the provided key
const storedValue = localStorage.getItem(key);
// If a stored value exists, split it into index and exactState
if (storedValue) {
const [index, exactState] = storedValue.split(',');
return {
index: parseInt(index, 10), // Convert index to an integer
exactState: exactState === '1', // Convert exactState to a boolean
};
}
// Return default values if no stored value exists
return { index: -1, exactState: state.exactSearch };
}
function storeData(key, index, exactState) {
// Create a string value from index and exactState to store in localStorage
const value = `${index},${exactState ? 1 : 0}`;
// Store the value in localStorage using the provided key
localStorage.setItem(key, value);
}
// PARSE VOCAB FUNCTIONS =====================================================================================================================
function parseVocabFromAnswer() {
// Select all links containing "/kanji/" or "/vocabulary/" in the href attribute
const elements = document.querySelectorAll('a.plain[href*="/kanji/"], a.plain[href*="/vocabulary/"]');
console.log('Parsing Answer Page');
// Iterate through the matched elements
for (const element of elements) {
const href = element.getAttribute('href');
const text = element.textContent.trim();
let kind = '';
if (href.includes('/kanji/')) {
kind = 'Kanji';
} else if (href.includes('/vocabulary/')) {
kind = 'Vocabulary';
}
// Match the href to extract kanji or vocabulary (ignoring ID if present)
const match = href.match(/\/(kanji|vocabulary)\/(?:\d+\/)?([^\#]*)#/);
if (match) return { kind, vocab: match[2].trim() };
if (text) return { kind, vocab: text.trim() };
}
return { kind: '', vocab: '' };
}
function parseVocabFromReview() {
// Select the element with class 'kind' to determine the type of content
const kindElement = document.querySelector('.kind');
console.log('Parsing Review Page');
// If kindElement doesn't exist, set kindText to ''
let kindText = kindElement ? kindElement.textContent.trim() : '';
// Accept 'Kanji', 'Vocabulary', or 'New' kindText
// if (kindText !== 'Kanji' && kindText !== 'Vocabulary' && kindText !== 'New') return ''; // Return empty if it's neither kanji nor vocab
// New code
// I am translating the user interface which is why this check fails for me
// Here I am testing for the hidden input element
// TODO: New Card detection
const hiddenInput = document.querySelector('input[type="hidden"][name="c"]');
const value = hiddenInput?.value;
if (value?.startsWith('kb,')) {
kindText = 'Kanji';
}
if (value?.startsWith('vf,')) {
kindText = 'Vocabulary';
}
if (kindText === 'Vocabulary' || kindText === 'New') {
// Select the element with class 'plain' to extract vocabulary
const plainElement = document.querySelector('.plain');
if (!plainElement) {
return { kind: kindText, vocab: '' };
}
let vocabulary = plainElement.textContent.trim();
const plainPlainElement = plainElement.querySelector('.plain')?.cloneNode(true);
if (plainPlainElement) {
// Remove furigana
plainPlainElement.querySelectorAll('rt').forEach((rt) => rt.remove());
vocabulary = plainPlainElement.textContent.trim();
}
// Regular expression to check if the vocabulary contains kanji characters
const kanjiRegex = /[\u4e00-\u9faf\u3400-\u4dbf]/;
if (kanjiRegex.test(vocabulary) || vocabulary) {
console.log('Found Vocabulary:', vocabulary);
return { kind: kindText, vocab: vocabulary };
}
} else if (kindText === 'Kanji') {
// Select the hidden input element to extract kanji
const hiddenInput = document.querySelector('input[name="c"]');
if (!hiddenInput) {
return { kind: kindText, vocab: '' };
}
const vocab = hiddenInput.value.split(',')[1];
const kanjiRegex = /[\u4e00-\u9faf\u3400-\u4dbf]/;
if (kanjiRegex.test(vocab)) {
console.log('Found Kanji:', vocab);
return { kind: kindText, vocab };
}
}
return { kind: kindText, vocab: '' };
}
function parseVocabFromVocabulary() {
// Get the current URL
let url = window.location.href;
// Remove query parameters (e.g., ?lang=english) and fragment identifiers (#)
url = url.split('?')[0].split('#')[0];
// Match the URL structure for a vocabulary page
const match = url.match(/https:\/\/jpdb\.io\/vocabulary\/(\d+)\/([^\#\/]*)/);
console.log('Parsing Vocabulary Page');
if (match) {
// Extract and decode the vocabulary part from the URL
let vocab = match[2];
state.embedAboveSubsectionMeanings = true; // Set state flag
return decodeURIComponent(vocab);
}
// Return empty string if no match
return '';
}
function parseVocabFromKanji() {
// Get the current URL
const url = window.location.href;
// Match the URL structure for a kanji page
const match = url.match(/https:\/\/jpdb\.io\/kanji\/(\d+)\/([^\#]*)#a/);
console.log('Parsing Kanji Page');
if (match) {
// Extract and decode the kanji part from the URL
let kanji = match[2];
state.embedAboveSubsectionMeanings = true; // Set state flag
kanji = kanji.split('/')[0];
return decodeURIComponent(kanji);
}
// Return empty string if no match
return '';
}
function parseVocabFromSearch() {
// Get the current URL
let url = window.location.href;
// Match the URL structure for a search query, capturing the vocab between `?q=` and either `&` or `+`
const match = url.match(/https:\/\/jpdb\.io\/search\?q=([^&+]*)/);
console.log("Parsing Search Page");
if (match) {
// Extract and decode the vocabulary part from the URL
let vocab = match[1];
return decodeURIComponent(vocab);
}
// Return empty string if no match
return '';
}
//EMBED FUNCTIONS=====================================================================================================================
function createAnchor(marginLeft) {
// Create and style an anchor element
const anchor = document.createElement('a');
anchor.href = '#';
anchor.style.border = '0';
anchor.style.display = 'inline-flex';
anchor.style.verticalAlign = 'middle';
anchor.style.marginLeft = marginLeft;
return anchor;
}
function createIcon(iconClass, fontSize = '1.4rem', color = 'var(--link-color)') {
// Create and style an icon element
const icon = document.createElement('i');
icon.className = iconClass;
icon.style.fontSize = fontSize;
icon.style.opacity = '0.7';
icon.style.verticalAlign = 'baseline';
icon.style.color = color;
return icon;
}
function createSpeakerButton(soundUrl) {
// Create a speaker button with an icon and click event for audio playback
const anchor = createAnchor('0.5rem');
const icon = createIcon('ti ti-volume');
anchor.appendChild(icon);
anchor.addEventListener('click', (event) => {
event.preventDefault();
playAudio(soundUrl);
});
return anchor;
}
function createStarButton() {
// Create a star button with an icon and click event for toggling favorite state
const anchor = createAnchor('0.5rem');
const starIcon = document.createElement('span');
const storedValue = localStorage.getItem(state.vocab);
// Determine the star icon (filled or empty) based on stored value
if (!storedValue) {
starIcon.textContent = '☆';
} else {
const [storedIndex, storedExactState] = storedValue.split(',');
const index = parseInt(storedIndex, 10);
const exactState = storedExactState === '1';
starIcon.textContent =
state.examples[state.currentExampleIndex].originalIndex === index && state.exactSearch === exactState ? '★' : '☆';
}
// Style the star icon
starIcon.style.fontSize = '1.4rem';
// starIcon.style.color = '#3D8DFF';
starIcon.style.color = 'var(--link-color)';
starIcon.style.opacity = '0.7';
starIcon.style.verticalAlign = 'middle';
starIcon.style.position = 'relative';
starIcon.style.top = '-2px';
// Append the star icon to the anchor and set up the click event to toggle star state
anchor.appendChild(starIcon);
anchor.addEventListener('click', (event) => {
event.preventDefault();
toggleStarState(starIcon);
});
return anchor;
}
function toggleStarState(starIcon) {
// Toggle the star state between filled and empty
const storedValue = localStorage.getItem(state.vocab);
const originalIndex = state.examples[state.currentExampleIndex].originalIndex;
if (storedValue) {
const [storedIndex, storedExactState] = storedValue.split(',');
const index = parseInt(storedIndex, 10);
const exactState = storedExactState === '1';
if (index === originalIndex && exactState === state.exactSearch) {
localStorage.removeItem(state.vocab);
starIcon.textContent = '☆';
} else {
localStorage.setItem(state.vocab, `${originalIndex},${state.exactSearch ? 1 : 0}`);
starIcon.textContent = '★';
}
} else {
localStorage.setItem(state.vocab, `${originalIndex},${state.exactSearch ? 1 : 0}`);
starIcon.textContent = '★';
}
}
function createQuoteButton() {
// Create a quote button with an icon and click event for toggling quote style
const anchor = createAnchor('0rem');
const quoteIcon = document.createElement('span');
// Set the icon based on exact search state
quoteIcon.innerHTML = state.exactSearch ? '<b>「」</b>' : '『』';
// Style the quote icon
quoteIcon.style.fontSize = '1.1rem';
// quoteIcon.style.color = '#3D8DFF';
quoteIcon.style.color = 'var(--link-color)';
quoteIcon.style.opacity = '0.7';
quoteIcon.style.verticalAlign = 'middle';
quoteIcon.style.position = 'relative';
quoteIcon.style.top = '0px';
// Append the quote icon to the anchor and set up the click event to toggle quote state
anchor.appendChild(quoteIcon);
anchor.addEventListener('click', (event) => {
event.preventDefault();
toggleQuoteState(quoteIcon);
});
return anchor;
}
function toggleQuoteState(quoteIcon) {
// Toggle between single and double quote styles
state.exactSearch = !state.exactSearch;
quoteIcon.innerHTML = state.exactSearch ? '<b>「」</b>' : '『』';
// Update state based on stored data
const storedData = getStoredData(state.vocab);
if (storedData && storedData.exactState === state.exactSearch) {
// TODO: Not quite sure what this does
// state.currentExampleIndex = storedData.index;
// const element = getElementByOriginalIndex(storedData.index);
// if (element) {
// state.currentExampleIndex = state.examples.indexOf(element);
// }
state.currentExampleIndex = 0;
} else {
state.currentExampleIndex = 0;
}
state.apiDataFetched = false;
getImmersionKitData(state.vocab, state.exactSearch)
.then(() => {
if (storedData.index >= 0 && storedData.exactState === state.exactSearch) {
const element = getElementByOriginalIndex(storedData.index);
moveToFront(state.examples, element);
}
embedImageAndPlayAudio();
})
.catch((error) => {
console.error(error);
});
}
function createMenuButton() {
// Create a menu button with a dropdown menu
const anchor = createAnchor('0.5rem');
const menuIcon = document.createElement('span');
menuIcon.innerHTML = '☰';
// Style the menu icon
menuIcon.style.fontSize = '1.4rem';
// menuIcon.style.color = '#3D8DFF';
menuIcon.style.color = 'var(--link-color)';
menuIcon.style.opacity = '0.7';
menuIcon.style.verticalAlign = 'middle';
menuIcon.style.position = 'relative';
menuIcon.style.top = '-2px';
// Append the menu icon to the anchor and set up the click event to show the overlay menu
anchor.appendChild(menuIcon);
anchor.addEventListener('click', (event) => {
event.preventDefault();
const overlay = createOverlayMenu();
document.body.appendChild(overlay);
});
return anchor;
}
function createTextButton(vocab, exact) {
// Create a text button for the Immersion Kit
const textButton = document.createElement('a');
textButton.textContent = 'Immersion Kit';
textButton.style.color = 'var(--subsection-label-color)';
textButton.style.fontSize = '85%';
textButton.style.marginRight = '0.5rem';
textButton.style.verticalAlign = 'middle';
textButton.href = `https://www.immersionkit.com/dictionary?keyword=${encodeURIComponent(vocab)}&sort=shortness${
exact ? '&exact=true' : ''
}`;
textButton.target = '_blank';
return textButton;
}
function createButtonContainer(soundUrl, vocab, exact) {
// Create a container for all buttons
const buttonContainer = document.createElement('div');
buttonContainer.className = 'button-container';
buttonContainer.style.display = 'flex';
buttonContainer.style.justifyContent = 'space-between';
buttonContainer.style.alignItems = 'center';
buttonContainer.style.marginBottom = '5px';
buttonContainer.style.lineHeight = '1.4rem';
// Create individual buttons
const menuButton = createMenuButton();
const textButton = createTextButton(vocab, exact);
const speakerButton = createSpeakerButton(soundUrl);
const starButton = createStarButton();
const quoteButton = createQuoteButton();
// Center the buttons within the container
const centeredButtonsWrapper = document.createElement('div');
centeredButtonsWrapper.style.display = 'flex';
centeredButtonsWrapper.style.justifyContent = 'center';
centeredButtonsWrapper.style.flex = '1';
centeredButtonsWrapper.append(textButton, speakerButton, starButton, quoteButton);
buttonContainer.append(centeredButtonsWrapper, menuButton);
return buttonContainer;
}
function stopCurrentAudio() {
// Stop any currently playing audio
if (state.currentAudio) {
state.currentAudio.source.stop();
state.currentAudio.context.close();
state.currentAudio = null;
}
}
function playAudio(soundUrl) {
// Skip playing audio if it is already playing
if (state.currentlyPlayingAudio) {
//console.log('Duplicate audio was skipped.');
return;
}
if (soundUrl) {
state.currentlyPlayingAudio = true;
stopCurrentAudio();
GM_xmlhttpRequest({
method: 'GET',
url: soundUrl,
responseType: 'arraybuffer',
onload: function (response) {
const audioContext = new (window.AudioContext || window.webkitAudioContext)();
audioContext.decodeAudioData(
response.response,
function (buffer) {
const source = audioContext.createBufferSource();
source.buffer = buffer;
const gainNode = audioContext.createGain();
// Connect the source to the gain node and the gain node to the destination
source.connect(gainNode);
gainNode.connect(audioContext.destination);
// Mute the first part and then ramp up the volume
gainNode.gain.setValueAtTime(0, audioContext.currentTime);
gainNode.gain.linearRampToValueAtTime(CONFIG.SOUND_VOLUME / 100, audioContext.currentTime + 0.1);
// Play the audio, skip the first part to avoid any "pop"
source.start(0, 0.05);
// Log when the audio starts playing
//console.log('Audio has started playing.');
// Save the current audio context and source for stopping later
state.currentAudio = {
context: audioContext,
source: source
};
// Set currentlyPlayingAudio to false when the audio ends
source.onended = function() {
state.currentlyPlayingAudio = false;
};
}, function(error) {
console.error('Error decoding audio:', error);
state.currentlyPlayingAudio = false;
});
},
onerror: function (error) {
console.error('Error fetching audio:', error);
state.currentlyPlayingAudio = false;
}
});
}
}
function renderImageAndPlayAudio(vocab, shouldAutoPlaySound) {
const example = state.examples[state.currentExampleIndex] || {};
const imageUrl = example.image_url || null;
const soundUrl = example.sound_url || null;
// Remove any existing container
removeExistingContainer();
if (!shouldRenderContainer()) return;
// Create and append the main wrapper and text button container
const wrapperDiv = createWrapperDiv();
const textDiv = createButtonContainer(soundUrl, vocab, state.exactSearch);
wrapperDiv.appendChild(textDiv);
// Handle image rendering and click event for playing audio
if (state.apiDataFetched) {
if (imageUrl) {
const imageElement = createImageElement(wrapperDiv, imageUrl, vocab, state.exactSearch);
if (imageElement) {
imageElement.addEventListener('click', () => playAudio(soundUrl));
}
} else {
const noImageText = document.createElement('div');
noImageText.textContent = `NO IMAGE\n(${state.examples[state.currentExampleIndex].deck_name})`;
noImageText.style.padding = '100px 0';
noImageText.style.whiteSpace = 'pre'; // This ensures that newlines are respected
wrapperDiv.appendChild(noImageText);
}
} else if (state.error) {
const errorText = document.createElement('div');
errorText.textContent = 'ERROR\nNO EXAMPLES FOUND\n\nRARE WORD OR\nIMMERSIONKIT API IS TEMPORARILY DOWN';
errorText.style.padding = '100px 0';
errorText.style.whiteSpace = 'pre'; // This ensures that newlines are respected
wrapperDiv.appendChild(errorText);
} else {
const loadingText = document.createElement('div');
loadingText.textContent = 'LOADING';
loadingText.style.padding = '100px 0';
wrapperDiv.appendChild(loadingText);
}
// Append sentence and translation or a placeholder text
example && state.apiDataFetched ? appendSentenceAndTranslation(wrapperDiv, example, state.vocab) : appendNoneText(wrapperDiv);
// Create navigation elements
const navigationDiv = createNavigationDiv();
const leftArrow = createLeftArrow(vocab, CONFIG.AUTO_PLAY_ON_CHANGE);
const rightArrow = createRightArrow(vocab, CONFIG.AUTO_PLAY_ON_CHANGE);
// Create and append the main container
const containerDiv = createContainerDiv(leftArrow, wrapperDiv, rightArrow, navigationDiv);
appendContainer(containerDiv);
// Auto-play sound if configured
if (shouldAutoPlaySound) {
playAudio(soundUrl);
}
}
function removeExistingContainer() {
// Remove the existing container if it exists
const existingContainer = document.getElementById('immersion-kit-container');
if (existingContainer) {
existingContainer.remove();
}
}
function shouldRenderContainer() {
// Determine if the container should be rendered based on the presence of certain elements
const resultVocabularySection = document.querySelector('.result.vocabulary');
const hboxWrapSection = document.querySelector('.hbox.wrap');
const subsectionMeanings = document.querySelector('.subsection-meanings');
const subsectionLabels = document.querySelectorAll('h6.subsection-label');
return resultVocabularySection || hboxWrapSection || subsectionMeanings || subsectionLabels.length >= 3;
}
function createWrapperDiv() {
// Create and style the wrapper div
const wrapperDiv = document.createElement('div');
wrapperDiv.id = 'image-wrapper';
wrapperDiv.style.textAlign = 'center';
wrapperDiv.style.padding = '5px 0';
wrapperDiv.style.display = 'flex';
wrapperDiv.style.flexDirection = 'column';
wrapperDiv.style.alignItems = 'center';
return wrapperDiv;
}
function createImageElement(wrapperDiv, imageUrl, vocab, exactSearch) {
// Create a container for the image
const imageContainer = document.createElement('div');
imageContainer.style.aspectRatio = '16 / 9';
imageContainer.style.width = '100%';
imageContainer.style.display = 'flex';
imageContainer.style.justifyContent = 'center';
imageContainer.style.alignItems = 'center';
imageContainer.style.maxHeight = CONFIG.IMAGE_HEIGHT;
// Create and return an image element with specified attributes
const searchVocab = exactSearch ? `「${vocab}」` : vocab;
const titleText = `${searchVocab} #${state.currentExampleIndex + 1} \n${state.examples[state.currentExampleIndex].deck_name}`;
const imageElement = GM_addElement(imageContainer, 'img', {
src: imageUrl,
alt: 'Embedded Image',
title: titleText,
style: `height: 100%; max-width: 100%; object-fit: contain; cursor: pointer;`,
});
// Append the image container to the wrapper div
wrapperDiv.appendChild(imageContainer);
return imageElement;
}
function findSublistIndices(mainList, subList) {
const indices = [];
const subLength = subList.length;