Files
labuh/board/board.js

1050 lines
53 KiB
JavaScript

// Labuh board: draws the harbour from /api/board and refreshes it every 20 seconds (5 while a
// Gas or a deploy is under way). Approvers act from the detail card.
// Text from the API is always set with textContent; SVG templates hold only fixed values.
(() => {
'use strict';
const REFRESH_MS = 20000;
const BUSY_REFRESH_MS = 5000;
const META = {
checking: { zone: 'cek', flag: '#7FA9C4', aria: 'sedang dicek', word: 'Dicek dulu', bg: '#E1EDF1', ink: '#1F4B5E', icon: 'dots' },
fix: { zone: 'cek', flag: '#D9654B', aria: 'ditahan reviewer', word: 'Tahan', bg: '#F8DDD5', ink: '#9A2E1A', icon: 'stop' },
blocked: { zone: 'cek', flag: '#9AA5A8', aria: 'nunggu, lihat alasannya', word: 'Nunggu', bg: '#EEF1F0', ink: '#3E4E53', icon: 'wait' },
manual: { zone: 'cek', flag: '#B7AE9C', aria: 'perlu dicek manual', word: 'Cek manual', bg: '#F1EBDF', ink: '#5C5440', icon: 'pause' },
parked: { zone: 'cek', flag: '#B7AE9C', aria: 'ditunda', word: 'Ditunda', bg: '#F1EBDF', ink: '#5C5440', icon: 'pause' },
ready: { zone: 'siap', flag: '#E8A33D', aria: 'aman, nunggu gas', word: 'Aman', bg: '#DDEFE5', ink: '#2E7A4E', icon: 'ok' },
gas: { zone: 'siap', flag: '#E8A33D', aria: 'sudah di-gas', word: 'Gas', bg: '#FBEBD0', ink: '#6B4206', icon: 'go' },
rejected: { zone: 'beres', flag: '#9AA5A8', aria: 'ditolak', word: 'Ditolak', bg: '#EEF1F0', ink: '#3E4E53', icon: 'x' },
sailing: { zone: 'beres', flag: '#7FA9C4', aria: 'berlayar, deploy jalan', word: 'Berlayar', bg: '#E1EDF1', ink: '#1F4B5E', icon: 'dots' },
failed: { zone: 'beres', flag: '#D9654B', aria: 'deploy gagal', word: 'Deploy gagal', bg: '#F8DDD5', ink: '#9A2E1A', icon: 'stop' },
done: { zone: 'beres', flag: '#5FA77C', aria: 'beres', word: 'Beres', bg: '#DDEFE5', ink: '#2E7A4E', icon: 'ok' },
};
const ZONES = [
{ key: 'cek', label: 'Dicek' },
{ key: 'siap', label: 'Siap gas' },
{ key: 'beres', label: 'Beres' },
];
const HULLS = ['#2F5D6B', '#6B8F71', '#B5653F', '#4C6A92', '#7A5C8E', '#8C6D3F', '#3F7F6A'];
const ICON = {
ok: '<svg width="26" height="26" viewBox="0 0 16 16"><path d="M3 8.5l3 3 7-7" fill="none" stroke="#FFFFFF" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
stop: '<svg width="26" height="26" viewBox="0 0 18 18"><path d="M9 3v12M4.5 10.5a4.5 4.5 0 0 0 9 0M6 6h6" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round"/><circle cx="9" cy="3" r="1.6" fill="#FFFFFF"/></svg>',
wait: '<svg width="26" height="26" viewBox="0 0 16 16"><path d="M4 2h8M4 14h8M5 2c0 3 6 3 6 6s-6 3-6 6M11 2c0 3-6 3-6 6s6 3 6 6" fill="none" stroke="#FFFFFF" stroke-width="1.6" stroke-linecap="round"/></svg>',
pause: '<svg width="24" height="24" viewBox="0 0 16 16"><path d="M5.5 3.5v9M10.5 3.5v9" stroke="#FFFFFF" stroke-width="2.4" stroke-linecap="round"/></svg>',
dots: '<span class="dots"><i></i><i></i><i></i></span>',
x: '<svg width="22" height="22" viewBox="0 0 16 16"><path d="M4 4l8 8M12 4l-8 8" stroke="#FFFFFF" stroke-width="2.4" stroke-linecap="round"/></svg>',
go: '<svg width="26" height="26" viewBox="0 0 16 16"><path d="M3 8h9M8.5 4.5L12 8l-3.5 3.5" fill="none" stroke="#FFFFFF" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
};
const ACTION_LABEL = { gas: 'Gas', tunda: 'Tunda', tolak: 'Tolak', close: 'Tutup MR', undo: 'Batalkan' };
const KIND = {
bad: '<svg width="12" height="12" viewBox="0 0 12 12"><path d="M6 2.5v4.2" stroke="#9A2E1A" stroke-width="2" stroke-linecap="round"/><circle cx="6" cy="9.3" r="1.1" fill="#9A2E1A"/></svg>',
ok: '<svg width="12" height="12" viewBox="0 0 16 16"><path d="M3 8.5l3 3 7-7" fill="none" stroke="#2E7A4E" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',
todo: '<svg width="12" height="12" viewBox="0 0 12 12"><path d="M3 6h6M6.5 3.5L9 6l-2.5 2.5" fill="none" stroke="#6B4206" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>',
};
const state = { cols: null, data: null, sel: null, lane: null, laneDir: 0, filter: 'all', listOpen: false, seen: new Set(), first: true, failedAt: null, shown: null, composing: null, busy: false, error: null, releaseTag: null };
const $ = (id) => document.getElementById(id);
const phone = window.matchMedia('(max-width: 899px)');
const shortTitle = (t, n = 28) => {
const s = String(t || '').trim().replace(/\s+/g, ' ');
if (!s) return '';
return s.length <= n ? s : `${s.slice(0, n - 1).trimEnd()}…`;
};
function el(tag, attrs, ...children) {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(attrs || {})) {
if (v === null || v === undefined || v === false) continue;
if (k === 'class') n.className = v;
else if (k === 'html') n.innerHTML = v;
else if (k === 'style') typeof v === 'string' ? n.setAttribute('style', v) : Object.assign(n.style, v);
else if (k.startsWith('on')) n.addEventListener(k.slice(2), v);
else n.setAttribute(k, v === true ? '' : v);
}
for (const c of children.flat()) if (c !== null && c !== undefined && c !== false) n.append(c instanceof Node ? c : document.createTextNode(String(c)));
return n;
}
const hash = (s) => [...s].reduce((h, c) => (h * 31 + c.charCodeAt(0)) >>> 0, 7);
const hullOf = (a) => HULLS[hash(a.repo + a.iid) % HULLS.length];
const colorOf = (name) => HULLS[hash(name || '?') % HULLS.length];
function age(iso) {
const m = Math.max(0, Math.round((Date.now() - Date.parse(iso)) / 60000));
if (m < 5) return 'baru';
if (m < 60) return `${m} menit`;
if (m < 60 * 24) return `${Math.round(m / 60)} jam`;
return `${Math.round(m / 1440)} hari`;
}
const clock = (iso) => {
const d = new Date(iso);
return `${String(d.getHours()).padStart(2, '0')}.${String(d.getMinutes()).padStart(2, '0')}`;
};
// ---- Sea decoration, drawn once ----
function drawSea() {
const sea = document.querySelector('.sea');
let d = 'M0 8 q25 -7 50 0';
for (let k = 0; k < 31; k++) d += ' t50 0';
const waves = [['6%', .35, 12, 'normal'], ['19%', .25, 16, 'reverse'], ['33%', .45, 9, 'normal'], ['47%', .3, 14, 'reverse'], ['61%', .4, 10, 'normal'], ['74%', .28, 15, 'reverse'], ['88%', .45, 11, 'normal']];
for (const [top, op, dur, dir] of waves) {
const s = el('span', { class: 'wave', style: { top, opacity: op, animationDuration: `${dur}s`, animationDirection: dir } });
s.innerHTML = `<svg width="1600" height="16"><path d="${d}" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-linecap="round"/></svg>`;
sea.append(s);
}
for (const [left, top, delay] of [['6%', '26%', 0], ['21%', '56%', 1.1], ['38%', '14%', 2.3], ['47%', '82%', .6], ['58%', '40%', 1.8], ['72%', '70%', 2.8], ['84%', '22%', .9], ['14%', '92%', 2]])
sea.append(el('span', { class: 'sparkle', style: { left, top, animationDelay: `${delay}s` } }));
for (const [left, top, delay] of [['12%', '44%', 0], ['33%', '90%', 1.6], ['55%', '9%', 3], ['66%', '58%', .8]])
sea.append(el('span', { class: 'ripple', style: { left, top, animationDelay: `${delay}s` } }));
for (const [top, dur, delay] of [['18%', 90, -20], ['62%', 120, -75]])
sea.append(el('span', { class: 'cloud', style: { top, animationDuration: `${dur}s`, animationDelay: `${delay}s` } }));
for (const [top, dur, delay, size] of [['6%', 38, -6, 22], ['13%', 52, -30, 16]]) {
const g = el('span', { class: 'gull', style: { top, animationDuration: `${dur}s`, animationDelay: `${delay}s` } });
g.innerHTML = `<svg width="${size}" height="12" viewBox="0 0 22 12"><path d="M1 8 Q6 1 11 8 Q16 1 21 8" fill="none" stroke="#2B4148" stroke-width="2" stroke-linecap="round"/></svg>`;
sea.append(g);
}
const edge = (x) => {
let p = `M${x} 0 q-12 35 0 70`;
for (let k = 0; k < 13; k++) p += ' t0 70';
return p;
};
const svg = document.querySelector('.shore .edge');
svg.setAttribute('viewBox', '0 0 64 980');
svg.querySelector('.foam').setAttribute('d', edge(14));
svg.querySelector('.sand').setAttribute('d', `${edge(26)} L64 980 L64 0 Z`);
svg.querySelector('.land').setAttribute('d', `${edge(42)} L64 980 L64 0 Z`);
}
// ---- Boats and lanes ----
function boat(a) {
const m = META[a.status];
const picked = state.sel === a.id;
const dim = state.filter === 'mine' && !a.needsYou;
const cls = ['boat', picked && 'picked', dim && 'dim', a.needsYou && 'needs', (a.status === 'done' || a.status === 'rejected') && 'done', a.status === 'sailing' && 'sailing', !state.first && !state.seen.has(a.id) && 'new'].filter(Boolean).join(' ');
// The bobbing phase comes from the clock and the boat, not its place in the list, so a boat
// drawn again carries on mid-swell instead of jumping back to the start of its loop.
const seed = hash(`${a.repo}${a.iid}`);
const secs = a.status === 'done' ? 6 : 4.2 + (seed % 3) * 0.4;
const now = Date.now() / 1000 + (seed % 97) * 0.37;
const delay = `-${(now % secs).toFixed(2)}s`;
const flagDelay = `-${(now % 2.2).toFixed(2)}s`;
const dur = `${secs.toFixed(1)}s`;
const title = shortTitle(a.title, phone.matches ? 24 : 28);
const b = el('button', { type: 'button', class: cls, 'data-id': a.id, 'aria-label': `${a.label}${a.title ? `, ${a.title}` : ''}, ${m.aria}`, 'aria-pressed': picked ? 'true' : 'false', onclick: () => pick(a.id) });
const hull = el('span', { class: 'hull', style: { animationDelay: delay, animationDuration: dur } });
const h = hullOf(a);
hull.innerHTML = `<svg width="96" height="72" viewBox="0 0 96 72" aria-hidden="true" style="overflow:visible"><line x1="48" y1="5" x2="48" y2="44" stroke="#172B33" stroke-width="2.5" stroke-linecap="round"/><g class="flag" style="animation-delay:${flagDelay}"><path d="M50 6 Q60 8 72 7 Q67 12.5 72 18 Q60 17 50 19 Z" fill="${m.flag}"/></g><rect x="34" y="29" width="28" height="16" rx="4" fill="#FFFDF8"/><circle cx="42" cy="37" r="2.6" fill="${h}"/><circle cx="54" cy="37" r="2.6" fill="${h}"/><path d="M6 44 H90 L81 61 Q79 65 73 65 H23 Q17 65 15 61 Z" fill="${h}"/><path d="M13 51 H83" stroke="#FFFDF8" stroke-opacity="0.45" stroke-width="2" stroke-linecap="round"/></svg>`;
b.append(hull, el('span', { class: 'shade', 'aria-hidden': 'true', style: { animationDelay: delay, animationDuration: dur } }));
if (a.status === 'fix' || a.status === 'manual' || a.status === 'failed')
b.append(el('span', { class: 'anchor', 'aria-hidden': 'true', html: '<svg width="24" height="46" viewBox="0 0 24 46"><path d="M18 0 Q8 14 12 28" fill="none" stroke="#5B3A2A" stroke-width="1.5" stroke-dasharray="3 3"/><path d="M12 30v12M7.5 37.5a4.5 4.5 0 0 0 9 0M9 33h6" fill="none" stroke="#9A2E1A" stroke-width="2" stroke-linecap="round"/><circle cx="12" cy="29.5" r="1.8" fill="#9A2E1A"/></svg>' }));
if (a.status === 'ready' || a.status === 'gas')
b.append(el('span', { class: 'buoy', 'aria-hidden': 'true', html: '<span class="ring"></span><svg width="18" height="22" viewBox="0 0 18 22"><line x1="9" y1="1" x2="9" y2="8" stroke="#172B33" stroke-width="1.5" stroke-linecap="round"/><path d="M2 15 a7 7 0 0 1 14 0 v2 H2 Z" fill="#E8A33D"/><rect x="2" y="12.5" width="14" height="2.4" fill="#FFFDF8"/></svg>' }));
if (a.status === 'done')
b.append(el('span', { class: 'rope', 'aria-hidden': 'true', html: '<svg width="20" height="12" viewBox="0 0 20 12"><path d="M0 2 Q10 12 20 4" fill="none" stroke="#7A5A33" stroke-width="1.8" stroke-linecap="round"/></svg>' }));
b.append(el('span', { class: 'chip' }, a.label));
if (title) b.append(el('span', { class: 'boat-title' }, title));
const marks = el('span', { class: 'marks', 'aria-hidden': 'true' });
if (a.status === 'checking' || a.status === 'sailing' || a.status === 'gas') marks.innerHTML = ICON.dots;
// Waiting can be a pipeline or another MR, so the mark is an hourglass, not a link.
if (a.status === 'blocked') marks.innerHTML = '<svg width="16" height="16" viewBox="0 0 16 16"><path d="M4 2h8M4 14h8M5 2c0 3 6 3 6 6s-6 3-6 6M11 2c0 3-6 3-6 6s6 3 6 6" fill="none" stroke="#3E4E53" stroke-width="1.6" stroke-linecap="round"/></svg>';
b.append(marks);
return b;
}
// Boats sail to their new place instead of jumping: each one starts where it was before the
// redraw (FLIP) and drifts there slowly. The move and the swell over it are two animations,
// each eased on its own, so the speed never changes abruptly along the way.
const calm = window.matchMedia('(prefers-reduced-motion: reduce)');
const SAIL_EASE = 'cubic-bezier(.42,0,.28,1)';
const SWELL_EASE = 'cubic-bezier(.37,0,.63,1)';
function sail(before) {
if (calm.matches) return;
for (const b of $('lanes').querySelectorAll('.boat[data-id]')) {
const from = before.get(b.dataset.id);
if (!from) continue;
const to = b.getBoundingClientRect();
const dx = from.left - to.left;
const dy = from.top - to.top;
const dist = Math.hypot(dx, dy);
if (dist < 1) continue;
// Unhurried: a short shuffle takes over a second, a crossing of the harbour about three.
const duration = Math.min(3200, 1300 + dist * 2.4);
const lift = Math.min(22, dist / 14);
const tilt = Math.abs(dx) < 4 ? 0 : dx < 0 ? 2.5 : -2.5;
const berth = b.closest('.zone, .band');
if (berth) berth.style.zIndex = '3';
const move = b.animate([{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'translate(0, 0)' }], { duration, easing: SAIL_EASE });
b.animate([
{ transform: 'translateY(0) rotate(0deg)', easing: SWELL_EASE },
{ transform: `translateY(${-lift}px) rotate(${tilt}deg)`, offset: 0.5, easing: SWELL_EASE },
{ transform: 'translateY(0) rotate(0deg)' },
], { duration, composite: 'add' });
move.onfinish = move.oncancel = () => { if (berth) berth.style.zIndex = ''; };
}
}
// ---- Quay rows: two slot rows per lane ----
// Every lane holds two rows of boats and never grows taller. Beres keeps its width: when it is
// full the boat that docked first sails out of the harbour (first in, first out). Dicek and Siap
// gas cannot hand boats on, so they widen instead and the other gives way; only when even that
// is not enough do their boats moor closer together. Column widths change through a CSS
// transition and boats glide (FLIP), so every shift is gradual.
const ROWS = 2;
const SLOT_GAP = 10;
const SHARE = { cek: 3, siap: 2 };
// Beres is a fixed berth: two boats per row, so four boats in all.
const BERES_PER_ROW = 2;
// Dicek and Siap gas share what Beres leaves: each its share, or what its boats need if more.
function splitWidth(total, needs, least, weights) {
const fixed = needs.map(() => false);
let widths = needs.slice();
for (let round = 0; round < needs.length; round++) {
const freeWidth = total - needs.reduce((s, n, i) => s + (fixed[i] ? n : 0), 0);
const freeWeight = weights.reduce((s, w, i) => s + (fixed[i] ? 0 : w), 0);
if (!freeWeight) break;
widths = needs.map((n, i) => (fixed[i] ? n : (freeWidth * weights[i]) / freeWeight));
const short = widths.map((w, i) => !fixed[i] && w < needs[i]);
if (!short.some(Boolean)) break;
short.forEach((x, i) => { if (x) fixed[i] = true; });
}
const need = needs.reduce((s, n) => s + n, 0);
if (need <= total) return widths;
const floor = least.reduce((s, n) => s + n, 0);
const keep = Math.max(0, (total - floor) / (need - floor));
return needs.map((n, i) => least[i] + (n - least[i]) * keep);
}
const perRow = (n) => Math.max(1, Math.ceil(n / ROWS));
const rowWidth = (n, boatW) => perRow(n) * boatW + (perRow(n) - 1) * SLOT_GAP;
// Slots for `n` boats in a column `width` wide: side by side with a gap, or overlapping when narrow.
function slots(n, width, boatW) {
const k = perRow(n);
if (k === 1) return `${boatW}px`;
const step = Math.max(0.45 * boatW, Math.min(boatW + SLOT_GAP, (width - boatW) / (k - 1)));
return `repeat(${k - 1}, ${step.toFixed(1)}px) ${boatW}px`;
}
// The harbour's measurements before boats are placed: usable width, column gap, boat width.
function measure(row) {
const css = getComputedStyle(row);
const gap = parseFloat(css.columnGap) || 0;
const total = row.clientWidth - (parseFloat(css.paddingRight) || 0) - gap * 2;
const boatW = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--boat-w')) || 120;
return { total, boatW };
}
const beresWidth = (boatW) => BERES_PER_ROW * boatW + (BERES_PER_ROW - 1) * SLOT_GAP;
// Shrink slot and boat sizes so every lane / phone scene fits inside the viewport.
const SLOT_MAX = 176;
const SLOT_MIN = 100;
const BOAT_NATURAL = 158; // hull + chip + title + marks at full size (desktop)
const PHONE_BOAT = 112; // hull + chip + marks at phone defaults
function clearFitVars(root) {
root.style.removeProperty('--slot-h');
root.style.removeProperty('--boat-w');
root.style.removeProperty('--hull-w');
root.style.removeProperty('--hull-h');
delete root.dataset.boatCompact;
}
function applyBoatScale(root, scale, baseBoat, baseHullW, baseHullH) {
if (scale >= 0.995) return;
root.style.setProperty('--boat-w', `${Math.max(64, Math.round(baseBoat * scale))}px`);
root.style.setProperty('--hull-w', `${Math.max(48, Math.round(baseHullW * scale))}px`);
root.style.setProperty('--hull-h', `${Math.max(36, Math.round(baseHullH * scale))}px`);
}
function layoutPhoneFit(root) {
const scene = document.querySelector('.harbour-scene');
if (!scene) {
clearFitVars(root);
return;
}
clearFitVars(root);
const baseBoat = parseFloat(getComputedStyle(root).getPropertyValue('--boat-w')) || 108;
const baseHullW = parseFloat(getComputedStyle(root).getPropertyValue('--hull-w')) || 88;
const baseHullH = parseFloat(getComputedStyle(root).getPropertyValue('--hull-h')) || 66;
const beach = scene.querySelector('.beach');
const avail = scene.clientHeight - (beach ? beach.offsetHeight : 22);
if (avail < 60) return;
// Grid rows are 1fr / 1.15fr / 1fr — size boats to the mid band.
const midBand = avail * (1.15 / 3.15);
const scale = Math.min(1, Math.max(0.55, (midBand - 6) / PHONE_BOAT));
applyBoatScale(root, scale, baseBoat, baseHullW, baseHullH);
}
function layoutFit() {
const root = document.documentElement;
if (phone.matches) {
layoutPhoneFit(root);
return;
}
const main = $('lanes');
const n = main.querySelectorAll('.lane').length;
if (!n) {
clearFitVars(root);
return;
}
// Read the stylesheet defaults (after clearing any previous inline shrink) so a roomy
// window can grow back to full size, and narrow-laptop media rules still apply.
clearFitVars(root);
const baseBoat = parseFloat(getComputedStyle(root).getPropertyValue('--boat-w')) || 120;
const baseHullW = parseFloat(getComputedStyle(root).getPropertyValue('--hull-w')) || 96;
const baseHullH = parseFloat(getComputedStyle(root).getPropertyValue('--hull-h')) || 72;
const avail = main.clientHeight;
if (avail < 80) return;
// Per lane: h2 + paddings + zone-label row + boat-row gap, then two slot rows.
const laneChrome = 28 + 26 + 36 + 4;
const slot = Math.max(SLOT_MIN, Math.min(SLOT_MAX, Math.floor((avail / n - laneChrome) / ROWS)));
root.style.setProperty('--slot-h', `${slot}px`);
// When the slot is shorter than a full boat, scale the boat and drop the title.
const boatH = Math.min(BOAT_NATURAL, slot - 4);
const scale = Math.min(1, boatH / BOAT_NATURAL);
root.dataset.boatCompact = scale < 0.92 ? '1' : '0';
applyBoatScale(root, scale, baseBoat, baseHullW, baseHullH);
}
// Places the boats already in `rows` (one grid per lane) and sizes the columns.
function layoutColumns() {
const rows = [...$('lanes').querySelectorAll('.zones')];
if (phone.matches) {
layoutFit();
for (const r of rows) r.style.gridTemplateColumns = '';
for (const b of $('lanes').querySelectorAll('.boats')) b.style.gridTemplateColumns = '';
state.cols = null;
return;
}
if (!rows.length) return;
layoutFit();
const { total, boatW } = measure(rows[0]);
const count = (z) => Math.max(1, ...rows.map((r) => r.children[z].querySelector('.boats').childElementCount));
const beres = beresWidth(boatW);
const [cek, siap] = splitWidth(total - beres, [rowWidth(count(0), boatW), rowWidth(count(1), boatW)], [boatW, boatW], [SHARE.cek, SHARE.siap]);
const widths = [cek, siap, beres];
const first = !state.cols;
state.cols = widths.map((w) => `${w.toFixed(1)}px`).join(' ');
for (const r of rows) {
[...r.children].forEach((zone, z) => {
const boats = zone.querySelector('.boats');
boats.style.gridTemplateColumns = slots(boats.childElementCount, widths[z], boatW);
});
if (first) r.style.transition = 'none';
r.style.gridTemplateColumns = state.cols;
}
if (first) {
void rows[0].offsetWidth;
for (const r of rows) r.style.transition = '';
}
}
// Boats that left the water since the last drawing sail out past the breakwater and fade.
function depart(before, shown) {
if (calm.matches) return;
const water = document.querySelector('.water');
const box = water.getBoundingClientRect();
for (const [id, { rect, node }] of before) {
if (shown.has(id)) continue;
const ghost = node.cloneNode(true);
ghost.classList.add('ghost');
ghost.removeAttribute('data-id');
ghost.setAttribute('aria-hidden', 'true');
ghost.tabIndex = -1;
Object.assign(ghost.style, { position: 'absolute', left: `${rect.left - box.left}px`, top: `${rect.top - box.top}px`, margin: '0', zIndex: '4', pointerEvents: 'none' });
water.append(ghost);
const run = ghost.animate([
{ transform: 'translate(0, 0) rotate(0deg)', opacity: 1 },
{ transform: 'translate(36px, 34px) rotate(-3deg)', opacity: 0.9, offset: 0.4 },
{ transform: 'translate(90px, 110px) rotate(-5deg)', opacity: 0 },
], { duration: 2400, easing: 'cubic-bezier(.42,0,.58,1)' });
run.onfinish = run.oncancel = () => ghost.remove();
}
}
// Interruptible motion (phone dermaga pan) — reuse this pattern for later board animations.
//
// Goal: a reverse tap mid-flight continues from the pixels on screen (UIKit / UIViewPropertyAnimator),
// never jumps back to a rest pose, and never tears the moving layer down early.
//
// Do:
// 1. Animate whole layers (here: two `.phone-harbour` scenes), not clones of children.
// 2. Keep both layers mounted for the whole pan (`#lanes.lane-panning`). On interrupt, swap
// which one is "stay" vs "leave" and retarget — do not replaceChildren / remove ghosts.
// 3. Retarget with commitStyles → cancel → animate from getComputedStyle().transform to the
// new end. That presentation value is the continuous join point.
// 4. Use one long ease-in-ease-out (Apple CAMediaTimingFunction easeInEaseOut below), no stagger,
// so it reads as a camera pan. Bump lanePanGen so stale finished callbacks no-op.
// 5. Clip at the real screen edge (full-bleed `#lanes`); padding belongs inside the scene.
//
// Don't:
// - Snapshot boats into absolute ghosts and delete the live tree (killing in-flight work).
// - Start a new keyframe from translate(0) / off-screen while an old animation still owns the node.
// - clear() or cancel without commitStyles first (causes a visible snap).
//
// Reference implementation: interruptiblePan + panPhoneHarbour below.
const LANE_SLIDE_MS = 920;
const LANE_SLIDE_EASE = 'cubic-bezier(0.42, 0, 0.58, 1)'; // CAMediaTimingFunction easeInEaseOut
let lanePanGen = 0;
function interruptiblePan(el, to, { onDone } = {}) {
for (const a of el.getAnimations()) {
try { a.commitStyles(); } catch { /* not fill:forwards yet */ }
a.cancel();
}
const from = getComputedStyle(el).transform;
const anim = el.animate(
[{ transform: from === 'none' ? 'matrix(1, 0, 0, 1, 0, 0)' : from }, { transform: to }],
{ duration: LANE_SLIDE_MS, easing: LANE_SLIDE_EASE, fill: 'forwards' },
);
const gen = lanePanGen;
anim.finished.then(() => {
if (gen !== lanePanGen) return;
try { anim.commitStyles(); } catch { /* already cancelled */ }
anim.cancel();
if (to === 'translateX(0px)') el.style.transform = '';
if (onDone) onDone();
}).catch(() => {});
return anim;
}
function buildPhoneScene(laneName) {
const scene = el('div', { class: 'harbour-scene' });
for (const z of ZONES) {
const items = zoneItems(state.data, laneName, z);
scene.append(
el('div', { class: `band band-${z.key}`, 'aria-label': z.label },
el('div', { class: 'boats' }, items.map((a) => boat(a))),
),
);
}
scene.append(el('div', { class: 'beach', 'aria-hidden': 'true' }));
return el('section', { class: 'lane phone-harbour', 'aria-label': laneName }, scene);
}
function settlePhoneHarbour(main, keep) {
for (const child of [...main.children]) {
if (child === keep) continue;
for (const a of child.getAnimations()) a.cancel();
child.remove();
}
for (const a of keep.getAnimations()) {
try { a.commitStyles(); } catch { /* ignore */ }
a.cancel();
}
keep.classList.remove('lane-pan', 'lane-in', 'lane-out');
keep.style.transform = '';
main.classList.remove('lane-panning');
main.style.height = '';
layoutFit();
}
function panPhoneHarbour(main, dir) {
const target = state.lane;
if (!target) {
main.replaceChildren();
main.classList.remove('lane-panning');
return;
}
if (calm.matches) {
main.classList.remove('lane-panning');
main.replaceChildren(buildPhoneScene(target));
layoutFit();
return;
}
lanePanGen += 1;
const gen = lanePanGen;
const scenes = [...main.querySelectorAll('.phone-harbour')];
let stay = scenes.find((s) => s.getAttribute('aria-label') === target) || null;
let leave = scenes.find((s) => s !== stay) || null;
// Mid-pan interrupt: both scenes stay mounted; only the targets change.
if (stay && leave && main.classList.contains('lane-panning')) {
stay.classList.add('lane-pan', 'lane-in');
stay.classList.remove('lane-out');
leave.classList.add('lane-pan', 'lane-out');
leave.classList.remove('lane-in');
interruptiblePan(leave, dir > 0 ? 'translateX(-100%)' : 'translateX(100%)', {
onDone: () => { if (gen === lanePanGen && leave.isConnected) leave.remove(); },
});
interruptiblePan(stay, 'translateX(0px)', {
onDone: () => { if (gen === lanePanGen) settlePhoneHarbour(main, stay); },
});
return;
}
// Fresh pan from a settled harbour.
const current = main.querySelector('.phone-harbour');
if (!current) {
main.replaceChildren(buildPhoneScene(target));
return;
}
if (current.getAttribute('aria-label') === target) return;
main.style.height = `${Math.max(main.offsetHeight, 280)}px`;
main.classList.add('lane-panning');
current.classList.add('lane-pan', 'lane-out');
current.classList.remove('lane-in');
const next = buildPhoneScene(target);
next.classList.add('lane-pan', 'lane-in');
next.style.transform = dir > 0 ? 'translateX(100%)' : 'translateX(-100%)';
main.append(next);
interruptiblePan(current, dir > 0 ? 'translateX(-100%)' : 'translateX(100%)', {
onDone: () => { if (gen === lanePanGen && current.isConnected) current.remove(); },
});
interruptiblePan(next, 'translateX(0px)', {
onDone: () => { if (gen === lanePanGen) settlePhoneHarbour(main, next); },
});
}
function visibleLanes(data) {
const used = new Set(data.ajuan.map((a) => a.lane));
return data.lanes.filter((l, i) => used.has(l) || (l !== 'Lainnya' && i < 2));
}
function zoneItems(data, lane, z) {
let items = data.ajuan.filter((a) => a.lane === lane && META[a.status].zone === z.key);
// Beres in the order boats docked, so the first in is the first out.
if (z.key === 'beres') items = items.slice().sort((x, y) => Date.parse(x.dockedAt) - Date.parse(y.dockedAt));
return items;
}
function drawToolbar(lanes) {
const bar = $('toolbar');
if (!phone.matches) {
bar.hidden = true;
bar.replaceChildren();
return;
}
const { data } = state;
const mine = data.ajuan.filter((a) => a.needsYou).length;
bar.hidden = false;
bar.replaceChildren(
el('div', { class: 'dermaga', role: 'group', 'aria-label': 'Dermaga' },
lanes.map((name) => el('button', {
type: 'button',
class: 'chip-pill',
'aria-pressed': String(state.lane === name),
onclick: () => {
if (state.lane === name) return;
const from = lanes.indexOf(state.lane);
const to = lanes.indexOf(name);
state.laneDir = to >= 0 && from >= 0 && to !== from ? (to > from ? 1 : -1) : 1;
state.lane = name;
state.sel = null;
state.listOpen = false;
history.replaceState(null, '', location.pathname);
drawnLanes = '';
draw();
},
}, name)),
),
el('button', {
type: 'button',
class: 'chip-pill filter',
'aria-pressed': String(state.filter === 'mine'),
onclick: () => {
// Toggle off restores the full harbour; only open the list when turning the filter on.
if (state.filter === 'mine') {
state.filter = 'all';
state.listOpen = false;
} else {
state.filter = 'mine';
state.sel = null;
state.listOpen = true;
history.replaceState(null, '', location.pathname);
}
draw();
},
}, 'Perlu kamu', el('span', { class: 'count' }, mine)),
);
}
// Phone: one dermaga as a single water scene (no zone-card chrome).
function resolvePhoneLane(data, lanes) {
const selected = state.sel && data.ajuan.find((a) => a.id === state.sel);
if (selected && lanes.includes(selected.lane)) state.lane = selected.lane;
else if (!state.lane || !lanes.includes(state.lane))
state.lane = lanes.find((l) => data.ajuan.some((a) => a.lane === l)) || lanes[0] || null;
}
function drawPhoneHarbour(main, data, lanes) {
resolvePhoneLane(data, lanes);
drawToolbar(lanes);
main.classList.remove('lane-panning');
if (!state.lane) {
main.replaceChildren();
clearFitVars(document.documentElement);
return;
}
main.replaceChildren(buildPhoneScene(state.lane));
layoutFit();
}
let drawnLanes = '';
function drawLanes() {
const { data } = state;
const lanes = visibleLanes(data);
const main = $('lanes');
// A refresh that changes nothing on the water leaves the boats alone, so none restarts mid-glide.
const key = JSON.stringify([phone.matches, state.lane, lanes, state.sel, state.filter, data.ajuan.map((a) => [a.id, a.lane, a.status, a.label, a.title, a.needsYou, state.seen.has(a.id)])]);
if (key === drawnLanes && main.childElementCount) {
if (phone.matches) drawToolbar(lanes);
return;
}
drawnLanes = key;
const before = new Map([...main.querySelectorAll('.boat[data-id]')].map((b) => [b.dataset.id, { rect: b.getBoundingClientRect(), node: b }]));
const shown = new Set();
if (phone.matches) {
const dir = state.laneDir;
state.laneDir = 0;
if (dir) {
resolvePhoneLane(data, lanes);
drawToolbar(lanes);
panPhoneHarbour(main, dir);
return;
}
// Don't tear down a live pan when the queue merely refreshes.
if (main.classList.contains('lane-panning')) {
drawToolbar(lanes);
return;
}
drawPhoneHarbour(main, data, lanes);
for (const b of main.querySelectorAll('.boat[data-id]')) shown.add(b.dataset.id);
sail(new Map([...before].map(([id, b]) => [id, b.rect])));
depart(before, shown);
return;
}
$('toolbar').hidden = true;
$('toolbar').replaceChildren();
main.replaceChildren();
lanes.forEach((name, li) => {
// A redrawn row starts at the widths it had, so the change to new widths can transition.
const zones = el('div', { class: 'zones', style: state.cols ? { gridTemplateColumns: state.cols } : null });
for (const z of ZONES) {
const items = zoneItems(data, name, z);
zones.append(
el('div', { class: `zone ${z.key}` },
z.key !== 'cek' && el('div', { class: 'floats', 'aria-hidden': 'true' }),
el('span', { class: 'zone-label' }, z.label, el('span', { class: `n${z.key === 'siap' && items.length ? ' hot' : ''}` }, items.length)),
el('div', { class: 'boats' }, items.map((a) => Object.assign(boat(a), { finished: a.status === 'done' || a.status === 'rejected' }))),
),
);
}
const last = li === lanes.length - 1;
const lane = el('section', { class: `lane${last ? '' : ' has-break'}`, 'aria-label': name },
el('div', { class: 'quay', 'aria-hidden': 'true' }),
el('div', { class: 'pilings', 'aria-hidden': 'true' }),
el('h2', {}, name),
zones,
);
if (!last)
lane.append(el('div', { class: 'breakwater', 'aria-hidden': 'true', html: '<svg width="30" height="58" viewBox="0 0 30 58"><circle class="beam" cx="15" cy="9" r="13" fill="#F6D58E"/><path d="M9 16 L21 16 L23 52 L7 52 Z" fill="#FFFDF8"/><path d="M8.4 27 L21.6 27 L22.2 36 L7.8 36 Z" fill="#C2453A"/><rect x="9" y="6" width="12" height="10" rx="2" fill="#E8A33D"/><path d="M7 6 L15 0 L23 6 Z" fill="#172B33"/></svg>' }));
main.append(lane);
});
// A full Beres lets its earliest finished boats go; deploys still running or failed stay.
const room = ROWS * BERES_PER_ROW;
for (const boats of main.querySelectorAll('.zone.beres .boats')) {
const docked = [...boats.children];
const finished = docked.filter((b) => b.finished);
finished.slice(0, Math.max(0, Math.min(finished.length, docked.length - room))).forEach((b) => b.remove());
boats.parentElement.querySelector('.zone-label .n').textContent = boats.childElementCount;
}
for (const b of main.querySelectorAll('.boat[data-id]')) shown.add(b.dataset.id);
// Boats take their new slots at once; the columns then widen or narrow through their
// transition, and every boat glides from where it was. layoutColumns fits height first
// so the shrunk boat width is what the columns measure.
layoutColumns();
sail(new Map([...before].map(([id, b]) => [id, b.rect])));
depart(before, shown);
}
// ---- Shore: detail or what needs you ----
function evidenceLinks(list) {
return el('span', { class: 'evidence' }, list.map((e) => el('a', { href: e.url, target: e.url.startsWith('/') ? null : '_blank', rel: 'noopener' }, e.label)));
}
// ---- Approver actions ----
function countdownText(a) {
if (a.closeAt) {
const c = Math.max(0, Math.ceil((a.closeAt - Date.now()) / 1000));
if (c === 0) return a.dry ? 'Labuh lagi cek (uji coba)…' : 'Labuh lagi menutup MR…';
return `${a.dry ? 'Uji coba tutup MR' : 'MR ditutup'} dalam ${c} dtk. Masih bisa dibatalkan.`;
}
const s = Math.max(0, Math.ceil((a.gasAt - Date.now()) / 1000));
if (s === 0) return a.dry ? 'Labuh lagi cek (uji coba)…' : 'Labuh lagi merge…';
return `${a.dry ? 'Uji coba' : 'Merge'} dalam ${s} dtk. Masih bisa dibatalkan.`;
}
async function act(a, action, note) {
state.busy = true;
state.error = null;
draw();
try {
const r = await fetch(`/api/ajuan/${a.id}/action`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ action, sha: a.reviewedSha, note }),
});
const body = await r.json().catch(() => ({}));
if (!r.ok) state.error = body.error || `Gagal (${r.status}).`;
else state.composing = null;
} catch {
state.error = 'Board nggak bisa dihubungi. Coba lagi.';
}
state.busy = false;
await load();
}
function actionLabel(a, k) {
if (k === 'undo' && a.status === 'gas') return 'Batalkan gas';
if (k === 'undo' && a.closeAt) return 'Batal tutup';
if (k === 'undo' && a.status === 'rejected') return 'Batalkan tolak';
if (k === 'gas' && a.dry) return 'Gas (uji coba)';
if (k === 'close' && a.dry) return 'Tutup MR (uji coba)';
return ACTION_LABEL[k];
}
function actionButton(a, k) {
return el('button', {
type: 'button',
class: `act ${k === 'gas' ? 'primary' : k === 'tolak' || k === 'close' ? 'danger' : 'quiet'}`,
disabled: state.busy,
onclick: () => (k === 'tunda' || k === 'tolak' ? (state.composing = { id: a.id, action: k, note: '' }, draw()) : act(a, k)),
}, actionLabel(a, k));
}
function actions(a) {
const box = el('div', { class: 'actions' });
if (a.gasAt || a.closeAt) box.append(el('p', { class: 'countdown', role: 'status', 'data-id': a.id }, countdownText(a)));
const compose = state.composing && state.composing.id === a.id ? state.composing : null;
if (compose) {
const input = el('textarea', { id: 'decision-note', rows: '2', maxlength: '200', placeholder: compose.action === 'tolak' ? 'Alasan ditolak (opsional), terlihat di MR' : 'Kenapa ditunda (opsional), terlihat di MR' });
input.value = compose.note || '';
input.addEventListener('input', () => { compose.note = input.value; });
box.append(
el('label', { class: 'note-label', for: 'decision-note' }, compose.action === 'tolak' ? 'Tolak ajuan ini' : 'Tunda ajuan ini'),
input,
el('div', { class: 'buttons main' },
el('button', { type: 'button', class: `act ${compose.action === 'tolak' ? 'danger' : 'quiet'}`, disabled: state.busy, onclick: () => act(a, compose.action, compose.note) }, compose.action === 'tolak' ? 'Tolak' : 'Tunda'),
el('button', { type: 'button', class: 'act quiet', onclick: () => { state.composing = null; draw(); } }, 'Batal'),
),
);
} else {
// Gas / undo / close first and full-width on a phone; Tunda and Tolak sit apart so a thumb misses Gas less often.
const main = a.actions.filter((k) => k === 'gas' || k === 'undo' || k === 'close');
const side = a.actions.filter((k) => k === 'tunda' || k === 'tolak');
if (main.length) box.append(el('div', { class: 'buttons main' }, main.map((k) => actionButton(a, k))));
if (side.length) box.append(el('div', { class: 'buttons side' }, side.map((k) => actionButton(a, k))));
}
if (state.error) box.append(el('p', { class: 'act-error', role: 'alert' }, state.error));
return box;
}
// ---- Releases (branches that deploy from tags) ----
function releaseCountdown(r, dry) {
const s = Math.max(0, Math.ceil((r.at - Date.now()) / 1000));
if (s === 0) return dry ? `Labuh lagi cek ${r.tag} (uji coba)…` : `Labuh lagi bikin tag ${r.tag}…`;
return `${dry ? `Uji coba ${r.tag}` : `Tag ${r.tag} dibuat`} dalam ${s} dtk. Masih bisa dibatalkan.`;
}
async function releaseAct(r, action, tag) {
// The shore is not redrawn while the tag field has focus; let go of it so the outcome shows.
if (document.activeElement && document.activeElement.id === 'release-tag') document.activeElement.blur();
state.busy = true;
state.error = null;
draw();
try {
const res = await fetch(`/api/release/${r.id}/action`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ action, tag }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) state.error = body.error || `Gagal (${res.status}).`;
else state.releaseTag = null;
} catch {
state.error = 'Board nggak bisa dihubungi. Coba lagi.';
}
state.busy = false;
await load();
const input = $('release-tag');
if (state.error && input) input.focus();
}
function releaseBox(a) {
const r = a.release;
const box = el('div', { class: 'release' }, el('p', { class: 'section-title' }, `Rilis ${r.branch}`));
if (r.actions.includes('release')) {
const typed = state.releaseTag && state.releaseTag.id === r.id ? state.releaseTag.value : r.proposedTag;
const input = el('input', { id: 'release-tag', type: 'text', inputmode: 'text', autocomplete: 'off', spellcheck: 'false', maxlength: '40', 'aria-describedby': 'release-hint' });
input.value = typed;
input.addEventListener('input', () => { state.releaseTag = { id: r.id, value: input.value }; });
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') releaseAct(r, 'release', input.value); });
box.append(
el('label', { class: 'note-label', for: 'release-tag' }, 'Nomor tag'),
el('div', { class: 'release-row' },
input,
el('button', { type: 'button', class: `act primary`, disabled: state.busy, onclick: () => releaseAct(r, 'release', input.value) }, a.dry ? 'Rilis (uji coba)' : 'Rilis'),
),
el('p', { class: 'hint', id: 'release-hint' }, `Usulan Labuh ${r.proposedTag}${r.fromTag ? `, setelah ${r.fromTag}` : ''}. Ganti kalau rilisnya bukan patch.`),
);
} else if (r.state === 'queued') {
box.append(el('p', { class: 'countdown', role: 'status', 'data-release': r.id }, releaseCountdown(r, a.dry)));
if (r.actions.includes('undo')) box.append(el('div', { class: 'buttons' }, el('button', { type: 'button', class: 'act quiet', disabled: state.busy, onclick: () => releaseAct(r, 'undo') }, 'Batalkan rilis')));
} else if (r.state === 'proposed') {
box.append(el('p', { class: 'note' }, `Labuh usul ${r.proposedTag}. Nunggu approver.`));
}
if (r.state === 'proposed' && r.result) box.append(el('p', { class: r.result.startsWith('uji coba') ? 'note' : 'act-error' }, r.result.replace(/^(ditolak|gagal): /, 'Rilis terakhir tidak jalan: ')));
if (state.error && r.actions.length) box.append(el('p', { class: 'act-error', role: 'alert' }, state.error));
const items = [
...r.changes.mrs.map((m) => el('li', {}, el('strong', {}, `!${m.iid}`), ` ${m.title}`, m.author ? el('span', { class: 'by' }, ` @${m.author}`) : null)),
...r.changes.commits.map((c) => el('li', { class: 'direct' }, el('strong', {}, c.sha.slice(0, 8)), ` ${c.title}`, el('span', { class: 'by' }, ' langsung, tanpa MR'))),
];
box.append(
el('p', { class: 'note-label' }, 'Changelog, jadi deskripsi tag'),
items.length ? el('ul', { class: 'changelog' }, items) : el('p', { class: 'note' }, 'Tidak ada perubahan sejak tag sebelumnya.'),
el('p', { class: 'stamp' }, `Tag di commit ${r.sha.slice(0, 8)}, ujung ${r.branch}`),
);
return box;
}
function detail(a) {
const m = META[a.status];
const card = el('div', { class: 'card' });
card.append(
el('div', { class: 'card-head' },
el('div', {},
el('h2', {}, a.label),
el('p', { class: 'title' }, a.title),
el('div', { class: 'meta' },
a.author && el('span', { class: 'who' }, el('span', { class: 'initial', 'aria-hidden': 'true', style: { background: colorOf(a.author) } }, a.author.charAt(0).toUpperCase()), a.author),
el('span', { class: 'env' }, a.lane.toLowerCase()),
el('span', { class: 'age' }, age(a.since)),
),
),
el('button', { type: 'button', class: 'close', 'aria-label': 'Tutup', onclick: () => pick(null), html: '<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>' }),
),
el('div', { class: 'tone', style: { background: m.bg, color: m.ink } },
el('span', { class: 'icon', 'aria-hidden': 'true', style: { background: m.ink }, html: ICON[m.icon] }),
el('div', {}, el('span', { class: 'word' }, m.word), el('span', { class: 'reason' }, a.reason)),
),
);
// Decide first (Gas under the thumb), then findings and history below the fold.
if (a.actions.length || a.gasAt || a.closeAt) card.append(actions(a));
const more = el('div', { class: 'more' });
if (a.release) more.append(releaseBox(a));
if (a.deployUrl) more.append(el('p', { class: 'note' }, el('a', { href: a.deployUrl, target: '_blank', rel: 'noopener' }, 'Pipeline deploy')));
if (a.findings.length)
more.append(el('ul', { class: 'findings' }, a.findings.map((f) => el('li', {}, el('span', { class: `k ${f.kind}`, 'aria-hidden': 'true', html: KIND[f.kind] }), el('span', {}, f.text, evidenceLinks(f.evidence))))));
if (a.postDeploy.length) {
more.append(el('p', { class: 'section-title' }, 'Habis deploy'));
more.append(el('ul', { class: 'findings' }, a.postDeploy.map((p) => el('li', {}, el('span', { class: 'k todo', 'aria-hidden': 'true', html: KIND.todo }), el('span', {}, p.text, evidenceLinks(p.evidence))))));
}
for (const o of a.overrides) more.append(el('p', { class: 'note' }, `Aturan Labuh: ${o}`));
if (a.reviewedSha) more.append(el('p', { class: 'stamp' }, `${state.data.reviewer} · commit ${a.reviewedSha.slice(0, 8)} · ${a.tokens.toLocaleString('id-ID')} token`));
const history = el('ol', {}, a.timeline.map((t) => el('li', {}, el('span', {}, clock(t.at)), el('span', {}, t.text))));
more.append(
el('div', { class: 'foot' },
el('details', {}, el('summary', {}, 'Riwayat'), history),
el('a', { class: 'open', href: a.webUrl, target: '_blank', rel: 'noopener', html: 'Buka MR <svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M6 3h7v7M13 3L5 11" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>' }),
),
);
if (more.childElementCount) card.append(more);
return card;
}
function needsYouCard() {
const list = state.data.ajuan.filter((a) => a.needsYou);
const card = el('div', { class: 'card' });
const head = el('div', { class: 'card-head' }, el('h2', {}, 'Perlu kamu'));
if (phone.matches)
head.append(el('button', { type: 'button', class: 'close', 'aria-label': 'Tutup', onclick: () => closeSheet(), html: '<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>' }));
card.append(head);
if (!list.length) card.append(el('p', { class: 'note' }, state.data.viewer.approver ? 'Belum ada. Santai dulu.' : 'Nggak ada ajuanmu yang ditahan.'));
else
card.append(el('div', { class: 'todo-list' }, list.map((a) =>
el('button', { type: 'button', class: 'todo-item', onclick: () => pick(a.id) },
el('span', { class: 'dot', 'aria-hidden': 'true' }, el('i'), el('i')),
el('span', { class: 'todo-copy' },
el('strong', {}, a.label),
a.title ? el('span', {}, shortTitle(a.title, 42)) : null,
),
el('span', { class: 'age' }, age(a.since)),
))));
return card;
}
function sheetMode(a) {
if (!phone.matches) return '';
if (a) return 'detail';
if (state.listOpen) return 'list';
return 'closed';
}
function drawShore() {
const { data } = state;
const a = data.ajuan.find((x) => x.id === state.sel);
if (state.sel && !a) state.sel = null;
// Keep a half-written Tunda or Tolak note across refreshes.
if (a && state.composing && state.composing.id === a.id && document.activeElement && document.activeElement.id === 'decision-note') return;
if (a && document.activeElement && document.activeElement.id === 'release-tag') return;
const mode = sheetMode(a);
const harbour = $('harbour');
harbour.dataset.sheet = mode || 'closed';
document.body.classList.toggle('sheet-open', mode === 'detail' || mode === 'list');
const scrim = $('scrim');
scrim.hidden = !(mode === 'detail' || mode === 'list');
let card = null;
if (a) card = detail(a);
else if (!phone.matches || state.listOpen) card = needsYouCard();
const key = a ? `a${a.id}` : state.listOpen || !phone.matches ? 'todo' : 'closed';
if (card) {
if (key === state.shown) card.classList.add('still');
$('detail').replaceChildren(card);
} else {
$('detail').replaceChildren();
}
state.shown = key;
const mine = data.ajuan.filter((x) => x.needsYou).length;
const mineCount = $('mine-count');
if (mineCount) mineCount.textContent = mine;
$('show-all').setAttribute('aria-pressed', String(state.filter === 'all'));
$('show-mine').setAttribute('aria-pressed', String(state.filter === 'mine'));
const v = data.viewer;
const initial = (v.name || v.username).charAt(0).toUpperCase();
for (const av of document.querySelectorAll('[data-avatar]')) {
av.textContent = initial;
av.title = `Keluar (@${v.username})`;
av.setAttribute('aria-label', `Keluar dari akun @${v.username}`);
}
}
function drawHeadline() {
const { data } = state;
const first = (data.viewer.name || data.viewer.username).split(' ')[0];
const empty = $('empty');
if (!data.ajuan.length) {
$('headline').textContent = 'Pelabuhan sepi.';
empty.hidden = false;
empty.textContent = `Belum ada ajuan. Pasang label labuh di MR supaya ${data.reviewer} mulai review.`;
return;
}
empty.hidden = true;
const n = data.ajuan.filter((a) => a.needsYou).length;
if (data.viewer.approver) {
const ready = data.ajuan.filter((a) => a.needsYou && a.status === 'ready').length;
const failed = data.ajuan.filter((a) => a.needsYou && a.status === 'failed').length;
const releases = new Set(data.ajuan.filter((a) => a.needsYou && a.release && a.release.state === 'proposed').map((a) => a.release.id)).size;
const parts = [ready && `${ready} kapal nunggu gas`, releases && `${releases} rilis nunggu persetujuan`, failed && `${failed} deploy gagal`].filter(Boolean);
$('headline').textContent = parts.length ? `${parts.join(', ')}.` : `Semua beres, ${first}.`;
}
else $('headline').textContent = n ? `${n} ajuanmu ditahan.` : 'Antrean aman.';
}
function draw() {
if (!state.data) return;
drawHeadline();
drawLanes();
drawShore();
for (const a of state.data.ajuan) state.seen.add(a.id);
state.first = false;
}
function closeSheet() {
// Closing the "Perlu kamu" list exits the filter so boats are not left dimmed.
if (state.listOpen) state.filter = 'all';
state.listOpen = false;
if (state.sel) pick(null);
else draw();
}
function pick(id) {
if (id !== state.sel) {
state.composing = null;
state.error = null;
state.releaseTag = null;
}
state.sel = id;
if (id) state.listOpen = false;
history.replaceState(null, '', id ? `#a${id}` : location.pathname);
draw();
// A new ajuan opens at its top: the sheet scrolls on a phone, the detail column on a laptop.
if (id) $('detail').scrollTop = 0;
}
async function load() {
try {
const r = await fetch('/api/board', { headers: { Accept: 'application/json' }, cache: 'no-store' });
if (r.status === 401) return location.reload();
if (!r.ok) throw new Error(String(r.status));
state.data = await r.json();
state.failedAt = null;
$('stale').hidden = true;
draw();
} catch {
if (!state.data) $('headline').textContent = 'Antrean belum bisa dibaca.';
state.failedAt = state.failedAt || new Date();
const s = $('stale');
s.hidden = false;
s.textContent = `Gagal memuat ulang sejak ${clock(state.failedAt.toISOString())}. Mencoba lagi…`;
}
}
document.addEventListener('DOMContentLoaded', () => {
drawSea();
const m = location.hash.match(/^#a(\d+)$/);
if (m) state.sel = Number(m[1]);
$('show-all').addEventListener('click', () => {
state.filter = 'all';
state.listOpen = false;
draw();
});
$('show-mine').addEventListener('click', () => {
state.filter = 'mine';
// On a phone the list is a sheet; on a laptop it lives in the shore panel.
if (phone.matches) {
state.sel = null;
state.listOpen = true;
history.replaceState(null, '', location.pathname);
}
draw();
});
$('scrim').addEventListener('click', () => closeSheet());
document.addEventListener('keydown', (e) => {
if (e.key !== 'Escape') return;
if (state.sel) pick(null);
else if (state.listOpen) closeSheet();
});
load();
// Faster while a Gas waits or a boat is sailing, so the harbour follows it.
let last = 0;
setInterval(() => {
if (document.hidden || !state.data) return;
const busy = state.data.ajuan.some((a) => a.status === 'gas' || a.status === 'sailing' || a.closeAt);
if (Date.now() - last >= (busy ? BUSY_REFRESH_MS : REFRESH_MS)) {
last = Date.now();
load();
}
for (const p of document.querySelectorAll('.countdown')) {
const a = state.data.ajuan.find((x) => String(x.id) === p.dataset.id);
if (a && (a.gasAt || a.closeAt)) p.textContent = countdownText(a);
}
for (const p of document.querySelectorAll('[data-release]')) {
const a = state.data.ajuan.find((x) => x.release && String(x.release.id) === p.dataset.release);
if (a && a.release.at) p.textContent = releaseCountdown(a.release, a.dry);
}
}, 1000);
document.addEventListener('visibilitychange', () => { if (!document.hidden) load(); });
const onViewport = () => {
drawnLanes = '';
if (state.data) {
if (!phone.matches) {
state.listOpen = false;
state.lane = null;
}
draw();
}
};
window.addEventListener('resize', onViewport);
phone.addEventListener('change', onViewport);
});
})();