Files
labuh/board/board.js
Adnan Zahir 112923640d 0.1.0: first release — review, harbour, Gas, deploys and releases
- Pandu reviews every MR labelled `labuh` through Codex app-server and answers
  in a fixed shape; the Hub checks each piece of evidence, applies hard rules
  the model cannot override, retries once, and posts the comments itself.
- The board shows the harbour: lanes per environment, Dicek / Siap gas /
  Beres, two fixed berth rows, boats that glide; GitLab sign-in, approvers
  from board.json, works on a phone.
- Gas, Tunda, Tolak and Tutup MR with 15 seconds to undo; the Hub checks
  GitLab again and merges the reviewed commit only, then follows the deploy.
- Branches that deploy from tags get a proposed version and changelog; the
  approver confirms the number and the Hub creates the annotated tag.
- Telegram notifications, reminders, dry mode for rehearsals.
- Hosting: one image, three containers. The reviewer runs in its own container
  with no GitLab token and read-only checkouts, reached by the Hub over a
  token-guarded WebSocket; every command it asks for still passes the Hub's
  allowlist. Configuration and state live in LABUH_HOME.
- AGPL-3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 19:39:58 +07:00

647 lines
38 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 Pandu', word: 'Tahan', bg: '#F8DDD5', ink: '#9A2E1A', icon: 'stop' },
blocked: { zone: 'cek', flag: '#9AA5A8', aria: 'nunggu MR lain', word: 'Nunggu', bg: '#EEF1F0', ink: '#3E4E53', icon: 'link' },
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>',
link: '<svg width="26" height="26" viewBox="0 0 16 16"><path d="M7 9.5l2-2M5.5 11.5l-1 1a2.1 2.1 0 0 1-3-3l2-2a2.1 2.1 0 0 1 3 0M10.5 4.5l1-1a2.1 2.1 0 0 1 3 3l-2 2a2.1 2.1 0 0 1-3 0" fill="none" stroke="#FFFFFF" stroke-width="1.8" 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, filter: 'all', seen: new Set(), first: true, failedAt: null, shown: null, composing: null, busy: false, error: null, releaseTag: null };
const $ = (id) => document.getElementById(id);
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.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 b = el('button', { type: 'button', class: cls, 'data-id': a.id, 'aria-label': `${a.label}, ${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));
const marks = el('span', { class: 'marks', 'aria-hidden': 'true' });
if (a.status === 'checking' || a.status === 'sailing' || a.status === 'gas') marks.innerHTML = ICON.dots;
if (a.status === 'blocked') marks.innerHTML = '<svg width="16" height="16" viewBox="0 0 16 16"><path d="M7 9.5l2-2M5.5 11.5l-1 1a2.1 2.1 0 0 1-3-3l2-2a2.1 2.1 0 0 1 3 0M10.5 4.5l1-1a2.1 2.1 0 0 1 3 3l-2 2a2.1 2.1 0 0 1-3 0" fill="none" stroke="#3E4E53" stroke-width="1.8" 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 zone = b.closest('.zone');
zone.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 = () => { zone.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;
const phone = window.matchMedia('(max-width: 899px)');
// 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;
// Places the boats already in `rows` (one grid per lane) and sizes the columns.
function layoutColumns() {
const rows = [...$('lanes').querySelectorAll('.zones')];
if (!rows.length) return;
if (phone.matches) {
for (const r of rows) r.style.gridTemplateColumns = '';
for (const b of $('lanes').querySelectorAll('.boats')) b.style.gridTemplateColumns = '';
state.cols = null;
return;
}
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();
}
}
let drawnLanes = '';
function drawLanes() {
const { data } = state;
const used = new Set(data.ajuan.map((a) => a.lane));
const lanes = data.lanes.filter((l, i) => used.has(l) || (l !== 'Lainnya' && i < 2));
const main = $('lanes');
// A refresh that changes nothing on the water leaves the boats alone, so none restarts mid-glide.
const key = JSON.stringify([lanes, state.sel, state.filter, data.ajuan.map((a) => [a.id, a.lane, a.status, a.label, a.needsYou, state.seen.has(a.id)])]);
if (key === drawnLanes && main.childElementCount) 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();
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) {
let items = data.ajuan.filter((a) => a.lane === name && 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));
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.
if (!phone.matches) {
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();
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 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' },
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 {
box.append(el('div', { class: 'buttons' }, a.actions.map((k) =>
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)),
}, k === 'undo' && a.status === 'gas' ? 'Batalkan gas' : k === 'undo' && a.closeAt ? 'Batal tutup' : k === 'undo' && a.status === 'rejected' ? 'Batalkan tolak' : k === 'gas' && a.dry ? 'Gas (uji coba)' : k === 'close' && a.dry ? 'Tutup MR (uji coba)' : ACTION_LABEL[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)),
),
);
if (a.actions.length || a.gasAt || a.closeAt) card.append(actions(a));
if (a.release) card.append(releaseBox(a));
if (a.deployUrl) card.append(el('p', { class: 'note' }, el('a', { href: a.deployUrl, target: '_blank', rel: 'noopener' }, 'Pipeline deploy')));
if (a.findings.length)
card.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) {
card.append(el('p', { class: 'section-title' }, 'Habis deploy'));
card.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) card.append(el('p', { class: 'note' }, `Aturan Labuh: ${o}`));
if (a.reviewedSha) card.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))));
card.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>' }),
),
);
return card;
}
function needsYouCard() {
const list = state.data.ajuan.filter((a) => a.needsYou);
const card = el('div', { class: 'card' }, el('h2', {}, 'Perlu kamu'));
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('strong', {}, a.label),
el('span', { class: 'age' }, age(a.since)),
))));
return card;
}
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 card = a ? detail(a) : needsYouCard();
// Animate only when what the shore shows changes, not on every refresh.
const key = a ? `a${a.id}` : 'todo';
if (key === state.shown) card.classList.add('still');
state.shown = key;
$('detail').replaceChildren(card);
const mine = data.ajuan.filter((x) => x.needsYou).length;
$('mine-count').textContent = mine;
$('show-all').setAttribute('aria-pressed', String(state.filter === 'all'));
$('show-mine').setAttribute('aria-pressed', String(state.filter === 'mine'));
const v = data.viewer;
$('avatar').textContent = (v.name || v.username).charAt(0).toUpperCase();
$('avatar').title = `Keluar (@${v.username})`;
$('avatar').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 pick(id) {
if (id !== state.sel) {
state.composing = null;
state.error = null;
state.releaseTag = null;
}
state.sel = id;
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) (window.matchMedia('(max-width: 899px)').matches ? $('shore') : $('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'; draw(); });
$('show-mine').addEventListener('click', () => { state.filter = 'mine'; draw(); });
document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && state.sel) pick(null); });
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(); });
window.addEventListener('resize', () => { drawnLanes = ''; if (state.data) drawLanes(); });
});
})();