diff --git a/README.md b/README.md index e79824b8..1ed2bb77 100644 --- a/README.md +++ b/README.md @@ -229,6 +229,7 @@ exact versions used for distribution. * Dexie: [homepage](http://dexie.org/) - [snapshot](https://github.com/dfahlander/Dexie.js/archive/v2.0.0-beta.10.zip) * Handlebars: [homepage](http://handlebarsjs.com/) - [snapshot](http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars.min-714a4c4.js) * JQuery: [homepage](https://blog.jquery.com/) - [snapshot](https://code.jquery.com/jquery-3.2.1.min.js) +* JSZip: [homepage](http://stuk.github.io/jszip/) - [snapshot](https://raw.githubusercontent.com/Stuk/jszip/de7f52fbcba485737bef7923a83f0fad92d9f5bc/dist/jszip.min.js) * WanaKana: [homepage](http://wanakana.com/) - [snapshot](https://raw.githubusercontent.com/WaniKani/WanaKana/f2152985f5f2953d74edfe1b6a78e0e329a7cdfb/lib/wanakana.min.js) ## Frequently Asked Questions ## @@ -288,4 +289,16 @@ exact versions used for distribution. ## License ## -GPL +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + diff --git a/ext/bg/background.html b/ext/bg/background.html index 4410c249..97b20f46 100644 --- a/ext/bg/background.html +++ b/ext/bg/background.html @@ -4,18 +4,25 @@ - - + - - - - - + + + + + + + + + + - + + + + diff --git a/ext/bg/popup.html b/ext/bg/context.html similarity index 90% rename from ext/bg/popup.html rename to ext/bg/context.html index dec52795..8a72acc7 100644 --- a/ext/bg/popup.html +++ b/ext/bg/context.html @@ -27,10 +27,14 @@

+ - + + + - + + diff --git a/ext/bg/js/anki-connect.js b/ext/bg/js/anki-connect.js deleted file mode 100644 index 9759c8f5..00000000 --- a/ext/bg/js/anki-connect.js +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (C) 2016 Alex Yatskov - * Author: Alex Yatskov - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -class AnkiConnect { - constructor(server) { - this.server = server; - this.asyncPools = {}; - this.localVersion = 2; - this.remoteVersion = null; - } - - addNote(note) { - return this.checkVersion().then(() => this.ankiInvoke('addNote', {note}, null)); - } - - canAddNotes(notes) { - return this.checkVersion().then(() => this.ankiInvoke('canAddNotes', {notes}, 'notes')); - } - - getDeckNames() { - return this.checkVersion().then(() => this.ankiInvoke('deckNames', {}, null)); - } - - getModelNames() { - return this.checkVersion().then(() => this.ankiInvoke('modelNames', {}, null)); - } - - getModelFieldNames(modelName) { - return this.checkVersion().then(() => this.ankiInvoke('modelFieldNames', {modelName}, null)); - } - - checkVersion() { - if (this.localVersion === this.remoteVersion) { - return Promise.resolve(true); - } - - return this.ankiInvoke('version', {}, null).then(version => { - this.remoteVersion = version; - if (this.remoteVersion < this.localVersion) { - return Promise.reject('extension and plugin versions incompatible'); - } - }); - } - - ankiInvoke(action, params, pool) { - return new Promise((resolve, reject) => { - if (pool !== null && this.asyncPools.hasOwnProperty(pool)) { - this.asyncPools[pool].abort(); - } - - const xhr = new XMLHttpRequest(); - xhr.addEventListener('loadend', () => { - if (pool !== null) { - delete this.asyncPools[pool]; - } - - if (xhr.responseText) { - resolve(JSON.parse(xhr.responseText)); - } else { - reject('unable to connect to plugin'); - } - }); - - xhr.open('POST', this.server); - xhr.send(JSON.stringify({action, params})); - }); - } -} diff --git a/ext/bg/js/anki.js b/ext/bg/js/anki.js new file mode 100644 index 00000000..c327969f --- /dev/null +++ b/ext/bg/js/anki.js @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2016 Alex Yatskov + * Author: Alex Yatskov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +/* + * AnkiConnect + */ + +class AnkiConnect { + constructor(server) { + this.server = server; + this.localVersion = 2; + this.remoteVersion = 0; + } + + async addNote(note) { + await this.checkVersion(); + return await this.ankiInvoke('addNote', {note}); + } + + async canAddNotes(notes) { + await this.checkVersion(); + return await this.ankiInvoke('canAddNotes', {notes}); + } + + async getDeckNames() { + await this.checkVersion(); + return await this.ankiInvoke('deckNames'); + } + + async getModelNames() { + await this.checkVersion(); + return await this.ankiInvoke('modelNames'); + } + + async getModelFieldNames(modelName) { + await this.checkVersion(); + return await this.ankiInvoke('modelFieldNames', {modelName}); + } + + async guiBrowse(query) { + await this.checkVersion(); + return await this.ankiInvoke('guiBrowse', {query}); + } + + async checkVersion() { + if (this.remoteVersion < this.localVersion) { + this.remoteVersion = await this.ankiInvoke('version'); + if (this.remoteVersion < this.localVersion) { + throw 'extension and plugin versions incompatible'; + } + } + } + + ankiInvoke(action, params) { + return requestJson(this.server, 'POST', {action, params, version: this.localVersion}); + } +} + + +/* + * AnkiNull + */ + +class AnkiNull { + async addNote(note) { + return null; + } + + async canAddNotes(notes) { + return []; + } + + async getDeckNames() { + return []; + } + + async getModelNames() { + return []; + } + + async getModelFieldNames(modelName) { + return []; + } + + async guiBrowse(query) { + return []; + } +} diff --git a/ext/bg/js/api.js b/ext/bg/js/api.js new file mode 100644 index 00000000..2afe82a0 --- /dev/null +++ b/ext/bg/js/api.js @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2016-2017 Alex Yatskov + * Author: Alex Yatskov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +async function apiOptionsSet(options) { + utilBackend().onOptionsUpdated(options); +} + +async function apiOptionsGet() { + return utilBackend().options; +} + +async function apiTermsFind(text) { + const options = utilBackend().options; + const translator = utilBackend().translator; + + const searcher = options.general.groupResults ? + translator.findTermsGrouped.bind(translator) : + translator.findTerms.bind(translator); + + const {definitions, length} = await searcher( + text, + dictEnabledSet(options), + options.scanning.alphanumeric + ); + + return { + length, + definitions: definitions.slice(0, options.general.maxResults) + }; +} + +async function apiKanjiFind(text) { + const options = utilBackend().options; + const definitions = await utilBackend().translator.findKanji(text, dictEnabledSet(options)); + return definitions.slice(0, options.general.maxResults); +} + +async function apiDefinitionAdd(definition, mode) { + const options = utilBackend().options; + + if (mode !== 'kanji') { + await audioInject( + definition, + options.anki.terms.fields, + options.general.audioSource + ); + } + + return utilBackend().anki.addNote(dictNoteFormat(definition, mode, options)); +} + +async function apiDefinitionsAddable(definitions, modes) { + const notes = []; + for (const definition of definitions) { + for (const mode of modes) { + notes.push(dictNoteFormat(definition, mode, utilBackend().options)); + } + } + + const results = await utilBackend().anki.canAddNotes(notes); + const states = []; + for (let resultBase = 0; resultBase < results.length; resultBase += modes.length) { + const state = {}; + for (let modeOffset = 0; modeOffset < modes.length; ++modeOffset) { + state[modes[modeOffset]] = results[resultBase + modeOffset]; + } + + states.push(state); + } + + return states; +} + +async function apiNoteView(noteId) { + return utilBackend().anki.guiBrowse(`nid:${noteId}`); +} + +async function apiTemplateRender(template, data) { + return handlebarsRender(template, data); +} + +async function apiCommandExec(command) { + const handlers = { + search: () => { + chrome.tabs.create({url: chrome.extension.getURL('/bg/search.html')}); + }, + + help: () => { + chrome.tabs.create({url: 'https://foosoft.net/projects/yomichan/'}); + }, + + options: () => { + chrome.runtime.openOptionsPage(); + }, + + toggle: async () => { + const options = utilBackend().options; + options.general.enable = !options.general.enable; + await optionsSave(options); + await apiOptionsSet(options); + } + }; + + const handler = handlers[command]; + if (handler) { + handler(); + } +} + +async function apiAudioGetUrl(definition, source) { + return audioBuildUrl(definition, source); +} diff --git a/ext/mixed/js/util.js b/ext/bg/js/audio.js similarity index 71% rename from ext/mixed/js/util.js rename to ext/bg/js/audio.js index 5cf62000..0952887e 100644 --- a/ext/mixed/js/util.js +++ b/ext/bg/js/audio.js @@ -17,30 +17,7 @@ */ -/* - * Cloze - */ - -function clozeBuild(sentence, source) { - const result = { - sentence: sentence.text.trim() - }; - - if (source) { - result.prefix = sentence.text.substring(0, sentence.offset).trim(); - result.body = source.trim(); - result.suffix = sentence.text.substring(sentence.offset + source.length).trim(); - } - - return result; -} - - -/* - * Audio - */ - -function audioBuildUrl(definition, mode, cache={}) { +async function audioBuildUrl(definition, mode, cache={}) { if (mode === 'jpod101') { let kana = definition.reading; let kanji = definition.expression; @@ -102,8 +79,36 @@ function audioBuildUrl(definition, mode, cache={}) { } } }); - } else { - return Promise.reject('unsupported audio source'); + } else if (mode === 'jisho') { + return new Promise((resolve, reject) => { + const response = cache[definition.expression]; + if (response) { + resolve(response); + } else { + const xhr = new XMLHttpRequest(); + xhr.open('GET', `http://jisho.org/search/${definition.expression}`); + xhr.addEventListener('error', () => reject('failed to scrape audio data')); + xhr.addEventListener('load', () => { + cache[definition.expression] = xhr.responseText; + resolve(xhr.responseText); + }); + + xhr.send(); + } + }).then(response => { + try { + const dom = new DOMParser().parseFromString(response, 'text/html'); + const audio = dom.getElementById(`audio_${definition.expression}:${definition.reading}`); + if (audio) { + return audio.getElementsByTagName('source').item(0).getAttribute('src'); + } + } catch (e) { + // NOP + } + }); + } + else { + return Promise.resolve(); } } @@ -121,16 +126,7 @@ function audioBuildFilename(definition) { } } -function audioInject(definition, fields, mode) { - if (mode === 'disabled') { - return Promise.resolve(true); - } - - const filename = audioBuildFilename(definition); - if (!filename) { - return Promise.resolve(true); - } - +async function audioInject(definition, fields, mode) { let usesAudio = false; for (const name in fields) { if (fields[name].includes('{audio}')) { @@ -140,11 +136,19 @@ function audioInject(definition, fields, mode) { } if (!usesAudio) { - return Promise.resolve(true); + return true; } - return audioBuildUrl(definition, mode).then(url => { - definition.audio = {url, filename}; + try { + const url = await audioBuildUrl(definition, mode); + const filename = audioBuildFilename(definition); + + if (url && filename) { + definition.audio = {url, filename}; + } + return true; - }).catch(() => false); + } catch (e) { + return false; + } } diff --git a/ext/bg/js/backend.js b/ext/bg/js/backend.js new file mode 100644 index 00000000..6b3acaa9 --- /dev/null +++ b/ext/bg/js/backend.js @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2016-2017 Alex Yatskov + * Author: Alex Yatskov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +class Backend { + constructor() { + this.translator = new Translator(); + this.anki = new AnkiNull(); + this.options = null; + } + + async prepare() { + await this.translator.prepare(); + await apiOptionsSet(await optionsLoad()); + + chrome.commands.onCommand.addListener(this.onCommand.bind(this)); + chrome.runtime.onMessage.addListener(this.onMessage.bind(this)); + + if (this.options.general.showGuide) { + chrome.tabs.create({url: chrome.extension.getURL('/bg/guide.html')}); + } + } + + onOptionsUpdated(options) { + this.options = utilIsolate(options); + + if (!options.general.enable) { + chrome.browserAction.setBadgeBackgroundColor({color: '#555555'}); + chrome.browserAction.setBadgeText({text: 'off'}); + } else if (!dictConfigured(options)) { + chrome.browserAction.setBadgeBackgroundColor({color: '#f0ad4e'}); + chrome.browserAction.setBadgeText({text: '!'}); + } else { + chrome.browserAction.setBadgeText({text: ''}); + } + + if (options.anki.enable) { + this.anki = new AnkiConnect(options.anki.server); + } else { + this.anki = new AnkiNull(); + } + + chrome.tabs.query({}, tabs => { + for (const tab of tabs) { + chrome.tabs.sendMessage(tab.id, {action: 'optionsSet', params: options}, () => null); + } + }); + } + + onCommand(command) { + apiCommandExec(command); + } + + onMessage({action, params}, sender, callback) { + const forward = (promise, callback) => { + return promise.then(result => { + callback({result}); + }).catch(error => { + callback({error}); + }); + }; + + const handlers = { + optionsGet: ({callback}) => { + forward(apiOptionsGet(), callback); + }, + + optionsSet: ({options, callback}) => { + forward(apiOptionsSet(options), callback); + }, + + kanjiFind: ({text, callback}) => { + forward(apiKanjiFind(text), callback); + }, + + termsFind: ({text, callback}) => { + forward(apiTermsFind(text), callback); + }, + + definitionAdd: ({definition, mode, callback}) => { + forward(apiDefinitionAdd(definition, mode), callback); + }, + + definitionsAddable: ({definitions, modes, callback}) => { + forward(apiDefinitionsAddable(definitions, modes), callback); + }, + + noteView: ({noteId}) => { + forward(apiNoteView(noteId), callback); + }, + + templateRender: ({template, data, callback}) => { + forward(apiTemplateRender(template, data), callback); + }, + + commandExec: ({command, callback}) => { + forward(apiCommandExec(command), callback); + }, + + audioGetUrl: ({definition, source, callback}) => { + forward(apiAudioGetUrl(definition, source), callback); + } + }; + + const handler = handlers[action]; + if (handler) { + params.callback = callback; + handler(params); + } + + return true; + } +} + +window.yomichan_backend = new Backend(); +window.yomichan_backend.prepare(); diff --git a/ext/bg/js/popup.js b/ext/bg/js/context.js similarity index 77% rename from ext/bg/js/popup.js rename to ext/bg/js/context.js index 8577dd96..689d6863 100644 --- a/ext/bg/js/popup.js +++ b/ext/bg/js/context.js @@ -17,15 +17,15 @@ */ -$(document).ready(() => { - $('#open-search').click(() => commandExec('search')); - $('#open-options').click(() => commandExec('options')); - $('#open-help').click(() => commandExec('help')); +$(document).ready(utilAsync(() => { + $('#open-search').click(() => apiCommandExec('search')); + $('#open-options').click(() => apiCommandExec('options')); + $('#open-help').click(() => apiCommandExec('help')); optionsLoad().then(options => { const toggle = $('#enable-search'); toggle.prop('checked', options.general.enable).change(); toggle.bootstrapToggle(); - toggle.change(() => commandExec('toggle')); + toggle.change(() => apiCommandExec('toggle')); }); -}); +})); diff --git a/ext/bg/js/database.js b/ext/bg/js/database.js index 70aeb0d7..e00cb7a3 100644 --- a/ext/bg/js/database.js +++ b/ext/bg/js/database.js @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Alex Yatskov + * Copyright (C) 2016-2017 Alex Yatskov * Author: Alex Yatskov * * This program is free software: you can redistribute it and/or modify @@ -20,59 +20,62 @@ class Database { constructor() { this.db = null; - this.dbVersion = 2; - this.tagMetaCache = {}; + this.version = 2; + this.tagCache = {}; } - sanitize() { - const db = new Dexie('dict'); - return db.open().then(() => { + async sanitize() { + try { + const db = new Dexie('dict'); + await db.open(); db.close(); - if (db.verno !== this.dbVersion) { - return db.delete(); + if (db.verno !== this.version) { + await db.delete(); } - }).catch(() => {}); + } catch(e) { + // NOP + } } - prepare() { - if (this.db !== null) { - return Promise.reject('database already initialized'); + async prepare() { + if (this.db) { + throw 'database already initialized'; } - return this.sanitize().then(() => { - this.db = new Dexie('dict'); - this.db.version(this.dbVersion).stores({ - terms: '++id,dictionary,expression,reading', - kanji: '++,dictionary,character', - tagMeta: '++,dictionary', - dictionaries: '++,title,version' - }); + await this.sanitize(); - return this.db.open(); + this.db = new Dexie('dict'); + this.db.version(this.version).stores({ + terms: '++id,dictionary,expression,reading', + kanji: '++,dictionary,character', + tagMeta: '++,dictionary', + dictionaries: '++,title,version' }); + + await this.db.open(); } - purge() { - if (this.db === null) { - return Promise.reject('database not initialized'); + async purge() { + if (!this.db) { + throw 'database not initialized'; } this.db.close(); - return this.db.delete().then(() => { - this.db = null; - this.tagMetaCache = {}; - return this.prepare(); - }); + await this.db.delete(); + this.db = null; + this.tagCache = {}; + + await this.prepare(); } - findTerms(term, dictionaries) { - if (this.db === null) { - return Promise.reject('database not initialized'); + async findTerms(term, titles) { + if (!this.db) { + throw 'database not initialized'; } const results = []; - return this.db.terms.where('expression').equals(term).or('reading').equals(term).each(row => { - if (dictionaries.includes(row.dictionary)) { + await this.db.terms.where('expression').equals(term).or('reading').equals(term).each(row => { + if (titles.includes(row.dictionary)) { results.push({ expression: row.expression, reading: row.reading, @@ -84,25 +87,24 @@ class Database { id: row.id }); } - }).then(() => { - return this.cacheTagMeta(dictionaries); - }).then(() => { - for (const result of results) { - result.tagMeta = this.tagMetaCache[result.dictionary] || {}; - } - - return results; }); + + await this.cacheTagMeta(titles); + for (const result of results) { + result.tagMeta = this.tagCache[result.dictionary] || {}; + } + + return results; } - findKanji(kanji, dictionaries) { - if (this.db === null) { + async findKanji(kanji, titles) { + if (!this.db) { return Promise.reject('database not initialized'); } const results = []; - return this.db.kanji.where('character').equals(kanji).each(row => { - if (dictionaries.includes(row.dictionary)) { + await this.db.kanji.where('character').equals(kanji).each(row => { + if (titles.includes(row.dictionary)) { results.push({ character: row.character, onyomi: dictFieldSplit(row.onyomi), @@ -112,83 +114,79 @@ class Database { dictionary: row.dictionary }); } - }).then(() => { - return this.cacheTagMeta(dictionaries); - }).then(() => { - for (const result of results) { - result.tagMeta = this.tagMetaCache[result.dictionary] || {}; - } - - return results; }); - } - cacheTagMeta(dictionaries) { - if (this.db === null) { - return Promise.reject('database not initialized'); + await this.cacheTagMeta(titles); + for (const result of results) { + result.tagMeta = this.tagCache[result.dictionary] || {}; } - const promises = []; - for (const dictionary of dictionaries) { - if (this.tagMetaCache[dictionary]) { - continue; - } + return results; + } - const tagMeta = {}; - promises.push( - this.db.tagMeta.where('dictionary').equals(dictionary).each(row => { + async cacheTagMeta(titles) { + if (!this.db) { + throw 'database not initialized'; + } + + for (const title of titles) { + if (!this.tagCache[title]) { + const tagMeta = {}; + await this.db.tagMeta.where('dictionary').equals(title).each(row => { tagMeta[row.name] = {category: row.category, notes: row.notes, order: row.order}; - }).then(() => { - this.tagMetaCache[dictionary] = tagMeta; - }) - ); - } + }); - return Promise.all(promises); + this.tagCache[title] = tagMeta; + } + } } - getDictionaries() { - if (this.db === null) { - return Promise.reject('database not initialized'); + async getDictionaries() { + if (this.db) { + return this.db.dictionaries.toArray(); + } else { + throw 'database not initialized'; } - - return this.db.dictionaries.toArray(); } - importDictionary(archive, callback) { - if (this.db === null) { + async importDictionary(archive, callback) { + if (!this.db) { return Promise.reject('database not initialized'); } let summary = null; - const indexLoaded = (title, version, revision, tagMeta, hasTerms, hasKanji) => { + const indexLoaded = async (title, version, revision, tagMeta, hasTerms, hasKanji) => { summary = {title, version, revision, hasTerms, hasKanji}; - return this.db.dictionaries.where('title').equals(title).count().then(count => { - if (count > 0) { - return Promise.reject(`dictionary "${title}" is already imported`); - } - return this.db.dictionaries.add({title, version, revision, hasTerms, hasKanji}).then(() => { - const rows = []; - for (const tag in tagMeta || {}) { - const meta = tagMeta[tag]; - const row = dictTagSanitize({ - name: tag, - category: meta.category, - notes: meta.notes, - order: meta.order, - dictionary: title - }); + const count = await this.db.dictionaries.where('title').equals(title).count(); + if (count > 0) { + throw `dictionary "${title}" is already imported`; + } - rows.push(row); - } + await this.db.dictionaries.add({title, version, revision, hasTerms, hasKanji}); - return this.db.tagMeta.bulkAdd(rows); + const rows = []; + for (const tag in tagMeta || {}) { + const meta = tagMeta[tag]; + const row = dictTagSanitize({ + name: tag, + category: meta.category, + notes: meta.notes, + order: meta.order, + dictionary: title }); - }); + + rows.push(row); + } + + await this.db.tagMeta.bulkAdd(rows); }; - const termsLoaded = (title, entries, total, current) => { + const termsLoaded = async (title, entries, total, current) => { + if (callback) { + callback(total, current); + } + const rows = []; for (const [expression, reading, tags, rules, score, ...glossary] of entries) { rows.push({ @@ -202,14 +200,14 @@ class Database { }); } - return this.db.terms.bulkAdd(rows).then(() => { - if (callback) { - callback(total, current); - } - }); + await this.db.terms.bulkAdd(rows); }; - const kanjiLoaded = (title, entries, total, current) => { + const kanjiLoaded = async (title, entries, total, current) => { + if (callback) { + callback(total, current); + } + const rows = []; for (const [character, onyomi, kunyomi, tags, ...meanings] of entries) { rows.push({ @@ -222,13 +220,56 @@ class Database { }); } - return this.db.kanji.bulkAdd(rows).then(() => { - if (callback) { - callback(total, current); - } - }); + await this.db.kanji.bulkAdd(rows); }; - return zipLoadDb(archive, indexLoaded, termsLoaded, kanjiLoaded).then(() => summary); + await Database.importDictionaryZip(archive, indexLoaded, termsLoaded, kanjiLoaded); + return summary; + } + + static async importDictionaryZip(archive, indexLoaded, termsLoaded, kanjiLoaded) { + const files = (await JSZip.loadAsync(archive)).files; + + const indexFile = files['index.json']; + if (!indexFile) { + throw 'no dictionary index found in archive'; + } + + const index = JSON.parse(await indexFile.async('string')); + if (!index.title || !index.version || !index.revision) { + throw 'unrecognized dictionary format'; + } + + await indexLoaded( + index.title, + index.version, + index.revision, + index.tagMeta || {}, + index.termBanks > 0, + index.kanjiBanks > 0 + ); + + const banksTotal = index.termBanks + index.kanjiBanks; + let banksLoaded = 0; + + for (let i = 1; i <= index.termBanks; ++i) { + const bankFile = files[`term_bank_${i}.json`]; + if (bankFile) { + const bank = JSON.parse(await bankFile.async('string')); + await termsLoaded(index.title, bank, banksTotal, banksLoaded++); + } else { + throw 'missing term bank file'; + } + } + + for (let i = 1; i <= index.kanjiBanks; ++i) { + const bankFile = files[`kanji_bank_${i}.json`]; + if (bankFile) { + const bank = JSON.parse(await bankFile.async('string')); + await kanjiLoaded(index.title, bank, banksTotal, banksLoaded++); + } else { + throw 'missing kanji bank file'; + } + } } } diff --git a/ext/bg/js/deinflector.js b/ext/bg/js/deinflector.js index 6484f953..0abde99d 100644 --- a/ext/bg/js/deinflector.js +++ b/ext/bg/js/deinflector.js @@ -1,5 +1,5 @@ /* - * Copyright (C) 2016 Alex Yatskov + * Copyright (C) 2016-2017 Alex Yatskov * Author: Alex Yatskov * * This program is free software: you can redistribute it and/or modify @@ -26,26 +26,7 @@ class Deinflection { this.children = []; } - deinflect(definer, reasons) { - const define = () => { - return definer(this.term).then(definitions => { - if (this.rules.length === 0) { - this.definitions = definitions; - } else { - for (const rule of this.rules) { - for (const definition of definitions) { - if (definition.rules.includes(rule)) { - this.definitions.push(definition); - } - } - } - } - - return this.definitions.length > 0; - }); - }; - - const promises = []; + async deinflect(definer, reasons) { for (const reason in reasons) { for (const variant of reasons[reason]) { let accept = this.rules.length === 0; @@ -68,20 +49,31 @@ class Deinflection { } const child = new Deinflection(term, {reason, rules: variant.rulesOut}); - promises.push( - child.deinflect(definer, reasons).then(valid => valid && this.children.push(child)) - ); + if (await child.deinflect(definer, reasons)) { + this.children.push(child); + } } } - return Promise.all(promises).then(define).then(valid => { - if (valid && this.children.length > 0) { - const child = new Deinflection(this.term, {rules: this.rules, definitions: this.definitions}); - this.children.push(child); + const definitions = await definer(this.term); + if (this.rules.length === 0) { + this.definitions = definitions; + } else { + for (const rule of this.rules) { + for (const definition of definitions) { + if (definition.rules.includes(rule)) { + this.definitions.push(definition); + } + } } + } - return valid || this.children.length > 0; - }); + if (this.definitions.length > 0 && this.children.length > 0) { + const child = new Deinflection(this.term, {rules: this.rules, definitions: this.definitions}); + this.children.push(child); + } + + return this.definitions.length > 0 || this.children.length > 0; } gather() { @@ -112,16 +104,16 @@ class Deinflection { class Deinflector { - constructor() { - this.reasons = {}; - } - - setReasons(reasons) { + constructor(reasons) { this.reasons = reasons; } - deinflect(term, definer) { + async deinflect(term, definer) { const node = new Deinflection(term); - return node.deinflect(definer, this.reasons).then(success => success ? node.gather() : []); + if (await node.deinflect(definer, this.reasons)) { + return node.gather(); + } else { + return []; + } } } diff --git a/ext/bg/js/dictionary.js b/ext/bg/js/dictionary.js new file mode 100644 index 00000000..c8d431b9 --- /dev/null +++ b/ext/bg/js/dictionary.js @@ -0,0 +1,273 @@ +/* + * Copyright (C) 2016-2017 Alex Yatskov + * Author: Alex Yatskov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +function dictEnabledSet(options) { + const dictionaries = {}; + for (const title in options.dictionaries) { + const dictionary = options.dictionaries[title]; + if (dictionary.enabled) { + dictionaries[title] = dictionary; + } + } + + return dictionaries; +} + +function dictConfigured(options) { + for (const title in options.dictionaries) { + if (options.dictionaries[title].enabled) { + return true; + } + } + + return false; +} + +function dictRowsSort(rows, options) { + return rows.sort((ra, rb) => { + const pa = (options.dictionaries[ra.title] || {}).priority || 0; + const pb = (options.dictionaries[rb.title] || {}).priority || 0; + if (pa > pb) { + return -1; + } else if (pa < pb) { + return 1; + } else { + return 0; + } + }); +} + +function dictTermsSort(definitions, dictionaries=null) { + return definitions.sort((v1, v2) => { + const sl1 = v1.source.length; + const sl2 = v2.source.length; + if (sl1 > sl2) { + return -1; + } else if (sl1 < sl2) { + return 1; + } + + if (dictionaries !== null) { + const p1 = (dictionaries[v1.dictionary] || {}).priority || 0; + const p2 = (dictionaries[v2.dictionary] || {}).priority || 0; + if (p1 > p2) { + return -1; + } else if (p1 < p2) { + return 1; + } + } + + const s1 = v1.score; + const s2 = v2.score; + if (s1 > s2) { + return -1; + } else if (s1 < s2) { + return 1; + } + + const rl1 = v1.reasons.length; + const rl2 = v2.reasons.length; + if (rl1 < rl2) { + return -1; + } else if (rl1 > rl2) { + return 1; + } + + return v2.expression.localeCompare(v1.expression); + }); +} + +function dictTermsUndupe(definitions) { + const definitionGroups = {}; + for (const definition of definitions) { + const definitionExisting = definitionGroups[definition.id]; + if (!definitionGroups.hasOwnProperty(definition.id) || definition.expression.length > definitionExisting.expression.length) { + definitionGroups[definition.id] = definition; + } + } + + const definitionsUnique = []; + for (const key in definitionGroups) { + definitionsUnique.push(definitionGroups[key]); + } + + return definitionsUnique; +} + +function dictTermsGroup(definitions, dictionaries) { + const groups = {}; + for (const definition of definitions) { + const key = [definition.source, definition.expression].concat(definition.reasons); + if (definition.reading) { + key.push(definition.reading); + } + + const group = groups[key]; + if (group) { + group.push(definition); + } else { + groups[key] = [definition]; + } + } + + const results = []; + for (const key in groups) { + const groupDefs = groups[key]; + const firstDef = groupDefs[0]; + dictTermsSort(groupDefs, dictionaries); + results.push({ + definitions: groupDefs, + expression: firstDef.expression, + reading: firstDef.reading, + reasons: firstDef.reasons, + score: groupDefs.reduce((p, v) => v.score > p ? v.score : p, Number.MIN_SAFE_INTEGER), + source: firstDef.source + }); + } + + return dictTermsSort(results); +} + +function dictTagBuildSource(name) { + return dictTagSanitize({name, category: 'dictionary', order: 100}); +} + +function dictTagBuild(name, meta) { + const tag = {name}; + const symbol = name.split(':')[0]; + for (const prop in meta[symbol] || {}) { + tag[prop] = meta[symbol][prop]; + } + + return dictTagSanitize(tag); +} + +function dictTagSanitize(tag) { + tag.name = tag.name || 'untitled'; + tag.category = tag.category || 'default'; + tag.notes = tag.notes || ''; + tag.order = tag.order || 0; + return tag; +} + +function dictTagsSort(tags) { + return tags.sort((v1, v2) => { + const order1 = v1.order; + const order2 = v2.order; + if (order1 < order2) { + return -1; + } else if (order1 > order2) { + return 1; + } + + const name1 = v1.name; + const name2 = v2.name; + if (name1 < name2) { + return -1; + } else if (name1 > name2) { + return 1; + } + + return 0; + }); +} + +function dictFieldSplit(field) { + return field.length === 0 ? [] : field.split(' '); +} + +function dictFieldFormat(field, definition, mode, options) { + const markers = [ + 'audio', + 'character', + 'cloze-body', + 'cloze-prefix', + 'cloze-suffix', + 'dictionary', + 'expression', + 'furigana', + 'glossary', + 'glossary-brief', + 'kunyomi', + 'onyomi', + 'reading', + 'sentence', + 'tags', + 'url' + ]; + + for (const marker of markers) { + const data = { + marker, + definition, + group: options.general.groupResults, + html: options.anki.htmlCards, + modeTermKanji: mode === 'term-kanji', + modeTermKana: mode === 'term-kana', + modeKanji: mode === 'kanji' + }; + + field = field.replace( + `{${marker}}`, + handlebarsRender('fields.html', data) + ); + } + + return field; +} + +function dictNoteFormat(definition, mode, options) { + const note = {fields: {}, tags: options.anki.tags}; + let fields = []; + + if (mode === 'kanji') { + fields = options.anki.kanji.fields; + note.deckName = options.anki.kanji.deck; + note.modelName = options.anki.kanji.model; + } else { + fields = options.anki.terms.fields; + note.deckName = options.anki.terms.deck; + note.modelName = options.anki.terms.model; + + if (definition.audio) { + const audio = { + url: definition.audio.url, + filename: definition.audio.filename, + skipHash: '7e2c2f954ef6051373ba916f000168dc', + fields: [] + }; + + for (const name in fields) { + if (fields[name].includes('{audio}')) { + audio.fields.push(name); + } + } + + if (audio.fields.length > 0) { + note.audio = audio; + } + } + } + + for (const name in fields) { + note.fields[name] = dictFieldFormat(fields[name], definition, mode, options); + } + + return note; +} diff --git a/ext/bg/js/display-window.js b/ext/bg/js/display-window.js deleted file mode 100644 index ae97cd36..00000000 --- a/ext/bg/js/display-window.js +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (C) 2016 Alex Yatskov - * Author: Alex Yatskov - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -window.displayWindow = new class extends Display { - constructor() { - super($('#spinner'), $('#content')); - - const search = $('#search'); - search.click(this.onSearch.bind(this)); - - const query = $('#query'); - query.on('input', () => search.prop('disabled', query.val().length === 0)); - window.wanakana.bind(query.get(0)); - } - - definitionAdd(definition, mode) { - return instYomi().definitionAdd(definition, mode); - } - - definitionsAddable(definitions, modes) { - return instYomi().definitionsAddable(definitions, modes).catch(() => []); - } - - templateRender(template, data) { - return instYomi().templateRender(template, data); - } - - kanjiFind(character) { - return instYomi().kanjiFind(character); - } - - handleError(error) { - window.alert(`Error: ${error}`); - } - - clearSearch() { - $('#query').focus().select(); - } - - onSearch(e) { - e.preventDefault(); - $('#intro').slideUp(); - instYomi().termsFind($('#query').val()).then(({length, definitions}) => { - super.showTermDefs(definitions, instYomi().options); - }).catch(this.handleError.bind(this)); - } -}; diff --git a/ext/bg/js/handlebars.js b/ext/bg/js/handlebars.js new file mode 100644 index 00000000..debb0690 --- /dev/null +++ b/ext/bg/js/handlebars.js @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2016-2017 Alex Yatskov + * Author: Alex Yatskov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + + +function handlebarsEscape(text) { + return Handlebars.Utils.escapeExpression(text); +} + +function handlebarsDumpObject(options) { + const dump = JSON.stringify(options.fn(this), null, 4); + return handlebarsEscape(dump); +} + +function handlebarsKanjiLinks(options) { + let result = ''; + for (const c of options.fn(this)) { + if (jpIsKanji(c)) { + result += `${c}`; + } else { + result += c; + } + } + + return result; +} + +function handlebarsMultiLine(options) { + return options.fn(this).split('\n').join('
'); +} + +function handlebarsRender(template, data) { + if (Handlebars.partials !== Handlebars.templates) { + Handlebars.partials = Handlebars.templates; + Handlebars.registerHelper('dumpObject', handlebarsDumpObject); + Handlebars.registerHelper('kanjiLinks', handlebarsKanjiLinks); + Handlebars.registerHelper('multiLine', handlebarsMultiLine); + } + + return Handlebars.templates[template](data); +} diff --git a/ext/bg/js/options.js b/ext/bg/js/options.js index 5aa18366..ea52d337 100644 --- a/ext/bg/js/options.js +++ b/ext/bg/js/options.js @@ -17,388 +17,115 @@ */ -/* - * General - */ +function optionsSetDefaults(options) { + const defaults = { + general: { + enable: true, + audioSource: 'jpod101', + audioVolume: 100, + groupResults: true, + debugInfo: false, + maxResults: 32, + showAdvanced: false, + popupWidth: 400, + popupHeight: 250, + popupOffset: 10, + showGuide: true + }, -function formRead() { - return optionsLoad().then(optionsOld => { - const optionsNew = $.extend(true, {}, optionsOld); + scanning: { + middleMouse: true, + selectText: true, + alphanumeric: true, + delay: 15, + length: 10, + modifier: 'shift' + }, - optionsNew.general.showGuide = $('#show-usage-guide').prop('checked'); - optionsNew.general.audioSource = $('#audio-playback-source').val(); - optionsNew.general.audioVolume = parseFloat($('#audio-playback-volume').val()); - optionsNew.general.groupResults = $('#group-terms-results').prop('checked'); - optionsNew.general.debugInfo = $('#show-debug-info').prop('checked'); - optionsNew.general.showAdvanced = $('#show-advanced-options').prop('checked'); - optionsNew.general.maxResults = parseInt($('#max-displayed-results').val(), 10); - optionsNew.general.popupWidth = parseInt($('#popup-width').val(), 10); - optionsNew.general.popupHeight = parseInt($('#popup-height').val(), 10); - optionsNew.general.popupOffset = parseInt($('#popup-offset').val(), 10); + dictionaries: {}, - optionsNew.scanning.middleMouse = $('#middle-mouse-button-scan').prop('checked'); - optionsNew.scanning.selectText = $('#select-matched-text').prop('checked'); - optionsNew.scanning.alphanumeric = $('#search-alphanumeric').prop('checked'); - optionsNew.scanning.delay = parseInt($('#scan-delay').val(), 10); - optionsNew.scanning.length = parseInt($('#scan-length').val(), 10); - optionsNew.scanning.modifier = $('#scan-modifier-key').val(); - - optionsNew.anki.enable = $('#anki-enable').prop('checked'); - optionsNew.anki.tags = $('#card-tags').val().split(/[,; ]+/); - optionsNew.anki.htmlCards = $('#generate-html-cards').prop('checked'); - optionsNew.anki.sentenceExt = parseInt($('#sentence-detection-extent').val(), 10); - optionsNew.anki.server = $('#interface-server').val(); - - if (optionsOld.anki.enable && !$('#anki-error').is(':visible')) { - optionsNew.anki.terms.deck = $('#anki-terms-deck').val(); - optionsNew.anki.terms.model = $('#anki-terms-model').val(); - optionsNew.anki.terms.fields = ankiFieldsToDict($('#terms .anki-field-value')); - optionsNew.anki.kanji.deck = $('#anki-kanji-deck').val(); - optionsNew.anki.kanji.model = $('#anki-kanji-model').val(); - optionsNew.anki.kanji.fields = ankiFieldsToDict($('#kanji .anki-field-value')); + anki: { + enable: false, + server: 'http://127.0.0.1:8765', + tags: ['yomichan'], + htmlCards: true, + sentenceExt: 200, + terms: {deck: '', model: '', fields: {}}, + kanji: {deck: '', model: '', fields: {}} } + }; - $('.dict-group').each((index, element) => { - const dictionary = $(element); - const title = dictionary.data('title'); - const priority = parseInt(dictionary.find('.dict-priority').val(), 10); - const enabled = dictionary.find('.dict-enabled').prop('checked'); - optionsNew.dictionaries[title] = {priority, enabled}; - }); - - return {optionsNew, optionsOld}; - }); -} - -function updateVisibility(options) { - const general = $('#anki-general'); - if (options.anki.enable) { - general.show(); - } else { - general.hide(); - } - - const advanced = $('.options-advanced'); - if (options.general.showAdvanced) { - advanced.show(); - } else { - advanced.hide(); - } - - const debug = $('#debug'); - if (options.general.debugInfo) { - const text = JSON.stringify(options, null, 4); - debug.html(handlebarsEscape(text)); - debug.show(); - } else { - debug.hide(); - } -} - -function onOptionsChanged(e) { - if (!e.originalEvent && !e.isTrigger) { - return; - } - - formRead().then(({optionsNew, optionsOld}) => { - return optionsSave(optionsNew).then(() => { - updateVisibility(optionsNew); - - const ankiUpdated = - optionsNew.anki.enable !== optionsOld.anki.enable || - optionsNew.anki.server !== optionsOld.anki.server; - - if (ankiUpdated) { - ankiErrorShow(null); - ankiSpinnerShow(true); - return ankiDeckAndModelPopulate(optionsNew); + const combine = (target, source) => { + for (const key in source) { + if (!target.hasOwnProperty(key)) { + target[key] = source[key]; } - }); - }).catch(ankiErrorShow).then(() => ankiSpinnerShow(false)); + } + }; + + combine(options, defaults); + combine(options.general, defaults.general); + combine(options.scanning, defaults.scanning); + combine(options.anki, defaults.anki); + combine(options.anki.terms, defaults.anki.terms); + combine(options.anki.kanji, defaults.anki.kanji); + + return options; } -$(document).ready(() => { - handlebarsRegister(); +function optionsVersion(options) { + const fixups = [ + () => {}, + () => {}, + () => {}, + () => {}, + () => { + if (options.general.audioPlayback) { + options.general.audioSource = 'jpod101'; + } else { + options.general.audioSource = 'disabled'; + } + }, + () => { + options.general.showGuide = false; + }, + () => { + if (options.scanning.requireShift) { + options.scanning.modifier = 'shift'; + } else { + options.scanning.modifier = 'none'; + } + } + ]; - optionsLoad().then(options => { - $('#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); - $('#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); - - $('#dict-purge').click(onDictionaryPurge); - $('#dict-file').change(onDictionaryImport); - - $('#anki-enable').prop('checked', options.anki.enable); - $('#card-tags').val(options.anki.tags.join(' ')); - $('#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); - ankiDeckAndModelPopulate(options); - updateVisibility(options); - }); -}); - - -/* - * Dictionary - */ - -function dictionaryErrorShow(error) { - const dialog = $('#dict-error'); - if (error) { - dialog.show().find('span').text(error); - } else { - dialog.hide(); + optionsSetDefaults(options); + if (!options.hasOwnProperty('version')) { + options.version = fixups.length; } -} -function dictionarySpinnerShow(show) { - const spinner = $('#dict-spinner'); - if (show) { - spinner.show(); - } else { - spinner.hide(); + while (options.version < fixups.length) { + fixups[options.version++](); } + + return options; } -function dictionaryGroupsSort() { - const dictGroups = $('#dict-groups'); - const dictGroupChildren = dictGroups.children('.dict-group').sort((ca, cb) => { - const pa = parseInt($(ca).find('.dict-priority').val(), 10); - const pb = parseInt($(cb).find('.dict-priority').val(), 10); - if (pa < pb) { - return 1; - } else if (pa > pb) { - return -1; - } else { - return 0; - } - }); - - dictGroups.append(dictGroupChildren); -} - -function dictionaryGroupsPopulate(options) { - dictionaryErrorShow(null); - dictionarySpinnerShow(true); - - const dictGroups = $('#dict-groups').empty(); - const dictWarning = $('#dict-warning').hide(); - - return instDb().getDictionaries().then(rows => { - if (rows.length === 0) { - dictWarning.show(); - } - - for (const row of dictRowsSort(rows, options)) { - const dictOptions = options.dictionaries[row.title] || {enabled: false, priority: 0}; - const dictHtml = handlebarsRender('dictionary.html', { - title: row.title, - version: row.version, - revision: row.revision, - priority: dictOptions.priority, - enabled: dictOptions.enabled - }); - - dictGroups.append($(dictHtml)); - } - - updateVisibility(options); - - $('.dict-enabled, .dict-priority').change(e => { - dictionaryGroupsSort(); - onOptionsChanged(e); - }); - }).catch(dictionaryErrorShow).then(() => dictionarySpinnerShow(false)); -} - -function onDictionaryPurge(e) { - e.preventDefault(); - - dictionaryErrorShow(null); - dictionarySpinnerShow(true); - - const dictControls = $('#dict-importer, #dict-groups').hide(); - const dictProgress = $('#dict-purge-progress').show(); - - instDb().purge().catch(dictionaryErrorShow).then(() => { - dictionarySpinnerShow(false); - dictControls.show(); - dictProgress.hide(); - return optionsLoad(); +function optionsLoad() { + return new Promise((resolve, reject) => { + chrome.storage.local.get(null, store => resolve(store.options)); + }).then(optionsStr => { + return optionsStr ? JSON.parse(optionsStr) : {}; + }).catch(error => { + return {}; }).then(options => { - options.dictionaries = {}; - optionsSave(options).then(() => dictionaryGroupsPopulate(options)); + return optionsVersion(options); }); } -function onDictionaryImport(e) { - dictionaryErrorShow(null); - dictionarySpinnerShow(true); - - const dictFile = $('#dict-file'); - const dictImporter = $('#dict-importer').hide(); - 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); - - optionsLoad().then(options => { - return instDb().importDictionary(e.target.files[0], updateProgress).then(summary => { - options.dictionaries[summary.title] = {enabled: true, priority: 0}; - return optionsSave(options); - }).then(() => dictionaryGroupsPopulate(options)); - }).catch(dictionaryErrorShow).then(() => { - dictFile.val(''); - dictionarySpinnerShow(false); - dictProgress.hide(); - dictImporter.show(); - }); -} - -/* - * Anki - */ - -function ankiSpinnerShow(show) { - const spinner = $('#anki-spinner'); - if (show) { - spinner.show(); - } else { - spinner.hide(); - } -} - -function ankiErrorShow(error) { - const dialog = $('#anki-error'); - if (error) { - dialog.show().find('span').text(error); - } - else { - dialog.hide(); - } -} - -function ankiFieldsToDict(selection) { - const result = {}; - selection.each((index, element) => { - result[$(element).data('field')] = $(element).val(); - }); - - return result; -} - -function ankiDeckAndModelPopulate(options) { - ankiErrorShow(null); - ankiSpinnerShow(true); - - 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($('