JSFiddle - React, Tailwind, and code Playground
JavaScript
const notesWrapperClassName = 'note_wrapper';
const noteClassName = 'note';
const notesContainerClassName = 'note_container';
const emptyElemStyle = 'color: #999; font-style: italic;';
const emptyText = '[empty]';
const createButtonText = 'Добавить заметку';
const saveButtonText = 'Save';
const removeButtonText = 'Remove';
const errorText = 'Данные невалидны';
/**
* Обьект модели, здесь все методы для манипуляции с данными
* @param {string} name - имя модели, требуется для получения данных с localStorage
* @constructor
*/
function Storage(name) {
this.data = load() ? load() : [];
this.add = () => {
this.data.push({
text: '',
state: false,
edit: ''
});
this.save()
};
this.remove = (index) => {
this.data = this.data.filter((item, i) => i !== index);
this.save();
};
this.set = (value, index) => {
if (this.data[index]) {
this.data[index].text = value;
this.data[index].state = false;
this.data[index].edit = '';
this.save();
return true;
}
return false;
};
this.save = () => {
window.localStorage && window.localStorage.setItem(name, JSON.stringify(this.data))
};
function load(){
try {
const data = JSON.parse(window.localStorage && window.localStorage.getItem(name));
if (data.length) {
// закрываем все открытые заметки при инициализации storage...
data.forEach((item, index) => item.state = false)
}
return data;
} catch(e) {
console.warn(errorText);
return false;
}
}
}
class Notes {
constructor(name, parentElem = document.body) {
this.storage = new Storage(name);
this.name = name;
this.notes = null;
this.wrapper = this._setWrapper();
parentElem.append(this.wrapper);
this.renderNotes();
}
_setWrapper() {
const wrapper = document.createElement('div');
wrapper.className = notesWrapperClassName;
wrapper.appendChild(this.renderButton());
return wrapper;
...