Files
zbiorki_app/static/js/edytuj_stan.js
Mateusz Gruszczyński 4515a1b391 zmiany w ux
2025-09-24 10:55:04 +02:00

89 lines
2.8 KiB
JavaScript

(() => {
// Root kontenera z danymi (dataset.cel)
const root = document.querySelector('[data-module="edit-stan"]');
if (!root) return;
const input = root.querySelector('#stan');
const previewPct = root.querySelector('#previewPct');
const previewBar = root.querySelector('#previewBar');
const previewNote = root.querySelector('#previewNote');
// Cel przekazany jako data atrybut
const cel = Number(root.dataset.cel || 0);
function clamp(n) {
if (Number.isNaN(n)) return 0;
return n < 0 ? 0 : n;
}
function pct(val) {
if (!cel || cel <= 0) return 0;
return (val / cel) * 100;
}
function updatePreview() {
if (!input) return;
const val = clamp(Number(input.value));
const p = Math.max(0, Math.min(100, pct(val)));
if (previewPct) previewPct.textContent = p.toFixed(1);
if (previewBar) {
previewBar.style.width = p + '%';
previewBar.setAttribute('aria-valuenow', p.toFixed(2));
}
if (previewNote) {
if (cel > 0) {
const diff = cel - val;
const isZero = Math.abs(diff) < 0.005; // float-safe
if (diff > 0 && !isZero) {
previewNote.textContent = 'Do celu brakuje: ' + diff.toFixed(2) + ' PLN';
} else if (isZero) {
previewNote.textContent = 'Cel osiągnięty.';
} else {
previewNote.textContent = 'Przekroczono cel o: ' + Math.abs(diff).toFixed(2) + ' PLN';
}
} else {
previewNote.textContent = 'Brak zdefiniowanego celu — procent nie jest wyliczany.';
}
}
}
// Zmiana ręczna
if (input) {
input.addEventListener('input', updatePreview);
input.addEventListener('change', () => {
if (Number(input.value) < 0) input.value = '0.00';
updatePreview();
});
}
// Przyciski +/- delta
root.querySelectorAll('.btn-delta').forEach(btn => {
btn.addEventListener('click', () => {
const d = Number(btn.getAttribute('data-delta') || 0);
const cur = Number(input?.value || 0);
if (!input) return;
input.value = clamp(cur + d).toFixed(2);
updatePreview();
input.focus();
});
});
// Ustaw na konkretną wartość
root.querySelectorAll('.btn-set').forEach(btn => {
btn.addEventListener('click', () => {
const v = Number(btn.getAttribute('data-value') || 0);
if (!input) return;
input.value = clamp(v).toFixed(2);
updatePreview();
input.focus();
});
});
// Inicjalny podgląd
updatePreview();
})();