(async function() {
'use strict';
const API = location.origin;
let notes = [];
let editingId = null;
let dragId = null;
function hdr() {
const t = sessionStorage.getItem('authToken');
return t ? { 'X-Auth-Token': t } : {};
}
function esc(s) {
return String(s || '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
function fmtTs(v) {
try { if (window.datetime && datetime.fmtDateTime) return datetime.fmtDateTime(v) || String(v); } catch (e) {}
return String(v);
}
function noteCardHtml(n) {
const color = /^#[0-9a-fA-F]{6}$/.test(n.color || '') ? n.color : '#2563eb';
const tags = n.tags ? n.tags.split(',').map(t => t.trim()).filter(Boolean) : [];
const tagsHtml = tags.length
? '
' + tags.map(t => '' + esc(t) + '').join('') + '
'
: '';
const body = n.note
? esc(n.note)
: 'Без текста';
return '' +
'
' +
'
⠿' +
'
' +
'' +
'' +
'
' +
'
' + esc(n.title || 'Без заголовка') + '
' +
tagsHtml +
'
' +
'
' + body + '
' +
'' +
'
';
}
function renderNotes() {
const el = document.getElementById('notesList');
if (!el) return;
if (!notes.length) {
el.innerHTML = 'Заметок пока нет. Нажмите «Новая заметка», чтобы создать первую заметку.
';
return;
}
el.innerHTML = notes.map(noteCardHtml).join('');
}
async function persistNoteOrder() {
const els = Array.prototype.slice.call(document.querySelectorAll('#notesList .note-card'));
const order = els.map(function (el) { return parseInt(el.dataset.id, 10); });
if (JSON.stringify(order) === JSON.stringify(notes.map(function (n) { return n.id; }))) return;
let res;
try {
res = await fetch(API + '/api/notes/reorder', {
method: 'PUT',
headers: Object.assign({ 'Content-Type': 'application/json' }, hdr()),
body: JSON.stringify({ ids: order })
});
} catch (e) {
showToast('Ошибка сети', true);
renderNotes();
return;
}
if (!res.ok) {
const data = await res.json().catch(function () { return {}; });
showToast(data.error || 'Не удалось сохранить порядок заметок', true);
renderNotes();
return;
}
notes = order.map(function (id) {
return notes.find(function (n) { return n.id === id; });
}).filter(Boolean);
showToast('Порядок заметок сохранён');
}
function bindDrag() {
const list = document.getElementById('notesList');
if (!list) return;
list.addEventListener('dragstart', function (e) {
const handle = e.target.closest('.note-drag');
if (!handle) { e.preventDefault(); return; }
const card = handle.closest('.note-card');
if (!card) return;
dragId = parseInt(card.dataset.id, 10);
card.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', String(dragId));
try { e.dataTransfer.setDragImage(card, 24, 24); } catch (err) {}
});
list.addEventListener('dragover', function (e) {
if (dragId == null) return;
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const target = e.target.closest('.note-card');
const dragged = list.querySelector('.note-card[data-id="' + dragId + '"]');
if (!target || !dragged || target === dragged || target.contains(dragged)) return;
const rect = target.getBoundingClientRect();
list.insertBefore(dragged, e.clientX > rect.left + rect.width / 2 ? target.nextSibling : target);
});
list.addEventListener('dragend', function (e) {
const card = e.target.closest('.note-card');
if (card) card.classList.remove('dragging');
if (dragId != null) persistNoteOrder();
dragId = null;
});
list.addEventListener('drop', function (e) { e.preventDefault(); });
}
function openModal(note) {
editingId = note ? note.id : null;
document.getElementById('notesModalTitle').textContent = note ? 'Редактировать заметку' : 'Новая заметка';
document.getElementById('notesTitle').value = note ? note.title : '';
document.getElementById('notesNote').value = note ? note.note : '';
document.getElementById('notesTags').value = note ? note.tags : '';
const color = note && /^#[0-9a-fA-F]{6}$/.test(note.color || '') ? note.color : '#2563eb';
document.getElementById('notesColor').value = color;
document.getElementById('notesColorPreview').style.background = color;
const row = document.getElementById('notesColorRow');
if (row) row.style.setProperty('--ncolor', color);
document.getElementById('notesModal').classList.add('open');
renderIcons();
setTimeout(() => document.getElementById('notesTitle').focus(), 50);
}
function closeModal() {
const m = document.getElementById('notesModal');
if (m) m.classList.remove('open');
editingId = null;
}
async function saveNote() {
const title = document.getElementById('notesTitle').value.trim();
const noteText = document.getElementById('notesNote').value.trim();
const rawTags = document.getElementById('notesTags').value.trim();
const tags = rawTags ? rawTags.split(',').map(t => t.trim()).filter(Boolean).slice(0, 10).join(', ') : '';
const color = document.getElementById('notesColor').value;
if (!title) { showToast('Укажите заголовок заметки', true); return; }
const payload = { title: title, note: noteText, tags: tags, color: color };
let res;
try {
if (editingId) {
res = await fetch(API + '/api/notes/' + editingId, { method: 'PUT', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr()), body: JSON.stringify(payload) });
} else {
res = await fetch(API + '/api/notes', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr()), body: JSON.stringify(payload) });
}
} catch (e) {
showToast('Ошибка сети', true);
return;
}
const data = await res.json().catch(function () { return {}; });
if (!res.ok) {
showToast(data.error || 'Ошибка при сохранении', true);
return;
}
const item = data.item || payload;
if (editingId) {
const idx = notes.findIndex(function (n) { return n.id === editingId; });
if (idx >= 0) notes[idx] = item;
showToast('Заметка обновлена');
} else {
notes.unshift(item);
showToast('Заметка сохранена');
}
renderNotes();
closeModal();
}
async function removeNote(id) {
if (!confirm('Удалить эту заметку?')) return;
let res;
try {
res = await fetch(API + '/api/notes/' + id, { method: 'DELETE', headers: hdr() });
} catch (e) {
showToast('Ошибка сети', true);
return;
}
const data = await res.json().catch(function () { return {}; });
if (!res.ok) {
showToast(data.error || 'Ошибка при удалении', true);
return;
}
notes = notes.filter(function (n) { return n.id !== id; });
renderNotes();
showToast('Заметка удалена');
}
function bindModal() {
document.getElementById('notesModalClose').addEventListener('click', closeModal);
document.getElementById('notesCancel').addEventListener('click', closeModal);
document.getElementById('notesSave').addEventListener('click', saveNote);
const colorInput = document.getElementById('notesColor');
if (colorInput) {
colorInput.addEventListener('input', function (e) {
document.getElementById('notesColorPreview').style.background = e.target.value;
const row = document.getElementById('notesColorRow');
if (row) row.style.setProperty('--ncolor', e.target.value);
});
}
document.addEventListener('keydown', function (e) {
if (e.key !== 'Escape') return;
const m = document.getElementById('notesModal');
if (m && m.classList.contains('open')) closeModal();
});
}
function bindPage() {
bindDrag();
document.addEventListener('click', async function (e) {
const editBtn = e.target.closest('[data-action="edit"]');
if (editBtn) {
const id = parseInt(editBtn.dataset.id, 10);
const note = notes.find(function (n) { return n.id === id; });
if (note) openModal(note);
return;
}
const delBtn = e.target.closest('[data-action="delete"]');
if (delBtn) {
await removeNote(parseInt(delBtn.dataset.id, 10));
return;
}
const colorRow = e.target.closest('[data-action="color"]');
if (colorRow) {
const picker = document.getElementById('noteColorPicker-' + parseInt(colorRow.dataset.id, 10));
if (picker) {
picker.click();
picker.onchange = async function () {
const id = parseInt(colorRow.dataset.id, 10);
const note = notes.find(function (n) { return n.id === id; });
if (!note) return;
let res;
try {
res = await fetch(API + '/api/notes/' + id, {
method: 'PUT',
headers: Object.assign({ 'Content-Type': 'application/json' }, hdr()),
body: JSON.stringify({ title: note.title, note: note.note, tags: note.tags, color: picker.value })
});
} catch (err) {
showToast('Ошибка сети', true);
return;
}
const data = await res.json().catch(function () { return {}; });
if (!res.ok) { showToast(data.error || 'Ошибка при сохранении', true); return; }
const idx = notes.findIndex(function (n) { return n.id === id; });
if (idx >= 0) notes[idx] = data.item;
renderNotes();
showToast('Цвет обновлён');
};
}
return;
}
if (e.target.closest('#notesNewBtn')) openModal(null);
});
}
async function loadNotes() {
let res;
try {
res = await fetch(API + '/api/notes', { headers: hdr() });
} catch (e) {
showToast('Ошибка сети при загрузке заметок', true);
return;
}
if (res.ok) {
const data = await res.json().catch(function () { return {}; });
notes = data.items || [];
renderNotes();
}
}
async function init() {
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
bindModal();
bindPage();
renderIcons();
await loadNotes();
}
init();
})();