Skip to content

A fully open source & end-to-end encrypted note taking alternative to Evernote.

undo

thecodrrca0442e0d938
diff --git a/packages/core/src/api/api.js b/packages/core/src/api/api.js
new file mode 100644
index 000000000..e69de29bb
diff --git a/packages/core/src/api/auth.js b/packages/core/src/api/auth.js
new file mode 100644
index 000000000..06b686c22
--- /dev/null
+++ b/packages/core/src/api/auth.js
@@ -0,0 +1,82 @@
+import { HOST, HEADERS } from "./constants";
+//var Database = require("./database").default;
+import fetch from "node-fetch";
+
+async function authRequest(endpoint, data) {
+ let response = await fetch(`${HOST}${endpoint}`, {
+ method: "POST",
+ headers: HEADERS,
+ body: JSON.stringify(data)
+ });
+
+ let json = await response.json();
+ if (response.ok) {
+ if (json.error) {
+ throw new Error(json.error);
+ }
+ return json;
+ }
+
+ if (json.error) {
+ throw new Error(json.error);
+ } else {
+ let error = `Request failed with status code: ${response.status} ${response.statusText}.`;
+ throw new Error(error);
+ }
+}
+
+async function saveUser(response) {
+ var dt = new Date();
+ dt.setDate(dt.getDate() + 1);
+ let user = {
+ ...response.payload,
+ accessToken: response.accessToken,
+ refreshToken: response.refreshToken,
+ scopes: response.scopes,
+ expiry: dt.getTime()
+ };
+ await this.db.createUser(user);
+ return this.db.getUser();
+}
+
+export default class Auth {
+ db;
+ constructor(db) {
+ this.db = db;
+ if (!this.db) {
+ throw new Error("db cannot be undefined.");
+ }
+ }
+
+ async login(data) {
+ let response = await authRequest("oauth/token", {
+ ...data,
+ grant_type: "password"
+ });
+ return await saveUser.call(this, response);
+ }
+
+ async refreshToken() {
+ let user = this.db.getUser();
+ if (user.expiry < Date.now()) {
+ return true;
+ }
+ let response = await authRequest("oauth/token", {
+ refresh_token: user.refreshToken,
+ grant_type: "refresh_token"
+ });
+ var dt = new Date();
+ dt.setDate(dt.getDate() + 1);
+ await this.db.createUser({
+ accessToken: response.accessToken,
+ refreshToken: response.refreshToken,
+ expiry: dt.getTime()
+ });
+ return true;
+ }
+
+ async signup(data) {
+ let response = await authRequest("auth/register", data);
+ return await saveUser.call(this, response);
+ }
+}
diff --git a/packages/core/src/api/constants.js b/packages/core/src/api/constants.js
new file mode 100644
index 000000000..7e170b26e
--- /dev/null
+++ b/packages/core/src/api/constants.js
@@ -0,0 +1,5 @@
+export const HOST = "http://localhost:4000/";
+export const HEADERS = {
+ "user-agent": "nn/1.0.0",
+ "Content-Type": "application/json"
+};
diff --git a/packages/core/src/api/database.js b/packages/core/src/api/database.js
new file mode 100644
index 000000000..a4f7746b1
--- /dev/null
+++ b/packages/core/src/api/database.js
@@ -0,0 +1,555 @@
+import Storage from "../helpers/storage";
+import fuzzysearch from "fuzzysearch";
+import ff from "fast-filter";
+import { extractValues, groupBy } from "../utils";
+import {
+ getWeekGroupFromTimestamp,
+ months,
+ getLastWeekTimestamp
+} from "../utils/date";
+
+const KEYS = {
+ notes: "notes",
+ notebooks: "notebooks",
+ trash: "trash",
+ tags: "tags",
+ user: "user"
+};
+
+function checkInitialized() {
+ if (!this.isInitialized) {
+ throw new Error(
+ "Database is not initialized. Make sure to call await init() on startup."
+ );
+ }
+}
+
+class Database {
+ constructor(storage) {
+ this.storage = new Storage(storage);
+ this.notes = {};
+ this.notebooks = {};
+ this.trash = {};
+ this.tags = {};
+ this.user = {};
+ this.isInitialized = false;
+ }
+
+ init() {
+ return new Promise((resolve, reject) => {
+ for (let key of extractValues(KEYS)) {
+ this.storage.read(key).then(data => {
+ this[key] = data || {};
+ if (key === KEYS.user) {
+ this.isInitialized = true;
+ //TODO use index here
+ resolve(true);
+ }
+ });
+ }
+ });
+ }
+
+ getNotes() {
+ checkInitialized.call(this);
+ return extractValues(this.notes).reverse();
+ }
+
+ getFavorites() {
+ return ff(
+ ...this.getNotes(),
+ ...this.getNotebooks(),
+ v => v.favorite == true
+ );
+ }
+
+ getPinned() {
+ return ff(this.getNotes(), v => v.pinned == true);
+ }
+
+ /**
+ * @param {string} by One from 'abc', 'month', 'year' or 'week'. Leave it empty for default grouping.
+ * @param {boolean} special Should only be used in the React app.
+ */
+ groupNotes(by, special = false) {
+ let notes = !special
+ ? ff(this.getNotes(), v => v.pinned == false)
+ : this.getNotes();
+ switch (by) {
+ case "abc":
+ return groupBy(
+ notes.sort((a, b) => a.title.localeCompare(b.title)),
+ note => note.title[0].toUpperCase(),
+ special
+ );
+ case "month":
+ return groupBy(
+ notes,
+ note => months[new Date(note.dateCreated).getMonth()],
+ special
+ );
+ case "week":
+ return groupBy(
+ notes,
+ note => getWeekGroupFromTimestamp(note.dateCreated),
+ special
+ );
+ case "year":
+ return groupBy(
+ notes,
+ note => new Date(note.dateCreated).getFullYear().toString(),
+ special
+ );
+ default:
+ let timestamps = {
+ recent: getLastWeekTimestamp(7),
+ lastWeek: getLastWeekTimestamp(7) - 604800000 //seven day timestamp value
+ };
+ return groupBy(
+ notes,
+ note =>
+ note.dateCreated >= timestamps.recent
+ ? "Recent"
+ : note.dateCreated >= timestamps.lastWeek
+ ? "Last week"
+ : "Older",
+ special
+ );
+ }
+ }
+
+ async addNote(note) {
+ if (!note) return;
+ let timestamp = note.dateCreated || Date.now();
+ note = { ...this.notes[timestamp], ...note };
+
+ if (
+ !note.title &&
+ !note.locked &&
+ (!note.content || !note.content.text || !note.content.delta) &&
+ this.notes[timestamp]
+ ) {
+ //delete the note
+ await this.deleteNotes(note);
+ return;
+ }
+
+ //add or update a note into the database
+ let title =
+ note.title ||
+ note.content.text
+ .split(" ")
+ .slice(0, 3)
+ .join(" ");
+
+ //if note exists
+ if (this.notes[timestamp] !== undefined) {
+ let oldNote = this.notes[timestamp];
+ //if we are having new colors
+ if (oldNote.colors !== note.colors && note.colors) {
+ note.colors = mergeDedupe([oldNote.colors, note.colors]);
+ }
+ //if we are having new tags
+ //TODO add new tags to the tags collection...
+ if (oldNote.tags !== note.tags && note.tags) {
+ note.tags = mergeDedupe([oldNote.tags, note.tags]);
+ }
+ }
+
+ this.notes[timestamp] = {
+ type: "note",
+ title,
+ content: note.content,
+ pinned: note.pinned || false,
+ tags: note.tags || [],
+ locked: note.locked || false,
+ notebook: note.notebook || {},
+ colors: note.colors || [],
+ favorite: note.favorite || false,
+ headline:
+ !note.locked &&
+ note.content.text.substring(0, 150) +
+ (note.content.text.length > 150 ? "..." : ""),
+ length: note.content.text.length,
+ dateEditted: Date.now(),
+ dateCreated: timestamp
+ };
+ await this.storage.write(KEYS.notes, this.notes);
+ return timestamp;
+ }
+
+ //TODO only send unique values here...
+ async updateTags(tags) {
+ for (let tag of tags) {
+ this[KEYS.tags][tag] = {
+ title: tag,
+ count: this[KEYS.tags][tag].count + 1
+ };
+ }
+ await this.storage.write(KEYS.tags, this[KEYS.tags]);
+ }
+
+ pinItem(type, id) {
+ return editItem.call(this, type, id, "pinned");
+ }
+
+ favoriteItem(type, id) {
+ return editItem.call(this, type, id, "favorite");
+ }
+
+ async deleteNotes(...notes) {
+ return await deleteItems.call(this, notes, KEYS.notes);
+ }
+
+ getNote(id) {
+ return getItem.call(this, id, KEYS.notes);
+ }
+
+ searchNotes(query) {
+ if (!query) return [];
+ return ff(extractValues(this.notes), v =>
+ fuzzysearch(query, v.title + " " + v.content.text)
+ );
+ }
+
+ async lockNote(noteId, password) {
+ if (!this.notes[noteId]) {
+ throw new Error(`Cannot lock note. Invalid ID: ${noteId} given.`);
+ }
+
+ this.notes[noteId].content = await this.storage.encrypt(
+ password,
+ JSON.stringify(this.notes[noteId].content)
+ );
+ this.notes[noteId].locked = true;
+ await this.storage.write(KEYS.notes, this.notes);
+ return true;
+ }
+
+ async unlockNote(noteId, password, perm = false) {
+ if (!this.notes[noteId]) {
+ throw new Error(`Cannot unlock note. Invalid ID: ${noteId} given.`);
+ }
+ let decrypted = await this.storage.decrypt(
+ password,
+ this.notes[noteId].content
+ );
+ if (perm) {
+ this.notes[noteId].locked = false;
+ this.notes[noteId].content = JSON.parse(decrypted);
+ await this.storage.write(KEYS.notes, this.notes);
+ }
+ return { ...this.notes[noteId], content: JSON.parse(decrypted) };
+ }
+
+ getNotebooks() {
+ checkInitialized.call(this);
+ return extractValues(this.notebooks);
+ }
+
+ async addNotebook(notebook) {
+ if (!notebook || !notebook.title) {
+ return;
+ }
+ if (
+ extractValues(this.notebooks).findIndex(
+ nb =>
+ nb.title === notebook.title && nb.dateCreated !== notebook.dateCreated
+ ) > -1
+ ) {
+ return;
+ }
+
+ const id = notebook.dateCreated || Date.now();
+ let topics =
+ !notebook.topics || notebook.topics.length <= 0 ? [] : notebook.topics; //
+ if (topics.findIndex(topic => topic.title === "General") <= -1) {
+ topics.splice(0, 0, makeTopic("General"));
+ }
+ let index = 0;
+
+ for (let topic of topics) {
+ if (
+ !topic ||
+ topics.findIndex(t => t.title === (topic || topic.title)) > -1 //check for duplicate
+ ) {
+ topics.splice(index, 1);
+ continue;
+ }
+ if (typeof topic === "string") {
+ if (topic.trim().length <= 0) topics.splice(index, 1);
+ topics[index] = makeTopic(topic);
+ }
+ index++;
+ }
+
+ this.notebooks[id] = {
+ type: "notebook",
+ title: notebook.title,
+ description: notebook.description,
+ dateCreated: id,
+ pinned: notebook.pinned || false,
+ favorite: notebook.favorite || false,
+ topics,
+ totalNotes: 0
+ };
+ await this.storage.write(KEYS.notebooks, this.notebooks);
+ return id;
+ }
+
+ addTopicToNotebook(notebookId, topic) {
+ return notebookTopicFn.call(this, notebookId, topic, notebook => {
+ if (notebook.topics.findIndex(t => t.title === topic) > -1) return false; //check for duplicates
+ notebook.topics[notebook.topics.length] = makeTopic(topic);
+ return true;
+ });
+ }
+
+ deleteTopicFromNotebook(notebookId, topic) {
+ return notebookTopicFn.call(this, notebookId, topic, notebook => {
+ let topicIndex = notebook.topics.findIndex(t => t.title === topic);
+ if (topicIndex === -1) return false;
+ notebook.topics.splice(topicIndex, 1);
+ return true;
+ });
+ }
+
+ addNoteToTopic(notebookId, topic, noteId) {
+ return topicNoteFn.call(
+ this,
+ notebookId,
+ topic,
+ noteId,
+ (notebook, topicIndex) => {
+ if (notebook.topics[topicIndex].notes.indexOf(noteId) > -1)
+ return false; //duplicate check
+ notebook.topics[topicIndex].notes.push(noteId);
+ //increment totalNotes count
+ notebook.topics[topicIndex].totalNotes++;
+ notebook.totalNotes++;
+ //add notebook to the note
+ this.notes[noteId].notebook = {
+ notebook: notebookId,
+ topic: notebook.topics[topicIndex].title
+ };
+ return true;
+ }
+ );
+ }
+
+ deleteNoteFromTopic(notebookId, topic, noteId) {
+ return topicNoteFn.call(
+ this,
+ notebookId,
+ topic,
+ noteId,
+ async (notebook, topicIndex) => {
+ let index = notebook.topics[topicIndex].notes.indexOf(noteId);
+ if (index <= -1) return false;
+ notebook.topics[topicIndex].notes.splice(index, 1);
+ //delete notebook from note
+ this.notes[noteId].notebook = {};
+ //decrement totalNotes count
+ if (notebook.topics[topicIndex].totalNotes > 0)
+ notebook.topics[topicIndex].totalNotes--;
+ if (notebook.totalNotes > 0) notebook.totalNotes--;
+ return true;
+ }
+ );
+ }
+
+ getTopic(notebookId, topic) {
+ if (!notebookId || !topic || !this.notebooks[notebookId]) return;
+ let notebook = this.notebooks[notebookId];
+ let topicIndex = notebook.topics.findIndex(t => t.title === topic);
+ if (topicIndex === -1) return;
+ let nbTopic = notebook.topics[topicIndex];
+ if (nbTopic.notes.length <= 0) return [];
+ return nbTopic.notes.map(note => this.getNote(note));
+ }
+
+ getNotebook(id) {
+ return getItem.call(this, id, KEYS.notebooks);
+ }
+
+ async deleteNotebooks(...notebooks) {
+ return await deleteItems.call(this, notebooks, KEYS.notebooks);
+ }
+
+ async moveNote(noteId, from, to) {
+ if (!noteId || !to || !to.notebook || !to.topic) {
+ throw new Error(`Error: Failed to move note.`);
+ }
+ if (!from.notebook && !from.topic) {
+ return await this.addNoteToTopic(to.notebook, to.topic, noteId);
+ } else if (
+ await this.deleteNoteFromTopic(from.notebook, from.topic, noteId)
+ ) {
+ if (from.notebook === to.notebook && from.topic === to.topic) {
+ throw new Error(
+ "Moving to the same notebook and topic is not possible."
+ );
+ }
+ return await this.addNoteToTopic(to.notebook, to.topic, noteId);
+ }
+ return false;
+ }
+
+ async restoreItem(id) {
+ if (!this.trash.hasOwnProperty(id)) {
+ throw new Error("Cannot restore: This item is not present in trash.");
+ }
+ let type = this.trash[id].dType;
+ delete this.trash[id].dateDeleted;
+ delete this.trash[id].dType;
+ let item = this.trash[id];
+ this[type][id] = item;
+ await this.storage.write(type, this[type]);
+ }
+
+ getTrash() {
+ checkInitialized.call(this);
+ return extractValues(this.trash).reverse();
+ }
+
+ async clearTrash() {
+ this[KEYS.trash] = {};
+ await this.storage.write(KEYS.trash, this[KEYS.trash]);
+ }
+
+ async createUser(user) {
+ this.user = { ...this.user, ...user };
+ await this.storage.write(KEYS.user, user);
+ }
+ getUser() {
+ return this.user;
+ }
+}
+
+export default Database;
+
+async function deleteItems(items, key) {
+ if (!items || items.length <= 0 || !this[key] || this[key].length <= 0)
+ return false;
+ for (let item of items) {
+ if (!item) continue;
+ if (this[key].hasOwnProperty(item.dateCreated)) {
+ //delete note from the notebook too.
+ if (item.type === "note" && item.notebook.hasOwnProperty("topic")) {
+ if (
+ !(await this.deleteNoteFromTopic(
+ item.notebook.notebook,
+ item.notebook.topic,
+ item.dateCreated
+ ))
+ ) {
+ continue;
+ }
+ } else if (item.type === "notebook") {
+ let skip = false;
+ for (let topic in item.topics) {
+ for (let note in topic.notes) {
+ if (
+ !(await this.deleteNoteFromTopic(item.dateCreated, topic, note))
+ ) {
+ skip = true;
+ break;
+ }
+ }
+ }
+ if (skip) {
+ continue;
+ }
+ }
+ //put into trash
+ this[KEYS.trash][item.dateCreated] = this[key][item.dateCreated];
+ this[KEYS.trash][item.dateCreated]["dateDeleted"] = Date.now();
+ this[KEYS.trash][item.dateCreated]["dType"] = key;
+
+ delete this[key][item.dateCreated];
+ }
+ }
+
+ return this.storage
+ .write(key, this[key])
+ .then(s =>
+ this.storage.write(KEYS.trash, this[KEYS.trash]).then(s => true)
+ );
+}
+
+function notebookTopicFn(notebookId, topic, fn) {
+ if (!notebookId || !topic || !this.notebooks[notebookId]) return false;
+ const notebook = this.notebooks[notebookId];
+ let result = fn(notebook);
+
+ const saveNotebooks = () => {
+ this.notebooks[notebookId] = notebook;
+ return this.storage.write(KEYS.notebooks, this.notebooks).then(s => true);
+ };
+
+ if (result instanceof Promise) {
+ return result.then(res => {
+ if (res === true) {
+ return saveNotebooks();
+ }
+ return false;
+ });
+ }
+
+ if (result === true) {
+ return saveNotebooks();
+ }
+
+ return result;
+}
+
+function topicNoteFn(notebookId, topic, noteId, fn) {
+ return notebookTopicFn.call(this, notebookId, topic, async notebook => {
+ let topicIndex = notebook.topics.findIndex(t => t.title === topic);
+ if (topicIndex === -1 || !this.notes.hasOwnProperty(noteId)) return false;
+
+ if ((await fn(notebook, topicIndex)) === true) {
+ return await this.storage.write(KEYS.notes, this.notes).then(s => true);
+ }
+ return false;
+ });
+}
+
+function getItem(id, key) {
+ checkInitialized.call(this);
+ if (this[key].hasOwnProperty(id)) {
+ return this[key][id];
+ }
+}
+
+function makeTopic(topic) {
+ return {
+ type: "topic",
+ title: topic,
+ dateCreated: Date.now(),
+ totalNotes: 0,
+ notes: []
+ };
+}
+
+async function editItem(type, id, prop) {
+ switch (type) {
+ case "notebook":
+ case "note":
+ let col = type == "note" ? this.notes : this.notebooks;
+ let func = type == "note" ? this.addNote : this.addNotebook;
+ if (col[id] === undefined) {
+ throw new Error(`Wrong ${type} id.`);
+ }
+ let state = col[id][prop];
+ let edit = { [prop]: !state };
+ await func.call(this, { ...col[id], ...edit });
+ break;
+ default:
+ throw new Error("Invalid type given to pinItem");
+ }
+}
+
+function mergeDedupe(arr) {
+ return [...new Set([].concat(...arr))];
+}
diff --git a/packages/core/src/api/notes.js b/packages/core/src/api/notes.js
new file mode 100644
index 000000000..60670f6e8
--- /dev/null
+++ b/packages/core/src/api/notes.js
@@ -0,0 +1,72 @@
+class Store {
+ constructor(storage) {
+ this.storage = storage;
+ this.collection = new Map();
+ }
+}
+
+export default class Notes extends Store {
+ //get notes(): INote[] {}
+ async addNote(note) {
+ if (this.isNoteEmpty(note)) {
+ return this.deleteNotes(note.id);
+ }
+
+ note.dateCreated = note.dateCreated || Date.now();
+ note.id = note.id || note.dateCreated.toString();
+ note.type = ModelType.note;
+ note.dateEdited = Date.now();
+ note.title = this.getNoteTitle(note);
+ note.headline = this.getNoteHeadline(note);
+
+ if (this.collection.has(note.id)) {
+ note = this.mergeNote(note);
+ }
+
+ this.collection.set(note.id, note);
+ return this.storage.write(note.id, note);
+ }
+
+ getNote(id) {
+ return this.collection.get(id);
+ }
+
+ deleteNotes(...ids) {
+ for (let id in ids) {
+ if (this.collection.delete(id)) {
+ this.storage.remove(id);
+ }
+ }
+ }
+
+ isNoteEmpty(note) {
+ return (
+ this.collection.has(note.id) &&
+ !note.locked &&
+ note.title?.length <= 0 &&
+ note.content.text?.length <= 0
+ );
+ }
+
+ getNoteTitle(note) {
+ return (
+ note.title ||
+ note.content.text
+ .split(" ")
+ .slice(0, 3)
+ .join(" ")
+ );
+ }
+
+ getNoteHeadline(note) {
+ return (
+ !note.locked &&
+ note.content.text.substring(0, 150) +
+ (note.content.text.length > 150 ? "..." : "")
+ );
+ }
+
+ mergeNote(note) {
+ return { ...this.collection.get(note.id), ...note };
+ }
+}
diff --git a/packages/core/src/helpers/storage.js b/packages/core/src/helpers/storage.js
new file mode 100644
index 000000000..142d4ec4c
--- /dev/null
+++ b/packages/core/src/helpers/storage.js
@@ -0,0 +1,29 @@
+import Convert from "../utils/convert";
+import IStorage from "../interfaces/IStorage";
+import ICipherData from "../interfaces/ICipherData";
+
+export default class Storage {
+ storage;
+ constructor(context) {
+ this.storage = context;
+ }
+ async write(key, data) {
+ await this.storage.write(key, Convert.toString(data));
+ }
+ async read() {
+ let data = await this.storage.read(key);
+ return Convert.fromString(data);
+ }
+ clear() {
+ this.storage.clear();
+ }
+ remove(key) {
+ this.storage.remove(key);
+ }
+ encrypt(password, data) {
+ return this.storage.encrypt(password, data);
+ }
+ decrypt(password, cipher) {
+ return this.storage.decrypt(password, cipher);
+ }
+}
diff --git a/packages/core/src/utils/convert.js b/packages/core/src/utils/convert.js
new file mode 100644
index 000000000..0a4eddce4
--- /dev/null
+++ b/packages/core/src/utils/convert.js
@@ -0,0 +1,12 @@
+export default class Convert {
+ static toString(input) {
+ return JSON.stringify(input);
+ }
+ static fromString(input) {
+ try {
+ return JSON.parse(input);
+ } catch (e) {
+ return input;
+ }
+ }
+}
diff --git a/packages/core/src/utils/date.js b/packages/core/src/utils/date.js
new file mode 100644
index 000000000..66efed06f
--- /dev/null
+++ b/packages/core/src/utils/date.js
@@ -0,0 +1,98 @@
+import IWeek from "../interfaces/IWeek";
+
+function getWeeksInMonth(month, year, _start) {
+ let weeks = [],
+ firstDate = new Date(year, month, 1),
+ lastDate = new Date(year, month + 1, 0),
+ numDays = lastDate.getDate();
+
+ let start = 1;
+ let end = 7 - firstDate.getDay();
+ if (firstDate.getDay() === _start) {
+ end = 7;
+ } else {
+ let preMonthEndDay = new Date(year, month, 0);
+ start = preMonthEndDay.getDate() + 1 - firstDate.getDay() + _start;
+ end = 7 - firstDate.getDay() + _start;
+ weeks.push({
+ start: new Date(
+ preMonthEndDay.getFullYear(),
+ preMonthEndDay.getMonth(),
+ start
+ ),
+ end: new Date(year, month, end)
+ });
+ start = end + 1;
+ end = end + 7;
+ }
+ while (start <= numDays) {
+ weeks.push({
+ start: new Date(year, month, start),
+ end: new Date(year, month, end)
+ });
+ start = end + 1;
+ end = end + 7;
+ if (end > numDays) {
+ end = end - numDays + _start;
+ weeks.push({
+ start: new Date(year, month, start),
+ end: new Date(year, month + 1, end)
+ });
+ break;
+ }
+ }
+ return weeks;
+}
+
+function getWeeksInYear(year) {
+ let weeks = [];
+ for (let i = 0; i <= 11; i++) {
+ weeks = [...weeks, ...getWeeksInMonth(i, year, 0)];
+ }
+ return weeks;
+}
+
+/* function getDayTimestamp(last) {
+ to = new Date().getDate() - last;
+ date = new Date();
+ return date.setDate(to);
+} */
+
+export function getLastWeekTimestamp() {
+ const t = new Date().getDate() + (6 - new Date().getDay() - 1) - 6;
+ const lastSaturday = new Date();
+ return lastSaturday.setDate(t);
+}
+
+export const months = [
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec"
+];
+
+let years;
+export function getWeekGroupFromTimestamp(timestamp) {
+ let date = new Date(timestamp);
+ date.setHours(0, 0, 0, 0);
+ if (!years.hasOwnProperty(date.getFullYear())) {
+ years[date.getFullYear()] = getWeeksInYear(date.getFullYear());
+ }
+ let weeks = years[date.getFullYear()];
+
+ let week = weeks.find(v => date >= v.start && date <= v.end);
+ //Format: {month} {start} - {end}, {year}
+ return `${
+ months[week.start.getMonth()]
+ } ${week.start.getDate()}, ${week.start.getFullYear()} - ${
+ months[week.end.getMonth()]
+ } ${week.end.getDate()}, ${week.end.getFullYear()}`;
+}
diff --git a/packages/core/src/utils/index.js b/packages/core/src/utils/index.js
new file mode 100644
index 000000000..43ba8b6b8
--- /dev/null
+++ b/packages/core/src/utils/index.js
@@ -0,0 +1,71 @@
+import IGroup from "../interfaces/IGroup";
+
+export function extractValues(obj) {
+ const t = [];
+ for (let key in obj) {
+ t[t.length] = obj[key];
+ }
+ return t;
+}
+
+export function groupBy(
+ arr,
+ key
+ // special: boolean = false
+) {
+ /* if (special) {
+ return groupBySpecial(arr, key);
+ } */
+ let retVal = [];
+ for (let val of arr) {
+ let v = key(val);
+ let index = retVal.findIndex(a => a.title === v);
+ if (index === -1) {
+ index = retVal.length;
+ retVal[retVal.length] = {
+ title: v,
+ data: []
+ };
+ }
+ retVal[index].data.push(val);
+ }
+ return retVal;
+}
+/*
+function groupBySpecial(arr: Array<any>, key: KeyFn) {
+ let retVal = [];
+ let _groups = { "": 0 };
+ let groups = [];
+ let groupCounts = [];
+ var i = -1;
+ let pinned = [];
+ for (let val of arr) {
+ if (val.pinned) {
+ pinned[pinned.length] = val;
+ continue;
+ }
+ i++;
+ let groupTitle = key(val);
+ let index =
+ _groups[groupTitle] === undefined ? i : _groups[groupTitle].index;
+ let groupIndex =
+ _groups[groupTitle] == undefined
+ ? groupCounts.length
+ : _groups[groupTitle].groupIndex;
+ retVal.splice(index + 1, 0, val);
+ groupCounts[groupIndex] =
+ groupCounts.length == groupIndex ? 1 : groupCounts[groupIndex] + 1;
+ groups[groupIndex] = { title: groupTitle };
+ _groups[groupTitle] = {
+ index: i,
+ groupIndex
+ };
+ }
+
+ let g = { items: retVal, groups, groupCounts };
+ g.items.splice(0, 0, ...pinned);
+ g.groupCounts.splice(0, 0, pinned.length);
+ g.groups.splice(0, 0, { title: "Pinned" });
+ return g;
+}
+ */