-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathWaniKani Open Framework Kanjidic2 and Traditional Radicals Filters.user.js
3170 lines (2807 loc) · 161 KB
/
WaniKani Open Framework Kanjidic2 and Traditional Radicals Filters.user.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
// ==UserScript==
// @name WaniKani Open Framework Kanjidic2 and Traditional Radicals Filters
// @namespace https://www.wanikani.com
// @description Kanjidic2 and traditional radicals filters for the WaniKani Open Framework
// @author prouleau
// @version 1.4.0
// @match https://www.wanikani.com/*
// @license GPLV3; https://www.gnu.org/licenses/gpl-3.0.en.html and MIT; http://opensource.org/licenses/MIT --- with an exception described in comments
// @grant none
// ==/UserScript==
// ===============================================================
// Software Licence
//
// The license is GPLV3 or later because this script includes @acm2010 code and databases licenced under GPLV3 or later
// --- for Keisei Semantic-Phonetic Composition
// --- for Niai Visual Similarity Data
//
// Code borrowed from WKOF is licensed under MIT --- http://opensource.org/licenses/MIT
//
// You may use Item Inspector code under either the GPLV3 or MIT license with these restrictions.
// --- The GPLV3 or later code and database borrowed from @acm2010 must remain licensed under GPLV3 or later in all cases.
// --- If you use @acm2010 code and/or databases you work as a whole must be licensed under GPLV3 or later to comply with @acm2010 license.
// --- The MIT code borrowed from WKOF must remain licensed under MIT in all cases.
// These restrictions are required because we can't legally change the license for someone else's code and database without their permission.
// Not even if we modify their code.
//
// ===============================================================
/* globals $, _, LZMA */
/* eslint-disable no-eval */
/* eslint-disable no-multi-spaces */
/* eslint-disable curly */
/* eslint-disable no-return-assign */
var advSearchFilters = {};
(function(wkof) {
'use strict';
//=================================================================
// These filters are button type filters
// They need a path to be defined in the config parameter of the on_click handler to locate where to store the filter parameters.
// The exception is Self Study Quiz because the path is automatically figured out upon detection that the on_click function is called from Self Study Quiz
//
// They support the callable dialog protocol, meaning that the on_click handler is callable directly without having to click an actual button
// The support of this protocol is indicated by the flag callable_dialog: true in the registry entry for the filter
//
// Callable on_click handlers support in their config parameter three callbacks and require one parameter
//
// on_save: called when the settings are saved
// on_cancel: called when the settings are cancelled
// on_close: called when the dialog is closed
// script_id: (required when called without clicking a button) must be the script id used to store wkof settings. (wkof.settings[script_id])
//
//=================================================================
var wkofMinimumVersion = '1.0.52';
if (!wkof) {
var response = confirm('WaniKani Open Framework Date Filters requires WaniKani Open Framework.\n Click "OK" to be forwarded to installation instructions.');
if (response) {
window.location.href = 'https://community.wanikani.com/t/instructions-installing-wanikani-open-framework/28549';
}
return;
}
// --------------------------------------
// File names for resources to be loaded.
// Prerequisite scripts
const lodash_file = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/lodash.min.js';
const lzma_file = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/lzma.js';
const lzma_shim_file = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/lzma.shim.js';
// Stroke count for Wanikani radicals
const Wkit_StrokeCountforRadicals = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/WK_radicals.json.compressed';
// Traditional radicals items
const traditionaRadicalsFile = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/trad_rad.json.compressed';
// Kanjidic 2 data
const kanjidic2File = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/kanjidic2.json.compressed';
// Keisei Semantic-Phonetic Composition databases
const kanji_db = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/kanji_esc.json.compressed';
const phonetic_db = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/phonetic_esc.json.compressed';
const wk_kanji_db = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/wk_kanji_esc.json.compressed';
// Lars Yencken visually similar kanji database - also required for Niai visual similarity
const visuallySimilarFilename = 'https://raw.githubusercontent.com/rouleaup88/item-inspector/main/stroke_edit_dist_esc.json.compressed';
// Niai Visually similar databases
const from_keisei_db_filename ='https://raw.githubusercontent.com/rouleaup88/item-inspector/main/from_keisei_esc.json.compressed';
const old_script_db_filename ='https://raw.githubusercontent.com/rouleaup88/item-inspector/main/old_script_esc.json.compressed';
const wk_niai_noto_db_filename ='https://raw.githubusercontent.com/rouleaup88/item-inspector/main/wk_niai_noto_esc.json.compressed';
const yl_radical_db_filename ='https://raw.githubusercontent.com/rouleaup88/item-inspector/main/yl_radical_esc.json.compressed';
// END of filenames
//-------------------
var settingsScriptId = 'advSearchFilters';
var settingsTitle = 'Advanced Search Filters';
var needToRegisterFilters = true;
var filterNamePrefix = 'advSearchFilters_';
var advancedSearchFilterName = filterNamePrefix + 'advancedSearch';
var relatedSearchFilterName = filterNamePrefix + 'relatedSearch';
var extensiveSearchFilterName = filterNamePrefix + 'extensiveSearch';
var strokeCountGteqFilterName = filterNamePrefix + 'strokeCountGteq';
var strokeCountLteqFilterName = filterNamePrefix + 'strokeCountLteq';
var explicitListFilterName = filterNamePrefix + 'explicitList';
var explicitBlockFilterName = filterNamePrefix + 'explicitBlock';
var supportedFilters = [advancedSearchFilterName, relatedSearchFilterName, extensiveSearchFilterName, strokeCountGteqFilterName, strokeCountLteqFilterName,
explicitListFilterName, explicitBlockFilterName, ];
function startupSequence(){
wkof.set_state(settingsScriptId, 'loading');
var config = {wk_items: {filters:{}, options:{'subjects': true,}}};
wkof.include('ItemData, Settings');
loadPrerequisiteScripts()
.then(function(){return wkof.ready('ItemData, Settings')})
.then(function(){return wkof.Settings.load(settingsScriptId)})
.then(ageCache)
.then(updateFiltersWhenReady)
};
var componentIndexKan = {};
var componentIndexVoc = {};
var usedInIndexRad = {};
var usedInIndexKan = {};
var WKvisuallySimilarIndex = {};
function prepareIndex(items){
for (var item of items){
if (item.object === 'kanji'){
componentIndexKan[item.data.slug] = item.data.component_subject_ids;
usedInIndexKan[item.data.slug] = item.data.amalgamation_subject_ids;
WKvisuallySimilarIndex[item.data.slug] = item.data.visually_similar_subject_ids;
};
if (item.object === 'radical'){
usedInIndexRad[item.data.slug] = item.data.amalgamation_subject_ids;
if (item.data.characters !== null) usedInIndexRad[item.data.characters] = item.data.amalgamation_subject_ids;
};
if (item.object !== 'vocabulary'){
componentIndexVoc[item.data.slug] = item.data.amalgamation_subject_ids;
};
};
};
function ageCache(){
// periodically ages the cache
let ageingTime = 1000*60*60*24*30*2; // two months
var now = Date.now();
if (wkof.settings[settingsScriptId] === undefined) wkof.settings[settingsScriptId] = {};
if (wkof.settings[settingsScriptId].lastTime === undefined){
wkof.settings[settingsScriptId].lastTime = now;
wkof.Settings.save(settingsScriptId);
}
let lastTime = wkof.settings[settingsScriptId].lastTime;
if (now > lastTime + ageingTime){
deleteCache();
wkof.settings[settingsScriptId].lastTime = now;
wkof.Settings.save(settingsScriptId);
};
};
function deleteCache(){
deleteKeiseiCache();
deleteVisuallySimilarCache();
deleteNiaiCache();
kanjidic2_cacheDelete();
WkStrokeCount_cacheDelete()
trad_rad_cacheDelete();
wkof.file_cache.delete(lodash_file);
wkof.file_cache.delete(lzma_file);
wkof.file_cache.delete(lzma_shim_file);
};
function updateFiltersWhenReady() {
// register the filters
needToRegisterFilters = true;
return waitForItemDataRegistry().then(registerFilters);
};
function waitForItemDataRegistry() {
return wkof.wait_state('wkof.ItemData.registry', 'ready');
};
function registerFilters() {
if (!needToRegisterFilters) {
return;
};
supportedFilters.forEach(function(filterName) {
delete wkof.ItemData.registry.sources.wk_items.filters[filterName];
});
registerTraditionalRadicals(); // must be first
registerAdvancedSearchFilter();
registerRelatedSearchFilter();
registerExtensiveSearchFilter();
registerStrokeCountGteqilter();
registerStrokeCountLteqilter();
registerExplicitListFilter();
registerExplicitBlockFilter();
needToRegisterFilters = false;
wkof.set_state(settingsScriptId, 'ready');
};
// Unicode for Japanese characters
// reference https://stackoverflow.com/questions/15033196/using-javascript-to-check-whether-a-string-contains-japanese-characters-includi
//
// regexes for splitting stings into words, one to get composed words that may have ' and - and one for subwords separated by ' or -
const breakTheWords = /[^\-'a-zA-Z0-9\u3040-\u309f\u30a0-\u30ff\u4e00-\u9faf\u3400-\u4dbf]/;
const breakTheSubwords = /[\-']/;
const noHtml = /<[^>]*>/g;
// constants for searches
const all = '*';
const none = '!*'
// ------------------
// helping functions
// split_list() is borrowed from @rfindley -- must be licensed under MIT
function split_list(str) {return str.replace(/、/g,',')
.replace(/[\s ]+/g,' ')
.replace(/!/g, '!')
.replace(/*/g, '*')
.trim()
.replace(/ *, */g, ',')
.replace(/ *, */g, ',')
.toLowerCase()
.split(',')
.filter(function(name) {return (name.length > 0);});
};
// detailed path parsing to make sure it is a real path and not something else -- much needed to keep eval safe to use
// there is no alternative to eval in this context
// function set_value() and get_value is borrowed from wkof Settings module -- must be under MIT license
function set_value(path, value) {
var depth=0, new_path='', param, c;
for (var idx = 0; idx < path.length; idx++) {
c = path[idx];
if (c === '[') {
if (depth++ === 0) {
new_path += '[';
param = '';
} else {
param += '[';
}
} else if (c === ']') {
if (--depth === 0) {
new_path += JSON.stringify(eval(param)) + ']';
} else {
param += ']';
}
} else {
if (c === '@') c = 'base.';
if (depth === 0)
new_path += c;
else
param += c;
};
};
eval(new_path + '=value');
};
function get_value(path) {
var depth=0, new_path='', param, c;
for (var idx = 0; idx < path.length; idx++) {
c = path[idx];
if (c === '[') {
if (depth++ === 0) {
new_path += '[';
param = '';
} else {
param += '[';
};
} else if (c === ']') {
if (--depth === 0) {
new_path += JSON.stringify(eval(param)) + ']';
} else {
param += ']';
};
} else {
if (c === '@') c = 'base.';
if (depth === 0)
new_path += c;
else
param += c;
};
};
return eval(new_path);
};
function katakana2hiragana(string){
const baseHiragana = 12352 // start of unicode hiragana block
const endHiragana = 12447 // end of unicode hiragana block
const baseKatakana = 12448 // start of unicode katakana block
const endKatakana = 12543 // end of unicode katakana block
const delta = baseKatakana - baseHiragana;
let result = []
for (let idx in string){
let x = string.charCodeAt(idx);
if (x > baseKatakana && x <= endKatakana) x -= delta;
x = String.fromCodePoint(x)
result.push(x);
};
return result.join('');
};
function reportSearchResult(item, match, place){
item.report = 'Search term '+match+' matches at '+place;
};
function prepareKanjidic2(filterValue){
dataRequired.kanjidic2 = true;
return loadMissingData();
};
function prepareKanjidic2AndWkRad(filterValue) {
dataRequired.WkStrokeCountData = true;
return prepareKanjidic2(filterValue);
};
// BEGIN Stroke Count GTEQ
let strokeCountGteqHover_tip = 'Kanji and traditional radicals whose stroke count >= value';
function registerStrokeCountGteqilter() {
const registration = {
type: 'number',
label: 'Stroke Count >=',
default: 0,
filter_func: strokeOrderGteqSearchFilter,
filter_value_map: (x) => Number(x),
prepare: prepareKanjidic2AndWkRad,
set_options: function(options) { options.subjects = true;},
hover_tip: strokeCountGteqHover_tip,
};
wkof.ItemData.registry.sources.wk_items.filters[strokeCountGteqFilterName] = $.extend({}, registration);
wkof.ItemData.registry.sources.wk_items.filters[strokeCountGteqFilterName].alternate_sources = ['trad_rad'];
wkof.ItemData.registry.sources.trad_rad.filters[strokeCountGteqFilterName] = $.extend({}, registration);
wkof.ItemData.registry.sources.trad_rad.filters[strokeCountGteqFilterName].main_source = 'wk_items';
};
function strokeOrderGteqSearchFilter(filterValue, item){
if (item.data === undefined) {
return false;
};
let itemType = item.object;
if (itemType === 'kanji' && (item.data.slug in kanjidic2Data)) {
return Number(kanjidic2Data[item.data.slug].stroke_count) >= filterValue;
} else if (itemType === 'radical') {
return WkStrokeCountData[item.id].stroke_count >= filterValue;
} else if (itemType === 'trad_rad') {
if (typeof item.data.stroke_count === 'string'){
return Number(item.data.stroke_count) >= filterValue;
};
};
return false;
};
// END Stroke Count GTEQ
// BEGIN Stroke Count LTEQ
let strokeCountLteqHover_tip = 'Kanji and traditional radicals whose stroke count <= value';
function registerStrokeCountLteqilter() {
const registration = {
type: 'number',
label: 'Stroke Count <=',
default: 100,
filter_func: strokeOrderLteqSearchFilter,
filter_value_map: (x) => Number(x),
prepare: prepareKanjidic2AndWkRad,
set_options: function(options) { options.subjects = true;},
hover_tip: strokeCountLteqHover_tip,
};
wkof.ItemData.registry.sources.wk_items.filters[strokeCountLteqFilterName] = $.extend({}, registration);
wkof.ItemData.registry.sources.wk_items.filters[strokeCountLteqFilterName].alternate_sources = ['trad_rad'];
wkof.ItemData.registry.sources.trad_rad.filters[strokeCountLteqFilterName] = $.extend({}, registration);
wkof.ItemData.registry.sources.trad_rad.filters[strokeCountLteqFilterName].main_source = 'wk_items';
};
function strokeOrderLteqSearchFilter(filterValue, item){
if (item.data === undefined) {
return false;
};
let itemType = item.object;
if (itemType === 'kanji' && item.data.characters in kanjidic2Data) {
return Number(kanjidic2Data[item.data.characters].stroke_count) <= filterValue;
} else if (itemType === 'radical') {
return WkStrokeCountData[item.id].stroke_count <= filterValue;
} else if (itemType === 'trad_rad') {
if (typeof item.data.stroke_count === 'string'){
return Number(item.data.stroke_count) <= filterValue;
};
};
return false;
};
// END Stroke Count LTEQ
// BEGIN Extensive Search
let extensiveSearchHover_tip = 'Search for terms in meanings, readings and kanji.\nKanjidic2 meaning and readings are searched.\nYou may use latin, kana and kanji.';
function registerExtensiveSearchFilter() {
const registration = {
type: 'text',
label: 'Extensive Search',
default: '',
filter_func: extensiveSearchFilter,
filter_value_map: prepareExtensiveFilterValue,
prepare: prepareKanjidic2,
set_options: function(options) { options.subjects = true;},
hover_tip: extensiveSearchHover_tip,
};
wkof.ItemData.registry.sources.wk_items.filters[extensiveSearchFilterName] = $.extend({}, registration);
wkof.ItemData.registry.sources.wk_items.filters[extensiveSearchFilterName].alternate_sources = ['trad_rad'];
wkof.ItemData.registry.sources.trad_rad.filters[extensiveSearchFilterName] = $.extend({}, registration);
wkof.ItemData.registry.sources.trad_rad.filters[extensiveSearchFilterName].main_source = 'wk_items';
};
function prepareExtensiveFilterValue(filterValue){
return split_list(filterValue);
};
function extensiveSearchFilter(filterValue, item){
if (item.data === undefined) {
return false;
};
let itemType = item.object;
for (var searchTerm of filterValue){
if (item.data.characters !== null && item.data.characters.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'characters'); return true;};
if (itemType === 'radical' && item.data.slug.indexOf(searchTerm.replace(' ', '-')) >= 0){reportSearchResult(item, searchTerm, 'characters'); return true;};
for (var meaning of item.data.meanings){
let term = meaning.meaning.toLowerCase();
if (term.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'meanings'); return true;};
};
if (itemType !== 'radical' && itemType !== 'kana_vocabulary'){
for (let reading of item.data.readings){
if (reading.reading.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'readings'); return true;};
};
};
if (itemType === 'kanji' && item.data.characters in kanjidic2Data){
for (let meaning of kanjidic2Data[item.data.characters].meanings){
let term = meaning.toLowerCase();
if (term.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'kanjidic2 meaning'); return true;};
};
for (let onyomi of kanjidic2Data[item.data.characters].onyomi){
let term = katakana2hiragana(onyomi);
if (term.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'kanjidic2 onyomi'); return true;};
};
for (let kunyomi of kanjidic2Data[item.data.characters].kunyomi){
let term = kunyomi
if (term.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'kanjidic2 kunyomi'); return true;};
};
for (let nanori of kanjidic2Data[item.data.characters].nanori){
let term = nanori
if (term.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'kanjidic2 nanori'); return true;};
};
};
};
return false;
};
// END Extensive Search
// BEGIN Advanced Search
let advancedSearchHover_tip = 'Search for terms in multiple locations of your choice.\nYou may use latin, kana and kanji.\nMultiple search options permit to tailor your search.';
function registerAdvancedSearchFilter() {
const registration = {
type: 'button',
label: 'Advanced Search',
default: advancedSearchDefaults,
callable_dialog: true,
on_click: advancedSearchDialog,
filter_func: advancedSearchFilter,
filter_value_map: prepareFilterValue,
prepare: prepareAdvancedSearch,
set_options: function(options) { options.subjects = true; options.study_materials = true; },
hover_tip: advancedSearchHover_tip,
};
wkof.ItemData.registry.sources.wk_items.filters[advancedSearchFilterName] = $.extend({}, registration);
wkof.ItemData.registry.sources.wk_items.filters[advancedSearchFilterName].alternate_sources = ['trad_rad'];
wkof.ItemData.registry.sources.trad_rad.filters[advancedSearchFilterName] = $.extend({}, registration);
wkof.ItemData.registry.sources.trad_rad.filters[advancedSearchFilterName].main_source = 'wk_items';
};
let advancedSearchDefaults = {itemType: {radical: true, kanji: true, vocabulary: true, kana_vocabulary: true, trad_rad: true,},
exactMatch: {characters: true, meanings: false, readings: true,
allow: false, block: false,
mMnemonics: false, mHints: false, rMnemonics: false, rHints: false, contextSentences: false,
mNotes: false, rNotes: false, synonyms: false,
Kanjidic2_Meaning: false, Kanjidic2_Onyomi: false,
Kanjidic2_Kunyomi: false, Kanjidic2_Nanori: false},
acceptedAnswer: true,
searchIn: {characters: true, meanings: true, readings: true, onyomi: true, kunyomi: true, nanori: true,
pos: false, allow: false, block: false,
mMnemonics: false, mHints: false, rMnemonics: false, rHints: false, contextSentences: false,
mNotes: false, rNotes: false, synonyms: false,
Kanjidic2_Meaning: false, Kanjidic2_Onyomi: false,
Kanjidic2_Kunyomi: false, Kanjidic2_Nanori: false},
keisei: {phonetic: false, nonPhonetic: false, compound: false,
notCompound: false, obscure: false, notInDB: false},
searchTerms: ''};
function advancedSearchDialog(name, config, on_change){
let $originalDialog = $('#wkof_ds').find('[role="dialog"]');
let areaId = settingsScriptId+'_advSearch';
let scriptId = config.script_id || $originalDialog.attr("aria-describedby").slice(6);
let path;
if (config.path){
path = config.path.replaceAll('@', 'wkof.settings["'+scriptId+'"].');
} else if (scriptId === 'ss_quiz') {
// Self Study Quiz doesn't define the path but we know what it is provided we find the source
let row = $(this.delegateTarget);
let panel = row.closest('[role="tabpanel"]');
let source = panel.attr('id').match(/^ss_quiz_pg_(.*)$/)[1];
path = 'wkof.settings.ss_quiz.ipresets[wkof.settings.ss_quiz.active_ipreset].content.'+source+'.filters.advSearchFilters_advancedSearch.value'
// initialize in case it is not already initialized
let v = $.extend(true, {}, get_value(path));
set_value(path, v)
} else {
throw 'config.path is not defined';
};
let value = $.extend(true, {}, advancedSearchDefaults, get_value(path));
set_value(path, value)
wkof.settings[settingsScriptId] = wkof.settings[settingsScriptId] || {};
wkof.settings[settingsScriptId].advSearch = $.extend(true, {}, advancedSearchDefaults, get_value(path));
let html = '<textarea id="'+areaId+'" rows="2"></textarea>';
let searchTermHovertip = ''+
'List your search terms separated by commas. Latin, hiragana and kanji accepted\n\n'+
'* selects items where "Search In" information is PRESENT *and* NON EMPTY.\n'+
'!* selects items where "Search In" information is ABSENT *or* EMPTY.\n\n'+
'Valid parts of speech are:\n'+
'adjective adverb conjunction counter expression godan verb ichican verb\n'+
'interjection intransitive verb noun numeral prefix pronoun proper noun suffix\n'+
'transitive verb い adjective な adjective の adjective する verb';
let dialogConfig = {
script_id: settingsScriptId,
title: 'Advanced Search',
on_save: on_save,
on_cancel: on_cancel,
on_close: on_close,
no_bkgd: true,
settings: {itemType: {type: 'list', multi: true, label: 'Item Type', path: '@advSearch.itemType',
hover_tip: 'The type of items that must match the search terms.',
default: {radical: true, kanji: true, vocabulary: true, kana_vocabulary: true, trad_rad: true},
content: {radical: 'Radical', kanji: 'Kanji', vocabulary: 'Vocabulary', kana_vocabulary: 'Kana Vocabulary',
trad_rad:'Traditional Radical'},},
exactMatch: {type: 'list', multi: true, label: 'Searches With Exact Match', size: 5, path: '@advSearch.exactMatch',
hover_tip: 'Selected searches requires the whole word matches.\nSubstring match is the default\nPart of Speech always use exact match.\n\nYou must select the search in Search In\nfor this parameter to take effect.',
default: {characters: true, meanings: false, readings: true,
allow: false, block: false,
mMnemonics: false, mHints: false, rMnemonics: false, rHints: false, contextSentences: false,
mNotes: false, rNotes: false, synonyms: false,
Kanjidic2_Meaning: false, Kanjidic2_Onyomi: false,
Kanjidic2_Kunyomi: false, Kanjidic2_Nanori: false},
content: {characters: 'Characters', meanings: 'Meanings', readings: 'Readings',
allow: 'Allow List', block: 'Block list',
mMnemonics: 'Meaning mnemonics', mHints: 'Meaning hints',
rMnemonics: 'Reading mnemonics', rHints: 'Reading hints',
contextSentences: 'Context Sentences',
mNotes: 'Meaning notes', rNotes: 'Reading notes', synonyms: 'User synonyms',
Kanjidic2_Meaning: 'Kanjidict2 Meaning', Kanjidic2_Onyomi: 'Kanjidict2 Onyomi',
Kanjidic2_Kunyomi: 'Kanjidict2 Kunyomi', Kanjidic2_Nanori: 'Kanjidict2 Nanori'},},
acceptedAnswer: {type: 'checkbox', label: 'Only Accepted Answers', default: true, path: '@advSearch.acceptedAnswer',
hover_tip: 'Match only meanings and readings marked\nas accepted answers by Wanikani.\nUnchecked, matches both accepted\nand unaccepted answers.',},
searchIn: {type: 'list', multi: true, label: 'Search In', size: 6, path: '@advSearch.searchIn',
hover_tip: 'Where to search to find a search term match.\nAny reading applies to both kanji and vocabulary.\nOther readings apply only to kanji.',
default: {characters: true, meanings: true, readings: true,
onyomi: true, kunyomi: true, nanori: true,
pos: false, allow: false, block: false,
mMnemonics: false, mHints: false, rMnemonics: false, rHints: false, contextSentences: false,
mNotes: false, rNotes: false, synonyms: false,
Kanjidic2_Meaning: false, Kanjidic2_Onyomi: false,
Kanjidic2_Kunyomi: false, Kanjidic2_Nanori: false},
content: {characters: 'Characters', meanings: 'Meanings', readings: 'Any Reading',
onyomi: 'Readings Onyomi', kunyomi: 'Readings Kunyomi', nanori: 'Readings Nanori',
pos: 'Part of Speech', allow: 'Allow List', block: 'Block List',
mMnemonics: 'Meaning Mnemonics', mHints: 'Meaning Hints',
rMnemonics: 'Reading Mnemonics', rHints: 'Reading Hints',
contextSentences: 'Context Sentences',
mNotes: 'Meaning Notes', rNotes: 'Reading Notes', synonyms: 'User Synonyms',
Kanjidic2_Meaning: 'Kanjidict2 Meaning', Kanjidic2_Onyomi: 'Kanjidict2 Onyomi',
Kanjidic2_Kunyomi: 'Kanjidict2 Kunyomi', Kanjidic2_Nanori: 'Kanjidict2 Nanori',},},
keisei: {type: 'list', multi: true, label: 'Search Keisei Database', size: 4, path: '@advSearch.keisei',
hover_tip: 'Selected items must have one of the selected Keisei Semantic-Phonetic properties.\n\nThis search criterion is not used if no property is selected.',
default: {phonetic: false, nonPhonetic: false, compound: false,
notCompound: false, obscure: false, notInDB: false},
content: {phonetic: 'Is a Phonetic Mark', nonPhonetic: 'Is Not a Phonetic Mark',
compound: 'Is a Phonetic Compound',
notCompound: 'Not a Phonetic Compound', obscure: 'Obscure or Contested Origin',
notInDB: 'Not in Keisei Database'},},
divider: {type: 'divider'},
searchTerms: {type: 'html', label: 'Search Terms',
html: html,},
},
};
let dialog = new wkof.Settings(dialogConfig);
dialog.open();
// ui issue: do not let the calling dialog be visible
let originalDisplay = $originalDialog.css('display');
$originalDialog.css('display', 'none');
// work around some framework limitations regarding html types
let $searchTerms = $('#'+areaId);
$searchTerms.val(wkof.settings[settingsScriptId].advSearch.searchTerms);
$searchTerms.change(textareaChanged);
let $label = $searchTerms.closest('form').children('.left');
$label.css('width', 'calc(100% - 5px)');
$label.children('label').css('text-align', 'left');
$label.attr('title', searchTermHovertip);
function on_close(){
$originalDialog.css('display', originalDisplay);
if (typeof config.on_close === 'function') config.on_close();
};
function on_save(){
set_value(path, get_value('wkof.settings.'+settingsScriptId+'.advSearch'))
if (typeof config.on_save === 'function') config.on_save();
};
function on_cancel(){
if (typeof config.on_cancel === 'function') config.on_cancel();
};
function textareaChanged(e){
wkof.settings[settingsScriptId].advSearch.searchTerms = $searchTerms.val();
};
};
function prepareAdvancedSearch(filterValueOriginal){
let searchIn = filterValueOriginal.searchIn;
dataRequired.kanjidic2 = (searchIn.Kanjidic2_Meaning || searchIn.Kanjidic2_Onyomi || searchIn.Kanjidic2_Kunyomi || searchIn.Kanjidic2_Nanori);
let keisei = filterValueOriginal.keisei;
dataRequired.keisei = (keisei.phonetic || keisei.nonPhonetic || keisei.compound || keisei.notCompound || keisei.obscure || keisei.notInDB);
return loadMissingData();
};
function prepareFilterValue(filterValueOriginal){
// Don't modify the original because it is a pointer to the filter settings - modifying it will accumulate trash in the settings
var filterValue = $.extend({}, filterValueOriginal);
filterValue.hasSearchIn = Object.values(filterValue.searchIn).reduce(((acc,cur) => acc || cur), false);
filterValue.searchIn.keisei = Object.values(filterValue.keisei).reduce(((acc, cur) => acc || cur), false);
filterValue.searchTermsArray = split_list(filterValue.searchTerms);
return filterValue;
};
function advancedSearchFilter(filterValue, item) {
if (item.data === undefined) {
return false;
};
if (!filterValue.itemType[item.object]) return false;
let searchIn = filterValue.searchIn;
let exactMatch = filterValue.exactMatch;
let keisei = filterValue.keisei;
let hasSearchIn = filterValue.hasSearchIn;
let acceptedAnswer = filterValue.acceptedAnswer;
let itemType = item.object;
for (var searchTerm of filterValue.searchTermsArray){
// must match keisei if searched in AND match ANY ONE of the other searched in locations
if (searchIn.keisei){
let result = false;
if (itemType === 'radical'){
if (searchTerm !== none) {
if (keiseiDB.checkPhonetic(keiseiDB.mapWKRadicalToPhon(item.data.slug))) {
if (keisei.phonetic) result = true;
} else {
if (keisei.nonPhonetic) result = true;
};
};
} else if (itemType === 'kanji'){
if (searchTerm !== none) {
let kan = item.data.slug;
if (!keiseiDB.checkKanji(kan)){
if (keisei.notInDB) result = true;
} else if (!keiseiDB.checkPhonetic(kan) && (keiseiDB.getKType(kan) !== keiseiDB.KTypeEnum.comp_phonetic)){
let typeKan = keiseiDB.getKType(kan);
if (keisei.nonPhonetic || keisei.notCompound) {
result = true;
} if (!(typeKan in Object.values(keiseiDB.KTypeEnum))) {
if (keisei.notInDB) result = true;
} else if (typeKan === keiseiDB.KTypeEnum.unknown) {
if (keisei.obscure) result = true;
};
} else {
if (keiseiDB.checkPhonetic(kan)) {
if (keisei.phonetic || keisei.notCompound) result = true;
} else if ((keisei.compound || (keisei.nonPhonetic))){
result = true;
};
};
};
};
if (!result) return false;
if (!hasSearchIn) return result; // if no other location is searched in we are done with the result
};
if (searchIn.characters){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'characters'); return true;};
if (searchTerm !== none) {
if (exactMatch.characters){
if (item.data.characters !== null && item.data.characters === searchTerm) {reportSearchResult(item, searchTerm, 'characters'); return true;};
if (itemType === 'radical' && item.data.slug === searchTerm.replace(' ', '-')) {reportSearchResult(item, searchTerm, 'characters'); return true;};
} else {
if (item.data.characters !== null && item.data.characters.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'characters'); return true;};
if (itemType === 'radical' && item.data.slug.indexOf(searchTerm.replace(' ', '-')) >= 0){reportSearchResult(item, searchTerm, 'characters'); return true;};
};
};
};
if (searchIn.meanings) {
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'meanings'); return true;};
if (searchTerm !== none) {
for (var meaning of item.data.meanings){
if (acceptedAnswer && !meaning.accepted_answer) continue;
let term = meaning.meaning.toLowerCase();
if (exactMatch.meanings){
if (searchTerm === term) {reportSearchResult(item, searchTerm, 'meanings'); return true;};
let words = term.split(' ').filter(function(name) {return (name.length > 0);});
for (let word of words) {
if (searchTerm === word) {reportSearchResult(item, searchTerm, 'meanings'); return true;};
};
} else {
if (term.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'meanings'); return true;};
};
};
};
};
if (searchIn.readings){
if (itemType !== 'radical' && itemType !== 'kana_vocabulary'){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'readings'); return true;};
if (exactMatch.readings){
for (let reading of item.data.readings){
if (acceptedAnswer && !reading.accepted_answer) continue;
if (reading.reading === searchTerm && reading.accepted_answer) {reportSearchResult(item, searchTerm, 'readings'); return true;};
};
} else {
for (let reading of item.data.readings){
if (acceptedAnswer && !reading.accepted_answer) continue;
if (reading.reading.indexOf(searchTerm) >= 0 && reading.accepted_answer) {reportSearchResult(item, searchTerm, 'readings'); return true;};
};
};
} else {
if (searchTerm === none) {reportSearchResult(item, searchTerm, 'readings');}
};
};
if (searchIn.onyomi || searchIn.kunyomi || searchIn.nanori){
if (itemType === 'kanji') {
let notSeen = {onyomi: true, kunyomi: true, nanori: true};
let seen = {onyomi: false, kunyomi: false, nanori: false};
if (exactMatch.readings){
for (let reading of item.data.readings){
if (acceptedAnswer && !reading.accepted_answer) continue;
notSeen[reading.type] = false;
seen[reading.type] = true;
if (reading.reading === searchTerm && searchIn[reading.type]) {reportSearchResult(item, searchTerm, reading.type); return true;};
};
} else {
for (let reading of item.data.readings){
if (acceptedAnswer && !reading.accepted_answer) continue;
notSeen[reading.type] = false;
seen[reading.type] = true;
if (reading.reading.indexOf(searchTerm) >= 0 && searchIn[reading.type]) {reportSearchResult(item, searchTerm, reading.type); return true;};
};
};
if (searchTerm === none){
if (searchIn.onyomi && notSeen.onyomi) {reportSearchResult(item, searchTerm, 'onyomi'); return true;};
if (searchIn.kunyomi && notSeen.kunyomi) {reportSearchResult(item, searchTerm, 'kunyomi'); return true;};
if (searchIn.nanori && notSeen.nanori) {reportSearchResult(item, searchTerm, 'nanori'); return true;};
};
if (searchTerm === all){
if (searchIn.onyomi && seen.onyomi) {reportSearchResult(item, searchTerm, 'onyomi'); return true;};
if (searchIn.kunyomi && seen.kunyomi) {reportSearchResult(item, searchTerm, 'kunyomi'); return true;};
if (searchIn.nanori && seen.nanori) {reportSearchResult(item, searchTerm, 'nanori'); return true;};
};
} else {
let reading;
if (searchIn.nanori) reading = 'nanori';
if (searchIn.kunyomi) reading = 'kunyomi';
if (searchIn.onyomi) reading = 'onyomi';
if (searchTerm === none) {reportSearchResult(item, searchTerm, reading); return true;};
};
};
if (searchIn.pos){
if (itemType === 'vocabulary' || itemType === 'kana_vocabulary'){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'part of speech'); return true;};
for (let pos of item.data.parts_of_speech){
if (searchTerm === pos) {reportSearchResult(item, searchTerm, 'part of speech'); return true;};
let words = pos.split(' ').filter(function(name) {return (name.length > 0);});
for (let word of words) {
if (searchTerm === word) {reportSearchResult(item, searchTerm, 'part of speech'); return true;};
};
};
} else {
if (searchTerm === none) {reportSearchResult(item, searchTerm, 'part of speech'); return true;};
};
};
if (searchIn.allow || searchIn.block) {
if (itemType !== 'trad_rad'){
let seenAllow = false;
let seenBlock = false;
for (let list of item.data.auxiliary_meanings){
if (searchIn.allow && list.type === 'whitelist'){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'allow list'); return true;};
seenAllow = true;
if (exactMatch.allow){
if (searchTerm === list.meaning.toLowerCase()) {reportSearchResult(item, searchTerm, 'allow list'); return true;};
let words = list.meaning.toLowerCase().split(' ').filter(function(name) {return (name.length > 0);});
for (let word of words) {
if (searchTerm === word) {reportSearchResult(item, searchTerm, 'allow list'); return true;};
};
} else {
if (list.meaning.toLowerCase().indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'allow list'); return true;};
};
} else if(searchIn.block && list.type === 'blacklist') {
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'block list'); return true;};
seenBlock = true;
if (exactMatch.block){
if (searchTerm === list.meaning.toLowerCase()) {reportSearchResult(item, searchTerm, 'block list'); return true;};
let words = list.meaning.toLowerCase().split(' ').filter(function(name) {return (name.length > 0);});
for (let word of words) {
if (searchTerm === word) {reportSearchResult(item, searchTerm, 'block list'); return true;};
};
} else {
if (list.meaning.toLowerCase().indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'block list'); return true;};
};
};
};
if (searchTerm === none){
if (searchIn.allow && !seenAllow) {reportSearchResult(item, searchTerm, 'allow list'); return true;};
if (searchIn.block && !seenBlock) {reportSearchResult(item, searchTerm, 'block list'); return true;};
};
} else {
if (searchTerm === none){
if (searchIn.allow) {reportSearchResult(item, searchTerm, 'allow list'); return true;};
if (searchIn.block) {reportSearchResult(item, searchTerm, 'block list'); return true;};
};
};
};
if (searchIn.mMnemonics) {
if (item.data.meaning_mnemonic){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'meaning mnemonic'); return true;};
let mnemonic = item.data.meaning_mnemonic.toLowerCase().replace(noHtml, ' ');
if (searchTerm === "onyomi" && mnemonic.indexOf("on'yomi") >= 0) {reportSearchResult(item, searchTerm, 'meaning mnemonic'); return true;};
if (searchTerm === "kunyomi" && mnemonic.indexOf("kun'yomi") >= 0) {reportSearchResult(item, searchTerm, 'meaning mnemonic'); return true;};
if (exactMatch.mMnemonics){
let words = mnemonic.toLowerCase().split(breakTheWords).filter(function(name) {return (name.length > 0);});
for (let word of words) {
if (searchTerm === word) {reportSearchResult(item, searchTerm, 'meaning mnemonic'); return true;};
let subwords = word.split(breakTheSubwords);
if (subwords.length !== 1){
for (let subword of subwords) if (searchTerm === subword) {reportSearchResult(item, searchTerm, 'meaning mnemonic'); return true;};
};
};
} else {
if (mnemonic.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'meaning mnemonic'); return true;};
};
} else {
if (searchTerm === none) {reportSearchResult(item, searchTerm, 'meaning mnemonic'); return true;};
};
};
if (searchIn.mHints){
if (item.data.meaning_hint){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'meaning hint'); return true;};
let hint = item.data.meaning_hint.toLowerCase().replace(noHtml, ' ');
if (searchTerm === "onyomi" && hint.indexOf("on'yomi") >= 0) {reportSearchResult(item, searchTerm, 'meaning hint'); return true;};
if (searchTerm === "kunyomi" && hint.indexOf("kun'yomi") >= 0) {reportSearchResult(item, searchTerm, 'meaning hint'); return true;};
if (exactMatch.mHints){
let words = hint.split(breakTheWords).filter(function(name) {return (name.length > 0);});
for (let word of words) {
if (searchTerm === word) {reportSearchResult(item, searchTerm, 'meaning hint'); return true;};
let subwords = word.split(breakTheSubwords);
if (subwords.length !== 1){
for (let subword of subwords) if (searchTerm === subwords) {reportSearchResult(item, searchTerm, 'meaning hint'); return true;};
}
};
} else {
if (hint.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'meaning hint'); return true;};
};
} else {
if (searchTerm === none) {reportSearchResult(item, searchTerm, 'meaning hint'); return true;};
};
};
if (searchIn.rMnemonics) {
if (item.data.reading_mnemonic){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'reading mnemonic'); return true;};
let mnemonic = item.data.reading_mnemonic.toLowerCase().replace(noHtml, ' ');
if (searchTerm === "onyomi" && mnemonic.indexOf("on'yomi") >= 0) {reportSearchResult(item, searchTerm, 'reading mnemonic'); return true;};
if (searchTerm === "kunyomi" && mnemonic.indexOf("kun'yomi") >= 0) {reportSearchResult(item, searchTerm, 'reading mnemonic'); return true;};
if (exactMatch.rMnemonics){
let words = mnemonic.split(breakTheWords).filter(function(name) {return (name.length > 0);});
for (let word of words) {
if (searchTerm === word) {reportSearchResult(item, searchTerm, 'reading mnemonic'); return true;};
let subwords = word.split(breakTheSubwords);
if (subwords.length !== 1){
for (let subword of subwords) if (searchTerm === subword) {reportSearchResult(item, searchTerm, 'reading mnemonic'); return true;};
}
};
} else {
if (mnemonic.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'reading mnemonic'); return true;};
};
} else {
if (searchTerm === none) {reportSearchResult(item, searchTerm, 'reading mnemonic'); return true;};
};
};
if (searchIn.rHints) {
if (item.data.reading_hint){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'reading hint'); return true;};
let hint = item.data.reading_hint.toLowerCase().replace(noHtml, ' ');
if (searchTerm === "onyomi" && hint.indexOf("on'yomi") >= 0) {reportSearchResult(item, searchTerm, 'reading hint'); return true;};
if (searchTerm === "kunyomi" && hint.indexOf("kun'yomi") >= 0) {reportSearchResult(item, searchTerm, 'reading hint'); return true;};
if (exactMatch.rHints){
let words = hint.split(breakTheWords).filter(function(name) {return (name.length > 0);});
for (let word of words) {
if (searchTerm === word) {reportSearchResult(item, searchTerm, 'reading hint'); return true;};
let subwords = word.split(breakTheSubwords);
if (subwords.length !== 1){
for (let subword of subwords) if (searchTerm === subword) {reportSearchResult(item, searchTerm, 'reading hint'); return true;};
}
};
} else {
if (hint.indexOf(searchTerm) >= 0) {reportSearchResult(item, searchTerm, 'reading hint'); return true;};
};
} else {
if (searchTerm === none) {reportSearchResult(item, searchTerm, 'reading hint'); return true;};
};
};
if (searchIn.contextSentences){
if (item.object === 'vocabulary'){
if (item.data.context_sentences.length !== 0){
if (searchTerm === all) {reportSearchResult(item, searchTerm, 'context sentences'); return true;};
for (let sentences of item.data.context_sentences){
let ja = sentences.ja;
let en = sentences.en;
if (exactMatch.contextSentences){
let words = ja.toLowerCase().split(breakTheWords).filter(function(name) {return (name.length > 0);});
for (let word of words) {