| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810 |
- /* global jQuery */
- /**
- * Main planning view (/sprints/{id}) — Section A: Arbeitstage grid.
- *
- * Behaviours:
- * - Day cells (per worker, per week) snap to 0.5 on blur, batch-saved via
- * PATCH /sprints/{id}/week-cells with 400 ms debounce.
- * - The Arbeitstage header row is derived from the weekday selection in
- * Sprint Settings — it's read-only here (Phase 12).
- * - RTB inputs snap to 0.05 on blur, saved via PATCH /sprints/{id}/workers/{sw_id}.
- * - Worker rows are sortable (jQuery UI). Drop posts to
- * POST /sprints/{id}/workers/reorder.
- *
- * All capacity values are recomputed client-side with the same formula as
- * `App\Services\CapacityCalculator` so the UI stays in sync without waiting
- * for the server response.
- */
- (function ($) {
- 'use strict';
- const $root = $('[data-sprint-root]');
- if ($root.length === 0) { return; }
- const sprintId = parseInt($root.data('sprint-id'), 10);
- const csrf = String($root.data('csrf') || '');
- const reserveFraction = Number($root.data('reserve-fraction') || 0);
- // ---------------------------------------------------------------------
- // Capacity math — MUST match App\Services\CapacityCalculator
- // ---------------------------------------------------------------------
- function roundHalf(x) { return Math.round(x * 2) / 2; }
- function snap05(x) { return roundHalf(x); }
- function snap005(x) { return Math.round(x * 20) / 20; }
- function fmtDays(x) {
- const n = Number(x);
- if (Math.abs(n - Math.round(n)) < 1e-9) { return String(Math.round(n)); }
- return n.toFixed(1);
- }
- function fmtRtb(x) { return Number(x).toFixed(2); }
- function capacity(ressourcen, committedPrio1) {
- committedPrio1 = committedPrio1 || 0;
- const afterReserves = roundHalf(ressourcen * (1 - reserveFraction));
- const available = afterReserves - committedPrio1;
- return { ressourcen, afterReserves, committedPrio1, available };
- }
- // Sum of prio-1 task assignment cells per sprint worker, read from DOM.
- function committedPrio1FromDom() {
- const per = {};
- $root.find('tr[data-task-row]').each(function () {
- const $row = $(this);
- if (parseInt($row.attr('data-prio'), 10) !== 1) { return; }
- $row.find('[data-assign]').each(function () {
- const key = String($(this).data('sw-id'));
- const v = Number($(this).val());
- if (!Number.isNaN(v) && v > 0) {
- per[key] = (per[key] || 0) + v;
- }
- });
- });
- return per;
- }
- // ---------------------------------------------------------------------
- // HTTP helper — spec §7 envelopes
- // ---------------------------------------------------------------------
- function request(method, url, body) {
- const opts = {
- method,
- headers: {
- Accept: 'application/json',
- 'X-CSRF-Token': csrf,
- },
- credentials: 'same-origin',
- };
- if (body !== undefined) {
- opts.headers['Content-Type'] = 'application/json';
- opts.body = JSON.stringify(body);
- }
- return fetch(url, opts).then(async function (res) {
- let payload = null;
- try { payload = await res.json(); } catch (_) { /* ignore */ }
- if (!res.ok || !payload || payload.ok !== true) {
- const msg = (payload && payload.error && payload.error.message)
- ? payload.error.message
- : res.statusText || 'Request failed';
- const err = new Error(msg);
- err.status = res.status;
- err.payload = payload;
- throw err;
- }
- return payload.data;
- });
- }
- // ---------------------------------------------------------------------
- // Status line (shared with settings page styling)
- // ---------------------------------------------------------------------
- const $status = $root.find('[data-status]');
- let statusTimer = null;
- function flash(text, isError) {
- $status
- .text(text)
- .removeClass('text-green-700 text-red-700 bg-green-50 bg-red-50 border-green-200 border-red-200')
- .addClass(isError ? 'text-red-700 bg-red-50 border-red-200' : 'text-green-700 bg-green-50 border-green-200')
- .removeClass('opacity-0').addClass('opacity-100');
- clearTimeout(statusTimer);
- statusTimer = setTimeout(function () {
- $status.removeClass('opacity-100').addClass('opacity-0');
- }, 2500);
- }
- // ---------------------------------------------------------------------
- // Recompute worker row sum + capacity summary locally
- // ---------------------------------------------------------------------
- function recomputeRow(swId, commitMap) {
- const $row = $root.find('[data-sw-row][data-sw-id="' + swId + '"]');
- let sum = 0;
- $row.find('[data-day]').each(function () {
- const v = Number($(this).val());
- if (!Number.isNaN(v)) { sum += v; }
- });
- const committed = (commitMap || committedPrio1FromDom())[String(swId)] || 0;
- const cap = capacity(sum, committed);
- $row.find('[data-sum-days]').text(fmtDays(cap.ressourcen));
- $root.find('[data-cap-ressourcen][data-sw-id="' + swId + '"]').text(fmtDays(cap.ressourcen));
- $root.find('[data-cap-after-reserves][data-sw-id="' + swId + '"]').text(fmtDays(cap.afterReserves));
- const $avail = $root.find('[data-cap-available][data-sw-id="' + swId + '"]');
- $avail.text(fmtDays(cap.available));
- if (cap.available < 0) {
- $avail.removeClass('text-slate-900').addClass('text-red-700');
- } else {
- $avail.removeClass('text-red-700').addClass('text-slate-900');
- }
- }
- // Recompute every worker row (capacity summary) — called when a task-side
- // change might affect committed prio-1 values.
- function recomputeAllCapacity() {
- const commit = committedPrio1FromDom();
- $root.find('[data-sw-row]').each(function () {
- recomputeRow(parseInt($(this).data('sw-id'), 10), commit);
- });
- }
- // ---------------------------------------------------------------------
- // Pending-cell queue, debounced batch save
- // ---------------------------------------------------------------------
- // key = "swId:weekId" → { sw_id, week_id, days }
- const pendingCells = new Map();
- let cellDebounce = null;
- function queueCell(swId, weekId, days) {
- pendingCells.set(swId + ':' + weekId, {
- sprint_worker_id: swId,
- sprint_week_id: weekId,
- days: days,
- });
- clearTimeout(cellDebounce);
- cellDebounce = setTimeout(flushCells, 400);
- }
- function flushCells() {
- if (pendingCells.size === 0) { return; }
- const cells = Array.from(pendingCells.values());
- pendingCells.clear();
- request('PATCH', '/sprints/' + sprintId + '/week-cells', cells)
- .then(function (data) {
- if (data.applied === 0 && data.noop > 0) {
- flash('No changes');
- } else {
- flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells'));
- }
- // Trust the server's capacity numbers — same formula, but a
- // safety net if an input was tampered with.
- if (data.per_worker && typeof data.per_worker === 'object') {
- Object.keys(data.per_worker).forEach(function (swIdStr) {
- const c = data.per_worker[swIdStr];
- $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
- $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
- const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
- $av.text(fmtDays(c.available));
- if (c.available < 0) {
- $av.removeClass('text-slate-900').addClass('text-red-700');
- } else {
- $av.removeClass('text-red-700').addClass('text-slate-900');
- }
- $root.find('[data-sw-row][data-sw-id="' + swIdStr + '"] [data-sum-days]').text(fmtDays(c.ressourcen));
- });
- }
- })
- .catch(function (e) { flash(e.message, true); });
- }
- // ---------------------------------------------------------------------
- // Day cells
- // ---------------------------------------------------------------------
- $root.on('blur change', '[data-day]', function () {
- const $el = $(this);
- let v = Number($el.val());
- if (Number.isNaN(v)) { v = 0; }
- if (v < 0) { v = 0; }
- if (v > 5) { v = 5; }
- v = snap05(v);
- $el.val(fmtDays(v));
- const swId = parseInt($el.data('sw-id'), 10);
- const weekId = parseInt($el.data('week-id'), 10);
- queueCell(swId, weekId, v);
- recomputeRow(swId);
- });
- // ---------------------------------------------------------------------
- // Per-row RTB edit
- // ---------------------------------------------------------------------
- $root.on('blur change', '[data-rtb]', function () {
- const $el = $(this);
- let v = Number($el.val());
- if (Number.isNaN(v)) { v = 0; }
- if (v < 0) { v = 0; }
- if (v > 1) { v = 1; }
- v = snap005(v);
- $el.val(fmtRtb(v));
- const swId = parseInt($el.data('sw-id'), 10);
- request('PATCH', '/sprints/' + sprintId + '/workers/' + swId, { rtb: v })
- .then(function () { flash('Saved'); })
- .catch(function (e) { flash(e.message, true); });
- });
- // ---------------------------------------------------------------------
- // Worker row drag-reorder (admin only — tbody only exists with handles)
- // ---------------------------------------------------------------------
- const sortableAvailable = typeof $.fn.sortable === 'function';
- if (!sortableAvailable) {
- // jQuery UI didn't load (SRI mismatch, offline CDN, ad blocker).
- // Drag-reorder is unavailable but the rest of the page still works.
- // eslint-disable-next-line no-console
- console.warn('[sprint-planner] jQuery UI not loaded — drag reorder disabled.');
- }
- const $tbody = $root.find('[data-tbody]');
- if (sortableAvailable && $tbody.find('.handle').length > 0) {
- $tbody.sortable({
- handle: '.handle',
- items: 'tr[data-sw-row]',
- axis: 'y',
- helper: function (e, tr) {
- // Preserve the td widths so the row doesn't collapse while dragging.
- const $cells = tr.children();
- const $clone = tr.clone();
- $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
- return $clone;
- },
- update: function () {
- const ordering = $tbody.find('tr[data-sw-row]').map(function (i, el) {
- return {
- sprint_worker_id: parseInt($(el).data('sw-id'), 10),
- sort_order: i + 1,
- };
- }).get();
- request('POST', '/sprints/' + sprintId + '/workers/reorder', ordering)
- .then(function (data) {
- if (data.moved) {
- // Column order in the task list below depends on
- // this ordering — simplest to re-render.
- window.location.reload();
- } else {
- flash('No changes');
- }
- })
- .catch(function (e) { flash(e.message, true); });
- },
- });
- }
- // =====================================================================
- // Task list — create/edit/delete/reorder + assignments + filter/sort
- // =====================================================================
- const $taskTbody = $root.find('[data-task-tbody]');
- const hasTaskUi = $taskTbody.length > 0;
- // --- Worker/owner helpers read from the DOM once ----------------------
- function sprintWorkerHeaders() {
- const out = [];
- $root.find('[data-task-table] thead th[data-sort-col^="sw-"]').each(function () {
- const col = String($(this).attr('data-sort-col'));
- out.push({
- id: parseInt(col.slice(3), 10),
- name: $(this).clone().children().remove().end().text().trim(),
- });
- });
- return out;
- }
- function ownerChoices() {
- const out = [];
- $root.find('[data-owner-filter] option').each(function () {
- const v = $(this).val();
- if (v === '' || v === '__none__') { return; }
- out.push({ id: parseInt(String(v), 10), name: String($(this).text()).trim() });
- });
- return out;
- }
- // --- Build a task row <tr> from an object ----------------------------
- function buildTaskRow(task, assignments) {
- assignments = assignments || {};
- const $tr = $('<tr>')
- .attr('data-task-row', '')
- .attr('data-task-id', task.id)
- .attr('data-prio', task.priority)
- .attr('data-owner', task.owner_worker_id || '')
- .attr('data-sort-order', task.sort_order);
- // handle
- $tr.append($('<td class="px-2 py-1"></td>').append(
- $('<span class="handle cursor-grab text-slate-400 select-none">').html('≡')
- ));
- // title
- $tr.append(
- $('<td class="px-2 py-1 min-w-[14rem]"></td>').append(
- $('<input type="text" data-title class="w-full rounded border border-slate-200 px-2 py-1 focus:outline-none focus:ring-2 focus:ring-slate-400">')
- .val(task.title)
- )
- );
- // owner
- const $sel = $('<select data-owner-select class="w-full rounded border border-slate-200 px-2 py-1 bg-white focus:outline-none focus:ring-2 focus:ring-slate-400">');
- $sel.append('<option value="">—</option>');
- ownerChoices().forEach(function (o) {
- const $opt = $('<option>').val(o.id).text(o.name);
- if (Number(o.id) === Number(task.owner_worker_id)) { $opt.attr('selected', 'selected'); }
- $sel.append($opt);
- });
- $tr.append($('<td class="px-2 py-1"></td>').append($sel));
- // priority
- const $prio = $('<select data-prio-select class="rounded border border-slate-200 px-2 py-1 bg-white font-mono focus:outline-none focus:ring-2 focus:ring-slate-400"><option value="1">1</option><option value="2">2</option></select>');
- $prio.val(String(task.priority));
- $tr.append($('<td class="px-2 py-1 text-center"></td>').append($prio));
- // tot
- let tot = 0;
- Object.keys(assignments).forEach(function (k) { tot += Number(assignments[k]) || 0; });
- $tr.append($('<td class="px-2 py-1 text-center font-mono font-semibold" data-task-tot>').text(fmtDays(tot)));
- // per-worker assignment cells
- sprintWorkerHeaders().forEach(function (sw) {
- const v = Number(assignments[sw.id] || 0);
- const $td = $('<td class="px-1 py-1 text-center"></td>')
- .attr('data-sort-value-sw-' + sw.id, v.toFixed(2));
- $td.append(
- $('<input type="number" min="0" step="0.5" data-assign class="w-14 rounded border border-slate-200 px-1 py-1 text-center font-mono focus:outline-none focus:ring-2 focus:ring-slate-400">')
- .val(fmtDays(v))
- .attr('data-sw-id', sw.id)
- );
- $tr.append($td);
- });
- // delete
- $tr.append(
- $('<td class="px-1 py-1 text-right"></td>').append(
- $('<button type="button" data-delete-task class="text-sm text-red-600 hover:underline">').text('×')
- )
- );
- return $tr;
- }
- // --- Add task ---------------------------------------------------------
- $root.on('click', '[data-add-task]', function () {
- request('POST', '/sprints/' + sprintId + '/tasks', { title: '', priority: 1 })
- .then(function (data) {
- $root.find('[data-empty-tasks]').remove();
- const $row = buildTaskRow(data.task, data.assignments || {});
- $taskTbody.append($row);
- // Clear any active sort so the new row is actually visible at the end.
- clearSort();
- applyFilters();
- $row.find('[data-title]').trigger('focus').trigger('select');
- flash('Task added');
- })
- .catch(function (e) { flash(e.message, true); });
- });
- // --- Edit task fields (title / owner / prio) --------------------------
- const titleDebounce = {};
- $root.on('input', '[data-title]', function () {
- const $inp = $(this);
- const taskId = parseInt($inp.closest('tr').data('task-id'), 10);
- clearTimeout(titleDebounce[taskId]);
- titleDebounce[taskId] = setTimeout(function () {
- const title = String($inp.val()).trim();
- if (title === '') {
- flash('Title cannot be empty', true);
- return;
- }
- request('PATCH', '/tasks/' + taskId, { title: title })
- .then(function () { flash('Saved'); })
- .catch(function (e) { flash(e.message, true); });
- }, 400);
- });
- $root.on('change', '[data-owner-select]', function () {
- const $sel = $(this);
- const $row = $sel.closest('tr');
- const taskId = parseInt($row.data('task-id'), 10);
- const v = $sel.val();
- const owner = v === '' ? null : parseInt(String(v), 10);
- $row.attr('data-owner', owner === null ? '' : owner);
- request('PATCH', '/tasks/' + taskId, { owner_worker_id: owner })
- .then(function () { flash('Saved'); applyFilters(); })
- .catch(function (e) { flash(e.message, true); });
- });
- $root.on('change', '[data-prio-select]', function () {
- const $sel = $(this);
- const $row = $sel.closest('tr');
- const taskId = parseInt($row.data('task-id'), 10);
- const prio = parseInt(String($sel.val()), 10);
- $row.attr('data-prio', prio);
- request('PATCH', '/tasks/' + taskId, { priority: prio })
- .then(function (data) {
- flash('Saved');
- applyFilters();
- applyServerCapacity(data && data.per_worker);
- recomputeAllCapacity();
- })
- .catch(function (e) { flash(e.message, true); });
- });
- // --- Delete task ------------------------------------------------------
- $root.on('click', '[data-delete-task]', function () {
- const $row = $(this).closest('tr');
- const taskId = parseInt($row.data('task-id'), 10);
- const title = $row.find('[data-title]').val() || '(untitled)';
- if (!window.confirm('Delete task "' + title + '"?')) { return; }
- request('DELETE', '/tasks/' + taskId)
- .then(function (data) {
- $row.remove();
- applyServerCapacity(data && data.per_worker);
- recomputeAllCapacity();
- flash('Task deleted');
- if ($taskTbody.children('tr[data-task-row]').length === 0) {
- // Re-show the empty-state row (simpler than templating).
- window.location.reload();
- }
- })
- .catch(function (e) { flash(e.message, true); });
- });
- // --- Assignment cells (per task, per sprint worker) -------------------
- // Same shape as the Arbeitstage cell queue, but against /tasks/{id}/assignments.
- const pendingAssign = new Map(); // taskId -> Map<swId, days>
- const assignTimers = {};
- function queueAssign(taskId, swId, days) {
- if (!pendingAssign.has(taskId)) { pendingAssign.set(taskId, new Map()); }
- pendingAssign.get(taskId).set(swId, days);
- clearTimeout(assignTimers[taskId]);
- assignTimers[taskId] = setTimeout(function () { flushAssign(taskId); }, 400);
- }
- function flushAssign(taskId) {
- const m = pendingAssign.get(taskId);
- if (!m || m.size === 0) { return; }
- const cells = [];
- m.forEach(function (days, swId) {
- cells.push({ sprint_worker_id: swId, days: days });
- });
- pendingAssign.delete(taskId);
- request('PATCH', '/tasks/' + taskId + '/assignments', cells)
- .then(function (data) {
- if (data.applied === 0 && data.noop > 0) { flash('No changes'); }
- else { flash('Saved ' + data.applied + (data.applied === 1 ? ' cell' : ' cells')); }
- applyServerCapacity(data && data.per_worker);
- })
- .catch(function (e) { flash(e.message, true); });
- }
- $root.on('blur change', '[data-assign]', function () {
- const $el = $(this);
- let v = Number($el.val());
- if (Number.isNaN(v) || v < 0) { v = 0; }
- v = snap05(v);
- $el.val(fmtDays(v));
- $el.closest('td').attr('data-sort-value-sw-' + $el.data('sw-id'), v.toFixed(2));
- const taskId = parseInt($el.closest('tr').data('task-id'), 10);
- const swId = parseInt($el.data('sw-id'), 10);
- queueAssign(taskId, swId, v);
- // Row total
- let tot = 0;
- $el.closest('tr').find('[data-assign]').each(function () {
- const n = Number($(this).val());
- if (!Number.isNaN(n)) { tot += n; }
- });
- $el.closest('tr').find('[data-task-tot]').text(fmtDays(tot));
- // Available recompute (in case this is a prio-1 task)
- recomputeAllCapacity();
- });
- function applyServerCapacity(perWorker) {
- if (!perWorker || typeof perWorker !== 'object') { return; }
- Object.keys(perWorker).forEach(function (swIdStr) {
- const c = perWorker[swIdStr];
- $root.find('[data-cap-ressourcen][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.ressourcen));
- $root.find('[data-cap-after-reserves][data-sw-id="' + swIdStr + '"]').text(fmtDays(c.after_reserves));
- const $av = $root.find('[data-cap-available][data-sw-id="' + swIdStr + '"]');
- $av.text(fmtDays(c.available));
- if (c.available < 0) {
- $av.removeClass('text-slate-900').addClass('text-red-700');
- } else {
- $av.removeClass('text-red-700').addClass('text-slate-900');
- }
- });
- }
- // --- Task reorder (drag) ----------------------------------------------
- if (sortableAvailable && hasTaskUi && $taskTbody.find('.handle').length > 0) {
- $taskTbody.sortable({
- handle: '.handle',
- items: 'tr[data-task-row]',
- axis: 'y',
- helper: function (e, tr) {
- const $cells = tr.children();
- const $clone = tr.clone();
- $clone.children().each(function (i) { $(this).width($cells.eq(i).width()); });
- return $clone;
- },
- start: function () {
- // Drag only makes sense when no sort is active.
- if (currentSort.col !== null) { clearSort(); }
- },
- update: function () {
- const ordering = $taskTbody.find('tr[data-task-row]').map(function (i, el) {
- return { task_id: parseInt($(el).data('task-id'), 10), sort_order: i + 1 };
- }).get();
- request('POST', '/sprints/' + sprintId + '/tasks/reorder', ordering)
- .then(function (data) {
- ordering.forEach(function (o) {
- $taskTbody.find('tr[data-task-id="' + o.task_id + '"]').attr('data-sort-order', o.sort_order);
- });
- flash(data.moved ? 'Order saved' : 'No changes');
- })
- .catch(function (e) { flash(e.message, true); });
- },
- });
- }
- // --- Multi-select owner filter (persisted in localStorage) -------------
- const ownerFilterKey = 'sp:' + sprintId + ':ownerFilter';
- /** @type {Set<string>} */
- const ownerFilterSet = (function () {
- try {
- const raw = window.localStorage.getItem(ownerFilterKey);
- if (raw) {
- const arr = JSON.parse(raw);
- if (Array.isArray(arr)) { return new Set(arr.map(String)); }
- }
- } catch (_) { /* ignore */ }
- return new Set();
- })();
- function persistOwnerFilter() {
- try {
- window.localStorage.setItem(ownerFilterKey, JSON.stringify(Array.from(ownerFilterSet)));
- } catch (_) { /* ignore quota / private mode */ }
- }
- function updateOwnerFilterUi() {
- // Reflect state back into the checkboxes.
- $root.find('[data-owner-filter-opt]').each(function () {
- $(this).prop('checked', ownerFilterSet.has(String($(this).val())));
- });
- // Count label on the trigger.
- const n = ownerFilterSet.size;
- $root.find('[data-owner-filter-count]').text(n === 0 ? '' : '(' + n + ')');
- }
- $root.on('change', '[data-owner-filter-opt]', function () {
- const v = String($(this).val());
- if ($(this).is(':checked')) { ownerFilterSet.add(v); } else { ownerFilterSet.delete(v); }
- persistOwnerFilter();
- updateOwnerFilterUi();
- applyFilters();
- });
- $root.on('click', '[data-owner-filter-clear]', function () {
- ownerFilterSet.clear();
- persistOwnerFilter();
- updateOwnerFilterUi();
- applyFilters();
- });
- $root.on('click', '[data-owner-filter-trigger]', function (ev) {
- ev.stopPropagation();
- $root.find('[data-columns-dropdown]').addClass('hidden');
- $root.find('[data-owner-filter-dropdown]').toggleClass('hidden');
- });
- // --- Filters (search / prio / owner) ----------------------------------
- function applyFilters() {
- const q = String($root.find('[data-task-search]').val() || '').trim().toLowerCase();
- const prio = String($root.find('[data-prio-filter]').val() || '');
- let visibleCount = 0;
- $taskTbody.children('tr[data-task-row]').each(function () {
- const $row = $(this);
- const title = String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
- const rowPrio = String($row.attr('data-prio'));
- const rowOwner = String($row.attr('data-owner') || '');
- // The filter set treats "" (no owner) as the special "__none__" key.
- const ownerKey = rowOwner === '' ? '__none__' : rowOwner;
- let ok = true;
- if (q !== '' && !title.includes(q)) { ok = false; }
- if (prio !== '' && rowPrio !== prio) { ok = false; }
- if (ownerFilterSet.size > 0 && !ownerFilterSet.has(ownerKey)) { ok = false; }
- $row.toggle(ok);
- if (ok) { visibleCount++; }
- });
- const totalRows = $taskTbody.children('tr[data-task-row]').length;
- $root.find('[data-task-empty-filter]').toggle(totalRows > 0 && visibleCount === 0);
- }
- let searchDebounce = null;
- $root.on('input', '[data-task-search]', function () {
- clearTimeout(searchDebounce);
- searchDebounce = setTimeout(applyFilters, 120);
- });
- $root.on('change', '[data-prio-filter]', applyFilters);
- // --- Column visibility toggle (persisted in localStorage) --------------
- const columnsKey = 'sp:' + sprintId + ':hiddenCols';
- /** @type {Set<string>} */
- const hiddenCols = (function () {
- try {
- const raw = window.localStorage.getItem(columnsKey);
- if (raw) {
- const arr = JSON.parse(raw);
- if (Array.isArray(arr)) { return new Set(arr.map(String)); }
- }
- } catch (_) { /* ignore */ }
- return new Set();
- })();
- function persistHiddenCols() {
- try {
- window.localStorage.setItem(columnsKey, JSON.stringify(Array.from(hiddenCols)));
- } catch (_) { /* ignore */ }
- }
- function applyColumnVisibility() {
- // Tailwind's .hidden is display:none; works on table cells.
- $root.find('[data-col]').each(function () {
- const col = String($(this).attr('data-col'));
- $(this).toggleClass('hidden', hiddenCols.has(col));
- });
- // Reflect state into the Columns dropdown checkboxes.
- $root.find('[data-column-opt]').each(function () {
- $(this).prop('checked', !hiddenCols.has(String($(this).val())));
- });
- }
- $root.on('change', '[data-column-opt]', function () {
- const v = String($(this).val());
- if ($(this).is(':checked')) { hiddenCols.delete(v); } else { hiddenCols.add(v); }
- persistHiddenCols();
- applyColumnVisibility();
- });
- $root.on('click', '[data-columns-trigger]', function (ev) {
- ev.stopPropagation();
- $root.find('[data-owner-filter-dropdown]').addClass('hidden');
- $root.find('[data-columns-dropdown]').toggleClass('hidden');
- });
- // Close either dropdown when clicking outside.
- $(document).on('click', function (ev) {
- if ($(ev.target).closest('[data-owner-filter-root]').length === 0) {
- $root.find('[data-owner-filter-dropdown]').addClass('hidden');
- }
- if ($(ev.target).closest('[data-columns-root]').length === 0) {
- $root.find('[data-columns-dropdown]').addClass('hidden');
- }
- });
- // --- Column sort (client-side) ----------------------------------------
- const currentSort = { col: null, dir: null }; // dir: 'asc' | 'desc'
- function clearSort() {
- currentSort.col = null; currentSort.dir = null;
- $root.find('[data-sort-col]').each(function () {
- $(this).find('.sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
- });
- // Restore original order by data-sort-order
- const rows = $taskTbody.children('tr[data-task-row]').get();
- rows.sort(function (a, b) {
- return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
- });
- rows.forEach(function (el) { $taskTbody.append(el); });
- }
- function rowValueFor(col, $row) {
- if (col === 'title') {
- return String($row.find('[data-title]').val() || $row.find('[data-title]').text() || '').toLowerCase();
- }
- if (col === 'owner') {
- const id = String($row.attr('data-owner') || '');
- if (id === '') { return '\uFFFF'; } // sort empty last
- const opt = $row.find('[data-owner-select] option:selected');
- return String(opt.text() || '').toLowerCase();
- }
- if (col === 'prio') { return Number($row.attr('data-prio')); }
- if (col === 'tot') { return Number($row.find('[data-task-tot]').text()) || 0; }
- if (col.indexOf('sw-') === 0) {
- const swId = col.slice(3);
- return Number($row.find('[data-assign][data-sw-id="' + swId + '"]').val()) || 0;
- }
- return 0;
- }
- function applySort(col) {
- let dir;
- if (currentSort.col !== col) { dir = 'asc'; }
- else if (currentSort.dir === 'asc') { dir = 'desc'; }
- else { clearSort(); return; } // third click clears
- currentSort.col = col;
- currentSort.dir = dir;
- $root.find('[data-sort-col] .sort-ind').text('↕').addClass('opacity-30').removeClass('opacity-100');
- $root.find('[data-sort-col="' + col + '"] .sort-ind')
- .text(dir === 'asc' ? '↑' : '↓')
- .removeClass('opacity-30').addClass('opacity-100');
- const rows = $taskTbody.children('tr[data-task-row]').get();
- rows.sort(function (a, b) {
- const va = rowValueFor(col, $(a));
- const vb = rowValueFor(col, $(b));
- if (va < vb) { return dir === 'asc' ? -1 : 1; }
- if (va > vb) { return dir === 'asc' ? 1 : -1; }
- // Stable-ish tiebreak: fall back to data-sort-order
- return Number($(a).attr('data-sort-order')) - Number($(b).attr('data-sort-order'));
- });
- rows.forEach(function (el) { $taskTbody.append(el); });
- }
- $root.on('click', '[data-sort-col]', function () {
- applySort(String($(this).attr('data-sort-col')));
- });
- // =====================================================================
- // Boot
- // =====================================================================
- // Recompute once at boot in case the server-rendered sums drift from the
- // JS formula (e.g. after a stale reload).
- $root.find('[data-sw-row]').each(function () {
- recomputeRow(parseInt($(this).data('sw-id'), 10));
- });
- // Restore persisted task-list UI state BEFORE applyFilters so hidden
- // columns don't briefly flash in before being toggled off.
- updateOwnerFilterUi();
- applyColumnVisibility();
- applyFilters();
- })(jQuery);
|