refactor options page

This commit is contained in:
Alex Yatskov 2017-07-16 19:29:43 -07:00
parent 39f1f30dc9
commit a22facec98

View File

@ -21,53 +21,52 @@
* General * General
*/ */
function formRead() { async function formRead() {
return optionsLoad().then(optionsOld => { const optionsOld = await optionsLoad();
const optionsNew = $.extend(true, {}, optionsOld); const optionsNew = $.extend(true, {}, optionsOld);
optionsNew.general.showGuide = $('#show-usage-guide').prop('checked'); optionsNew.general.showGuide = $('#show-usage-guide').prop('checked');
optionsNew.general.audioSource = $('#audio-playback-source').val(); optionsNew.general.audioSource = $('#audio-playback-source').val();
optionsNew.general.audioVolume = parseFloat($('#audio-playback-volume').val()); optionsNew.general.audioVolume = parseFloat($('#audio-playback-volume').val());
optionsNew.general.groupResults = $('#group-terms-results').prop('checked'); optionsNew.general.groupResults = $('#group-terms-results').prop('checked');
optionsNew.general.debugInfo = $('#show-debug-info').prop('checked'); optionsNew.general.debugInfo = $('#show-debug-info').prop('checked');
optionsNew.general.showAdvanced = $('#show-advanced-options').prop('checked'); optionsNew.general.showAdvanced = $('#show-advanced-options').prop('checked');
optionsNew.general.maxResults = parseInt($('#max-displayed-results').val(), 10); optionsNew.general.maxResults = parseInt($('#max-displayed-results').val(), 10);
optionsNew.general.popupWidth = parseInt($('#popup-width').val(), 10); optionsNew.general.popupWidth = parseInt($('#popup-width').val(), 10);
optionsNew.general.popupHeight = parseInt($('#popup-height').val(), 10); optionsNew.general.popupHeight = parseInt($('#popup-height').val(), 10);
optionsNew.general.popupOffset = parseInt($('#popup-offset').val(), 10); optionsNew.general.popupOffset = parseInt($('#popup-offset').val(), 10);
optionsNew.scanning.middleMouse = $('#middle-mouse-button-scan').prop('checked'); optionsNew.scanning.middleMouse = $('#middle-mouse-button-scan').prop('checked');
optionsNew.scanning.selectText = $('#select-matched-text').prop('checked'); optionsNew.scanning.selectText = $('#select-matched-text').prop('checked');
optionsNew.scanning.alphanumeric = $('#search-alphanumeric').prop('checked'); optionsNew.scanning.alphanumeric = $('#search-alphanumeric').prop('checked');
optionsNew.scanning.delay = parseInt($('#scan-delay').val(), 10); optionsNew.scanning.delay = parseInt($('#scan-delay').val(), 10);
optionsNew.scanning.length = parseInt($('#scan-length').val(), 10); optionsNew.scanning.length = parseInt($('#scan-length').val(), 10);
optionsNew.scanning.modifier = $('#scan-modifier-key').val(); optionsNew.scanning.modifier = $('#scan-modifier-key').val();
optionsNew.anki.enable = $('#anki-enable').prop('checked'); optionsNew.anki.enable = $('#anki-enable').prop('checked');
optionsNew.anki.tags = $('#card-tags').val().split(/[,; ]+/); optionsNew.anki.tags = $('#card-tags').val().split(/[,; ]+/);
optionsNew.anki.htmlCards = $('#generate-html-cards').prop('checked'); optionsNew.anki.htmlCards = $('#generate-html-cards').prop('checked');
optionsNew.anki.sentenceExt = parseInt($('#sentence-detection-extent').val(), 10); optionsNew.anki.sentenceExt = parseInt($('#sentence-detection-extent').val(), 10);
optionsNew.anki.server = $('#interface-server').val(); optionsNew.anki.server = $('#interface-server').val();
if (optionsOld.anki.enable && !$('#anki-error').is(':visible')) { if (optionsOld.anki.enable && !$('#anki-error').is(':visible')) {
optionsNew.anki.terms.deck = $('#anki-terms-deck').val(); optionsNew.anki.terms.deck = $('#anki-terms-deck').val();
optionsNew.anki.terms.model = $('#anki-terms-model').val(); optionsNew.anki.terms.model = $('#anki-terms-model').val();
optionsNew.anki.terms.fields = ankiFieldsToDict($('#terms .anki-field-value')); optionsNew.anki.terms.fields = ankiFieldsToDict($('#terms .anki-field-value'));
optionsNew.anki.kanji.deck = $('#anki-kanji-deck').val(); optionsNew.anki.kanji.deck = $('#anki-kanji-deck').val();
optionsNew.anki.kanji.model = $('#anki-kanji-model').val(); optionsNew.anki.kanji.model = $('#anki-kanji-model').val();
optionsNew.anki.kanji.fields = ankiFieldsToDict($('#kanji .anki-field-value')); optionsNew.anki.kanji.fields = ankiFieldsToDict($('#kanji .anki-field-value'));
} }
$('.dict-group').each((index, element) => { $('.dict-group').each((index, element) => {
const dictionary = $(element); const dictionary = $(element);
const title = dictionary.data('title'); const title = dictionary.data('title');
const priority = parseInt(dictionary.find('.dict-priority').val(), 10); const priority = parseInt(dictionary.find('.dict-priority').val(), 10);
const enabled = dictionary.find('.dict-enabled').prop('checked'); const enabled = dictionary.find('.dict-enabled').prop('checked');
optionsNew.dictionaries[title] = {priority, enabled}; optionsNew.dictionaries[title] = {priority, enabled};
});
return {optionsNew, optionsOld};
}); });
return {optionsNew, optionsOld};
} }
function updateVisibility(options) { function updateVisibility(options) {
@ -95,66 +94,84 @@ function updateVisibility(options) {
} }
} }
function onOptionsChanged(e) { async function onOptionsChanged(e) { (async () => {
if (!e.originalEvent && !e.isTrigger) { if (!e.originalEvent && !e.isTrigger) {
return; return;
} }
formRead().then(({optionsNew, optionsOld}) => { try {
return optionsSave(optionsNew).then(() => { ankiErrorShow();
updateVisibility(optionsNew); ankiSpinnerShow(true);
const ankiUpdated = const {optionsNew, optionsOld} = await formRead();
optionsNew.anki.enable !== optionsOld.anki.enable || await optionsSave(optionsNew);
optionsNew.anki.server !== optionsOld.anki.server;
if (ankiUpdated) { updateVisibility(optionsNew);
ankiErrorShow(null);
ankiSpinnerShow(true);
return ankiDeckAndModelPopulate(optionsNew);
}
});
}).catch(ankiErrorShow).then(() => ankiSpinnerShow(false));
}
$(document).ready(() => { const ankiUpdated =
optionsNew.anki.enable !== optionsOld.anki.enable ||
optionsNew.anki.server !== optionsOld.anki.server;
if (ankiUpdated) {
await ankiDeckAndModelPopulate(optionsNew);
}
} catch (e) {
ankiErrorShow(e);
} finally {
ankiSpinnerShow(false);
}
})();}
function onReady() {(async () => {
handlebarsRegister(); handlebarsRegister();
optionsLoad().then(options => { const options = await optionsLoad();
$('#show-usage-guide').prop('checked', options.general.showGuide);
$('#audio-playback-source').val(options.general.audioSource);
$('#audio-playback-volume').val(options.general.audioVolume);
$('#group-terms-results').prop('checked', options.general.groupResults);
$('#show-debug-info').prop('checked', options.general.debugInfo);
$('#show-advanced-options').prop('checked', options.general.showAdvanced);
$('#max-displayed-results').val(options.general.maxResults);
$('#popup-width').val(options.general.popupWidth);
$('#popup-height').val(options.general.popupHeight);
$('#popup-offset').val(options.general.popupOffset);
$('#middle-mouse-button-scan').prop('checked', options.scanning.middleMouse); $('#show-usage-guide').prop('checked', options.general.showGuide);
$('#select-matched-text').prop('checked', options.scanning.selectText); $('#audio-playback-source').val(options.general.audioSource);
$('#search-alphanumeric').prop('checked', options.scanning.alphanumeric); $('#audio-playback-volume').val(options.general.audioVolume);
$('#scan-delay').val(options.scanning.delay); $('#group-terms-results').prop('checked', options.general.groupResults);
$('#scan-length').val(options.scanning.length); $('#show-debug-info').prop('checked', options.general.debugInfo);
$('#scan-modifier-key').val(options.scanning.modifier); $('#show-advanced-options').prop('checked', options.general.showAdvanced);
$('#max-displayed-results').val(options.general.maxResults);
$('#popup-width').val(options.general.popupWidth);
$('#popup-height').val(options.general.popupHeight);
$('#popup-offset').val(options.general.popupOffset);
$('#dict-purge').click(onDictionaryPurge); $('#middle-mouse-button-scan').prop('checked', options.scanning.middleMouse);
$('#dict-file').change(onDictionaryImport); $('#select-matched-text').prop('checked', options.scanning.selectText);
$('#search-alphanumeric').prop('checked', options.scanning.alphanumeric);
$('#scan-delay').val(options.scanning.delay);
$('#scan-length').val(options.scanning.length);
$('#scan-modifier-key').val(options.scanning.modifier);
$('#anki-enable').prop('checked', options.anki.enable); $('#dict-purge').click(onDictionaryPurge);
$('#card-tags').val(options.anki.tags.join(' ')); $('#dict-file').change(onDictionaryImport);
$('#generate-html-cards').prop('checked', options.anki.htmlCards);
$('#sentence-detection-extent').val(options.anki.sentenceExt);
$('#interface-server').val(options.anki.server);
$('input, select').not('.anki-model').change(onOptionsChanged);
$('.anki-model').change(onAnkiModelChanged);
dictionaryGroupsPopulate(options); $('#anki-enable').prop('checked', options.anki.enable);
ankiDeckAndModelPopulate(options); $('#card-tags').val(options.anki.tags.join(' '));
updateVisibility(options); $('#generate-html-cards').prop('checked', options.anki.htmlCards);
}); $('#sentence-detection-extent').val(options.anki.sentenceExt);
}); $('#interface-server').val(options.anki.server);
$('input, select').not('.anki-model').change(onOptionsChanged);
$('.anki-model').change(onAnkiModelChanged);
try {
await dictionaryGroupsPopulate(options);
} catch (e) {
dictionaryErrorShow(e);
}
try {
await ankiDeckAndModelPopulate(options);
} catch (e) {
ankiErrorShow(e);
}
updateVisibility(options);
})();}
$(document).ready(onReady);
/* /*
@ -196,84 +213,91 @@ function dictionaryGroupsSort() {
dictGroups.append(dictGroupChildren); dictGroups.append(dictGroupChildren);
} }
function dictionaryGroupsPopulate(options) { async function dictionaryGroupsPopulate(options) {
dictionaryErrorShow(null);
dictionarySpinnerShow(true);
const dictGroups = $('#dict-groups').empty(); const dictGroups = $('#dict-groups').empty();
const dictWarning = $('#dict-warning').hide(); const dictWarning = $('#dict-warning').hide();
return instDb().getDictionaries().then(rows => { const dictRows = await instDb().getDictionaries();
if (rows.length === 0) { if (dictRows.length === 0) {
dictWarning.show(); dictWarning.show();
} }
for (const row of dictRowsSort(rows, options)) { for (const dictRow of dictRowsSort(dictRows, options)) {
const dictOptions = options.dictionaries[row.title] || {enabled: false, priority: 0}; const dictOptions = options.dictionaries[dictRow.title] || {enabled: false, priority: 0};
const dictHtml = handlebarsRender('dictionary.html', { const dictHtml = handlebarsRender('dictionary.html', {
title: row.title, title: dictRow.title,
version: row.version, version: dictRow.version,
revision: row.revision, revision: dictRow.revision,
priority: dictOptions.priority, priority: dictOptions.priority,
enabled: dictOptions.enabled enabled: dictOptions.enabled
});
dictGroups.append($(dictHtml));
}
updateVisibility(options);
$('.dict-enabled, .dict-priority').change(e => {
dictionaryGroupsSort();
onOptionsChanged(e);
}); });
}).catch(dictionaryErrorShow).then(() => dictionarySpinnerShow(false));
dictGroups.append($(dictHtml));
}
updateVisibility(options);
$('.dict-enabled, .dict-priority').change(e => {
dictionaryGroupsSort();
onOptionsChanged(e);
});
} }
function onDictionaryPurge(e) { async function onDictionaryPurge(e) { (async () => {
e.preventDefault(); e.preventDefault();
dictionaryErrorShow(null);
dictionarySpinnerShow(true);
const dictControls = $('#dict-importer, #dict-groups').hide(); const dictControls = $('#dict-importer, #dict-groups').hide();
const dictProgress = $('#dict-purge-progress').show(); const dictProgress = $('#dict-purge-progress').show();
instDb().purge().catch(dictionaryErrorShow).then(() => { try {
dictionaryErrorShow();
dictionarySpinnerShow(true);
await instDb().purge();
const options = await optionsLoad();
options.dictionaries = {};
await optionsSave(options);
await dictionaryGroupsPopulate(options);
} catch (e) {
dictionaryErrorShow(e);
} finally {
dictionarySpinnerShow(false); dictionarySpinnerShow(false);
dictControls.show(); dictControls.show();
dictProgress.hide(); dictProgress.hide();
return optionsLoad(); }
}).then(options => { })();}
options.dictionaries = {};
optionsSave(options).then(() => dictionaryGroupsPopulate(options));
});
}
function onDictionaryImport(e) {
dictionaryErrorShow(null);
dictionarySpinnerShow(true);
function onDictionaryImport(e) { (async () => {
const dictFile = $('#dict-file'); const dictFile = $('#dict-file');
const dictImporter = $('#dict-importer').hide(); const dictControls = $('#dict-importer').hide();
const dictProgress = $('#dict-import-progress').show(); const dictProgress = $('#dict-import-progress').show();
const setProgress = percent => dictProgress.find('.progress-bar').css('width', `${percent}%`);
const updateProgress = (total, current) => setProgress(current / total * 100.0);
setProgress(0.0); try {
dictionaryErrorShow();
dictionarySpinnerShow(true);
optionsLoad().then(options => { const setProgress = percent => dictProgress.find('.progress-bar').css('width', `${percent}%`);
return instDb().importDictionary(e.target.files[0], updateProgress).then(summary => { const updateProgress = (total, current) => setProgress(current / total * 100.0);
options.dictionaries[summary.title] = {enabled: true, priority: 0}; setProgress(0.0);
return optionsSave(options);
}).then(() => dictionaryGroupsPopulate(options)); const options = await optionsLoad();
}).catch(dictionaryErrorShow).then(() => { const summary = await instDb().importDictionary(e.target.files[0], updateProgress);
dictFile.val(''); options.dictionaries[summary.title] = {enabled: true, priority: 0};
await optionsSave(options);
await dictionaryGroupsPopulate(options);
} catch (e) {
dictionaryErrorShow(e);
} finally {
dictionarySpinnerShow(false); dictionarySpinnerShow(false);
dictFile.val('');
dictControls.show();
dictProgress.hide(); dictProgress.hide();
dictImporter.show(); }
}); })();}
}
/* /*
* Anki * Anki
@ -307,40 +331,38 @@ function ankiFieldsToDict(selection) {
return result; return result;
} }
function ankiDeckAndModelPopulate(options) { async function ankiDeckAndModelPopulate(options) {
ankiErrorShow(null);
ankiSpinnerShow(true);
const ankiFormat = $('#anki-format').hide(); const ankiFormat = $('#anki-format').hide();
return Promise.all([instAnki().getDeckNames(), instAnki().getModelNames()]).then(([deckNames, modelNames]) => {
const ankiDeck = $('.anki-deck');
ankiDeck.find('option').remove();
deckNames.sort().forEach(name => ankiDeck.append($('<option/>', {value: name, text: name})));
$('#anki-terms-deck').val(options.anki.terms.deck); const deckNames = await instAnki().getDeckNames();
$('#anki-kanji-deck').val(options.anki.kanji.deck); const ankiDeck = $('.anki-deck');
ankiDeck.find('option').remove();
deckNames.sort().forEach(name => ankiDeck.append($('<option/>', {value: name, text: name})));
const ankiModel = $('.anki-model'); const modelNames = await instAnki().getModelNames();
ankiModel.find('option').remove(); const ankiModel = $('.anki-model');
modelNames.sort().forEach(name => ankiModel.append($('<option/>', {value: name, text: name}))); ankiModel.find('option').remove();
modelNames.sort().forEach(name => ankiModel.append($('<option/>', {value: name, text: name})));
return Promise.all([ $('#anki-terms-deck').val(options.anki.terms.deck);
ankiFieldsPopulate($('#anki-terms-model').val(options.anki.terms.model), options), await ankiFieldsPopulate($('#anki-terms-model').val(options.anki.terms.model), options);
ankiFieldsPopulate($('#anki-kanji-model').val(options.anki.kanji.model), options)
]); $('#anki-kanji-deck').val(options.anki.kanji.deck);
}).then(() => ankiFormat.show()).catch(ankiErrorShow).then(() => ankiSpinnerShow(false)); await ankiFieldsPopulate($('#anki-kanji-model').val(options.anki.kanji.model), options);
ankiFormat.show();
} }
function ankiFieldsPopulate(element, options) { async function ankiFieldsPopulate(element, options) {
const modelName = element.val();
if (!modelName) {
return;
}
const tab = element.closest('.tab-pane'); const tab = element.closest('.tab-pane');
const tabId = tab.attr('id'); const tabId = tab.attr('id');
const container = tab.find('tbody').empty(); const container = tab.find('tbody').empty();
const modelName = element.val();
if (!modelName) {
return Promise.resolve();
}
const markers = { const markers = {
'terms': [ 'terms': [
'audio', 'audio',
@ -369,37 +391,41 @@ function ankiFieldsPopulate(element, options) {
] ]
}[tabId] || {}; }[tabId] || {};
return instAnki().getModelFieldNames(modelName).then(names => { for (const name of await instAnki().getModelFieldNames(modelName)) {
names.forEach(name => { const value = options.anki[tabId].fields[name] || '';
const value = options.anki[tabId].fields[name] || ''; const html = Handlebars.templates['model.html']({name, markers, value});
const html = Handlebars.templates['model.html']({name, markers, value}); container.append($(html));
container.append($(html)); }
});
tab.find('.anki-field-value').change(onOptionsChanged); tab.find('.anki-field-value').change(onOptionsChanged);
tab.find('.marker-link').click(e => { tab.find('.marker-link').click(e => {
e.preventDefault(); e.preventDefault();
const link = e.target; const link = e.target;
$(link).closest('.input-group').find('.anki-field-value').val(`{${link.text}}`).trigger('change'); $(link).closest('.input-group').find('.anki-field-value').val(`{${link.text}}`).trigger('change');
});
}); });
} }
function onAnkiModelChanged(e) { function onAnkiModelChanged(e) { (async () => {
if (!e.originalEvent) { if (!e.originalEvent) {
return; return;
} }
ankiErrorShow(null); try {
ankiSpinnerShow(true); ankiErrorShow();
ankiSpinnerShow(true);
const element = $(this); const element = $(this);
formRead().then(({optionsNew, optionsOld}) => {
const tab = element.closest('.tab-pane'); const tab = element.closest('.tab-pane');
const tabId = tab.attr('id'); const tabId = tab.attr('id');
const {optionsNew, optionsOld} = await formRead();
optionsNew.anki[tabId].fields = {}; optionsNew.anki[tabId].fields = {};
ankiFieldsPopulate(element, optionsNew).then(() => { await optionsSave(optionsNew);
optionsSave(optionsNew);
}).catch(ankiErrorShow).then(() => ankiSpinnerShow(false)); await ankiFieldsPopulate(element, optionsNew);
}); } catch (e) {
} ankiErrorShow(e);
} finally {
ankiSpinnerShow(false);
}
})();}