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

100 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-02-04 18:27:32 +05:00
import CachedCollection from "../database/cached-collection";
import fuzzysearch from "fuzzysearch";
2020-02-05 20:57:43 +05:00
import Notebook from "../models/notebook";
2020-02-06 16:46:23 +05:00
import Notes from "./notes";
import Trash from "./trash";
2020-02-04 18:27:32 +05:00
var tfun = require("transfun/transfun.js").tfun;
if (!tfun) {
tfun = global.tfun;
}
export default class Notebooks {
constructor(context) {
this.context = context;
this.collection = new CachedCollection(context, "notebooks");
2020-02-05 00:17:12 +05:00
this.notes = undefined;
}
2020-02-06 16:46:23 +05:00
/**
*
* @param {Notes} notes
* @param {Trash} trash
*/
init(notes, trash) {
2020-02-05 00:17:12 +05:00
this.notes = notes;
2020-02-06 16:46:23 +05:00
this.trash = trash;
2020-02-05 00:17:12 +05:00
return this.collection.init();
2020-02-04 18:27:32 +05:00
}
async add(notebookArg) {
if (!notebookArg) throw new Error("Notebook cannot be undefined or null.");
//TODO reliably and efficiently check for duplicates.
const id = notebookArg.id || Date.now().toString() + "_notebook";
let oldNotebook = this.collection.getItem(id);
if (!oldNotebook && !notebookArg.title)
throw new Error("Notebook must contain at least a title.");
let notebook = {
...oldNotebook,
...notebookArg
};
notebook = {
id,
type: "notebook",
title: notebook.title,
description: notebook.description,
dateCreated: notebook.dateCreated || Date.now(),
dateEdited: Date.now(),
pinned: !!notebook.pinned,
favorite: !!notebook.favorite,
2020-02-06 18:47:42 +05:00
topics: notebook.topics || [],
2020-02-04 18:27:32 +05:00
totalNotes: 0
};
2020-02-06 18:47:42 +05:00
if (!oldNotebook) {
notebook.topics.splice(0, 0, "General");
}
2020-02-04 18:27:32 +05:00
await this.collection.addItem(notebook);
2020-02-06 18:47:42 +05:00
//if (!oldNotebook) {
await this.notebook(notebook.id).topics.add(...notebook.topics);
//}
2020-02-04 18:27:32 +05:00
return notebook.id;
}
get all() {
return this.collection.getAllItems();
}
2020-02-06 22:46:57 +05:00
/**
*
* @param {string} id The id of the notebook
* @returns {Notebook} The notebook of the given id
*/
2020-02-05 20:57:43 +05:00
notebook(id) {
let notebook = this.collection.getItem(id);
if (!notebook) return;
return new Notebook(this, notebook);
2020-02-04 18:27:32 +05:00
}
async delete(...ids) {
for (let id of ids) {
2020-02-05 20:57:43 +05:00
let notebook = this.notebook(id);
if (!notebook) continue;
await this.collection.transaction(() =>
2020-02-05 20:57:43 +05:00
notebook.topics.delete(...notebook.topics.all)
);
await this.collection.removeItem(id);
2020-02-06 16:46:23 +05:00
await this.trash.add(notebook.data);
}
}
2020-02-04 18:27:32 +05:00
filter(query) {
if (!query) return [];
return tfun.filter(v => fuzzysearch(query, v.title + " " + v.description))(
this.all
);
}
}