You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
NotePostApp/www/js/Notes.class.js

104 lines
2.5 KiB
JavaScript

/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
function Notes() {
this.notes = [];
}
Notes.prototype.get = function (id) {
for (var i = 0; i < this.notes.length; i++) {
if (this.notes[i].id == id) {
return this.notes[i];
}
}
}
Notes.prototype.getAll = function () {
return this.notes;
}
Notes.prototype.set = function (note) {
for (var i = 0; i < this.notes.length; i++) {
if (this.notes[i].id == note.id) {
this.notes[i] = note;
return;
}
}
this.notes.push(note);
}
Notes.prototype.add = function (note, callback) {
this.notes.push(note);
if (typeof callback == 'function') {
callback();
}
}
Notes.prototype.fix = function (note) {
// Set background color
if (typeof note.color !== 'string') {
note.color = "FFF59D";
}
// Set text color based on background
if (typeof note.textcolor !== 'string') {
var r = parseInt(note.color.substring(0, 2), 16);
var g = parseInt(note.color.substring(2, 4), 16);
var b = parseInt(note.color.substring(4, 6), 16);
var contrast = Math.sqrt(
r * r * 0.241 +
g * g * 0.691 +
b * b * 0.068
);
if (contrast > 130) {
note.textcolor = "000000";
} else {
note.textcolor = "FFFFFF";
}
}
// Just in case
if (typeof note.content !== 'string') {
note.content = "";
}
// Set title
if (typeof note.title !== 'string') {
note.title = note.content.split('\n')[0].replace(/[#\-]+/gi, "").trim();
}
// Render Markdown to HTML
if (typeof note.html !== 'string') {
note.html = marked(note.content);
}
// Save
this.set(note);
}
Notes.prototype.fixAll = function () {
for (var i = 0; i < this.notes.length; i++) {
this.fix(this.notes[i]);
}
}
Notes.prototype.load = function (callback) {
if (localStorage.getItem("notes") !== null) {
data = JSON.parse(localStorage.getItem("notes"));
if (data.length > 0) {
this.notes = data;
}
}
if (typeof callback == 'function') {
callback();
}
}
Notes.prototype.save = function (callback) {
localStorage.setItem("notes", JSON.stringify(this.notes));
if (typeof callback == 'function') {
callback();
}
}