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

98 lines
2.7 KiB
JavaScript
Raw Normal View History

2020-02-06 16:46:23 +05:00
import CachedCollection from "../database/cached-collection";
import Notes from "./notes";
import Notebooks from "./notebooks";
import Storage from "../database/storage";
export default class Trash {
constructor(context) {
this._collection = new CachedCollection(context, "trash");
this._deltaStorage = new Storage(context);
2020-02-06 16:46:23 +05:00
}
/**
*
* @param {Notes} notes
* @param {Notebooks} notebooks
*/
async init(notes, notebooks) {
this._notes = notes;
this._notebooks = notebooks;
await this._collection.init();
2020-02-06 16:46:23 +05:00
}
get all() {
return this._collection.getAllItems();
2020-02-06 16:46:23 +05:00
}
async add(item) {
if (this._collection.exists(item.id + "_deleted"))
2020-02-06 16:46:23 +05:00
throw new Error("This item has already been deleted.");
2020-02-22 22:03:09 +05:00
await this._collection.addItem({
...item,
dateDeleted: Date.now(),
id: item.id + "_deleted"
});
2020-02-06 16:46:23 +05:00
}
async delete(...ids) {
for (let id of ids) {
if (!this._collection.exists(id)) return;
2020-02-06 16:46:23 +05:00
if (id.indexOf("note") > -1)
await this._deltaStorage.remove(id.replace("_deleted", "") + "_delta");
await this._collection.removeItem(id);
2020-02-06 16:46:23 +05:00
}
}
async restore(...ids) {
for (let id of ids) {
2020-02-22 22:03:09 +05:00
let item = { ...this._collection.getItem(id) };
2020-02-06 16:46:23 +05:00
if (!item) continue;
delete item.dateDeleted;
item.id = item.id.replace("_deleted", "");
if (item.type === "note") {
let { notebook } = item;
item.notebook = {};
await this._notes.add(item);
2020-02-06 16:46:23 +05:00
if (notebook && notebook.id && notebook.topic) {
const { id, topic } = notebook;
// if the notebook has been deleted
if (!this._notebooks._collection.exists(id)) {
2020-02-06 16:46:23 +05:00
notebook = {};
} else {
// if the topic has been deleted
if (!this._notebooks.notebook(id).topics.has(topic)) {
2020-02-06 16:46:23 +05:00
notebook = {};
}
}
// restore the note to the topic it was in before deletion
if (notebook.id && notebook.topic) {
await this._notebooks
2020-02-06 16:46:23 +05:00
.notebook(id)
.topics.topic(topic)
.add(item.id);
}
}
} else {
const { topics } = item;
item.topics = [];
await this._notebooks.add(item);
let notebook = this._notebooks.notebook(item.id);
2020-02-06 16:46:23 +05:00
for (let topic of topics) {
2020-02-06 18:47:42 +05:00
await notebook.topics.add(topic.title || topic);
let t = notebook.topics.topic(topic.title || topic);
if (!t) continue;
if (topic.notes) await t.add(...topic.notes);
2020-02-06 16:46:23 +05:00
}
}
await this._collection.removeItem(id);
2020-02-06 16:46:23 +05:00
}
}
async clear() {
let indices = await this._collection.indexer.getIndices();
2020-02-06 16:46:23 +05:00
return this.delete(...indices);
}
}