- new note created without a title gets one generated by a background worker (createNoteTitleWorker, ai_status column, wake channel, notes_changed SSE event, settings toggle notes_ai_enabled) - notes are strictly personal: list/update/delete/reorder always scoped to req.user.id, admin no longer sees other users' notes (403) - notes modal: focus goes to the text body, random color for new notes, ctrl+enter hint, tags hint styling, empty-title 400 fix (optText) - backup/restore: user_notes.ai_status normalized and restored
342 lines
14 KiB
JavaScript
342 lines
14 KiB
JavaScript
(async function() {
|
|
'use strict';
|
|
const API = location.origin;
|
|
let notes = [];
|
|
let editingId = null;
|
|
let dragId = null;
|
|
let saving = false;
|
|
const NOTE_COLORS = ['#2563eb', '#4f46e5', '#7c3aed', '#db2777', '#dc2626', '#ea580c', '#ca8a04', '#16a34a', '#0d9488', '#0891b2'];
|
|
|
|
function randomColor() {
|
|
return NOTE_COLORS[Math.floor(Math.random() * NOTE_COLORS.length)];
|
|
}
|
|
|
|
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, '"').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
|
|
? '<div class="note-tags">' + tags.map(t => '<span class="note-tag">' + esc(t) + '</span>').join('') + '</div>'
|
|
: '';
|
|
const body = n.note
|
|
? esc(n.note)
|
|
: '<span class="note-empty-note">Без текста</span>';
|
|
const generating = !n.title && (n.ai_status === 'pending' || n.ai_status === 'processing');
|
|
const titleHtml = n.title
|
|
? esc(n.title)
|
|
: generating
|
|
? '<span class="note-empty-note">Заголовок генерируется…</span>'
|
|
: esc('Без заголовка');
|
|
return '<div class="note-card" data-id="' + n.id + '" style="--ncolor:' + color + '">' +
|
|
'<div class="note-card-head">' +
|
|
'<span class="note-drag" draggable="true" title="Перетащите, чтобы изменить порядок">⠿</span>' +
|
|
'<div class="note-color-row" data-action="color" data-id="' + n.id + '">' +
|
|
'<input type="color" id="noteColorPicker-' + n.id + '" value="' + color + '" style="display:none">' +
|
|
'<span class="note-color-swatch" style="background:' + color + '" title="Изменить цвет"></span>' +
|
|
'</div>' +
|
|
'<div class="note-card-title">' + titleHtml + '</div>' +
|
|
tagsHtml +
|
|
'</div>' +
|
|
'<div class="note-card-note">' + body + '</div>' +
|
|
'<div class="note-card-foot">' +
|
|
'<span class="note-card-time">' + esc(fmtTs(n.updated_at)) + '</span>' +
|
|
'<div class="note-card-actions">' +
|
|
'<button type="button" class="btn-link" data-action="edit" data-id="' + n.id + '">Изменить</button>' +
|
|
'<button type="button" class="btn-link danger" data-action="delete" data-id="' + n.id + '">Удалить</button>' +
|
|
'</div>' +
|
|
'</div>' +
|
|
'</div>';
|
|
}
|
|
|
|
function renderNotes() {
|
|
const el = document.getElementById('notesList');
|
|
if (!el) return;
|
|
if (!notes.length) {
|
|
el.innerHTML = '<div class="note-empty">Заметок пока нет. Нажмите «Новая заметка», чтобы создать первую заметку.</div>';
|
|
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 : randomColor();
|
|
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('notesNote').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 && !noteText) { showToast('Заполните текст заметки', true); return; }
|
|
if (saving) return;
|
|
const payload = { title: title, note: noteText, tags: tags, color: color };
|
|
let res;
|
|
saving = true;
|
|
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) {
|
|
saving = false;
|
|
showToast('Ошибка сети', true);
|
|
return;
|
|
}
|
|
saving = false;
|
|
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) {
|
|
const m = document.getElementById('notesModal');
|
|
const open = m && m.classList.contains('open');
|
|
if (e.key === 'Enter' && (e.ctrlKey || e.metaKey) && open) {
|
|
e.preventDefault();
|
|
saveNote();
|
|
return;
|
|
}
|
|
if (e.key === 'Escape' && 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();
|
|
}
|
|
}
|
|
|
|
let liveSource = null;
|
|
let liveReconnectTimer = null;
|
|
let liveReloadTimer = null;
|
|
|
|
function connectNotesLive() {
|
|
if (liveSource) { liveSource.close(); liveSource = null; }
|
|
const connect = () => {
|
|
const t = sessionStorage.getItem('authToken');
|
|
if (!t) return;
|
|
liveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
|
|
const scheduleReload = () => {
|
|
if (liveReloadTimer) clearTimeout(liveReloadTimer);
|
|
liveReloadTimer = setTimeout(() => { liveReloadTimer = null; loadNotes(); }, 300);
|
|
};
|
|
liveSource.addEventListener('notes_changed', scheduleReload);
|
|
liveSource.onerror = () => {
|
|
if (liveSource) { liveSource.close(); liveSource = null; }
|
|
if (liveReconnectTimer) clearTimeout(liveReconnectTimer);
|
|
liveReconnectTimer = setTimeout(connect, 5000);
|
|
};
|
|
};
|
|
connect();
|
|
window.addEventListener('beforeunload', () => { if (liveSource) liveSource.close(); });
|
|
}
|
|
|
|
async function init() {
|
|
if (!(await checkAuth())) return;
|
|
buildSidebar(document.body.dataset.page);
|
|
bindModal();
|
|
bindPage();
|
|
renderIcons();
|
|
await loadNotes();
|
|
connectNotesLive();
|
|
}
|
|
|
|
init();
|
|
})();
|