-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathoptions.ts
1237 lines (1062 loc) · 37.1 KB
/
options.ts
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
import '../html/options.html.src';
import {
allDataSeries,
allMajorDataSeries,
DataSeries,
DataSeriesState,
MajorDataSeries,
} from '@birchill/hikibiki-data';
import Browser, { browser } from 'webextension-polyfill-ts';
import { Config, DEFAULT_KEY_SETTINGS } from './config';
import { AccentDisplay, PartOfSpeechDisplay } from './content-config';
import { Command, CommandParams, isValidKey } from './commands';
import { CopyKeys, CopyNextKeyStrings } from './copy-keys';
import { dbLanguageMeta, isDbLanguageId } from './db-languages';
import {
DbStateUpdatedMessage,
cancelDbUpdate,
deleteDb,
reportError,
updateDb,
} from './db-listener-messages';
import { translateDoc } from './l10n';
import { getReferenceLabelsForLang, getReferencesForLang } from './refs';
import { isChromium, isEdge, isFirefox, isMac, isSafari } from './ua-utils';
const config = new Config();
function completeForm() {
// UA-specific styles
if (isFirefox()) {
document.documentElement.classList.add('firefox');
}
if (isChromium()) {
document.documentElement.classList.add('chromium');
}
if (isEdge()) {
document.documentElement.classList.add('edge');
}
if (isSafari()) {
document.documentElement.classList.add('safari');
}
// Pop-up
renderPopupStyleSelect();
// Keyboard
configureCommands();
configureHoldToShowKeys();
addPopupKeys();
translateKeys();
// Language
fillInLanguages();
// Kanji
createKanjiReferences();
// l10n
translateDoc();
document.getElementById('highlightText')!.addEventListener('click', (evt) => {
config.noTextHighlight = !(evt.target as HTMLInputElement).checked;
});
document
.getElementById('contextMenuEnable')!
.addEventListener('click', (evt) => {
config.contextMenuEnable = (evt.target as HTMLInputElement).checked;
});
document.getElementById('showPriority')!.addEventListener('click', (evt) => {
config.showPriority = (evt.target as HTMLInputElement).checked;
renderPopupStyleSelect();
});
document.getElementById('showRomaji')!.addEventListener('click', (evt) => {
config.showRomaji = (evt.target as HTMLInputElement).checked;
renderPopupStyleSelect();
});
document
.getElementById('showDefinitions')!
.addEventListener('click', (evt) => {
config.readingOnly = !(evt.target as HTMLInputElement).checked;
renderPopupStyleSelect();
});
document.getElementById('accentDisplay')!.addEventListener('input', (evt) => {
config.accentDisplay = (evt.target as HTMLSelectElement)
.value as AccentDisplay;
renderPopupStyleSelect();
});
document.getElementById('posDisplay')!.addEventListener('input', (evt) => {
config.posDisplay = (evt.target as HTMLSelectElement)
.value as PartOfSpeechDisplay;
renderPopupStyleSelect();
});
document
.getElementById('showKanjiComponents')!
.addEventListener('click', (evt) => {
config.showKanjiComponents = (evt.target as HTMLInputElement).checked;
});
if (browser.management) {
browser.management.getSelf().then((info) => {
if (info.installType === 'development') {
(document.querySelector('.db-admin') as HTMLElement).style.display =
'block';
document
.getElementById('deleteDatabase')!
.addEventListener('click', (evt) => {
if (browserPort) {
browserPort.postMessage(deleteDb());
}
});
}
});
}
}
function renderPopupStyleSelect() {
const popupStyleSelect = document.getElementById('popupstyle-select')!;
empty(popupStyleSelect);
const themes = ['default', 'light', 'blue', 'lightblue', 'black', 'yellow'];
for (const theme of themes) {
const input = document.createElement('input');
input.setAttribute('type', 'radio');
input.setAttribute('name', 'popupStyle');
input.setAttribute('value', theme);
input.setAttribute('id', `popupstyle-${theme}`);
popupStyleSelect.appendChild(input);
input.addEventListener('click', () => {
config.popupStyle = theme;
});
const label = document.createElement('label');
label.setAttribute('for', `popupstyle-${theme}`);
popupStyleSelect.appendChild(label);
// The default theme alternates between light and dark so we need to
// generate two popup previews and overlay them.
if (theme === 'default') {
const popupPreviewContainer = document.createElement('div');
popupPreviewContainer.classList.add('overlay');
popupPreviewContainer.appendChild(renderPopupPreview('light'));
popupPreviewContainer.appendChild(renderPopupPreview('black'));
label.appendChild(popupPreviewContainer);
} else {
label.appendChild(renderPopupPreview(theme));
}
}
}
function renderPopupPreview(theme: string): HTMLElement {
const popupPreview = document.createElement('div');
popupPreview.classList.add('popup-preview');
popupPreview.classList.add('window');
popupPreview.classList.add(`-${theme}`);
const entry = document.createElement('div');
entry.classList.add('entry');
popupPreview.appendChild(entry);
const headingDiv = document.createElement('div');
entry.append(headingDiv);
const spanKanji = document.createElement('span');
spanKanji.classList.add('w-kanji');
spanKanji.textContent = '理解';
if (config.showPriority) {
spanKanji.append(renderStar());
}
headingDiv.appendChild(spanKanji);
const spanKana = document.createElement('span');
spanKana.classList.add('w-kana');
switch (config.accentDisplay) {
case 'downstep':
spanKana.textContent = 'りꜜかい';
break;
case 'binary':
{
const spanWrapper = document.createElement('span');
spanWrapper.classList.add('w-binary');
const spanRi = document.createElement('span');
spanRi.classList.add('h-l');
spanRi.textContent = 'り';
spanWrapper.append(spanRi);
const spanKai = document.createElement('span');
spanKai.classList.add('l');
spanKai.textContent = 'かい';
spanWrapper.append(spanKai);
spanKana.append(spanWrapper);
}
break;
case 'none':
spanKana.textContent = 'りかい';
break;
}
if (config.showPriority) {
spanKana.append(renderStar());
}
headingDiv.appendChild(spanKana);
if (config.showRomaji) {
const spanRomaji = document.createElement('span');
spanRomaji.classList.add('w-romaji');
spanRomaji.textContent = 'rikai';
headingDiv.appendChild(spanRomaji);
}
if (!config.readingOnly) {
const spanDef = document.createElement('span');
if (config.posDisplay !== 'none') {
const posSpan = document.createElement('span');
posSpan.classList.add('w-pos', 'tag');
switch (config.posDisplay) {
case 'expl':
posSpan.append(
['n', 'vs']
.map((pos) => browser.i18n.getMessage(`pos_label_${pos}`) || pos)
.join(', ')
);
break;
case 'code':
posSpan.append('n, vs');
break;
}
spanDef.append(posSpan);
}
spanDef.classList.add('w-def');
spanDef.append('understanding');
entry.appendChild(spanDef);
}
return popupPreview;
}
const SVG_NS = 'http://www.w3.org/2000/svg';
function renderStar(): SVGElement {
const svg = document.createElementNS(SVG_NS, 'svg');
svg.classList.add('svgicon');
svg.style.opacity = '0.5';
svg.setAttribute('viewBox', '0 0 98.6 93.2');
const path = document.createElementNS(SVG_NS, 'path');
path.setAttribute(
'd',
'M98 34a4 4 0 00-3-1l-30-4L53 2a4 4 0 00-7 0L33 29 4 33a4 4 0 00-3 6l22 20-6 29a4 4 0 004 5 4 4 0 002 0l26-15 26 15a4 4 0 002 0 4 4 0 004-4 4 4 0 000-1l-6-29 22-20a4 4 0 001-5z'
);
svg.append(path);
return svg;
}
function configureCommands() {
// Disable any controls associated with configuring browser.commands if the
// necessary APIs are not available.
const canConfigureCommands =
browser.commands &&
typeof browser.commands.update === 'function' &&
typeof browser.commands.reset === 'function';
const browserCommandControls =
document.querySelectorAll('.key.command input');
for (const control of browserCommandControls) {
(control as HTMLInputElement).disabled = !canConfigureCommands;
}
const explanationBlock = document.getElementById(
'browser-commands-alternative'
) as HTMLDivElement;
explanationBlock.style.display = canConfigureCommands ? 'none' : 'revert';
if (!canConfigureCommands) {
if (isEdge()) {
explanationBlock.textContent = browser.i18n.getMessage(
'options_browser_commands_no_toggle_key_edge'
);
} else if (isChromium()) {
explanationBlock.textContent = browser.i18n.getMessage(
'options_browser_commands_no_toggle_key_chrome'
);
} else {
explanationBlock.textContent = browser.i18n.getMessage(
'options_browser_commands_no_toggle_key'
);
}
return;
}
const getFormToggleKeyValue = (): Command => {
const getControl = (part: string): HTMLInputElement | null => {
return document.getElementById(
`toggle-${part}`
) as HTMLInputElement | null;
};
const params: CommandParams = {
alt: getControl('alt')?.checked,
ctrl: getControl('ctrl')?.checked,
macCtrl: getControl('macctrl')?.checked,
shift: getControl('shift')?.checked,
key: getControl('key')?.value || '',
};
return Command.fromParams(params);
};
const updateToggleKey = async () => {
try {
const shortcut = getFormToggleKeyValue();
await browser.commands.update({
name: '_execute_browser_action',
shortcut: shortcut.toString(),
});
setToggleKeyWarningState('ok');
} catch (e) {
setToggleKeyWarningState('error', e.message);
}
};
const toggleKeyCheckboxes = document.querySelectorAll(
'.command input[type=checkbox][id^=toggle-]'
);
for (const checkbox of toggleKeyCheckboxes) {
checkbox.addEventListener('click', updateToggleKey);
}
const toggleKeyTextbox = document.getElementById(
'toggle-key'
) as HTMLInputElement;
toggleKeyTextbox.addEventListener('keydown', (evt) => {
let key = evt.key;
if (evt.key.length === 1) {
key = key.toUpperCase();
}
if (!isValidKey(key)) {
// Most printable keys are one character in length so make sure we don't
// allow the default action of adding them to the text input. For other
// keys we don't handle though (e.g. Tab) we probably want to allow the
// default action.
if (evt.key.length === 1) {
evt.preventDefault();
}
return;
}
toggleKeyTextbox.value = key;
evt.preventDefault();
updateToggleKey();
});
toggleKeyTextbox.addEventListener('compositionstart', () => {
toggleKeyTextbox.value = '';
});
toggleKeyTextbox.addEventListener('compositionend', () => {
toggleKeyTextbox.value = toggleKeyTextbox.value.toUpperCase();
updateToggleKey();
});
}
type WarningState = 'ok' | 'warning' | 'error';
function setToggleKeyWarningState(state: WarningState, message?: string) {
const icon = document.getElementById('toggle-key-icon')!;
icon.classList.toggle('-warning', state === 'warning');
icon.classList.toggle('-error', state === 'error');
if (message) {
icon.setAttribute('title', message);
} else {
icon.removeAttribute('title');
}
}
async function getConfiguredToggleKeyValue(): Promise<Command | null> {
const commands = await browser.commands.getAll();
// Safari (14.1.1) has a very broken implementation of
// chrome.commands.getAll(). It returns an object but it has no properties
// and is not iterable.
//
// There's not much we can do in that case so we just hard code the default
// key since Safari also has no way of changing shortcut keys. Hopefully
// Safari will fix chrome.commands.getAll() before or at the same time it
// provides a way of re-assigning shortcut keys.
if (
typeof commands === 'object' &&
typeof commands[Symbol.iterator] !== 'function'
) {
return new Command('R', 'MacCtrl', 'Ctrl');
}
for (const command of commands) {
if (command.name === '_execute_browser_action' && command.shortcut) {
return Command.fromString(command.shortcut);
}
}
return null;
}
function configureHoldToShowKeys() {
const checkboxes = document.querySelectorAll(
'.holdtoshowkeys input[type=checkbox][id^=show-]'
);
const getHoldToShowKeysValue = (): string | null => {
const parts: Array<string> = [];
for (const checkbox of checkboxes) {
if ((checkbox as HTMLInputElement).checked) {
parts.push((checkbox as HTMLInputElement).value);
}
}
if (!parts.length) {
return null;
}
return parts.join('+');
};
for (const checkbox of checkboxes) {
checkbox.addEventListener('click', () => {
config.holdToShowKeys = getHoldToShowKeysValue();
});
}
}
function addPopupKeys() {
const grid = document.getElementById('key-grid')!;
for (const setting of DEFAULT_KEY_SETTINGS) {
// Don't show the copy entry if the clipboard API is not available
if (
setting.name === 'startCopy' &&
(!navigator.clipboard ||
typeof navigator.clipboard.writeText !== 'function')
) {
continue;
}
const keyBlock = document.createElement('div');
keyBlock.classList.add('key');
keyBlock.classList.add('browser-style');
for (const key of setting.keys) {
const keyInput = document.createElement('input');
keyInput.setAttribute('type', 'checkbox');
keyInput.setAttribute('id', `key-${setting.name}-${key}`);
keyInput.setAttribute('name', `key-${setting.name}-${key}`);
keyInput.classList.add(`key-${setting.name}`);
keyInput.dataset.key = key;
keyBlock.append(keyInput);
keyBlock.append(' '); // <-- Mimick the whitespace in the template file
keyInput.addEventListener('click', () => {
const checkedKeys = document.querySelectorAll(
`input[type=checkbox].key-${setting.name}:checked`
);
config.updateKeys({
[setting.name]: Array.from(checkedKeys).map(
(checkbox) => (checkbox as HTMLInputElement).dataset.key
),
});
});
const keyLabel = document.createElement('label');
keyLabel.setAttribute('for', `key-${setting.name}-${key}`);
// We need to add an extra span inside in order to be able to get
// consistent layout when using older versions of extensions.css that put
// the checkbox in a pseudo.
if (setting.name === 'movePopupDownOrUp') {
const [down, up] = key.split(',', 2);
{
const downSpan = document.createElement('span');
downSpan.classList.add('key-box');
downSpan.textContent = down;
keyLabel.append(downSpan);
}
{
const orSpan = document.createElement('span');
orSpan.classList.add('or');
orSpan.textContent = '/';
keyLabel.append(orSpan);
}
{
const upSpan = document.createElement('span');
upSpan.classList.add('key-box');
upSpan.textContent = up;
keyLabel.append(upSpan);
}
} else {
const keyLabelSpan = document.createElement('span');
keyLabelSpan.classList.add('key-box');
keyLabelSpan.textContent = key;
keyLabel.append(keyLabelSpan);
}
keyBlock.append(keyLabel);
}
grid.append(keyBlock);
const keyDescription = document.createElement('div');
keyDescription.classList.add('key-description');
keyDescription.textContent = browser.i18n.getMessage(setting.l10nKey);
// Copy keys has an extended description.
if (setting.name === 'startCopy') {
const copyKeyList = document.createElement('ul');
copyKeyList.classList.add('key-list');
const copyKeys: Array<{
key: string;
l10nKey: string;
}> = CopyKeys.map(({ key, optionsString }) => ({
key,
l10nKey: optionsString,
}));
copyKeys.push({
// We just show the first key here. This matches what we show in the
// pop-up too.
key: setting.keys[0],
l10nKey: CopyNextKeyStrings.optionsString,
});
for (const copyKey of copyKeys) {
const item = document.createElement('li');
item.classList.add('key');
const keyLabel = document.createElement('label');
const keySpan = document.createElement('span');
keySpan.classList.add('key-box');
keySpan.append(copyKey.key);
keyLabel.append(keySpan);
item.append(keyLabel);
item.append(browser.i18n.getMessage(copyKey.l10nKey));
copyKeyList.appendChild(item);
}
keyDescription.appendChild(copyKeyList);
}
grid.appendChild(keyDescription);
}
}
function translateKeys() {
const mac = isMac();
// Hide MacCtrl key if we're not on Mac
const macCtrlInput = document.getElementById(
'toggle-macctrl'
) as HTMLInputElement | null;
const labels = macCtrlInput?.labels ? Array.from(macCtrlInput.labels) : [];
if (macCtrlInput) {
macCtrlInput.style.display = mac ? 'revert' : 'none';
}
for (const label of labels) {
label.style.display = mac ? 'revert' : 'none';
}
if (!mac) {
return;
}
const keyLabels = document.querySelectorAll<HTMLSpanElement>(
'.key > label > span'
);
for (const label of keyLabels) {
// Look for a special key on the label saying what it really is.
//
// We need to do this because we have an odd situation where the 'commands'
// manifest.json property treats 'Ctrl' as 'Command' but in all other cases
// where we see 'Ctrl', it should actually be 'Control'.
//
// So to cover this, we stick data-mac="Command" on any labels that map to
// 'commands'.
const labelText = label.dataset['mac'] || label.textContent;
if (labelText === 'Command') {
label.textContent = '⌘';
} else if (labelText === 'Ctrl') {
label.textContent = 'Control';
} else if (labelText === 'Alt') {
label.textContent = '⌥';
}
}
}
function fillInLanguages() {
const select = document.querySelector('select#lang') as HTMLSelectElement;
for (let [id, data] of dbLanguageMeta) {
let label = data.name;
if (data.hasWords && !data.hasKanji) {
label += browser.i18n.getMessage('options_lang_words_only');
} else if (!data.hasWords && data.hasKanji) {
label += browser.i18n.getMessage('options_lang_kanji_only');
}
const option = document.createElement('option');
option.value = id;
option.append(label);
select.append(option);
}
select.addEventListener('change', () => {
if (!isDbLanguageId(select.value)) {
const msg = `Got unexpected language code: ${select.value}`;
if (browserPort) {
browserPort.postMessage(reportError(msg));
}
console.error(msg);
return;
}
config.dictLang = select.value;
});
}
function createKanjiReferences() {
const container = document.getElementById(
'kanji-reference-list'
) as HTMLDivElement;
// Remove any non-static entries
for (const child of Array.from(container.children)) {
if (!child.classList.contains('static')) {
child.remove();
}
}
const referenceNames = getReferenceLabelsForLang(config.dictLang);
for (const { ref, full } of referenceNames) {
const rowDiv = document.createElement('div');
rowDiv.classList.add('browser-style');
rowDiv.classList.add('checkbox-row');
const checkbox = document.createElement('input');
checkbox.setAttribute('type', 'checkbox');
checkbox.setAttribute('id', `ref-${ref}`);
checkbox.setAttribute('name', ref);
checkbox.addEventListener('click', (evt) => {
config.updateKanjiReferences({
[ref]: (evt.target as HTMLInputElement).checked,
});
});
rowDiv.append(checkbox);
const label = document.createElement('label');
label.setAttribute('for', `ref-${ref}`);
label.textContent = full;
rowDiv.append(label);
container.append(rowDiv);
}
// We want to match the arrangement of references when they are displayed,
// that is, in a vertically flowing grid. See comments where we generate the
// popup styles for more explanation.
//
// We need to add 1 to the number of references, however, to accommodate the
// "Kanji components" item.
container.style.gridTemplateRows = `repeat(${Math.ceil(
(referenceNames.length + 1) / 2
)}, minmax(min-content, max-content))`;
}
function fillVals() {
const optform = document.getElementById('optform') as HTMLFormElement;
optform.showPriority.checked = config.showPriority;
optform.showRomaji.checked = config.showRomaji;
optform.showDefinitions.checked = !config.readingOnly;
optform.accentDisplay.value = config.accentDisplay;
optform.posDisplay.value = config.posDisplay;
optform.highlightText.checked = !config.noTextHighlight;
optform.contextMenuEnable.checked = config.contextMenuEnable;
optform.showKanjiComponents.checked = config.showKanjiComponents;
optform.popupStyle.value = config.popupStyle;
getConfiguredToggleKeyValue()
.then((toggleCommand) => {
const getToggleControl = (part: string): HTMLInputElement =>
document.getElementById(`toggle-${part}`) as HTMLInputElement;
getToggleControl('alt').checked = !!toggleCommand?.alt;
getToggleControl('ctrl').checked = !!toggleCommand?.ctrl;
getToggleControl('shift').checked = !!toggleCommand?.shift;
if (getToggleControl('macctrl')) {
getToggleControl('macctrl').checked = !!toggleCommand?.macCtrl;
}
getToggleControl('key').value = toggleCommand?.key || '';
})
.catch((e) => {
console.error(e);
if (browserPort) {
browserPort.postMessage(reportError(e.message));
}
});
// Note that this setting is hidden in active-tab only mode
const holdKeyParts: Array<string> =
typeof config.holdToShowKeys === 'string'
? config.holdToShowKeys.split('+')
: [];
const holdKeyCheckboxes = document.querySelectorAll(
'.holdtoshowkeys input[type=checkbox][id^=show-]'
);
for (const checkbox of holdKeyCheckboxes) {
(checkbox as HTMLInputElement).checked = holdKeyParts.includes(
(checkbox as HTMLInputElement).value
);
}
for (const [setting, keys] of Object.entries(config.keys)) {
const checkboxes = document.querySelectorAll<HTMLInputElement>(
`input[type=checkbox].key-${setting}`
);
for (const checkbox of checkboxes) {
checkbox.checked =
!!checkbox.dataset.key && keys.includes(checkbox.dataset.key);
}
}
const langSelect = document.querySelector('select#lang') as HTMLSelectElement;
const langOptions = langSelect.querySelectorAll('option');
const dictLang = config.dictLang;
for (const option of langOptions) {
option.selected = option.value === dictLang;
}
const enabledReferences = new Set(config.kanjiReferences);
for (const ref of getReferencesForLang(config.dictLang)) {
const checkbox = document.getElementById(`ref-${ref}`) as HTMLInputElement;
if (checkbox) {
checkbox.checked = enabledReferences.has(ref);
}
}
}
let browserPort: Browser.Runtime.Port | undefined;
function isDbStateUpdatedMessage(evt: unknown): evt is DbStateUpdatedMessage {
return (
typeof evt === 'object' &&
typeof (evt as any).type === 'string' &&
(evt as any).type === 'dbstateupdated'
);
}
function updateFormFromConfig() {
// If the language changes, the set of references we should show might also
// change. We need to do this before calling `fillVals` since that will take
// care of ticking the right boxes.
createKanjiReferences();
fillVals();
}
window.onload = async () => {
await config.ready;
completeForm();
fillVals();
config.addChangeListener(updateFormFromConfig);
// Listen to changes to the database.
browserPort = browser.runtime.connect(undefined, { name: 'options' });
browserPort.onMessage.addListener((evt: unknown) => {
if (isDbStateUpdatedMessage(evt)) {
// For Runtime.Port.postMessage Chrome appears to serialize objects using
// JSON serialization (not structured cloned). As a result, any Date
// objects will be transformed into strings.
//
// Ideally we'd introduce a new type for these deserialized objects that
// converts `Date` to `Date | string` but that is likely to take a full
// day of TypeScript wrestling so instead we just manually reach into
// this object and convert the fields known to possibly contain dates
// into dates.
if (typeof evt.state.updateState.lastCheck === 'string') {
evt.state.updateState.lastCheck = new Date(
evt.state.updateState.lastCheck
);
}
if (typeof (evt.state.updateState as any).nextRetry === 'string') {
(evt.state.updateState as any).nextRetry = new Date(
(evt.state.updateState as any).nextRetry
);
}
updateDatabaseSummary(evt);
}
});
};
window.onunload = () => {
config.removeChangeListener(updateFormFromConfig);
if (browserPort) {
browserPort.disconnect();
browserPort = undefined;
}
};
function updateDatabaseSummary(evt: DbStateUpdatedMessage) {
updateDatabaseBlurb(evt);
updateDatabaseStatus(evt);
}
function updateDatabaseBlurb(evt: DbStateUpdatedMessage) {
const blurb = document.querySelector('.db-summary-blurb')!;
empty(blurb);
const attribution = browser.i18n.getMessage('options_data_source');
blurb.append(
linkify(attribution, [
{
keyword: 'JMdict/EDICT',
href: 'https://www.edrdg.org/wiki/index.php/JMdict-EDICT_Dictionary_Project',
},
{
keyword: 'KANJIDIC',
href: 'https://www.edrdg.org/wiki/index.php/KANJIDIC_Project',
},
{
keyword: 'JMnedict/ENAMDICT',
href: 'https://www.edrdg.org/enamdict/enamdict_doc.html',
},
])
);
const license = browser.i18n.getMessage('options_edrdg_license');
const licenseKeyword = browser.i18n.getMessage(
'options_edrdg_license_keyword'
);
blurb.append(
linkify(license, [
{
keyword: 'Electronic Dictionary Research and Development Group',
href: 'https://www.edrdg.org/',
},
{
keyword: licenseKeyword,
href: 'https://www.edrdg.org/edrdg/licence.html',
},
])
);
const accentAttribution = browser.i18n.getMessage(
'options_accent_data_source'
);
const accentPara = document.createElement('p');
accentPara.append(accentAttribution);
blurb.append(accentPara);
}
function updateDatabaseStatus(evt: DbStateUpdatedMessage) {
const { updateState } = evt.state;
const statusElem = document.querySelector('.db-summary-status')!;
empty(statusElem);
statusElem.classList.remove('-error');
statusElem.classList.remove('-warning');
// Fill out the info part
switch (updateState.state) {
case 'idle':
updateIdleStateSummary(evt, statusElem);
break;
case 'checking': {
const infoDiv = document.createElement('div');
infoDiv.classList.add('db-summary-info');
infoDiv.append(browser.i18n.getMessage('options_checking_for_updates'));
statusElem.append(infoDiv);
break;
}
case 'downloading':
case 'updatingdb': {
const infoDiv = document.createElement('div');
infoDiv.classList.add('db-summary-info');
const progressElem = document.createElement('progress');
progressElem.classList.add('progress');
progressElem.max = 100;
progressElem.value = updateState.progress * 100;
progressElem.id = 'update-progress';
infoDiv.append(progressElem);
const labelElem = document.createElement('label');
labelElem.classList.add('label');
labelElem.htmlFor = 'update-progress';
const labels: { [series in DataSeries]: string } = {
kanji: 'options_kanji_data_name',
radicals: 'options_bushu_data_name',
names: 'options_name_data_name',
words: 'options_words_data_name',
};
const dbLabel = browser.i18n.getMessage(labels[updateState.series]);
const { major, minor, patch } = updateState.downloadVersion;
const versionString = `${major}.${minor}.${patch}`;
const progressAsPercent = Math.round(updateState.progress * 100);
const key =
updateState.state === 'downloading'
? 'options_downloading_data'
: 'options_updating_data';
labelElem.textContent = browser.i18n.getMessage(key, [
dbLabel,
versionString,
String(progressAsPercent),
]);
infoDiv.append(labelElem);
statusElem.append(infoDiv);
break;
}
}
// Add the action button info if any
const buttonDiv = document.createElement('div');
buttonDiv.classList.add('db-summary-button');
switch (updateState.state) {
case 'idle': {
// We should probably skip this when we are offline, but for now it
// doesn't really matter.
const updateButton = document.createElement('button');
updateButton.classList.add('browser-style');
updateButton.setAttribute('type', 'button');
const isUnavailable = allDataSeries.some(
(series) => evt.state[series].state === DataSeriesState.Unavailable
);
updateButton.textContent = browser.i18n.getMessage(
updateState.state === 'idle' && !isUnavailable
? 'options_update_check_button_label'
: 'options_update_retry_button_label'
);
updateButton.addEventListener('click', triggerDatabaseUpdate);
buttonDiv.append(updateButton);
if (updateState.lastCheck) {
const lastCheckDiv = document.createElement('div');
lastCheckDiv.classList.add('last-check');
const lastCheckString = browser.i18n.getMessage(
'options_last_database_check',
formatDate(updateState.lastCheck)
);
lastCheckDiv.append(lastCheckString);
buttonDiv.append(lastCheckDiv);
}
break;
}
case 'checking':
case 'downloading':
case 'updatingdb': {
const cancelButton = document.createElement('button');
cancelButton.classList.add('browser-style');
cancelButton.setAttribute('type', 'button');
cancelButton.textContent = browser.i18n.getMessage(
'options_cancel_update_button_label'
);
cancelButton.addEventListener('click', cancelDatabaseUpdate);
buttonDiv.append(cancelButton);
break;
}
}
statusElem.append(buttonDiv);
}
async function updateIdleStateSummary(
evt: DbStateUpdatedMessage,
statusElem: Element
) {