Files
notesnook/packages/core/collections/topics.js

59 lines
1.4 KiB
JavaScript
Raw Normal View History

2020-02-04 18:27:32 +05:00
import Notebooks from "./notebooks";
import Notes from "./notes";
2020-02-05 20:57:43 +05:00
import Topic from "../models/topic";
2020-02-04 18:27:32 +05:00
export default class Topics {
/**
*
* @param {Notebooks} notebooks
2020-02-05 00:17:12 +05:00
* @param {Notes} notes
2020-02-04 18:27:32 +05:00
* @param {string} notebookId
*/
2020-02-05 00:17:12 +05:00
constructor(notebooks, notes, notebookId) {
2020-02-04 18:27:32 +05:00
this.notebooks = notebooks;
this.notebookId = notebookId;
2020-02-05 00:17:12 +05:00
this.notes = notes;
2020-02-04 18:27:32 +05:00
}
2020-02-05 00:17:12 +05:00
async add(topic) {
await this.notebooks.add({
2020-02-04 18:27:32 +05:00
id: this.notebookId,
topics: [topic]
});
2020-02-05 00:17:12 +05:00
return this.topic(topic);
2020-02-04 18:27:32 +05:00
}
get all() {
2020-02-05 20:57:43 +05:00
return this.notebooks.notebook(this.notebookId).data.topics;
2020-02-04 18:27:32 +05:00
}
2020-02-05 00:17:12 +05:00
topic(topic) {
2020-02-04 18:27:32 +05:00
if (typeof topic === "string") {
2020-02-05 00:17:12 +05:00
topic = this.all.find(t => t.title === topic);
2020-02-04 18:27:32 +05:00
}
2020-02-05 00:17:12 +05:00
if (!topic) return;
return new Topic(this, topic);
2020-02-04 18:27:32 +05:00
}
async delete(...topics) {
2020-02-05 20:57:43 +05:00
let notebook = this.notebooks.notebook(this.notebookId);
if (!notebook) return;
notebook = notebook.data;
2020-02-04 18:27:32 +05:00
for (let topic of topics) {
2020-02-05 00:17:12 +05:00
if (!topic) continue;
let index = notebook.topics.findIndex(
t => t.title === topic.title || topic
);
2020-02-04 18:27:32 +05:00
if (index <= -1) continue;
topic = notebook.topics[index];
let t = this.topic(topic);
await t.transaction(() => t.delete(...topic.notes), false);
2020-02-04 18:27:32 +05:00
notebook.topics.splice(index, 1);
}
await this.notebooks.add({
id: notebook.id,
topics: notebook.topics
});
}
}