fix: improve calculator accessibility and async result handling

This commit is contained in:
nyan404 committed 2026-11-14 01:34:20 +03:00
1 parent ea2f0fbe05
commit bb21a767d7
9 files changed
+473 -105

No files matched your search

+47 -9
View File
@@ -10,39 +10,77 @@
.intro, .hint, .status { color: #62675f; line-height: 1.55; } .intro { margin: 13px 0 31px; max-width: 640px; }
.topnav { display:flex; justify-content:space-between; gap:15px; align-items:center; margin-bottom:52px; padding-bottom:18px; border-bottom:1px solid #e6e7e2; } .brand { color:#1d622e; font-weight:800; text-decoration:none; font-size:1.05rem; } .topnav a:not(.brand) { color:#4f554d; text-decoration:none; font-size:.92rem; }
.auth { max-width:470px; margin: 14vh auto; border:1px solid #e1e4dc; border-radius:14px; padding:28px; box-shadow:0 12px 35px #3340130b; }
.auth label, label { display:grid; gap:7px; color:#40453f; font-size:.84rem; font-weight:700; } input, select, textarea, button { font:inherit; } input, select, textarea { width:100%; min-height:44px; padding:10px 12px; border:1px solid #cfd4cb; border-radius:8px; background:#fff; color:#20241f; } textarea { min-height:105px; resize:vertical; } input:focus, select:focus, textarea:focus { outline:3px solid #2f813529; border-color:#2f8135; } button:focus-visible, a:focus-visible { outline:3px solid var(--focus); outline-offset:3px; }
.auth label, label { display:grid; gap:7px; color:#40453f; font-size:.84rem; font-weight:700; } input, select, textarea, button { font:inherit; } input, select, textarea { font-size:1rem; width:100%; min-height:44px; padding:10px 12px; border:1px solid #cfd4cb; border-radius:8px; background:#fff; color:#20241f; } textarea { min-height:105px; resize:vertical; } input:focus, select:focus, textarea:focus { outline:3px solid #2f813529; border-color:#2f8135; } input:focus-visible, select:focus-visible, textarea:focus-visible, button:focus-visible, a:focus-visible { outline:3px solid var(--focus); outline-offset:3px; }
.types { display:grid; grid-template-columns:repeat(2, minmax(0,1fr)); gap:10px; margin:25px 0 27px; } .type { display:flex; align-items:center; min-height:76px; padding:14px; text-align:left; color:#333a32; border:1px solid #dce1d8; border-radius:10px; background:#fff; cursor:pointer; font-weight:700; } .type::before { content:""; width:14px; height:14px; border:1px solid #aeb7ab; border-radius:50%; margin-right:11px; flex:0 0 auto; } .type.active { border-color:#237530; box-shadow:inset 0 0 0 1px #237530; } .type.active::before { border:4px solid #237530; }
.panel { border:1px solid #e0e4dc; border-radius:14px; padding:28px; box-shadow:0 14px 40px #3142190a; } .grid { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:16px; } .wide { grid-column:1/-1; } .hidden { display:none!important; }
.upload { display:grid; justify-items:center; gap:8px; min-height:150px; padding:24px; text-align:center; border:1px dashed #b8c3b3; border-radius:10px; background:#fbfdf9; color:#596259; cursor:pointer; } .upload strong { color:#333a32; } .upload input { display:none; } .files { margin:10px 0 0; padding-left:18px; color:#5a6258; font-size:.86rem; }
.feather { display:grid; grid-template-columns:110px 1fr 1.3fr auto; gap:9px; align-items:end; margin-bottom:9px; } .remove { min-height:44px; padding:9px; background:#fff; border:1px solid #d9aaa5; color:#9b423a; border-radius:8px; cursor:pointer; } button.primary { min-height:48px; padding:10px 18px; border:1px solid #1e6a2b; border-radius:8px; background:#1e6a2b; color:#fff; cursor:pointer; font-weight:750; } button.primary:hover { background:#165521; } button.secondary { border:1px solid #bbc5b8; border-radius:8px; padding:9px 12px; background:#fff; color:#354234; cursor:pointer; }
.upload { display:grid; justify-items:center; gap:8px; min-height:150px; padding:24px; text-align:center; border:1px dashed #b8c3b3; border-radius:10px; background:#fbfdf9; color:#596259; cursor:pointer; } .upload strong { color:#333a32; } .upload input { max-width:100%; font-size:1rem; } .upload:focus-within { outline:3px solid var(--focus); outline-offset:3px; } .files { margin:10px 0 0; padding-left:18px; color:#5a6258; font-size:.86rem; }
.feather { display:grid; grid-template-columns:110px 1fr 1.3fr auto; gap:9px; align-items:end; margin-bottom:9px; } .remove { min-height:44px; padding:9px; background:#fff; border:1px solid #d9aaa5; color:#9b423a; border-radius:8px; cursor:pointer; } button.primary { min-height:48px; padding:10px 18px; border:1px solid #1e6a2b; border-radius:8px; background:#1e6a2b; color:#fff; cursor:pointer; font-weight:750; } button.primary:hover { background:#165521; } button.secondary { min-height:44px; border:1px solid #bbc5b8; border-radius:8px; padding:9px 12px; background:#fff; color:#354234; cursor:pointer; }
.actions { display:flex; justify-content:space-between; align-items:center; gap:16px; margin-top:25px; } .error { min-height:22px; color:#a13d35; white-space:pre-wrap; } .success { margin-top:24px; padding:18px; border-left:4px solid #268038; background:#f4fbf3; color:#244b2c; border-radius:7px; }
@media (max-width:640px) { main{width:calc(100% - 26px);padding-top:26px}.topnav{margin-bottom:34px}.types,.grid{grid-template-columns:1fr}.panel{padding:20px}.wide{grid-column:auto}.feather{grid-template-columns:1fr}.actions{align-items:stretch;flex-direction:column-reverse}.actions button{width:100%} }
button:disabled { opacity:.55; cursor:not-allowed; }
input:user-invalid, textarea:user-invalid { border-color:#a13d35; }
</style>
</head>
<body><main>
<nav class="topnav"><a class="brand" href="/belki">Беличья нора</a><a href="/belki">Калькулятор отчётов</a></nav>
<section id="app"><h1>Новая заявка</h1><p class="intro">Заполните форму, и администратор получит заявку. Готовить форумную отпись не нужно.</p>
<div class="types" role="radiogroup" aria-label="Тип заявки">
<div class="types" role="group" aria-label="Тип заявки">
<button class="type active" type="button" data-type="feather_donation">Пожертвовать перо отряду</button><button class="type" type="button" data-type="kitten">Хочу стать бельчонком</button><button class="type" type="button" data-type="flying_squirrel">Хочу стать белкой-летягой</button><button class="type" type="button" data-type="curator">Хочу стать куратором</button>
</div>
<form id="form" class="panel"><div class="grid">
<label>Имя кота<input name="name" required></label><label>ID кота<input name="character_id" type="number" min="1" required></label>
<label id="vkField" class="wide">Ссылка на страницу VK <span class="hint">(необязательно)</span><input name="vk_link" type="text" inputmode="url" placeholder="vk.com/id… или vk.ru/id…"></label>
<section id="kittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Перетащите изображение сюда или выберите файл</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="kittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Выберите изображение</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="curatorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
<section id="flyingFields" class="wide hidden"><label>Уже сдавали практику?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="practiceLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/... или https://vk.com/... "></label></section>
<section id="featherFields" class="wide"><h2>Перья для казны</h2><p class="hint">Укажите цвет, количество и откуда получены перья.</p><div id="feathers"></div><button id="addFeather" class="secondary" type="button">Добавить перо</button></section>
</div><p id="error" class="error" role="alert"></p><div class="actions"><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden"></div>
</div><p id="error" class="error" role="alert"></p><div class="actions"><button class="primary" type="submit">Отправить заявку</button></div></form><div id="success" class="success hidden" role="status"></div>
</section>
</main><script>
/* Form helpers manage repeatable feather rows, conditional sections, image
uploads, and final serialization into the applications API payload. */
const form=document.querySelector('#form'), error=document.querySelector('#error'); let active='feather_donation';
const form=document.querySelector('#form'), error=document.querySelector('#error'); let active='feather_donation', submitting=false;
function addFeather(data={}){const row=document.createElement('div');row.className='feather';row.innerHTML='<label>Количество<input data-field="amount" type="number" min="1" required></label><label>Цвет<input data-field="color" placeholder="например, синие" required></label><label>Источник добычи<input data-field="source" placeholder="личные запасы, осмотр дупла…" required></label><button class="remove" type="button">Убрать</button>';Object.entries(data).forEach(([k,v])=>{const el=row.querySelector(`[data-field="${k}"]`);if(el)el.value=v});row.querySelector('.remove').onclick=()=>row.remove();document.querySelector('#feathers').append(row)} addFeather();document.querySelector('#addFeather').onclick=()=>addFeather();
function setVisible(selector,visible){const section=document.querySelector(selector);section.classList.toggle('hidden',!visible);section.querySelectorAll('input,select,textarea,button').forEach(field=>field.disabled=!visible)}
function sync(){setVisible('#featherFields',active==='feather_donation');setVisible('#kittenFields',active==='kitten');setVisible('#curatorFields',active==='curator');setVisible('#flyingFields',active==='flying_squirrel');setVisible('#vkField',active==='flying_squirrel');const practiced=document.querySelector('[name="practiced_before"]');setVisible('#practiceLink',active==='flying_squirrel'&&practiced.value==='yes');document.querySelectorAll('.type').forEach(x=>x.classList.toggle('active',x.dataset.type===active))} document.querySelectorAll('.type').forEach(b=>b.onclick=()=>{active=b.dataset.type;sync()});sync();
function sync(){setVisible('#featherFields',active==='feather_donation');setVisible('#kittenFields',active==='kitten');setVisible('#curatorFields',active==='curator');setVisible('#flyingFields',active==='flying_squirrel');setVisible('#vkField',active==='flying_squirrel');const practiced=document.querySelector('[name="practiced_before"]');setVisible('#practiceLink',active==='flying_squirrel'&&practiced.value==='yes');document.querySelectorAll('.type').forEach(x=>{x.classList.toggle('active',x.dataset.type===active);x.setAttribute('aria-pressed',String(x.dataset.type===active))})} document.querySelectorAll('.type').forEach(b=>b.onclick=()=>{active=b.dataset.type;sync()});sync();
document.querySelector('[name="practiced_before"]').onchange=()=>sync();
document.querySelectorAll('.screenshots').forEach(input=>input.onchange=()=>{const list=input.closest('section').querySelector('.files');list.replaceChildren(...[...input.files].map(file=>{const li=document.createElement('li');li.textContent=file.name;return li}))});
async function uploads(){const items=[];for(const file of [...document.querySelectorAll('.screenshots:not(:disabled)')].flatMap(x=>[...x.files])){const data=await new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(reader.result);reader.onerror=reject;reader.readAsDataURL(file)});const r=await fetch('/api/web/upload',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({name:file.name,type:file.type,data})});const d=await r.json();if(!r.ok)throw new Error(d.error||`Не удалось загрузить ${file.name}`);items.push({type:'photo',url:d.url,name:file.name})}return items}
form.addEventListener('submit',async e=>{e.preventDefault();error.textContent='';try{const data=Object.fromEntries(new FormData(form).entries());data.type=active;data.character_id=Number(data.character_id);data.attachments=await uploads();if(active==='flying_squirrel'){data.practiced_before=data.practiced_before==='yes'}if(active==='feather_donation')data.feathers=[...document.querySelectorAll('.feather')].map(row=>({amount:Number(row.querySelector('[data-field="amount"]').value),color:row.querySelector('[data-field="color"]').value,source:row.querySelector('[data-field="source"]').value}));const r=await fetch('/api/applications',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});const d=await r.json();if(!r.ok)throw new Error(d.error||'Не удалось отправить заявку');const success=document.querySelector('#success');success.textContent=`Заявка №${d.id} отправлена на рассмотрение.`;success.classList.remove('hidden');form.reset();document.querySelector('#feathers').replaceChildren();addFeather();sync()}catch(err){error.textContent=err.message}});
form.addEventListener('submit', async event => {
event.preventDefault();
if (submitting) return;
submitting = true;
const submit = form.querySelector('[type="submit"]');
submit.disabled = true;
submit.textContent = 'Отправляем…';
error.textContent = '';
document.querySelector('#success').classList.add('hidden');
try {
const data = Object.fromEntries(new FormData(form).entries());
data.type = active;
data.character_id = Number(data.character_id);
if (active === 'flying_squirrel') data.practiced_before = data.practiced_before === 'yes';
if (active === 'feather_donation') data.feathers = [...document.querySelectorAll('.feather')].map(row => ({
amount: Number(row.querySelector('[data-field="amount"]').value),
color: row.querySelector('[data-field="color"]').value,
source: row.querySelector('[data-field="source"]').value,
}));
data.attachments = await uploads();
const response = await fetch('/api/applications', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)});
const result = await response.json();
if (!response.ok) throw new Error(result.error || 'Не удалось отправить заявку');
const success = document.querySelector('#success');
success.textContent = `Заявка №${result.id} отправлена на рассмотрение.`;
success.classList.remove('hidden');
form.reset();
document.querySelector('#feathers').replaceChildren();
addFeather();
sync();
} catch (err) { error.textContent = err.message; }
finally {
submitting = false;
submit.disabled = false;
submit.textContent = 'Отправить заявку';
}
});
</script></body></html>