Files
PIKKIE/server/public/app.js
T
Codex 031eda1453 PIKKIE 1.4.3: official announcements
Resolve PK-24 with admin announcements on the web and Android boards, linked releases and bullets, MCP tools, and opt-in notifications.
2026-11-12 23:10:04 +01:00

1988 lines
134 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* PIKKIE web client — no framework, no innerHTML with user data. */
const $app = document.getElementById('app');
const REPO_URL = 'https://git.autisme.monster/juli/PIKKIE';
const state = { me: null, status: null, paste: null };
/* ---------------- helpers ---------------- */
function h(tag, props, ...kids) {
const el = document.createElement(tag);
for (const [k, v] of Object.entries(props || {})) {
if (v === undefined || v === null || v === false) continue;
if (k === 'class') el.className = v;
else if (k.startsWith('on')) el.addEventListener(k.slice(2).toLowerCase(), v);
else if (k === 'value') el.value = v;
else if (k === 'checked') el.checked = !!v;
else el.setAttribute(k, v === true ? '' : v);
}
for (const kid of kids.flat(Infinity)) {
if (kid === null || kid === undefined || kid === false) continue;
el.append(kid instanceof Node ? kid : document.createTextNode(String(kid)));
}
return el;
}
const STATUS = {
open: 'Open',
needs_info: 'Needs info',
in_progress: 'In progress',
fixed: 'Fixed',
finished: 'Finished',
declined: 'Declined',
};
/* avatars, user links, linkified text, link-preview cards */
const AV_COLORS = ['#ff2e93', '#3ddc97', '#6cb6ff', '#ffc94a', '#ff8a3d', '#b388ff'];
function avatar(u, size = 24) {
const st = `width:${size}px;height:${size}px`;
if (u?.avatar) return h('img', { class: 'av', src: u.avatar, alt: '', style: st, loading: 'lazy' });
const c = AV_COLORS[(u?.id || 0) % AV_COLORS.length];
return h('span', { class: 'av av-none', style: `${st};font-size:${Math.round(size * 0.5)}px;background:${c}` }, (u?.name || '?').trim().slice(0, 1).toUpperCase());
}
const userLink = (u, size = 20) => (u ? h('a', { class: 'ulink', href: `#/u/${u.id}`, onclick: (e) => e.stopPropagation() }, avatar(u, size), h('span', {}, u.name)) : null);
function linkify(text) {
const out = [];
let last = 0;
for (const m of String(text || '').matchAll(/\bhttps?:\/\/[^\s<>"'()]+[^\s<>"'().,;:!?]/gi)) {
if (m.index > last) out.push(text.slice(last, m.index));
out.push(h('a', { href: m[0], target: '_blank', rel: 'noopener noreferrer nofollow', onclick: (e) => e.stopPropagation() }, m[0].length > 60 ? m[0].slice(0, 57) + '…' : m[0]));
last = m.index + m[0].length;
}
out.push(text.slice(last));
return out;
}
const hostOf = (u) => { try { return new URL(u).hostname; } catch { return ''; } };
const previewCard = (p) => h('a', { class: `lp lp-${p.kind}`, href: p.url, target: '_blank', rel: 'noopener noreferrer nofollow', onclick: (e) => e.stopPropagation() },
p.image && h('div', { class: 'lp-img' }, h('img', { src: p.image, alt: '', loading: 'lazy' }), p.kind === 'video' && h('span', { class: 'lp-play' }, '▶')),
h('div', { class: 'lp-txt' }, h('small', {}, p.site || hostOf(p.url)), h('b', {}, p.title || p.url), p.description && h('span', {}, p.description)));
const previews = (list) => (list?.length ? h('div', { class: 'lps' }, list.map(previewCard)) : null);
function gallery(atts, { hero = false } = {}) {
const imgs = (atts || []).filter((a) => a.inline);
if (!imgs.length) return null;
return h('div', { class: `gallery ${hero ? 'hero' : ''} n${Math.min(imgs.length, 5)}` }, imgs.map((a, i) =>
h('a', { href: a.url, onclick: (e) => { e.preventDefault(); e.stopPropagation(); lightbox(imgs.map((x) => x.url), i); } }, h('img', { src: a.url, alt: a.filename, loading: 'lazy' }))));
}
/* full-screen image viewer: ← → / swipe-free buttons, Esc or click outside to close */
function lightbox(urls, start = 0) {
let i = start;
const img = h('img', { alt: '' });
const count = h('span', { class: 'lb-count' });
const show = () => { img.src = urls[i]; count.textContent = urls.length > 1 ? `${i + 1} / ${urls.length}` : ''; };
const step = (d) => { i = (i + d + urls.length) % urls.length; show(); };
const close = () => { overlay.remove(); document.removeEventListener('keydown', key); };
const key = (e) => { if (e.key === 'Escape') close(); if (e.key === 'ArrowRight') step(1); if (e.key === 'ArrowLeft') step(-1); };
const overlay = h('div', { class: 'lightbox', onclick: (e) => { if (e.target === overlay) close(); } },
img, count,
urls.length > 1 && h('button', { class: 'lb-nav lb-prev', onclick: () => step(-1), 'aria-label': 'previous' }, '‹'),
urls.length > 1 && h('button', { class: 'lb-nav lb-next', onclick: () => step(1), 'aria-label': 'next' }, '›'),
h('a', { class: 'lb-open', href: urls[i], target: '_blank', rel: 'noopener', onclick: (e) => { e.currentTarget.href = urls[i]; } }, 'open original ↗'),
h('button', { class: 'lb-close', onclick: close, 'aria-label': 'close' }, '✕'));
document.addEventListener('keydown', key);
document.body.append(overlay);
show();
}
const statusTag = (s) => h('span', { class: `st st-${s}` }, STATUS[s] || s);
const viaTag = (via, label) => (via && via !== 'web' ? h('span', { class: `via ${via}`, title: label ? `${via} · ${label}` : via }, via === 'mcp' ? `🤖 via MCP${label ? ' · ' + label : ''}` : via) : null);
const WEIGHTS = [
{ value: 1, caliber: '.22', name: 'Nitpick', color: '#a1a1aa' },
{ value: 2, caliber: '9mm', name: 'Minor', color: '#f4f4f5' },
{ value: 3, caliber: '.45 ACP', name: 'Annoying', color: '#ffc94a' },
{ value: 4, caliber: '7.62', name: 'Major', color: '#ff8a3d' },
{ value: 5, caliber: '12 GAUGE', name: 'Blocker', color: '#c93438' },
];
const W = (v) => WEIGHTS[(v || 1) - 1] || WEIGHTS[0];
const reportVersion = (v) => /^\d/.test(v.trim()) ? `v${v.trim()}` : v.trim();
const weightTag = (v) => { const w = W(v); return h('span', { class: `cal cal-${w.value}`, style: `--wc:${w.color}`, title: `${w.caliber} · ${w.name}` }, w.caliber); };
const WEIGHT_TAGS = [[/^(\.?22|22lr|nit(pick)?|!1)$/i, 1], [/^(9mm|9|minor|!2)$/i, 2], [/^(\.?45|45acp|\.45acp|annoying|!3)$/i, 3], [/^(7\.?62|762|major|!4)$/i, 4], [/^(12\s*(g|ga|gauge)?|shotgun|blocker|!5)$/i, 5]];
function extractWeight(line) {
const m = /^(?:\[([^\]]{1,12})\]|(![1-5]))\s*/.exec(line);
if (m) { const t = (m[1] ?? m[2]).trim(); for (const [re, v] of WEIGHT_TAGS) if (re.test(t)) return { text: line.slice(m[0].length).trim() || line, weight: v }; }
return { text: line, weight: null };
}
function weightPicker(selected, onPick) {
const btns = WEIGHTS.map((w) => h('button', { type: 'button', class: `calpick ${w.value === selected ? 'sel' : ''}`, style: `--wc:${w.color}`, title: w.name, onclick: () => { btns.forEach((b, i) => b.classList.toggle('sel', i === w.value - 1)); onPick(w.value); } },
h('span', { class: `cal cal-${w.value}`, style: `--wc:${w.color}` }, w.caliber), h('small', {}, w.name)));
return h('div', { class: 'calpicker' }, btns);
}
const projTag = (p) => (p ? h('span', { class: 'proj', style: `--pc:${/^#[0-9a-f]{6}$/i.test(p.color || '') ? p.color : '#ff2e93'}` }, p.name) : null);
async function loadProjects() {
const r = await api('/projects');
state.projects = r.projects;
state.currentProject = r.current_id;
return r;
}
function projectSelect(selected, { allowAll = false, onchange } = {}) {
const sel = h('select', { onchange: () => onchange && onchange(sel.value) },
allowAll && h('option', { value: '' }, 'All projects'),
(state.projects || []).map((p) => h('option', { value: p.id, selected: String(p.id) === String(selected) }, `${p.name}${p.open_count ? ` (${p.open_count} open)` : ''}`)));
return sel;
}
const ago = (t) => {
const s = (Date.now() - t) / 1000;
if (s < 60) return 'just now';
if (s < 3600) return `${Math.floor(s / 60)}m ago`;
if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
if (s < 86400 * 30) return `${Math.floor(s / 86400)}d ago`;
return new Date(t).toLocaleDateString();
};
const size = (n) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`);
const isAdmin = () => state.me?.role === 'admin';
let toastTimer;
function toast(msg, bad = false) {
const t = document.getElementById('toast');
t.textContent = msg;
t.className = 'show' + (bad ? ' bad' : '');
clearTimeout(toastTimer);
toastTimer = setTimeout(() => (t.className = ''), 3200);
}
function copyButton(value, label = 'Copy', description = label) {
return h('button', { type: 'button', class: 'small ghost', title: description, 'aria-label': description, onclick: async (e) => {
e.stopPropagation();
try {
await navigator.clipboard.writeText(typeof value === 'function' ? value() : value);
toast('Copied');
} catch { toast('Could not copy to clipboard', true); }
} }, `📋 ${label}`);
}
async function api(path, { method = 'GET', body, form } = {}) {
const opts = { method, headers: {} };
if (form) opts.body = form;
else if (body !== undefined) {
opts.headers['content-type'] = 'application/json';
opts.body = JSON.stringify(body);
}
const res = await fetch('/api' + path, opts);
let data = null;
try { data = await res.json(); } catch { /* empty */ }
if (!res.ok) {
if (res.status === 401 && data?.error === 'not_authenticated') {
const wasIn = !!state.me;
resetState();
if (wasIn) route(); // session ended (expired, password changed elsewhere, 2FA switched on…)
} else if (res.status === 403 && data?.error === '2fa_setup_required') {
state.me && (state.me.needs_2fa_setup = true);
location.hash = '#/profile';
}
throw new Error(data?.error || `HTTP ${res.status}`);
}
return data;
}
const busy = async (btn, fn) => {
btn.disabled = true;
try { await fn(); } catch (e) { toast(e.message, true); } finally { btn.disabled = false; }
};
/* ---------------- file collector (drag, pick, paste) ---------------- */
function fileCollector(hint = 'Drop files, click to pick, or paste a screenshot or log text here', allowText = true) {
const files = [];
const chips = h('div', { class: 'chips' });
const input = h('input', { type: 'file', multiple: true, hidden: true, onchange: () => { add([...input.files]); input.value = ''; } });
// phones: open the camera directly / pick from the gallery
const cam = h('input', { type: 'file', accept: 'image/*,video/*', capture: 'environment', hidden: true, onchange: () => { add([...cam.files]); cam.value = ''; } });
const gallery = h('input', { type: 'file', accept: 'image/*,video/*', multiple: true, hidden: true, onchange: () => { add([...gallery.files]); gallery.value = ''; } });
const touch = matchMedia('(pointer: coarse)').matches;
const phoneBtns = touch && h('div', { class: 'row', style: 'margin-top:8px' },
h('button', { type: 'button', class: 'small', onclick: () => cam.click() }, '📷 Take photo'),
h('button', { type: 'button', class: 'small', onclick: () => gallery.click() }, '🖼 From gallery'));
const drop = h('div', { class: 'drop', tabindex: 0, role: 'button', onclick: () => input.click(), onkeydown: (e) => e.key === 'Enter' && input.click() }, '📎 ', hint);
drop.addEventListener('dragover', (e) => { e.preventDefault(); drop.classList.add('over'); });
drop.addEventListener('dragleave', () => drop.classList.remove('over'));
drop.addEventListener('drop', (e) => { e.preventDefault(); drop.classList.remove('over'); add([...e.dataTransfer.files]); });
if (allowText) drop.addEventListener('paste', (e) => {
if (e.clipboardData?.files.length) return; // the shared file-paste handler handles screenshots
const value = e.clipboardData?.getData('text/plain') || '';
if (!value) return;
e.preventDefault();
e.stopPropagation();
if (addText(value)) toast('Text attached as evidence 📎');
});
function add(list) {
for (let f of list) {
if (files.length >= 10) { toast('Max 10 files', true); break; }
if (f.size > 25 * 1024 * 1024) { toast(`${f.name} is over 25 MB`, true); continue; }
if (!f.name || f.name === 'image.png') f = new File([f], `pasted-${new Date().toISOString().replace(/[:.]/g, '-')}.${(f.type.split('/')[1] || 'bin').replace('jpeg', 'jpg')}`, { type: f.type });
files.push(f);
}
render();
}
function addText(value) {
if (!value.trim()) { toast('Paste some text first', true); return false; }
if (files.length >= 10) { toast('Max 10 files', true); return false; }
const file = new File([value], `pasted-log-${new Date().toISOString().replace(/[:.]/g, '-')}.txt`, { type: 'text/plain' });
if (file.size > 25 * 1024 * 1024) { toast('Text is over 25 MB; attach it as a file instead', true); return false; }
add([file]);
return true;
}
const thumbs = new Map();
const thumb = (f) => { if (!thumbs.has(f)) thumbs.set(f, URL.createObjectURL(f)); return thumbs.get(f); };
function render() {
for (const [f, u] of thumbs) if (!files.includes(f)) { URL.revokeObjectURL(u); thumbs.delete(f); }
chips.replaceChildren(
...files.map((f, i) =>
h('span', { class: 'chip' }, f.type.startsWith('image/') ? h('img', { src: thumb(f), alt: '' }) : '📄', `${f.name} (${size(f.size)})`,
h('button', { type: 'button', title: 'remove', onclick: () => { files.splice(i, 1); render(); } }, '×')),
),
);
}
const textDraft = allowText && h('textarea', { placeholder: 'Paste terminal output or log text here…', 'aria-label': 'Text evidence', style: 'min-height:100px;font-family:var(--mono)' });
const textBox = allowText && h('details', { class: 'text-evidence' },
h('summary', {}, '📋 Paste terminal or log text'),
textDraft,
h('div', { class: 'row' }, h('small', { class: 'muted' }, 'Review the text before attaching it.'), h('span', { class: 'spacer' }),
h('button', { type: 'button', class: 'small', onclick: () => { if (addText(textDraft.value)) { textDraft.value = ''; textBox.open = false; } } }, 'Attach text')));
const el = h('div', {}, input, cam, gallery, drop, phoneBtns, textBox, chips);
const self = { el, files, add, clear: () => { files.length = 0; render(); } };
state.paste = self;
(state.collectors ||= []).push(self);
return self;
}
document.addEventListener('paste', (e) => {
const fs = [...(e.clipboardData?.files || [])];
const live = (state.collectors || []).filter((c) => document.body.contains(c.el));
state.collectors = live;
const form = document.activeElement?.closest?.('form');
const target = live.find((c) => form && form.contains(c.el)) || live[0];
if (fs.length && target) {
e.preventDefault();
target.add(fs);
toast(`Pasted ${fs.length} file${fs.length > 1 ? 's' : ''} 📎`);
}
});
function fileList(atts) {
if (!atts?.length) return null;
const textFile = (a) => {
const preview = h('pre', { class: 'evidence-text', hidden: true });
let loaded = false;
const view = h('button', { type: 'button', class: 'small', onclick: async () => {
if (!loaded) {
view.disabled = true;
try {
const res = await fetch(a.url, { credentials: 'same-origin' });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
preview.textContent = await res.text();
loaded = true;
} catch (e) { toast(`Could not open ${a.filename}: ${e.message}`, true); return; }
finally { view.disabled = false; }
}
preview.hidden = !preview.hidden;
view.textContent = preview.hidden ? 'View text' : 'Hide text';
} }, 'View text');
return h('div', { class: 'text-file' }, h('div', { class: 'row' }, view,
h('a', { class: 'file', href: a.url + '?download=1' }, '📄', h('span', {}, a.filename), h('small', { class: 'muted' }, size(a.size)))), preview);
};
return h('div', { class: 'files' },
atts.map((a) =>
a.inline
? h('a', { class: 'thumb', href: a.url, target: '_blank', rel: 'noopener', title: a.filename }, h('img', { src: a.url, alt: a.filename, loading: 'lazy' }))
: a.mime === 'text/plain' && a.size <= 256_000 ? textFile(a)
: h('a', { class: 'file', href: a.url + '?download=1' }, '📄', h('span', {}, a.filename), h('small', { class: 'muted' }, size(a.size))),
));
}
/* ---------------- layout ---------------- */
function layout(active, ...content) {
const link = (href, label, key) => h('a', { href, class: active === key ? 'active' : '' }, label);
return h('div', {},
h('header', { class: 'top' },
h('a', { class: 'brand', href: '#/' }, h('img', { src: '/logo.svg', alt: '' }), h('div', {}, h('b', {}, 'PIKKIE', h('span', { class: 'dot' }, '.')), h('small', {}, 'picky issues keeper'))),
h('nav', { class: 'main' },
link('#/', 'Bullets', 'issues'),
link('#/new', '+ Report', 'new'),
link('#/code', 'Code', 'code'),
link('#/board', 'Board', 'board'),
link('#/download', 'Android', 'download'),
isAdmin() && link('#/admin', 'Admin', 'admin'),
),
h('div', { class: 'who' },
bell(),
h('a', { href: '#/profile', class: `ulink ${active === 'profile' ? 'active' : ''}` }, avatar(state.me, 26), h('span', {}, state.me.name)),
isAdmin() && h('span', { class: 'st st-finished' }, 'admin'),
h('button', { class: 'small ghost', onclick: logout }, 'Log out'),
),
),
h('main', {}, content),
h('div', { class: 'footer' }, h('b', {}, 'PIKKIE'), ' · picky issues keeper & knitpick ideas explorer · ', h('i', {}, 'stay pikkie 🤘'),
h('br'), h('a', { href: REPO_URL, target: '_blank', rel: 'noopener' }, '⌥ source on git.autisme.monster'), ' · MIT licensed'),
);
}
const mount = (node) => $app.replaceChildren(node);
/* 🔔 in-app inbox */
let bellTimer;
document.addEventListener('click', () => document.querySelectorAll('.bell-panel').forEach((p) => (p.hidden = true)));
function bell() {
const badge = h('span', { class: 'bell-badge', hidden: true });
const panel = h('div', { class: 'bell-panel', hidden: true });
const btn = h('button', { class: 'bell ghost', title: 'Notifications', onclick: async (e) => { e.stopPropagation(); panel.hidden ? await open() : (panel.hidden = true); } }, '🔔', badge);
const setUnread = (n) => { badge.hidden = !n; badge.textContent = n > 9 ? '9+' : String(n); };
async function refresh() { try { setUnread((await api('/notifications?limit=1')).unread); } catch { /* offline */ } }
async function open() {
const r = await api('/notifications?limit=25');
panel.replaceChildren(
h('div', { class: 'bell-head' }, h('b', {}, 'Notifications'), h('span', { class: 'spacer' }),
h('a', { href: '#/profile', onclick: () => (panel.hidden = true) }, 'settings'),
r.unread > 0 && h('button', { class: 'small ghost', onclick: async (ev) => { ev.stopPropagation(); await api('/notifications/read', { method: 'POST', body: { all: true } }); setUnread(0); open(); } }, 'mark all read')),
...(r.items.length ? r.items.map((n) => h('a', {
class: `bell-item ${n.read ? '' : 'unread'}`, href: n.link || '#/',
onclick: () => { panel.hidden = true; if (!n.read) api('/notifications/read', { method: 'POST', body: { ids: [n.id] } }).then(refresh); },
}, avatar(n.actor, 28), h('div', {}, h('b', {}, n.title), n.body && h('span', {}, n.body), h('small', {}, ago(n.created)))))
: [h('div', { class: 'empty small' }, 'Nothing yet. Opt in to phone or e-mail alerts under your profile.')]));
panel.hidden = false;
}
panel.addEventListener('click', (e) => e.stopPropagation());
refresh();
clearInterval(bellTimer);
bellTimer = setInterval(() => (document.body.contains(btn) ? refresh() : clearInterval(bellTimer)), 60_000);
return h('div', { class: 'bell-wrap' }, btn, panel);
}
/** forget everything the previous account loaded (drafts, "filed this session", projects, tour state…) */
function resetState() {
for (const k of Object.keys(state)) delete state[k];
Object.assign(state, { me: null, status: null, paste: null });
}
async function logout() {
await api('/logout', { method: 'POST' }).catch(() => {});
finishTour(false);
resetState();
location.hash = '#/';
route();
}
/* ---------------- auth screens ---------------- */
function authShell(...kids) {
return h('div', { class: 'auth' },
h('img', { class: 'logo-big', src: '/logo.svg', alt: 'PIKKIE logo: a tiny punk bug with a mohawk and a safety pin' }),
h('h1', {}, 'PIKKIE'),
h('p', { class: 'tag' }, 'picky issues keeper & knitpick ideas explorer'),
h('p', { class: 'joke' }, h('em', {}, 'stay pikkie 🤘')),
h('div', { class: 'card loud' }, kids),
h('p', { class: 'footer' }, h('a', { href: REPO_URL, target: '_blank', rel: 'noopener' }, 'source code'), ' · MIT'),
);
}
function viewAuth(mode = 'login') {
const st = state.status;
if (st.needs_setup) mode = 'setup';
const err = h('div', { class: 'err' });
const email = h('input', { type: 'email', autocomplete: 'username', required: true });
const pw = h('input', { type: 'password', autocomplete: mode === 'login' ? 'current-password' : 'new-password', required: true, minlength: mode === 'login' ? undefined : 10 });
const name = h('input', { type: 'text', autocomplete: 'nickname', maxlength: 60 });
const setupToken = h('input', { type: 'password', autocomplete: 'off', placeholder: 'from PIKKIE_SETUP_TOKEN' });
const btn = h('button', { class: 'primary', type: 'submit' }, mode === 'login' ? 'Let me in' : mode === 'setup' ? 'Create admin' : 'Sign me up');
const form = h('form', {
onsubmit: async (e) => {
e.preventDefault();
err.textContent = '';
btn.disabled = true;
try {
const body = { email: email.value, password: pw.value, name: name.value };
if (mode === 'setup' && st.setup_token_required) body.setup_token = setupToken.value;
const r = await api(mode === 'login' ? '/login' : mode === 'setup' ? '/setup' : '/signup', { method: 'POST', body });
if (r.need_2fa) return mount(view2faLogin(r.challenge));
state.me = r.user;
route();
} catch (ex) {
err.textContent = ex.message;
} finally {
btn.disabled = false;
}
},
},
h('h2', {}, mode === 'login' ? 'Log in' : mode === 'setup' ? 'First run: create the admin' : 'Join the beta'),
mode !== 'login' && [h('label', {}, 'Display name'), name],
h('label', {}, 'E-mail'), email,
h('label', {}, 'Password'), pw,
mode !== 'login' && h('div', { class: 'small muted' }, 'At least 10 characters.'),
mode === 'setup' && st.setup_token_required && [h('label', {}, 'Setup token'), setupToken],
err,
h('div', { class: 'row', style: 'margin-top:16px' }, btn, h('span', { class: 'spacer' }),
mode === 'login' && st.signup_enabled && h('a', { href: '#', onclick: (e) => { e.preventDefault(); mount(viewAuth('signup')); } }, 'No account? Sign up'),
mode === 'signup' && h('a', { href: '#', onclick: (e) => { e.preventDefault(); mount(viewAuth('login')); } }, 'Have an account? Log in'),
),
mode === 'login' && !st.signup_enabled && h('p', { class: 'small muted' }, 'Invite only. Ask an admin for an account.'),
);
if (mode === 'login') {
const qrBox = h('div', { class: 'applogin' },
h('button', { type: 'button', class: 'applogin-btn', onclick: () => appLogin(qrBox) },
h('img', { src: '/phone-cracked.svg', alt: '', class: 'cracked-phone small' }),
h('span', {}, h('b', {}, 'Log in with the PIKKIE app'), h('br'), h('small', {}, 'Scan a QR with your phone, no password'))));
setTimeout(() => email.focus());
return authShell(form, qrBox);
}
setTimeout(() => (mode === 'login' ? email : name).focus());
return authShell(form);
}
async function viewInvite(token) {
let inv;
try {
inv = await api('/invite/lookup', { method: 'POST', body: { token } });
} catch (e) {
return authShell(h('h2', {}, 'Invite not valid'), h('p', { class: 'err' }, e.message), h('a', { class: 'btn', href: '#/' }, 'Go to login'));
}
const err = h('div', { class: 'err' });
const name = h('input', { type: 'text', autocomplete: 'nickname', maxlength: 60, required: true });
const pw = h('input', { type: 'password', autocomplete: 'new-password', minlength: 10, required: true });
const btn = h('button', { class: 'primary', type: 'submit' }, "I'm in 🤘");
setTimeout(() => name.focus());
return authShell(h('form', {
onsubmit: async (e) => {
e.preventDefault();
btn.disabled = true;
try {
const r = await api('/invite/accept', { method: 'POST', body: { token, name: name.value, password: pw.value } });
state.me = r.user;
location.hash = '#/';
route();
} catch (ex) { err.textContent = ex.message; } finally { btn.disabled = false; }
},
},
h('h2', {}, "You're invited!"),
h('p', {}, inv.invited_by ? `${inv.invited_by} invited ` : 'You were invited as ', h('b', {}, inv.email), inv.invited_by ? ' to the PIKKIE beta.' : '.', inv.role === 'admin' ? h('span', { class: 'st st-finished', style: 'margin-left:6px' }, 'admin') : null),
inv.message && h('p', { class: 'muted', style: 'border-left:3px solid var(--pink);padding-left:10px;white-space:pre-wrap' }, inv.message),
h('label', {}, 'Display name'), name,
h('label', {}, 'Password (10+ characters)'), pw,
err,
h('div', { class: 'row', style: 'margin-top:16px' }, btn, h('span', { class: 'spacer' }), h('span', { class: 'small muted' }, `Valid until ${new Date(inv.expires).toLocaleDateString()}`))));
}
/* computer login approved from the phone app */
async function appLogin(box) {
let stop = false;
const cancel = () => { stop = true; route(); };
async function start() {
const w = await api('/weblogin/new', { method: 'POST' }).catch((e) => { toast(e.message, true); return null; });
if (!w) return;
const svg = new DOMParser().parseFromString(w.qr_svg, 'image/svg+xml').documentElement;
const left = h('b', {});
box.replaceChildren(h('div', { class: 'applogin-qr' },
h('div', { class: 'qr' }, document.importNode(svg, true)),
h('div', {},
h('b', {}, 'Scan with the PIKKIE app'),
h('ol', { class: 'small' }, h('li', {}, 'Open PIKKIE on your phone'), h('li', {}, 'Me → ', h('b', {}, 'Log in on a computer')), h('li', {}, 'Point at this code and confirm')),
h('p', { class: 'small muted' }, 'Expires in ', left, ' · ', h('a', { href: '#', onclick: (e) => { e.preventDefault(); cancel(); } }, 'use password instead')))));
while (!stop && document.body.contains(box)) {
const s = Math.max(0, Math.round((w.expires - Date.now()) / 1000));
left.textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
if (!s) return start();
try {
const r = await fetch('/api/weblogin/poll', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id: w.id, secret: w.secret }) });
const j = await r.json();
if (r.status === 410) return start();
if (r.ok && j.user) { state.me = j.user; toast(`Welcome back, ${j.user.name} 🤘`); return route(); }
} catch { /* network blip, keep polling */ }
await new Promise((res) => setTimeout(res, 2000));
}
}
start();
}
function view2faLogin(challenge) {
const err = h('div', { class: 'err' });
const code = h('input', { type: 'text', inputmode: 'numeric', autocomplete: 'one-time-code', placeholder: '123456 or recovery code', required: true });
const btn = h('button', { class: 'primary', type: 'submit' }, 'Verify');
setTimeout(() => code.focus());
return authShell(h('form', {
onsubmit: async (e) => {
e.preventDefault();
btn.disabled = true;
try {
const r = await api('/login/2fa', { method: 'POST', body: { challenge, code: code.value } });
state.me = r.user;
route();
} catch (ex) { err.textContent = ex.message; } finally { btn.disabled = false; }
},
}, h('h2', {}, 'Two-factor check'), h('p', { class: 'muted' }, 'Enter the 6-digit code from your authenticator app.'), code, err, h('div', { class: 'row', style: 'margin-top:16px' }, btn)));
}
/* ---------------- issues list ---------------- */
async function viewIssues() {
const q = new URLSearchParams(location.hash.split('?')[1] || '');
await loadProjects();
const filter = { status: q.get('status') || '', q: q.get('q') || '', mine: q.get('mine') === '1', project: q.get('project') ?? '', weight: q.get('weight') || '', sort: q.get('sort') || '' };
const pq = filter.project ? `&project=${encodeURIComponent(filter.project)}` : '';
const wq = `${filter.weight ? `&weight=${filter.weight}` : ''}${filter.sort ? `&sort=${filter.sort}` : ''}`;
const [stats, list, announcements] = await Promise.all([
api(`/stats?${pq}`),
api(`/items?limit=200&status=${encodeURIComponent(filter.status)}&q=${encodeURIComponent(filter.q)}${filter.mine ? '&mine=1' : ''}${pq}${wq}`),
api('/announcements?limit=1'),
]);
const go = (patch) => {
const n = { ...filter, ...patch };
const p = new URLSearchParams();
if (n.status) p.set('status', n.status);
if (n.q) p.set('q', n.q);
if (n.mine) p.set('mine', '1');
if (n.project) p.set('project', n.project);
if (n.weight) p.set('weight', n.weight);
if (n.sort) p.set('sort', n.sort);
location.hash = '#/' + (p.toString() ? '?' + p : '');
};
const search = h('input', { type: 'text', placeholder: 'Search bullets or people…', value: filter.q, onkeydown: (e) => e.key === 'Enter' && go({ q: search.value }) });
return layout('issues',
h('h1', {}, 'All the ', h('span', { class: 'hl' }, 'little things')),
h('p', { class: 'sub' }, 'Every bullet every tester reported, and where it stands.'),
announcements[0] && h('a', { class: 'card announcement-banner', href: `#/post/${announcements[0].id}` },
h('b', {}, `📣 ${announcements[0].title}`),
announcements[0].release_version && h('span', { class: 'small' }, ` v${announcements[0].release_version}`),
h('span', { class: 'small muted' }, ` · ${ago(announcements[0].created)} · read announcement →`)),
h('div', { class: 'stats' },
Object.keys(STATUS).map((s) =>
h('button', { class: `stat ${filter.status === s ? 'on' : ''}`, onclick: () => go({ status: filter.status === s ? '' : s }) }, h('b', {}, stats[s]), h('span', {}, STATUS[s])))),
h('div', { class: 'row', style: 'margin-bottom:14px' },
state.projects.length > 1 && h('div', { style: 'min-width:170px' }, projectSelect(filter.project, { allowAll: true, onchange: (v) => go({ project: v }) })),
h('div', { style: 'flex:1;min-width:200px' }, search),
h('label', { class: 'check', style: 'margin:0' }, h('input', { type: 'checkbox', checked: filter.mine, onchange: (e) => go({ mine: e.target.checked }) }), 'Only mine'),
(filter.status || filter.q || filter.mine || filter.project || filter.weight || filter.sort) && h('button', { class: 'small', onclick: () => go({ status: '', q: '', mine: false, project: '', weight: '', sort: '' }) }, 'Clear'),
h('a', { class: 'btn primary', href: '#/new' }, '+ Report something'),
),
h('div', { class: 'row', style: 'margin-bottom:12px;gap:6px' }, h('span', { class: 'small muted' }, 'CALIBER'),
WEIGHTS.map((w) => h('button', { class: `calfilter ${String(w.value) === filter.weight ? 'on' : ''}`, style: `--wc:${w.color}`, title: w.name, onclick: () => go({ weight: String(w.value) === filter.weight ? '' : String(w.value) }) }, weightTag(w.value))),
h('span', { class: 'spacer' }),
h('label', { class: 'check', style: 'margin:0' }, h('input', { type: 'checkbox', checked: filter.sort === 'weight', onchange: (e) => go({ sort: e.target.checked ? 'weight' : '' }) }), 'Heaviest first 💥')),
h('div', { class: 'card', style: 'padding:0' },
list.items.length
? h('ul', { class: 'bullets' }, list.items.map(bulletRow))
: h('div', { class: 'empty' }, h('img', { src: '/logo.svg', alt: '' }), h('p', {}, 'Nothing here. Suspiciously un-picky.'))),
list.total > list.items.length && h('p', { class: 'muted small' }, `Showing ${list.items.length} of ${list.total}. Narrow it down with filters.`),
);
}
function bulletRow(it) {
return h('li', { class: `w-${it.weight}`, style: `--wc:${W(it.weight).color}`, onclick: () => (location.hash = `#/item/${it.id}`) },
weightTag(it.weight),
h('div', { class: 'txt' },
h('div', {}, it.text),
h('div', { class: 'meta' }, h('span', { class: 'ref' }, it.ref), state.projects?.length > 1 && projTag(it.project), h('span', {}, `by ${it.author.name}`), h('span', {}, ago(it.updated)),
it.version && h('span', {}, reportVersion(it.version)), it.comment_count ? h('span', {}, `💬 ${it.comment_count}`) : null, it.metoo ? h('span', { title: 'me too' }, `✋ ${it.metoo}`) : null,
it.attachment_count ? h('span', {}, `📎 ${it.attachment_count}`) : null, viaTag(it.via, it.via_label))),
statusTag(it.status));
}
/* ---------------- new report ---------------- */
/* "- bullet" lines from a .txt / .md file. Nested bullets and indented lines become details of their parent;
headings, paragraphs and code are ignored; "- [ ]" / "- [x]" checkboxes are stripped. */
function bulletLinesFromFile(text) {
const out = [];
let inBullet = false, fence = false;
for (const raw of String(text).replace(/\r/g, '').split('\n')) {
if (/^\s*(```|~~~)/.test(raw)) { fence = !fence; inBullet = false; continue; }
if (fence) continue;
const m = /^(\s*)([-*+•]|\d{1,3}[.)])\s+(?:\[[ xX]\]\s+)?(.*\S)\s*$/.exec(raw);
if (m && m[1].replace(/\t/g, ' ').length < 2) { out.push(m[3]); inBullet = true; continue; }
if (m && inBullet) { out[out.length - 1] += '\n' + m[3]; continue; }
if (/^\s{2,}\S/.test(raw) && inBullet) { out[out.length - 1] += '\n' + raw.trim(); continue; }
if (!raw.trim()) continue;
inBullet = false;
}
return out;
}
function importButton(onBullets) {
const input = h('input', { type: 'file', accept: '.txt,.md,.markdown,text/plain,text/markdown', multiple: true, hidden: true, onchange: async () => {
const all = [];
for (const f of input.files) {
if (f.size > 2 * 1024 * 1024) { toast(`${f.name} is too big for an import`, true); continue; }
all.push(...bulletLinesFromFile(await f.text()));
}
input.value = '';
if (!all.length) return toast('No "- bullet" lines found in that file', true);
onBullets(all);
toast(`Imported ${all.length} bullet${all.length > 1 ? 's' : ''} 📥`);
} });
return h('span', {}, input, h('button', { type: 'button', class: 'small', title: 'Import "- bullet" lines from .txt or .md files', onclick: () => input.click() }, '📥 Import .txt / .md'));
}
const CAL_TAG = { 1: '.22', 2: '9mm', 3: '.45', 4: '7.62', 5: '12g' };
/* rapid fire: one input per bullet, Enter = next bullet, Backspace on empty = back, ⌘/Ctrl+Enter = fire */
function rapidFire({ getDefault, onFire }) {
const list = h('div', { class: 'rapid-list' });
const rows = [];
const counter = h('span', { class: 'rapid-count' });
const update = () => {
const n = rows.filter((r) => r.input.value.trim()).length;
counter.textContent = n ? `${n} loaded` : 'empty chamber';
rows.forEach((r, i) => { r.num.textContent = String(i + 1).padStart(2, '0'); r.drawCal(); });
};
function addRow(after, text = '', focus = true) {
const r = { weight: null };
const pre = extractWeight(text.trim());
if (pre.weight) { r.weight = pre.weight; text = pre.text; }
r.num = h('span', { class: 'rapid-num' });
r.cal = h('button', { type: 'button', class: 'rapid-cal', tabindex: -1, title: 'Click (or Alt+1…5) to change caliber' });
r.drawCal = () => { const w = r.weight ?? getDefault(); r.cal.replaceChildren(weightTag(w)); r.cal.classList.toggle('explicit', !!r.weight); };
r.cal.addEventListener('click', () => { r.weight = ((r.weight ?? getDefault()) % 5) + 1; r.drawCal(); r.input.focus(); });
r.input = h('input', { type: 'text', class: 'rapid-input', value: text, maxlength: 2000, placeholder: rows.length ? '' : 'Type a bullet, hit Enter, repeat…', autocomplete: 'off', spellcheck: 'true' });
r.el = h('div', { class: 'rapid-row' }, r.num, r.cal, r.input);
const idx = after ? rows.indexOf(after) + 1 : rows.length;
rows.splice(idx, 0, r);
list.insertBefore(r.el, rows[idx + 1]?.el || null);
r.input.addEventListener('input', update);
r.input.addEventListener('keydown', (e) => {
const i = rows.indexOf(r);
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); onFire(); return; }
if (e.key === 'Enter') { e.preventDefault(); if (r.input.value.trim()) addRow(r); else toast('Write something first 😉'); return; }
if (e.key === 'Backspace' && !r.input.value && rows.length > 1) {
e.preventDefault(); rows.splice(i, 1); r.el.remove();
const prev = rows[Math.max(0, i - 1)]; prev.input.focus(); prev.input.setSelectionRange(prev.input.value.length, prev.input.value.length); update(); return;
}
if (e.key === 'ArrowUp' && i > 0) { e.preventDefault(); rows[i - 1].input.focus(); }
if (e.key === 'ArrowDown' && i < rows.length - 1) { e.preventDefault(); rows[i + 1].input.focus(); }
if (e.altKey && /^Digit[1-5]$/.test(e.code)) { e.preventDefault(); r.weight = Number(e.code.slice(5)); r.drawCal(); }
});
r.input.addEventListener('paste', (e) => {
const t = e.clipboardData?.getData('text') || '';
if (!t.includes('\n')) return;
e.preventDefault();
const lines = bulletLinesFromFile(t).length ? bulletLinesFromFile(t) : t.split('\n').map((x) => x.trim()).filter(Boolean);
load(lines, r);
});
update();
if (focus) { if (document.body.contains(r.input)) r.input.focus(); else setTimeout(() => r.input.focus()); }
return r;
}
function load(lines, at) {
let cur = at && !at.input.value.trim() ? at : null;
let last = at;
for (const l of lines) {
const flat = l.replace(/\n+/g, ' · ');
if (cur) { const pre = extractWeight(flat); cur.input.value = pre.text; if (pre.weight) cur.weight = pre.weight; last = cur; cur = null; }
else last = addRow(last, flat, false);
}
addRow(last, '', true);
}
addRow(null);
return {
el: h('div', { class: 'rapid' }, list, h('div', { class: 'rapid-help small muted' }, h('kbd', {}, 'Enter'), ' next bullet · ', h('kbd', {}, '⌫'), ' on empty = back · ', h('kbd', {}, '↑↓'), ' move · ', h('kbd', {}, 'Alt+1…5'), ' caliber · ', h('kbd', {}, '⌘/Ctrl+Enter'), ' fire'), counter),
text: () => rows.filter((r) => r.input.value.trim()).map((r) => `- ${r.weight ? `[${CAL_TAG[r.weight]}] ` : ''}${r.input.value.trim()}`).join('\n'),
load: (lines) => load(lines, rows[rows.length - 1]),
reset: () => { rows.splice(0).forEach((r) => r.el.remove()); addRow(null); },
focus: () => rows[rows.length - 1]?.input.focus(),
redraw: update,
};
}
async function viewNew() {
await loadProjects();
let mode = 'classic';
try { mode = localStorage.getItem('pikkie.mode') || 'classic'; } catch { /* private mode */ }
const ta = h('textarea', { class: 'bullets', placeholder: '- The save button jumps when I tap it\n- Typo on the settings page: "Setings"\n- Dark mode makes the chart unreadable\n (indent a line to add details to the bullet above)' });
const version = h('input', { type: 'text', placeholder: 'e.g. 0.4.2 (optional)', maxlength: 60, value: state.lastVersion || '' });
const files = fileCollector();
const preview = h('ul', { class: 'bullets' });
let weight = state.me.last_weight || 1;
const btn = h('button', { class: 'primary', type: 'submit' }, 'Send it 🤘');
const rapid = rapidFire({ getDefault: () => weight, onFire: () => btn.click() });
const wPicker = weightPicker(weight, async (v) => { weight = v; state.me.last_weight = v; upd(); rapid.redraw(); api('/me', { method: 'PATCH', body: { last_weight: v } }).catch(() => {}); focusInput(); });
const count = h('span', { class: 'muted small' });
const currentText = () => (mode === 'rapid' ? rapid.text() : ta.value);
const parse = () => {
const out = [];
for (const raw of currentText().split('\n')) {
if (!raw.trim()) continue;
if (/^(\s{2,}|\t)\S/.test(raw) && out.length) { out[out.length - 1] += '\n' + raw.trim(); continue; }
const l = raw.trim().replace(/^([-*•·▪‣◦]|\d{1,3}[.)])\s+/, '').trim();
if (l) out.push(l);
}
return out;
};
const upd = () => {
const b = parse();
count.textContent = b.length ? `${b.length} bullet${b.length > 1 ? 's' : ''} → ${b.length} separate item${b.length > 1 ? 's' : ''}` : '';
btn.textContent = mode === 'rapid' ? (b.length ? `🔥 Fire ${b.length}` : '🔥 Fire') : 'Send it 🤘';
preview.replaceChildren(...b.map((t) => { const x = extractWeight(t); const wv = x.weight ?? weight; return h('li', { style: `cursor:default;--wc:${W(wv).color}`, class: `w-${wv}` }, weightTag(wv), h('div', { class: 'txt' }, x.text), statusTag('open')); }));
};
ta.addEventListener('input', upd);
rapid.el.addEventListener('input', upd);
rapid.el.addEventListener('keydown', () => setTimeout(upd));
const focusInput = () => (mode === 'rapid' ? rapid.focus() : ta.focus());
const projSel = projectSelect(state.currentProject, {
onchange: async (v) => {
state.currentProject = Number(v);
await api('/me', { method: 'PATCH', body: { last_project_id: Number(v) } }).catch(() => {});
toast(`Now reporting on ${state.projects.find((p) => p.id === Number(v))?.name}`);
focusInput();
},
});
state.sessionFiled ||= [];
const filed = h('div', { class: 'card', hidden: !state.sessionFiled.length });
const drawFiled = () => {
filed.hidden = !state.sessionFiled.length;
filed.replaceChildren(h('h3', {}, `Filed this session: ${state.sessionFiled.length}`),
h('ul', { class: 'bullets' }, state.sessionFiled.slice().reverse().map((f) =>
h('li', { class: `w-${f.weight}`, style: `--wc:${W(f.weight).color}`, onclick: () => (location.hash = `#/item/${f.id}`) }, weightTag(f.weight), h('div', { class: 'txt' }, h('div', {}, f.text), h('div', { class: 'meta' }, h('span', { class: 'ref' }, `PK-${f.id}`), projTag(f.project))), statusTag('open')))));
};
drawFiled();
ta.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); btn.click(); } });
const classicBox = h('div', {}, h('label', {}, 'Your bullets'), ta);
const evidence = h('details', { class: 'evidence' }, h('summary', {}, '📎 Add evidence (optional): screenshots, logs, videos'), files.el);
const evidenceClassic = h('div', {}, h('label', {}, 'Evidence (screenshots, logs, videos, anything)'));
const imp = importButton((lines) => {
if (mode === 'rapid') rapid.load(lines);
else { ta.value = (ta.value.trim() ? ta.value.replace(/\s*$/, '\n') : '') + lines.map((l) => '- ' + l.split('\n').join('\n ')).join('\n'); ta.focus(); }
upd();
});
const tabs = h('div', { class: 'tabs mode-tabs' });
const sub = h('p', { class: 'sub' });
const formBody = h('div', {});
const setMode = (m) => {
mode = m;
try { localStorage.setItem('pikkie.mode', m); } catch { /* ignore */ }
tabs.replaceChildren(
h('button', { type: 'button', class: m === 'classic' ? 'on' : '', onclick: () => setMode('classic') }, '✍ Classic'),
h('button', { type: 'button', class: m === 'rapid' ? 'on' : '', onclick: () => setMode('rapid') }, '⚡ Rapid fire'),
h('span', { class: 'spacer' }), imp);
sub.textContent = m === 'rapid'
? 'Rapid fire: type, Enter, type, Enter… Each line is a bullet. ⌘/Ctrl+Enter fires the whole magazine.'
: 'One bullet per issue. Paste screenshots straight in. ⌘/Ctrl+Enter sends and keeps you here for the next batch.';
if (m === 'rapid') formBody.replaceChildren(h('label', {}, 'Bullets'), rapid.el, evidence);
else formBody.replaceChildren(classicBox, evidenceClassic);
(m === 'rapid' ? evidence : evidenceClassic).append(files.el);
upd();
setTimeout(focusInput);
};
setMode(mode);
return layout('new',
h('h1', {}, 'Be ', h('span', { class: 'hl' }, 'picky')),
sub,
h('form', {
class: 'card loud tape',
onsubmit: async (e) => {
e.preventDefault();
if (!parse().length) return toast('Write at least one bullet', true);
await busy(btn, async () => {
const fd = new FormData();
fd.append('bullets', currentText());
fd.append('version', version.value);
fd.append('project_id', projSel.value);
fd.append('weight', String(weight));
for (const f of files.files) fd.append('files', f, f.name);
const bullets = parse();
const r = await api('/reports', { method: 'POST', form: fd });
r.ids.forEach((id, i) => state.sessionFiled.push({ id, weight: r.weights[i], text: extractWeight(bullets[i]).text, project: state.projects.find((p) => p.id === r.project.id) || r.project }));
state.lastVersion = version.value;
toast(`${r.ids.length} bullet${r.ids.length > 1 ? 's' : ''} filed in ${r.project.name}. ${mode === 'rapid' ? 'Reload! 🔫' : "Keep 'em coming!"}`);
ta.value = '';
rapid.reset();
files.clear();
evidence.open = false;
upd();
drawFiled();
focusInput();
});
},
},
tabs,
h('div', { class: 'grid2' }, h('div', {}, h('label', {}, 'Project (remembered for next time)'), projSel), h('div', {}, h('label', {}, 'App version'), version)),
h('label', {}, 'Default caliber (remembered) — or tag a line: [.22] [9mm] [.45] [7.62] [12g]'), wPicker,
formBody,
h('div', { class: 'row', style: 'margin-top:16px' }, count, h('span', { class: 'spacer' }), btn),
),
h('div', { class: 'card' }, h('h3', {}, 'Preview'), preview),
filed,
);
}
/* ---------------- item detail ---------------- */
async function viewItem(id) {
const [it] = await Promise.all([api(`/items/${id}`), loadProjects()]);
const inlineReply = (c, holder) => {
const ta = h('textarea', { placeholder: `Reply to ${c.author.name}…`, style: 'min-height:70px' });
const fc = fileCollector('Attach or paste');
const b = h('button', { class: 'primary small', type: 'submit' }, 'Reply');
holder.replaceChildren(h('form', {
class: 'inline-reply',
onsubmit: async (e) => {
e.preventDefault();
await busy(b, async () => {
const fd = new FormData();
fd.append('body', ta.value);
fd.append('parent_id', String(c.id));
for (const f of fc.files) fd.append('files', f, f.name);
await api(`/items/${id}/comments`, { method: 'POST', form: fd });
route();
});
},
}, ta, fc.el, h('div', { class: 'row end', style: 'margin-top:8px' }, h('button', { type: 'button', class: 'small ghost', onclick: () => holder.replaceChildren() }, 'Cancel'), b)));
ta.focus();
};
const commentEl = (c, isChild) => {
const mine = c.author.id === state.me.id;
const bodyEl = h('div', { class: 'body' }, c.body);
const replyHolder = h('div', {});
const actions = h('div', { class: 'acts' },
!isChild && h('button', { class: 'small ghost', onclick: () => inlineReply(c, replyHolder) }, '↩ Reply'),
isChild && h('button', { class: 'small ghost', onclick: () => { const root = document.getElementById(`c-${c.parent_id}`); root?.querySelector('.acts button')?.click(); } }, '↩ Reply'),
mine && c.body && h('button', { class: 'small ghost', onclick: () => {
const ta = h('textarea', { style: 'min-height:70px' }, c.body);
bodyEl.replaceChildren(ta, h('div', { class: 'row end', style: 'margin-top:6px' },
h('button', { class: 'small ghost', onclick: () => bodyEl.replaceChildren(c.body) }, 'Cancel'),
h('button', { class: 'small primary', onclick: async (e) => busy(e.target, async () => { await api(`/comments/${c.id}`, { method: 'PATCH', body: { body: ta.value } }); route(); }) }, 'Save')));
ta.focus();
} }, '✎ Edit'),
(isAdmin() || (mine && !c.status_to)) && h('button', { class: 'small ghost', onclick: async () => {
if (!confirm(isChild || !c.reply_count ? 'Delete this comment?' : `Delete this comment and its ${c.reply_count} repl${c.reply_count === 1 ? 'y' : 'ies'}?`)) return;
await api(`/comments/${c.id}`, { method: 'DELETE' }).catch((e) => toast(e.message, true));
route();
} }, '🗑'));
return h('div', { class: `ev ${isChild ? 'child' : ''} ${c.author.role === 'admin' ? 'admin' : ''} ${c.status_to ? 'status' : ''}`, id: `c-${c.id}` },
h('div', { class: 'head' }, userLink(c.author, 22), c.author.role === 'admin' && h('span', { class: 'via' }, 'admin'),
c.author.id === it.author.id && h('span', { class: 'via op' }, 'reporter'), viaTag(c.via, c.via_label),
c.status_to && [h('span', {}, 'flagged as'), statusTag(c.status_to)], h('span', {}, ago(c.created)), c.edited && h('span', { title: new Date(c.edited).toLocaleString() }, '(edited)')),
c.body && bodyEl,
fileList(c.attachments),
actions,
!isChild && h('div', { class: 'thread' }, it.comments.filter((r) => r.parent_id === c.id).map((r) => commentEl(r, true))),
replyHolder);
};
const comments = it.comments.filter((c) => !c.parent_id).map((c) => commentEl(c, false));
let metoo = { metoo: it.metoo, my_metoo: it.my_metoo, metoo_names: it.metoo_names };
const metooBtn = h('button', { class: 'small metoo', title: '' });
const drawMetoo = () => {
metooBtn.className = `small metoo ${metoo.my_metoo ? 'on' : ''}`;
metooBtn.title = metoo.metoo_names.join(', ') || 'Nobody yet';
metooBtn.replaceChildren(metoo.my_metoo ? '✋ You too' : '✋ Me too', h('b', {}, String(metoo.metoo)));
};
metooBtn.addEventListener('click', async () => { metoo = await api(`/items/${id}/metoo`, { method: 'POST' }); drawMetoo(); });
drawMetoo();
const replyTa = h('textarea', { placeholder: it.status === 'needs_info' ? 'The admins asked for more info — tell them!' : 'Add a comment, steps to reproduce, more evidence…', style: 'min-height:90px' });
const replyFiles = fileCollector('Attach or paste more evidence');
const replyBtn = h('button', { class: 'primary', type: 'submit' }, 'Comment');
const reply = h('form', {
class: 'card',
onsubmit: async (e) => {
e.preventDefault();
await busy(replyBtn, async () => {
const fd = new FormData();
fd.append('body', replyTa.value);
for (const f of replyFiles.files) fd.append('files', f, f.name);
await api(`/items/${id}/comments`, { method: 'POST', form: fd });
toast('Comment added');
route();
});
},
}, h('h3', {}, 'Join the discussion'), replyTa, replyFiles.el, h('div', { class: 'row end', style: 'margin-top:12px' }, replyBtn));
let adminBox = null;
if (isAdmin()) {
let pick = it.status;
const pickBtns = Object.keys(STATUS).map((s) => h('button', { type: 'button', class: `small ${s === pick ? 'sel' : ''}`, 'data-s': s, onclick: () => { pick = s; pickBtns.forEach((b) => b.classList.toggle('sel', b.dataset.s === s)); } }, statusTag(s)));
const msg = h('textarea', { placeholder: 'Message to the reporter: what changed, why declined, what info you need…', style: 'min-height:90px' });
const aFiles = fileCollector('Attach screenshots of the fix, patches, builds…');
const flagBtn = h('button', { class: 'primary', type: 'submit' }, 'Flag it');
adminBox = h('form', {
class: 'card admin-box',
onsubmit: async (e) => {
e.preventDefault();
await busy(flagBtn, async () => {
const fd = new FormData();
fd.append('status', pick);
fd.append('message', msg.value);
for (const f of aFiles.files) fd.append('files', f, f.name);
await api(`/items/${id}/status`, { method: 'POST', form: fd });
toast(`Flagged as ${STATUS[pick]}`);
route();
});
},
},
h('h3', {}, '⚡ Admin: flag this bullet'),
h('div', { class: 'status-pick' }, pickBtns),
h('label', {}, 'Message'), msg, aFiles.el,
h('div', { class: 'row', style: 'margin-top:12px' },
h('button', { type: 'button', class: 'danger small', onclick: async () => { if (confirm(`Delete ${it.ref} forever?`)) { await api(`/items/${id}`, { method: 'DELETE' }); toast('Deleted'); location.hash = '#/'; } } }, 'Delete'),
h('span', { class: 'spacer' }), h('span', { class: 'small muted' }, 'Reporter gets an e-mail for needs info / fixed / finished / declined.'), flagBtn));
}
// the lowest threshold for a fix: paste the code right here, nothing else to fill in
const fixCode = codeBlocks([], { hint: false });
const fixNote = h('input', { type: 'text', placeholder: 'Optional: a word for the reviewer' });
const fixBtn = h('button', { class: 'primary', type: 'submit' }, 'Send fix for review');
const fixBox = h('details', { class: 'suggest-fix' }, h('summary', {}, '⌥ Got a fix? Paste the code here'),
h('form', { onsubmit: (e) => { e.preventDefault(); busy(fixBtn, async () => {
const blocks = fixCode.get();
if (!blocks.length) throw new Error('Paste some code first');
const fd = new FormData();
fd.append('fixes', it.ref);
fd.append('description', fixNote.value);
codeForm(fd, blocks);
const c = await api('/changes', { method: 'POST', form: fd });
submitted(c);
location.hash = `#/change/${c.id}`;
}); } },
h('p', { class: 'small muted', style: 'margin:8px 0' }, 'You do not need the repository: paste what you wrote and, if you know it, the file it belongs in. Admins review it and put it in place.'),
fixCode.el, fixNote,
h('div', { class: 'row', style: 'margin-top:10px' }, h('a', { class: 'small', href: `#/code/new?fixes=${it.ref}` }, 'More options…'), h('span', { class: 'spacer' }), fixBtn)));
const canEdit = isAdmin() || (it.author.id === state.me.id && it.status === 'open');
const textEl = h('div', { class: 'item-text' }, it.text);
let projectMover;
if (canEdit && state.projects?.length > 1) projectMover = projectSelect(it.project?.id, { onchange: async (v) => {
if (Number(v) === it.project?.id) return;
projectMover.disabled = true;
try {
await api(`/items/${id}/project`, { method: 'PATCH', body: { project_id: Number(v) } });
toast('Moved to project');
route();
} catch (e) {
projectMover.value = String(it.project?.id || '');
toast(e.message, true);
} finally { projectMover.disabled = false; }
} });
const editBtn = canEdit && h('button', {
class: 'small', onclick: async () => {
const t = prompt('Edit bullet', it.text);
if (t && t.trim() && t !== it.text) { await api(`/items/${id}`, { method: 'PATCH', body: { text: t } }).catch((e) => toast(e.message, true)); route(); }
},
}, 'Edit');
return layout('issues',
h('p', {}, h('a', { href: '#/' }, '← all bullets')),
h('div', { class: 'card loud' },
h('div', { class: 'row' }, weightTag(it.weight), h('span', { class: 'ref' }, it.ref), copyButton(it.ref, 'Ref', 'Copy bullet reference'), projTag(it.project), statusTag(it.status), viaTag(it.via, it.via_label), h('span', { class: 'spacer' }), editBtn),
textEl,
h('div', { class: 'row', style: 'margin:0 0 12px' }, copyButton(it.text, 'Text', 'Copy bullet text'), copyButton(() => `${location.origin}/#/item/${id}`, 'Link', 'Copy bullet link'), projectMover && h('label', { class: 'small', style: 'margin-left:auto' }, 'Project ', projectMover)),
(isAdmin() || it.author.id === state.me.id) && h('details', { class: 'reweigh' }, h('summary', {}, 'Re-weigh this bullet'),
weightPicker(it.weight, async (v) => { await api(`/items/${id}/weight`, { method: 'PATCH', body: { weight: v } }).catch((e) => toast(e.message, true)); toast(`Reloaded with ${W(v).caliber} 💥`); route(); })),
h('div', { class: 'row', style: 'margin-bottom:6px' }, metooBtn, metoo.metoo_names.length > 0 && h('span', { class: 'small muted' }, metoo.metoo_names.slice(0, 5).join(', ') + (metoo.metoo_names.length > 5 ? ` +${metoo.metoo_names.length - 5}` : ''))),
h('div', { class: 'muted small row', style: 'gap:6px' }, 'Reported by', userLink(it.author, 20), `· ${new Date(it.created).toLocaleString()}`, it.version ? ` · version ${it.version}` : ''),
fileList(it.attachments),
it.siblings.length > 0 && h('div', { style: 'margin-top:14px' }, h('div', { class: 'small muted' }, 'Same report:'),
h('ul', { class: 'bullets' }, it.siblings.map((s) => h('li', { onclick: () => (location.hash = `#/item/${s.id}`) }, h('div', { class: 'txt' }, h('span', { class: 'ref' }, s.ref), ' ', s.text), statusTag(s.status))))),
it.changes?.length > 0 && h('div', { style: 'margin-top:14px' }, h('div', { class: 'small muted' }, 'Code changes that fix this:'),
h('ul', { class: 'bullets' }, it.changes.map((c) => h('li', { onclick: () => (location.hash = `#/change/${c.id}`) }, h('div', { class: 'txt' }, h('span', { class: 'ref' }, c.ref), ' ', c.title), changeTag(c.status))))),
fixBox,
),
adminBox,
h('h2', {}, `Discussion${it.comments.length ? ` (${it.comments.length})` : ''}`),
comments.length ? h('div', { class: 'timeline' }, comments) : h('p', { class: 'muted' }, 'No replies yet. Start the discussion.'),
reply,
);
}
/* ---------------- code changes ---------------- */
const CHANGE = { pending: 'Pending review', needs_work: 'Needs work', accepted: 'Accepted', declined: 'Declined', withdrawn: 'Withdrawn' };
const changeTag = (s) => h('span', { class: `st cst-${s}` }, CHANGE[s] || s);
const diffStat = (c) => h('span', { class: 'dstat' },
c.has_patch && [h('b', { class: 'd-add' }, `+${c.additions}`), ' ', h('b', { class: 'd-del' }, `−${c.deletions}`)],
c.snippet_count > 0 && h('span', { class: 'snip-tag' }, `{ } ${c.snippet_count} snippet${c.snippet_count === 1 ? '' : 's'} · ${c.snippet_lines} lines`),
c.files_count > 0 && ` · ${c.files_count} file${c.files_count === 1 ? '' : 's'}`, c.has_patch && c.commits > 1 && ` · ${c.commits} commits`);
/** colored unified diff; huge patches render the first part until asked for the rest */
/* Invisible and text-direction characters can make code read differently from what it does ("Trojan Source").
Reviewers see them spelled out. The class is built from code points, so none of them sit in this file. */
const HIDDEN_CHARS = new RegExp(`[${[[0x200b], [0x200e, 0x200f], [0x202a, 0x202e], [0x2060], [0x2066, 0x2069], [0x61c], [0xfeff]].map(([a, b]) => String.fromCodePoint(a) + (b ? '-' + String.fromCodePoint(b) : '')).join('')}]`, 'g');
function visible(text) {
if (text.search(HIDDEN_CHARS) < 0) return text;
const out = [];
let last = 0;
for (const m of text.matchAll(HIDDEN_CHARS)) {
out.push(text.slice(last, m.index), h('b', { class: 'hidden-char', title: 'invisible or text-direction character' }, `⟦U+${m[0].codePointAt(0).toString(16).toUpperCase().padStart(4, '0')}⟧`));
last = m.index + m[0].length;
}
out.push(text.slice(last));
return out;
}
const codePre = (text, cls = '') => h('pre', { class: `diff code ${cls}` }, text.replace(/\n$/, '').split('\n').map((l) => h('span', {}, visible(l), '\n')));
const warnBox = (c) => c.warnings?.length > 0 && h('div', { class: 'card warnbox' }, h('b', {}, '⚠ Review with care'),
h('ul', {}, c.warnings.map((w) => h('li', {}, `This change ${w.text}.`))));
function diffView(patch, max = 3000) {
const lines = patch.replace(/\n$/, '').split('\n');
const pre = h('pre', { class: 'diff' });
const cls = (l) => (l.startsWith('diff --git') || l.startsWith('From ') && /^From [0-9a-f]{40} /.test(l) ? 'd-file'
: l.startsWith('+++') || l.startsWith('---') || /^(index|new file|deleted file|similarity|rename|old mode|new mode) /.test(l) ? 'd-meta'
: l.startsWith('@@') ? 'd-hunk' : l.startsWith('+') ? 'd-add' : l.startsWith('-') ? 'd-del' : '');
const draw = (n) => pre.replaceChildren(...lines.slice(0, n).map((l) => h('span', { class: cls(l) }, visible(l), '\n')));
draw(max);
const more = lines.length > max && h('button', { class: 'small', onclick: () => { draw(lines.length); more.remove(); } }, `Show all ${lines.length} lines`);
return h('div', {}, pre, more);
}
/** Code editor for a change: one or more blocks of code, each with an optional file path. No repository needed:
* paste the function or file you wrote, or drop files in. A block that is a git diff is recognised by the server
* and lands via git am. Blocks keep their note / "replaces" / language, so revising never loses them. */
function codeBlocks(initial = [], { hint = true } = {}) {
const list = h('div', { class: 'codeblocks' });
const blocks = [];
const add = (b = {}) => {
const path = h('input', { type: 'text', class: 'mono', placeholder: 'File it belongs in, if you know it (e.g. app/src/Login.kt)', value: b.path || '' });
const ta = h('textarea', { class: 'mono', spellcheck: 'false', placeholder: 'Paste your code: a function, a whole file, the fix you would make… (Got the repo? A git diff works too.)', style: 'min-height:150px' }, b.content || '');
const replaces = h('textarea', { class: 'mono', spellcheck: 'false', placeholder: 'The existing code this replaces, if you can see it (helps admins find the spot)', style: 'min-height:70px' }, b.replaces || '');
const note = h('input', { type: 'text', placeholder: 'Where it goes: "replace the onSave function", "new file", "after the imports"…', value: b.note || '' });
const self = { path, ta, replaces, note, language: b.language || '' };
const el = h('div', { class: 'codeblock' },
h('div', { class: 'row' }, h('div', { style: 'flex:1;min-width:200px' }, path),
h('button', { type: 'button', class: 'small ghost', title: 'remove this block', 'aria-label': 'remove this block', onclick: () => { if (blocks.length > 1) { blocks.splice(blocks.indexOf(self), 1); el.remove(); } else { ta.value = ''; path.value = ''; replaces.value = ''; note.value = ''; } } }, '×')),
ta,
h('details', { open: !!(b.replaces || b.note) }, h('summary', { class: 'small' }, 'Say where it goes (optional)'), note, replaces));
blocks.push(self);
list.append(el);
return self;
};
const addFiles = async (files) => {
for (const f of files) {
if (f.size > 2_000_000) { toast(`${f.name} is over 2 MB. Split it up.`, true); continue; }
const text = await f.text();
if (text.includes('\0')) { toast(`${f.name} is not a text file`, true); continue; }
const empty = blocks.find((b) => !b.ta.value.trim() && !b.path.value.trim());
const blk = empty || add();
blk.ta.value = text;
// a .patch file is a diff, not a file in the project
if (!/\.(patch|diff|mbox)$/i.test(f.name)) blk.path.value = f.webkitRelativePath || f.name;
}
};
const pick = h('input', { type: 'file', multiple: true, hidden: true, onchange: async () => { await addFiles([...pick.files]); pick.value = ''; } });
(initial.length ? initial : [{}]).forEach(add);
const el = h('div', { class: 'code-editor' }, h('label', {}, 'Code'),
hint && h('p', { class: 'small muted', style: 'margin:0 0 6px' }, 'No access to the repository? No problem: paste the code you wrote, or drop files here. Admins put it in place.'),
list, pick,
h('div', { class: 'row' }, h('button', { type: 'button', class: 'small', onclick: () => add().ta.focus() }, '+ Another snippet'),
h('button', { type: 'button', class: 'small', onclick: () => pick.click() }, '📄 Load files')));
el.addEventListener('dragover', (e) => { if (e.dataTransfer?.types?.includes('Files')) { e.preventDefault(); el.classList.add('over'); } });
el.addEventListener('dragleave', () => el.classList.remove('over'));
el.addEventListener('drop', (e) => { if (!e.dataTransfer?.files?.length) return; e.preventDefault(); e.stopPropagation(); el.classList.remove('over'); addFiles([...e.dataTransfer.files]); });
// files pasted while typing in the editor belong to the editor, not to an evidence box elsewhere on the page
el.addEventListener('paste', (e) => { if (e.clipboardData?.files?.length) { e.preventDefault(); e.stopPropagation(); addFiles([...e.clipboardData.files]); } });
return {
el,
get: () => blocks.map((b) => ({ path: b.path.value.trim(), content: b.ta.value, replaces: b.replaces.value, note: b.note.value.trim(), language: b.language })).filter((b) => b.content.trim()),
};
}
const codeForm = (fd, blocks) => fd.append('snippets_file', new Blob([JSON.stringify(blocks)], { type: 'application/json' }), 'snippets.json');
/** what the server said about a submission, as a toast */
const submitted = (c) => toast(c.duplicate ? `You already sent this as ${c.ref}` : c.notices?.[0] ? `${c.ref} is in the queue. ${c.notices[0]}` : `${c.ref} is in the queue 🤘`);
async function viewChanges() {
const q = new URLSearchParams(location.hash.split('?')[1] || '');
await loadProjects();
const filter = { status: q.get('status') ?? 'pending', q: q.get('q') || '', mine: q.get('mine') === '1', project: q.get('project') || '' };
const go = (patch) => {
const n = { ...filter, ...patch };
const p = new URLSearchParams();
if (n.status !== 'pending') p.set('status', n.status);
if (n.q) p.set('q', n.q);
if (n.mine) p.set('mine', '1');
if (n.project) p.set('project', n.project);
location.hash = '#/code' + (p.toString() ? '?' + p : '');
};
const list = await api(`/changes?limit=200&status=${encodeURIComponent(filter.status)}&q=${encodeURIComponent(filter.q)}${filter.mine ? '&mine=1' : ''}${filter.project ? `&project=${filter.project}` : ''}`);
const search = h('input', { type: 'text', placeholder: 'Search titles, files or people…', value: filter.q, onkeydown: (e) => e.key === 'Enter' && go({ q: search.value }) });
// admins: tick a batch, download it as one mbox, then handle it in one go
const selected = new Set();
const canBatch = isAdmin();
const batchCount = h('b', {}, '0');
const bundleLink = h('a', { class: 'btn', href: '#' }, '⬇ Diffs (.mbox)');
const sheetLink = h('a', { class: 'btn', href: '#' }, '⬇ Code sheet (.md)');
const byId = new Map(list.changes.map((c) => [c.id, c]));
const syncBatch = () => {
batchCount.textContent = String(selected.size);
const ids = [...selected].sort((a, b) => a - b);
const q = `/api/admin/changes/bundle?ids=${ids.join(',')}`;
const diffs = ids.some((i) => byId.get(i)?.has_patch);
const code = ids.some((i) => byId.get(i)?.snippet_count > 0);
bundleLink.href = diffs ? q : '#';
bundleLink.hidden = !diffs;
sheetLink.href = code ? `${q}&format=md` : '#';
sheetLink.hidden = !code;
batchBar.hidden = !selected.size;
};
let pick = 'accepted';
const pickBtns = ['accepted', 'needs_work', 'declined'].map((s) => h('button', { type: 'button', class: `small ${s === pick ? 'sel' : ''}`, 'data-s': s, onclick: () => { pick = s; pickBtns.forEach((b) => b.classList.toggle('sel', b.dataset.s === s)); fixWrap.hidden = s !== 'accepted'; } }, changeTag(s)));
const msg = h('textarea', { placeholder: 'One message for every author in this batch: what landed, what to fix…', style: 'min-height:70px' });
const fixIssues = h('input', { type: 'checkbox', checked: true });
const version = h('input', { type: 'text', placeholder: 'Landed in version, e.g. 1.4.1', maxlength: 40, style: 'max-width:240px' });
const fixWrap = h('div', { class: 'row', style: 'gap:12px' }, version, h('label', { class: 'check', style: 'margin:0' }, fixIssues, 'Also flag the bullets they fix as fixed'));
const applyBtn = h('button', { class: 'primary', onclick: (e) => busy(e.target, async () => {
const ids = [...selected];
const warned = ids.filter((i) => byId.get(i)?.warnings?.length).length;
if (!confirm(`Mark ${ids.length} change${ids.length > 1 ? 's' : ''} as ${CHANGE[pick]}?${pick === 'accepted' && warned ? `\n\n${warned} of them ${warned > 1 ? 'have' : 'has'} a review warning.` : ''}`)) return;
const r = await api('/admin/changes/review', { method: 'POST', body: { ids, status: pick, message: msg.value, version: version.value, fix_issues: pick === 'accepted' && fixIssues.checked } });
toast(`${r.changes.length} marked ${CHANGE[pick]}${r.bullets_fixed.length ? ` · ${r.bullets_fixed.length} bullet${r.bullets_fixed.length > 1 ? 's' : ''} fixed` : ''} 🤘`);
route();
}) }, 'Apply to batch');
const batchBar = h('div', { class: 'card admin-box batchbar', hidden: true },
h('div', { class: 'row' }, h('h3', { style: 'margin:0' }, '⚡ Batch: ', batchCount, ' selected'), h('span', { class: 'spacer' }), bundleLink, sheetLink),
h('p', { class: 'small muted' }, 'Land diffs with ', h('code', {}, 'git am --patch-format=mboxrd -3 <file>'), '; the code sheet has everything sent without a diff, to put in place by hand or with your agent. Then report back here:'),
h('div', { class: 'status-pick' }, pickBtns), msg,
h('div', { class: 'row', style: 'margin-top:10px' }, fixWrap, h('span', { class: 'spacer' }), applyBtn));
const pendingIds = list.changes.filter((c) => c.status === 'pending').map((c) => c.id);
const boxes = [];
const row = (c) => {
const box = canBatch && c.status !== 'withdrawn' && h('input', { type: 'checkbox', 'aria-label': `select ${c.ref}`, onclick: (e) => e.stopPropagation(), onchange: (e) => { e.target.checked ? selected.add(c.id) : selected.delete(c.id); syncBatch(); } });
if (box) boxes.push([c.id, box]);
return h('li', { class: 'change', onclick: () => (location.hash = `#/change/${c.id}`) },
box || h('span', { class: 'ch-icon' }, '⌥'),
h('div', { class: 'txt' },
h('div', {}, c.title),
h('div', { class: 'meta' }, h('span', { class: 'ref' }, c.ref), state.projects?.length > 1 && projTag(c.project), h('span', {}, `by ${c.author.name}`), h('span', {}, ago(c.updated)), diffStat(c),
c.revision > 1 && h('span', {}, `rev ${c.revision}`), c.note_count ? h('span', {}, `💬 ${c.note_count}`) : null,
c.fixes.length > 0 && h('span', {}, `fixes ${c.fixes.map((f) => f.ref).join(', ')}`),
c.warnings.length > 0 && h('span', { class: 'warn-tag', title: c.warnings.map((w) => w.text).join('\n') }, `⚠ ${c.warnings.length === 1 ? 'review with care' : `${c.warnings.length} warnings`}`),
viaTag(c.via, c.via_label))),
changeTag(c.status));
};
const selectAll = canBatch && pendingIds.length > 1 && h('button', { class: 'small', onclick: () => {
const all = pendingIds.every((id) => selected.has(id));
for (const [id, b] of boxes) if (pendingIds.includes(id)) { b.checked = !all; all ? selected.delete(id) : selected.add(id); }
syncBatch();
} }, 'Select all pending');
return layout('code',
h('h1', {}, 'Code ', h('span', { class: 'hl' }, 'changes')),
h('p', { class: 'sub' }, 'Code from testers and their bots, no repo access needed. Queued per project; admins take a whole batch in one go.'),
h('div', { class: 'stats stats-5' },
Object.keys(CHANGE).map((s) => h('button', { class: `stat ${filter.status === s ? 'on' : ''}`, onclick: () => go({ status: filter.status === s ? '' : s }) }, h('b', {}, list.counts[s]), h('span', {}, CHANGE[s])))),
h('div', { class: 'row', style: 'margin-bottom:14px' },
state.projects.length > 1 && h('div', { style: 'min-width:170px' }, projectSelect(filter.project, { allowAll: true, onchange: (v) => go({ project: v }) })),
h('div', { style: 'flex:1;min-width:200px' }, search),
h('label', { class: 'check', style: 'margin:0' }, h('input', { type: 'checkbox', checked: filter.mine, onchange: (e) => go({ mine: e.target.checked }) }), 'Only mine'),
selectAll,
h('a', { class: 'btn primary', href: '#/code/new' }, '+ Submit a change')),
list.overlaps.length > 0 && h('div', { class: 'card warnbox' }, h('b', {}, '⚠ Pending changes that touch the same files'),
h('ul', {}, list.overlaps.slice(0, 12).map((o) => h('li', {}, h('code', {}, o.file), ' · ', o.changes.join(', ')))),
h('p', { class: 'small muted', style: 'margin:0' }, 'They may conflict. The batch applies oldest first; git am -3 does a three-way merge where it can.')),
batchBar,
h('div', { class: 'card', style: 'padding:0' },
list.changes.length ? h('ul', { class: 'bullets changes' }, list.changes.map(row))
: h('div', { class: 'empty' }, h('img', { src: '/logo.svg', alt: '' }), h('p', {}, filter.status === 'pending' ? 'Nothing waiting for review.' : 'No code changes here.'))),
list.total > list.changes.length && h('p', { class: 'muted small' }, `Showing ${list.changes.length} of ${list.total}.`),
h('div', { class: 'card', style: 'margin-top:18px' }, h('h3', {}, '🤖 From your bot'),
h('p', { class: 'small' }, 'With an API key (on your ', h('a', { href: '#/profile' }, 'Me'), ' page), an agent can call ', h('code', {}, 'submit_change'), ' with code snippets (or a git diff) and the bullets it fixes, revise it with ', h('code', {}, 'update_change'), isAdmin() ? ['. Admins collect the queue with ', h('code', {}, 'get_change_bundle'), ' and handle it with ', h('code', {}, 'review_changes'), '.'] : '.')),
);
}
async function viewChangeNew() {
const q = new URLSearchParams(location.hash.split('?')[1] || '');
await loadProjects();
const title = h('input', { type: 'text', placeholder: 'Optional. Left empty, it is named after the bullet or the file', maxlength: 150 });
const desc = h('textarea', { placeholder: 'Optional: why and how, anything the reviewer should know', style: 'min-height:70px' });
const fixes = h('input', { type: 'text', placeholder: 'PK-3, PK-7', value: q.get('fixes') || '' });
const baseRef = h('input', { type: 'text', placeholder: 'v1.3.5, main @ 1a2b3c4…' });
const author = h('input', { type: 'text', placeholder: 'Name <you@example.com>' });
// only sent when picked: otherwise the server files it under the project of the first bullet it fixes
let proj = null;
const code = codeBlocks();
const send = h('button', { class: 'primary', type: 'submit' }, 'Submit for review');
return layout('code',
h('p', {}, h('a', { href: '#/code' }, '← code changes')),
h('h1', {}, 'Submit a ', h('span', { class: 'hl' }, 'code change')),
h('p', { class: 'sub' }, 'Only the code is required. Everything else helps, but can stay empty.'),
h('form', {
class: 'card',
onsubmit: (e) => {
e.preventDefault();
busy(send, async () => {
const blocks = code.get();
if (!blocks.length) throw new Error('Paste some code first');
const fd = new FormData();
fd.append('title', title.value);
fd.append('description', desc.value);
fd.append('fixes', fixes.value);
fd.append('base', baseRef.value);
fd.append('author', author.value);
if (proj) fd.append('project_id', String(proj));
codeForm(fd, blocks);
const c = await api('/changes', { method: 'POST', form: fd });
submitted(c);
location.hash = `#/change/${c.id}`;
});
},
},
code.el,
h('label', {}, 'Which bullets does it fix?'), fixes,
h('label', {}, 'Title'), title,
h('label', {}, 'Notes for the reviewer'), desc,
h('details', { class: 'more-options' }, h('summary', {}, 'More options'),
state.projects.length > 1 && [h('label', {}, 'Project'), (() => {
const sel = projectSelect('', { onchange: (v) => (proj = v ? Number(v) : null) });
sel.prepend(h('option', { value: '', selected: true }, 'Same as the bullets it fixes (or my last project)'));
sel.value = '';
return sel;
})()],
h('label', {}, 'Written against (version, branch or commit)'), baseRef,
h('label', {}, 'Commit author'), author,
h('p', { class: 'small muted', style: 'margin-top:4px' }, 'Only admins see this. Leave empty to be credited by your display name with a no-reply address. A format-patch series keeps the authors it already has.')),
h('div', { class: 'row end', style: 'margin-top:12px' }, send)));
}
async function viewChange(id) {
const [c] = await Promise.all([api(`/changes/${id}`), loadProjects()]);
const mine = c.author.id === state.me.id;
const open = ['pending', 'needs_work'].includes(c.status);
const noteEl = (n) => h('div', { class: `ev ${n.author.role === 'admin' ? 'admin' : ''} ${n.status_to ? 'status' : ''}` },
h('div', { class: 'head' }, userLink(n.author, 22), n.author.role === 'admin' && h('span', { class: 'via' }, 'admin'), n.author.id === c.author.id && h('span', { class: 'via op' }, 'author'),
viaTag(n.via, n.via_label), n.status_to && [h('span', {}, n.status_to === 'pending' && n.author.id === c.author.id ? `revision ${n.revision} →` : 'marked'), changeTag(n.status_to)], h('span', {}, ago(n.created))),
n.body && h('div', { class: 'body' }, n.body));
const noteTa = h('textarea', { placeholder: c.status === 'needs_work' && mine ? 'Answer the review, or send a new revision below' : 'Questions, test results, review remarks…', style: 'min-height:80px' });
const noteBtn = h('button', { class: 'primary', type: 'submit' }, 'Comment');
const noteForm = h('form', { class: 'card', onsubmit: (e) => { e.preventDefault(); busy(noteBtn, async () => { await api(`/changes/${id}/notes`, { method: 'POST', body: { body: noteTa.value } }); route(); }); } },
h('h3', {}, 'Review discussion'), noteTa, h('div', { class: 'row end', style: 'margin-top:10px' }, noteBtn));
let reviseBox = null;
if (mine && open) {
const code = codeBlocks([...(c.patch ? [{ path: '', content: c.patch }] : []), ...c.snippets]);
const note = h('textarea', { placeholder: 'What changed in this revision', style: 'min-height:60px' });
const t = h('input', { type: 'text', value: c.title });
const btn = h('button', { class: 'primary', type: 'submit' }, 'Send revision');
reviseBox = h('details', { class: 'card' }, h('summary', {}, h('b', {}, '✎ Revise this change')),
h('form', { onsubmit: (e) => { e.preventDefault(); busy(btn, async () => {
const fd = new FormData();
if (t.value !== c.title) fd.append('title', t.value);
fd.append('note', note.value);
codeForm(fd, code.get());
await api(`/changes/${id}/revise`, { method: 'POST', form: fd });
toast('Back in the review queue');
route();
}); } }, h('label', {}, 'Title'), t, code.el, h('label', {}, 'Note for the reviewers'), note,
h('div', { class: 'row', style: 'margin-top:10px' },
h('button', { type: 'button', class: 'danger small', onclick: async () => { if (confirm(`Withdraw ${c.ref}? Admins will skip it.`)) { await api(`/changes/${id}/withdraw`, { method: 'POST', body: {} }).catch((e) => toast(e.message, true)); route(); } } }, 'Withdraw'),
h('span', { class: 'spacer' }), btn)));
}
let adminBox = null;
if (isAdmin() && c.status !== 'withdrawn') {
let pick = c.status === 'pending' ? 'accepted' : c.status;
const fixIssues = h('input', { type: 'checkbox', checked: true });
const version = h('input', { type: 'text', placeholder: 'Landed in version, e.g. 1.4.1', maxlength: 40, style: 'max-width:240px', hidden: pick !== 'accepted' });
const fixWrap = h('label', { class: 'check', style: 'margin:0', hidden: pick !== 'accepted' || !c.fixes.length }, fixIssues, `Also flag ${c.fixes.map((f) => f.ref).join(', ')} as fixed`);
const pickBtns = ['pending', 'needs_work', 'accepted', 'declined'].map((s) => h('button', { type: 'button', class: `small ${s === pick ? 'sel' : ''}`, 'data-s': s, onclick: () => { pick = s; pickBtns.forEach((b) => b.classList.toggle('sel', b.dataset.s === s)); fixWrap.hidden = s !== 'accepted' || !c.fixes.length; version.hidden = s !== 'accepted'; } }, changeTag(s)));
const msg = h('textarea', { placeholder: 'Message to the author: what landed, what to change, why declined…', style: 'min-height:80px' });
const btn = h('button', { class: 'primary', type: 'submit' }, 'Mark it');
adminBox = h('form', { class: 'card admin-box', onsubmit: (e) => { e.preventDefault(); busy(btn, async () => {
await api('/admin/changes/review', { method: 'POST', body: { ids: [c.id], status: pick, message: msg.value, version: version.value, fix_issues: pick === 'accepted' && fixIssues.checked } });
toast(`${c.ref} → ${CHANGE[pick]}`);
route();
}); } },
h('h3', {}, '⚡ Admin: review'), h('div', { class: 'status-pick' }, pickBtns), msg,
h('div', { class: 'row', style: 'margin-top:10px' }, version, fixWrap,
h('button', { type: 'button', class: 'danger small', onclick: async () => { if (confirm(`Delete ${c.ref} forever?`)) { await api(`/changes/${id}`, { method: 'DELETE' }); location.hash = '#/code'; } } }, 'Delete'),
h('span', { class: 'spacer' }), btn));
}
return layout('code',
h('p', {}, h('a', { href: '#/code' }, '← code changes')),
h('div', { class: 'card loud' },
h('div', { class: 'row' }, h('span', { class: 'ref' }, c.ref), projTag(c.project), changeTag(c.status), viaTag(c.via, c.via_label), c.revision > 1 && h('span', { class: 'small muted' }, `revision ${c.revision}`),
h('span', { class: 'spacer' }), c.has_patch && h('a', { class: 'btn small', href: `/api/changes/${c.id}/patch` }, '⬇ .mbox'), c.snippet_count > 0 && h('a', { class: 'btn small', href: `/api/changes/${c.id}/patch?format=md` }, '⬇ code .md')),
h('div', { class: 'item-text' }, c.title),
c.description && h('div', { class: 'ch-desc' }, linkify(c.description)),
h('div', { class: 'muted small row', style: 'gap:6px' }, 'Submitted by', userLink(c.author, 20), `· ${new Date(c.created).toLocaleString()}`, diffStat(c)),
(c.base || c.commit_author) && h('div', { class: 'small muted', style: 'margin-top:6px' }, c.base && ['Made against ', h('code', {}, c.base)], c.base && c.commit_author && ' · ', c.commit_author && ['commit author ', h('code', {}, c.commit_author)]),
c.fixes.length > 0 && h('div', { style: 'margin-top:12px' }, h('div', { class: 'small muted' }, 'Fixes:'),
h('ul', { class: 'bullets' }, c.fixes.map((f) => h('li', { onclick: () => (location.hash = `#/item/${f.id}`) }, h('div', { class: 'txt' }, h('span', { class: 'ref' }, f.ref), ' ', f.text), statusTag(f.status))))),
h('details', { class: 'ch-files' }, h('summary', {}, `${c.files.length} file${c.files.length === 1 ? '' : 's'} touched`), h('ul', {}, c.files.map((f) => h('li', {}, h('code', {}, f)))))),
warnBox(c),
adminBox,
c.snippets.length > 0 && [h('h2', {}, 'The code'),
h('p', { class: 'small muted' }, 'Sent as code without a diff. The paths are the author\'s hints; put it in place by hand or with your coding agent.'),
c.snippets.map((sn, i) => h('div', { class: 'snippet' },
h('div', { class: 'snippet-head' }, sn.path ? h('code', {}, sn.path) : h('span', { class: 'muted' }, `Snippet ${i + 1} (no file given)`), h('span', { class: 'spacer' }),
h('button', { type: 'button', class: 'small ghost', onclick: () => { navigator.clipboard?.writeText(sn.content); toast('Copied'); } }, 'Copy')),
sn.note && h('p', { class: 'small snippet-note' }, sn.note),
sn.replaces && [h('div', { class: 'snippet-label d-del' }, '− replace this'), codePre(sn.replaces, 'old'), h('div', { class: 'snippet-label d-add' }, '+ with this')],
codePre(sn.content)))],
c.patch && [h('h2', {}, 'The diff'),
h('p', { class: 'small muted' }, 'To apply just this one: download the .mbox above and run ', h('code', {}, `git am --patch-format=mboxrd -3 ${c.ref}.mbox`), '.'),
diffView(c.patch)],
reviseBox,
h('h2', {}, `Discussion${c.notes.length ? ` (${c.notes.length})` : ''}`),
c.notes.length ? h('div', { class: 'timeline' }, c.notes.map(noteEl)) : h('p', { class: 'muted' }, 'No review yet.'),
noteForm,
);
}
/* ---------------- board ---------------- */
const announcementLinks = (p) => p.type === 'announcement' && p.bullets?.length
? h('div', { class: 'row announcement-links' }, 'Bullets: ', p.bullets.map((b) =>
h('a', { href: `#/item/${b.id}`, onclick: (e) => e.stopPropagation(), title: b.text }, b.ref))) : null;
function pollBlock(p, onVote) {
return h('div', {},
p.options.map((o) => {
const pct = p.total_votes ? Math.round((o.votes / p.total_votes) * 100) : 0;
return h('button', {
class: `opt ${p.my_vote === o.id ? 'mine' : ''}`, type: 'button',
onclick: async (e) => { e.stopPropagation(); const np = await api(`/posts/${p.id}/vote`, { method: 'POST', body: { option_id: o.id } }); onVote(np); },
}, h('div', { class: 'bar', style: `width:${pct}%` }), h('span', {}, (p.my_vote === o.id ? '✓ ' : '') + o.text), h('span', {}, `${pct}% · ${o.votes}`));
}),
h('div', { class: 'small muted' }, `${p.total_votes} vote${p.total_votes === 1 ? '' : 's'} · tap to (re)vote`));
}
async function viewBoard() {
const board = (location.hash.split('?b=')[1] || 'main') === 'offtopic' ? 'offtopic' : 'main';
const posts = await api(`/posts?board=${board}`);
let type = 'post';
const title = h('input', { type: 'text', placeholder: board === 'offtopic' ? 'Share something fun: a meme, a song, a cat…' : 'Title', maxlength: 200 });
const body = h('textarea', { placeholder: board === 'offtopic' ? 'Paste a link (YouTube, articles…) and PIKKIE makes a preview' : 'Say something to your fellow testers…', style: 'min-height:80px' });
const version = h('input', { type: 'text', placeholder: 'Release version, e.g. 1.4.3 (optional)', maxlength: 60 });
const bullets = h('input', { type: 'text', placeholder: 'Linked bullets, e.g. PK-20, PK-21 (optional)' });
const announceFields = h('div', { hidden: true }, h('label', {}, 'Release version'), version, h('label', {}, 'Fixed or related bullets'), bullets);
const imgs = fileCollector('🖼 Add images: drop, pick, or paste', false);
const optsBox = h('div', { hidden: true });
const optInputs = [];
const addOpt = () => { const i = h('input', { type: 'text', placeholder: `Option ${optInputs.length + 1}`, maxlength: 200, style: 'margin-bottom:6px' }); optInputs.push(i); optsBox.insertBefore(i, addOptBtn); };
const addOptBtn = h('button', { type: 'button', class: 'small', onclick: addOpt }, '+ option');
optsBox.append(h('label', {}, 'Poll options'), addOptBtn);
addOpt(); addOpt();
const types = board === 'main' && isAdmin() ? ['post', 'poll', 'announcement'] : ['post', 'poll'];
const tabs = types.map((t) => h('button', { type: 'button', class: t === type ? 'on' : '', onclick: () => {
type = t; tabs.forEach((b, i) => b.classList.toggle('on', types[i] === t));
optsBox.hidden = t !== 'poll'; announceFields.hidden = t !== 'announcement'; imgs.el.hidden = t === 'announcement';
btn.textContent = t === 'announcement' ? 'Publish announcement' : 'Post it';
} }, t === 'post' ? '✍ Post' : t === 'poll' ? '📊 Poll' : '📣 Announcement'));
const btn = h('button', { class: 'primary', type: 'submit' }, 'Post it');
const list = h('div', {});
const renderList = () => list.replaceChildren(...(posts.length ? [h('div', { class: 'board-grid' }, posts.map((p, i) => {
const imgs = p.attachments.filter((x) => x.inline);
const cover = imgs[0]?.url || p.previews.find((x) => x.image)?.image;
const coverIsVideo = !imgs.length && p.previews.find((x) => x.image)?.kind === 'video';
return h('div', { class: `bcard ${p.pinned ? 'pinned' : ''} ${cover ? 'has-cover' : 'no-cover'}`, onclick: () => (location.hash = `#/post/${p.id}`) },
cover && h('div', { class: 'bcover', onclick: (e) => { if (imgs.length) { e.stopPropagation(); lightbox(imgs.map((x) => x.url), 0); } } },
h('img', { src: cover, alt: '', loading: 'lazy' }),
coverIsVideo && h('span', { class: 'lp-play' }, '▶'),
imgs.length > 1 && h('span', { class: 'bcount' }, `🖼 ${imgs.length}`),
p.pinned && h('span', { class: 'bpin' }, '📌')),
h('div', { class: 'bbody' },
h('div', { class: 'row', style: 'gap:6px' }, !cover && p.pinned && '📌', p.type !== 'post' && h('span', { class: `kind ${p.type}` }, p.type === 'announcement' ? '📣 ANNOUNCEMENT' : 'POLL'), h('b', { class: 'btitle' }, p.title)),
p.release_version && h('div', { class: 'small muted' }, `Release v${p.release_version}`),
p.body && h('p', { class: 'bsnip' }, linkify(p.body.length > 220 ? p.body.slice(0, 220) + '…' : p.body)),
announcementLinks(p),
!imgs.length && previews(p.previews.slice(0, 1).map((x) => ({ ...x, image: null }))),
p.type === 'poll' && pollBlock(p, (np) => { posts[i] = { ...p, ...np }; renderList(); }),
h('div', { class: 'bmeta' }, userLink(p.author, 20), h('span', { class: 'spacer' }), h('span', {}, `${ago(p.created)} · 💬 ${p.reply_count}`))));
}))] : [h('div', { class: 'empty' }, board === 'offtopic' ? 'No fun yet. Post a meme, be the change.' : 'Quiet in here. Start some noise.')]));
renderList();
return layout('board',
h('h1', {}, 'The ', h('span', { class: 'hl' }, board === 'offtopic' ? 'off-topic' : 'board')),
h('p', { class: 'sub' }, board === 'offtopic' ? 'Not about bugs. Memes, music, pets, links. Keep it friendly.' : 'Chat, rant, vote. Be nice-ish.'),
h('div', { class: 'tabs' },
h('button', { class: board === 'main' ? 'on' : '', onclick: () => (location.hash = '#/board') }, '📣 Main board'),
h('button', { class: board === 'offtopic' ? 'on' : '', onclick: () => (location.hash = '#/board?b=offtopic') }, '🎸 Off-topic')),
h('form', {
class: 'card tape',
onsubmit: async (e) => {
e.preventDefault();
await busy(btn, async () => {
if (type === 'announcement') {
await api('/announcements', { method: 'POST', body: { title: title.value, body: body.value,
version: version.value, bullets: bullets.value.split(/[\s,]+/).filter(Boolean) } });
toast('Announcement published 📣');
} else {
const fd = new FormData();
fd.append('board', board); fd.append('type', type); fd.append('title', title.value); fd.append('body', body.value);
fd.append('options', JSON.stringify(optInputs.map((i) => i.value)));
for (const f of imgs.files) fd.append('files', f, f.name);
btn.textContent = /https?:\/\//.test(body.value) ? 'Fetching previews…' : 'Posting…';
await api('/posts', { method: 'POST', form: fd });
toast('Posted 🤘');
}
route();
});
btn.textContent = type === 'announcement' ? 'Publish announcement' : 'Post it';
},
}, h('div', { class: 'tabs' }, tabs), title, h('div', { style: 'height:8px' }), body, optsBox, announceFields, imgs.el, h('div', { class: 'row end', style: 'margin-top:10px' }, btn)),
list);
}
async function viewPost(id) {
let p = await api(`/posts/${id}`);
const pollHost = h('div', {});
const drawPoll = () => p.type === 'poll' && pollHost.replaceChildren(pollBlock(p, (np) => { p = { ...p, ...np }; drawPoll(); }));
drawPoll();
const ta = h('textarea', { placeholder: 'Reply… (links get a preview)', style: 'min-height:70px' });
const imgs = fileCollector('🖼 Add images');
const btn = h('button', { class: 'primary', type: 'submit' }, 'Reply');
const mine = p.author.id === state.me.id;
const back = p.board === 'offtopic' ? '#/board?b=offtopic' : '#/board';
return layout('board',
h('p', {}, h('a', { href: back }, `← ${p.board === 'offtopic' ? 'off-topic' : 'board'}`)),
h('div', { class: 'card loud' },
h('div', { class: 'row' }, h('span', { class: `kind ${p.type}`, style: 'font-family:var(--display)' }, p.type.toUpperCase()), h('h2', { style: 'margin:0' }, p.title), h('span', { class: 'spacer' }),
isAdmin() && h('button', { class: 'small', onclick: async () => { await api(`/posts/${id}/pin`, { method: 'POST', body: { pinned: !p.pinned } }); route(); } }, p.pinned ? 'Unpin' : '📌 Pin'),
(mine || isAdmin()) && h('button', { class: 'small danger', onclick: async () => { if (confirm('Delete this post?')) { await api(`/posts/${id}`, { method: 'DELETE' }); location.hash = back; } } }, 'Delete')),
h('div', { class: 'small muted row', style: 'gap:6px;margin-top:6px' }, userLink(p.author, 22), `· ${new Date(p.created).toLocaleString()}`),
gallery(p.attachments, { hero: true }),
p.body && h('p', { style: 'white-space:pre-wrap;font-size:16px' }, linkify(p.body)),
p.release_version && h('p', { class: 'small muted' }, `Release v${p.release_version}`),
announcementLinks(p),
previews(p.previews),
pollHost),
h('div', { class: 'timeline' }, p.replies.map((r) => h('div', { class: 'ev' },
h('div', { class: 'head' }, userLink(r.author, 22), h('span', {}, ago(r.created)),
(r.author.id === state.me.id || isAdmin()) && h('button', { class: 'small ghost', onclick: async () => { await api(`/replies/${r.id}`, { method: 'DELETE' }); route(); } }, '×')),
r.body && h('div', { class: 'body' }, linkify(r.body)),
gallery(r.attachments),
previews(r.previews)))),
h('form', {
class: 'card', onsubmit: async (e) => {
e.preventDefault();
await busy(btn, async () => {
const fd = new FormData();
fd.append('body', ta.value);
for (const f of imgs.files) fd.append('files', f, f.name);
await api(`/posts/${id}/replies`, { method: 'POST', form: fd });
route();
});
},
}, ta, imgs.el, h('div', { class: 'row end', style: 'margin-top:10px' }, btn)));
}
/* ---------------- download ---------------- */
async function viewDownload() {
const apk = await api('/apk');
return layout('download',
h('h1', {}, 'PIKKIE in your ', h('span', { class: 'hl' }, 'pocket')),
connectCard(),
h('div', { class: 'card loud apk-hero' },
h('img', { src: '/logo.svg', alt: '' }),
h('div', { style: 'flex:1;min-width:240px' },
apk.available
? [h('h2', {}, `Android app ${apk.version ? 'v' + apk.version : ''}`),
h('p', { class: 'muted' }, `Built ${ago(apk.uploaded)} · ${size(apk.size)}`),
h('a', { class: 'btn primary big-dl', href: apk.url }, '⬇ Download APK')]
: [h('h2', {}, 'No APK yet'), h('p', { class: 'muted' }, 'No build in the repo yet. Check back soon.')])),
h('div', { class: 'card' }, h('h3', {}, 'Installing'),
h('ol', {}, h('li', {}, 'Download the APK on your Android phone.'), h('li', {}, 'Allow "install unknown apps" for your browser when asked.'),
h('li', {}, 'Open PIKKIE and scan your QR code from above, or enter this server address: ', h('code', {}, location.origin), ' ', copyButton(() => location.origin, 'Address', 'Copy server address')), h('li', {}, 'Or log in with the same account (2FA works too).'))));
}
/* ---------------- profile (2FA, API keys, MCP) ---------------- */
async function viewProfile() {
const me = state.me = await api('/me');
const parts = [];
if (me.needs_2fa_setup) {
parts.push(h('div', { class: 'card loud' }, h('h2', {}, '🔒 2FA required'), h('p', {}, 'Your admins require two-factor authentication. Set it up below to continue using PIKKIE.')));
}
// --- 2FA
const tfa = h('div', { class: 'card' });
const draw2fa = () => {
if (state.me.totp_enabled) {
const pw = h('input', { type: 'password', placeholder: 'Password', autocomplete: 'current-password' });
const code = h('input', { type: 'text', placeholder: 'Current code', inputmode: 'numeric' });
tfa.replaceChildren(h('h2', {}, 'Two-factor auth ', h('span', { class: 'st st-fixed' }, 'on')),
h('p', { class: 'muted' }, 'Your account asks for a code from your authenticator app at login.'),
state.status.enforce_2fa === 'all' || (state.status.enforce_2fa === 'admins' && isAdmin())
? h('p', { class: 'small muted' }, 'Required by your admins, so it cannot be turned off.')
: h('details', {}, h('summary', {}, 'Turn off 2FA'), h('div', { class: 'grid2' }, pw, code),
h('button', { class: 'danger small', style: 'margin-top:10px', onclick: async (e) => busy(e.target, async () => { await api('/2fa/disable', { method: 'POST', body: { password: pw.value, code: code.value } }); state.me.totp_enabled = false; toast('2FA turned off'); draw2fa(); }) }, 'Turn off')));
} else {
const start = h('button', { class: 'primary', onclick: async (e) => busy(e.target, async () => {
const s = await api('/2fa/setup', { method: 'POST' });
const svg = new DOMParser().parseFromString(s.qr_svg, 'image/svg+xml').documentElement;
const code = h('input', { type: 'text', inputmode: 'numeric', autocomplete: 'one-time-code', placeholder: '123456', maxlength: 6 });
const confirmBtn = h('button', { class: 'primary', onclick: async (ev) => busy(ev.target, async () => {
const r = await api('/2fa/enable', { method: 'POST', body: { code: code.value } });
state.me.totp_enabled = true;
state.me.needs_2fa_setup = false;
tfa.replaceChildren(h('h2', {}, '2FA is on 🎉'), h('p', {}, 'Save these one-time recovery codes somewhere safe. Each works once if you lose your phone.'),
h('div', { class: 'codes' }, r.recovery_codes.map((c) => h('span', {}, c))),
h('div', { class: 'row', style: 'margin-top:12px' }, h('button', { onclick: () => { navigator.clipboard?.writeText(r.recovery_codes.join('\n')); toast('Copied'); } }, 'Copy'), h('button', { class: 'primary', onclick: () => route() }, 'Done')));
}) }, 'Confirm');
tfa.replaceChildren(h('h2', {}, 'Set up 2FA'), h('div', { class: 'row', style: 'align-items:flex-start;gap:22px' },
h('div', { class: 'qr' }, document.importNode(svg, true)),
h('div', { style: 'flex:1;min-width:220px' }, h('p', {}, 'Scan with any authenticator (Aegis, 2FAS, Google Authenticator, 1Password…). Or type the secret:'),
h('div', { class: 'secret' }, s.secret), h('label', {}, 'Code from the app'), code, h('div', { class: 'row', style: 'margin-top:10px' }, confirmBtn))));
code.focus();
}) }, 'Set up 2FA');
tfa.replaceChildren(h('h2', {}, 'Two-factor auth ', h('span', { class: 'st st-declined' }, 'off')), h('p', { class: 'muted' }, 'Add a second lock with an authenticator app.'), start);
}
};
draw2fa();
parts.push(tfa);
if (!me.needs_2fa_setup) {
// --- profile
const name = h('input', { type: 'text', value: me.name, maxlength: 60 });
const bio = h('textarea', { maxlength: 500, placeholder: 'Who are you, picky one? Devices, favourite bugs, gamer tag…', style: 'min-height:70px' }, me.bio || '');
const website = h('input', { type: 'url', value: me.website || '', placeholder: 'https://…', maxlength: 200 });
const avBox = h('div', { class: 'av-edit' });
const drawAv = () => avBox.replaceChildren(avatar(state.me, 84), h('div', {},
h('button', { type: 'button', class: 'small', onclick: () => avInput.click() }, state.me.avatar ? 'Change picture' : 'Add a profile picture'),
state.me.avatar && h('button', { type: 'button', class: 'small ghost', onclick: async () => { await api('/me/avatar', { method: 'DELETE' }); state.me.avatar = null; drawAv(); } }, 'Remove')));
const avInput = h('input', { type: 'file', accept: 'image/*', hidden: true, onchange: async () => {
const f = avInput.files[0];
avInput.value = '';
if (!f) return;
try {
const blob = await shrinkImage(f, 512);
const fd = new FormData();
fd.append('avatar', blob, 'avatar.' + (blob.type === 'image/webp' ? 'webp' : 'jpg'));
state.me = await api('/me/avatar', { method: 'POST', form: fd });
drawAv();
toast('Looking sharp 😎');
} catch (e) { toast(e.message, true); }
} });
drawAv();
const cur = h('input', { type: 'password', autocomplete: 'current-password' });
const npw = h('input', { type: 'password', autocomplete: 'new-password', minlength: 10 });
parts.unshift(h('div', { class: 'grid2' },
h('div', { class: 'card' }, h('h2', {}, 'You'), avInput, avBox, h('div', { class: 'muted small', style: 'margin-top:8px' }, me.email), h('label', {}, 'Display name'), name,
h('label', {}, 'Bio'), bio, h('label', {}, 'Website'), website,
h('div', { class: 'row', style: 'margin-top:12px' }, h('a', { href: `#/u/${me.id}` }, 'View my public profile →'), h('span', { class: 'spacer' }),
h('button', { class: 'primary', onclick: async (e) => busy(e.target, async () => { state.me = await api('/me', { method: 'PATCH', body: { name: name.value, bio: bio.value, website: website.value } }); toast('Saved'); }) }, 'Save'))),
h('div', { class: 'card' }, h('h2', {}, 'Password'), h('label', {}, 'Current'), cur, h('label', {}, 'New (10+ chars)'), npw,
h('div', { class: 'row end', style: 'margin-top:12px' }, h('button', { onclick: async (e) => busy(e.target, async () => { await api('/me/password', { method: 'POST', body: { current: cur.value, password: npw.value } }); cur.value = npw.value = ''; toast('Password changed'); }) }, 'Change')))));
parts.push(h('div', { class: 'card' }, h('div', { class: 'row' },
h('div', { style: 'flex:1;min-width:200px' }, h('h2', { style: 'margin:0' }, '🎓 Tutorial'), h('p', { class: 'muted', style: 'margin:4px 0 0' }, 'Forgot where things are? Take the 60-second tour again.')),
h('button', { class: 'primary', onclick: () => startTour() }, '▶ Replay tutorial'))));
parts.push(await prefsCard());
parts.push(await apiKeysCard());
}
if (!me.needs_2fa_setup) parts.unshift(connectCard());
return layout('profile', h('h1', {}, 'Your ', h('span', { class: 'hl' }, 'profile')), parts);
}
/* downscale a picked image on the client (avatars) */
async function shrinkImage(file, max) {
const img = await createImageBitmap(file).catch(() => { throw new Error('That image could not be read'); });
const scale = Math.min(1, max / Math.max(img.width, img.height));
const c = document.createElement('canvas');
c.width = Math.round(img.width * scale);
c.height = Math.round(img.height * scale);
c.getContext('2d').drawImage(img, 0, 0, c.width, c.height);
const blob = await new Promise((r) => c.toBlob(r, 'image/webp', 0.85));
return blob && blob.type === 'image/webp' ? blob : new Promise((r) => c.toBlob(r, 'image/jpeg', 0.85));
}
async function prefsCard() {
const r = await api('/me/prefs');
let prefs = r.prefs;
const save = async (key, ch, val) => {
prefs = (await api('/me/prefs', { method: 'PUT', body: { prefs: { [key]: { [ch]: val } } } })).prefs;
toast(val ? 'Opted in ✔' : 'Opted out');
};
const box = (key, ch) => h('input', { type: 'checkbox', checked: prefs[key][ch], 'aria-label': `${key} ${ch}`, onchange: (e) => save(key, ch, e.target.checked).catch((err) => toast(err.message, true)) });
return h('div', { class: 'card' }, h('h2', {}, '🔔 Notifications'),
h('p', { class: 'muted', style: 'margin-top:0' }, 'Everything lands in the 🔔 inbox up top. E-mail and phone alerts are opt-in: nothing is sent until you tick it.'),
!r.smtp && h('p', { class: 'small', style: 'color:var(--warn)' }, 'Heads up: this server has no e-mail set up yet, so e-mail alerts will wait until an admin configures SMTP.'),
h('div', { class: 'tablewrap' }, h('table', { class: 'prefs' },
h('tr', {}, h('th', {}, 'When…'), h('th', {}, '📧 E-mail'), h('th', {}, '📱 Phone')),
r.events.map((ev) => h('tr', {}, h('td', {}, ev.label, ev.admin && h('span', { class: 'via', style: 'margin-left:6px' }, 'admin')), h('td', {}, box(ev.key, 'email')), h('td', {}, box(ev.key, 'app')))))),
h('p', { class: 'small muted' }, 'Phone alerts need the PIKKIE Android app (Me → Notifications).'));
}
async function viewUser(id) {
const u = await api(`/users/${id}`);
const mine = u.id === state.me.id;
const stat = (n, l) => h('div', { class: 'stat', style: 'cursor:default' }, h('b', {}, n), h('span', {}, l));
return layout(mine ? 'profile' : '',
h('div', { class: 'card loud profile-hero' },
avatar(u, 120),
h('div', { style: 'flex:1;min-width:220px' },
h('h1', { style: 'margin:0' }, u.name, ' ', u.role === 'admin' && h('span', { class: 'st st-finished', style: 'font-size:13px;vertical-align:middle' }, 'admin')),
h('p', { class: 'muted small', style: 'margin:4px 0 10px' }, `picky since ${new Date(u.joined).toLocaleDateString()}`),
u.bio ? h('p', { style: 'white-space:pre-wrap' }, linkify(u.bio)) : h('p', { class: 'muted' }, mine ? 'No bio yet. Tell the crew who you are.' : 'No bio yet.'),
u.website && h('p', {}, '🔗 ', h('a', { href: u.website, target: '_blank', rel: 'noopener noreferrer nofollow' }, u.website.replace(/^https?:\/\//, ''))),
mine && h('a', { class: 'btn small', href: '#/profile' }, '✎ Edit profile'))),
h('div', { class: 'stats' }, stat(u.stats.bullets, 'bullets'), stat(u.stats.resolved, 'fixed'), stat(u.stats.blockers, '12 gauges'), stat(u.stats.comments, 'comments'), stat(u.stats.posts, 'posts'), stat(u.stats.metoo, 'me toos')),
h('h2', {}, 'Latest bullets'),
h('div', { class: 'card', style: 'padding:0' }, u.recent.length ? h('ul', { class: 'bullets' }, u.recent.map(bulletRow)) : h('div', { class: 'empty' }, 'Nothing reported yet.')),
u.posts.length > 0 && [h('h2', {}, 'On the board'), h('div', { class: 'card' }, h('ul', {}, u.posts.map((p) => h('li', {}, h('a', { href: `#/post/${p.id}` }, p.title), ' ', h('span', { class: 'small muted' }, `${p.board === 'offtopic' ? '🎸 off-topic · ' : ''}${ago(p.created)}`)))))],
);
}
function connectCard() {
const card = h('div', { class: 'card loud connect' });
let timer;
const idle = () => {
clearInterval(timer);
card.replaceChildren(
h('div', { class: 'row', style: 'align-items:flex-start;gap:18px' },
h('img', { src: '/phone-cracked.svg', alt: '', class: 'cracked-phone' }),
h('div', { style: 'flex:1;min-width:220px' },
h('h2', {}, 'Connect your phone'),
h('p', { class: 'muted', style: 'margin-top:0' }, 'Scan a QR code with your phone and you are logged in to the PIKKIE app instantly. No typing server addresses or passwords. If the app is not installed yet, the same code gets you the APK.'),
h('button', { class: 'primary', onclick: show }, 'Show my QR code'))));
};
async function show(e) {
await busy(e.target, async () => {
const c = await api('/connect/new', { method: 'POST' });
const svg = new DOMParser().parseFromString(c.qr_svg, 'image/svg+xml').documentElement;
const left = h('b', {});
const tick = () => {
const s = Math.max(0, Math.round((c.expires - Date.now()) / 1000));
left.textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
if (!s) idle();
};
card.replaceChildren(h('div', { class: 'row', style: 'align-items:flex-start;gap:22px' },
h('div', { class: 'qr big' }, document.importNode(svg, true)),
h('div', { style: 'flex:1;min-width:220px' },
h('h2', {}, 'Scan me 📸'),
h('ol', {},
h('li', {}, 'Open your phone camera (or the scanner in the PIKKIE app) and point it at the code.'),
h('li', {}, 'Tap the link. No app yet? Grab the APK from that page first.'),
h('li', {}, 'Tap ', h('b', {}, 'Open in the PIKKIE app'), '. Done, you are in.')),
h('p', { class: 'small muted' }, 'Works once. Expires in ', left, '. Only show it to yourself, it logs in as you.'),
c.local && h('p', { class: 'small', style: 'color:var(--warn)' }, '⚠ This code points at localhost. Phones need the public HTTPS address: set the site URL under Admin → Sign-up & 2FA.'),
h('div', { class: 'row' }, h('button', { class: 'small', onclick: show }, 'New code'), h('button', { class: 'small ghost', onclick: idle }, 'Hide')))));
tick();
timer = setInterval(() => (document.body.contains(card) ? tick() : clearInterval(timer)), 1000);
});
}
idle();
return card;
}
function mcpSnippet(key) {
const url = `${location.origin}/mcp`;
const claude = `claude mcp add --transport http pikkie ${url} --header "Authorization: Bearer ${key}"`;
const generic = JSON.stringify({ mcpServers: { pikkie: { type: 'http', url, headers: { Authorization: `Bearer ${key}` } } } }, null, 2);
return h('div', {},
h('div', { class: 'row' }, h('label', {}, 'Claude Code'), copyButton(claude, 'Command', 'Copy Claude MCP command')),
h('pre', { class: 'code' }, claude),
h('div', { class: 'row' }, h('label', {}, 'Generic MCP client config (Cursor, Claude Desktop via mcp-remote, etc.)'), copyButton(generic, 'Config', 'Copy MCP client config')),
h('pre', { class: 'code' }, generic));
}
async function apiKeysCard() {
const keys = await api('/keys');
const card = h('div', { class: 'card' });
const name = h('input', { type: 'text', placeholder: 'Key name, e.g. "fixbot" or "my claude"', maxlength: 60 });
const reveal = h('div', {});
const draw = (list) => card.replaceChildren(
h('h2', {}, '🤖 API keys & MCP'),
h('p', { class: 'muted' }, isAdmin()
? 'Point bots at PIKKIE over MCP. Your keys are admin keys: bots can read all bullets, submit new ones, comment, and flag statuses with messages and files.'
: 'Point your own AI agent at PIKKIE over MCP. With your key it can read all bullets, submit new ones (marked "via MCP") and answer admin questions.'),
h('div', { class: 'row' }, h('div', { style: 'flex:1;min-width:200px' }, name),
h('button', { class: 'primary', onclick: async (e) => busy(e.target, async () => {
const k = await api('/keys', { method: 'POST', body: { name: name.value } });
name.value = '';
reveal.replaceChildren(h('div', { class: 'card loud', style: 'margin-top:14px' }, h('b', {}, 'Copy your key now — it will not be shown again:'),
h('div', { class: 'row', style: 'margin:8px 0' }, h('div', { class: 'secret' }, k.key), copyButton(k.key, 'Key', 'Copy API key')), mcpSnippet(k.key)));
draw(await api('/keys'));
}) }, 'Create key')),
reveal,
list.length ? h('div', { class: 'tablewrap', style: 'margin-top:14px' }, h('table', {}, h('tr', {}, h('th', {}, 'Name'), h('th', {}, 'Key'), h('th', {}, 'Created'), h('th', {}, 'Last used'), h('th', {})),
list.map((k) => h('tr', {}, h('td', {}, k.name), h('td', { class: 'mono' }, k.prefix + '…'), h('td', {}, ago(k.created)), h('td', {}, k.last_used ? ago(k.last_used) : 'never'),
h('td', {}, h('button', { class: 'small danger', onclick: async () => { if (confirm(`Revoke "${k.name}"?`)) { await api(`/keys/${k.id}`, { method: 'DELETE' }); draw(await api('/keys')); } } }, 'Revoke')))))) : null,
h('details', { style: 'margin-top:14px' }, h('summary', {}, 'Available MCP tools'),
h('ul', { class: 'small' },
h('li', {}, h('code', {}, 'list_issues'), ' · ', h('code', {}, 'get_issue'), ' · ', h('code', {}, 'stats'), ' · ', h('code', {}, 'list_projects'), ' — read bullets, timelines, admin messages; use ', h('code', {}, 'since'), ' to see what changed'),
h('li', {}, h('code', {}, 'submit_bullets'), ' — file new bullets with a project and caliber (flagged "via MCP"); ', h('code', {}, 'set_weight'), ' to re-weigh your own'),
h('li', {}, h('code', {}, 'add_comment'), ' · ', h('code', {}, 'get_attachment'), ' · ', h('code', {}, 'list_board_posts'), ' · ', h('code', {}, 'whoami')),
isAdmin() && h('li', {}, h('code', {}, 'set_status'), ' — flag open / needs_info / in_progress / fixed / finished / declined with message + files; ', h('code', {}, 'delete_issue')))));
draw(keys);
return card;
}
/* ---------------- admin ---------------- */
async function viewAdmin() {
if (!isAdmin()) return layout('admin', h('p', {}, 'Admins only.'));
const tab = (location.hash.split('?tab=')[1] || 'projects');
const tabs = [['projects', 'Projects'], ['users', 'Testers'], ['invites', 'Invites'], ['settings', 'Sign-up & 2FA'], ['mail', 'E-mail / SMTP'], ['keys', 'API keys'], ['apk', 'Android APK']];
let body;
if (tab === 'projects') body = await adminProjects();
else if (tab === 'users') body = await adminUsers();
else if (tab === 'invites') body = await adminInvites();
else if (tab === 'settings') body = await adminSettings();
else if (tab === 'mail') body = await adminMail();
else if (tab === 'keys') body = await adminKeys();
else body = await adminApk();
return layout('admin', h('h1', {}, 'Admin ', h('span', { class: 'hl' }, 'cave')),
h('div', { class: 'tabs' }, tabs.map(([k, l]) => h('button', { class: k === tab ? 'on' : '', onclick: () => (location.hash = `#/admin?tab=${k}`) }, l))), body);
}
async function adminProjects() {
const { projects } = await api('/projects?all=1');
const name = h('input', { type: 'text', placeholder: 'Project name, e.g. "iOS app" or "Website v2"', maxlength: 80 });
const desc = h('input', { type: 'text', placeholder: 'Short description (optional)', maxlength: 500 });
const color = h('input', { type: 'color', value: '#ff2e93', style: 'width:60px;height:42px;padding:2px' });
const patch = (p, body, msg) => api(`/admin/projects/${p.id}`, { method: 'PATCH', body }).then(() => { toast(msg); route(); }).catch((e) => toast(e.message, true));
return h('div', {},
h('div', { class: 'card tape' }, h('h2', {}, 'New project'),
h('p', { class: 'muted small' }, 'Testers pick a project once; PIKKIE remembers it for their next reports (web, Android and MCP).'),
h('div', { class: 'row' }, h('div', { style: 'flex:1;min-width:180px' }, name), h('div', { style: 'flex:2;min-width:180px' }, desc), color,
h('button', { class: 'primary', onclick: async (e) => busy(e.target, async () => { await api('/admin/projects', { method: 'POST', body: { name: name.value, description: desc.value, color: color.value } }); toast('Project created'); route(); }) }, 'Create'))),
h('div', { class: 'card tablewrap' }, h('table', {},
h('tr', {}, ['Project', 'Description', 'Open', 'Total', ''].map((t) => h('th', {}, t))),
projects.map((p) => h('tr', { style: p.archived ? 'opacity:.5' : '' },
h('td', {}, projTag(p), p.archived && h('span', { class: 'small muted' }, ' archived')), h('td', { class: 'small' }, p.description), h('td', {}, p.open_count), h('td', {}, p.item_count),
h('td', {}, h('div', { class: 'row' },
h('button', { class: 'small', onclick: () => { const n = prompt('Rename project', p.name); if (n) patch(p, { name: n }, 'Renamed'); } }, 'Rename'),
h('button', { class: 'small', onclick: () => { const d = prompt('Description', p.description); if (d !== null) patch(p, { description: d }, 'Saved'); } }, 'Describe'),
h('a', { class: 'btn small', href: `#/?project=${p.id}` }, 'View'),
h('button', { class: 'small', onclick: () => patch(p, { archived: !p.archived }, p.archived ? 'Restored' : 'Archived') }, p.archived ? 'Restore' : 'Archive'))))))));
}
async function adminInvites() {
const [invites, settings] = await Promise.all([api('/admin/invites'), api('/admin/settings')]);
const emails = h('textarea', { placeholder: 'one@tester.com, two@tester.com\nthree@tester.com', style: 'min-height:90px' });
const msg = h('textarea', { placeholder: 'Personal note (optional): what you want them to test, links, deadlines…', style: 'min-height:70px' });
const role = h('select', { style: 'width:auto' }, h('option', { value: 'tester' }, 'as tester'), h('option', { value: 'admin' }, 'as admin'));
const out = h('div', {});
const copyBtn = (link) => h('button', { class: 'small', onclick: () => { navigator.clipboard?.writeText(link); toast('Invite link copied'); } }, '📋 Copy link');
const LABEL = { sent: '📬 sent', link_only: '🔗 link only', exists: 'already a user', invalid: 'not an e-mail' };
return h('div', {},
h('div', { class: 'card loud tape' }, h('h2', {}, 'Invite testers'),
!settings.smtp_host && h('p', { class: 'small', style: 'color:var(--warn)' }, '⚠ SMTP is not set up, so invites are not mailed. You get a link per person to send yourself. ', h('a', { href: '#/admin?tab=mail' }, 'Set up SMTP')),
h('label', {}, 'E-mail addresses (comma, space or one per line)'), emails,
h('label', {}, 'Message'), msg,
h('div', { class: 'row', style: 'margin-top:12px' }, role, h('span', { class: 'small muted' }, 'Links work once, for 7 days, even when open sign-up is off.'), h('span', { class: 'spacer' }),
h('button', { class: 'primary', onclick: async (e) => busy(e.target, async () => {
const r = await api('/admin/invites', { method: 'POST', body: { emails: emails.value, message: msg.value, role: role.value } });
emails.value = '';
out.replaceChildren(h('div', { class: 'card' }, h('h3', {}, 'Results'), h('table', {}, r.results.map((x) =>
h('tr', {}, h('td', {}, x.email), h('td', {}, LABEL[x.status] || x.status, x.error ? h('div', { class: 'small muted' }, x.error) : null), h('td', {}, x.link && copyBtn(x.link)))))));
const sent = r.results.filter((x) => x.status === 'sent').length;
toast(sent ? `${sent} invite${sent > 1 ? 's' : ''} sent 📬` : 'Invites created — copy the links');
}) }, 'Send invites'))),
out,
h('div', { class: 'card tablewrap' }, h('h2', {}, 'Invites'),
invites.length ? h('table', {}, h('tr', {}, ['E-mail', 'Role', 'State', 'By', 'Sent', ''].map((t) => h('th', {}, t))),
invites.map((i) => h('tr', { style: i.state !== 'pending' ? 'opacity:.6' : '' },
h('td', {}, i.email), h('td', {}, i.role), h('td', {}, h('span', { class: `st ${i.state === 'accepted' ? 'st-fixed' : i.state === 'expired' ? 'st-declined' : 'st-needs_info'}` }, i.state)),
h('td', {}, i.inviter || '—'), h('td', {}, i.sent ? ago(i.sent) : 'not mailed'),
h('td', {}, i.state !== 'accepted' && h('div', { class: 'row' },
h('button', { class: 'small', onclick: async (e) => busy(e.target, async () => {
const r = await api(`/admin/invites/${i.id}/resend`, { method: 'POST' });
if (r.status === 'sent') toast('Re-sent 📬'); else { navigator.clipboard?.writeText(r.link); toast('New link copied (not mailed)'); }
route();
}) }, i.state === 'expired' ? 'Renew' : 'Resend'),
h('button', { class: 'small danger', onclick: async () => { if (confirm(`Revoke invite for ${i.email}?`)) { await api(`/admin/invites/${i.id}`, { method: 'DELETE' }); route(); } } }, 'Revoke')))))) : h('p', { class: 'muted' }, 'No invites yet.')));
}
async function adminUsers() {
const users = await api('/admin/users');
const email = h('input', { type: 'email', placeholder: 'email' });
const name = h('input', { type: 'text', placeholder: 'name' });
const pw = h('input', { type: 'text', placeholder: 'initial password (10+)' });
const role = h('select', {}, h('option', { value: 'tester' }, 'tester'), h('option', { value: 'admin' }, 'admin'));
const invite = h('input', { type: 'checkbox', checked: true });
const patch = (u, body, msg) => api(`/admin/users/${u.id}`, { method: 'PATCH', body }).then(() => { toast(msg); route(); }).catch((e) => toast(e.message, true));
return h('div', {},
h('div', { class: 'card tape' }, h('h2', {}, 'Add a tester'), h('div', { class: 'grid2' }, email, name, pw, role),
h('div', { class: 'row', style: 'margin-top:10px' }, h('label', { class: 'check', style: 'margin:0' }, invite, 'Send welcome e-mail'), h('span', { class: 'spacer' }),
h('button', { class: 'primary', onclick: async (e) => busy(e.target, async () => { await api('/admin/users', { method: 'POST', body: { email: email.value, name: name.value, password: pw.value, role: role.value, send_invite: invite.checked } }); toast('Added'); route(); }) }, 'Add'))),
h('div', { class: 'card tablewrap' }, h('table', {},
h('tr', {}, ['Name', 'E-mail', 'Role', '2FA', 'Bullets', 'Joined', ''].map((t) => h('th', {}, t))),
users.map((u) => h('tr', { style: u.disabled ? 'opacity:.5' : '' },
h('td', {}, u.name), h('td', {}, u.email), h('td', {}, u.role === 'admin' ? h('span', { class: 'st st-finished' }, 'admin') : 'tester'),
h('td', {}, u.totp_enabled ? '✅' : '—'), h('td', {}, u.item_count), h('td', {}, ago(u.created_at)),
h('td', {}, u.id !== state.me.id && h('div', { class: 'row' },
h('button', { class: 'small', onclick: () => patch(u, { role: u.role === 'admin' ? 'tester' : 'admin' }, 'Role changed') }, u.role === 'admin' ? 'Make tester' : 'Make admin'),
h('button', { class: 'small', onclick: () => patch(u, { disabled: !u.disabled }, u.disabled ? 'Enabled' : 'Disabled') }, u.disabled ? 'Enable' : 'Disable'),
u.totp_enabled && h('button', { class: 'small', onclick: () => confirm(`Reset 2FA for ${u.name}?`) && patch(u, { reset_2fa: true }, '2FA reset') }, 'Reset 2FA'),
h('button', { class: 'small', onclick: () => { const p = prompt(`New password for ${u.name} (10+ chars)`); if (p) patch(u, { password: p }, 'Password set'); } }, 'Set password'))))))));
}
async function adminSettings() {
const s = await api('/admin/settings');
const signup = h('input', { type: 'checkbox', checked: s.signup_enabled === '1' });
const enforce = h('select', {}, [['off', 'Optional for everyone'], ['admins', 'Required for admins'], ['all', 'Required for everyone']].map(([v, l]) => h('option', { value: v, selected: s.enforce_2fa === v }, l)));
const site = h('input', { type: 'url', value: s.site_url, placeholder: 'https://pikkie.example.com' });
return h('div', { class: 'card' },
h('h2', {}, 'Access'),
h('label', { class: 'check' }, signup, 'Open sign-up (anyone with the link can create a tester account)'),
h('label', {}, 'Two-factor policy'), enforce,
h('p', { class: 'small muted' }, 'When required, users without 2FA are sent to set it up before they can do anything else.'),
h('label', {}, 'Public site URL (used in e-mail links)'), site,
h('p', { class: 'small muted', style: 'margin-top:14px' }, 'Admins choose their own alerts (new bullets, answers…) under Profile → Notifications.'),
h('div', { class: 'row end', style: 'margin-top:14px' }, h('button', { class: 'primary', onclick: async (e) => busy(e.target, async () => {
await api('/admin/settings', { method: 'PUT', body: { signup_enabled: signup.checked ? '1' : '0', enforce_2fa: enforce.value, site_url: site.value} });
state.status = await api('/status');
toast('Saved');
}) }, 'Save')));
}
async function adminMail() {
const s = await api('/admin/settings');
const f = {
smtp_host: h('input', { type: 'text', value: s.smtp_host, placeholder: 'smtp.example.com' }),
smtp_port: h('input', { type: 'number', value: s.smtp_port }),
smtp_user: h('input', { type: 'text', value: s.smtp_user, autocomplete: 'off' }),
smtp_pass: h('input', { type: 'password', placeholder: s.smtp_pass_set ? '•••••• (saved, leave blank to keep)' : '', autocomplete: 'new-password' }),
smtp_from: h('input', { type: 'text', value: s.smtp_from }),
};
const secure = h('input', { type: 'checkbox', checked: s.smtp_secure === '1' });
const to = h('input', { type: 'email', placeholder: state.me.email });
return h('div', { class: 'grid2' },
h('div', { class: 'card' }, h('h2', {}, 'SMTP'),
h('label', {}, 'Host'), f.smtp_host, h('label', {}, 'Port'), f.smtp_port,
h('label', { class: 'check', style: 'margin-top:12px' }, secure, 'Use implicit TLS (port 465). Off = STARTTLS when offered.'),
h('label', {}, 'Username'), f.smtp_user, h('label', {}, 'Password'), f.smtp_pass, h('label', {}, 'From'), f.smtp_from,
h('div', { class: 'row end', style: 'margin-top:14px' }, h('button', { class: 'primary', onclick: async (e) => busy(e.target, async () => {
const body = Object.fromEntries(Object.entries(f).map(([k, v]) => [k, v.value]));
body.smtp_secure = secure.checked ? '1' : '0';
await api('/admin/settings', { method: 'PUT', body });
toast('SMTP saved');
}) }, 'Save'))),
h('div', { class: 'card' }, h('h2', {}, 'Test it'), h('p', { class: 'muted' }, 'Save first, then send yourself a test mail.'), to,
h('div', { class: 'row end', style: 'margin-top:10px' }, h('button', { onclick: async (e) => busy(e.target, async () => { await api('/admin/smtp-test', { method: 'POST', body: { to: to.value } }); toast('Test mail sent 📬'); }) }, 'Send test')),
h('h3', { style: 'margin-top:20px' }, 'What gets mailed'),
h('ul', { class: 'small muted' }, h('li', {}, 'Reporter: their bullet was flagged needs info / fixed / finished / declined (with your message)'), h('li', {}, 'Reporter: an admin replied'),
h('li', {}, 'Admins: new bullets came in (toggle in Sign-up & 2FA)'), h('li', {}, 'Admins: a tester answered a "needs info" bullet'), h('li', {}, 'New testers: welcome mail when you add them'))));
}
async function adminKeys() {
const keys = await api('/admin/keys');
return h('div', { class: 'card tablewrap' }, h('h2', {}, 'All API keys'),
h('p', { class: 'muted small' }, 'Create your own keys on your profile page. Admin-owned keys unlock the admin MCP tools.'),
keys.length ? h('table', {}, h('tr', {}, ['Owner', 'Name', 'Key', 'Last used', ''].map((t) => h('th', {}, t))),
keys.map((k) => h('tr', {}, h('td', {}, k.user.name, ' ', k.user.role === 'admin' && h('span', { class: 'st st-finished' }, 'admin')), h('td', {}, k.name), h('td', { class: 'mono' }, k.prefix + '…'),
h('td', {}, k.last_used ? ago(k.last_used) : 'never'),
h('td', {}, h('button', { class: 'small danger', onclick: async () => { if (confirm('Revoke?')) { await api(`/keys/${k.id}`, { method: 'DELETE' }); route(); } } }, 'Revoke'))))) : h('p', { class: 'muted' }, 'No keys yet.'),
h('h3', { style: 'margin-top:18px' }, 'Hooking up a bot'), mcpSnippet('pk_YOUR_KEY'));
}
async function adminApk() {
const apk = await api('/apk');
return h('div', { class: 'card' }, h('h2', {}, 'Android build'),
h('p', {}, 'PIKKIE serves the newest ', h('code', {}, '.apk'), ' it finds in the repo. No uploading needed: build, and it is live.'),
apk.available
? h('p', {}, 'Serving ', h('code', {}, apk.path), ` · v${apk.version || '?'} · ${size(apk.size)} · built ${ago(apk.uploaded)}`)
: h('p', { class: 'err' }, 'No APK found yet.'),
h('label', {}, 'Searched folders'), h('pre', { class: 'code' }, (apk.searched || []).join('\n')),
h('label', {}, 'Build + publish'), h('pre', { class: 'code' }, './scripts/build-apk.sh # builds the release APK and copies it to releases/'));
}
/* ---------------- interactive tutorial (spotlight tour) ---------------- */
const TOUR = [
{ center: true, title: () => `Welcome to PIKKIE, ${state.me.name}! 🤘`, body: 'A 60-second tour of how testers report the little things. You can skip it now and replay it any time from your profile.', next: "Let's go" },
{ route: '#/', sel: '.stats', title: 'Every bullet, every tester', body: 'This is the public overview: everything anyone reported and where it stands. Click a status to filter.' },
{ route: '#/', sel: '.calfilter', parent: true, title: 'Calibers = weight', body: 'Bullets carry a caliber, from a .22 nitpick up to a 12 GAUGE blocker. Filter by caliber or sort heaviest-first.' },
{ route: '#/new', sel: '.mode-tabs', title: 'Two ways to report', body: 'Classic is a big text box. ⚡ Rapid fire is one line per bullet: type, Enter, type, Enter… Import .txt or .md lists here too.' },
{ route: '#/new', sel: 'select', title: 'Pick a project once', body: 'PIKKIE remembers your project (and caliber), so you can fire off dozens of bullets in a row.' },
{ route: '#/new', sel: '.calpicker', title: 'Default caliber', body: 'Every bullet gets this weight unless you tag a line, like "[12g] app crashes on start".' },
{ route: '#/new', sel: 'textarea.bullets, .rapid-input', title: 'Your turn: write a bullet ✍', body: 'Type anything here, one issue per line. (Nothing gets sent; this is just practice.)', interactive: (el) => el.value.trim().length > 2, waitText: 'Type first ✍' },
{ route: '#/new', sel: '.drop', title: 'Evidence welcome', body: 'Paste a screenshot, attach terminal or log text, drop files, or snap a photo on your phone.' },
{ route: '#/code', sel: '.stats-5', title: 'Got a fix? Send the code ⌥', body: () => `Got a fix? Paste the code right on a bullet, or here under Code (your bot can too, via MCP submit_change). Only the code is needed, no repo access: say where it goes if you know. A git diff works too.${isAdmin() ? ' As an admin you tick a batch, download the diffs as one mbox for git am plus a sheet with all code snippets, and accept it in one go, closing the bullets it fixes.' : ' Admins land a whole batch at once and tell you how it went.'}` },
{ route: '#/board', sel: '.tabs', title: 'The board', body: 'Chat, polls and announcements, plus 🎸 off-topic for memes, music and links (with previews).' },
{ route: '#/board', sel: '.bell', title: 'Your inbox', body: 'Status changes, replies and admin questions land here. E-mail and phone alerts are opt-in on your profile.' },
{ route: '#/download', sel: '.connect', title: 'PIKKIE in your pocket', body: 'Scan your QR code with your phone to log in to the Android app instantly. The app can also log you in on a computer.' },
{ route: '#/profile', sel: '.av-edit', title: 'Make it yours', body: 'Add a profile picture and a bio, choose your notifications, and find "Replay tutorial" here whenever you like.' },
{ center: true, title: "You're ready. Stay pikkie 🤘", body: 'Now go find some little things.', next: 'Start reporting', route: '#/new' },
];
let tourEl = null;
let tourPlace = null;
const waitForEl = async (sel, ms = 3000) => {
const t0 = Date.now();
for (;;) {
const el = [...document.querySelectorAll(sel)].find((x) => x.offsetParent !== null);
if (el || Date.now() - t0 > ms) return el || null;
await new Promise((r) => setTimeout(r, 80));
}
};
async function finishTour(done = true) {
tourEl?.remove();
tourEl = null;
if (tourPlace) { window.removeEventListener('resize', tourPlace); window.removeEventListener('scroll', tourPlace); tourPlace = null; }
if (done && state.me && !state.me.tutorial_done) {
state.me.tutorial_done = true;
api('/me', { method: 'PATCH', body: { tutorial_done: true } }).catch(() => {});
}
}
async function startTour() {
if (tourEl) return;
tourEl = h('div', { class: 'tour' });
document.body.append(tourEl);
await showTourStep(0);
}
async function showTourStep(i) {
if (!tourEl) return;
const step = TOUR[i];
if (step.route && location.hash.split('?')[0] !== step.route) {
location.hash = step.route;
await new Promise((r) => setTimeout(r, 250));
}
let target = null;
if (step.sel) {
target = await waitForEl(step.sel);
if (target && step.parent) target = target.parentElement;
if (!target) return showTourStep(i + 1 < TOUR.length ? i + 1 : i); // element missing (e.g. no projects): skip
target.scrollIntoView({ block: 'center', behavior: 'smooth' });
await new Promise((r) => setTimeout(r, 350));
}
if (!tourEl) return;
const last = i === TOUR.length - 1;
const next = h('button', { class: 'primary', onclick: () => (last ? (finishTour(true), step.route && (location.hash = step.route)) : showTourStep(i + 1)) }, step.next || (last ? 'Done' : 'Next →'));
const card = h('div', { class: `tour-card ${step.center ? 'center' : ''}`, role: 'dialog', 'aria-live': 'polite' },
step.center && i === 0 && h('img', { src: '/logo.svg', alt: '', class: 'tour-logo' }),
h('div', { class: 'tour-step' }, `${i + 1} / ${TOUR.length}`),
h('h3', {}, typeof step.title === 'function' ? step.title() : step.title),
h('p', {}, typeof step.body === 'function' ? step.body() : step.body),
h('div', { class: 'tour-dots' }, TOUR.map((_, j) => h('span', { class: j === i ? 'on' : j < i ? 'done' : '' }))),
h('div', { class: 'row', style: 'margin-top:12px' },
h('button', { class: 'small ghost', onclick: () => finishTour(true) }, i === 0 ? 'Skip tour' : 'Skip'),
h('span', { class: 'spacer' }),
i > 0 && h('button', { class: 'small', onclick: () => showTourStep(i - 1) }, '← Back'),
next));
const spot = h('div', { class: 'tour-spot' + (step.center ? ' none' : '') });
tourEl.replaceChildren(spot, card);
if (step.interactive && target) {
next.disabled = true;
next.textContent = step.waitText || 'Try it…';
const check = () => { if (step.interactive(target)) { next.disabled = false; next.textContent = 'Nice! Next →'; } };
target.addEventListener('input', check);
target.focus();
check();
}
const place = () => {
if (!tourEl || step.center || !target) return;
const r = target.getBoundingClientRect();
const pad = 8;
Object.assign(spot.style, { left: `${r.left - pad}px`, top: `${r.top - pad}px`, width: `${r.width + pad * 2}px`, height: `${r.height + pad * 2}px` });
const cw = Math.min(360, window.innerWidth - 24);
const below = r.bottom + 16 + 220 < window.innerHeight;
card.style.width = `${cw}px`;
card.style.left = `${Math.max(12, Math.min(window.innerWidth - cw - 12, r.left + r.width / 2 - cw / 2))}px`;
card.style.top = below ? `${r.bottom + 18}px` : '';
card.style.bottom = below ? '' : `${window.innerHeight - r.top + 18}px`;
card.classList.toggle('above', !below);
};
place();
if (tourPlace) { window.removeEventListener('resize', tourPlace); window.removeEventListener('scroll', tourPlace); }
tourPlace = place;
window.addEventListener('resize', place);
window.addEventListener('scroll', place, { passive: true });
document.onkeydown = (e) => { if (!tourEl) return; if (e.key === 'Escape') finishTour(true); };
}
/* ---------------- router ---------------- */
let navSeq = 0;
async function route() {
const seq = ++navSeq;
// a slow page load must not overwrite the page the user has navigated to in the meantime
const mount = (node) => { if (seq === navSeq) $app.replaceChildren(node); };
try {
if (!state.status) state.status = await api('/status');
if (!state.me) {
state.status = await api('/status');
state.me = state.status.user;
}
const invite = location.hash.match(/^#\/invite\/([\w-]+)/);
if (invite && !state.me) return mount(await viewInvite(invite[1]));
if (!state.me) return mount(viewAuth());
const path = location.hash.replace(/^#/, '').split('?')[0] || '/';
if (state.me.needs_2fa_setup && path !== '/profile') return (location.hash = '#/profile');
if (path === '/tour') { location.hash = '#/'; setTimeout(startTour, 400); return; }
let m;
if (path === '/') mount(await viewIssues());
else if (path === '/new') mount(await viewNew());
else if ((m = path.match(/^\/item\/(\d+)$/))) mount(await viewItem(m[1]));
else if (path === '/code') mount(await viewChanges());
else if (path === '/code/new') mount(await viewChangeNew());
else if ((m = path.match(/^\/change\/(\d+)$/))) mount(await viewChange(m[1]));
else if (path === '/board') mount(await viewBoard());
else if ((m = path.match(/^\/post\/(\d+)$/))) mount(await viewPost(m[1]));
else if ((m = path.match(/^\/u\/(\d+)$/))) mount(await viewUser(m[1]));
else if (path === '/download') mount(await viewDownload());
else if (path === '/profile') mount(await viewProfile());
else if (path === '/admin') mount(await viewAdmin());
else if (path.startsWith('/invite/')) mount(layout('', h('h1', {}, 'Already in'), h('p', {}, `You are logged in as ${state.me.email}. Log out first to accept an invite for someone else.`)));
else mount(layout('', h('h1', {}, '404'), h('p', {}, 'Too picky — that page does not exist.')));
if (seq !== navSeq) return; // superseded by a newer navigation
if (!tourEl) window.scrollTo(0, 0);
if (!state.me.tutorial_done && !state.me.needs_2fa_setup && !tourEl && !state.tourOffered) { state.tourOffered = true; setTimeout(startTour, 500); }
} catch (e) {
if (state.me) toast(e.message, true);
else mount(h('div', { class: 'auth' }, h('h1', {}, 'PIKKIE'), h('p', { class: 'err' }, e.message)));
}
}
window.addEventListener('hashchange', route);
route();