Optimize dictFieldFormat

This commit is contained in:
toasted-nutbread 2019-11-08 22:08:11 -05:00
parent fa963722a7
commit 4d7940e8e4
2 changed files with 58 additions and 38 deletions

View File

@ -327,45 +327,50 @@ function dictFieldSplit(field) {
} }
async function dictFieldFormat(field, definition, mode, options) { async function dictFieldFormat(field, definition, mode, options) {
const markers = [ const data = {
'audio', marker: null,
'character', definition,
'cloze-body', group: options.general.resultOutputMode === 'group',
'cloze-prefix', merge: options.general.resultOutputMode === 'merge',
'cloze-suffix', modeTermKanji: mode === 'term-kanji',
'dictionary', modeTermKana: mode === 'term-kana',
'expression', modeKanji: mode === 'kanji',
'furigana', compactGlossaries: options.general.compactGlossaries
'furigana-plain', };
'glossary', const markers = dictFieldFormat.markers;
'glossary-brief', const pattern = /\{([\w\-]+)\}/g;
'kunyomi', return await stringReplaceAsync(field, pattern, async (g0, marker) => {
'onyomi', if (!markers.has(marker)) {
'reading', return g0;
'screenshot', }
'sentence', data.marker = marker;
'tags', try {
'url' return await apiTemplateRender(options.anki.fieldTemplates, data, true);
]; } catch (e) {
return `{${marker}-render-error}`;
for (const marker of markers) { }
const data = { });
marker,
definition,
group: options.general.resultOutputMode === 'group',
merge: options.general.resultOutputMode === 'merge',
modeTermKanji: mode === 'term-kanji',
modeTermKana: mode === 'term-kana',
modeKanji: mode === 'kanji',
compactGlossaries: options.general.compactGlossaries
};
const html = await apiTemplateRender(options.anki.fieldTemplates, data, true);
field = field.replace(`{${marker}}`, html);
}
return field;
} }
dictFieldFormat.markers = new Set([
'audio',
'character',
'cloze-body',
'cloze-prefix',
'cloze-suffix',
'dictionary',
'expression',
'furigana',
'furigana-plain',
'glossary',
'glossary-brief',
'kunyomi',
'onyomi',
'reading',
'screenshot',
'sentence',
'tags',
'url'
]);
async function dictNoteFormat(definition, mode, options) { async function dictNoteFormat(definition, mode, options) {
const note = {fields: {}, tags: options.anki.tags}; const note = {fields: {}, tags: options.anki.tags};

View File

@ -133,3 +133,18 @@ function promiseTimeout(delay, resolveValue) {
return promise; return promise;
} }
function stringReplaceAsync(str, regex, replacer) {
let match;
let index = 0;
const parts = [];
while ((match = regex.exec(str)) !== null) {
parts.push(str.substring(index, match.index), replacer(...match, match.index, str));
index = regex.lastIndex;
}
if (parts.length === 0) {
return Promise.resolve(str);
}
parts.push(str.substring(index));
return Promise.all(parts).then(v => v.join(''));
}