Files
notesnook/packages/core/models/topic.js

103 lines
2.5 KiB
JavaScript
Raw Normal View History

import { qclone } from "qclone";
import sort from "fast-sort";
import { deleteItem, findById } from "../utils/array";
2020-02-05 20:57:43 +05:00
export default class Topic {
/**
* @param {Object} topic
2020-04-16 02:14:53 +05:00
* @param {string} notebookId
* @param {import('../api').default} db
2020-02-05 20:57:43 +05:00
*/
2020-04-16 02:14:53 +05:00
constructor(topic, notebookId, db) {
this._topic = topic;
2020-04-16 02:14:53 +05:00
this._db = db;
this._notebookId = notebookId;
}
get totalNotes() {
return this._topic.notes.length;
2020-02-05 20:57:43 +05:00
}
has(noteId) {
return this._topic.notes.indexOf(noteId) > -1;
2020-02-05 20:57:43 +05:00
}
async add(...noteIds) {
const topic = qclone(this._topic);
2020-02-05 20:57:43 +05:00
for (let noteId of noteIds) {
2020-04-16 02:14:53 +05:00
let note = this._db.notes.note(noteId);
2020-03-23 13:22:28 +05:00
if (this.has(noteId) || !note || note.data.deleted) continue;
let array = note.notebooks || [];
const notebookIndex = array.findIndex((nb) => nb.id === this._notebookId);
if (notebookIndex === -1) {
let notebook = {};
notebook.id = this._notebookId;
notebook.topics = [topic.id];
array.push(notebook);
} else {
const topicIndex = array[notebookIndex].topics.indexOf(topic.id);
if (topicIndex > -1) {
if (!this.has(noteId)) topic.notes.push(noteId);
continue;
}
array[notebookIndex].topics.push(topic.id);
}
2020-04-16 02:14:53 +05:00
await this._db.notes.add({
2020-02-05 20:57:43 +05:00
id: noteId,
notebooks: array,
2020-02-05 20:57:43 +05:00
});
topic.notes.push(noteId);
2020-02-05 20:57:43 +05:00
}
return await this._save(topic);
2020-02-05 20:57:43 +05:00
}
async delete(...noteIds) {
const topic = qclone(this._topic);
2020-02-05 20:57:43 +05:00
for (let noteId of noteIds) {
let note = this._db.notes.note(noteId);
if (
!note ||
note.deleted ||
!deleteItem(topic.notes, noteId) ||
!note.notebooks
) {
continue;
}
let { notebooks } = note;
const notebook = findById(notebooks, this._notebookId);
if (!notebook) continue;
const { topics } = notebook;
if (!deleteItem(topics, topic.id)) continue;
if (topics.length <= 0) deleteItem(notebooks, notebook);
2020-04-16 02:14:53 +05:00
await this._db.notes.add({
2020-02-05 20:57:43 +05:00
id: noteId,
notebooks,
2020-02-05 20:57:43 +05:00
});
}
return await this._save(topic);
2020-02-05 20:57:43 +05:00
}
async _save(topic) {
2020-04-16 02:14:53 +05:00
await this._db.notebooks.notebook(this._notebookId).topics.add(topic);
2020-02-06 18:47:42 +05:00
return this;
2020-02-05 20:57:43 +05:00
}
get all() {
const notes = this._topic.notes.reduce((arr, noteId) => {
let note = this._db.notes.note(noteId);
if (note) arr.push(note.data);
return arr;
}, []);
return sort(notes).desc((note) => note.dateCreated);
2020-02-05 20:57:43 +05:00
}
}