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
|
/*
* Copyright (C) 2020-2021 Yomichan Authors
*
* 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 <https://www.gnu.org/licenses/>.
*/
/* global
* AnkiUtil
* TemplateRendererProxy
*/
class AnkiNoteBuilder {
constructor() {
this._markerPattern = AnkiUtil.cloneFieldMarkerPattern(true);
this._templateRenderer = new TemplateRendererProxy();
this._batchedRequests = [];
this._batchedRequestsQueued = false;
}
async createNote({
dictionaryEntry,
mode,
context,
template,
deckName,
modelName,
fields,
tags=[],
requirements=[],
checkForDuplicates=true,
duplicateScope='collection',
resultOutputMode='split',
glossaryLayoutMode='default',
compactTags=false,
mediaOptions=null
}) {
let duplicateScopeDeckName = null;
let duplicateScopeCheckChildren = false;
if (duplicateScope === 'deck-root') {
duplicateScope = 'deck';
duplicateScopeDeckName = AnkiUtil.getRootDeckName(deckName);
duplicateScopeCheckChildren = true;
}
const allErrors = [];
let media;
if (requirements.length > 0 && mediaOptions !== null) {
let errors;
({media, errors} = await this._injectMedia(dictionaryEntry, requirements, mediaOptions));
for (const error of errors) {
allErrors.push(deserializeError(error));
}
} else {
media = {};
}
const commonData = this._createData(dictionaryEntry, mode, context, resultOutputMode, glossaryLayoutMode, compactTags, media);
const formattedFieldValuePromises = [];
for (const [, fieldValue] of fields) {
const formattedFieldValuePromise = this._formatField(fieldValue, commonData, template);
formattedFieldValuePromises.push(formattedFieldValuePromise);
}
const formattedFieldValues = await Promise.all(formattedFieldValuePromises);
const uniqueRequirements = new Map();
const noteFields = {};
for (let i = 0, ii = fields.length; i < ii; ++i) {
const fieldName = fields[i][0];
const {value, errors: fieldErrors, requirements: fieldRequirements} = formattedFieldValues[i];
noteFields[fieldName] = value;
allErrors.push(...fieldErrors);
for (const requirement of fieldRequirements) {
const key = JSON.stringify(requirement);
if (uniqueRequirements.has(key)) { continue; }
uniqueRequirements.set(key, requirement);
}
}
const note = {
fields: noteFields,
tags,
deckName,
modelName,
options: {
allowDuplicate: !checkForDuplicates,
duplicateScope,
duplicateScopeOptions: {
deckName: duplicateScopeDeckName,
checkChildren: duplicateScopeCheckChildren
}
}
};
return {note, errors: allErrors, requirements: [...uniqueRequirements.values()]};
}
async getRenderingData({
dictionaryEntry,
mode,
context,
resultOutputMode='split',
glossaryLayoutMode='default',
compactTags=false,
marker=null
}) {
const commonData = this._createData(dictionaryEntry, mode, context, resultOutputMode, glossaryLayoutMode, compactTags, {});
return await this._templateRenderer.getModifiedData({marker, commonData}, 'ankiNote');
}
getDictionaryEntryDetailsForNote(dictionaryEntry) {
const {type} = dictionaryEntry;
if (type === 'kanji') {
const {character} = dictionaryEntry;
return {type, character};
}
const {headwords} = dictionaryEntry;
let bestIndex = -1;
for (let i = 0, ii = headwords.length; i < ii; ++i) {
const {term, reading, sources} = headwords[i];
for (const {deinflectedText} of sources) {
if (term === deinflectedText) {
bestIndex = i;
i = ii;
break;
} else if (reading === deinflectedText && bestIndex < 0) {
bestIndex = i;
break;
}
}
}
const {term, reading} = headwords[Math.max(0, bestIndex)];
return {type, term, reading};
}
// Private
_createData(dictionaryEntry, mode, context, resultOutputMode, glossaryLayoutMode, compactTags, media) {
return {
dictionaryEntry,
mode,
context,
resultOutputMode,
glossaryLayoutMode,
compactTags,
media
};
}
async _formatField(field, commonData, template) {
const errors = [];
const requirements = [];
const value = await this._stringReplaceAsync(field, this._markerPattern, async (g0, marker) => {
try {
const {result, requirements: fieldRequirements} = await this._renderTemplateBatched(template, commonData, marker);
requirements.push(...fieldRequirements);
return result;
} catch (e) {
const error = new Error(`Template render error for {${marker}}`);
error.data = {error: e};
errors.push(error);
return `{${marker}-render-error}`;
}
});
return {value, errors, requirements};
}
async _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 str;
}
parts.push(str.substring(index));
return (await Promise.all(parts)).join('');
}
_getBatchedTemplateGroup(template) {
for (const item of this._batchedRequests) {
if (item.template === template) {
return item;
}
}
const result = {template, commonDataRequestsMap: new Map()};
this._batchedRequests.push(result);
return result;
}
_renderTemplateBatched(template, commonData, marker) {
const {promise, resolve, reject} = deferPromise();
const {commonDataRequestsMap} = this._getBatchedTemplateGroup(template);
let requests = commonDataRequestsMap.get(commonData);
if (typeof requests === 'undefined') {
requests = [];
commonDataRequestsMap.set(commonData, requests);
}
requests.push({resolve, reject, marker});
this._runBatchedRequestsDelayed();
return promise;
}
_runBatchedRequestsDelayed() {
if (this._batchedRequestsQueued) { return; }
this._batchedRequestsQueued = true;
Promise.resolve().then(() => {
this._batchedRequestsQueued = false;
this._runBatchedRequests();
});
}
_runBatchedRequests() {
if (this._batchedRequests.length === 0) { return; }
const allRequests = [];
const items = [];
for (const {template, commonDataRequestsMap} of this._batchedRequests) {
const templateItems = [];
for (const [commonData, requests] of commonDataRequestsMap.entries()) {
const datas = [];
for (const {marker} of requests) {
datas.push(marker);
}
allRequests.push(...requests);
templateItems.push({type: 'ankiNote', commonData, datas});
}
items.push({template, templateItems});
}
this._batchedRequests.length = 0;
this._resolveBatchedRequests(items, allRequests);
}
async _resolveBatchedRequests(items, requests) {
let responses;
try {
responses = await this._templateRenderer.renderMulti(items);
} catch (e) {
for (const {reject} of requests) {
reject(e);
}
return;
}
for (let i = 0, ii = requests.length; i < ii; ++i) {
const request = requests[i];
try {
const response = responses[i];
const {error} = response;
if (typeof error !== 'undefined') {
throw deserializeError(error);
} else {
request.resolve(response.result);
}
} catch (e) {
request.reject(e);
}
}
}
async _injectMedia(dictionaryEntry, requirements, mediaOptions) {
const timestamp = Date.now();
// Parse requirements
let injectAudio = false;
let injectScreenshot = false;
let injectClipboardImage = false;
let injectClipboardText = false;
let injectSelectionText = false;
const dictionaryMediaDetails = [];
for (const requirement of requirements) {
const {type} = requirement;
switch (type) {
case 'audio': injectAudio = true; break;
case 'screenshot': injectScreenshot = true; break;
case 'clipboardImage': injectClipboardImage = true; break;
case 'clipboardText': injectClipboardText = true; break;
case 'selectionText': injectSelectionText = true; break;
case 'dictionaryMedia':
{
const {dictionary, path} = requirement;
dictionaryMediaDetails.push({dictionary, path});
}
break;
}
}
// Generate request data
const dictionaryEntryDetails = this.getDictionaryEntryDetailsForNote(dictionaryEntry);
let audioDetails = null;
let screenshotDetails = null;
const clipboardDetails = {image: injectClipboardImage, text: injectClipboardText};
if (injectAudio && dictionaryEntryDetails.type !== 'kanji') {
const audioOptions = mediaOptions.audio;
if (typeof audioOptions === 'object' && audioOptions !== null) {
const {sources, preferredAudioIndex} = audioOptions;
audioDetails = {sources, preferredAudioIndex};
}
}
if (injectScreenshot) {
const screenshotOptions = mediaOptions.screenshot;
if (typeof screenshotOptions === 'object' && screenshotOptions !== null) {
const {format, quality, contentOrigin: {tabId, frameId}} = screenshotOptions;
if (typeof tabId === 'number' && typeof frameId === 'number') {
screenshotDetails = {tabId, frameId, format, quality};
}
}
}
// Inject media
const selectionText = injectSelectionText ? this._getSelectionText() : null;
const injectedMedia = await yomichan.api.injectAnkiNoteMedia(
timestamp,
dictionaryEntryDetails,
audioDetails,
screenshotDetails,
clipboardDetails,
dictionaryMediaDetails
);
const {audioFileName, screenshotFileName, clipboardImageFileName, clipboardText, dictionaryMedia: dictionaryMediaArray, errors} = injectedMedia;
// Format results
const dictionaryMedia = {};
for (const {dictionary, path, fileName} of dictionaryMediaArray) {
if (fileName === null) { continue; }
const dictionaryMedia2 = (
Object.prototype.hasOwnProperty.call(dictionaryMedia, dictionary) ?
(dictionaryMedia[dictionary]) :
(dictionaryMedia[dictionary] = {})
);
dictionaryMedia2[path] = {fileName};
}
const media = {
audio: (typeof audioFileName === 'string' ? {fileName: audioFileName} : null),
screenshot: (typeof screenshotFileName === 'string' ? {fileName: screenshotFileName} : null),
clipboardImage: (typeof clipboardImageFileName === 'string' ? {fileName: clipboardImageFileName} : null),
clipboardText: (typeof clipboardText === 'string' ? {text: clipboardText} : null),
selectionText: (typeof selectionText === 'string' ? {text: selectionText} : null),
dictionaryMedia
};
return {media, errors};
}
_getSelectionText() {
return document.getSelection().toString();
}
}
|