genanki-js 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Changelog.md ADDED
@@ -0,0 +1,13 @@
1
+ ## 2.0.0
2
+ Now, import genanki as node modules.
3
+ View [Documentation](https://krmanik.github.io/genanki-js/)
4
+
5
+ ## v1.0.5
6
+ genanki zip file contains two folder
7
+
8
+ - `dist` : This folder contains `genanki.js` file. If project already configured with [sql.js](https://github.com/sql-js/sql.js), [FileSaver.js](https://github.com/eligrey/FileSaver.js) and [JSZip](https://github.com/Stuk/jszip) then just add `genanki.js` file to project.
9
+
10
+ - `sample` : This folder contains latest [sql.js](https://github.com/sql-js/sql.js), [FileSaver.js](https://github.com/eligrey/FileSaver.js), [JSZip](https://github.com/Stuk/jszip) and [genanki.js](https://github.com/krmanik/genanki-js). It is ready to use folder.
11
+
12
+
13
+ View [Documentation](https://krmanik.github.io/genanki-js/)
package/License.md ADDED
@@ -0,0 +1,22 @@
1
+ ### [sql.js](https://github.com/sql-js/sql.js)
2
+ [The MIT License](https://github.com/sql-js/sql.js/blob/master/LICENSE)
3
+ <br>Copyright (c) 2017 sql.js authors (see AUTHORS)
4
+
5
+ ### [JSZip](https://github.com/Stuk/jszip)
6
+ JSZip is dual-licensed. You may use it under the MIT license or the GPLv3 license. See [JSZip LICENSE.markdown](https://github.com/Stuk/jszip/blob/master/LICENSE.markdown).
7
+
8
+ ### [FileSaver.js](https://github.com/eligrey/FileSaver.js)
9
+ [The MIT License](https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md)
10
+ <br>Copyright © 2016 Eli Grey.
11
+
12
+ ### [mkanki](https://github.com/nornagon/mkanki)
13
+ [GNU Affero General Public License v3](https://opensource.org/licenses/AGPL-3.0)
14
+ <br>Copyright (c) 2018 Jeremy Apthorp
15
+
16
+ ### [js-sha256](https://github.com/emn178/js-sha256)
17
+ [The MIT License](https://github.com/emn178/js-sha256/blob/master/LICENSE.txt)
18
+ <br>Copyright (c) Chen, Yi-Cyuan 2017
19
+
20
+ ### [genanki](https://github.com/kerrickstaley/genanki)
21
+ [The MIT License](https://github.com/kerrickstaley/genanki/blob/master/LICENSE.txt)
22
+ <br>Copyright (c) Kerrick Staley 2021
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # genanki-js
2
+ A JavaScript implementation for generating Anki decks in browser. This is fork of [mkanki](https://github.com/nornagon/mkanki).
3
+
4
+ # QuickStart
5
+ ```
6
+ npm i genanki-js
7
+ ```
8
+
9
+ ### View sample project to get started
10
+ [genanki-js-template](https://github.com/krmanik/genanki-js/tree/main/sample)
11
+
12
+ # Documentation
13
+ View [Documentation](https://krmanik.github.io/genanki-js)
14
+
15
+ ## CSV/TSV to Anki Package
16
+ Visit page and select `CSV to APKG` from top menu.<br>
17
+ [CSV to APKG](https://krmanik.github.io/genanki-js/demo/index.html)
18
+
19
+ # Set-up a project from scratch
20
+ 1. Install genanki-js
21
+ ```
22
+ npm i genanki-js
23
+ ```
24
+
25
+ 2. Create a `SQL` global variable (may be added to index.js). Sql setup may be different for different JS library. View for react [sql-js/react-sqljs-demo](https://github.com/sql-js/react-sqljs-demo) and read more at [sql.js.org](https://sql.js.org/)
26
+
27
+ ```js
28
+ // The `initSqlJs` function is globally provided by all of the main dist files if loaded in the browser.
29
+ // We must specify this locateFile function if we are loading a wasm file from anywhere other than the current html page's folder.
30
+ config = {
31
+ locateFile: filename => `js/sql/sql-wasm.wasm`
32
+ }
33
+
34
+ let SQL;
35
+ initSqlJs(config).then(function (sql) {
36
+ //Create the database
37
+ SQL = sql;
38
+ });
39
+ ```
40
+
41
+ 3. Now use following `Examples` to generate and export decks.
42
+
43
+ *View more examples here [Examples](https://krmanik.github.io/genanki-js/demo/index.html)*
44
+
45
+ # Examples
46
+ ```js
47
+ var m = new Model({
48
+ name: "Basic (and reversed card)",
49
+ id: "1543634829843",
50
+ flds: [
51
+ { name: "Front" },
52
+ { name: "Back" }
53
+ ],
54
+ req: [
55
+ [ 0, "all", [ 0 ] ],
56
+ [ 1, "all", [ 1 ] ]
57
+ ],
58
+ tmpls: [
59
+ {
60
+ name: "Card 1",
61
+ qfmt: "{{Front}}",
62
+ afmt: "{{FrontSide}}\n\n<hr id=answer>\n\n{{Back}}",
63
+ },
64
+ {
65
+ name: "Card 2",
66
+ qfmt: "{{Back}}",
67
+ afmt: "{{FrontSide}}\n\n<hr id=answer>\n\n{{Front}}",
68
+ }
69
+ ],
70
+ })
71
+
72
+ var d = new Deck(1276438724672, "Test Deck")
73
+
74
+ d.addNote(m.note(['this is front', 'this is back']))
75
+
76
+ var p = new Package()
77
+ p.setSqlJs(SQL); // global SQL variable from step 2 in setup
78
+ p.addDeck(d)
79
+
80
+ p.writeToFile('deck.apkg')
81
+ ```
82
+
83
+ # License
84
+ ### [genanki-js]()
85
+ [GNU Affero General Public License v3](https://opensource.org/licenses/AGPL-3.0)
86
+ <br>Copyright (c) 2021 Mani
87
+
88
+ ## Other Third Party Licenses
89
+ [License.md](https://github.com/krmanik/genanki-js/blob/master/License.md)
@@ -0,0 +1 @@
1
+ import{saveAs}from"file-saver";import{sha256}from"js-sha256";import JSZip from"jszip";import bigInt from"big-integer";const BASE91_TABLE=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","0","1","2","3","4","5","6","7","8","9","!","#","$","%","&","(",")","*","+",",","-",".","/",":",";","<","=",">","?","@","[","]","^","_","`","{","|","}","~"];function ankiHash(n){const e=n.join("__"),t=sha256.create();t.update(e);const o=t.digest();let l=bigInt();for(let n=0;n<8;n++)l*=bigInt("256"),l+=bigInt(o[n]);let s=[];for(;l>0;)s.push(BASE91_TABLE[l%bigInt("91")]),l/=bigInt("91");return s.reverse().join("")}const MODEL_STD=0,MODEL_CLOZE=1;export class Model{constructor(n){this.props={...defaultModel,...n,flds:n.flds.map((n,e)=>({...defaultField,ord:e,...n})),tmpls:n.tmpls.map((n,e)=>({...defaultTemplate,ord:e,name:`Card ${e+1}`,...n})),mod:(new Date).getTime()},this.fieldNameToOrd={},this.props.flds.forEach(n=>{this.fieldNameToOrd[n.name]=n.ord})}note(n,e,t=null){if(Array.isArray(n)){if(n.length!==this.props.flds.length)throw new Error(`Expected ${this.props.flds.length} fields for model '${this.props.name}' but got ${n.length}`);return new Note(this,n,e,t)}{const o=Object.keys(n),l=[];return o.forEach(e=>{const t=this.fieldNameToOrd[e];if(null==t)throw new Error(`Field '${e}' does not exist in the model`);l[t]=n[e]}),new Note(this,l,e,t)}}}export class ClozeModel extends Model{constructor(n){super({type:MODEL_CLOZE,css:"\n .card {\n font-family: arial;\n font-size: 20px;\n text-align: center;\n color: black;\n background-color: white;\n }\n \n .cloze {\n font-weight: bold;\n color: blue;\n }\n ",tmpls:[{name:"Cloze",...n.tmpl}],...n})}}export const defaultModel={sortf:0,did:1,latexPre:"\\documentclass[12pt]{article}\n \\special{papersize=3in,5in}\n \\usepackage[utf8]{inputenc}\n \\usepackage{amssymb,amsmath}\n \\pagestyle{empty}\n \\setlength{\\parindent}{0in}\n \\begin{document}",latexPost:"\\end{document}",mod:0,usn:0,vers:[],type:MODEL_STD,css:".card {\n font-family: arial;\n font-size: 20px;\n text-align: center;\n color: black;\n background-color: white;\n }",tags:[]};export const defaultField={name:"",ord:null,sticky:!1,rtl:!1,font:"Arial",size:20,media:[]};export const defaultTemplate={name:"",ord:null,qfmt:"",afmt:"",did:null,bqfmt:"",bafmt:""};const NEW_CARDS_DISTRIBUTE=0,NEW_CARDS_LAST=1,NEW_CARDS_FIRST=2;export const defaultConf={activeDecks:[1],curDeck:1,newSpread:0,collapseTime:1200,timeLim:0,estTimes:!0,dueCounts:!0,curModel:null,nextPos:1,sortType:"noteFld",sortBackwards:!1,addToCur:!0,dayLearnFirst:!1};const NEW_CARDS_RANDOM=0,NEW_CARDS_DUE=1,STARTING_FACTOR=2500;export const defaultDeckConf={name:"Default",new:{delays:[1,10],ints:[1,4,7],initialFactor:2500,separate:!0,order:1,perDay:20,bury:!1},lapse:{delays:[10],mult:0,minInt:1,leechFails:8,leechAction:0},rev:{perDay:200,ease4:1.3,fuzz:.05,minSpace:1,ivlFct:1,maxIvl:36500,bury:!1,hardFactor:1.2},maxTaken:60,timer:0,autoplay:!0,replayq:!0,mod:0,usn:0};export const defaultDeck={newToday:[0,0],revToday:[0,0],lrnToday:[0,0],timeToday:[0,0],conf:1,usn:0,desc:"",dyn:0,collapsed:!1,extendNew:10,extendRev:50};export class Deck{constructor(n,e,t=""){this.id=n,this.name=e,this.desc=t,this.notes=[]}addNote(n){this.notes.push(n)}}export class Note{constructor(n,e,t=null,o=null){this.model=n,this.fields=e,this.tags=t,this._guid=o}get guid(){return this._guid?this._guid:ankiHash(this.fields)}get cards(){if(this.model.props.type===MODEL_STD){const n=n=>!n||0===n.toString().trim().length,e=[];for(const[t,o,l]of this.model.props.req){l["any"===o?"some":"every"](e=>!n(this.fields[e]))&&e.push(t)}return e}{const n=new Set,e=[],t=/{{[^}]*?cloze:(?:[^}]?:)*(.+?)}}/g,o=/<%cloze:(.+?)%>/g,{qfmt:l}=this.model.props.tmpls[0];let s;for(;s=t.exec(l);)e.push(s[1]);for(;s=o.exec(l);)e.push(s[1]);const i={};this.model.props.flds.forEach((n,e)=>{i[n.name]=[e,n]});for(const t of e){if(!(t in i))continue;const e=i[t][0],o=/{{c(\d+)::.+?}}/gs;for(;s=o.exec(this.fields[e]);){const e=parseInt(s[1]);e>0&&n.add(e-1)}}return 0===n.size?[0]:Array.from(n)}}}export class Package{constructor(){this.db=null,this.decks=[],this.media=[]}setSqlJs(n){this.db=n}addDeck(n){this.decks.push(n)}addMedia(n,e){this.media.push({name:e,data:n})}addMediaFile(n,e=null){this.media.push({name:e||n,filename:n})}writeToFile(n){let e=this.db;e.run(APKG_SCHEMA),this.write(e);let t=new JSZip;const o=e.export(),l=new Uint8Array(o).buffer;t.file("collection.anki2",l);const s={};this.media.forEach((n,e)=>{null!=n.filename?t.file(e.toString(),n.filename):t.file(e.toString(),n.data),s[e]=n.name}),t.file("media",JSON.stringify(s)),t.generateAsync({type:"blob",mimeType:"application/apkg"}).then(function(e){saveAs(e,n)})}write(n){const e=new Date,t={},o={};o[1]={...defaultDeck,id:1,name:"Default"},this.decks.forEach(n=>{n.notes.forEach(n=>t[n.model.props.id]=n.model.props),o[n.id]={...defaultDeck,id:n.id,name:n.name,desc:n.desc}});const l=[null,+e/1e3|0,+e,+e,11,0,0,0,JSON.stringify(defaultConf),JSON.stringify(t),JSON.stringify(o),JSON.stringify({1:{id:1,...defaultDeckConf}}),JSON.stringify({})];n.prepare("INSERT INTO col\n (id, crt, mod, scm, ver, dty, usn, ls, conf, models, decks, dconf, tags)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(l);const s=n.prepare("INSERT INTO notes (id, guid, mid, mod, usn, tags, flds, sfld, csum, flags, data) \n VALUES (null, ?, ?, ?, ?, ?, ?, ?, 0, 0, '')"),i=n.prepare("INSERT INTO cards (id, nid, did, ord, mod, usn, type, queue, due, ivl, factor, reps, lapses, left, odue, odid, flags, data) \n VALUES (null, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0, 0, 0, 0, '')");for(const t of this.decks)for(const o of t.notes){let l=null==o.tags?"":o.tags.join(" ");s.run([o.guid,o.model.props.id,+e/1e3|0,-1,l,o.fields.join(""),0]);let r=n.exec("select last_insert_rowid();")[0].values[0][0];for(const n of o.cards)i.run([r,t.id,n,+e/1e3|0,-1,0,0])}}}export const APKG_SCHEMA="\nPRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n\nCREATE TABLE col (\n id integer primary key,\n crt integer not null,\n mod integer not null,\n scm integer not null,\n ver integer not null,\n dty integer not null,\n usn integer not null,\n ls integer not null,\n conf text not null,\n models text not null,\n decks text not null,\n dconf text not null,\n tags text not null\n);\nCREATE TABLE notes (\n id integer primary key, /* 0 */\n guid text not null, /* 1 */\n mid integer not null, /* 2 */\n mod integer not null, /* 3 */\n usn integer not null, /* 4 */\n tags text not null, /* 5 */\n flds text not null, /* 6 */\n sfld integer not null, /* 7 */\n csum integer not null, /* 8 */\n flags integer not null, /* 9 */\n data text not null /* 10 */\n);\nCREATE TABLE cards (\n id integer primary key, /* 0 */\n nid integer not null, /* 1 */\n did integer not null, /* 2 */\n ord integer not null, /* 3 */\n mod integer not null, /* 4 */\n usn integer not null, /* 5 */\n type integer not null, /* 6 */\n queue integer not null, /* 7 */\n due integer not null, /* 8 */\n ivl integer not null, /* 9 */\n factor integer not null, /* 10 */\n reps integer not null, /* 11 */\n lapses integer not null, /* 12 */\n left integer not null, /* 13 */\n odue integer not null, /* 14 */\n odid integer not null, /* 15 */\n flags integer not null, /* 16 */\n data text not null /* 17 */\n);\nCREATE TABLE revlog (\n id integer primary key,\n cid integer not null,\n usn integer not null,\n ease integer not null,\n ivl integer not null,\n lastIvl integer not null,\n factor integer not null,\n time integer not null,\n type integer not null\n);\nCREATE TABLE graves (\n usn integer not null,\n oid integer not null,\n type integer not null\n);\nCREATE INDEX ix_notes_usn on notes (usn);\nCREATE INDEX ix_cards_usn on cards (usn);\nCREATE INDEX ix_revlog_usn on revlog (usn);\nCREATE INDEX ix_cards_nid on cards (nid);\nCREATE INDEX ix_cards_sched on cards (did, queue, due);\nCREATE INDEX ix_revlog_cid on revlog (cid);\nCREATE INDEX ix_notes_csum on notes (csum);\nCOMMIT;\n";
@@ -0,0 +1,536 @@
1
+ /**
2
+ * [mkanki]{@link https://github.com/nornagon/mkanki}
3
+ * @copyright Copyright (c) 2018 Jeremy Apthorp
4
+ * @license AGPL-3.0 License
5
+ *
6
+ *
7
+ * [genanki]{@link https://github.com/kerrickstaley/genanki}
8
+ * @copyright Copyright (c) Kerrick Staley 2021
9
+ * @license The MIT License
10
+ *
11
+ *
12
+ * [genanki-js]{@link https://github.com/krmanik/genanki-js}
13
+ * @copyright Copyright (c) 2021 Mani
14
+ * @license AGPL-3.0 License
15
+ */
16
+
17
+ import { saveAs } from "file-saver";
18
+ import { sha256 } from "js-sha256";
19
+ import JSZip from "jszip";
20
+ import bigInt from "big-integer";
21
+
22
+ const BASE91_TABLE = [
23
+ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
24
+ 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
25
+ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4',
26
+ '5', '6', '7', '8', '9', '!', '#', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/', ':',
27
+ ';', '<', '=', '>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~']
28
+
29
+ function ankiHash(fields) {
30
+ const str = fields.join('__')
31
+ const h = sha256.create();
32
+ h.update(str)
33
+ const hex = h.digest()
34
+
35
+ let hash_int = bigInt();
36
+ for (let i = 0; i < 8; i++) {
37
+ hash_int *= bigInt("256");
38
+ hash_int += bigInt(hex[i])
39
+ }
40
+
41
+ // convert to the weird base91 format that Anki uses
42
+ let rv_reversed = []
43
+ while (hash_int > 0) {
44
+ rv_reversed.push(BASE91_TABLE[hash_int % bigInt("91")])
45
+ hash_int = (hash_int / bigInt("91"))
46
+ }
47
+
48
+ return rv_reversed.reverse().join('')
49
+ }
50
+
51
+ const MODEL_STD = 0
52
+ const MODEL_CLOZE = 1
53
+
54
+ export class Model {
55
+ constructor(props) {
56
+ this.props = {
57
+ ...defaultModel,
58
+ ...props,
59
+ flds: props.flds.map((f, i) => ({ ...defaultField, ord: i, ...f })),
60
+ tmpls: props.tmpls.map((t, i) => ({ ...defaultTemplate, ord: i, name: `Card ${i + 1}`, ...t })),
61
+ mod: new Date().getTime()
62
+ }
63
+ this.fieldNameToOrd = {}
64
+ this.props.flds.forEach(f => { this.fieldNameToOrd[f.name] = f.ord })
65
+ }
66
+
67
+ note(fields, tags, guid = null) {
68
+ if (Array.isArray(fields)) {
69
+ if (fields.length !== this.props.flds.length) {
70
+ throw new Error(`Expected ${this.props.flds.length} fields for model '${this.props.name}' but got ${fields.length}`)
71
+ }
72
+ return new Note(this, fields, tags, guid)
73
+ } else {
74
+ const field_names = Object.keys(fields)
75
+ const fields_list = []
76
+ field_names.forEach(field_name => {
77
+ const ord = this.fieldNameToOrd[field_name]
78
+ if (ord == null) throw new Error(`Field '${field_name}' does not exist in the model`)
79
+ fields_list[ord] = fields[field_name]
80
+ })
81
+ return new Note(this, fields_list, tags, guid)
82
+ }
83
+ }
84
+ }
85
+
86
+ export class ClozeModel extends Model {
87
+ constructor(props) {
88
+ super({
89
+ type: MODEL_CLOZE,
90
+ css: `
91
+ .card {
92
+ font-family: arial;
93
+ font-size: 20px;
94
+ text-align: center;
95
+ color: black;
96
+ background-color: white;
97
+ }
98
+
99
+ .cloze {
100
+ font-weight: bold;
101
+ color: blue;
102
+ }
103
+ `,
104
+ tmpls: [{ name: "Cloze", ...props.tmpl }],
105
+ ...props
106
+ })
107
+ }
108
+ }
109
+
110
+ export const defaultModel = {
111
+ sortf: 0, // sort field
112
+ did: 1, // deck id
113
+ latexPre: `\\documentclass[12pt]{article}
114
+ \\special{papersize=3in,5in}
115
+ \\usepackage[utf8]{inputenc}
116
+ \\usepackage{amssymb,amsmath}
117
+ \\pagestyle{empty}
118
+ \\setlength{\\parindent}{0in}
119
+ \\begin{document}`,
120
+ latexPost: "\\end{document}",
121
+ mod: 0, // modification time
122
+ usn: 0, // unsure, something to do with sync?
123
+ vers: [], // seems to be unused
124
+ type: MODEL_STD,
125
+ css: `.card {
126
+ font-family: arial;
127
+ font-size: 20px;
128
+ text-align: center;
129
+ color: black;
130
+ background-color: white;
131
+ }`,
132
+ /* also:
133
+ name: string,
134
+ flds: [Field],
135
+ tmpls: [Template],
136
+ tags: [??],
137
+ id: string
138
+ */
139
+ tags: [],
140
+ }
141
+
142
+ export const defaultField = {
143
+ name: "",
144
+ ord: null,
145
+ sticky: false,
146
+ rtl: false,
147
+ font: "Arial",
148
+ size: 20,
149
+ media: [],
150
+ }
151
+
152
+ export const defaultTemplate = {
153
+ name: "",
154
+ ord: null,
155
+ qfmt: "",
156
+ afmt: "",
157
+ did: null,
158
+ bqfmt: "",
159
+ bafmt: "",
160
+ }
161
+
162
+ // whether new cards should be mixed with reviews, or shown first or last
163
+ const NEW_CARDS_DISTRIBUTE = 0
164
+ const NEW_CARDS_LAST = 1
165
+ const NEW_CARDS_FIRST = 2
166
+
167
+ export const defaultConf = {
168
+ // review options
169
+ 'activeDecks': [1],
170
+ 'curDeck': 1,
171
+ 'newSpread': NEW_CARDS_DISTRIBUTE,
172
+ 'collapseTime': 1200,
173
+ 'timeLim': 0,
174
+ 'estTimes': true,
175
+ 'dueCounts': true,
176
+ // other config
177
+ 'curModel': null,
178
+ 'nextPos': 1,
179
+ 'sortType': "noteFld",
180
+ 'sortBackwards': false,
181
+ 'addToCur': true, // add new to currently selected deck?
182
+ 'dayLearnFirst': false,
183
+ }
184
+
185
+
186
+ // new card insertion order
187
+ const NEW_CARDS_RANDOM = 0
188
+ const NEW_CARDS_DUE = 1
189
+
190
+ const STARTING_FACTOR = 2500
191
+
192
+ export const defaultDeckConf = {
193
+ 'name': "Default",
194
+ 'new': {
195
+ 'delays': [1, 10],
196
+ 'ints': [1, 4, 7], // 7 is not currently used
197
+ 'initialFactor': STARTING_FACTOR,
198
+ 'separate': true,
199
+ 'order': NEW_CARDS_DUE,
200
+ 'perDay': 20,
201
+ // may not be set on old decks
202
+ 'bury': false,
203
+ },
204
+ 'lapse': {
205
+ 'delays': [10],
206
+ 'mult': 0,
207
+ 'minInt': 1,
208
+ 'leechFails': 8,
209
+ // type 0=suspend, 1=tagonly
210
+ 'leechAction': 0,
211
+ },
212
+ 'rev': {
213
+ 'perDay': 200,
214
+ 'ease4': 1.3,
215
+ 'fuzz': 0.05,
216
+ 'minSpace': 1, // not currently used
217
+ 'ivlFct': 1,
218
+ 'maxIvl': 36500,
219
+ // may not be set on old decks
220
+ 'bury': false,
221
+ 'hardFactor': 1.2,
222
+ },
223
+ 'maxTaken': 60,
224
+ 'timer': 0,
225
+ 'autoplay': true,
226
+ 'replayq': true,
227
+ 'mod': 0,
228
+ 'usn': 0,
229
+ }
230
+
231
+ export const defaultDeck = {
232
+ newToday: [0, 0], // currentDay, count
233
+ revToday: [0, 0],
234
+ lrnToday: [0, 0],
235
+ timeToday: [0, 0], // time in ms
236
+ conf: 1,
237
+ usn: 0,
238
+ desc: "",
239
+ dyn: 0, // anki uses int/bool interchangably here
240
+ collapsed: false,
241
+ // added in beta11
242
+ extendNew: 10,
243
+ extendRev: 50,
244
+ }
245
+
246
+ export class Deck {
247
+ constructor(id, name, desc="") {
248
+ this.id = id
249
+ this.name = name
250
+ this.desc = desc
251
+ this.notes = []
252
+ }
253
+
254
+ addNote(note) {
255
+ this.notes.push(note)
256
+ }
257
+ }
258
+
259
+ export class Note {
260
+ constructor(model, fields, tags = null, guid = null) {
261
+ this.model = model
262
+ this.fields = fields
263
+ this.tags = tags
264
+ this._guid = guid
265
+ }
266
+
267
+ get guid() {
268
+ return this._guid ? this._guid : ankiHash(this.fields);
269
+ }
270
+
271
+ get cards() {
272
+ if (this.model.props.type === MODEL_STD) {
273
+ const isEmpty = f => {
274
+ return !f || f.toString().trim().length === 0
275
+ }
276
+ const rv = []
277
+ for (const [card_ord, any_or_all, required_field_ords] of this.model.props.req) {
278
+ const op = any_or_all === "any" ? "some" : "every"
279
+ if (required_field_ords[op](f => !isEmpty(this.fields[f]))) {
280
+ rv.push(card_ord)
281
+ }
282
+ }
283
+ return rv
284
+ } else {
285
+ // the below logic is copied from anki's ModelManager._availClozeOrds
286
+ const ords = new Set()
287
+ const matches = []
288
+ const curliesRe = /{{[^}]*?cloze:(?:[^}]?:)*(.+?)}}/g
289
+ const percentRe = /<%cloze:(.+?)%>/g
290
+ const { qfmt } = this.model.props.tmpls[0] // cloze models only have 1 template
291
+ let m;
292
+ while (m = curliesRe.exec(qfmt))
293
+ matches.push(m[1])
294
+ while (m = percentRe.exec(qfmt))
295
+ matches.push(m[1])
296
+ const map = {}
297
+ this.model.props.flds.forEach((fld, i) => {
298
+ map[fld.name] = [i, fld]
299
+ })
300
+ for (const fname of matches) {
301
+ if (!(fname in map)) continue
302
+ const ord = map[fname][0]
303
+ const re = /{{c(\d+)::.+?}}/gs
304
+ while (m = re.exec(this.fields[ord])) {
305
+ const i = parseInt(m[1])
306
+ if (i > 0)
307
+ ords.add(i - 1)
308
+ }
309
+ }
310
+ if (ords.size === 0) {
311
+ // empty clozes use first ord
312
+ return [0]
313
+ }
314
+ return Array.from(ords)
315
+ }
316
+ }
317
+ }
318
+
319
+ export class Package {
320
+ constructor() {
321
+ this.db = null;
322
+ this.decks = []
323
+ this.media = []
324
+ }
325
+
326
+ setSqlJs(SQL) {
327
+ this.db = SQL;
328
+ }
329
+
330
+ addDeck(deck) {
331
+ this.decks.push(deck)
332
+ }
333
+
334
+ addMedia(data, name) {
335
+ this.media.push({ name, data })
336
+ }
337
+
338
+ addMediaFile(filename, name = null) {
339
+ this.media.push({ name: name || filename, filename })
340
+ }
341
+
342
+ writeToFile(filename) {
343
+ let db = this.db;
344
+ db.run(APKG_SCHEMA);
345
+
346
+ this.write(db)
347
+
348
+ let zip = new JSZip();
349
+
350
+ const data = db.export();
351
+ const buffer = new Uint8Array(data).buffer;
352
+
353
+ zip.file("collection.anki2", buffer);
354
+
355
+ const media_info = {}
356
+
357
+ this.media.forEach((m, i) => {
358
+ if (m.filename != null) {
359
+ zip.file(i.toString(), m.filename)
360
+ } else {
361
+ zip.file(i.toString(), m.data)
362
+ }
363
+
364
+ media_info[i] = m.name
365
+ })
366
+
367
+ zip.file('media', JSON.stringify(media_info))
368
+
369
+ zip.generateAsync({ type: "blob", mimeType: "application/apkg" }).then(function (content) {
370
+ // see FileSaver.js
371
+ saveAs(content, filename);
372
+ });
373
+ }
374
+
375
+
376
+ write(db) {
377
+ const now = new Date
378
+ const models = {}
379
+ const decks = {}
380
+
381
+ // AnkiDroid failed to import subdeck, So add a Default deck
382
+ decks["1"] = {...defaultDeck, id: 1, name: "Default"}
383
+
384
+ this.decks.forEach(d => {
385
+ d.notes.forEach(n => models[n.model.props.id] = n.model.props)
386
+ decks[d.id] = {
387
+ ...defaultDeck,
388
+ id: d.id,
389
+ name: d.name,
390
+ desc: d.desc,
391
+ }
392
+ })
393
+
394
+ const col = [
395
+ null, // id
396
+ (+now / 1000) | 0, // crt
397
+ +now, // mod
398
+ +now, // scm
399
+ 11, // ver
400
+ 0, // dty
401
+ 0, // usn
402
+ 0, // ls
403
+ JSON.stringify(defaultConf), // conf
404
+ JSON.stringify(models), // models
405
+ JSON.stringify(decks), // decks
406
+ JSON.stringify({ 1: { id: 1, ...defaultDeckConf } }), // dconf
407
+ JSON.stringify({}), // tags
408
+ ]
409
+
410
+ db.prepare(`INSERT INTO col
411
+ (id, crt, mod, scm, ver, dty, usn, ls, conf, models, decks, dconf, tags)
412
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(col)
413
+
414
+ const insert_notes = db.prepare(`INSERT INTO notes (id, guid, mid, mod, usn, tags, flds, sfld, csum, flags, data)
415
+ VALUES (null, ?, ?, ?, ?, ?, ?, ?, 0, 0, '')`)
416
+
417
+ const insert_cards = db.prepare(`INSERT INTO cards (id, nid, did, ord, mod, usn, type, queue, due, ivl, factor, reps, lapses, left, odue, odid, flags, data)
418
+ VALUES (null, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0, 0, 0, 0, '')`)
419
+
420
+ for (const deck of this.decks) {
421
+ for (const note of deck.notes) {
422
+ let tags = note.tags == null ? '' : note.tags.join(' ')
423
+ insert_notes.run(
424
+ [
425
+ note.guid, // guid
426
+ note.model.props.id, // mid
427
+ (+now / 1000) | 0, // mod
428
+ -1, // usn
429
+ tags, // tags
430
+ note.fields.join('\x1f'), // flds
431
+ 0, // sfld
432
+ ])
433
+
434
+ let rowID = db.exec("select last_insert_rowid();")
435
+ let note_id = rowID[0]['values'][0][0];
436
+
437
+ for (const card_ord of note.cards) {
438
+ insert_cards.run(
439
+ [
440
+ note_id, // nid
441
+ deck.id, // did
442
+ card_ord, // ord
443
+ (+now / 1000) | 0, // mod
444
+ -1, // usn
445
+ 0, // type 0=new, 1=learning, 2=due
446
+ 0, // queue -1 for suspended
447
+ ])
448
+ }
449
+ }
450
+ }
451
+ }
452
+ }
453
+
454
+ /*
455
+ * [genanki]{@link https://github.com/kerrickstaley/genanki}
456
+ * @copyright Copyright (c) Kerrick Staley 2021
457
+ * @license The MIT License
458
+ */
459
+
460
+ export const APKG_SCHEMA = `
461
+ PRAGMA foreign_keys=OFF;
462
+ BEGIN TRANSACTION;
463
+
464
+ CREATE TABLE col (
465
+ id integer primary key,
466
+ crt integer not null,
467
+ mod integer not null,
468
+ scm integer not null,
469
+ ver integer not null,
470
+ dty integer not null,
471
+ usn integer not null,
472
+ ls integer not null,
473
+ conf text not null,
474
+ models text not null,
475
+ decks text not null,
476
+ dconf text not null,
477
+ tags text not null
478
+ );
479
+ CREATE TABLE notes (
480
+ id integer primary key, /* 0 */
481
+ guid text not null, /* 1 */
482
+ mid integer not null, /* 2 */
483
+ mod integer not null, /* 3 */
484
+ usn integer not null, /* 4 */
485
+ tags text not null, /* 5 */
486
+ flds text not null, /* 6 */
487
+ sfld integer not null, /* 7 */
488
+ csum integer not null, /* 8 */
489
+ flags integer not null, /* 9 */
490
+ data text not null /* 10 */
491
+ );
492
+ CREATE TABLE cards (
493
+ id integer primary key, /* 0 */
494
+ nid integer not null, /* 1 */
495
+ did integer not null, /* 2 */
496
+ ord integer not null, /* 3 */
497
+ mod integer not null, /* 4 */
498
+ usn integer not null, /* 5 */
499
+ type integer not null, /* 6 */
500
+ queue integer not null, /* 7 */
501
+ due integer not null, /* 8 */
502
+ ivl integer not null, /* 9 */
503
+ factor integer not null, /* 10 */
504
+ reps integer not null, /* 11 */
505
+ lapses integer not null, /* 12 */
506
+ left integer not null, /* 13 */
507
+ odue integer not null, /* 14 */
508
+ odid integer not null, /* 15 */
509
+ flags integer not null, /* 16 */
510
+ data text not null /* 17 */
511
+ );
512
+ CREATE TABLE revlog (
513
+ id integer primary key,
514
+ cid integer not null,
515
+ usn integer not null,
516
+ ease integer not null,
517
+ ivl integer not null,
518
+ lastIvl integer not null,
519
+ factor integer not null,
520
+ time integer not null,
521
+ type integer not null
522
+ );
523
+ CREATE TABLE graves (
524
+ usn integer not null,
525
+ oid integer not null,
526
+ type integer not null
527
+ );
528
+ CREATE INDEX ix_notes_usn on notes (usn);
529
+ CREATE INDEX ix_cards_usn on cards (usn);
530
+ CREATE INDEX ix_revlog_usn on revlog (usn);
531
+ CREATE INDEX ix_cards_nid on cards (nid);
532
+ CREATE INDEX ix_cards_sched on cards (did, queue, due);
533
+ CREATE INDEX ix_revlog_cid on revlog (cid);
534
+ CREATE INDEX ix_notes_csum on notes (csum);
535
+ COMMIT;
536
+ `;
@@ -0,0 +1,28 @@
1
+ const BASE91_TABLE = [
2
+ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
3
+ 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
4
+ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4',
5
+ '5', '6', '7', '8', '9', '!', '#', '$', '%', '&', '(', ')', '*', '+', ',', '-', '.', '/', ':',
6
+ ';', '<', '=', '>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~']
7
+
8
+ function ankiHash(fields) {
9
+ const str = fields.join('__')
10
+ const h = sha256.create();
11
+ h.update(str)
12
+ const hex = h.digest()
13
+
14
+ let hash_int = bigInt();
15
+ for (let i = 0; i < 8; i++) {
16
+ hash_int *= bigInt("256");
17
+ hash_int += bigInt(hex[i])
18
+ }
19
+
20
+ // convert to the weird base91 format that Anki uses
21
+ let rv_reversed = []
22
+ while (hash_int > 0) {
23
+ rv_reversed.push(BASE91_TABLE[hash_int % bigInt("91")])
24
+ hash_int = (hash_int / bigInt("91"))
25
+ }
26
+
27
+ return rv_reversed.reverse().join('')
28
+ }
@@ -0,0 +1,83 @@
1
+ /*
2
+ * [genanki]{@link https://github.com/kerrickstaley/genanki}
3
+ * @copyright Copyright (c) Kerrick Staley 2021
4
+ * @license The MIT License
5
+ */
6
+
7
+ export const APKG_SCHEMA = `
8
+ PRAGMA foreign_keys=OFF;
9
+ BEGIN TRANSACTION;
10
+
11
+ CREATE TABLE col (
12
+ id integer primary key,
13
+ crt integer not null,
14
+ mod integer not null,
15
+ scm integer not null,
16
+ ver integer not null,
17
+ dty integer not null,
18
+ usn integer not null,
19
+ ls integer not null,
20
+ conf text not null,
21
+ models text not null,
22
+ decks text not null,
23
+ dconf text not null,
24
+ tags text not null
25
+ );
26
+ CREATE TABLE notes (
27
+ id integer primary key, /* 0 */
28
+ guid text not null, /* 1 */
29
+ mid integer not null, /* 2 */
30
+ mod integer not null, /* 3 */
31
+ usn integer not null, /* 4 */
32
+ tags text not null, /* 5 */
33
+ flds text not null, /* 6 */
34
+ sfld integer not null, /* 7 */
35
+ csum integer not null, /* 8 */
36
+ flags integer not null, /* 9 */
37
+ data text not null /* 10 */
38
+ );
39
+ CREATE TABLE cards (
40
+ id integer primary key, /* 0 */
41
+ nid integer not null, /* 1 */
42
+ did integer not null, /* 2 */
43
+ ord integer not null, /* 3 */
44
+ mod integer not null, /* 4 */
45
+ usn integer not null, /* 5 */
46
+ type integer not null, /* 6 */
47
+ queue integer not null, /* 7 */
48
+ due integer not null, /* 8 */
49
+ ivl integer not null, /* 9 */
50
+ factor integer not null, /* 10 */
51
+ reps integer not null, /* 11 */
52
+ lapses integer not null, /* 12 */
53
+ left integer not null, /* 13 */
54
+ odue integer not null, /* 14 */
55
+ odid integer not null, /* 15 */
56
+ flags integer not null, /* 16 */
57
+ data text not null /* 17 */
58
+ );
59
+ CREATE TABLE revlog (
60
+ id integer primary key,
61
+ cid integer not null,
62
+ usn integer not null,
63
+ ease integer not null,
64
+ ivl integer not null,
65
+ lastIvl integer not null,
66
+ factor integer not null,
67
+ time integer not null,
68
+ type integer not null
69
+ );
70
+ CREATE TABLE graves (
71
+ usn integer not null,
72
+ oid integer not null,
73
+ type integer not null
74
+ );
75
+ CREATE INDEX ix_notes_usn on notes (usn);
76
+ CREATE INDEX ix_cards_usn on cards (usn);
77
+ CREATE INDEX ix_revlog_usn on revlog (usn);
78
+ CREATE INDEX ix_cards_nid on cards (nid);
79
+ CREATE INDEX ix_cards_sched on cards (did, queue, due);
80
+ CREATE INDEX ix_revlog_cid on revlog (cid);
81
+ CREATE INDEX ix_notes_csum on notes (csum);
82
+ COMMIT;
83
+ `;
@@ -0,0 +1,12 @@
1
+ export class Deck {
2
+ constructor(id, name, desc="") {
3
+ this.id = id
4
+ this.name = name
5
+ this.desc = desc
6
+ this.notes = []
7
+ }
8
+
9
+ addNote(note) {
10
+ this.notes.push(note)
11
+ }
12
+ }
@@ -0,0 +1,135 @@
1
+ export const defaultModel = {
2
+ sortf: 0, // sort field
3
+ did: 1, // deck id
4
+ latexPre: `\\documentclass[12pt]{article}
5
+ \\special{papersize=3in,5in}
6
+ \\usepackage[utf8]{inputenc}
7
+ \\usepackage{amssymb,amsmath}
8
+ \\pagestyle{empty}
9
+ \\setlength{\\parindent}{0in}
10
+ \\begin{document}`,
11
+ latexPost: "\\end{document}",
12
+ mod: 0, // modification time
13
+ usn: 0, // unsure, something to do with sync?
14
+ vers: [], // seems to be unused
15
+ type: MODEL_STD,
16
+ css: `.card {
17
+ font-family: arial;
18
+ font-size: 20px;
19
+ text-align: center;
20
+ color: black;
21
+ background-color: white;
22
+ }`,
23
+ /* also:
24
+ name: string,
25
+ flds: [Field],
26
+ tmpls: [Template],
27
+ tags: [??],
28
+ id: string
29
+ */
30
+ tags: [],
31
+ }
32
+
33
+ export const defaultField = {
34
+ name: "",
35
+ ord: null,
36
+ sticky: false,
37
+ rtl: false,
38
+ font: "Arial",
39
+ size: 20,
40
+ media: [],
41
+ }
42
+
43
+ export const defaultTemplate = {
44
+ name: "",
45
+ ord: null,
46
+ qfmt: "",
47
+ afmt: "",
48
+ did: null,
49
+ bqfmt: "",
50
+ bafmt: "",
51
+ }
52
+
53
+ // whether new cards should be mixed with reviews, or shown first or last
54
+ const NEW_CARDS_DISTRIBUTE = 0
55
+ const NEW_CARDS_LAST = 1
56
+ const NEW_CARDS_FIRST = 2
57
+
58
+ export const defaultConf = {
59
+ // review options
60
+ 'activeDecks': [1],
61
+ 'curDeck': 1,
62
+ 'newSpread': NEW_CARDS_DISTRIBUTE,
63
+ 'collapseTime': 1200,
64
+ 'timeLim': 0,
65
+ 'estTimes': true,
66
+ 'dueCounts': true,
67
+ // other config
68
+ 'curModel': null,
69
+ 'nextPos': 1,
70
+ 'sortType': "noteFld",
71
+ 'sortBackwards': false,
72
+ 'addToCur': true, // add new to currently selected deck?
73
+ 'dayLearnFirst': false,
74
+ }
75
+
76
+
77
+ // new card insertion order
78
+ const NEW_CARDS_RANDOM = 0
79
+ const NEW_CARDS_DUE = 1
80
+
81
+ const STARTING_FACTOR = 2500
82
+
83
+ export const defaultDeckConf = {
84
+ 'name': "Default",
85
+ 'new': {
86
+ 'delays': [1, 10],
87
+ 'ints': [1, 4, 7], // 7 is not currently used
88
+ 'initialFactor': STARTING_FACTOR,
89
+ 'separate': true,
90
+ 'order': NEW_CARDS_DUE,
91
+ 'perDay': 20,
92
+ // may not be set on old decks
93
+ 'bury': false,
94
+ },
95
+ 'lapse': {
96
+ 'delays': [10],
97
+ 'mult': 0,
98
+ 'minInt': 1,
99
+ 'leechFails': 8,
100
+ // type 0=suspend, 1=tagonly
101
+ 'leechAction': 0,
102
+ },
103
+ 'rev': {
104
+ 'perDay': 200,
105
+ 'ease4': 1.3,
106
+ 'fuzz': 0.05,
107
+ 'minSpace': 1, // not currently used
108
+ 'ivlFct': 1,
109
+ 'maxIvl': 36500,
110
+ // may not be set on old decks
111
+ 'bury': false,
112
+ 'hardFactor': 1.2,
113
+ },
114
+ 'maxTaken': 60,
115
+ 'timer': 0,
116
+ 'autoplay': true,
117
+ 'replayq': true,
118
+ 'mod': 0,
119
+ 'usn': 0,
120
+ }
121
+
122
+ export const defaultDeck = {
123
+ newToday: [0, 0], // currentDay, count
124
+ revToday: [0, 0],
125
+ lrnToday: [0, 0],
126
+ timeToday: [0, 0], // time in ms
127
+ conf: 1,
128
+ usn: 0,
129
+ desc: "",
130
+ dyn: 0, // anki uses int/bool interchangably here
131
+ collapsed: false,
132
+ // added in beta11
133
+ extendNew: 10,
134
+ extendRev: 50,
135
+ }
@@ -0,0 +1,4 @@
1
+ import { saveAs } from "file-saver";
2
+ import { sha256 } from "js-sha256";
3
+ import JSZip from "jszip";
4
+ import bigInt from "big-integer";
@@ -0,0 +1,15 @@
1
+ /**
2
+ * [mkanki]{@link https://github.com/nornagon/mkanki}
3
+ * @copyright Copyright (c) 2018 Jeremy Apthorp
4
+ * @license AGPL-3.0 License
5
+ *
6
+ *
7
+ * [genanki]{@link https://github.com/kerrickstaley/genanki}
8
+ * @copyright Copyright (c) Kerrick Staley 2021
9
+ * @license The MIT License
10
+ *
11
+ *
12
+ * [genanki-js]{@link https://github.com/krmanik/genanki-js}
13
+ * @copyright Copyright (c) 2021 Mani
14
+ * @license AGPL-3.0 License
15
+ */
@@ -0,0 +1,58 @@
1
+ const MODEL_STD = 0
2
+ const MODEL_CLOZE = 1
3
+
4
+ export class Model {
5
+ constructor(props) {
6
+ this.props = {
7
+ ...defaultModel,
8
+ ...props,
9
+ flds: props.flds.map((f, i) => ({ ...defaultField, ord: i, ...f })),
10
+ tmpls: props.tmpls.map((t, i) => ({ ...defaultTemplate, ord: i, name: `Card ${i + 1}`, ...t })),
11
+ mod: new Date().getTime()
12
+ }
13
+ this.fieldNameToOrd = {}
14
+ this.props.flds.forEach(f => { this.fieldNameToOrd[f.name] = f.ord })
15
+ }
16
+
17
+ note(fields, tags, guid = null) {
18
+ if (Array.isArray(fields)) {
19
+ if (fields.length !== this.props.flds.length) {
20
+ throw new Error(`Expected ${this.props.flds.length} fields for model '${this.props.name}' but got ${fields.length}`)
21
+ }
22
+ return new Note(this, fields, tags, guid)
23
+ } else {
24
+ const field_names = Object.keys(fields)
25
+ const fields_list = []
26
+ field_names.forEach(field_name => {
27
+ const ord = this.fieldNameToOrd[field_name]
28
+ if (ord == null) throw new Error(`Field '${field_name}' does not exist in the model`)
29
+ fields_list[ord] = fields[field_name]
30
+ })
31
+ return new Note(this, fields_list, tags, guid)
32
+ }
33
+ }
34
+ }
35
+
36
+ export class ClozeModel extends Model {
37
+ constructor(props) {
38
+ super({
39
+ type: MODEL_CLOZE,
40
+ css: `
41
+ .card {
42
+ font-family: arial;
43
+ font-size: 20px;
44
+ text-align: center;
45
+ color: black;
46
+ background-color: white;
47
+ }
48
+
49
+ .cloze {
50
+ font-weight: bold;
51
+ color: blue;
52
+ }
53
+ `,
54
+ tmpls: [{ name: "Cloze", ...props.tmpl }],
55
+ ...props
56
+ })
57
+ }
58
+ }
@@ -0,0 +1,59 @@
1
+ export class Note {
2
+ constructor(model, fields, tags = null, guid = null) {
3
+ this.model = model
4
+ this.fields = fields
5
+ this.tags = tags
6
+ this._guid = guid
7
+ }
8
+
9
+ get guid() {
10
+ return this._guid ? this._guid : ankiHash(this.fields);
11
+ }
12
+
13
+ get cards() {
14
+ if (this.model.props.type === MODEL_STD) {
15
+ const isEmpty = f => {
16
+ return !f || f.toString().trim().length === 0
17
+ }
18
+ const rv = []
19
+ for (const [card_ord, any_or_all, required_field_ords] of this.model.props.req) {
20
+ const op = any_or_all === "any" ? "some" : "every"
21
+ if (required_field_ords[op](f => !isEmpty(this.fields[f]))) {
22
+ rv.push(card_ord)
23
+ }
24
+ }
25
+ return rv
26
+ } else {
27
+ // the below logic is copied from anki's ModelManager._availClozeOrds
28
+ const ords = new Set()
29
+ const matches = []
30
+ const curliesRe = /{{[^}]*?cloze:(?:[^}]?:)*(.+?)}}/g
31
+ const percentRe = /<%cloze:(.+?)%>/g
32
+ const { qfmt } = this.model.props.tmpls[0] // cloze models only have 1 template
33
+ let m;
34
+ while (m = curliesRe.exec(qfmt))
35
+ matches.push(m[1])
36
+ while (m = percentRe.exec(qfmt))
37
+ matches.push(m[1])
38
+ const map = {}
39
+ this.model.props.flds.forEach((fld, i) => {
40
+ map[fld.name] = [i, fld]
41
+ })
42
+ for (const fname of matches) {
43
+ if (!(fname in map)) continue
44
+ const ord = map[fname][0]
45
+ const re = /{{c(\d+)::.+?}}/gs
46
+ while (m = re.exec(this.fields[ord])) {
47
+ const i = parseInt(m[1])
48
+ if (i > 0)
49
+ ords.add(i - 1)
50
+ }
51
+ }
52
+ if (ords.size === 0) {
53
+ // empty clozes use first ord
54
+ return [0]
55
+ }
56
+ return Array.from(ords)
57
+ }
58
+ }
59
+ }
@@ -0,0 +1,134 @@
1
+ export class Package {
2
+ constructor() {
3
+ this.db = null;
4
+ this.decks = []
5
+ this.media = []
6
+ }
7
+
8
+ setSqlJs(SQL) {
9
+ this.db = SQL;
10
+ }
11
+
12
+ addDeck(deck) {
13
+ this.decks.push(deck)
14
+ }
15
+
16
+ addMedia(data, name) {
17
+ this.media.push({ name, data })
18
+ }
19
+
20
+ addMediaFile(filename, name = null) {
21
+ this.media.push({ name: name || filename, filename })
22
+ }
23
+
24
+ writeToFile(filename) {
25
+ let db = this.db;
26
+ db.run(APKG_SCHEMA);
27
+
28
+ this.write(db)
29
+
30
+ let zip = new JSZip();
31
+
32
+ const data = db.export();
33
+ const buffer = new Uint8Array(data).buffer;
34
+
35
+ zip.file("collection.anki2", buffer);
36
+
37
+ const media_info = {}
38
+
39
+ this.media.forEach((m, i) => {
40
+ if (m.filename != null) {
41
+ zip.file(i.toString(), m.filename)
42
+ } else {
43
+ zip.file(i.toString(), m.data)
44
+ }
45
+
46
+ media_info[i] = m.name
47
+ })
48
+
49
+ zip.file('media', JSON.stringify(media_info))
50
+
51
+ zip.generateAsync({ type: "blob", mimeType: "application/apkg" }).then(function (content) {
52
+ // see FileSaver.js
53
+ saveAs(content, filename);
54
+ });
55
+ }
56
+
57
+
58
+ write(db) {
59
+ const now = new Date
60
+ const models = {}
61
+ const decks = {}
62
+
63
+ // AnkiDroid failed to import subdeck, So add a Default deck
64
+ decks["1"] = {...defaultDeck, id: 1, name: "Default"}
65
+
66
+ this.decks.forEach(d => {
67
+ d.notes.forEach(n => models[n.model.props.id] = n.model.props)
68
+ decks[d.id] = {
69
+ ...defaultDeck,
70
+ id: d.id,
71
+ name: d.name,
72
+ desc: d.desc,
73
+ }
74
+ })
75
+
76
+ const col = [
77
+ null, // id
78
+ (+now / 1000) | 0, // crt
79
+ +now, // mod
80
+ +now, // scm
81
+ 11, // ver
82
+ 0, // dty
83
+ 0, // usn
84
+ 0, // ls
85
+ JSON.stringify(defaultConf), // conf
86
+ JSON.stringify(models), // models
87
+ JSON.stringify(decks), // decks
88
+ JSON.stringify({ 1: { id: 1, ...defaultDeckConf } }), // dconf
89
+ JSON.stringify({}), // tags
90
+ ]
91
+
92
+ db.prepare(`INSERT INTO col
93
+ (id, crt, mod, scm, ver, dty, usn, ls, conf, models, decks, dconf, tags)
94
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(col)
95
+
96
+ const insert_notes = db.prepare(`INSERT INTO notes (id, guid, mid, mod, usn, tags, flds, sfld, csum, flags, data)
97
+ VALUES (null, ?, ?, ?, ?, ?, ?, ?, 0, 0, '')`)
98
+
99
+ const insert_cards = db.prepare(`INSERT INTO cards (id, nid, did, ord, mod, usn, type, queue, due, ivl, factor, reps, lapses, left, odue, odid, flags, data)
100
+ VALUES (null, ?, ?, ?, ?, ?, ?, ?, 0, 0, 0, 0, 0, 0, 0, 0, 0, '')`)
101
+
102
+ for (const deck of this.decks) {
103
+ for (const note of deck.notes) {
104
+ let tags = note.tags == null ? '' : note.tags.join(' ')
105
+ insert_notes.run(
106
+ [
107
+ note.guid, // guid
108
+ note.model.props.id, // mid
109
+ (+now / 1000) | 0, // mod
110
+ -1, // usn
111
+ tags, // tags
112
+ note.fields.join('\x1f'), // flds
113
+ 0, // sfld
114
+ ])
115
+
116
+ let rowID = db.exec("select last_insert_rowid();")
117
+ let note_id = rowID[0]['values'][0][0];
118
+
119
+ for (const card_ord of note.cards) {
120
+ insert_cards.run(
121
+ [
122
+ note_id, // nid
123
+ deck.id, // did
124
+ card_ord, // ord
125
+ (+now / 1000) | 0, // mod
126
+ -1, // usn
127
+ 0, // type 0=new, 1=learning, 2=due
128
+ 0, // queue -1 for suspended
129
+ ])
130
+ }
131
+ }
132
+ }
133
+ }
134
+ }
package/gulpfile.js ADDED
@@ -0,0 +1,28 @@
1
+ const {src, dest} = require('gulp');
2
+ const concat = require('gulp-concat');
3
+ const minify = require("gulp-minify");
4
+
5
+ const jsFiles = [
6
+ './genanki/license.js',
7
+ './genanki/import.js',
8
+ './genanki/anki_hash.js',
9
+ './genanki/model.js',
10
+ './genanki/default.js',
11
+ './genanki/deck.js',
12
+ './genanki/note.js',
13
+ './genanki/package.js',
14
+ './genanki/apkg_schema.js'
15
+ ]
16
+
17
+ const bundleJs = () => {
18
+ return src(jsFiles)
19
+ // bundle all js files in genanki folder in genanki.js file
20
+ .pipe(concat('genanki.js'))
21
+ .pipe(minify({}))
22
+ // write genanki.js to dist, demo and sample folder
23
+ .pipe(dest('./dist'))
24
+ //.pipe(dest('./docs/demo/js/anki'))
25
+ //.pipe(dest('./sample/js/anki'))
26
+ }
27
+
28
+ exports.bundleJs = bundleJs;
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "genanki-js",
3
+ "version": "2.0.0",
4
+ "description": "A JavaScript implementation for generating Anki decks in browser client side",
5
+ "main": "dist/genanki.js",
6
+ "directories": {
7
+ "doc": "docs"
8
+ },
9
+ "scripts": {
10
+ "test": "echo \"Error: no test specified\" && exit 1"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/krmanik/genanki-js.git"
15
+ },
16
+ "keywords": [
17
+ "genanki",
18
+ "anki"
19
+ ],
20
+ "author": "Mani",
21
+ "license": "AGPL-3.0-or-later",
22
+ "bugs": {
23
+ "url": "https://github.com/krmanik/genanki-js/issues"
24
+ },
25
+ "homepage": "https://github.com/krmanik/genanki-js#readme",
26
+ "dependencies": {
27
+ "big-integer": "^1.6.51",
28
+ "file-saver": "^2.0.5",
29
+ "gulp": "^4.0.2",
30
+ "gulp-concat": "^2.6.1",
31
+ "gulp-minify": "^3.1.0",
32
+ "js-sha256": "^0.9.0",
33
+ "jszip": "^3.9.1",
34
+ "sql.js": "^1.6.2"
35
+ }
36
+ }