Skip to content
This repository has been archived by the owner on Feb 25, 2023. It is now read-only.

Refactor anki note building #1223

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 25 additions & 22 deletions ext/bg/js/anki-note-builder.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@

/* global
* DictionaryDataUtil
* TemplateRendererProxy
*/

class AnkiNoteBuilder {
constructor({renderTemplate}) {
this._renderTemplate = renderTemplate;
constructor(enabled) {
this._markerPattern = /\{([\w-]+)\}/g;
this._templateRenderer = enabled ? new TemplateRendererProxy() : null;
}

async createNote({
Expand All @@ -49,22 +50,6 @@ class AnkiNoteBuilder {
duplicateScopeCheckChildren = true;
}

const noteFields = {};
const note = {
fields: noteFields,
tags,
deckName,
modelName,
options: {
allowDuplicate: !checkForDuplicates,
duplicateScope,
duplicateScopeOptions: {
deckName: duplicateScopeDeckName,
checkChildren: duplicateScopeCheckChildren
}
}
};

const data = this._createNoteData(definition, mode, context, resultOutputMode, glossaryLayoutMode, compactTags);
const formattedFieldValuePromises = [];
for (const [, fieldValue] of fields) {
Expand All @@ -73,13 +58,27 @@ class AnkiNoteBuilder {
}

const formattedFieldValues = await Promise.all(formattedFieldValuePromises);
const noteFields = {};
for (let i = 0, ii = fields.length; i < ii; ++i) {
const fieldName = fields[i][0];
const formattedFieldValue = formattedFieldValues[i];
noteFields[fieldName] = formattedFieldValue;
}

return note;
return {
fields: noteFields,
tags,
deckName,
modelName,
options: {
allowDuplicate: !checkForDuplicates,
duplicateScope,
duplicateScopeOptions: {
deckName: duplicateScopeDeckName,
checkChildren: duplicateScopeCheckChildren
}
}
};
}

containsMarker(fields, marker) {
Expand Down Expand Up @@ -146,7 +145,7 @@ class AnkiNoteBuilder {
});
}

_stringReplaceAsync(str, regex, replacer) {
async _stringReplaceAsync(str, regex, replacer) {
let match;
let index = 0;
const parts = [];
Expand All @@ -155,9 +154,13 @@ class AnkiNoteBuilder {
index = regex.lastIndex;
}
if (parts.length === 0) {
return Promise.resolve(str);
return str;
}
parts.push(str.substring(index));
return Promise.all(parts).then((v) => v.join(''));
return (await Promise.all(parts)).join('');
}

async _renderTemplate(template, data, marker) {
return await this._templateRenderer.render(template, {data, marker}, 'ankiNote');
}
}
4 changes: 1 addition & 3 deletions ext/bg/js/settings/anki-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ class AnkiController {
constructor(settingsController) {
this._settingsController = settingsController;
this._ankiConnect = new AnkiConnect();
this._ankiNoteBuilder = new AnkiNoteBuilder({
renderTemplate: null
});
this._ankiNoteBuilder = new AnkiNoteBuilder(false);
this._selectorObserver = new SelectorObserver({
selector: '.anki-card',
ignoreSelector: null,
Expand Down
12 changes: 2 additions & 10 deletions ext/bg/js/settings/anki-templates-controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

/* global
* AnkiNoteBuilder
* TemplateRendererProxy
* api
*/

Expand All @@ -34,7 +33,7 @@ class AnkiTemplatesController {
this._renderFieldInput = null;
this._renderResult = null;
this._fieldTemplateResetModal = null;
this._templateRenderer = new TemplateRendererProxy();
this._ankiNoteBuilder = new AnkiNoteBuilder(true);
}

async prepare() {
Expand Down Expand Up @@ -180,11 +179,8 @@ class AnkiTemplatesController {
};
let templates = options.anki.fieldTemplates;
if (typeof templates !== 'string') { templates = this._defaultFieldTemplates; }
const ankiNoteBuilder = new AnkiNoteBuilder({
renderTemplate: this._renderTemplate.bind(this)
});
const {general: {resultOutputMode, glossaryLayoutMode, compactTags}} = options;
const note = await ankiNoteBuilder.createNote({
const note = await this._ankiNoteBuilder.createNote({
definition,
mode,
context,
Expand Down Expand Up @@ -213,8 +209,4 @@ class AnkiTemplatesController {
this._fieldTemplatesTextarea.dataset.invalid = `${hasException}`;
}
}

async _renderTemplate(template, data, marker) {
return await this._templateRenderer.render(template, data, marker);
}
}
8 changes: 5 additions & 3 deletions ext/bg/js/template-renderer-frame-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,16 @@ class TemplateRendererFrameApi {
constructor(templateRenderer) {
this._templateRenderer = templateRenderer;
this._windowMessageHandlers = new Map([
['renderHandlebarsTemplate', {async: true, handler: this._onRenderHandlebarsTemplate.bind(this)}]
['render', {async: true, handler: this._onRender.bind(this)}]
]);
}

prepare() {
window.addEventListener('message', this._onWindowMessage.bind(this), false);
}

// Private

_onWindowMessage(e) {
const {source, data: {action, params, id}} = e;
const messageHandler = this._windowMessageHandlers.get(action);
Expand All @@ -51,8 +53,8 @@ class TemplateRendererFrameApi {
source.postMessage({action: `${action}.response`, params: response, id}, '*');
}

async _onRenderHandlebarsTemplate({template, data, marker}) {
return await this._templateRenderer.render(template, data, marker);
async _onRender({template, data, type}) {
return await this._templateRenderer.render(template, data, type);
}

_errorToJson(error) {
Expand Down
6 changes: 6 additions & 0 deletions ext/bg/js/template-renderer-frame-main.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@
(() => {
const japaneseUtil = new JapaneseUtil(null);
const templateRenderer = new TemplateRenderer(japaneseUtil);
templateRenderer.registerDataType('ankiNote', {
modifier: ({data, marker}) => {
data.marker = marker;
return data;
}
});
const api = new TemplateRendererFrameApi(templateRenderer);
api.prepare();
})();
4 changes: 2 additions & 2 deletions ext/bg/js/template-renderer-proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ class TemplateRendererProxy {
this._invocations = new Set();
}

async render(template, data, marker) {
async render(template, data, type) {
await this._prepareFrame();
return await this._invoke('renderHandlebarsTemplate', {template, data, marker});
return await this._invoke('render', {template, data, type});
}

// Private
Expand Down
30 changes: 22 additions & 8 deletions ext/bg/js/template-renderer.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,14 @@ class TemplateRenderer {
this._cacheMaxSize = 5;
this._helpersRegistered = false;
this._stateStack = null;
this._dataTypes = new Map();
}

async render(template, data, marker) {
registerDataType(name, {modifier=null, modifierPost=null}) {
this._dataTypes.set(name, {modifier, modifierPost});
}

async render(template, data, type) {
if (!this._helpersRegistered) {
this._registerHelpers();
this._helpersRegistered = true;
Expand All @@ -42,18 +47,27 @@ class TemplateRenderer {
cache.set(template, instance);
}

const markerPre = data.marker;
const markerPreHas = Object.prototype.hasOwnProperty.call(data, 'marker');
let modifier = null;
let modifierPost = null;
if (typeof type === 'string') {
const typeInfo = this._dataTypes.get(type);
if (typeof typeInfo !== 'undefined') {
({modifier, modifierPost} = typeInfo);
}
}

try {
if (typeof modifier === 'function') {
data = modifier(data);
}

this._stateStack = [new Map()];
data.marker = marker;
return instance(data).trim();
} finally {
this._stateStack = null;
if (markerPreHas) {
data.marker = markerPre;
} else {
delete data.marker;

if (typeof modifierPost === 'function') {
modifierPost(data);
}
}
}
Expand Down
10 changes: 1 addition & 9 deletions ext/mixed/js/display.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
* MediaLoader
* PopupFactory
* QueryParser
* TemplateRendererProxy
* TextScanner
* WindowScroll
* api
Expand Down Expand Up @@ -89,10 +88,7 @@ class Display extends EventDispatcher {
this._mode = null;
this._defaultAnkiFieldTemplates = null;
this._defaultAnkiFieldTemplatesPromise = null;
this._templateRenderer = new TemplateRendererProxy();
this._ankiNoteBuilder = new AnkiNoteBuilder({
renderTemplate: this._renderTemplate.bind(this)
});
this._ankiNoteBuilder = new AnkiNoteBuilder(true);
this._updateAdderButtonsPromise = Promise.resolve();
this._contentScrollElement = document.querySelector('#content-scroll');
this._contentScrollBodyElement = document.querySelector('#content-body');
Expand Down Expand Up @@ -1493,10 +1489,6 @@ class Display extends EventDispatcher {
return value;
}

async _renderTemplate(template, data, marker) {
return await this._templateRenderer.render(template, data, marker);
}

async _addDefinition(definition, mode, context) {
const options = this._options;
const templates = await this._getTemplates(options);
Expand Down