-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
451 lines (402 loc) · 18.4 KB
/
script.js
File metadata and controls
451 lines (402 loc) · 18.4 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
/*
script.js
Shared site logic for index, gallery, and manage pages.
- Adds small "magical nostalgic" animations behavior (motes, glimmer CTA, illum initial)
- Persistence in localStorage (key = 'scriptorium_books')
- Seed data included at top (3 sample books)
- To reset: localStorage.removeItem('scriptorium_books') OR use Reset Demo Data button on Manage page.
Seeded data (same 3 items):
- b1: The Willow Grimoire (E. Rowan)
- b2: Lanterns at Dawn (M. Harth)
- b3: Stoneletters (F. Quill)
Future backend: Replace loadBooks/saveBooks with fetch() calls to /api/works (GET/POST/PUT/DELETE).
*/
/* -------------------- Utilities -------------------- */
const STORAGE_KEY = 'scriptorium_books';
const YEAR_EL = document.getElementById('year');
if (YEAR_EL) YEAR_EL.textContent = new Date().getFullYear();
const $ = sel => document.querySelector(sel);
const $$ = sel => Array.from(document.querySelectorAll(sel));
const uid = (p='id') => p + Math.random().toString(36).slice(2,9);
const safeParse = raw => { try { return JSON.parse(raw); } catch(e){ return null; } };
const average = arr => { if(!arr || arr.length===0) return 0; return Math.round((arr.reduce((a,b)=>a+b,0)/arr.length)*10)/10; };
/* accessible toast */
function toast(msg, timeout=1600){
const t = document.createElement('div');
t.className = 'toast';
t.setAttribute('role','status');
t.setAttribute('aria-live','polite');
t.textContent = msg;
Object.assign(t.style, {
position: 'fixed',
right: '18px',
bottom: '18px',
background: '#2b2b2b',
color: '#fff',
padding: '8px 12px',
borderRadius: '8px',
zIndex: 9999,
opacity: '1',
transition: 'opacity 300ms ease, transform 300ms ease'
});
document.body.appendChild(t);
setTimeout(()=>{ t.style.opacity='0'; t.style.transform='translateY(8px)'; }, timeout - 200);
setTimeout(()=>{ t.remove(); }, timeout);
}
/* -------------------- Data layer -------------------- */
function seedData(){
const examples = [
{id:'b1',title:'The Willow Grimoire',author:'E. Rowan',thumbnail:'https://picsum.photos/seed/1/400/600',blurb:'A sorrowful tale of a wandering bard.',tags:['fantasy','poetry'],favorites:false,ratings:[5,4]},
{id:'b2',title:'Lanterns at Dawn',author:'M. Harth',thumbnail:'https://picsum.photos/seed/2/400/600',blurb:'Short novellas about forgotten hamlets.',tags:['shorts','nostalgia'],favorites:true,ratings:[4,4,5]},
{id:'b3',title:'Stoneletters',author:'F. Quill',thumbnail:'https://picsum.photos/seed/3/400/600',blurb:'Illustrated folktales and sketches.',tags:['illustration','folk'],favorites:false,ratings:[3,4]}
];
localStorage.setItem(STORAGE_KEY, JSON.stringify(examples));
return examples;
}
function loadBooks(){
const raw = localStorage.getItem(STORAGE_KEY);
const data = safeParse(raw);
if(!data || !Array.isArray(data) || data.length===0) return seedData();
return data;
}
function saveBooks(list){
localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
}
/* -------------------- CRUD & Actions -------------------- */
function addBook(payload){
const list = loadBooks();
const entry = Object.assign({id: uid('b'), favorites:false, ratings:[]}, payload);
list.unshift(entry);
saveBooks(list);
return entry;
}
function deleteBook(id){
let list = loadBooks();
list = list.filter(b => b.id !== id);
saveBooks(list);
return list;
}
function updateBook(id, patch){
const list = loadBooks().map(b => b.id === id ? Object.assign({}, b, patch) : b);
saveBooks(list);
return list;
}
function toggleFavorite(id){
const list = loadBooks().map(b => {
if(b.id === id) b.favorites = !b.favorites;
return b;
});
saveBooks(list);
return list;
}
function rateBook(id, value){
const list = loadBooks().map(b => {
if(b.id === id){
b.ratings = b.ratings || [];
b.ratings.push(Number(value));
}
return b;
});
saveBooks(list);
return list;
}
/* -------------------- Rendering Helpers -------------------- */
function escapeHtml(str){ return String(str||'').replace(/[&<>"']/g, (m)=>({ '&':'&','<':'<','>':'>','"':'"',"'":''' }[m])); }
function shorten(s,n){ if(!s) return ''; return s.length>n? s.slice(0,n-1)+'…': s; }
function thumbnailPlaceholder(){ return 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="400" height="600"><rect fill="%23efe7d9" width="100%" height="100%"/><text x="50%" y="50%" font-size="20" fill="%236a1b1b" text-anchor="middle" font-family="serif">No Image</text></svg>'; }
function renderStars(n){
if(!n) return '<span class="stars" data-filled="0">☆☆☆☆☆</span>';
const full = Math.round(n);
return `<span class="stars" data-filled="${full}">${'★'.repeat(full)}${'☆'.repeat(5-full)}</span>`;
}
function makeCardHTML(book){
const avg = average(book.ratings);
return `
<article class="work-card" data-id="${book.id}" tabindex="0" aria-labelledby="title-${book.id}">
<div class="card-top">
<img src="${book.thumbnail || thumbnailPlaceholder()}" alt="Cover of ${escapeHtml(book.title)}" loading="lazy">
<div class="meta">
<div id="title-${book.id}" class="title">${escapeHtml(book.title)}</div>
<small>by ${escapeHtml(book.author)}</small>
<div class="rating" aria-label="Average rating">${renderStars(avg)} <small>${avg || ''}</small></div>
</div>
</div>
<p class="excerpt">${escapeHtml(shorten(book.blurb,120))}</p>
<div class="card-actions" style="display:flex;gap:.5rem;align-items:center">
<button class="btn read-btn" data-action="read" aria-label="Read ${escapeHtml(book.title)}">Read</button>
<button class="icon-btn favorite-btn" data-action="favorite" aria-label="Toggle favorite">
<span class="heart" aria-hidden="true">${book.favorites? '♥':'♡'}</span>
</button>
<button class="icon-btn edit-btn" data-action="edit" aria-label="Edit">✎</button>
<button class="icon-btn del-btn" data-action="delete" aria-label="Delete">🗑</button>
</div>
</article>
`;
}
/* -------------------- Init per page -------------------- */
document.addEventListener('DOMContentLoaded', () => {
initNavToggle();
initIllum(); // small entrance for illuminated initial
const page = document.body.dataset.page || 'home';
if(page === 'home') initHome();
if(page === 'gallery') initGallery();
if(page === 'manage') initManage();
});
/* -------------------- UI helpers -------------------- */
function initNavToggle(){
const btn = document.getElementById('nav-toggle');
const nav = document.getElementById('primary-nav');
if(!btn || !nav) return;
btn.addEventListener('click', ()=>{
const expanded = btn.getAttribute('aria-expanded') === 'true';
btn.setAttribute('aria-expanded', String(!expanded));
nav.style.display = expanded ? '' : 'block';
btn.focus();
});
}
function initIllum(){
// small sparkle around the illuminated initial on first page load
const illum = document.querySelector('.hero-title .illumin');
if(!illum) return;
// subtle flicker + tiny particles
illum.animate([{opacity:.9, transform:'translateY(6px) scale(.98)'},{opacity:1, transform:'translateY(0) scale(1)'}], {duration:900, easing:'cubic-bezier(.2,.9,.2,1)'});
// create tiny particle burst once
if(window.matchMedia('(prefers-reduced-motion: no-preference)').matches){
for(let i=0;i<6;i++){
const p = document.createElement('span');
p.className='spark';
Object.assign(p.style,{
position:'absolute',width:'6px',height:'6px',background:'rgba(184,134,11,0.9)',borderRadius:'50%',pointerEvents:'none',top:`${illum.getBoundingClientRect().top + 4}px`,left:`${illum.getBoundingClientRect().left + 6}px`,opacity:0,transform:'translate(0,0) scale(.6)'
});
document.body.appendChild(p);
// animate then remove
setTimeout(()=>{ p.animate([{opacity:1, transform:`translate(${(Math.random()-0.5)*60}px, ${(Math.random()-0.9)*60}px) scale(1)`},{opacity:0, transform:`translate(${(Math.random()-0.5)*90}px, ${(Math.random()-1.6)*120}px) scale(.2)`}], {duration:1200 + Math.random()*600, easing:'cubic-bezier(.2,.9,.2,1)'}); setTimeout(()=>p.remove(), 2000); }, 140 + i*60);
}
}
}
/* pulse helper for hearts */
function pulseHeart(button){
const heart = button.querySelector('.heart');
if(!heart) return;
heart.classList.add('pulse');
setTimeout(()=> heart.classList.remove('pulse'), 420);
}
/* animate stars (stagger, small visual) */
function animateStars(){
document.querySelectorAll('.stars').forEach((el, idx) => {
const filled = Number(el.dataset.filled || 0);
if(filled > 0 && window.matchMedia('(prefers-reduced-motion: no-preference)').matches){
el.style.opacity = '0';
el.style.transform = 'translateY(6px)';
setTimeout(()=>{ el.style.transition = 'transform 320ms ease, opacity 320ms ease'; el.style.opacity = '1'; el.style.transform = 'translateY(0)'; }, idx*80);
}
});
}
/* -------------------- Home -------------------- */
function initHome(){
const scroller = document.getElementById('recent-scroller');
if(!scroller) return;
const list = loadBooks();
scroller.innerHTML = list.slice(0,8).map(b => {
return `<div class="recent-card" tabindex="0"><img class="thumbnail" src="${b.thumbnail||thumbnailPlaceholder()}" alt=""><strong>${escapeHtml(b.title)}</strong><small>by ${escapeHtml(b.author)}</small></div>`;
}).join('');
// gentle auto-scroll (respect visibility and reduced-motion)
if(window.matchMedia('(prefers-reduced-motion: no-preference)').matches){
let x = 0;
const speed = 0.2;
let raf;
function frame(){
if(document.hidden) { raf = requestAnimationFrame(frame); return; }
x += speed;
if(scroller.scrollWidth - scroller.clientWidth <= x) x = 0;
scroller.scrollLeft = Math.round(x);
raf = requestAnimationFrame(frame);
}
raf = requestAnimationFrame(frame);
scroller.addEventListener('mouseenter', ()=> cancelAnimationFrame(raf));
scroller.addEventListener('focusin', ()=> cancelAnimationFrame(raf));
}
}
/* -------------------- Gallery -------------------- */
function initGallery(){
const grid = document.getElementById('library-grid');
const search = document.getElementById('search-input');
const sort = document.getElementById('sort-select');
const modal = document.getElementById('detail-modal');
const modalContent = document.getElementById('modal-content');
const modalClose = document.getElementById('modal-close');
const favToggle = document.getElementById('show-favorites');
function refresh(){
let books = loadBooks();
const qv = search?.value?.trim()?.toLowerCase();
if(qv){
books = books.filter(b => (b.title + ' ' + b.author + ' ' + (b.tags||[]).join(' ')).toLowerCase().includes(qv));
}
if(favToggle && favToggle.checked) books = books.filter(b => b.favorites);
const s = sort?.value;
if(s === 'highest') books = books.slice().sort((a,b) => average(b.ratings) - average(a.ratings));
if(s === 'title') books = books.slice().sort((a,b) => a.title.localeCompare(b.title));
grid.innerHTML = books.map(makeCardHTML).join('') || '<p>No works found.</p>';
attachGridHandlers();
animateStars();
}
function attachGridHandlers(){
grid.querySelectorAll('[data-action]').forEach(btn => {
btn.onclick = (e) => {
const action = btn.getAttribute('data-action');
const card = btn.closest('.work-card');
const id = card?.dataset?.id;
if(!id) return;
if(action === 'read') openModal(id);
if(action === 'favorite'){ toggleFavorite(id); toast('Favorite updated'); refresh(); pulseHeart(btn); }
if(action === 'delete'){ if(confirm('Delete this work?')){ deleteBook(id); toast('Deleted'); refresh(); } }
if(action === 'edit'){ openEditInline(id); }
};
});
}
function openModal(id){
const book = loadBooks().find(b => b.id === id);
if(!book) return;
modal.setAttribute('aria-hidden','false');
const avg = average(book.ratings);
modalContent.innerHTML = `
<h2 id="modal-title" class="section-heading">${escapeHtml(book.title)}</h2>
<div style="display:flex;gap:1rem;align-items:flex-start;flex-wrap:wrap">
<img src="${book.thumbnail || thumbnailPlaceholder()}" alt="" style="width:220px;height:auto;border-radius:10px">
<div style="flex:1;min-width:220px">
<p><strong>Author:</strong> ${escapeHtml(book.author)}</p>
<p><strong>Tags:</strong> ${escapeHtml((book.tags||[]).join(', '))}</p>
<p>${escapeHtml(book.blurb)}</p>
<p><strong>Average Rating:</strong> ${avg || 'No ratings yet'}</p>
<div style="display:flex;gap:.4rem;margin-top:.6rem;align-items:center">
<label for="rate-select">Rate:</label>
<select id="rate-select" aria-label="Rate this work">
<option value="">--</option>
<option>1</option><option>2</option><option>3</option><option>4</option><option>5</option>
</select>
<button id="fav-toggle-modal" class="icon-btn" aria-label="Toggle favorite">${book.favorites? '♥':'♡'}</button>
<button id="modal-delete" class="icon-btn" title="Delete">🗑</button>
</div>
</div>
</div>
`;
document.getElementById('rate-select').onchange = (e) => {
const v = e.target.value;
if(!v) return;
rateBook(id, v);
toast('Thanks for rating');
openModal(id);
refresh();
};
document.getElementById('fav-toggle-modal').onclick = () => { toggleFavorite(id); toast('Favorite toggled'); openModal(id); refresh(); };
document.getElementById('modal-delete').onclick = () => { if(confirm('Delete?')){ deleteBook(id); toast('Deleted'); closeModal(); refresh(); } };
const panel = modal.querySelector('.modal-panel');
panel && panel.focus();
}
function closeModal(){ modal.setAttribute('aria-hidden','true'); modalContent.innerHTML = ''; }
modalClose && (modalClose.onclick = closeModal);
modal && (modal.onclick = (e) => { if(e.target === modal) closeModal(); });
document.addEventListener('keydown', e => { if(e.key === 'Escape') closeModal(); });
function openEditInline(id){
window.location.href = `manage.html#edit=${id}`;
}
[search, sort, favToggle].forEach(el => { if(!el) return; el.addEventListener('input', refresh); el.addEventListener('change', refresh); });
refresh();
}
/* -------------------- Manage -------------------- */
function initManage(){
const form = document.getElementById('add-form');
const listEl = document.getElementById('manage-list');
const resetBtn = document.getElementById('reset-storage');
function renderList(){
const list = loadBooks();
listEl.innerHTML = list.map(b => {
const avg = average(b.ratings);
return `
<div class="manage-item" data-id="${b.id}">
<img src="${b.thumbnail||thumbnailPlaceholder()}" alt="" style="width:64px;height:84px;border-radius:8px;object-fit:cover">
<div>
<div><strong>${escapeHtml(b.title)}</strong> <small>by ${escapeHtml(b.author)}</small></div>
<div style="font-size:.9rem;color:rgba(43,43,43,0.7)">${shorten(b.blurb,88)}</div>
<div style="margin-top:.3rem">Rating: ${avg||'—'} • Tags: ${escapeHtml((b.tags||[]).join(', '))}</div>
</div>
<div class="actions">
<button class="btn edit" data-action="edit">Edit</button>
<button class="btn ghost del" data-action="delete">Delete</button>
<button class="btn" data-action="fav">${b.favorites? 'Unfav':'Fav'}</button>
</div>
</div>
`;
}).join('');
attachManageHandlers();
}
function attachManageHandlers(){
listEl.querySelectorAll('[data-action]').forEach(btn => {
btn.onclick = (e) => {
const card = btn.closest('.manage-item');
const id = card?.dataset?.id;
const action = btn.getAttribute('data-action');
if(action === 'delete'){ if(confirm('Delete this item?')){ deleteBook(id); toast('Deleted'); renderList(); } }
if(action === 'fav'){ toggleFavorite(id); toast('Favorite toggled'); renderList(); }
if(action === 'edit'){ openInlineEdit(id); }
};
});
}
form && form.addEventListener('submit', (e) => {
e.preventDefault();
const title = (document.getElementById('title').value || '').trim();
const author = (document.getElementById('author').value || '').trim();
const thumbnail = (document.getElementById('thumbnail').value || '').trim();
const tags = (document.getElementById('tags').value || '').split(',').map(s => s.trim()).filter(Boolean);
const blurb = (document.getElementById('blurb').value || '').trim();
if(!title || !author){ toast('Title & author required'); return; }
addBook({title,author,thumbnail,blurb,tags});
form.reset();
toast('Added new work');
renderList();
});
function openInlineEdit(id){
const books = loadBooks();
const item = books.find(b => b.id === id);
if(!item) return;
const newTitle = prompt('Edit title', item.title);
if(newTitle === null) return;
const newAuthor = prompt('Edit author', item.author);
if(newAuthor === null) return;
const newBlurb = prompt('Edit blurb', item.blurb);
if(newBlurb === null) return;
const newThumb = prompt('Edit thumbnail URL (leave blank for none)', item.thumbnail || '');
if(newThumb === null) return;
const newTags = prompt('Edit tags (comma separated)', (item.tags||[]).join(', '));
if(newTags === null) return;
updateBook(id, {
title: newTitle.trim(),
author: newAuthor.trim(),
blurb: newBlurb.trim(),
thumbnail: (newThumb || '').trim(),
tags: (newTags || '').split(',').map(s => s.trim()).filter(Boolean)
});
toast('Updated');
renderList();
}
resetBtn && resetBtn.addEventListener('click', () => {
if(confirm('Reset demo data? This will replace your current saved works.')){ seedData(); toast('Demo data reset'); renderList(); }
});
if(window.location.hash){
const h = window.location.hash.slice(1);
if(h.startsWith('edit=')){
const id = h.split('=')[1];
setTimeout(()=> openInlineEdit(id), 220);
window.location.hash = '';
}
}
renderList();
}
/* -------------------- Notes for future backend --------------------
Replace localStorage calls with fetch() to:
GET /api/works
POST /api/works
PUT /api/works/:id
DELETE /api/works/:id
Update UI after responses (optimistic update or re-fetch).
------------------------------------------------------------ */