Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
233 lines (205 loc) · 6.63 KB
/
Copy pathapp.js
File metadata and controls
233 lines (205 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
(function () {
'use strict';
/** Storage keys */
const STORAGE_KEY = 'memo.notes.v1';
/** DOM refs */
const noteForm = document.getElementById('noteForm');
const noteIdInput = document.getElementById('noteId');
const titleInput = document.getElementById('noteTitle');
const contentInput = document.getElementById('noteContent');
const colorSelect = document.getElementById('noteColor');
const pinnedInput = document.getElementById('notePinned');
const notesContainer = document.getElementById('notesContainer');
const emptyState = document.getElementById('emptyState');
const searchInput = document.getElementById('searchInput');
const newNoteButton = document.getElementById('newNoteButton');
const saveButton = document.getElementById('saveButton');
/** Utils */
function generateId() {
return 'n_' + Math.random().toString(36).slice(2) + Date.now().toString(36);
}
function nowIso() {
return new Date().toISOString();
}
function formatTime(iso) {
const d = new Date(iso);
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
return `${y}-${m}-${day} ${hh}:${mm}`;
}
function safeText(el, text) {
el.textContent = text || '';
}
/** Data layer */
function loadNotes() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return [];
const parsed = JSON.parse(raw);
if (!Array.isArray(parsed)) return [];
return parsed;
} catch (e) {
console.error('Failed to load notes', e);
return [];
}
}
function saveNotes(notes) {
try {
const serialized = JSON.stringify(notes);
localStorage.setItem(STORAGE_KEY, serialized);
} catch (e) {
console.error('Failed to save notes', e);
}
}
/** State */
let notes = loadNotes();
let query = '';
/** Derived */
function getFilteredNotes() {
if (!query) return sortNotes(notes);
const q = query.toLowerCase();
return sortNotes(notes.filter(n =>
(n.title && n.title.toLowerCase().includes(q)) ||
(n.content && n.content.toLowerCase().includes(q))
));
}
function sortNotes(list) {
return [...list].sort((a, b) => {
if (a.pinned && !b.pinned) return -1;
if (!a.pinned && b.pinned) return 1;
return (b.updatedAt || b.createdAt).localeCompare(a.updatedAt || a.createdAt);
});
}
/** Render */
function render() {
const list = getFilteredNotes();
notesContainer.innerHTML = '';
if (list.length === 0) {
emptyState.removeAttribute('hidden');
return;
}
emptyState.setAttribute('hidden', '');
const tpl = document.getElementById('noteCardTemplate');
for (const note of list) {
const node = tpl.content.firstElementChild.cloneNode(true);
node.style.background = note.color || '#0e1118';
const titleEl = node.querySelector('.note-card__title');
const contentEl = node.querySelector('.note-card__content');
const timeEl = node.querySelector('.note-card__time');
safeText(titleEl, note.title);
safeText(contentEl, note.content);
timeEl.setAttribute('datetime', note.updatedAt || note.createdAt);
safeText(timeEl, formatTime(note.updatedAt || note.createdAt));
// wiring controls
node.querySelector('.edit-btn').addEventListener('click', () => editNote(note.id));
node.querySelector('.delete-btn').addEventListener('click', () => deleteNote(note.id));
node.querySelector('.pin-btn').addEventListener('click', () => togglePin(note.id));
// keyboard shortcuts on card
node.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { editNote(note.id); }
if (e.key === 'Delete') { deleteNote(note.id); }
});
notesContainer.appendChild(node);
}
}
/** Actions */
function resetFormForNew() {
noteIdInput.value = '';
titleInput.value = '';
contentInput.value = '';
colorSelect.value = '#fff9c4';
pinnedInput.checked = false;
titleInput.focus();
saveButton.textContent = '保存';
}
function editNote(id) {
const note = notes.find(n => n.id === id);
if (!note) return;
noteIdInput.value = note.id;
titleInput.value = note.title || '';
contentInput.value = note.content || '';
colorSelect.value = note.color || '#fff9c4';
pinnedInput.checked = !!note.pinned;
titleInput.focus();
saveButton.textContent = '更新';
window.scrollTo({ top: 0, behavior: 'smooth' });
}
function deleteNote(id) {
const i = notes.findIndex(n => n.id === id);
if (i === -1) return;
notes.splice(i, 1);
saveNotes(notes);
render();
}
function togglePin(id) {
const note = notes.find(n => n.id === id);
if (!note) return;
note.pinned = !note.pinned;
note.updatedAt = nowIso();
saveNotes(notes);
render();
}
/** Events */
noteForm.addEventListener('submit', (e) => {
e.preventDefault();
const title = titleInput.value.trim();
const content = contentInput.value.trim();
const color = colorSelect.value;
const pinned = pinnedInput.checked;
if (!title || !content) return;
const existingId = noteIdInput.value;
if (existingId) {
const note = notes.find(n => n.id === existingId);
if (!note) return;
note.title = title;
note.content = content;
note.color = color;
note.pinned = pinned;
note.updatedAt = nowIso();
} else {
const newNote = {
id: generateId(),
title,
content,
color,
pinned,
createdAt: nowIso(),
updatedAt: null
};
notes.push(newNote);
}
saveNotes(notes);
resetFormForNew();
render();
});
noteForm.addEventListener('reset', () => {
setTimeout(resetFormForNew, 0);
});
newNoteButton.addEventListener('click', () => {
resetFormForNew();
});
searchInput.addEventListener('input', () => {
query = searchInput.value.trim();
render();
});
// initial render
resetFormForNew();
render();
// basic runtime self-check
(function selfCheck() {
const sample = { id: generateId(), title: '测试', content: '仅用于自检', color: '#bbdefb', pinned: false, createdAt: nowIso(), updatedAt: null };
const before = loadNotes();
try {
saveNotes([...before, sample]);
const after = loadNotes();
const added = after.find(n => n.id === sample.id);
console.log('[SelfCheck] storage', added ? { ok: true } : { ok: false });
} finally {
// cleanup
saveNotes(before);
}
})();
})();