Files
MangaBom/dist/app.js
2026-11-02 04:08:02 +03:00

40 lines
6.3 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

(() => {
const key = n => 'mangabom.' + n;
const read = (n, fallback) => { try { return JSON.parse(localStorage.getItem(key(n))) ?? fallback; } catch { return fallback; } };
const write = (n, value) => { try { localStorage.setItem(key(n), JSON.stringify(value)); return true; } catch { return false; } };
const $ = s => document.querySelector(s);
const $$ = s => [...document.querySelectorAll(s)];
let favorites = read('favorites', []);
const series = [ ['food','Повелитель дешёвого обеда'],['port','Нулевой причал'],['veranda','Последняя веранда'],['realtor','Риелтор грёз'],['volley','Второе касание'],['warm','Пока в доме тепло'],['dry','Сухая сторона'],['bar','БАР-БАР'] ];
const settings = read('settings', {});
document.documentElement.classList.toggle('motion-reduced', !!settings.reduceMotion);
document.documentElement.classList.toggle('compact-cards', !!settings.compactCards);
const profile = read('profile', null);
if (profile) $$('.auth-button').forEach(a=>{a.href='account.html';a.querySelector('span:last-child').textContent='Кабинет';});
function syncFavorites() {
$$('[data-favorite]').forEach(b=>{const selected=favorites.includes(b.dataset.favorite);b.setAttribute('aria-pressed',String(selected));b.textContent=selected?'♥ В избранном':'♡ В избранное';});
if (!$('#favorites-list')) return;
const list=$('#favorites-list'); list.replaceChildren();
const chosen=series.filter(([id])=>favorites.includes(id));
if(!chosen.length){const p=document.createElement('p');p.className='empty-state';p.textContent='Пока пусто. Выбери любимые истории в каталоге.';list.append(p);}
chosen.forEach(([id,title])=>{const row=document.createElement('div');row.className='favorite-row';const a=document.createElement('a');a.href=`series-${id}.html`;a.textContent=title;const b=document.createElement('button');b.type='button';b.dataset.removeFavorite=id;b.textContent='Убрать';row.append(a,b);list.append(row);});
}
syncFavorites();
document.addEventListener('click',e=>{const b=e.target.closest('[data-favorite],[data-remove-favorite]');if(!b)return;const id=b.dataset.favorite||b.dataset.removeFavorite;favorites=favorites.includes(id)?favorites.filter(x=>x!==id):[...favorites,id];write('favorites',favorites);syncFavorites();});
function filterCatalog(){const text=($('#catalog-search')?.value||'').trim().toLocaleLowerCase('ru');const genre=$('#genre-filter')?.value||'all';let count=0;$$('.catalog-card').forEach(c=>{const visible=c.dataset.title.includes(text)&&(genre==='all'||c.dataset.genre===genre);c.hidden=!visible;count+=Number(visible);});if($('#catalog-count'))$('#catalog-count').textContent=`Найдено: ${count}`;if($('#catalog-empty'))$('#catalog-empty').hidden=count!==0;}
$('#catalog-search')?.addEventListener('input',filterCatalog);$('#genre-filter')?.addEventListener('change',filterCatalog);
const vote=read('vote',null);if(vote){const radio=$(`input[name=series][value="${vote}"]`);if(radio)radio.checked=true;if($('#vote-status'))$('#vote-status').textContent='Твой выбор сохранён в этом браузере. Его можно изменить.';}
$('#vote-form')?.addEventListener('submit',e=>{e.preventDefault();const value=new FormData(e.currentTarget).get('series');if(!value)return;const ok=write('vote',value);$('#vote-status').textContent=ok?'Выбор сохранён на этом устройстве. В редакцию голос не отправлен.':'Браузер не разрешил сохранить выбор.';});
function selectDay(day){$$('[data-event-day]').forEach(e=>e.hidden=!!day&&e.dataset.eventDay!==day);$$('[data-day]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.day===day)));}
$$('[data-day]').forEach(b=>b.addEventListener('click',()=>selectDay(b.getAttribute('aria-pressed')==='true'?'':b.dataset.day)));$('#reset-days')?.addEventListener('click',()=>selectDay(''));
$('#demo-login')?.addEventListener('submit',e=>{e.preventDefault();const name=String(new FormData(e.currentTarget).get('name')||'').trim().slice(0,40)||'читатель';write('profile',{name});location.href='account.html';});
if($('#reader-name'))$('#reader-name').textContent=profile?.name||'читатель';
$('#logout')?.addEventListener('click',()=>{try{localStorage.removeItem(key('profile'));}catch{}location.href='login.html';});
[['reduce-motion','reduceMotion'],['compact-cards','compactCards']].forEach(([id,setting])=>{const field=$('#'+id);if(!field)return;field.checked=!!settings[setting];field.addEventListener('change',()=>{settings[setting]=field.checked;write('settings',settings);document.documentElement.classList.toggle(id==='reduce-motion'?'motion-reduced':'compact-cards',field.checked);});});
$('#support-form')?.addEventListener('submit',e=>{e.preventDefault();const amount=new FormData(e.currentTarget).get('amount');$('#support-status').textContent=`Выбрано ${amount} ₽. Это предпросмотр: платёж не создаётся, деньги не списываются.`;});
$('#copy-site')?.addEventListener('click',async()=>{const url=new URL('index.html',location.href).href;try{await navigator.clipboard.writeText(url);$('#copy-status').textContent='Ссылка скопирована.';}catch{$('#copy-status').textContent=url;}});
const draft=read('draft',null);if($('#contact-form')&&draft){$('#contact-form').elements.topic.value=draft.topic;$('#contact-form').elements.message.value=draft.message;}
$('#contact-form')?.addEventListener('submit',e=>{e.preventDefault();const data=new FormData(e.currentTarget);const ok=write('draft',{topic:data.get('topic'),message:data.get('message')});$('#contact-status').textContent=ok?'Черновик сохранён на этом устройстве. Сообщение не отправлено редакции.':'Браузер не разрешил сохранить черновик.';});
$('#clear-local')?.addEventListener('click',()=>{try{Object.keys(localStorage).filter(k=>k.startsWith('mangabom.')).forEach(k=>localStorage.removeItem(k));$('#clear-status').textContent='Локальные данные MANGABOM удалены.';}catch{$('#clear-status').textContent='Не удалось получить доступ к хранилищу.';}});
})();