Files

1264 lines
62 KiB
HTML
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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<title>TaskBoard</title>
<meta name="theme-color" content="#323338">
<link rel="manifest" href="manifest.webmanifest">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="apple-mobile-web-app-title" content="TaskBoard">
<style>
:root{
--bg:#f6f7fb; --surface:#ffffff; --text:#323338; --text-dim:#676879;
--border:#d0d4e4; --border-light:#e6e9ef; --accent:#0073ea; --accent-dim:#cce5ff;
--danger:#e2445c; --shadow:0 4px 12px rgba(0,0,0,.08);
--kcol:#eceef5; --toast-bg:#323338; --toast-text:#fff;
--radius:8px;
}
html.dark{
--bg:#181b34; --surface:#232847; --text:#e6e9f5; --text-dim:#9ba2c0;
--border:#4b5178; --border-light:#343a5e; --accent:#4da9ff; --accent-dim:#1f3a5f;
--shadow:0 4px 14px rgba(0,0,0,.45);
--kcol:#1f2440; --toast-bg:#e6e9f5; --toast-text:#181b34;
}
html.dark ::placeholder{color:#6d7494}
html.dark .rows,html.dark .wk-list{box-shadow:0 1px 3px rgba(0,0,0,.3)}
html.dark .kcard{box-shadow:0 1px 3px rgba(0,0,0,.35)}
*{box-sizing:border-box;margin:0;padding:0}
html,body{height:100%}
body{
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;
background:var(--bg);color:var(--text);font-size:14px;
-webkit-font-smoothing:antialiased;
padding-top:env(safe-area-inset-top);
}
button{font:inherit;cursor:pointer;border:none;background:none;color:inherit}
input,select,textarea{font:inherit;color:inherit}
::placeholder{color:#9b9eab}
/* ---------- header ---------- */
header{
background:var(--surface);border-bottom:1px solid var(--border-light);
padding:10px 16px 0;position:sticky;top:0;z-index:50;
}
.hdr-top{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
.logo{font-size:18px;font-weight:700;display:flex;align-items:center;gap:8px}
.logo .dot{width:14px;height:14px;border-radius:4px;background:linear-gradient(135deg,#00c875,#0073ea)}
#searchBox{flex:0 1 200px;min-width:90px;border:1px solid var(--border);border-radius:6px;padding:6px 10px;background:var(--bg);color:var(--text);font:inherit;font-size:13px}
#searchBox:focus{outline:none;border-color:var(--accent)}
.sync{margin-left:auto;display:flex;align-items:center;gap:6px;color:var(--text-dim);font-size:12px}
.sync .ind{width:8px;height:8px;border-radius:50%;background:#c4c4c4}
.sync.ok .ind{background:#00c875}
.sync.dirty .ind{background:#fdab3d}
.sync.err .ind{background:#e2445c}
.icon-btn{padding:6px 8px;border-radius:6px;color:var(--text-dim);font-size:16px;line-height:1}
.icon-btn:hover{background:var(--bg)}
.tabs{display:flex;gap:2px;margin-top:8px;overflow-x:auto}
.tab{padding:8px 14px;border-radius:6px 6px 0 0;color:var(--text-dim);font-weight:500;white-space:nowrap;border-bottom:2px solid transparent}
.tab.active{color:var(--accent);border-bottom-color:var(--accent);background:var(--bg)}
.views{display:flex;gap:2px;margin-left:auto}
.view-btn{padding:8px 12px;border-radius:6px 6px 0 0;color:var(--text-dim);white-space:nowrap;border-bottom:2px solid transparent}
.view-btn.active{color:var(--text);font-weight:600;border-bottom-color:var(--text)}
main{padding:16px;max-width:1100px;margin:0 auto;padding-bottom:80px}
/* ---------- table view ---------- */
.group{margin-bottom:26px}
.group-hdr{display:flex;align-items:center;gap:8px;margin-bottom:6px}
.group-collapse{font-size:11px;width:22px;height:22px;border-radius:4px;display:flex;align-items:center;justify-content:center;transition:transform .15s}
.group.collapsed .group-collapse{transform:rotate(-90deg)}
.group-title{font-size:16px;font-weight:600;background:none;border:1px solid transparent;border-radius:4px;padding:2px 6px;min-width:60px;max-width:60vw}
.group-title:focus{border-color:var(--border);outline:none;background:var(--surface)}
.group-count{color:var(--text-dim);font-size:12px}
.group-menu-btn{color:var(--text-dim);padding:4px 8px;border-radius:4px;opacity:.5}
.group-hdr:hover .group-menu-btn{opacity:1}
.rows{background:var(--surface);border-radius:var(--radius);box-shadow:0 1px 3px rgba(0,0,0,.05);overflow:hidden}
.group.collapsed .rows,.group.collapsed .col-hdr{display:none}
.col-hdr{display:grid;grid-template-columns:1fr 130px 120px 36px;gap:0;color:var(--text-dim);font-size:11px;text-transform:uppercase;letter-spacing:.4px;padding:6px 10px 4px 14px}
.row{display:grid;grid-template-columns:1fr 130px 120px 36px;align-items:center;border-top:1px solid var(--border-light);border-left:5px solid var(--gcolor,#579bfc)}
.row:first-child{border-top:none}
.row-name{display:flex;align-items:center;gap:6px;min-width:0;padding:0 6px 0 9px}
.row-name input.item-name{flex:1;border:1px solid transparent;background:none;padding:9px 4px;border-radius:4px;min-width:0}
.row-name input.item-name:focus{outline:none;border-color:var(--border);background:var(--bg)}
.row.done-item input.item-name{color:var(--text-dim);text-decoration:line-through}
.expander{color:var(--text-dim);font-size:11px;padding:4px;border-radius:4px;flex-shrink:0;min-width:30px;text-align:left}
.expander:hover{background:var(--bg)}
.expander.has-subs{color:var(--accent);font-weight:600}
.status-cell{align-self:stretch}
.status-pill{width:100%;height:100%;min-height:38px;color:#fff;font-weight:500;font-size:13px;display:flex;align-items:center;justify-content:center;text-align:center;padding:2px 4px}
.due-cell{padding:0 8px}
.due-btn{width:100%;text-align:center;padding:8px 4px;border-radius:4px;font-size:13px;color:var(--text-dim)}
.due-btn:hover{background:var(--bg)}
.due-btn.has-date{color:var(--text)}
.due-btn.overdue{color:var(--danger);font-weight:600}
.due-btn.today{color:#fdab3d;font-weight:600}
.menu-btn{color:var(--text-dim);opacity:.4;font-size:15px;padding:6px;border-radius:4px}
.row:hover .menu-btn{opacity:1}
.menu-btn:hover{background:var(--bg)}
.drag{cursor:grab;color:var(--text-dim);opacity:0;font-size:11px;padding:2px 0 2px 2px;flex-shrink:0;user-select:none;-webkit-user-select:none}
.row:hover .drag{opacity:.55}
.row.drop-above{box-shadow:inset 0 3px 0 var(--accent)}
.row.drop-below{box-shadow:inset 0 -3px 0 var(--accent)}
.add-row.drop-above{box-shadow:inset 0 3px 0 var(--accent)}
.arch-row{display:flex;align-items:center;gap:10px;padding:8px 12px;border-top:1px solid var(--border-light);color:var(--text-dim)}
.arch-row:first-child{border-top:none}
.arch-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.arch-row .when{font-size:12px;white-space:nowrap}
.restore-btn{color:var(--accent);font-size:13px;padding:4px 8px;border-radius:4px}
.restore-btn:hover{background:var(--accent-dim)}
.arch-del{opacity:.5;padding:4px 6px}
.arch-del:hover{color:var(--danger);opacity:1}
.detail{grid-column:1/-1;background:var(--bg);border-top:1px solid var(--border-light);padding:10px 14px 12px}
.detail .sub{display:flex;align-items:center;gap:8px;padding:4px 0}
.detail .sub input[type=text]{flex:1;background:none;border:1px solid transparent;border-radius:4px;padding:4px}
.detail .sub input[type=text]:focus{outline:none;border-color:var(--border);background:var(--surface)}
.detail .sub.done input[type=text]{text-decoration:line-through;color:var(--text-dim)}
.detail .sub .x{color:var(--text-dim);opacity:.5;padding:2px 6px}
.detail .sub .x:hover{color:var(--danger);opacity:1}
.add-sub{display:flex;gap:8px;margin-top:4px}
.add-sub input{flex:1;border:1px dashed var(--border);border-radius:4px;padding:5px 8px;background:var(--surface)}
.detail textarea{width:100%;margin-top:10px;border:1px solid var(--border-light);border-radius:6px;padding:8px;background:var(--surface);resize:vertical;min-height:50px}
.add-row{display:flex;border-top:1px solid var(--border-light);border-left:5px solid transparent}
.add-row input{flex:1;border:none;background:none;padding:10px 14px}
.add-row input:focus{outline:none;background:var(--bg)}
.add-group-btn{color:var(--text-dim);border:1px dashed var(--border);border-radius:var(--radius);padding:10px 16px;width:100%;text-align:left}
.add-group-btn:hover{color:var(--accent);border-color:var(--accent)}
/* ---------- status menu ---------- */
.popmenu{position:absolute;z-index:200;background:var(--surface);border-radius:8px;box-shadow:var(--shadow);border:1px solid var(--border-light);padding:6px;display:flex;flex-direction:column;gap:4px;min-width:160px}
.popmenu button{color:#fff;font-weight:500;padding:8px;border-radius:4px;text-align:center}
.popmenu button.plain{color:var(--text);font-weight:400;text-align:left}
.popmenu button.plain:hover{background:var(--bg)}
.popmenu button.danger{color:var(--danger)}
.popmenu .pm-board{font-weight:600;font-size:13px;padding:6px 8px 2px;cursor:pointer;user-select:none}
.popmenu .pm-board:hover{color:var(--accent)}
.popmenu label.pm-grp{display:flex;align-items:center;gap:8px;padding:5px 8px 5px 16px;border-radius:4px;font-size:13px;cursor:pointer}
.popmenu label.pm-grp:hover{background:var(--bg)}
.popmenu label.pm-grp input{accent-color:var(--accent)}
.popmenu button.pm-print{background:var(--accent);margin-top:4px}
.popmenu input[type=date]{border:1px solid var(--border);border-radius:6px;padding:7px 8px;background:var(--bg);color:var(--text);font:inherit;width:100%;min-width:170px;color-scheme:light}
html.dark .popmenu input[type=date]{color-scheme:dark}
/* ---------- kanban ---------- */
.kanban{display:flex;gap:12px;overflow-x:auto;align-items:flex-start;padding-bottom:12px}
.kcol{background:var(--kcol);border-radius:var(--radius);min-width:240px;width:240px;flex-shrink:0}
.kcol-hdr{color:#fff;font-weight:600;padding:8px 12px;border-radius:var(--radius) var(--radius) 0 0;display:flex;justify-content:space-between}
.kcol-body{padding:8px;display:flex;flex-direction:column;gap:8px;min-height:60px}
.kcol.dragover .kcol-body{outline:2px dashed var(--accent);outline-offset:-4px;border-radius:6px}
.kcard{background:var(--surface);border-radius:6px;padding:10px;box-shadow:0 1px 3px rgba(0,0,0,.08);cursor:grab}
.kcard .kname{font-weight:500;margin-bottom:6px}
.kcard .kmeta{display:flex;gap:6px;flex-wrap:wrap;font-size:11px;color:var(--text-dim);align-items:center}
.gtag{padding:1px 7px;border-radius:10px;color:#fff;font-size:11px}
.kcard .due-late{color:var(--danger);font-weight:600}
/* ---------- my week ---------- */
.wk-section{margin-bottom:22px}
.wk-title{font-size:15px;font-weight:700;margin-bottom:6px;display:flex;align-items:center;gap:8px}
.wk-title .n{color:var(--text-dim);font-weight:400;font-size:12px}
.wk-list{background:var(--surface);border-radius:var(--radius);box-shadow:0 1px 3px rgba(0,0,0,.05);overflow:hidden}
.wk-item{display:flex;align-items:center;gap:10px;padding:9px 12px;border-top:1px solid var(--border-light)}
.wk-item:first-child{border-top:none}
.wk-check{width:18px;height:18px;border-radius:50%;border:2px solid var(--border);flex-shrink:0}
.wk-check.done{background:#00c875;border-color:#00c875;color:#fff;font-size:11px;display:flex;align-items:center;justify-content:center}
.wk-name{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.wk-item.is-done .wk-name{text-decoration:line-through;color:var(--text-dim)}
.wk-due{font-size:12px;color:var(--text-dim);white-space:nowrap}
.wk-due.late{color:var(--danger);font-weight:600}
.spill{font-size:12px;border-radius:10px;padding:1px 8px;color:#fff;flex-shrink:0}
.empty{color:var(--text-dim);padding:28px;text-align:center}
/* ---------- setup / settings ---------- */
.panel{max-width:480px;margin:40px auto;background:var(--surface);border-radius:12px;box-shadow:var(--shadow);padding:28px}
.panel h1{font-size:20px;margin-bottom:4px}
.panel p{color:var(--text-dim);margin-bottom:18px;line-height:1.5}
.panel label{display:block;font-weight:600;font-size:12px;margin:14px 0 4px}
.panel input{width:100%;border:1px solid var(--border);border-radius:6px;padding:9px 10px;background:var(--bg)}
.panel input:focus{outline:none;border-color:var(--accent)}
.panel .hint{font-size:12px;color:var(--text-dim);margin-top:4px;line-height:1.4}
.primary{background:var(--accent);color:#fff;font-weight:600;border-radius:6px;padding:10px 18px;margin-top:20px;width:100%}
.primary:disabled{opacity:.5;cursor:default}
.setup-msg{margin-top:12px;font-size:13px;line-height:1.4}
.setup-msg.err{color:var(--danger)}
.setup-msg.ok{color:#00a25b}
.linklike{color:var(--accent);background:none;text-decoration:underline;margin-top:14px;font-size:13px}
/* ---------- status editor ---------- */
.overlay{position:fixed;inset:0;background:rgba(0,0,0,.45);z-index:250;display:flex;align-items:flex-start;justify-content:center;padding:7vh 16px 16px;overflow:auto}
.editor{background:var(--surface);border-radius:12px;box-shadow:var(--shadow);padding:20px;width:100%;max-width:460px}
.editor h2{font-size:16px;margin-bottom:2px}
.editor .sub-h{color:var(--text-dim);font-size:12px;margin-bottom:14px}
.st-row{display:flex;align-items:center;gap:7px;margin-bottom:8px}
.st-swatch{width:32px;height:32px;border-radius:6px;flex-shrink:0;border:none;cursor:pointer}
.st-row input[type=text]{flex:1;border:1px solid var(--border);border-radius:6px;padding:7px 8px;background:var(--bg);min-width:0}
.st-done{display:flex;align-items:center;gap:4px;font-size:11px;color:var(--text-dim);white-space:nowrap;cursor:pointer}
.st-mv{color:var(--text-dim);padding:2px 3px;font-size:11px}
.st-mv:hover{color:var(--text)}
.st-x{color:var(--text-dim);padding:2px 6px}
.st-x:hover{color:var(--danger)}
.editor .foot{display:flex;gap:10px;margin-top:16px}
.editor .foot .primary{margin-top:0;flex:1}
.editor .linklike{margin-top:0;align-self:center}
.toast{position:fixed;bottom:18px;left:50%;transform:translateX(-50%);background:var(--toast-bg);color:var(--toast-text);padding:10px 18px;border-radius:8px;font-size:13px;box-shadow:var(--shadow);z-index:300;opacity:0;transition:opacity .2s;pointer-events:none;max-width:90vw}
.toast.show{opacity:1}
/* ---------- mobile ---------- */
#printview{display:none}
@media print{
body > :not(#printview){display:none !important}
html, body{background:#fff;color:#000}
#printview{display:block;color:#000;font:12px/1.45 -apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;padding:4px}
#printview h1{font-size:19px;margin:0}
#printview .pdate{color:#555;margin:1px 0 14px;font-size:11px}
#printview h2{font-size:15px;margin:16px 0 6px;border-bottom:2px solid #000;padding-bottom:3px;break-after:avoid}
#printview .pgroup{margin:0 0 12px;break-inside:avoid}
#printview h3{font-size:12px;margin:8px 0 3px}
#printview table{width:100%;border-collapse:collapse}
#printview th,#printview td{border:1px solid #999;padding:3px 7px;text-align:left;vertical-align:top;font-size:11px}
#printview th{background:#eee;font-size:10px;text-transform:uppercase;letter-spacing:.04em}
#printview .pdone{text-decoration:line-through;color:#777}
#printview .psub{margin:2px 0 0 10px;color:#333}
#printview .pnotes{margin:2px 0 0 10px;color:#555;font-style:italic}
#printview .parch{color:#666;font-size:10px;margin:4px 0 0}
}
@media (max-width:640px){
main{padding:10px}
#searchBox{order:9;flex:1 1 100%}
.hdr-top{gap:6px}
.icon-btn{padding:6px 5px}
#syncTxt{display:none}
.col-hdr{display:none}
.row{grid-template-columns:1fr 96px 34px;grid-template-rows:auto auto;padding-bottom:4px}
.row-name{grid-column:1/-1}
.status-cell{grid-row:2;grid-column:1;align-self:center;padding-left:9px}
.status-pill{min-height:26px;border-radius:4px;font-size:12px}
.due-cell{grid-row:2;grid-column:2;padding-right:2px}
.menu-btn{grid-row:2;grid-column:3;opacity:.7}
.drag{display:none}
.detail{grid-row:3;grid-column:1/-1}
.kcol{min-width:200px;width:200px}
}
</style>
</head>
<body>
<header id="header" hidden>
<div class="hdr-top">
<div class="logo"><span class="dot"></span>TaskBoard</div>
<input type="search" id="searchBox" placeholder="&#128269; Search" autocomplete="off">
<div class="sync" id="sync"><span class="ind"></span><span id="syncTxt">loading</span></div>
<button class="icon-btn" id="printBtn" title="Print backup">&#128424;&#xFE0F;</button>
<button class="icon-btn" id="themeBtn" title="Theme: auto"></button>
<button class="icon-btn" id="refreshBtn" title="Refresh from Gitea">&#x21bb;</button>
<button class="icon-btn" id="settingsBtn" title="Settings">&#9881;</button>
</div>
<div class="tabs" id="tabs"></div>
</header>
<main id="main"></main>
<div id="printview"></div>
<div class="toast" id="toast"></div>
<script>
"use strict";
/* ============================================================
TaskBoard — a Monday-inspired task manager.
Data lives as tasks.json in a private repo on git.kburchtree.cloud (Gitea),
synced via the Gitea contents API. See the data repo README for schema.
============================================================ */
const LS_CFG = "taskboard-config";
const LS_CACHE = "taskboard-cache";
const LS_DIRTY = "taskboard-dirty"; // unsaved local edits survive reloads
const LS_UI = "taskboard-ui";
const DEFAULT_STATUSES = [
{ id: "not_started", label: "Not Started", color: "#c4c4c4", done: false },
{ id: "working", label: "Working on it", color: "#fdab3d", done: false },
{ id: "stuck", label: "Stuck", color: "#e2445c", done: false },
{ id: "done", label: "Done", color: "#00c875", done: true },
];
const GROUP_COLORS = ["#579bfc","#a25ddc","#00c875","#fdab3d","#e2445c","#66ccff","#ff642e","#7f5347"];
const STATUS_COLORS = ["#c4c4c4","#fdab3d","#e2445c","#00c875","#579bfc","#a25ddc","#66ccff","#ff642e","#ffcb00","#7f5347"];
let cfg = loadJSON(LS_CFG) || null; // {token, repo, path}
let ui = loadJSON(LS_UI) || { view: "table", board: null, collapsed: {} };
if (!ui.theme) ui.theme = "auto"; // auto | dark | light
let data = null; // the tasks document
let sha = null; // git blob sha of tasks.json
let dirty = localStorage.getItem(LS_DIRTY) === "1";
let authFailed = false; // Gitea rejected the token (revoked)
let saveTimer = null;
let saving = false;
let expanded = new Set(); // expanded item ids (this session)
function loadJSON(k){ try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } }
function storeJSON(k,v){ localStorage.setItem(k, JSON.stringify(v)); }
function saveUI(){ storeJSON(LS_UI, ui); }
function uid(){ return Date.now().toString(36) + Math.random().toString(36).slice(2,7); }
function esc(s){ return String(s ?? "").replace(/[&<>"']/g, c => ({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[c])); }
function statusesFor(board){ return board.statuses || DEFAULT_STATUSES; }
function statusOf(board, id){ const ss = statusesFor(board); return ss.find(s => s.id === id) || ss[0]; }
function isDone(board, item){ return !!statusesFor(board).find(s => s.id === item.status)?.done; }
function doneStatusOf(board){ return statusesFor(board).find(s => s.done); }
// give boards their own editable status list (older files predate per-board statuses)
function migrateStatuses(){
let changed = false;
for (const b of data.boards) if (!b.statuses) { b.statuses = DEFAULT_STATUSES.map(s => ({ ...s })); changed = true; }
return changed;
}
function dateStr(offset){ const d = new Date(); d.setDate(d.getDate()+offset); return d.getFullYear()+"-"+String(d.getMonth()+1).padStart(2,"0")+"-"+String(d.getDate()).padStart(2,"0"); }
function todayStr(){ return dateStr(0); }
function fmtDue(due){
if (!due) return "+ date";
const [y,m,d] = due.split("-").map(Number);
return new Date(y, m-1, d).toLocaleDateString(undefined, { month:"short", day:"numeric" });
}
function starterData(){
return {
version: 1,
updatedAt: new Date().toISOString(),
boards: [
{ id: "work", name: "Work", statuses: DEFAULT_STATUSES.map(s => ({ ...s })), groups: [ { id: uid(), name: "To Do", color: "#579bfc", items: [] } ] },
{ id: "personal", name: "Personal", statuses: DEFAULT_STATUSES.map(s => ({ ...s })), groups: [ { id: uid(), name: "To Do", color: "#00c875", items: [] } ] },
],
};
}
/* ---------------- Gitea sync ---------------- */
const API_BASE = "https://git.kburchtree.cloud/api/v1";
function ghHeaders(token){
return { "Authorization": "token " + token, "Accept": "application/json", "Content-Type": "application/json" };
}
function contentsURL(c){ return `${API_BASE}/repos/${c.repo}/contents/${c.path}`; }
// UTF-8-safe base64
function b64encode(str){ return btoa(String.fromCharCode(...new TextEncoder().encode(str))); }
function b64decode(b64){ return new TextDecoder().decode(Uint8Array.from(atob(b64.replace(/\n/g,"")), c => c.charCodeAt(0))); }
async function ghGet(c){
const r = await fetch(contentsURL(c) + "?t=" + Date.now(), { headers: ghHeaders(c.token) });
if (r.status === 404) return { missing: true };
if (!r.ok) { const e = new Error("Gitea read failed (" + r.status + ")"); e.status = r.status; throw e; }
const j = await r.json();
return { doc: JSON.parse(b64decode(j.content)), sha: j.sha };
}
async function ghPut(c, doc, prevSha){
const body = { message: "taskboard: update tasks", content: b64encode(JSON.stringify(doc, null, 2)) };
if (prevSha) body.sha = prevSha;
const r = await fetch(contentsURL(c), { method: "PUT", headers: ghHeaders(c.token), body: JSON.stringify(body) });
if (!r.ok) { const e = new Error("Gitea write failed (" + r.status + ")"); e.status = r.status; throw e; }
return (await r.json()).content.sha;
}
function setDirty(v){
dirty = v;
try { v ? localStorage.setItem(LS_DIRTY, "1") : localStorage.removeItem(LS_DIRTY); } catch {}
}
function onAuthFail(){
authFailed = true;
setSync("err", "token expired");
render();
}
function markDirty(){
data.updatedAt = new Date().toISOString();
setDirty(true);
storeJSON(LS_CACHE, data);
setSync("dirty", "saving…");
clearTimeout(saveTimer);
saveTimer = setTimeout(saveNow, 1200);
}
async function saveNow(){
if (!dirty || saving || !cfg) return;
saving = true;
try {
try {
sha = await ghPut(cfg, data, sha);
} catch (e) {
if (e.status === 409 || e.status === 422) {
// someone else (other device / an agent) wrote since we loaded; we are
// the active editor, so re-read the sha and write our version on top
const latest = await ghGet(cfg);
sha = await ghPut(cfg, data, latest.sha);
} else throw e;
}
setDirty(false);
setSync("ok", "synced");
} catch (e) {
if (e.status === 401) { onAuthFail(); return; }
setSync("err", navigator.onLine ? "save failed" : "offline — will retry");
saveTimer = setTimeout(saveNow, 15000);
} finally {
saving = false;
}
}
async function refresh(showToast){
if (!cfg) return;
if (dirty) { await saveNow(); if (dirty) return; }
try {
setSync("", "syncing…");
const res = await ghGet(cfg);
if (res.missing) throw new Error("tasks file missing");
data = res.doc; sha = res.sha;
if (migrateStatuses()) markDirty();
storeJSON(LS_CACHE, data);
setSync("ok", "synced");
render();
if (showToast) toast("Refreshed");
} catch (e) {
if (e.status === 401) { onAuthFail(); return; }
setSync("err", navigator.onLine ? "sync error" : "offline");
}
}
function setSync(cls, txt){
const el = document.getElementById("sync");
el.className = "sync " + cls;
document.getElementById("syncTxt").textContent = txt;
}
/* ---------------- data helpers ---------------- */
function activeBoard(){
return data.boards.find(b => b.id === ui.board) || data.boards[0];
}
function findItem(id){
for (const b of data.boards) for (const g of b.groups) {
const it = g.items.find(i => i.id === id);
if (it) return { board: b, group: g, item: it };
}
return null;
}
function touch(item){ item.updatedAt = new Date().toISOString(); }
function groupById(id){
for (const b of data.boards) { const g = b.groups.find(x => x.id === id); if (g) return g; }
return null;
}
let dragItemId = null;
const archOpen = new Set(); // boards whose archive section is expanded (this session)
// move an item to tg at index (index is relative to tg BEFORE removal is adjusted)
function moveItemTo(itemId, tg, index){
const f = findItem(itemId);
if (!f || !tg) return;
const cur = f.group.items.indexOf(f.item);
f.group.items.splice(cur, 1);
if (f.group === tg && index > cur) index--;
index = Math.max(0, Math.min(index, tg.items.length));
tg.items.splice(index, 0, f.item);
// crossing boards: the status id may not exist there — remap to the
// target board's equivalent (a done status stays done-ish)
const tb = data.boards.find(bd => bd.groups.includes(tg));
if (tb !== f.board && !statusesFor(tb).some(s => s.id === f.item.status)) {
const wasDone = isDone(f.board, f.item);
f.item.status = (wasDone && doneStatusOf(tb)?.id) || statusesFor(tb)[0].id;
}
touch(f.item); markDirty(); render();
}
function archiveItem(board, group, item, save = true){
(board.archive ||= []).push({ ...item, fromGroup: group.name, archivedAt: new Date().toISOString() });
group.items = group.items.filter(i => i !== item);
if (save) { markDirty(); render(); }
}
function restoreItem(board, archId){
const i = (board.archive || []).findIndex(a => a.id === archId);
if (i < 0) return;
const { fromGroup, archivedAt, ...item } = board.archive.splice(i, 1)[0];
let g = board.groups.find(x => x.name === fromGroup) || board.groups[0];
if (!g) { g = { id: uid(), name: fromGroup || "Restored", color: GROUP_COLORS[0], items: [] }; board.groups.push(g); }
item.updatedAt = new Date().toISOString();
g.items.push(item);
markDirty(); render();
toast("Restored to " + g.name);
}
/* ---------------- rendering ---------------- */
const main = document.getElementById("main");
function render(){
closeMenu();
if (!cfg || authFailed) { document.getElementById("header").hidden = true; renderSetup(authFailed ? cfg : undefined); return; }
if (!data) return;
const typing = captureTyping();
document.getElementById("header").hidden = false;
renderTabs();
if (ui.view === "kanban") renderKanban();
else if (ui.view === "week") renderWeek();
else renderTable();
restoreTyping(typing);
}
// Re-rendering rebuilds main's DOM, which would discard text the user is
// mid-typing (background sync re-renders every 90s). Capture the focused
// field before a render and restore text + caret + focus after.
function captureTyping(){
const a = document.activeElement;
if (!a || !main.contains(a) || (a.tagName !== "INPUT" && a.tagName !== "TEXTAREA") || a.type === "checkbox") return null;
let sel = null;
for (const k of ["irename","grename","subrename","notes"])
if (a.dataset[k] !== undefined) sel = `[data-${k}="${a.dataset[k]}"]`;
if (!sel) {
const f = a.closest("[data-additem],[data-addsub]");
if (f) sel = (f.dataset.additem ? `[data-additem="${f.dataset.additem}"]` : `[data-addsub="${f.dataset.addsub}"]`) + " input";
}
return sel ? { sel, value: a.value, start: a.selectionStart, end: a.selectionEnd } : null;
}
function restoreTyping(t){
if (!t) return;
const el = main.querySelector(t.sel);
if (!el) return;
el.value = t.value;
el.focus();
try { el.setSelectionRange(t.start, t.end); } catch {}
}
function renderTabs(){
const t = document.getElementById("tabs");
t.innerHTML =
data.boards.map(b =>
`<button class="tab ${activeBoard().id===b.id && ui.view!=="week" ? "active":""}" data-board="${b.id}">${esc(b.name)}</button>`
).join("") +
`<div class="views">
<button class="view-btn ${ui.view==="table"?"active":""}" data-view="table">Table</button>
<button class="view-btn ${ui.view==="kanban"?"active":""}" data-view="kanban">Kanban</button>
<button class="view-btn ${ui.view==="week"?"active":""}" data-view="week">My Week</button>
</div>`;
t.querySelectorAll("[data-board]").forEach(el => el.onclick = () => {
ui.board = el.dataset.board;
if (ui.view === "week") ui.view = "table";
saveUI(); render();
});
t.querySelectorAll("[data-view]").forEach(el => el.onclick = () => { ui.view = el.dataset.view; saveUI(); render(); });
}
/* ----- search ----- */
let searchQ = "";
function matchesQ(it, q){
return (it.name + " " + (it.notes || "") + " " + (it.subitems || []).map(s => s.name).join(" ")).toLowerCase().includes(q);
}
/* ----- table view ----- */
function renderTable(){
const b = activeBoard();
const q = searchQ.trim().toLowerCase();
let html = "";
let shown = 0;
for (const g of b.groups) {
const items = q ? g.items.filter(it => matchesQ(it, q)) : g.items;
if (q && !items.length) continue;
shown += items.length;
const collapsed = !q && ui.collapsed[g.id];
html += `<div class="group ${collapsed?"collapsed":""}" style="--gcolor:${g.color}">
<div class="group-hdr">
<button class="group-collapse" data-collapse="${g.id}" style="color:${g.color}">&#9660;</button>
<input class="group-title" style="color:${g.color}" value="${esc(g.name)}" data-grename="${g.id}">
<span class="group-count">${q ? items.length + "/" + g.items.length : g.items.length}</span>
<button class="group-menu-btn" data-gmenu="${g.id}">&#8943;</button>
</div>
<div class="col-hdr"><span>Task</span><span style="text-align:center">Status</span><span style="text-align:center">Due</span><span></span></div>
<div class="rows">`;
for (const it of items) html += rowHTML(b, g, it);
if (!q) html += `<form class="add-row" data-additem="${g.id}"><input placeholder="+ Add task" autocomplete="off"></form>`;
html += `</div></div>`;
}
if (q) {
const archMatches = (b.archive || []).filter(a => matchesQ(a, q));
if (!shown && !archMatches.length) html = `<div class="empty">No matches for &ldquo;${esc(searchQ.trim())}&rdquo; on ${esc(b.name)}</div>`;
if (archMatches.length) html += archiveHTML(archMatches, true);
main.innerHTML = html;
wireTable(b);
return;
}
const doneCount = b.groups.reduce((n,g) => n + g.items.filter(i => isDone(b, i)).length, 0);
if (doneCount) html += `<button class="add-group-btn" id="archDone" style="margin-bottom:10px">&#128230; Archive all done tasks (${doneCount})</button>`;
html += `<button class="add-group-btn" id="addGroup">+ Add group</button>`;
const arch = b.archive || [];
if (arch.length) html += archiveHTML(arch, archOpen.has(b.id));
main.innerHTML = html;
wireTable(b);
}
function archiveHTML(arch, open){
return `<div class="group ${open?"":"collapsed"}" style="margin-top:26px">
<div class="group-hdr">
<button class="group-collapse" data-archtoggle="${activeBoard().id}" style="color:var(--text-dim)">&#9660;</button>
<span style="font-size:16px;font-weight:600;color:var(--text-dim);padding:2px 6px">Archive</span>
<span class="group-count">${arch.length}</span>
</div>
<div class="rows">` +
arch.slice().reverse().map(a => `<div class="arch-row">
<span class="arch-name">${esc(a.name)}</span>
<span class="gtag" style="background:var(--text-dim)">${esc(a.fromGroup || "")}</span>
<span class="when">${esc(fmtDue((a.archivedAt||"").slice(0,10)))}</span>
<button class="restore-btn" data-restore="${a.id}">Restore</button>
<button class="arch-del" data-archdel="${a.id}" title="Delete forever">&#10005;</button>
</div>`).join("") +
`</div></div>`;
}
function rowHTML(b, g, it){
const st = statusOf(b, it.status);
const subs = it.subitems || [];
const doneSubs = subs.filter(s => s.done).length;
const isExp = expanded.has(it.id);
const dueCls = dueClass(b, it);
let html = `<div class="row ${isDone(b,it)?"done-item":""}" data-row="${it.id}" data-g="${g.id}">
<div class="row-name">
<span class="drag" draggable="true" data-drag="${it.id}" title="Drag to move">&#10495;</span>
<button class="expander ${subs.length?"has-subs":""}" data-expand="${it.id}" title="Subitems & notes">${subs.length ? doneSubs+"/"+subs.length : (isExp?"&#9650;":"&#9656;")}</button>
<input class="item-name" value="${esc(it.name)}" data-irename="${it.id}">
</div>
<div class="status-cell"><button class="status-pill" style="background:${st.color}" data-status="${it.id}">${esc(st.label)}</button></div>
<div class="due-cell"><button class="due-btn ${it.due?"has-date":""} ${dueCls}" data-due="${it.id}">${esc(fmtDue(it.due))}</button></div>
<button class="menu-btn" data-imenu="${it.id}" title="Task actions">&#8943;</button>`;
if (isExp) {
html += `<div class="detail">`;
for (const s of subs) html += `<div class="sub ${s.done?"done":""}">
<input type="checkbox" ${s.done?"checked":""} data-subtoggle="${it.id}:${s.id}">
<input type="text" value="${esc(s.name)}" data-subrename="${it.id}:${s.id}">
<button class="x" data-subdel="${it.id}:${s.id}">&#10005;</button></div>`;
html += `<form class="add-sub" data-addsub="${it.id}"><input placeholder="+ Add subitem" autocomplete="off"></form>
<textarea placeholder="Notes…" data-notes="${it.id}">${esc(it.notes||"")}</textarea></div>`;
}
return html + `</div>`;
}
function dueClass(b, it){
if (!it.due || isDone(b, it)) return "";
const t = todayStr();
if (it.due < t) return "overdue";
if (it.due === t) return "today";
return "";
}
function wireTable(b){
main.querySelectorAll("[data-collapse]").forEach(el => el.onclick = () => {
const id = el.dataset.collapse;
ui.collapsed[id] = !ui.collapsed[id]; saveUI(); render();
});
main.querySelectorAll("[data-grename]").forEach(el => el.onchange = () => {
const g = b.groups.find(x => x.id === el.dataset.grename);
if (g && el.value.trim()) { g.name = el.value.trim(); markDirty(); }
});
main.querySelectorAll("[data-gmenu]").forEach(el => el.onclick = (e) => groupMenu(e, b, el.dataset.gmenu));
main.querySelectorAll("[data-additem]").forEach(f => f.onsubmit = (e) => {
e.preventDefault();
const name = f.querySelector("input").value.trim();
if (!name) return;
const g = b.groups.find(x => x.id === f.dataset.additem);
const now = new Date().toISOString();
g.items.push({ id: uid(), name, status: statusesFor(b)[0].id, due: null, notes: "", subitems: [], createdAt: now, updatedAt: now });
f.querySelector("input").value = "";
markDirty(); render();
main.querySelector(`[data-additem="${g.id}"] input`)?.focus();
});
main.querySelectorAll("[data-irename]").forEach(el => el.onchange = () => {
const f = findItem(el.dataset.irename);
if (f && el.value.trim()) { f.item.name = el.value.trim(); touch(f.item); markDirty(); }
});
main.querySelectorAll("[data-status]").forEach(el => el.onclick = (e) => statusMenu(e, el.dataset.status));
main.querySelectorAll("[data-due]").forEach(el => el.onclick = (e) => dueMenu(e, el.dataset.due));
main.querySelectorAll("[data-imenu]").forEach(el => el.onclick = (e) => itemMenu(e, el.dataset.imenu));
// --- drag & drop: reorder within a group, drop into another group ---
const clearCues = () => main.querySelectorAll(".drop-above,.drop-below").forEach(el => el.classList.remove("drop-above","drop-below"));
main.querySelectorAll("[data-drag]").forEach(h => {
h.addEventListener("dragstart", (e) => {
dragItemId = h.dataset.drag;
e.dataTransfer.setData("text/plain", dragItemId);
e.dataTransfer.effectAllowed = "move";
});
h.addEventListener("dragend", () => { dragItemId = null; clearCues(); });
});
main.querySelectorAll(".row").forEach(row => {
row.addEventListener("dragover", (e) => {
if (!dragItemId || row.dataset.row === dragItemId) return;
e.preventDefault(); clearCues();
const r = row.getBoundingClientRect();
row.classList.add(e.clientY < r.top + r.height/2 ? "drop-above" : "drop-below");
});
row.addEventListener("drop", (e) => {
if (!dragItemId || row.dataset.row === dragItemId) return;
e.preventDefault();
const r = row.getBoundingClientRect();
const before = e.clientY < r.top + r.height/2;
const tg = groupById(row.dataset.g);
const ti = tg.items.findIndex(i => i.id === row.dataset.row);
moveItemTo(dragItemId, tg, before ? ti : ti + 1);
clearCues();
});
});
main.querySelectorAll(".add-row").forEach(f => {
f.addEventListener("dragover", (e) => { if (!dragItemId) return; e.preventDefault(); clearCues(); f.classList.add("drop-above"); });
f.addEventListener("dragleave", () => f.classList.remove("drop-above"));
f.addEventListener("drop", (e) => {
if (!dragItemId) return;
e.preventDefault();
const tg = groupById(f.dataset.additem);
moveItemTo(dragItemId, tg, tg.items.length);
clearCues();
});
});
// --- archive ---
const ad = document.getElementById("archDone");
if (ad) ad.onclick = () => {
for (const g of [...b.groups]) for (const it of [...g.items]) if (isDone(b, it)) archiveItem(b, g, it, false);
markDirty(); render();
toast("Done tasks archived");
};
main.querySelectorAll("[data-archtoggle]").forEach(el => el.onclick = () => {
const id = el.dataset.archtoggle;
archOpen.has(id) ? archOpen.delete(id) : archOpen.add(id);
render();
});
main.querySelectorAll("[data-restore]").forEach(el => el.onclick = () => restoreItem(b, el.dataset.restore));
main.querySelectorAll("[data-archdel]").forEach(el => el.onclick = () => {
const a = (b.archive || []).find(x => x.id === el.dataset.archdel);
if (!a) return;
if (!confirm(`Permanently delete "${a.name}"?`)) return;
b.archive = b.archive.filter(x => x.id !== a.id);
markDirty(); render();
});
main.querySelectorAll("[data-expand]").forEach(el => el.onclick = () => {
const id = el.dataset.expand;
expanded.has(id) ? expanded.delete(id) : expanded.add(id);
render();
});
main.querySelectorAll("[data-subtoggle]").forEach(el => el.onchange = () => {
const [iid, sid] = el.dataset.subtoggle.split(":");
const f = findItem(iid);
const s = f?.item.subitems.find(x => x.id === sid);
if (s) { s.done = el.checked; touch(f.item); markDirty(); render(); }
});
main.querySelectorAll("[data-subrename]").forEach(el => el.onchange = () => {
const [iid, sid] = el.dataset.subrename.split(":");
const f = findItem(iid);
const s = f?.item.subitems.find(x => x.id === sid);
if (s && el.value.trim()) { s.name = el.value.trim(); touch(f.item); markDirty(); }
});
main.querySelectorAll("[data-subdel]").forEach(el => el.onclick = () => {
const [iid, sid] = el.dataset.subdel.split(":");
const f = findItem(iid);
if (f) { f.item.subitems = f.item.subitems.filter(x => x.id !== sid); touch(f.item); markDirty(); render(); }
});
main.querySelectorAll("[data-addsub]").forEach(fm => fm.onsubmit = (e) => {
e.preventDefault();
const name = fm.querySelector("input").value.trim();
if (!name) return;
const f = findItem(fm.dataset.addsub);
f.item.subitems.push({ id: uid(), name, done: false });
fm.querySelector("input").value = "";
touch(f.item); markDirty(); render();
main.querySelector(`[data-addsub="${f.item.id}"] input`)?.focus();
});
main.querySelectorAll("[data-notes]").forEach(el => el.onchange = () => {
const f = findItem(el.dataset.notes);
if (f) { f.item.notes = el.value; touch(f.item); markDirty(); }
});
const ag = document.getElementById("addGroup");
if (ag) ag.onclick = () => {
const color = GROUP_COLORS[b.groups.length % GROUP_COLORS.length];
b.groups.push({ id: uid(), name: "New Group", color, items: [] });
markDirty(); render();
};
}
function dueMenu(e, itemId){
e.stopPropagation();
const f = findItem(itemId);
if (!f) return;
let changed = false;
const m = openMenu(e,
`<input type="date" data-din value="${f.item.due || ""}">
<button class="plain" data-q="0">Today</button>
<button class="plain" data-q="1">Tomorrow</button>
<button class="plain" data-q="7">In a week</button>
<button class="plain" data-q="clear">No date</button>`,
() => { if (changed) render(); });
// iOS fires change on every picker-wheel tick, so commit silently and
// re-render only when the menu closes
m.querySelector("[data-din]").addEventListener("change", (ev) => {
f.item.due = ev.target.value || null;
touch(f.item); markDirty(); changed = true;
});
m.querySelectorAll("[data-q]").forEach(el => el.onclick = () => {
f.item.due = el.dataset.q === "clear" ? null : dateStr(+el.dataset.q);
touch(f.item); markDirty(); changed = true;
closeMenu();
});
}
/* ----- menus ----- */
let menuEl = null;
let menuOnClose = null;
function closeMenu(){
if (!menuEl) return;
menuEl.remove(); menuEl = null;
const cb = menuOnClose; menuOnClose = null;
if (cb) cb();
}
function openMenu(e, html, onClose){
closeMenu();
menuOnClose = onClose || null;
menuEl = document.createElement("div");
menuEl.className = "popmenu";
menuEl.innerHTML = html;
document.body.appendChild(menuEl);
const r = e.currentTarget.getBoundingClientRect();
const w = menuEl.offsetWidth;
menuEl.style.left = Math.min(r.left, window.innerWidth - w - 8) + "px";
menuEl.style.top = Math.min(r.bottom + 4, window.innerHeight - menuEl.offsetHeight - 8) + window.scrollY + "px";
setTimeout(() => document.addEventListener("click", onDocClick), 0);
function onDocClick(ev){ if (!menuEl || !menuEl.contains(ev.target)) { closeMenu(); document.removeEventListener("click", onDocClick); } }
return menuEl;
}
function statusMenu(e, itemId){
e.stopPropagation();
const f = findItem(itemId);
if (!f) return;
const m = openMenu(e,
statusesFor(f.board).map(s => `<button style="background:${s.color}" data-set="${s.id}">${esc(s.label)}</button>`).join("") +
`<button class="plain" data-customize>&#9881; Customize statuses…</button>`);
m.querySelectorAll("[data-set]").forEach(el => el.onclick = () => {
f.item.status = el.dataset.set; touch(f.item); markDirty(); render();
});
m.querySelector("[data-customize]").onclick = () => { closeMenu(); statusEditor(f.board); };
}
function itemMenu(e, itemId){
e.stopPropagation();
const f = findItem(itemId);
if (!f) return;
const moveBtns = data.boards
.flatMap(b => b.groups.map(g => ({ b, g })))
.filter(x => x.g.id !== f.group.id)
.map(x => `<button class="plain" data-mv="${x.g.id}">&#8594; ${esc(x.b.name)}: ${esc(x.g.name)}</button>`)
.join("");
const m = openMenu(e,
`<button class="plain" data-act="up">Move up</button>
<button class="plain" data-act="down">Move down</button>
${moveBtns}
<button class="plain" data-act="arch">&#128230; Archive</button>
<button class="plain danger" data-act="del">Delete</button>`);
m.querySelector('[data-act="up"]').onclick = () => {
const i = f.group.items.indexOf(f.item);
if (i > 0) moveItemTo(itemId, f.group, i - 1);
};
m.querySelector('[data-act="down"]').onclick = () => {
const i = f.group.items.indexOf(f.item);
if (i < f.group.items.length - 1) moveItemTo(itemId, f.group, i + 2);
};
m.querySelectorAll("[data-mv]").forEach(el => el.onclick = () => {
const tg = groupById(el.dataset.mv);
moveItemTo(itemId, tg, tg.items.length);
toast("Moved to " + tg.name);
});
m.querySelector('[data-act="arch"]').onclick = () => archiveItem(f.board, f.group, f.item);
m.querySelector('[data-act="del"]').onclick = () => {
if (!confirm(`Delete "${f.item.name}"? (Archive keeps it recoverable)`)) return;
f.group.items = f.group.items.filter(i => i.id !== f.item.id);
markDirty(); render();
};
}
function groupMenu(e, board, groupId){
e.stopPropagation();
const g = board.groups.find(x => x.id === groupId);
const colorBtns = GROUP_COLORS.map(c => `<button data-color="${c}" style="background:${c};height:22px;flex:1;border-radius:4px"></button>`).join("");
const doneInGroup = g.items.filter(i => isDone(board, i)).length;
const m = openMenu(e,
`<div style="display:flex;gap:4px">${colorBtns}</div>
<button class="plain" data-act="up">Move up</button>
<button class="plain" data-act="down">Move down</button>
<button class="plain" data-act="sortdue">Sort by due date</button>
${doneInGroup ? `<button class="plain" data-act="archdone">&#128230; Archive done items (${doneInGroup})</button>` : ""}
<button class="plain danger" data-act="del">Delete group</button>`);
const adBtn = m.querySelector('[data-act="archdone"]');
if (adBtn) adBtn.onclick = () => {
for (const it of [...g.items]) if (isDone(board, it)) archiveItem(board, g, it, false);
markDirty(); render();
};
m.querySelectorAll("[data-color]").forEach(el => el.onclick = () => { g.color = el.dataset.color; markDirty(); render(); });
m.querySelector('[data-act="up"]').onclick = () => moveGroup(board, g, -1);
m.querySelector('[data-act="down"]').onclick = () => moveGroup(board, g, 1);
m.querySelector('[data-act="sortdue"]').onclick = () => {
// earliest due first, then undated, done tasks last; ties keep their order
const rank = it => isDone(board, it) ? 2 : (it.due ? 0 : 1);
g.items.sort((a,z) => rank(a) - rank(z) || ((a.due || "") < (z.due || "") ? -1 : (a.due || "") > (z.due || "") ? 1 : 0));
markDirty(); render();
toast("Sorted by due date");
};
m.querySelector('[data-act="del"]').onclick = () => {
if (g.items.length && !confirm(`Delete group "${g.name}" and its ${g.items.length} task(s)?`)) return;
board.groups = board.groups.filter(x => x.id !== groupId);
markDirty(); render();
};
}
function moveGroup(board, g, dir){
const i = board.groups.indexOf(g), j = i + dir;
if (j < 0 || j >= board.groups.length) return;
board.groups.splice(i, 1); board.groups.splice(j, 0, g);
markDirty(); render();
}
/* ----- kanban view ----- */
function renderKanban(){
const b = activeBoard();
const q = searchQ.trim().toLowerCase();
let html = `<div class="kanban">`;
const ss = statusesFor(b);
for (const st of ss) {
const cards = [];
for (const g of b.groups) for (const it of g.items) if (statusOf(b, it.status).id === st.id && (!q || matchesQ(it, q))) cards.push({ g, it });
html += `<div class="kcol" data-kcol="${st.id}">
<div class="kcol-hdr" style="background:${st.color}"><span>${esc(st.label)}</span><span>${cards.length}</span></div>
<div class="kcol-body">` +
cards.map(({g,it}) => `<div class="kcard" draggable="true" data-kcard="${it.id}">
<div class="kname">${esc(it.name)}</div>
<div class="kmeta"><span class="gtag" style="background:${g.color}">${esc(g.name)}</span>${it.due ? `<span class="${dueClass(b,it)==="overdue"?"due-late":""}">${esc(fmtDue(it.due))}</span>` : ""}</div>
</div>`).join("") +
`</div></div>`;
}
main.innerHTML = html + `</div>`;
main.querySelectorAll("[data-kcard]").forEach(el => {
el.addEventListener("dragstart", e => e.dataTransfer.setData("text/plain", el.dataset.kcard));
el.onclick = (e) => statusMenu(e, el.dataset.kcard);
});
main.querySelectorAll("[data-kcol]").forEach(col => {
col.addEventListener("dragover", e => { e.preventDefault(); col.classList.add("dragover"); });
col.addEventListener("dragleave", () => col.classList.remove("dragover"));
col.addEventListener("drop", e => {
e.preventDefault(); col.classList.remove("dragover");
const f = findItem(e.dataTransfer.getData("text/plain"));
if (f) { f.item.status = col.dataset.kcol; touch(f.item); markDirty(); render(); }
});
});
}
/* ----- my week view (all boards) ----- */
function renderWeek(){
const t = todayStr();
const week = new Date(); week.setDate(week.getDate() + 7);
const weekStr = week.getFullYear()+"-"+String(week.getMonth()+1).padStart(2,"0")+"-"+String(week.getDate()).padStart(2,"0");
const q = searchQ.trim().toLowerCase();
const buckets = { overdue: [], today: [], week: [], later: [], nodate: [] };
for (const b of data.boards) for (const g of b.groups) for (const it of g.items) {
if (isDone(b, it)) continue;
if (q && !matchesQ(it, q)) continue;
const entry = { b, g, it };
if (!it.due) buckets.nodate.push(entry);
else if (it.due < t) buckets.overdue.push(entry);
else if (it.due === t) buckets.today.push(entry);
else if (it.due <= weekStr) buckets.week.push(entry);
else buckets.later.push(entry);
}
for (const k of ["overdue","today","week","later"]) buckets[k].sort((a,z) => a.it.due < z.it.due ? -1 : 1);
const sections = [
["overdue", "⚠️ Overdue"], ["today", "Today"], ["week", "This Week"],
["later", "Later"], ["nodate", "No Date"],
];
let html = "";
let any = false;
for (const [key, title] of sections) {
const list = buckets[key];
if (!list.length) continue;
any = true;
html += `<div class="wk-section"><div class="wk-title">${title} <span class="n">${list.length}</span></div><div class="wk-list">` +
list.map(({b,g,it}) => `<div class="wk-item">
<button class="wk-check" data-wkdone="${it.id}" title="Mark done"></button>
<span class="wk-name">${esc(it.name)}</span>
<span class="spill" style="background:${g.color}">${esc(b.name)}</span>
<span class="wk-due ${it.due && it.due < t ? "late":""}">${it.due ? esc(fmtDue(it.due)) : ""}</span>
</div>`).join("") +
`</div></div>`;
}
main.innerHTML = any ? html : `<div class="empty">${q ? `No matches for &ldquo;${esc(searchQ.trim())}&rdquo;` : "Nothing on your plate — add tasks in the Table view 🎉"}</div>`;
main.querySelectorAll("[data-wkdone]").forEach(el => el.onclick = () => {
const f = findItem(el.dataset.wkdone);
if (!f) return;
const ds = doneStatusOf(f.board);
if (!ds) { toast("No done-type status on " + f.board.name + " — add one in Customize statuses"); return; }
f.item.status = ds.id; touch(f.item); markDirty(); render(); toast("Done: " + f.item.name);
});
}
/* ----- setup / settings ----- */
function renderSetup(existing){
const c = existing || { token: "", repo: "krburchel/taskboard-data", path: "tasks.json" };
main.innerHTML = `<div class="panel">
<h1>${authFailed ? "Reconnect TaskBoard" : existing ? "Settings" : "Welcome to TaskBoard"}</h1>
${authFailed ? `<p class="setup-msg err">Gitea rejected the saved token — it may have been revoked. Paste the current TaskBoard token below.${dirty ? " Your unsaved changes on this device are kept and will be uploaded when you reconnect." : ""}</p>` : ""}
<p>Tasks are stored as <code>tasks.json</code> in a private repo on git.kburchtree.cloud so every device (and your agents) sees the same board.</p>
<label>TaskBoard token</label>
<input id="suToken" type="password" value="${authFailed ? "" : esc(c.token)}" placeholder="Gitea token">
<div class="hint">On your Mac it's in Keychain Access as <b>TaskBoard token (Gitea)</b>. It belongs to the <b>taskboard-bot</b> account, which can only read and write the data repo.</div>
<label>Data repository</label>
<input id="suRepo" value="${esc(c.repo)}" placeholder="krburchel/taskboard-data">
<label>File path</label>
<input id="suPath" value="${esc(c.path)}">
<button class="primary" id="suGo">Connect</button>
<div class="setup-msg" id="suMsg"></div>
${existing ? `<button class="linklike" id="suSignout">Disconnect this device (clears token)</button>` : ""}
</div>`;
document.getElementById("suGo").onclick = async () => {
const c2 = {
token: document.getElementById("suToken").value.trim(),
repo: document.getElementById("suRepo").value.trim(),
path: document.getElementById("suPath").value.trim() || "tasks.json",
};
const msg = document.getElementById("suMsg");
if (!c2.token || !c2.repo.includes("/")) { msg.className = "setup-msg err"; msg.textContent = "Token and owner/repo are required."; return; }
msg.className = "setup-msg"; msg.textContent = "Connecting…";
try {
const res = await ghGet(c2);
if (res.missing) {
msg.textContent = "No tasks file yet — creating one…";
const doc = starterData();
const newSha = await ghPut(c2, doc, null);
data = doc; sha = newSha;
} else if (dirty && data) {
// edits made while disconnected: write them on top of the remote copy
sha = await ghPut(c2, data, res.sha);
} else {
data = res.doc; sha = res.sha;
}
cfg = c2; storeJSON(LS_CFG, cfg); storeJSON(LS_CACHE, data);
setDirty(false); authFailed = false;
ui.board = data.boards[0]?.id; saveUI();
setSync("ok", "synced");
render();
} catch (e) {
msg.className = "setup-msg err";
msg.textContent = "Could not connect: " + e.message + ". Check the token has Contents read/write on " + c2.repo + ".";
}
};
const so = document.getElementById("suSignout");
if (so) so.onclick = () => {
if (!confirm("Remove the token from this device? Your data on Gitea is untouched.")) return;
localStorage.removeItem(LS_CFG); localStorage.removeItem(LS_CACHE); setDirty(false); authFailed = false;
cfg = null; data = null; sha = null; render();
};
}
/* ----- status editor ----- */
function statusEditor(board){
if (!board.statuses) board.statuses = DEFAULT_STATUSES.map(s => ({ ...s }));
const ov = document.createElement("div");
ov.className = "overlay";
document.body.appendChild(ov);
const close = () => { ov.remove(); render(); };
ov.onclick = (e) => { if (e.target === ov) close(); };
function usageCount(statusId){
let n = 0;
for (const g of board.groups) n += g.items.filter(i => i.status === statusId).length;
n += (board.archive || []).filter(a => a.status === statusId).length;
return n;
}
function remap(fromId, toId){
for (const g of board.groups) for (const it of g.items) if (it.status === fromId) { it.status = toId; touch(it); }
for (const a of board.archive || []) if (a.status === fromId) a.status = toId;
}
function draw(){
const ss = board.statuses;
ov.innerHTML = `<div class="editor">
<h2>Statuses — ${esc(board.name)}</h2>
<div class="sub-h">Click the color to change it. “Done” statuses get strikethrough, leave My Week, and are picked up by Archive-all-done.</div>
${ss.map((s, i) => `<div class="st-row">
<button class="st-swatch" style="background:${s.color}" data-c="${i}" title="Change color"></button>
<input type="text" value="${esc(s.label)}" data-l="${i}">
<label class="st-done"><input type="checkbox" ${s.done?"checked":""} data-d="${i}">done</label>
<button class="st-mv" data-u="${i}" ${i===0?"disabled":""}>&#9650;</button>
<button class="st-mv" data-w="${i}" ${i===ss.length-1?"disabled":""}>&#9660;</button>
<button class="st-x" data-x="${i}" ${ss.length<=1?"disabled":""} title="Delete status">&#10005;</button>
</div>`).join("")}
<div class="foot">
<button class="linklike" id="stAdd">+ Add status</button>
<button class="primary" id="stClose">Close</button>
</div>
</div>`;
ov.querySelectorAll("[data-c]").forEach(el => el.onclick = () => {
const s = ss[+el.dataset.c];
s.color = STATUS_COLORS[(STATUS_COLORS.indexOf(s.color) + 1) % STATUS_COLORS.length];
markDirty(); draw();
});
ov.querySelectorAll("[data-l]").forEach(el => el.onchange = () => {
const s = ss[+el.dataset.l];
if (el.value.trim()) { s.label = el.value.trim(); markDirty(); }
});
ov.querySelectorAll("[data-d]").forEach(el => el.onchange = () => {
ss[+el.dataset.d].done = el.checked; markDirty();
});
ov.querySelectorAll("[data-u]").forEach(el => el.onclick = () => {
const i = +el.dataset.u; [ss[i-1], ss[i]] = [ss[i], ss[i-1]]; markDirty(); draw();
});
ov.querySelectorAll("[data-w]").forEach(el => el.onclick = () => {
const i = +el.dataset.w; [ss[i+1], ss[i]] = [ss[i], ss[i+1]]; markDirty(); draw();
});
ov.querySelectorAll("[data-x]").forEach(el => el.onclick = () => {
const i = +el.dataset.x;
const s = ss[i];
const n = usageCount(s.id);
const fallback = ss.find(x => x !== s);
if (n && !confirm(`${n} task(s) use "${s.label}" — they'll be set to "${fallback.label}". Delete it?`)) return;
remap(s.id, fallback.id);
ss.splice(i, 1);
markDirty(); draw();
});
ov.querySelector("#stAdd").onclick = () => {
ss.push({ id: uid(), label: "New Status", color: STATUS_COLORS[ss.length % STATUS_COLORS.length], done: false });
markDirty(); draw();
const inputs = ov.querySelectorAll("[data-l]");
const last = inputs[inputs.length-1];
last.focus(); last.select();
};
ov.querySelector("#stClose").onclick = close;
}
draw();
}
/* ----- theme ----- */
const darkMedia = window.matchMedia("(prefers-color-scheme: dark)");
const THEME_ICONS = { auto: "◐", dark: "☾", light: "☀︎" };
function applyTheme(){
const dark = ui.theme === "dark" || (ui.theme === "auto" && darkMedia.matches);
document.documentElement.classList.toggle("dark", dark);
document.querySelector('meta[name="theme-color"]').content = dark ? "#181b34" : "#323338";
const btn = document.getElementById("themeBtn");
btn.textContent = THEME_ICONS[ui.theme];
btn.title = "Theme: " + ui.theme;
}
document.getElementById("themeBtn").onclick = () => {
ui.theme = { auto: "dark", dark: "light", light: "auto" }[ui.theme];
saveUI(); applyTheme();
toast("Theme: " + ui.theme);
};
darkMedia.addEventListener("change", () => { if (ui.theme === "auto") applyTheme(); });
applyTheme();
/* ----- print (paper backup) ----- */
function buildPrintView(groupIds){
const picked = data.boards
.map(b => ({ b, groups: b.groups.filter(g => groupIds.has(g.id)) }))
.filter(p => p.groups.length);
const title = picked.length === 1 ? `TaskBoard — ${picked[0].b.name}` : "TaskBoard";
let html = `<h1>${esc(title)}</h1><p class="pdate">Printed ${esc(new Date().toLocaleString(undefined,{dateStyle:"full",timeStyle:"short"}))}</p>`;
for (const { b, groups } of picked) {
html += `<h2>${esc(b.name)}</h2>`;
for (const g of groups) {
html += `<div class="pgroup"><h3>${esc(g.name)} (${g.items.length})</h3>`;
if (g.items.length) {
html += `<table><tr><th style="width:58%">Task</th><th>Status</th><th>Due</th></tr>`;
for (const it of g.items) {
const subs = (it.subitems || []).map(s => `<div class="psub">${s.done ? "&#9745;" : "&#9744;"} ${esc(s.name)}</div>`).join("");
const notes = it.notes ? `<div class="pnotes">${esc(it.notes)}</div>` : "";
html += `<tr><td><span class="${isDone(b,it) ? "pdone" : ""}">${esc(it.name)}</span>${subs}${notes}</td>
<td>${esc(statusOf(b, it.status).label)}</td><td>${it.due ? esc(fmtDue(it.due)) : ""}</td></tr>`;
}
html += `</table>`;
}
html += `</div>`;
}
const arch = b.archive || [];
if (arch.length) html += `<p class="parch">+ ${arch.length} archived task${arch.length===1?"":"s"} (not printed)</p>`;
}
document.getElementById("printview").innerHTML = html;
}
document.getElementById("printBtn").onclick = (e) => {
if (!data) return;
const m = openMenu(e,
data.boards.map(b =>
`<div class="pm-board" data-bhdr="${b.id}" title="Toggle all">${esc(b.name)}</div>` +
b.groups.map(g => `<label class="pm-grp"><input type="checkbox" checked data-pg="${g.id}" data-pb="${b.id}">${esc(g.name)}</label>`).join("")
).join("") +
`<button class="pm-print" data-doprint>&#128424;&#xFE0F; Print selected</button>`);
// clicking a board name checks/unchecks all of its groups
m.querySelectorAll("[data-bhdr]").forEach(el => el.onclick = () => {
const boxes = [...m.querySelectorAll(`[data-pb="${el.dataset.bhdr}"]`)];
const all = boxes.every(x => x.checked);
boxes.forEach(x => x.checked = !all);
});
m.querySelector("[data-doprint]").onclick = () => {
const ids = new Set([...m.querySelectorAll("[data-pg]:checked")].map(x => x.dataset.pg));
if (!ids.size) { toast("Nothing selected"); return; }
buildPrintView(ids);
closeMenu();
window.print();
};
};
/* ----- toast ----- */
let toastTimer = null;
function toast(msg){
const el = document.getElementById("toast");
el.textContent = msg; el.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => el.classList.remove("show"), 2200);
}
/* ---------------- boot ---------------- */
document.getElementById("settingsBtn").onclick = () => { document.getElementById("header").hidden = true; renderSetup(cfg); };
document.getElementById("refreshBtn").onclick = () => refresh(true);
const searchBox = document.getElementById("searchBox");
searchBox.oninput = () => { searchQ = searchBox.value; render(); };
searchBox.onkeydown = (e) => { if (e.key === "Escape") { searchBox.value = ""; searchQ = ""; render(); searchBox.blur(); } };
document.addEventListener("visibilitychange", () => { if (!document.hidden && cfg && !dirty) refresh(false); });
window.addEventListener("online", () => { if (dirty) saveNow(); else refresh(false); });
setInterval(() => { if (cfg && !dirty && !document.hidden) refresh(false); }, 90000);
window.addEventListener("beforeunload", (e) => { if (dirty) { saveNow(); e.preventDefault(); } });
// Quick add via URL: ?add=Task+name[&board=work|personal][&due=today|tomorrow|YYYY-MM-DD]
// Lets an iOS Shortcut (or bookmark) capture a task without navigating the app.
function handleQuickAdd(){
const p = new URLSearchParams(location.search);
const name = (p.get("add") || "").trim();
if (!name) return;
history.replaceState(null, "", location.pathname); // strip the query so reload/restore can't double-add
if (!data) { toast("Couldn't add — no connection"); return; }
const want = (p.get("board") || "").toLowerCase();
const b = data.boards.find(x => x.id.toLowerCase() === want || x.name.toLowerCase() === want)
|| data.boards.find(x => x.id === "personal") || data.boards[0];
const g = b.groups[0];
if (!g) { toast("No group on " + b.name); return; }
let due = (p.get("due") || "").toLowerCase();
due = due === "today" ? todayStr() : due === "tomorrow" ? dateStr(1)
: /^\d{4}-\d{2}-\d{2}$/.test(due) ? due : null;
const now = new Date().toISOString();
g.items.push({ id: uid(), name, status: statusesFor(b)[0].id, due, notes: "", subitems: [], createdAt: now, updatedAt: now });
ui.board = b.id; if (ui.view === "week") ui.view = "table"; saveUI();
markDirty(); render();
toast("Added to " + b.name + ": " + name);
saveNow(); // don't wait for the debounce — iOS may kill the page quickly
}
(async function boot(){
if (!cfg) { render(); return; }
const cached = loadJSON(LS_CACHE);
if (cached) { data = cached; if (!ui.board) ui.board = data.boards[0]?.id; render(); }
await refresh(false);
handleQuickAdd();
if (!data) { // no cache and fetch failed
setSync("err", "offline");
main.innerHTML = `<div class="empty">Can’t reach git.kburchtree.cloud and no local copy yet. Connect to the internet and reload.</div>`;
}
})();
if ("serviceWorker" in navigator) navigator.serviceWorker.register("sw.js");
</script>
</body>
</html>