summaryrefslogtreecommitdiff
path: root/ext/bg/js/anki-note-builder.js
diff options
context:
space:
mode:
authortoasted-nutbread <toasted-nutbread@users.noreply.github.com>2020-09-08 11:01:08 -0400
committerGitHub <noreply@github.com>2020-09-08 11:01:08 -0400
commitf7093b4c1abf73363e65dba54a098b76d0f2ba50 (patch)
treec54fc65cb559d21450a1c2a3596ec222e40fc9ba /ext/bg/js/anki-note-builder.js
parent36fc5abae543840484b3d8f7abff85f57de66ada (diff)
Anki note clipboard marker (#780)
* Update fields reference * Add support for adding clipboard images to anki notes * Add handlebars templates * Add markers * Add markers to readme
Diffstat (limited to 'ext/bg/js/anki-note-builder.js')
-rw-r--r--ext/bg/js/anki-note-builder.js38
1 files changed, 37 insertions, 1 deletions
diff --git a/ext/bg/js/anki-note-builder.js b/ext/bg/js/anki-note-builder.js
index 041e6dcd..d69a4fea 100644
--- a/ext/bg/js/anki-note-builder.js
+++ b/ext/bg/js/anki-note-builder.js
@@ -20,10 +20,11 @@
*/
class AnkiNoteBuilder {
- constructor({anki, audioSystem, renderTemplate}) {
+ constructor({anki, audioSystem, renderTemplate, getClipboardImage=null}) {
this._anki = anki;
this._audioSystem = audioSystem;
this._renderTemplate = renderTemplate;
+ this._getClipboardImage = getClipboardImage;
}
async createNote(definition, mode, context, options, templates) {
@@ -138,6 +139,31 @@ class AnkiNoteBuilder {
definition.screenshotFileName = fileName;
}
+ async injectClipboardImage(definition, fields) {
+ if (!this._containsMarker(fields, 'clipboard-image')) { return; }
+
+ const reading = definition.reading;
+ const now = new Date(Date.now());
+
+ try {
+ const dataUrl = await this._getClipboardImage();
+ if (dataUrl === null) { return; }
+
+ const extension = this._getImageExtensionFromDataUrl(dataUrl);
+ if (extension === null) { return; }
+
+ let fileName = `yomichan_clipboard_image_${reading}_${this._dateToString(now)}.${extension}`;
+ fileName = AnkiNoteBuilder.replaceInvalidFileNameCharacters(fileName);
+ const data = dataUrl.replace(/^data:[\w\W]*?,/, '');
+
+ await this._anki.storeMediaFile(fileName, data);
+
+ definition.clipboardImageFileName = fileName;
+ } catch (e) {
+ // NOP
+ }
+ }
+
_createInjectedAudioFileName(definition) {
const {reading, expression} = definition;
if (!reading && !expression) { return null; }
@@ -170,6 +196,16 @@ class AnkiNoteBuilder {
return false;
}
+ _getImageExtensionFromDataUrl(dataUrl) {
+ const match = /^data:([^;]*);/.exec(dataUrl);
+ if (match === null) { return null; }
+ switch (match[1].toLowerCase()) {
+ case 'image/png': return 'png';
+ case 'image/jpeg': return 'jpeg';
+ default: return null;
+ }
+ }
+
static replaceInvalidFileNameCharacters(fileName) {
// eslint-disable-next-line no-control-regex
return fileName.replace(/[<>:"/\\|?*\x00-\x1F]/g, '-');