fix: improve calculator accessibility and async result handling
This commit is contained in:
1 parent
ea2f0fbe05
commit
bb21a767d7
9 files changed
+473
-105
No files matched your search
+160
-68
@@ -14,15 +14,25 @@
|
||||
h2 { font: 500 1.55rem/1.15 Georgia, "Times New Roman", serif; } .muted { color: var(--muted); line-height: 1.55; }
|
||||
.tabs { display: flex; gap: 8px; flex-wrap: wrap; margin: 24px 0 16px; }
|
||||
.section-tabs { margin-top: 32px; border-bottom: 1px solid var(--line); padding-bottom: 16px; }
|
||||
.section-tabs button { border-color: transparent; background: transparent; }
|
||||
.section-tabs a { display: inline-flex; align-items: center; min-height: 44px; border: 1px solid transparent; border-radius: 7px; padding: 9px 14px; color: var(--ink); text-decoration: none; }
|
||||
.section-tabs a:hover { background: var(--paper); }
|
||||
.section-tabs a[aria-current="page"] { border-color: var(--ink); text-decoration: underline; text-underline-offset: 5px; }
|
||||
.mode-options { padding: 0; border: 0; min-width: 0; }
|
||||
.mode-options legend { font-weight: 700; }
|
||||
.mode-option { display: flex; align-items: center; gap: 8px; min-height: 48px; padding: 9px 14px; border: 1px solid var(--line); border-radius: 7px; background: var(--paper); cursor: pointer; font-weight: 400; }
|
||||
.mode-option:has(:checked) { border-color: var(--ink); background: var(--ink); color: var(--paper); }
|
||||
.mode-option input { width: 18px; min-height: 18px; margin: 0; accent-color: var(--accent); }
|
||||
.mode-option:focus-within { outline: 3px solid var(--focus); outline-offset: 3px; }
|
||||
button, select, input, textarea { font: inherit; }
|
||||
button { min-height:44px; cursor: pointer; touch-action:manipulation; border: 1px solid #bdb6ad; border-radius: 7px; padding: 9px 14px; background: var(--paper); color: var(--ink); transition: background-color 160ms ease-out, border-color 160ms ease-out, color 160ms ease-out; }
|
||||
button:hover { border-color:var(--accent); background:#fff6e5; } button:focus-visible, a:focus-visible { outline:3px solid var(--focus); outline-offset:3px; }
|
||||
button:hover { border-color:var(--accent); background:#fff6e5; } button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible, textarea:focus-visible { outline:3px solid var(--focus); outline-offset:3px; }
|
||||
button:disabled { opacity: .55; cursor: not-allowed; }
|
||||
input:user-invalid, textarea:user-invalid { border-color: var(--error); }
|
||||
button.active, button.primary { background: var(--ink); color: #fffdfa; border-color: var(--ink); } button.active:hover, button.primary:hover { background:#45413d; }
|
||||
.panel { background: var(--paper); border: 1px solid var(--line); border-radius: 10px; padding: 28px; box-shadow:0 10px 28px #3b30220d; }
|
||||
.grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; align-items: start; }
|
||||
label { display: grid; gap: 6px; color: #403b36; font-weight:700; }
|
||||
input, select, textarea { min-height:44px; width: 100%; border: 1px solid #c8bca9; border-radius: 7px; padding: 9px 12px; background: #fffefa; color: var(--ink); } input:focus,select:focus,textarea:focus { outline:3px solid #b5682433; border-color:var(--accent); }
|
||||
input, select, textarea { min-height:44px; width: 100%; border: 1px solid #c8bca9; border-radius: 7px; padding: 9px 12px; background: #fffefa; color: var(--ink); } input:focus,select:focus,textarea:focus { border-color:var(--accent); }
|
||||
textarea { min-height: 210px; resize: vertical; }
|
||||
.wide { grid-column: 1 / -1; }
|
||||
.actions { display: flex; gap: 10px; margin-top: 18px; }
|
||||
@@ -38,7 +48,8 @@
|
||||
.status-help { margin: -4px 0 0; font-size: .85rem; }
|
||||
@media (max-width: 700px) { .extra-kitten, .time-range { grid-template-columns: 1fr; } }
|
||||
dialog { max-width: min(520px, calc(100% - 32px)); background: var(--paper); color: var(--ink); border: 1px solid #5a524b; border-radius: 10px; padding: 24px; box-shadow:0 24px 80px #211b1855; }
|
||||
dialog::backdrop { background: #211b1866; }
|
||||
dialog:modal { overscroll-behavior: contain; }
|
||||
dialog::backdrop { background: #211b1866; overflow: hidden; overscroll-behavior: contain; }
|
||||
.result { margin-top: 20px; }
|
||||
.hidden { display: none; }
|
||||
.error { color: var(--error); font-weight:700; white-space: pre-wrap; }
|
||||
@@ -47,9 +58,11 @@
|
||||
.application-intro { max-width: 68ch; margin: 0 0 24px; }
|
||||
.application-types { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; margin: 20px 0; }
|
||||
.application-type { min-height: 68px; text-align: left; font-weight: 700; }
|
||||
.application-type[aria-pressed="true"] { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); background: #fff8ef; }
|
||||
.application-type[aria-pressed="true"] { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); background: #fff8ef; text-decoration: underline; text-underline-offset: 4px; }
|
||||
.upload { display: grid; justify-items: center; gap: 8px; min-height: 132px; padding: 20px; text-align: center; border: 1px dashed #b9afa4; border-radius: 7px; background: #fffaf4; color: var(--muted); cursor: pointer; }
|
||||
.upload strong { color: var(--ink); } .upload input { display: none; }
|
||||
.upload strong { color: var(--ink); }
|
||||
.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: var(--muted); }
|
||||
.feather { display: grid; grid-template-columns: 110px 1fr 1.3fr auto; gap: 9px; align-items: end; margin-bottom: 9px; }
|
||||
.remove { color: var(--error); border-color: #d9aaa5; }
|
||||
@@ -70,7 +83,7 @@
|
||||
.panel { padding: 16px; }
|
||||
.section-tabs { margin-top: 24px; padding-bottom: 12px; }
|
||||
.tabs { gap: 6px; margin: 18px 0 14px; }
|
||||
.tabs button { flex: 1 1 144px; }
|
||||
.section-tabs a, .mode-option { flex: 1 1 144px; }
|
||||
.grid, .application-types, .feather { grid-template-columns: 1fr; }
|
||||
.wide { grid-column: auto; }
|
||||
.actions { flex-direction: column; }
|
||||
@@ -94,32 +107,32 @@
|
||||
<h1>Генератор отчётов и калькулятор</h1>
|
||||
<p class="muted">Здесь можно подготовить отчёт, посчитать баллы и подать заявку.</p>
|
||||
|
||||
<nav class="tabs section-tabs" role="tablist" aria-label="Раздел Беличьей норы">
|
||||
<button class="active" id="reportsTab" type="button" role="tab" aria-selected="true" aria-controls="reportsSection" data-section="reports">Отчёты</button>
|
||||
<button id="sentReportsTab" type="button" role="tab" aria-selected="false" aria-controls="sentReportsSection" data-section="sentReports">Отчёты по ID кота</button>
|
||||
<button id="applicationsTab" type="button" role="tab" aria-selected="false" aria-controls="applicationsSection" data-section="applications">Заявки</button>
|
||||
<button id="identityTab" type="button" role="tab" aria-selected="false" aria-controls="identitySection" data-section="identity">Имя кота</button>
|
||||
<nav class="tabs section-tabs" aria-label="Раздел Беличьей норы">
|
||||
<a id="reportsTab" href="/belki" aria-current="page" data-section="reports">Отчёты</a>
|
||||
<a id="sentReportsTab" href="/belki?section=sentReports" data-section="sentReports">Отчёты по ID кота</a>
|
||||
<a id="applicationsTab" href="/belki?section=applications" data-section="applications">Заявки</a>
|
||||
<a id="identityTab" href="/belki?section=identity" data-section="identity">Имя кота</a>
|
||||
</nav>
|
||||
|
||||
<section id="reportsSection" role="tabpanel" aria-labelledby="reportsTab">
|
||||
<section id="reportsSection" aria-labelledby="reportsTab">
|
||||
<p class="muted">На каждый заход нужен отдельный отчёт. Для осмотра прикрепите скриншот перед подготовкой сообщения. Для других отчётов он не нужен.</p>
|
||||
<div class="tabs" role="tablist" aria-label="Вид отчёта">
|
||||
<button class="active" data-mode="coaching">Прокачка ЛУ/ЗУ</button>
|
||||
<button data-mode="training">Тренировка</button>
|
||||
<button data-mode="inspection">Осмотры</button>
|
||||
<button data-mode="goal">Калькулятор цели</button>
|
||||
<button data-mode="points">Калькулятор баллов</button>
|
||||
</div>
|
||||
<fieldset class="mode-options"><legend>Вид расчёта</legend><div class="tabs">
|
||||
<label class="mode-option"><input type="radio" name="calculator_mode" value="coaching" data-mode="coaching" checked>Прокачка ЛУ/ЗУ</label>
|
||||
<label class="mode-option"><input type="radio" name="calculator_mode" value="training" data-mode="training">Тренировка</label>
|
||||
<label class="mode-option"><input type="radio" name="calculator_mode" value="inspection" data-mode="inspection">Осмотры</label>
|
||||
<label class="mode-option"><input type="radio" name="calculator_mode" value="goal" data-mode="goal">Калькулятор цели</label>
|
||||
<label class="mode-option"><input type="radio" name="calculator_mode" value="points" data-mode="points">Калькулятор баллов</label>
|
||||
</div></fieldset>
|
||||
|
||||
<section class="panel">
|
||||
<div class="bulk">
|
||||
<strong>Быстрый ввод</strong>
|
||||
<label for="bulkText">Быстрый ввод</label>
|
||||
<p class="muted">Вставьте данные одной строкой без разделителей <code>|</code>. Калькулятор заполнит поля и подскажет, чего не хватает.</p>
|
||||
<textarea id="bulkText" placeholder="15 августа, 11:00–11:20, Дикая Вишня 1604614, Серолап 1617140"></textarea>
|
||||
<button type="button" id="inspectBulk">Распознать данные</button>
|
||||
<p class="muted bulk-status" id="bulkStatus"></p>
|
||||
<p class="muted bulk-status" id="bulkStatus" role="status"></p>
|
||||
</div>
|
||||
<form id="form">
|
||||
<form id="form" aria-label="Расчёт отчёта или баллов">
|
||||
<div id="coaching" class="grid mode">
|
||||
<label>Дата<input name="date" required>
|
||||
<div class="quick-actions"><button type="button" id="todayBtn" class="today-btn quick-btn">Сегодня</button></div>
|
||||
@@ -203,21 +216,21 @@
|
||||
<p class="muted">Имя и ID из профиля будут подставляться в новые отчёты.</p>
|
||||
</div>
|
||||
|
||||
<dialog id="confirmDialog">
|
||||
<h3 style="margin-top:0">Подтверждение</h3>
|
||||
<dialog id="confirmDialog" aria-labelledby="confirmTitle">
|
||||
<h2 id="confirmTitle" style="margin-top:0">Подтверждение</h2>
|
||||
<div id="confirmPreview" style="white-space:pre-wrap;background:#f8f5f0;padding:12px;border-radius:8px;border:1px solid #ded9d1;max-height:40vh;overflow-y:auto;margin-bottom:12px;"></div>
|
||||
<div style="display:flex;gap:10px;">
|
||||
<button type="button" id="confirmYes" class="primary">Да, подготовить</button>
|
||||
<button type="button" id="confirmNo">Отмена</button>
|
||||
<button type="button" id="confirmNo" autofocus>Отмена</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<div class="result hidden" id="result"><h2>Сообщение</h2><textarea id="message" readonly></textarea><div class="actions"><button type="button" id="sendReport" class="primary" disabled>Отправить отчёт</button></div><p class="muted hidden" id="reportStatus" aria-live="polite"></p></div>
|
||||
<div class="result hidden" id="result"><h2><label for="message">Сообщение</label></h2><textarea id="message" readonly></textarea><div class="actions"><button type="button" id="sendReport" class="primary" disabled>Отправить отчёт</button></div><p class="muted" id="reportStatus" role="status"></p></div>
|
||||
<div class="result hidden" id="pointsResult" aria-live="polite"><h2>Заработанные баллы</h2><div id="pointsSummary"></div></div>
|
||||
<p class="error" id="error"></p>
|
||||
<p class="error" id="error" role="alert"></p>
|
||||
</section>
|
||||
</section>
|
||||
<section id="sentReportsSection" class="hidden" role="tabpanel" aria-labelledby="sentReportsTab">
|
||||
<section id="sentReportsSection" class="hidden" aria-labelledby="sentReportsTab">
|
||||
<h2>Найти отчёты по ID кота</h2>
|
||||
<p class="muted">Покажем последние 100 отправленных отчётов, где кот указан участником.</p>
|
||||
<form id="sentReportsForm" class="panel">
|
||||
@@ -231,7 +244,7 @@
|
||||
<div id="sentReportsResults" class="report-results" aria-live="polite"></div>
|
||||
</section>
|
||||
|
||||
<section id="applicationsSection" class="hidden" role="tabpanel" aria-labelledby="applicationsTab">
|
||||
<section id="applicationsSection" class="hidden" aria-labelledby="applicationsTab">
|
||||
<div id="applicationWorkspace">
|
||||
<h2>Новая заявка</h2>
|
||||
<p class="muted application-intro">Заполните форму, и администратор получит заявку. Готовить форумную отпись не нужно.</p>
|
||||
@@ -246,7 +259,7 @@
|
||||
<label>Имя кота<input name="name" required></label>
|
||||
<label>ID кота<input name="character_id" type="number" min="1" inputmode="numeric" required></label>
|
||||
<label id="applicationVkField" class="wide hidden">Ссылка на страницу VK <span class="muted">(необязательно)</span><input name="vk_link" type="text" inputmode="url" placeholder="vk.com/id… или vk.ru/id…"></label>
|
||||
<section id="applicationKittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Выберите или перетащите изображение</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
||||
<section id="applicationKittenFields" class="wide hidden"><label>Скриншот активности<span class="upload"><strong>Выберите изображение</strong><span>PNG, JPEG или WebP до 15 МБ</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
||||
<section id="applicationCuratorFields" class="wide hidden"><label>Скриншот ЛУ с дробью<span class="upload"><strong>Прикрепите скриншот ЛУ с дробью</strong><span>PNG, JPEG или WebP; нужен хотя бы один файл</span><input class="application-screenshots" type="file" accept="image/png,image/jpeg,image/webp" multiple></span></label><ul class="files"></ul></section>
|
||||
<section id="applicationFlyingFields" class="wide hidden"><label>Уже сдавали практику?<select name="practiced_before"><option value="no">Нет, не сдавал(-а)</option><option value="yes">Да, сдавал(-а)</option></select></label><label id="applicationPracticeLink" class="hidden">Ссылка на комментарий с прошлой практики<input name="practice_review_link" type="url" placeholder="https://catwar.su/… или https://vk.com/…"></label></section>
|
||||
<section id="applicationFeatherFields" class="wide"><h2>Перья для казны</h2><p class="muted">Укажите количество и цвет перьев, а также откуда они получены.</p><div id="applicationFeathers"></div><button id="applicationAddFeather" type="button">Добавить перо</button></section>
|
||||
@@ -257,7 +270,7 @@
|
||||
<div id="applicationSuccess" class="success hidden" role="status" aria-live="polite"></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="identitySection" class="hidden" role="tabpanel" aria-labelledby="identityTab">
|
||||
<section id="identitySection" class="hidden" aria-labelledby="identityTab">
|
||||
<div id="identityWorkspace">
|
||||
<h2>Изменить имя кота</h2>
|
||||
<p class="muted">Введите ID кота, чьё имя уже сохранено. Проверьте текущее имя и укажите новое.</p>
|
||||
@@ -279,9 +292,9 @@
|
||||
</section>
|
||||
<footer class="site-footer">Proudly made by Nyan404 | <a href="https://git.nyan404.ru/nyan404/cwshed-clone">GitLab Page</a></footer>
|
||||
</main>
|
||||
<dialog id="identityDialog">
|
||||
<p id="identityDialogText"></p>
|
||||
<label id="identityMissingLabel">Имя или ID, которого не хватает<input id="identityMissingValue"></label>
|
||||
<dialog id="identityDialog" aria-label="Уточнить имя или ID кота" aria-describedby="identityDialogText">
|
||||
<p id="identityDialogText" role="status"></p>
|
||||
<label id="identityMissingLabel" for="identityMissingValue">Имя или ID, которого не хватает<input id="identityMissingValue" autofocus></label>
|
||||
<p class="muted">Эти имя и ID будут использованы только в текущем расчёте.</p>
|
||||
<button type="button" id="saveIdentity">Добавить имя и ID</button>
|
||||
<button type="button" id="closeIdentityDialog">Понятно</button>
|
||||
@@ -313,21 +326,38 @@
|
||||
const identityMissingLabel = document.querySelector('#identityMissingLabel');
|
||||
const identityMissingValue = document.querySelector('#identityMissingValue');
|
||||
let mode = 'coaching';
|
||||
let calculationVersion = 0;
|
||||
let calculating = false;
|
||||
// Any edit makes the previous result and an in-flight response obsolete.
|
||||
function invalidateCalculation() {
|
||||
calculationVersion += 1;
|
||||
preparedReportPayload = null;
|
||||
result.classList.add('hidden');
|
||||
pointsResult.classList.add('hidden');
|
||||
message.value = '';
|
||||
copy.disabled = goalCopy.disabled = sendReport.disabled = true;
|
||||
reportStatus.textContent = '';
|
||||
error.textContent = '';
|
||||
}
|
||||
form.addEventListener('input', invalidateCalculation);
|
||||
form.addEventListener('change', invalidateCalculation);
|
||||
const extraKittens = document.querySelector('#extraKittens');
|
||||
const statusHelp = document.querySelector('#statusHelp');
|
||||
// Adds one repeatable kitten row and optionally fills it from saved values.
|
||||
function addExtraKitten(values = {}) {
|
||||
const row = document.createElement('div'); row.className = 'extra-kitten';
|
||||
row.innerHTML = `<input data-extra="name" placeholder="Имя котёнка" required>
|
||||
<input data-extra="id" type="text" inputmode="numeric" pattern="[0-9]+" placeholder="ID" required>
|
||||
<select data-extra="independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select>
|
||||
row.innerHTML = `<label>Имя котёнка<input data-extra="name" required></label>
|
||||
<label>ID котёнка<input data-extra="id" type="text" inputmode="numeric" pattern="[1-9][0-9]*" required></label>
|
||||
<label>Самостоятельность<select data-extra="independence"><option value="самостоятельно">сам / самостоятельный</option><option value="несамостоятельно">несам / несамостоятельный</option></select></label>
|
||||
<button type="button" data-remove>Удалить</button>`;
|
||||
row.querySelector('[data-extra="name"]').value = values.name || '';
|
||||
row.querySelector('[data-extra="id"]').value = values.id || '';
|
||||
row.querySelector('[data-extra="independence"]').value = values.independence || 'самостоятельно';
|
||||
row.querySelector('[data-extra="independence"]').addEventListener('change', updateStatusRules);
|
||||
row.querySelector('[data-remove]').addEventListener('click', () => row.remove());
|
||||
row.querySelector('[data-remove]').addEventListener('click', () => { row.remove(); invalidateCalculation(); document.querySelector('#addKitten').focus(); });
|
||||
extraKittens.append(row);
|
||||
row.querySelectorAll('input, select').forEach(field => { field.disabled = mode !== 'coaching'; });
|
||||
invalidateCalculation();
|
||||
}
|
||||
document.querySelector('#addKitten').addEventListener('click', () => addExtraKitten());
|
||||
// Returns all independence controls participating in the current coaching form.
|
||||
@@ -335,7 +365,7 @@
|
||||
// Keeps every kitten's independence selection available for the chosen skill.
|
||||
function updateStatusRules(event) {
|
||||
const fields = statusFields();
|
||||
fields.forEach(field => { field.disabled = false; });
|
||||
fields.forEach(field => { field.disabled = mode !== 'coaching'; });
|
||||
statusHelp.textContent = document.querySelector('#coaching [name="skill"]').value === 'ЛУ'
|
||||
? 'Для ЛУ можно указать не более одного несамостоятельного котёнка.'
|
||||
: 'Укажите самостоятельность каждого котёнка отдельно.';
|
||||
@@ -349,8 +379,9 @@
|
||||
}
|
||||
// Switches the visible calculator panel and disables fields in hidden panels.
|
||||
function selectMode(nextMode) {
|
||||
invalidateCalculation();
|
||||
mode = nextMode;
|
||||
document.querySelectorAll('[data-mode]').forEach(item => item.classList.toggle('active', item.dataset.mode === mode));
|
||||
document.querySelectorAll('[data-mode]').forEach(item => { item.checked = item.dataset.mode === mode; });
|
||||
document.querySelectorAll('.mode').forEach(panel => panel.classList.toggle('hidden', panel.id !== mode));
|
||||
document.querySelectorAll('.mode').forEach(panel => panel.querySelectorAll('input, select, textarea').forEach(field => { field.disabled = panel.id !== mode; }));
|
||||
bulk.classList.toggle('hidden', mode !== 'coaching');
|
||||
@@ -363,8 +394,9 @@
|
||||
pointsActions.classList.toggle('hidden', mode !== 'points');
|
||||
if (mode !== 'coaching') bulkStatus.textContent = '';
|
||||
error.textContent = '';
|
||||
updatePointsFields();
|
||||
}
|
||||
document.querySelectorAll('[data-mode]').forEach(button => button.addEventListener('click', () => selectMode(button.dataset.mode)));
|
||||
document.querySelectorAll('[data-mode]').forEach(input => input.addEventListener('change', () => selectMode(input.value)));
|
||||
function updatePointsFields() {
|
||||
const activity = pointsActivity.value;
|
||||
document.querySelector('#pointsCoaching').classList.toggle('hidden', activity !== 'coaching');
|
||||
@@ -372,6 +404,9 @@
|
||||
document.querySelector('#pointsTraining').classList.toggle('hidden', activity !== 'training');
|
||||
const count = Number(document.querySelector('#points [name="kitten_count"]').value);
|
||||
document.querySelectorAll('.points-extra').forEach((field, index) => field.classList.toggle('hidden', activity !== 'coaching' || index >= count - 1));
|
||||
document.querySelectorAll('#points input, #points select, #points textarea').forEach(field => {
|
||||
field.disabled = mode !== 'points' || Boolean(field.closest('.hidden'));
|
||||
});
|
||||
}
|
||||
pointsActivity.addEventListener('change', updatePointsFields);
|
||||
document.querySelector('#points [name="kitten_count"]').addEventListener('change', updatePointsFields);
|
||||
@@ -379,14 +414,19 @@
|
||||
function setToday(button) {
|
||||
const now = new Date();
|
||||
button.closest('label').querySelector('input').value = `${String(now.getDate()).padStart(2, '0')}.${String(now.getMonth() + 1).padStart(2, '0')}`;
|
||||
invalidateCalculation();
|
||||
}
|
||||
document.querySelectorAll('.today-btn').forEach(setToday);
|
||||
document.querySelectorAll('.today-btn').forEach(button => button.addEventListener('click', () => setToday(button)));
|
||||
document.querySelector('#coaching [name="kitten_independence"]').addEventListener('change', updateStatusRules);
|
||||
document.querySelector('#noResourcesBtn').addEventListener('click', () => {
|
||||
document.querySelector('#inspection [name="resources"]').value = '';
|
||||
invalidateCalculation();
|
||||
});
|
||||
// Writes a value into a named field inside a calculator panel.
|
||||
function setField(panel, name, value) {
|
||||
const field = document.querySelector(`#${panel} [name="${name}"]`);
|
||||
if (field && value !== undefined && value !== null) field.value = value;
|
||||
if (field && value !== undefined && value !== null) { field.value = value; invalidateCalculation(); }
|
||||
}
|
||||
document.querySelector('#inspectBulk').addEventListener('click', async () => {
|
||||
bulkStatus.textContent = '';
|
||||
@@ -427,8 +467,7 @@
|
||||
identityMissingLabel.firstChild.textContent = `Введите ${missing}`;
|
||||
identityMissingValue.value = '';
|
||||
identityMissingValue.type = name ? 'number' : 'text';
|
||||
if (identityDialog.showModal) identityDialog.showModal();
|
||||
else window.alert(data.message);
|
||||
identityDialog.showModal();
|
||||
}
|
||||
} catch (err) { identityStatus.textContent = err.message; }
|
||||
});
|
||||
@@ -438,11 +477,17 @@
|
||||
const name = nameField.value.trim() || (identityMissingValue.type === 'text' ? identityMissingValue.value.trim() : '');
|
||||
const characterId = idField.value.trim() || (identityMissingValue.type === 'number' ? identityMissingValue.value.trim() : '');
|
||||
if (!name || !characterId) { identityDialogText.textContent = 'Нужно указать и имя, и ID кота.'; return; }
|
||||
const response = await fetch('/api/resolve-identity', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name, character_id: characterId, remember: true}) });
|
||||
const data = await response.json();
|
||||
if (!response.ok) { identityDialogText.textContent = data.error || 'Не удалось сохранить имя и ID'; return; }
|
||||
setField('inspection', 'character_name', data.name); setField('inspection', 'character_id', data.character_id);
|
||||
identityDialog.close(); identityStatus.textContent = 'Имя и ID добавлены в текущий расчёт.';
|
||||
const saveButton = document.querySelector('#saveIdentity');
|
||||
if (saveButton.disabled) return;
|
||||
saveButton.disabled = true;
|
||||
try {
|
||||
const response = await fetch('/api/resolve-identity', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({name, character_id: characterId, remember: true}) });
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Не удалось сохранить имя и ID');
|
||||
setField('inspection', 'character_name', data.name); setField('inspection', 'character_id', data.character_id);
|
||||
identityDialog.close(); identityStatus.textContent = 'Имя и ID добавлены в текущий расчёт.';
|
||||
} catch (err) { identityDialogText.textContent = err.message; }
|
||||
finally { saveButton.disabled = false; }
|
||||
});
|
||||
document.querySelector('#closeIdentityDialog').addEventListener('click', () => identityDialog.close());
|
||||
// Serializes the active calculator form into the API payload shape.
|
||||
@@ -502,6 +547,16 @@
|
||||
}
|
||||
form.addEventListener('submit', async event => {
|
||||
event.preventDefault(); error.textContent = '';
|
||||
if (calculating) return;
|
||||
invalidateCalculation();
|
||||
const version = calculationVersion;
|
||||
const requestMode = mode;
|
||||
const submitButton = event.submitter;
|
||||
const submitLabel = submitButton?.textContent;
|
||||
if (submitButton) submitButton.textContent = 'Рассчитываем…';
|
||||
calculating = true;
|
||||
form.setAttribute('aria-busy', 'true');
|
||||
form.querySelectorAll('[type="submit"]').forEach(button => { button.disabled = true; });
|
||||
try {
|
||||
if (mode === 'coaching') {
|
||||
const statusError = validateStatusRules();
|
||||
@@ -509,50 +564,79 @@
|
||||
}
|
||||
const reportPayload = payload();
|
||||
preparedReportPayload = null;
|
||||
reportStatus.classList.add('hidden');
|
||||
reportStatus.textContent = '';
|
||||
reportPayload.attachments = mode === 'inspection' ? await uploadScreenshots() : [];
|
||||
reportPayload.attachments = requestMode === 'inspection' ? await uploadScreenshots() : [];
|
||||
const response = await fetch('/api/calculate', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(reportPayload) });
|
||||
const data = await response.json();
|
||||
if (version !== calculationVersion) return;
|
||||
if (!response.ok) throw new Error(data.error || 'Ошибка калькулятора');
|
||||
if (mode === 'points') {
|
||||
if (requestMode === 'points') {
|
||||
const values = data.result;
|
||||
const lines = values.kitten_points ? values.kitten_points.map((value, index) => `<p>Бельчонок ${index + 1}: <strong>${value}</strong> баллов</p>`) : [`<p>Баллы осмотра: <strong>${values.points}</strong></p>`];
|
||||
if (values.curator_points !== undefined) lines.unshift(`<p>Куратор: <strong>${values.curator_points}</strong> баллов</p>`);
|
||||
pointsSummary.innerHTML = lines.join(''); pointsResult.classList.remove('hidden'); return;
|
||||
const scores = Array.isArray(values.kitten_points)
|
||||
? values.kitten_points.map((value, index) => [`Бельчонок ${index + 1}`, value])
|
||||
: [[values.kitten_points !== undefined ? 'Бельчонок' : 'Баллы осмотра', values.kitten_points ?? values.points]];
|
||||
if (values.curator_points !== undefined) scores.unshift(['Куратор', values.curator_points]);
|
||||
pointsSummary.replaceChildren(...scores.map(([label, value]) => {
|
||||
const line = document.createElement('p');
|
||||
const score = document.createElement('strong');
|
||||
score.textContent = value;
|
||||
line.append(`${label}: `, score, ' баллов');
|
||||
return line;
|
||||
}));
|
||||
pointsResult.classList.remove('hidden'); return;
|
||||
}
|
||||
message.value = data.message;
|
||||
result.classList.remove('hidden');
|
||||
copy.disabled = mode === 'goal';
|
||||
goalCopy.disabled = mode !== 'goal';
|
||||
sendReport.classList.toggle('hidden', mode === 'goal');
|
||||
if (mode !== 'goal') {
|
||||
copy.disabled = requestMode === 'goal';
|
||||
goalCopy.disabled = requestMode !== 'goal';
|
||||
sendReport.classList.toggle('hidden', requestMode === 'goal');
|
||||
reportStatus.textContent = 'Расчёт готов. Проверьте сообщение.';
|
||||
if (requestMode !== 'goal') {
|
||||
preparedReportPayload = reportPayload;
|
||||
sendReport.disabled = false;
|
||||
sendReport.textContent = 'Отправить отчёт';
|
||||
}
|
||||
} catch (err) { error.textContent = err.message; }
|
||||
} catch (err) { if (version === calculationVersion) error.textContent = err.message; }
|
||||
finally {
|
||||
calculating = false;
|
||||
form.removeAttribute('aria-busy');
|
||||
form.querySelectorAll('[type="submit"]').forEach(button => { button.disabled = false; });
|
||||
if (submitButton) submitButton.textContent = submitLabel;
|
||||
}
|
||||
});
|
||||
sendReport.addEventListener('click', async () => {
|
||||
if (!preparedReportPayload || sendReport.disabled) return;
|
||||
sendReport.disabled = true;
|
||||
sendReport.textContent = 'Отправляем…';
|
||||
const version = calculationVersion;
|
||||
try {
|
||||
const response = await fetch('/api/reports', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(preparedReportPayload) });
|
||||
const data = await response.json();
|
||||
if (version !== calculationVersion) return;
|
||||
if (!response.ok) throw new Error(data.error || 'Не удалось отправить отчёт');
|
||||
preparedReportPayload = null;
|
||||
sendReport.textContent = 'Отчёт отправлен';
|
||||
reportStatus.textContent = 'Отчёт отправлен и сохранён.';
|
||||
reportStatus.classList.remove('hidden');
|
||||
} catch (err) {
|
||||
if (version !== calculationVersion) return;
|
||||
error.textContent = err.message;
|
||||
sendReport.disabled = false;
|
||||
sendReport.textContent = 'Отправить отчёт';
|
||||
}
|
||||
});
|
||||
copy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); copy.textContent = 'Скопировано'; setTimeout(() => copy.textContent = 'Скопировать', 1500); });
|
||||
goalCopy.addEventListener('click', async () => { await navigator.clipboard.writeText(message.value); goalCopy.textContent = 'Скопировано'; setTimeout(() => goalCopy.textContent = 'Скопировать', 1500); });
|
||||
async function copyMessage() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(message.value);
|
||||
reportStatus.textContent = 'Сообщение скопировано.';
|
||||
} catch {
|
||||
message.focus();
|
||||
message.select();
|
||||
reportStatus.textContent = 'Не удалось скопировать автоматически. Текст выделен: скопируйте его через меню браузера или Ctrl+C / ⌘C.';
|
||||
}
|
||||
}
|
||||
copy.addEventListener('click', copyMessage);
|
||||
goalCopy.addEventListener('click', copyMessage);
|
||||
|
||||
const reportsSection = document.querySelector('#reportsSection');
|
||||
const sentReportsSection = document.querySelector('#sentReportsSection');
|
||||
@@ -590,17 +674,22 @@
|
||||
identitySection.classList.toggle('hidden', selectedSection !== 'identity');
|
||||
sectionTabs.forEach(tab => {
|
||||
const selected = tab.dataset.section === selectedSection;
|
||||
tab.classList.toggle('active', selected);
|
||||
tab.setAttribute('aria-selected', String(selected));
|
||||
if (selected) tab.setAttribute('aria-current', 'page');
|
||||
else tab.removeAttribute('aria-current');
|
||||
});
|
||||
document.title = `${sectionTabs.find(tab => tab.dataset.section === selectedSection).textContent} — Беличья нора`;
|
||||
if (updateUrl) {
|
||||
const url = new URL(window.location.href);
|
||||
if (selectedSection !== 'reports') url.searchParams.set('section', selectedSection);
|
||||
else url.searchParams.delete('section');
|
||||
window.history.pushState({}, '', url);
|
||||
if (url.href !== window.location.href) window.history.pushState({}, '', url);
|
||||
}
|
||||
}
|
||||
sectionTabs.forEach(tab => tab.addEventListener('click', () => setSection(tab.dataset.section)));
|
||||
sectionTabs.forEach(tab => tab.addEventListener('click', event => {
|
||||
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||
event.preventDefault();
|
||||
setSection(tab.dataset.section);
|
||||
}));
|
||||
window.addEventListener('popstate', () => setSection(new URLSearchParams(window.location.search).get('section'), false));
|
||||
|
||||
sentReportsForm.addEventListener('submit', async event => {
|
||||
@@ -713,6 +802,7 @@
|
||||
setApplicationFieldsVisible('#applicationCuratorFields', applicationType === 'curator');
|
||||
setApplicationFieldsVisible('#applicationFlyingFields', applicationType === 'flying_squirrel');
|
||||
setApplicationFieldsVisible('#applicationVkField', applicationType === 'flying_squirrel');
|
||||
setApplicationFieldsVisible('#applicationPracticeLink', applicationType === 'flying_squirrel' && document.querySelector('[name="practiced_before"]').value === 'yes');
|
||||
document.querySelectorAll('[data-application-type]').forEach(button => button.setAttribute('aria-pressed', String(button.dataset.applicationType === applicationType)));
|
||||
applicationError.textContent = '';
|
||||
}
|
||||
@@ -740,20 +830,22 @@
|
||||
}
|
||||
applicationForm.addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
if (applicationSubmit.disabled) return;
|
||||
applicationError.textContent = '';
|
||||
applicationSuccess.classList.add('hidden');
|
||||
applicationSubmit.disabled = true;
|
||||
applicationSubmit.textContent = 'Отправляем…';
|
||||
try {
|
||||
const payload = Object.fromEntries(new FormData(applicationForm).entries());
|
||||
payload.type = applicationType;
|
||||
payload.character_id = Number(payload.character_id);
|
||||
payload.attachments = await uploadApplicationScreenshots();
|
||||
if (applicationType === 'flying_squirrel') payload.practiced_before = payload.practiced_before === 'yes';
|
||||
if (applicationType === 'feather_donation') payload.feathers = [...applicationFeathers.querySelectorAll('.feather')].map(row => ({
|
||||
amount: Number(row.querySelector('[data-application-field="amount"]').value),
|
||||
color: row.querySelector('[data-application-field="color"]').value,
|
||||
source: row.querySelector('[data-application-field="source"]').value,
|
||||
}));
|
||||
payload.attachments = await uploadApplicationScreenshots();
|
||||
const response = await fetch('/api/applications', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(payload)});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Не удалось отправить заявку');
|
||||
|
||||
Reference in new issue
Block a user