anki-reader
Version:
A library for reading Anki apkg and collection files.
125 lines (124 loc) • 3.2 kB
JavaScript
import { Question } from './Question.js';
export class Card {
id;
cardData;
collection;
deckId;
noteId;
rawFields;
orderedFields;
fields;
modelId;
model;
questions;
constructor(id, cardData, collection) {
this.id = id;
this.cardData = cardData;
this.collection = collection;
}
getId() {
return this.id;
}
getDeckId() {
if (this.deckId != null) {
return this.deckId;
}
const result = this.cardData.did?.toString() ?? '';
this.deckId = result;
return this.deckId;
}
getNoteId() {
if (this.noteId != null) {
return this.noteId;
}
const result = this.cardData.nid?.toString() ?? '';
this.noteId = result;
return this.noteId;
}
getRawFields() {
if (this.rawFields != null) {
return this.rawFields;
}
const result = this.cardData.flds?.toString() ?? '';
this.rawFields = result;
return this.rawFields;
}
getOrderedFields() {
if (this.orderedFields != null) {
return [
...this.orderedFields
];
}
const result = this.getRawFields().split('\x1f');
this.orderedFields = result;
return [
...this.orderedFields
];
}
getFields() {
if (this.fields != null) {
return {
...this.fields
};
}
const model = this.getModel();
const orderedFields = this.getOrderedFields();
const result = {};
for (let i = 0; i < orderedFields.length; i++) {
if (i >= model.getFields().length) {
break;
}
result[model.getFields()[i].name] = orderedFields[i];
}
this.fields = result;
return {
...this.fields
};
}
getFront() {
return this.getOrderedFields()[0];
}
getBack() {
return this.getOrderedFields()[1];
}
getModelId() {
if (this.modelId != null) {
return this.modelId;
}
const result = this.cardData.mid?.toString() ?? '';
this.modelId = result;
return this.modelId;
}
getModel() {
if (this.model != null) {
return this.model;
}
const result = this.collection.getModels()[this.getModelId()];
this.model = result;
return this.model;
}
getQuestions() {
if (this.questions != null) {
return [
...this.questions
];
}
const questions = [];
const model = this.getModel();
const fields = this.getFields();
for (const template of model.getTemplates()) {
const question = new Question(fields, template, model);
if (question.getQuestionString() === '') {
continue;
}
questions.push(question);
}
this.questions = questions;
return [
...this.questions
];
}
getRawCard() {
return this.cardData;
}
}