Files
notesnook/packages/core/api/settings.js

82 lines
2.0 KiB
JavaScript
Raw Normal View History

2020-12-10 14:17:37 +05:00
import { EV } from "../common";
2020-12-05 11:26:02 +05:00
import id from "../utils/id";
2020-11-25 15:04:39 +05:00
class Settings {
/**
*
* @param {import("./index").default} db
*/
constructor(db) {
this._db = db;
2020-12-05 11:26:02 +05:00
this._settings = {
type: "settings",
2020-12-05 11:26:02 +05:00
id: id(),
pins: [],
dateEdited: 0,
dateCreated: Date.now(),
};
}
get raw() {
return this._settings;
}
merge(item) {
2020-12-05 13:20:39 +05:00
this._settings = {
...this._settings,
...item,
};
2020-11-25 15:04:39 +05:00
}
async init() {
2020-12-05 11:26:02 +05:00
var settings = await this._db.context.read("settings");
if (!settings) await this._db.context.write("settings", this._settings);
else this._settings = settings;
2020-12-10 14:16:05 +05:00
EV.subscribe("user:loggedOut", () => {
this._settings = {
type: "settings",
id: id(),
pins: [],
dateEdited: 0,
dateCreated: Date.now(),
};
});
2020-11-25 15:04:39 +05:00
}
async pin(type, data) {
2020-11-25 20:49:29 +05:00
if (type !== "notebook" && type !== "topic" && type !== "tag")
2020-11-25 15:04:39 +05:00
throw new Error("This item cannot be pinned.");
2020-11-25 20:52:54 +05:00
if (this.isPinned(data.id)) return;
2020-11-25 20:49:29 +05:00
this._settings.pins.push({ type, data });
2020-12-05 11:26:02 +05:00
this._settings.dateEdited = Date.now();
2020-11-25 15:04:39 +05:00
await this._db.context.write("settings", this._settings);
}
async unpin(id) {
2020-11-25 20:49:29 +05:00
const index = this._settings.pins.findIndex((i) => i.data.id === id);
2020-11-25 15:04:39 +05:00
if (index <= -1) return;
this._settings.pins.splice(index, 1);
2020-12-05 11:26:02 +05:00
this._settings.dateEdited = Date.now();
2020-11-25 15:04:39 +05:00
await this._db.context.write("settings", this._settings);
}
2020-11-25 20:52:54 +05:00
isPinned(id) {
2020-11-25 20:59:27 +05:00
return this._settings.pins.findIndex((v) => v.data.id === id) > -1;
2020-11-25 20:52:54 +05:00
}
2020-11-25 15:04:39 +05:00
get pins() {
return this._settings.pins.map((pin) => {
if (pin.type === "notebook") {
return this._db.notebooks.notebook(pin.data.id).data;
} else if (pin.type === "topic") {
return this._db.notebooks
2020-11-25 20:49:29 +05:00
.notebook(pin.data.notebookId)
2020-11-25 23:51:15 +05:00
.topics.topic(pin.data.id)._topic;
2020-11-25 15:04:39 +05:00
} else if (pin.type === "tag") {
return this._db.tags.tag(pin.data.id);
}
});
}
}
export default Settings;