@pritzlaff/agile 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Main.dc.html ADDED
@@ -0,0 +1,4176 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <title>Markdown agile board</title>
6
+ <script src="./vendor/react.js"></script>
7
+ <script src="./vendor/react-dom.js"></script>
8
+ <script src="./support.js"></script>
9
+ </head>
10
+ <body>
11
+ <x-dc>
12
+ <helmet>
13
+ <link href="https://fonts.googleapis.com/css2?family=Geist:wght@400;500;600&amp;family=Geist+Mono:wght@400;500&amp;family=JetBrains+Mono:wght@400;600&amp;family=Newsreader:opsz,wght@6..72,400;6..72,600&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;family=IBM+Plex+Mono:wght@400;500;600&amp;family=Bricolage+Grotesque:wght@500;700&amp;family=Fraunces:opsz,wght@9..144,400;9..144,600&amp;display=swap" rel="stylesheet">
14
+ <style>
15
+ body{margin:0}
16
+ *{box-sizing:border-box}
17
+ .kb{position:relative;height:100vh;display:flex;flex-direction:column;overflow:hidden;background:var(--bg);color:var(--fg);font-family:var(--font);font-size:14px;line-height:1.4}
18
+ /* Zero specificity, so any component class (e.g. .kb-primary) sets its own colour. */
19
+ :where(.kb) :where(button,input,textarea,select){font:inherit;color:inherit}
20
+ .kb :focus-visible{outline:2px solid var(--accent);outline-offset:2px}
21
+ .kb-fx{position:absolute;inset:0;width:100%;height:100%;z-index:0;pointer-events:none;display:block}
22
+ .kb-fx-off{display:none}
23
+ .kb-scan{position:absolute;inset:0;z-index:40;pointer-events:none;background:repeating-linear-gradient(to bottom,transparent 0,transparent 2px,rgba(0,0,0,.28) 2px,rgba(0,0,0,.28) 3px)}
24
+ .kb-dragging,.kb-dragging *{user-select:none;cursor:grabbing}
25
+ .kb-top{position:relative;z-index:5;display:flex;flex-direction:column;gap:10px;padding:14px 20px;background:var(--header-bg);border-bottom:1px solid var(--line);backdrop-filter:var(--header-blur)}
26
+ .kb-row{display:flex;flex-wrap:wrap;align-items:center;gap:10px}
27
+ .kb-title{flex:0 1 260px;min-width:120px;border:1px solid transparent;background:transparent;font-family:var(--font-title);font-size:20px;font-weight:600;padding:4px 6px;border-radius:var(--radius);text-shadow:var(--glow)}
28
+ .kb-title:hover{border-color:var(--line)}
29
+ .kb-search{flex:1 1 260px;display:flex;align-items:center;gap:8px;min-width:180px;height:36px;padding:0 10px;border:1px solid var(--line);border-radius:var(--radius);background:var(--control)}
30
+ .kb-search input{flex:1;min-width:0;border:0;background:transparent;outline:none;height:100%}
31
+ .kb-search:focus-within{border-color:var(--accent)}
32
+ .kb-search svg{color:var(--muted);flex:none}
33
+ .kb-btn{display:inline-flex;align-items:center;gap:6px;height:36px;padding:0 12px;border:1px solid var(--line);border-radius:var(--radius);background:var(--control);cursor:pointer;white-space:nowrap}
34
+ .kb-btn:hover{border-color:var(--muted)}
35
+ .kb-btn[aria-expanded="true"]{border-color:var(--accent);color:var(--accent)}
36
+ .kb-count{display:inline-grid;place-items:center;min-width:18px;height:18px;padding:0 5px;border-radius:9px;background:var(--accent);color:var(--accent-fg);font-size:11px;font-weight:600}
37
+ .kb-seg{display:inline-flex;border:1px solid var(--line);border-radius:var(--radius);overflow:hidden;background:var(--control)}
38
+ .kb-seg-btn{height:34px;padding:0 12px;border:0;background:transparent;cursor:pointer}
39
+ .kb-seg-btn+.kb-seg-btn{border-left:1px solid var(--line)}
40
+ .kb-seg-btn[aria-pressed="true"]{background:var(--accent);color:var(--accent-fg)}
41
+ .kb-time{display:flex;align-items:center;gap:12px;padding-top:4px}
42
+ .kb-time-range{flex:1 1 auto;min-width:120px;accent-color:var(--accent,currentColor)}
43
+ .kb-time-label{flex:0 1 50%;font-family:var(--mono);font-size:12px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
44
+ .kb-past .kb-board{outline:2px dashed var(--line);outline-offset:-2px}
45
+ .kb-filters{display:flex;flex-wrap:wrap;align-items:flex-start;gap:16px 28px;padding-top:4px}
46
+ .kb-fgroup{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
47
+ .kb-flabel{font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.06em}
48
+ .kb-pills{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
49
+ .kb-pill{display:inline-flex;align-items:center;gap:4px;height:22px;padding:0 8px;border-radius:11px;font-size:12px;font-weight:500;white-space:nowrap;border:1px solid transparent}
50
+ .kb-toggle{cursor:pointer;height:28px;padding:0 10px;border-radius:14px;opacity:.75}
51
+ .kb-toggle[aria-pressed="true"]{opacity:1;box-shadow:0 0 0 2px var(--accent)}
52
+ .kb-owner-toggle{background:var(--control);border:1px solid var(--line)}
53
+ .kb-link{border:0;background:none;color:var(--accent);cursor:pointer;padding:6px 0;text-decoration:underline;text-underline-offset:3px}
54
+ .kb-muted{color:var(--muted)}
55
+ .kb-banner{position:relative;z-index:6;margin:10px 20px 0;padding:10px 14px;border-radius:var(--radius);background:var(--danger-bg);color:var(--danger-fg);display:flex;align-items:center;gap:12px;justify-content:space-between}
56
+ .kb-main{position:relative;z-index:1;flex:1;min-height:0;display:grid;grid-template-columns:minmax(0,1fr)}
57
+ .kb-mode-split{grid-template-columns:minmax(0,1fr) minmax(320px,38%)}
58
+ .kb-board{display:flex;align-items:flex-start;gap:var(--col-gap);padding:18px 20px 40px;overflow:auto;min-height:0}
59
+ .kb-locked{opacity:.45;pointer-events:none;filter:grayscale(.4)}
60
+ .kb-col{flex:none;width:var(--col-w);display:flex;flex-direction:column;gap:var(--gap);padding:var(--col-pad);border-radius:var(--radius);background:var(--surface);border:var(--col-border)}
61
+ .kb-col-head{display:flex;align-items:center;gap:4px;min-height:36px;color:var(--col-head-fg);text-shadow:var(--col-head-shadow)}
62
+ .kb-col-name{flex:1;min-width:0;border:1px solid transparent;background:transparent;font-weight:600;font-family:var(--font-title);font-size:15px;padding:4px 6px;border-radius:var(--radius);text-shadow:var(--glow)}
63
+ .kb-col-name:hover{border-color:var(--line)}
64
+ .kb-col-name:focus{background:var(--control)}
65
+ .kb-col-count{font-size:12px;color:inherit;opacity:.75;font-family:var(--mono);padding:0 4px}
66
+ .kb-icon{display:inline-grid;place-items:center;width:30px;height:30px;border:0;border-radius:var(--radius);background:transparent;cursor:pointer;color:inherit;opacity:.7;flex:none}
67
+ .kb-icon:hover:not(:disabled){opacity:1;background:var(--control)}
68
+ .kb-icon:disabled{opacity:.25;cursor:not-allowed}
69
+ .kb-grip{cursor:grab;touch-action:none}
70
+ .kb-cards{display:flex;flex-direction:column;gap:var(--gap);min-height:24px}
71
+ .kb-card{position:relative;display:flex;flex-direction:column;gap:6px;padding:var(--pad);border-radius:var(--radius);background:var(--card);color:var(--card-fg);border:1px solid var(--card-border);box-shadow:var(--card-shadow);backdrop-filter:var(--card-blur);cursor:grab;touch-action:none;user-select:none;transition:box-shadow .15s}
72
+ .kb-card:hover{box-shadow:var(--card-shadow-hover)}
73
+ .kb-card-title{all:unset;cursor:pointer;font-weight:600;font-family:var(--font-title);font-size:var(--card-title-size);line-height:1.3;text-shadow:var(--glow);overflow-wrap:anywhere}
74
+ .kb-card-title:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:2px}
75
+ .kb-card-desc{color:var(--card-muted);font-size:13px;max-height:8.6em;overflow:hidden}
76
+ .kb-card-desc.kb-desc-long{-webkit-mask-image:linear-gradient(to bottom,#000 65%,transparent);mask-image:linear-gradient(to bottom,#000 65%,transparent)}
77
+ .md{display:flex;flex-direction:column;gap:6px;min-width:0;overflow-wrap:anywhere}
78
+ .md-p,.md-h,.md-q{margin:0;white-space:pre-line}
79
+ .md-h{font-weight:600;color:var(--card-fg)}
80
+ .kb-preview .md-h{color:inherit;font-size:1.05em}
81
+ .md-q{padding-left:10px;border-left:2px solid var(--line);font-style:italic}
82
+ .md-b{font-weight:600}
83
+ .md-i{font-style:italic}
84
+ .md-s{text-decoration:line-through}
85
+ .md-code{font-family:var(--mono);font-size:.88em;padding:.05em .35em;border-radius:4px;background:var(--code-bg)}
86
+ .md-a{color:var(--accent);text-decoration:underline;text-underline-offset:2px}
87
+ .kb-card .md-a{color:inherit}
88
+ .md-pre{margin:0;padding:8px 10px;border-radius:var(--radius);background:var(--code-bg);font-family:var(--mono);font-size:12px;line-height:1.5;overflow:auto;white-space:pre}
89
+ .md-hr{width:100%;border:0;border-top:1px solid var(--line);margin:2px 0}
90
+ .md-list{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:3px}
91
+ .md-li{display:flex;align-items:flex-start;gap:7px}
92
+ .md-marker{flex:none;min-width:1em;text-align:right;opacity:.75;font-variant-numeric:tabular-nums}
93
+ .md-li input[type=checkbox]{flex:none;width:14px;height:14px;margin:2px 0 0;accent-color:var(--accent);cursor:pointer}
94
+ .md-li-body{min-width:0;white-space:pre-line}
95
+ .md-done{text-decoration:line-through;opacity:.65}
96
+ .kb-desc-head{display:flex;align-items:center;justify-content:space-between;gap:8px}
97
+ .kb-desc-head>span{font-size:12px;color:var(--panel-muted);font-weight:500}
98
+ .kb-tabs{display:inline-flex;border:1px solid var(--line);border-radius:var(--radius);overflow:hidden}
99
+ .kb-tab{height:28px;padding:0 10px;border:0;background:transparent;cursor:pointer;font-size:12px}
100
+ .kb-tab+.kb-tab{border-left:1px solid var(--line)}
101
+ .kb-tab[aria-pressed="true"]{background:var(--accent);color:var(--accent-fg)}
102
+ .kb-md-editor{display:flex;flex-direction:column;border:1px solid var(--line);border-radius:var(--radius);background:var(--control);overflow:hidden}
103
+ .kb-md-editor:focus-within{border-color:var(--accent)}
104
+ .kb-fmtbar{display:flex;flex-wrap:wrap;gap:2px;padding:4px;border-bottom:1px solid var(--line)}
105
+ .kb-fmt{display:inline-grid;place-items:center;width:32px;height:32px;border:0;border-radius:calc(var(--radius) - 2px);background:transparent;cursor:pointer;color:inherit;opacity:.75}
106
+ .kb-fmt:hover{opacity:1;background:var(--code-bg)}
107
+ .kb-fmt-sep{margin-right:8px}
108
+ .kb-md-editor textarea{border:0;border-radius:0;background:transparent;min-height:170px;font-family:var(--mono);font-size:12.5px;line-height:1.6;padding:10px 12px;resize:vertical;width:100%;outline:none}
109
+ .kb-preview{cursor:text;min-height:120px;padding:12px;border:1px solid var(--line);border-radius:var(--radius);font-size:14px;line-height:1.5}
110
+ .kb-hint{margin:0;font-size:11.5px;color:var(--panel-muted);font-family:var(--mono)}
111
+ .kb-card-foot{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap}
112
+ .kb-owner{display:inline-flex;align-items:center;gap:6px;font-size:12px;color:var(--card-muted);margin-left:auto}
113
+ .kb-avatar{display:inline-grid;place-items:center;width:22px;height:22px;border-radius:50%;font-size:10px;font-weight:600;color:var(--tag-fg)}
114
+ .kb-card-tools{position:absolute;top:6px;right:6px;display:flex;gap:4px}
115
+ .kb-card-haskids .kb-card-title{padding-right:48px}
116
+ .kb-card-fold{display:inline-flex;align-items:center;gap:2px;height:22px;padding:0 4px;border:1px solid var(--card-border);border-radius:var(--radius);background:var(--card);color:var(--card-muted);font-size:11px;cursor:pointer}
117
+ .kb-card-fold:hover{color:var(--card-fg)}
118
+ .kb-card-fold[aria-expanded="false"] svg{transform:rotate(-90deg)}
119
+ .kb-card-away{position:relative;display:flex;align-items:baseline;justify-content:space-between;gap:8px;padding:6px var(--pad);border:1.5px dotted var(--card-muted);border-radius:var(--radius);background:color-mix(in srgb,var(--card) 55%,transparent);color:var(--card-fg)}
120
+ .kb-card-away small{flex:none;color:var(--card-muted);font-size:11px}
121
+ .kb-card-away-link{all:unset;cursor:pointer;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px}
122
+ .kb-card-away-link:hover{text-decoration:underline}
123
+ .kb-card-away-link:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:2px}
124
+ .kb-card.kb-card-flash{animation:kbFlash 1.2s ease-out}
125
+ @keyframes kbFlash{0%,50%{box-shadow:0 0 0 3px var(--accent),var(--card-shadow)}100%{box-shadow:var(--card-shadow)}}
126
+ .kb-card-child{display:grid;place-items:center;width:22px;height:22px;padding:0;border:1px solid var(--card-border);border-radius:var(--radius);background:var(--card);color:var(--card-muted);cursor:pointer;opacity:0;transition:opacity .12s}
127
+ .kb-card:hover .kb-card-child,.kb-card-child:focus-visible{opacity:1}
128
+ .kb-card-child:hover{color:var(--card-fg)}
129
+ .kb-card-parent{all:unset;cursor:pointer;color:var(--card-muted);font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
130
+ .kb-card-parent:hover{color:var(--card-fg);text-decoration:underline}
131
+ .kb-card-parent:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:2px}
132
+ .kb-card.kb-card-ancestor{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent),var(--card-shadow)}
133
+ /* Tree lines: each starts in the gap above its card, so stacked rows join into one line. */
134
+ .kb-rail{position:absolute;top:calc(-1 * var(--gap) - 1px);bottom:-1px;border-left:2px solid var(--line);pointer-events:none}
135
+ .kb-rail-end{bottom:auto;height:calc(var(--gap) + 18px)}
136
+ .kb-rail-tee::after,.kb-rail-end::after{content:"";position:absolute;top:calc(var(--gap) + 16px);left:0;width:7px;border-top:2px solid var(--line)}
137
+ .kb-card-ph{border:1.5px dashed var(--accent);border-radius:var(--radius);opacity:.6;background:var(--placeholder)}
138
+ .kb-col-ph{flex:none;width:var(--col-w);border:1.5px dashed var(--accent);border-radius:var(--radius);background:var(--placeholder);opacity:.6}
139
+ .kb-add{display:flex;align-items:center;gap:6px;height:34px;padding:0 8px;border:1px dashed var(--line);border-radius:var(--radius);background:transparent;color:var(--col-head-fg);cursor:pointer;opacity:.8}
140
+ .kb-add:hover{opacity:1;border-color:var(--accent)}
141
+ .kb-add-col{flex:none;display:inline-grid;place-items:center;width:36px;height:36px;margin-top:2px;border:0;border-radius:var(--radius);background:transparent;color:var(--col-head-fg);cursor:pointer;opacity:.2;transition:opacity .15s,background .15s}
142
+ .kb-add-col:hover,.kb-add-col:focus-visible{opacity:1;background:var(--control)}
143
+ .kb-burst{position:absolute;inset:0;width:100%;height:100%;z-index:45;pointer-events:none;display:block}
144
+ @keyframes kbPop{0%{transform:scale(.6);opacity:0}60%{transform:scale(1.04);opacity:1}100%{transform:scale(1);opacity:1}}
145
+ @keyframes kbNova{0%,35%{opacity:0;transform:scale(.3);filter:blur(8px) brightness(2)}70%{opacity:1;transform:scale(1.03);filter:blur(0) brightness(1.3)}100%{opacity:1;transform:scale(1);filter:none}}
146
+ .kb-card.kb-anim-pop{animation:kbPop .45s cubic-bezier(.2,.9,.3,1.3)}
147
+ .kb-card.kb-anim-nova{animation:kbNova .9s ease-out}
148
+ @media (prefers-reduced-motion: reduce){.kb-card.kb-anim-pop,.kb-card.kb-anim-nova{animation:none}}
149
+ .kb-actions{display:flex;flex-wrap:wrap;align-items:center;gap:10px}
150
+ .kb-actions .kb-btn{height:34px}
151
+ .kb-primary{display:inline-flex;align-items:center;gap:6px;height:34px;padding:0 12px;border:1px solid var(--accent);border-radius:var(--radius);background:var(--accent);color:var(--accent-fg);cursor:pointer}
152
+ .kb-primary:disabled{opacity:.45;cursor:default}
153
+ .kb-effect{display:grid;grid-template-columns:110px minmax(0,1fr) auto;align-items:center;gap:10px;font-size:13px}
154
+ .kb-effect label{display:contents}
155
+ .kb-effect select{height:30px;border:1px solid var(--line);border-radius:6px;background:var(--control);padding:0 6px}
156
+ .kb-effect .kb-link:disabled{opacity:.35;cursor:default}
157
+ .kb-empty{margin:4px 2px;font-size:12px;color:var(--col-head-fg);opacity:.7}
158
+ .kb-ghost{position:absolute;z-index:20;pointer-events:none}
159
+ .kb-ghost .kb-card{box-shadow:0 18px 40px rgba(0,0,0,.22),0 2px 6px rgba(0,0,0,.12);transform:rotate(1.5deg);cursor:grabbing}
160
+ .kb-ghost .kb-col{box-shadow:0 18px 40px rgba(0,0,0,.22);background:var(--card);color:var(--card-fg)}
161
+ .kb-source{display:flex;flex-direction:column;min-height:0;border-left:1px solid var(--line);background:var(--source-bg);backdrop-filter:var(--header-blur)}
162
+ .kb-mode-source .kb-source{border-left:0}
163
+ .kb-source-bar{display:flex;align-items:center;gap:10px;padding:10px 16px;border-bottom:1px solid var(--line);font-family:var(--mono);font-size:12px}
164
+ .kb-source-bar .kb-status{flex:1;color:var(--muted)}
165
+ .kb-md{flex:1;min-height:0;width:100%;resize:none;border:0;outline:none;padding:16px 20px;background:transparent;font-family:var(--mono);font-size:13px;line-height:1.6;tab-size:2;white-space:pre;overflow:auto}
166
+ .kb-error{padding:10px 16px;background:var(--danger-bg);color:var(--danger-fg);font-family:var(--mono);font-size:12px;white-space:pre-wrap}
167
+ .kb-pop{position:absolute;z-index:25;top:62px;right:20px;width:320px;max-width:calc(100% - 32px);max-height:calc(100% - 80px);overflow:auto;display:flex;flex-direction:column;gap:14px;padding:16px;border-radius:calc(var(--radius) + 4px);background:var(--panel);color:var(--panel-fg);border:1px solid var(--line);box-shadow:0 20px 50px rgba(0,0,0,.22)}
168
+ .kb-pop h2,.kb-drawer h2{margin:0;font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.06em;color:var(--panel-muted)}
169
+ .kb-themes{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
170
+ .kb-theme{display:flex;flex-direction:column;align-items:flex-start;gap:6px;padding:10px;border:1px solid var(--line);border-radius:var(--radius);background:transparent;cursor:pointer;text-align:left}
171
+ .kb-theme[aria-pressed="true"]{border-color:var(--accent);box-shadow:0 0 0 1px var(--accent)}
172
+ .kb-swatch{display:flex;gap:3px}
173
+ .kb-swatch span{width:14px;height:14px;border-radius:3px;border:1px solid rgba(0,0,0,.12)}
174
+ .kb-theme small{color:var(--panel-muted);font-size:11px;line-height:1.3}
175
+ .kb-setting{display:grid;grid-template-columns:110px minmax(0,1fr) auto;align-items:center;gap:10px;font-size:13px}
176
+ .kb-setting input[type=range]{width:100%;accent-color:var(--accent)}
177
+ .kb-setting input[type=color]{width:44px;height:28px;padding:0;border:1px solid var(--line);border-radius:6px;background:none;cursor:pointer}
178
+ .kb-setting select{height:30px;border:1px solid var(--line);border-radius:6px;background:var(--control);padding:0 6px}
179
+ .kb-setting input[type=checkbox]{width:18px;height:18px;accent-color:var(--accent)}
180
+ .kb-setting output{font-family:var(--mono);font-size:11px;color:var(--panel-muted);min-width:42px;text-align:right}
181
+ .kb-drawer-resize{position:absolute;top:0;bottom:0;left:0;width:6px;cursor:ew-resize;touch-action:none}
182
+ .kb-drawer-resize:hover{background:var(--accent);opacity:.4}
183
+ .kb-drawer{position:absolute;z-index:30;top:0;right:0;bottom:0;width:400px;max-width:100%;display:flex;flex-direction:column;gap:16px;padding:18px 20px;overflow:auto;background:var(--panel);color:var(--panel-fg);border-left:1px solid var(--line);box-shadow:-20px 0 50px rgba(0,0,0,.18)}
184
+ .kb-drawer-head{display:flex;align-items:center;justify-content:space-between;gap:8px;font-family:var(--mono);font-size:12px;color:var(--panel-muted)}
185
+ .kb-field{display:flex;flex-direction:column;gap:6px}
186
+ .kb-field>span{font-size:12px;color:var(--panel-muted);font-weight:500}
187
+ .kb-field input,.kb-field textarea{width:100%;border:1px solid var(--line);border-radius:var(--radius);background:var(--control);padding:8px 10px}
188
+ .kb-field textarea{resize:vertical;min-height:110px;line-height:1.5}
189
+ .kb-field input:focus,.kb-field textarea:focus{border-color:var(--accent);outline:none}
190
+ .kb-field-error{margin:0;font-size:12px;color:var(--danger-fg);background:var(--danger-bg);padding:6px 8px;border-radius:var(--radius)}
191
+ .kb-tag-edit{padding:6px;border:1px solid var(--line);border-radius:var(--radius);background:var(--control)}
192
+ .kb-tag-edit .kb-tag-input{flex:1;min-width:90px;border:0;background:transparent;padding:4px;outline:none}
193
+ .kb-pill-x{display:inline-grid;place-items:center;width:16px;height:16px;margin-right:-4px;border:0;border-radius:50%;background:transparent;cursor:pointer;color:inherit;opacity:.7}
194
+ .kb-pill-x:hover{opacity:1;background:rgba(0,0,0,.12)}
195
+ .kb-archive{position:relative;overflow:auto;min-height:0;padding:20px 24px 48px}
196
+ .kb-archive-head{display:flex;align-items:baseline;gap:12px;margin-bottom:16px}
197
+ .kb-archive-head h2{margin:0;font-family:var(--font-title);font-size:18px;font-weight:600;text-shadow:var(--glow)}
198
+ .kb-archive-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(280px,100%),1fr));gap:12px;align-items:start}
199
+ .kb-card-archived{cursor:default}
200
+ .kb-archive-foot{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding-top:8px;border-top:1px solid var(--card-border);font-size:12px;color:var(--card-muted)}
201
+ .kb-archive-when{flex:1 1 auto;font-family:var(--mono)}
202
+ .kb-restore select{height:28px;max-width:140px;border:1px solid var(--card-border);border-radius:6px;background:transparent;color:inherit;padding:0 4px}
203
+ .kb-btn-sm{height:28px;padding:0 10px;font-size:12px;color:var(--card-fg)}
204
+ .kb-btn:disabled{opacity:.45;cursor:default}
205
+ .kb-hist-toggle{display:flex;flex-wrap:wrap;align-items:center;gap:6px 8px;width:100%;padding:8px 10px;border:1px solid var(--line);border-radius:var(--radius);background:var(--control);cursor:pointer;text-align:left}
206
+ .kb-hist-toggle:hover{border-color:var(--panel-muted)}
207
+ .kb-chev{flex:none;transition:transform .15s;color:var(--panel-muted)}
208
+ .kb-hist-toggle[aria-expanded="true"] .kb-chev{transform:rotate(90deg)}
209
+ .kb-hist-title{font-size:12px;font-weight:500;color:var(--panel-muted)}
210
+ .kb-hist-summary{display:flex;flex-wrap:wrap;gap:4px 14px;margin-left:auto;font-family:var(--mono);font-size:11.5px;color:var(--panel-muted)}
211
+ .kb-hist-summary b{font-weight:600;color:var(--panel-fg)}
212
+ .kb-hist-head{display:flex;align-items:center;gap:8px}
213
+ .kb-history{list-style:none;margin:0;padding:0;display:flex;flex-direction:column}
214
+ .kb-history li{display:grid;grid-template-columns:14px minmax(0,1fr);gap:10px;padding-bottom:12px;position:relative}
215
+ .kb-history li::before{content:"";position:absolute;left:6px;top:14px;bottom:0;width:1px;background:var(--line)}
216
+ .kb-history li:last-child::before{display:none}
217
+ .kb-dot{width:9px;height:9px;margin:4px 0 0 2px;border-radius:50%;background:var(--accent)}
218
+ .kb-history strong{font-weight:600}
219
+ .kb-history-meta{display:flex;flex-wrap:wrap;gap:4px 10px;font-size:12px;color:var(--panel-muted);font-family:var(--mono)}
220
+ .kb-danger{align-self:flex-start;height:34px;padding:0 12px;border:1px solid var(--danger-fg);border-radius:var(--radius);background:transparent;color:var(--danger-fg);cursor:pointer}
221
+ .kb-danger:hover{background:var(--danger-bg)}
222
+ .kb-toast{position:absolute;z-index:50;left:50%;bottom:20px;transform:translateX(-50%);max-width:min(560px,calc(100% - 32px));display:flex;gap:12px;align-items:center;padding:10px 14px;border-radius:var(--radius);background:var(--danger-bg);color:var(--danger-fg);box-shadow:0 10px 30px rgba(0,0,0,.2);font-size:13px}
223
+ .kb-toast-info{background:var(--panel);color:inherit;border:1px solid var(--line);pointer-events:none}
224
+ .kb[data-theme="terminal"] .kb-card,.kb[data-theme="terminal"] .kb-col{border-style:solid}
225
+ .kb[data-theme="terminal"] .kb-card-title::before{content:"> ";opacity:.6}
226
+ .kb[data-theme="terminal"] .kb-pill{border-color:currentColor;border-radius:0}
227
+ .kb[data-theme="paper"] .kb-card:nth-child(3n+1){transform:rotate(calc(var(--tilt) * -1deg))}
228
+ .kb[data-theme="paper"] .kb-card:nth-child(3n+2){transform:rotate(calc(var(--tilt) * .6deg))}
229
+ .kb[data-theme="paper"] .kb-card:nth-child(3n){transform:rotate(calc(var(--tilt) * 1deg))}
230
+ .kb-drawer,.kb-pop,.kb-modal,.kb-menu{--control:var(--panel-control);--line:var(--panel-line)}
231
+ .kb-menu-wrap{position:relative}
232
+ .kb-undo{display:inline-grid;place-items:center;padding:0 9px}
233
+ .kb-undo:disabled{opacity:.35;cursor:not-allowed}
234
+ .kb-pop-head{display:flex;align-items:center;justify-content:space-between;margin:-6px 0}
235
+ .kb-menu-btn{padding:0 9px}
236
+ .kb-menu-back{position:fixed;inset:0;z-index:29}
237
+ .kb-menu{position:absolute;z-index:30;top:calc(100% + 6px);right:0;min-width:220px;display:flex;flex-direction:column;padding:6px;border-radius:calc(var(--radius) + 4px);background:var(--panel);color:var(--panel-fg);border:1px solid var(--line);box-shadow:0 20px 50px rgba(0,0,0,.22)}
238
+ .kb-menu-item{display:flex;align-items:baseline;justify-content:space-between;gap:16px;padding:8px 10px;border:0;border-radius:var(--radius);background:transparent;cursor:pointer;text-align:left}
239
+ .kb-menu-item:hover,.kb-menu-item:focus-visible{background:var(--control)}
240
+ a.kb-menu-item{color:inherit;text-decoration:none}
241
+ .kb-menu-badge{justify-content:center}
242
+ .kb-menu-badge img,.kb-badge-preview img{display:block;max-width:100%}
243
+ .kb-badge-preview{display:flex;justify-content:center;padding:12px;border:1px dashed var(--line);border-radius:var(--radius)}
244
+ .kb-badge-row{display:grid;grid-template-columns:minmax(0,1fr) 80px 64px 40px;gap:8px;align-items:center}
245
+ .kb-badge-row select{height:36px;border:1px solid var(--line);border-radius:var(--radius);background:var(--control);font-size:16px}
246
+ .kb-badge-row input[type=color]{width:40px;height:36px;padding:2px;border:1px solid var(--line);border-radius:var(--radius);background:var(--control)}
247
+ .kb-cardp{display:flex;flex-direction:column;gap:10px;padding:14px 16px;border:1px solid #e3e3e8;border-radius:12px;background:#fff;color:#16181d;font-family:system-ui,sans-serif;font-size:13px}
248
+ .kb-cardp-head{display:flex;justify-content:space-between;align-items:flex-start;gap:8px}
249
+ .kb-cardp-head small{display:block;color:#6b7280}
250
+ .kb-card-pill{padding:2px 8px;border-radius:999px;font-size:11px;background:#eef0f4}
251
+ .kb-tone-good{background:#dcf2e6;color:#1d6b44}.kb-tone-warn{background:#fdf0d5;color:#8a5a00}.kb-tone-bad{background:#fbe0e3;color:#9b1c2e}
252
+ .kb-cardp-big b{font-size:28px}
253
+ .kb-cardp-bar{display:flex;gap:2px;height:8px}.kb-cardp-bar span{border-radius:4px;min-width:2px}
254
+ .kb-cardp-legend{display:flex;flex-wrap:wrap;gap:4px 12px;color:#4b5563}.kb-cardp-legend i{display:inline-block;width:8px;height:8px;margin-right:5px;border-radius:2px}
255
+ .kb-cardp-foot{display:flex;justify-content:space-between;gap:8px;padding-top:8px;border-top:1px solid #e3e3e8}.kb-cardp-foot code{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
256
+ .kb-badge-col{display:flex;align-items:center;gap:8px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
257
+ .kb-menu-sep{border:0;border-top:1px solid var(--line);margin:6px 4px;width:auto}
258
+ .kb-menu-item small{color:var(--panel-muted);font-size:11px;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
259
+ .kb-src{font-family:var(--mono);font-size:11px;padding:3px 8px;border:1px dashed var(--line);border-radius:var(--radius);color:var(--muted);white-space:nowrap;cursor:help}
260
+ .kb-btn-primary{background:var(--accent);color:var(--accent-fg);border-color:var(--accent)}
261
+ .kb-btn:disabled{opacity:.5;cursor:not-allowed}
262
+ .kb-modal-back{position:absolute;inset:0;z-index:60;display:flex;align-items:center;justify-content:center;padding:16px;background:rgba(0,0,0,.45)}
263
+ .kb-modal{width:min(520px,100%);max-height:calc(100% - 32px);overflow:auto;display:flex;flex-direction:column;gap:14px;padding:16px;border-radius:calc(var(--radius) + 4px);background:var(--panel);color:var(--panel-fg);border:1px solid var(--line);box-shadow:0 20px 50px rgba(0,0,0,.3)}
264
+ .kb-modal-small{width:min(380px,100%)}
265
+ .kb-modal-head{display:flex;align-items:center;gap:8px}
266
+ .kb-modal-head h2{margin:0;flex:1;font-size:15px;font-weight:600}
267
+ .kb-drop{position:relative;display:flex;flex-direction:column;align-items:center;gap:8px;padding:28px 16px;border:2px dashed var(--line);border-radius:var(--radius);cursor:pointer;text-align:center;color:var(--panel-muted)}
268
+ .kb-drop:hover,.kb-drop-on{border-color:var(--accent);color:var(--panel-fg)}
269
+ .kb-hidden-input{position:absolute;width:1px;height:1px;opacity:0;pointer-events:none}
270
+ .kb-open-url{display:flex;flex-direction:column;gap:6px}
271
+ .kb-open-url .kb-row{flex-wrap:nowrap}
272
+ .kb-input{flex:1;min-width:0;height:36px;padding:0 10px;border:1px solid var(--line);border-radius:var(--radius);background:var(--control);font-family:var(--mono);font-size:12px}
273
+ .kb-small{font-size:12px;line-height:1.45}
274
+ .kb-recents{display:flex;flex-direction:column;gap:4px}
275
+ .kb-recent{display:flex;flex-direction:column;align-items:flex-start;gap:2px;padding:8px 10px;border:1px solid transparent;border-radius:var(--radius);background:transparent;cursor:pointer;text-align:left}
276
+ .kb-recent:hover{border-color:var(--line);background:var(--control)}
277
+ .kb-recent small{color:var(--panel-muted);font-family:var(--mono);font-size:11px;word-break:break-all}
278
+ @media (max-width: 900px){
279
+ .kb-mode-split{grid-template-columns:minmax(0,1fr);grid-template-rows:minmax(0,1fr) minmax(0,1fr)}
280
+ .kb-mode-split .kb-source{border-left:0;border-top:1px solid var(--line)}
281
+ .kb-top{padding:12px 16px}
282
+ .kb-board{padding:16px}
283
+ }
284
+ </style>
285
+ </helmet>
286
+ <div class="{{rootClass}}" data-kb-root="{{uid}}" data-theme="{{themeId}}" style="{{rootStyle}}">
287
+ <canvas class="{{canvasClass}}" data-kb-canvas="{{uid}}" aria-hidden="true"></canvas>
288
+
289
+ <header class="kb-top" data-obstacle="toolbar">
290
+ <div class="kb-row">
291
+ <input class="kb-title" aria-label="Board title" value="{{titleValue}}" onChange="{{onTitle}}" onBlur="{{onTitleBlur}}">
292
+ <sc-if value="{{fromSrc}}" hint-placeholder-val="{{ false }}"><span class="kb-src" title="{{srcTitle}}">{{srcName}} · not saved here</span></sc-if>
293
+ <div class="kb-search">
294
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg>
295
+ <input type="search" placeholder="Search title, description, owner, tags" aria-label="Search tasks" value="{{query}}" onChange="{{onQuery}}">
296
+ </div>
297
+ <button class="kb-btn" aria-expanded="{{filterOpen}}" onClick="{{toggleFilter}}">
298
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M4 6h16M7 12h10M10 18h4"></path></svg>
299
+ <span>Filter</span>
300
+ <sc-if value="{{hasActiveFilters}}" hint-placeholder-val="{{ false }}"><span class="kb-count">{{activeFilterCount}}</span></sc-if>
301
+ </button>
302
+ <div class="kb-seg" role="group" aria-label="View">
303
+ <sc-for list="{{modes}}" as="m" hint-placeholder-count="3">
304
+ <button class="kb-seg-btn" aria-pressed="{{m.pressed}}" onClick="{{m.pick}}">{{m.label}}</button>
305
+ </sc-for>
306
+ </div>
307
+ <div class="kb-seg" role="group" aria-label="History">
308
+ <button class="kb-seg-btn kb-undo" aria-label="Undo" title="Undo (Ctrl/⌘ Z)" disabled="{{undoDisabled}}" onClick="{{undo}}"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M9 14 4 9l5-5"></path><path d="M4 9h11a5 5 0 0 1 0 10h-3"></path></svg></button>
309
+ <button class="kb-seg-btn kb-undo" aria-label="Redo" title="Redo (Ctrl/⌘ Shift Z)" disabled="{{redoDisabled}}" onClick="{{redo}}"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 14 5-5-5-5"></path><path d="M20 9H9a5 5 0 0 0 0 10h3"></path></svg></button>
310
+ <button class="kb-seg-btn kb-undo" aria-label="Time slider" title="History: see the board at an earlier time" aria-pressed="{{timeOpen}}" onClick="{{toggleTime}}"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3 2"></path></svg></button>
311
+ </div>
312
+ <div class="kb-menu-wrap" onKeyDown="{{menuKey}}">
313
+ <button class="kb-btn kb-menu-btn" aria-label="Menu" aria-haspopup="menu" aria-expanded="{{menuOpen}}" onClick="{{toggleMenu}}"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M4 7h16M4 12h16M4 17h16"></path></svg></button>
314
+ <sc-if value="{{menuOpen}}" hint-placeholder-val="{{ false }}">
315
+ <div class="kb-menu-back" onClick="{{closeMenu}}"></div>
316
+ <div class="kb-menu" role="menu">
317
+ <button class="kb-menu-item kb-menu-badge" role="menuitem" title="Badge: settings, download or copy" onClick="{{openBadge}}"><img src="{{badgeSrc}}" alt="{{badgeAlt}}"></button>
318
+ <hr class="kb-menu-sep">
319
+ <sc-for list="{{menuItems}}" as="mi" hint-placeholder-count="5">
320
+ <button class="kb-menu-item" role="menuitem" onClick="{{mi.pick}}"><span>{{mi.label}}</span><small>{{mi.hint}}</small></button>
321
+ </sc-for>
322
+ <hr class="kb-menu-sep">
323
+ <a class="kb-menu-item" role="menuitem" href="https://github.com/aaronp/agile" target="_blank" rel="noopener noreferrer" onClick="{{closeMenu}}"><span>Repo</span><small>GitHub</small></a>
324
+ </div>
325
+ </sc-if>
326
+ </div>
327
+ </div>
328
+ <sc-if value="{{time}}" hint-placeholder-val="{{ false }}">
329
+ <div class="kb-time">
330
+ <input type="range" class="kb-time-range" min="0" max="{{time.max}}" step="1" value="{{time.value}}" aria-label="Time" aria-valuetext="{{time.label}}" onChange="{{time.onChange}}">
331
+ <span class="kb-time-label">{{time.label}}</span>
332
+ <button class="kb-btn" disabled="{{time.atNow}}" onClick="{{time.now}}">Now</button>
333
+ </div>
334
+ </sc-if>
335
+ <sc-if value="{{filterOpen}}" hint-placeholder-val="{{ false }}">
336
+ <div class="kb-filters">
337
+ <div class="kb-fgroup">
338
+ <span class="kb-flabel">Tags</span>
339
+ <div class="kb-pills">
340
+ <sc-for list="{{tagOptions}}" as="o" hint-placeholder-count="4">
341
+ <button class="kb-pill kb-toggle" aria-pressed="{{o.pressed}}" style="{{o.style}}" onClick="{{o.toggle}}">{{o.label}}</button>
342
+ </sc-for>
343
+ <sc-if value="{{noTags}}" hint-placeholder-val="{{ false }}"><span class="kb-muted">No tags yet</span></sc-if>
344
+ </div>
345
+ </div>
346
+ <div class="kb-fgroup">
347
+ <span class="kb-flabel">Owner</span>
348
+ <div class="kb-pills">
349
+ <sc-for list="{{ownerOptions}}" as="o" hint-placeholder-count="3">
350
+ <button class="kb-pill kb-toggle kb-owner-toggle" aria-pressed="{{o.pressed}}" onClick="{{o.toggle}}">{{o.label}}</button>
351
+ </sc-for>
352
+ </div>
353
+ </div>
354
+ <sc-if value="{{hasActiveFilters}}" hint-placeholder-val="{{ false }}">
355
+ <button class="kb-link" onClick="{{clearFilters}}">Clear filters</button>
356
+ </sc-if>
357
+ </div>
358
+ </sc-if>
359
+ </header>
360
+
361
+ <sc-if value="{{effectError}}" hint-placeholder-val="{{ false }}">
362
+ <div class="kb-banner" role="alert"><span>{{effectError}}</span></div>
363
+ </sc-if>
364
+ <sc-if value="{{hasParseError}}" hint-placeholder-val="{{ false }}">
365
+ <div class="kb-banner" role="status"><span>The board is locked until the markdown parses again.</span></div>
366
+ </sc-if>
367
+
368
+ <main class="{{mainClass}}">
369
+ <sc-if value="{{showBoard}}" hint-placeholder-val="{{ true }}">
370
+ <section class="{{boardClass}}" aria-label="Board" data-kb-scroller="{{uid}}">
371
+ <sc-for list="{{columns}}" as="col" hint-placeholder-count="4">
372
+ <sc-if value="{{col.isPlaceholder}}" hint-placeholder-val="{{ false }}">
373
+ <div class="kb-col-ph" style="{{col.phStyle}}"></div>
374
+ </sc-if>
375
+ <sc-if value="{{col.isColumn}}" hint-placeholder-val="{{ true }}">
376
+ <div class="kb-col" data-col-drop="{{col.id}}">
377
+ <div class="kb-col-head">
378
+ <button class="kb-icon kb-grip" aria-label="{{col.gripLabel}}" onPointerDown="{{col.onGrip}}">
379
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><circle cx="9" cy="6" r="1.6"></circle><circle cx="15" cy="6" r="1.6"></circle><circle cx="9" cy="12" r="1.6"></circle><circle cx="15" cy="12" r="1.6"></circle><circle cx="9" cy="18" r="1.6"></circle><circle cx="15" cy="18" r="1.6"></circle></svg>
380
+ </button>
381
+ <input class="kb-col-name" data-kb-col="{{col.nameRef}}" aria-label="Column name" value="{{col.nameValue}}" onChange="{{col.onName}}" onBlur="{{col.onNameBlur}}">
382
+ <span class="kb-col-count">{{col.countLabel}}</span>
383
+ <button class="kb-icon" aria-label="{{col.deleteLabel}}" title="{{col.deleteTitle}}" disabled="{{col.deleteDisabled}}" onClick="{{col.onDelete}}">
384
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"></path></svg>
385
+ </button>
386
+ </div>
387
+ <sc-if value="{{col.nameError}}" hint-placeholder-val="{{ false }}"><p class="kb-field-error">{{col.nameError}}</p></sc-if>
388
+ <div class="kb-cards">
389
+ <sc-for list="{{col.items}}" as="it" hint-placeholder-count="2">
390
+ <sc-if value="{{it.isPlaceholder}}" hint-placeholder-val="{{ false }}">
391
+ <div class="kb-card-ph" style="{{it.phStyle}}"></div>
392
+ </sc-if>
393
+ <sc-if value="{{it.isAway}}" hint-placeholder-val="{{ false }}">
394
+ <div class="kb-card-away" style="{{it.indentStyle}}">
395
+ <sc-for list="{{it.rails}}" as="rl" hint-placeholder-count="0"><span class="{{rl.cls}}" style="{{rl.style}}" aria-hidden="true"></span></sc-for>
396
+ <button class="kb-card-away-link" title="{{it.focusLabel}}" onClick="{{it.focus}}">{{it.title}}</button>
397
+ <small>{{it.awayIn}}</small>
398
+ </div>
399
+ </sc-if>
400
+ <sc-if value="{{it.isTask}}" hint-placeholder-val="{{ true }}">
401
+ <article class="{{it.cardClass}}" style="{{it.indentStyle}}" data-obstacle="{{it.obstacleId}}" data-card-slot="{{it.id}}" onPointerDown="{{it.onPointerDown}}">
402
+ <sc-for list="{{it.rails}}" as="rl" hint-placeholder-count="0"><span class="{{rl.cls}}" style="{{rl.style}}" aria-hidden="true"></span></sc-for>
403
+ <div class="kb-card-tools">
404
+ <button class="kb-card-child" aria-label="{{it.addChildLabel}}" title="Add child task" onClick="{{it.onAddChild}}"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"></path></svg></button>
405
+ <sc-if value="{{it.hasKids}}" hint-placeholder-val="{{ false }}"><button class="kb-card-fold" aria-expanded="{{it.expanded}}" aria-label="{{it.foldLabel}}" title="{{it.foldLabel}}" onClick="{{it.toggleFold}}">{{it.foldText}}<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 9 6 6 6-6"></path></svg></button></sc-if>
406
+ </div>
407
+ <sc-if value="{{it.hasParentHint}}" hint-placeholder-val="{{ false }}"><button class="kb-card-parent" title="Open parent task" onClick="{{it.openParent}}">{{it.parentHint}}</button></sc-if>
408
+ <button class="kb-card-title" onClick="{{it.open}}">{{it.title}}</button>
409
+ <sc-if value="{{it.hasDescription}}" hint-placeholder-val="{{ false }}"><div class="{{it.descClass}}"><sc-for list="{{it.desc}}" as="blk" hint-placeholder-count="1"><sc-if value="{{blk.isPara}}" hint-placeholder-val="{{ true }}"><p class="md-p"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></p></sc-if><sc-if value="{{blk.isHeading}}" hint-placeholder-val="{{ false }}"><p class="md-h"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></p></sc-if><sc-if value="{{blk.isQuote}}" hint-placeholder-val="{{ false }}"><blockquote class="md-q"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></blockquote></sc-if><sc-if value="{{blk.isCode}}" hint-placeholder-val="{{ false }}"><pre class="md-pre"><code>{{blk.text}}</code></pre></sc-if><sc-if value="{{blk.isRule}}" hint-placeholder-val="{{ false }}"><hr class="md-hr"></sc-if><sc-if value="{{blk.isList}}" hint-placeholder-val="{{ false }}"><ul class="md-list"><sc-for list="{{blk.items}}" as="li"><li class="md-li" style="{{li.style}}"><sc-if value="{{li.isCheck}}" hint-placeholder-val="{{ false }}"><input type="checkbox" aria-label="{{li.checkLabel}}" checked="{{li.checked}}" onChange="{{li.toggle}}"></sc-if><sc-if value="{{li.isMarker}}" hint-placeholder-val="{{ true }}"><span class="md-marker" aria-hidden="true">{{li.marker}}</span></sc-if><span class="{{li.bodyCls}}"><sc-for list="{{li.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></span></li></sc-for></ul></sc-if></sc-for></div></sc-if>
410
+ <sc-if value="{{it.hasFoot}}" hint-placeholder-val="{{ true }}">
411
+ <div class="kb-card-foot">
412
+ <div class="kb-pills">
413
+ <sc-for list="{{it.tags}}" as="tg" hint-placeholder-count="1"><span class="kb-pill" style="{{tg.style}}">{{tg.label}}</span></sc-for>
414
+ </div>
415
+ <sc-if value="{{it.hasOwner}}" hint-placeholder-val="{{ true }}">
416
+ <span class="kb-owner"><span class="kb-avatar" style="{{it.avatarStyle}}" aria-hidden="true">{{it.initials}}</span>{{it.owner}}</span>
417
+ </sc-if>
418
+ </div>
419
+ </sc-if>
420
+ </article>
421
+ </sc-if>
422
+ </sc-for>
423
+ <sc-if value="{{col.showEmpty}}" hint-placeholder-val="{{ false }}"><p class="kb-empty">{{col.emptyLabel}}</p></sc-if>
424
+ </div>
425
+ <button class="kb-add" onClick="{{col.onAddTask}}">
426
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"></path></svg>
427
+ <span>Add task</span>
428
+ </button>
429
+ </div>
430
+ </sc-if>
431
+ </sc-for>
432
+ <button class="kb-add-col" aria-label="Add column" title="Add column" onClick="{{addColumn}}">
433
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14"></path></svg>
434
+ </button>
435
+ </section>
436
+ </sc-if>
437
+
438
+
439
+ <sc-if value="{{showArchive}}" hint-placeholder-val="{{ false }}">
440
+ <section class="kb-archive" aria-label="Archive">
441
+ <div class="kb-archive-head">
442
+ <h2>Archive</h2>
443
+ <span class="kb-muted">{{archiveCountLabel}}</span>
444
+ </div>
445
+ <sc-if value="{{archiveEmpty}}" hint-placeholder-val="{{ false }}"><p class="kb-muted">{{archiveEmptyLabel}}</p></sc-if>
446
+ <div class="kb-archive-grid">
447
+ <sc-for list="{{archived}}" as="it" hint-placeholder-count="3">
448
+ <article class="kb-card kb-card-archived">
449
+ <button class="kb-card-title" onClick="{{it.open}}">{{it.title}}</button>
450
+ <sc-if value="{{it.hasDescription}}" hint-placeholder-val="{{ false }}"><div class="{{it.descClass}}"><sc-for list="{{it.desc}}" as="blk" hint-placeholder-count="1"><sc-if value="{{blk.isPara}}" hint-placeholder-val="{{ true }}"><p class="md-p"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></p></sc-if><sc-if value="{{blk.isHeading}}" hint-placeholder-val="{{ false }}"><p class="md-h"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></p></sc-if><sc-if value="{{blk.isQuote}}" hint-placeholder-val="{{ false }}"><blockquote class="md-q"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></blockquote></sc-if><sc-if value="{{blk.isCode}}" hint-placeholder-val="{{ false }}"><pre class="md-pre"><code>{{blk.text}}</code></pre></sc-if><sc-if value="{{blk.isRule}}" hint-placeholder-val="{{ false }}"><hr class="md-hr"></sc-if><sc-if value="{{blk.isList}}" hint-placeholder-val="{{ false }}"><ul class="md-list"><sc-for list="{{blk.items}}" as="li"><li class="md-li" style="{{li.style}}"><sc-if value="{{li.isCheck}}" hint-placeholder-val="{{ false }}"><input type="checkbox" aria-label="{{li.checkLabel}}" checked="{{li.checked}}" onChange="{{li.toggle}}"></sc-if><sc-if value="{{li.isMarker}}" hint-placeholder-val="{{ true }}"><span class="md-marker" aria-hidden="true">{{li.marker}}</span></sc-if><span class="{{li.bodyCls}}"><sc-for list="{{li.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></span></li></sc-for></ul></sc-if></sc-for></div></sc-if>
451
+ <sc-if value="{{it.hasFoot}}" hint-placeholder-val="{{ true }}">
452
+ <div class="kb-card-foot">
453
+ <div class="kb-pills">
454
+ <sc-for list="{{it.tags}}" as="tg" hint-placeholder-count="1"><span class="kb-pill" style="{{tg.style}}">{{tg.label}}</span></sc-for>
455
+ </div>
456
+ <sc-if value="{{it.hasOwner}}" hint-placeholder-val="{{ true }}">
457
+ <span class="kb-owner"><span class="kb-avatar" style="{{it.avatarStyle}}" aria-hidden="true">{{it.initials}}</span>{{it.owner}}</span>
458
+ </sc-if>
459
+ </div>
460
+ </sc-if>
461
+ <div class="kb-archive-foot">
462
+ <span class="kb-archive-when">{{it.completedAgo}}</span>
463
+ <label class="kb-restore">
464
+ <select aria-label="{{it.restoreLabel}}" value="{{it.restoreTo}}" disabled="{{it.restoreDisabled}}" onChange="{{it.onRestoreTo}}"><sc-for list="{{it.restoreOptions}}" as="ro"><option value="{{ro.value}}">{{ro.label}}</option></sc-for></select>
465
+ </label>
466
+ <button class="kb-btn kb-btn-sm" disabled="{{it.restoreDisabled}}" onClick="{{it.restore}}">Restore</button>
467
+ </div>
468
+ </article>
469
+ </sc-for>
470
+ </div>
471
+ </section>
472
+ </sc-if>
473
+
474
+ <sc-if value="{{showSource}}" hint-placeholder-val="{{ false }}">
475
+ <section class="kb-source" aria-label="Markdown source">
476
+ <div class="kb-source-bar">
477
+ <span>board.md</span>
478
+ <span class="kb-status">{{saveStatus}}</span>
479
+ <button class="kb-btn" onClick="{{copySource}}">{{copyLabel}}</button>
480
+ </div>
481
+ <textarea class="kb-md" spellcheck="false" aria-label="Markdown source" value="{{sourceText}}" onChange="{{onSource}}" onBlur="{{onSourceBlur}}"></textarea>
482
+ <sc-if value="{{hasParseError}}" hint-placeholder-val="{{ false }}"><div class="kb-error" role="alert">{{parseError}}</div></sc-if>
483
+ </section>
484
+ </sc-if>
485
+ </main>
486
+
487
+ <sc-if value="{{pickerOpen}}" hint-placeholder-val="{{ false }}">
488
+ <div class="kb-pop" role="dialog" aria-label="Style" onKeyDown="{{pickerKey}}">
489
+ <div class="kb-pop-head"><h2>Style</h2><button class="kb-icon" aria-label="Close style settings" onClick="{{closePicker}}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"></path></svg></button></div>
490
+ <div class="kb-themes">
491
+ <sc-for list="{{themeOptions}}" as="t" hint-placeholder-count="5">
492
+ <button class="kb-theme" aria-pressed="{{t.pressed}}" onClick="{{t.pick}}">
493
+ <span class="kb-swatch" aria-hidden="true"><sc-for list="{{t.swatch}}" as="sw"><span style="{{sw.style}}"></span></sc-for></span>
494
+ <strong>{{t.name}}</strong>
495
+ <small>{{t.blurb}}</small>
496
+ </button>
497
+ </sc-for>
498
+ </div>
499
+ <h2>{{themeName}} settings</h2>
500
+ <sc-for list="{{settingControls}}" as="c" hint-placeholder-count="4">
501
+ <label class="kb-setting">
502
+ <span>{{c.label}}</span>
503
+ <sc-if value="{{c.isRange}}" hint-placeholder-val="{{ true }}"><input type="range" min="{{c.min}}" max="{{c.max}}" step="{{c.step}}" value="{{c.value}}" onChange="{{c.onChange}}"></sc-if>
504
+ <sc-if value="{{c.isColor}}" hint-placeholder-val="{{ false }}"><input type="color" value="{{c.value}}" onChange="{{c.onChange}}"></sc-if>
505
+ <sc-if value="{{c.isSelect}}" hint-placeholder-val="{{ false }}">
506
+ <select value="{{c.value}}" onChange="{{c.onChange}}"><sc-for list="{{c.options}}" as="op"><option value="{{op.value}}">{{op.label}}</option></sc-for></select>
507
+ </sc-if>
508
+ <sc-if value="{{c.isBoolean}}" hint-placeholder-val="{{ false }}"><input type="checkbox" checked="{{c.checked}}" onChange="{{c.onChange}}"></sc-if>
509
+ <output>{{c.valueLabel}}</output>
510
+ </label>
511
+ </sc-for>
512
+ <button class="kb-link" onClick="{{resetTheme}}">Reset {{themeName}} settings</button>
513
+ <h2>Effects</h2>
514
+ <sc-for list="{{effectControls}}" as="ec" hint-placeholder-count="3">
515
+ <div class="kb-effect">
516
+ <label>
517
+ <span>{{ec.label}}</span>
518
+ <select value="{{ec.value}}" onChange="{{ec.onChange}}"><sc-for list="{{ec.options}}" as="op"><option value="{{op.value}}">{{op.label}}</option></sc-for></select>
519
+ </label>
520
+ <button class="kb-link" aria-label="{{ec.tryLabel}}" disabled="{{ec.tryDisabled}}" onClick="{{ec.tryIt}}">Try</button>
521
+ </div>
522
+ </sc-for>
523
+ <sc-if value="{{storageWarning}}" hint-placeholder-val="{{ false }}"><p class="kb-field-error">{{storageWarning}}</p></sc-if>
524
+ </div>
525
+ </sc-if>
526
+
527
+ <sc-if value="{{isDragging}}" hint-placeholder-val="{{ false }}">
528
+ <div class="kb-ghost" style="{{ghostStyle}}">
529
+ <sc-if value="{{ghost.isTask}}" hint-placeholder-val="{{ false }}">
530
+ <article class="kb-card" data-obstacle="{{ghost.obstacleId}}">
531
+ <span class="kb-card-title">{{ghost.title}}</span>
532
+ <sc-if value="{{ghost.hasDescription}}" hint-placeholder-val="{{ false }}"><div class="{{ghost.descClass}}"><sc-for list="{{ghost.desc}}" as="blk" hint-placeholder-count="1"><sc-if value="{{blk.isPara}}" hint-placeholder-val="{{ true }}"><p class="md-p"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></p></sc-if><sc-if value="{{blk.isHeading}}" hint-placeholder-val="{{ false }}"><p class="md-h"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></p></sc-if><sc-if value="{{blk.isQuote}}" hint-placeholder-val="{{ false }}"><blockquote class="md-q"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></blockquote></sc-if><sc-if value="{{blk.isCode}}" hint-placeholder-val="{{ false }}"><pre class="md-pre"><code>{{blk.text}}</code></pre></sc-if><sc-if value="{{blk.isRule}}" hint-placeholder-val="{{ false }}"><hr class="md-hr"></sc-if><sc-if value="{{blk.isList}}" hint-placeholder-val="{{ false }}"><ul class="md-list"><sc-for list="{{blk.items}}" as="li"><li class="md-li" style="{{li.style}}"><sc-if value="{{li.isCheck}}" hint-placeholder-val="{{ false }}"><input type="checkbox" aria-label="{{li.checkLabel}}" checked="{{li.checked}}" onChange="{{li.toggle}}"></sc-if><sc-if value="{{li.isMarker}}" hint-placeholder-val="{{ true }}"><span class="md-marker" aria-hidden="true">{{li.marker}}</span></sc-if><span class="{{li.bodyCls}}"><sc-for list="{{li.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></span></li></sc-for></ul></sc-if></sc-for></div></sc-if>
533
+ <sc-if value="{{ghost.hasFoot}}" hint-placeholder-val="{{ false }}">
534
+ <div class="kb-card-foot">
535
+ <div class="kb-pills"><sc-for list="{{ghost.tags}}" as="tg"><span class="kb-pill" style="{{tg.style}}">{{tg.label}}</span></sc-for></div>
536
+ <sc-if value="{{ghost.hasOwner}}" hint-placeholder-val="{{ false }}"><span class="kb-owner"><span class="kb-avatar" style="{{ghost.avatarStyle}}" aria-hidden="true">{{ghost.initials}}</span>{{ghost.owner}}</span></sc-if>
537
+ </div>
538
+ </sc-if>
539
+ </article>
540
+ </sc-if>
541
+ <sc-if value="{{ghost.isColumn}}" hint-placeholder-val="{{ false }}">
542
+ <div class="kb-col" data-obstacle="{{ghost.obstacleId}}">
543
+ <div class="kb-col-head"><span class="kb-col-name">{{ghost.name}}</span><span class="kb-col-count">{{ghost.countLabel}}</span></div>
544
+ </div>
545
+ </sc-if>
546
+ </div>
547
+ </sc-if>
548
+
549
+ <sc-if value="{{editorOpen}}" hint-placeholder-val="{{ false }}">
550
+ <aside class="kb-drawer" style="{{drawerStyle}}" aria-label="Task details">
551
+ <div class="kb-drawer-resize" role="separator" aria-orientation="vertical" aria-label="Resize task panel" title="Drag to resize" onPointerDown="{{onDrawerResize}}"></div>
552
+ <div class="kb-drawer-head">
553
+ <span>{{editor.id}} · in {{editor.columnName}}</span>
554
+ <button class="kb-icon" aria-label="Close task details" onClick="{{closeEditor}}">
555
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"></path></svg>
556
+ </button>
557
+ </div>
558
+ <label class="kb-field">
559
+ <span>Title</span>
560
+ <input data-kb-title="{{uid}}" value="{{editor.title}}" onChange="{{editor.onTitle}}" onBlur="{{editor.onBlurTitle}}" onKeyDown="{{editor.onTitleKey}}">
561
+ </label>
562
+ <sc-if value="{{editor.titleError}}" hint-placeholder-val="{{ false }}"><p class="kb-field-error">{{editor.titleError}}</p></sc-if>
563
+ <div class="kb-field">
564
+ <div class="kb-desc-head">
565
+ <span>Description</span>
566
+ <div class="kb-tabs" role="group" aria-label="Description view">
567
+ <button class="kb-tab" tabindex="-1" aria-pressed="{{editor.isWrite}}" onClick="{{editor.showWrite}}">Write</button>
568
+ <button class="kb-tab" tabindex="-1" aria-pressed="{{editor.isPreview}}" onClick="{{editor.showPreview}}">Preview</button>
569
+ </div>
570
+ </div>
571
+ <sc-if value="{{editor.isWrite}}" hint-placeholder-val="{{ true }}">
572
+ <div class="kb-md-editor">
573
+ <div class="kb-fmtbar" role="toolbar" aria-label="Formatting">
574
+ <sc-for list="{{editor.formatButtons}}" as="fb" hint-placeholder-count="10">
575
+ <button class="{{fb.cls}}" tabindex="-1" aria-label="{{fb.label}}" title="{{fb.title}}" onMouseDown="{{fb.keepFocus}}" onClick="{{fb.apply}}">
576
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="{{fb.d}}"></path></svg>
577
+ </button>
578
+ </sc-for>
579
+ </div>
580
+ <textarea data-kb-desc="{{uid}}" aria-label="Description (markdown)" spellcheck="true" value="{{editor.description}}" onChange="{{editor.onDescription}}" onKeyDown="{{editor.onDescriptionKey}}" onBlur="{{editor.onBlurDescription}}"></textarea>
581
+ </div>
582
+ <p class="kb-hint">**bold** *italic* `code` - list 1. list - [ ] todo &gt; quote</p>
583
+ </sc-if>
584
+ <sc-if value="{{editor.isPreview}}" hint-placeholder-val="{{ false }}">
585
+ <div class="kb-preview md" title="Click to edit" onClick="{{editor.editFromPreview}}">
586
+ <sc-for list="{{editor.preview}}" as="blk" hint-placeholder-count="1"><sc-if value="{{blk.isPara}}" hint-placeholder-val="{{ true }}"><p class="md-p"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></p></sc-if><sc-if value="{{blk.isHeading}}" hint-placeholder-val="{{ false }}"><p class="md-h"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></p></sc-if><sc-if value="{{blk.isQuote}}" hint-placeholder-val="{{ false }}"><blockquote class="md-q"><sc-for list="{{blk.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></blockquote></sc-if><sc-if value="{{blk.isCode}}" hint-placeholder-val="{{ false }}"><pre class="md-pre"><code>{{blk.text}}</code></pre></sc-if><sc-if value="{{blk.isRule}}" hint-placeholder-val="{{ false }}"><hr class="md-hr"></sc-if><sc-if value="{{blk.isList}}" hint-placeholder-val="{{ false }}"><ul class="md-list"><sc-for list="{{blk.items}}" as="li"><li class="md-li" style="{{li.style}}"><sc-if value="{{li.isCheck}}" hint-placeholder-val="{{ false }}"><input type="checkbox" aria-label="{{li.checkLabel}}" checked="{{li.checked}}" onChange="{{li.toggle}}"></sc-if><sc-if value="{{li.isMarker}}" hint-placeholder-val="{{ true }}"><span class="md-marker" aria-hidden="true">{{li.marker}}</span></sc-if><span class="{{li.bodyCls}}"><sc-for list="{{li.spans}}" as="sp"><sc-if value="{{sp.isLink}}" hint-placeholder-val="{{ false }}"><a class="{{sp.cls}}" href="{{sp.href}}" target="_blank" rel="noopener noreferrer">{{sp.text}}</a></sc-if><sc-if value="{{sp.isPlain}}" hint-placeholder-val="{{ true }}"><span class="{{sp.cls}}">{{sp.text}}</span></sc-if></sc-for></span></li></sc-for></ul></sc-if></sc-for>
587
+ <sc-if value="{{editor.previewEmpty}}" hint-placeholder-val="{{ false }}"><p class="md-p kb-muted">Nothing to preview yet.</p></sc-if>
588
+ </div>
589
+ </sc-if>
590
+ </div>
591
+ <sc-if value="{{editor.descriptionError}}" hint-placeholder-val="{{ false }}"><p class="kb-field-error">{{editor.descriptionError}}</p></sc-if>
592
+ <div class="kb-field">
593
+ <span>Tags</span>
594
+ <div class="kb-pills kb-tag-edit">
595
+ <sc-for list="{{editor.tags}}" as="tg">
596
+ <span class="kb-pill" style="{{tg.style}}">{{tg.label}}<button class="kb-pill-x" tabindex="-1" aria-label="{{tg.removeLabel}}" onClick="{{tg.remove}}"><svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"></path></svg></button></span>
597
+ </sc-for>
598
+ <input class="kb-tag-input" placeholder="Add tag, press Enter" aria-label="Add tag" list="{{tagListId}}" value="{{tagInput}}" onChange="{{onTagInput}}" onKeyDown="{{onTagKey}}">
599
+ <datalist id="{{tagListId}}"><sc-for list="{{tagNames}}" as="tn"><option value="{{tn}}"></option></sc-for></datalist>
600
+ </div>
601
+ </div>
602
+ <label class="kb-field">
603
+ <span>Owner</span>
604
+ <input value="{{editor.owner}}" placeholder="Unassigned" list="{{ownerListId}}" onChange="{{editor.onOwner}}" onKeyDown="{{editor.onOwnerKey}}" onBlur="{{editor.onBlurOwner}}">
605
+ </label>
606
+ <datalist id="{{ownerListId}}"><sc-for list="{{ownerNames}}" as="on"><option value="{{on}}"></option></sc-for></datalist>
607
+ <sc-if value="{{editor.ownerError}}" hint-placeholder-val="{{ false }}"><p class="kb-field-error">{{editor.ownerError}}</p></sc-if>
608
+ <div class="kb-field">
609
+ <button class="kb-hist-toggle" aria-expanded="{{editor.historyOpen}}" onClick="{{editor.toggleHistory}}">
610
+ <svg class="kb-chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 6 6 6-6 6"></path></svg>
611
+ <span class="kb-hist-title">History</span>
612
+ <span class="kb-hist-summary">
613
+ <sc-for list="{{editor.summary}}" as="si" hint-placeholder-count="3"><span>{{si.column}}: <b>{{si.duration}}</b></span></sc-for>
614
+ </span>
615
+ </button>
616
+ <sc-if value="{{editor.historyOpen}}" hint-placeholder-val="{{ false }}">
617
+ <ol class="kb-history">
618
+ <sc-for list="{{editor.history}}" as="h" hint-placeholder-count="2">
619
+ <li>
620
+ <span class="kb-dot" aria-hidden="true"></span>
621
+ <div>
622
+ <div class="kb-hist-head"><strong>{{h.title}}</strong></div>
623
+ <div class="kb-history-meta"><span>{{h.label}}</span><span>{{h.owner}}</span><span>{{h.duration}}</span></div>
624
+ </div>
625
+ </li>
626
+ </sc-for>
627
+ </ol>
628
+ </sc-if>
629
+ </div>
630
+ <div class="kb-actions">
631
+ <button class="kb-primary" onClick="{{closeEditor}}">Ok</button>
632
+ <button class="kb-btn" disabled="{{editor.completeDisabled}}" title="{{editor.addChildTitle}}" onClick="{{editor.onAddChild}}">Create child task</button>
633
+ <button class="kb-btn" onClick="{{editor.openCompleteDialog}}">Complete…</button>
634
+ </div>
635
+ </aside>
636
+ </sc-if>
637
+
638
+ <sc-if value="{{editor.completeDialogOpen}}" hint-placeholder-val="{{ false }}">
639
+ <div class="kb-modal-back" onClick="{{editor.completeDialogBackdrop}}" onKeyDown="{{editor.completeDialogKey}}">
640
+ <div class="kb-modal kb-modal-small" role="dialog" aria-modal="true" aria-labelledby="kb-complete-h">
641
+ <div class="kb-modal-head">
642
+ <h2 id="kb-complete-h">{{editor.completeDialogTitle}}</h2>
643
+ <button class="kb-icon" aria-label="Close" onClick="{{editor.closeCompleteDialog}}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"></path></svg></button>
644
+ </div>
645
+ <p class="kb-muted kb-small">Mark complete moves it to the archive (see the Archive view). Delete removes it for good.</p>
646
+ <div class="kb-actions">
647
+ <button class="kb-primary" data-kb-complete="{{uid}}" disabled="{{editor.completeDisabled}}" title="{{editor.completeTitle}}" onClick="{{editor.onComplete}}">
648
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m5 12 5 5L20 7"></path></svg>
649
+ <span>{{editor.completeLabel}}</span>
650
+ </button>
651
+ <button class="kb-danger" onClick="{{editor.onDelete}}">Delete</button>
652
+ <button class="kb-btn" onClick="{{editor.closeCompleteDialog}}">Cancel</button>
653
+ </div>
654
+ </div>
655
+ </div>
656
+ </sc-if>
657
+
658
+ <canvas class="kb-burst" data-kb-burst="{{uid}}" aria-hidden="true"></canvas>
659
+
660
+ <sc-if value="{{openOpen}}" hint-placeholder-val="{{ false }}">
661
+ <div class="kb-modal-back" onClick="{{openBackdrop}}" onKeyDown="{{openKey}}">
662
+ <div class="kb-modal" role="dialog" aria-modal="true" aria-labelledby="kb-open-h">
663
+ <div class="kb-modal-head">
664
+ <h2 id="kb-open-h">Open a board</h2>
665
+ <button class="kb-icon" aria-label="Close" onClick="{{hideOpen}}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"></path></svg></button>
666
+ </div>
667
+ <label class="{{dropClass}}" onDragOver="{{openDragOver}}" onDragLeave="{{openDragLeave}}" onDrop="{{openDrop}}">
668
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 16V4m-4 4 4-4 4 4M4 17v3h16v-3"></path></svg>
669
+ <span>Drop a .md file here, or <u>choose a file</u></span>
670
+ <input type="file" accept=".md,.markdown,.txt,text/markdown,text/plain" onChange="{{onMdFile}}" class="kb-hidden-input">
671
+ </label>
672
+ <form class="kb-open-url" onSubmit="{{openUrlSubmit}}">
673
+ <label for="kb-open-url" class="kb-flabel">Or open from a URL</label>
674
+ <div class="kb-row">
675
+ <input id="kb-open-url" class="kb-input" type="url" placeholder="https://…/board.md" value="{{openUrl}}" onChange="{{onOpenUrl}}">
676
+ <button class="kb-btn kb-btn-primary" type="submit" disabled="{{openUrlDisabled}}">{{openUrlLabel}}</button>
677
+ </div>
678
+ <span class="kb-muted kb-small">GitHub file links work. A URL is shown with ?src= so the address can be shared, and isn't saved in this browser. A file replaces the board saved here.</span>
679
+ </form>
680
+ <sc-if value="{{hasRecents}}" hint-placeholder-val="{{ false }}">
681
+ <div class="kb-recents">
682
+ <span class="kb-flabel">Recent</span>
683
+ <sc-for list="{{recents}}" as="r" hint-placeholder-count="3">
684
+ <button class="kb-recent" onClick="{{r.open}}"><strong>{{r.name}}</strong><small>{{r.detail}}</small></button>
685
+ </sc-for>
686
+ </div>
687
+ </sc-if>
688
+ <sc-if value="{{openError}}" hint-placeholder-val="{{ false }}"><div class="kb-error" role="alert">{{openError}}</div></sc-if>
689
+ </div>
690
+ </div>
691
+ </sc-if>
692
+
693
+ <sc-if value="{{badgeOpen}}" hint-placeholder-val="{{ false }}">
694
+ <div class="kb-modal-back" onClick="{{badgeBackdrop}}" onKeyDown="{{badgeKey}}">
695
+ <div class="kb-modal" role="dialog" aria-modal="true" aria-labelledby="kb-badge-h">
696
+ <div class="kb-modal-head">
697
+ <h2 id="kb-badge-h">Badge and card</h2>
698
+ <button class="kb-icon" aria-label="Close" onClick="{{hideBadge}}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"></path></svg></button>
699
+ </div>
700
+ <div class="kb-badge-preview"><img src="{{badgeSrc}}" alt="{{badgeAlt}}"></div>
701
+ <div class="kb-row">
702
+ <button class="kb-btn kb-btn-primary" onClick="{{downloadBadge}}">Download SVG</button>
703
+ <button class="kb-btn" onClick="{{copyBadge}}">Copy SVG</button>
704
+ </div>
705
+ <sc-if value="{{cardPreview}}" hint-placeholder-val="{{ false }}">
706
+ <div class="kb-cardp" aria-label="card.json preview">
707
+ <div class="kb-cardp-head"><div><b>{{cardPreview.title}}</b><small>{{cardPreview.subtitle}}</small></div><span class="{{cardPreview.tone}}">{{cardPreview.pill}}</span></div>
708
+ <div class="kb-cardp-big"><b>{{cardPreview.big}}</b> {{cardPreview.bigLabel}}</div>
709
+ <div class="kb-cardp-bar"><sc-for list="{{cardPreview.items}}" as="ci"><span style="{{ci.seg}}"></span></sc-for></div>
710
+ <div class="kb-cardp-legend"><sc-for list="{{cardPreview.items}}" as="ci"><span><i style="{{ci.dot}}"></i>{{ci.label}} {{ci.n}}</span></sc-for></div>
711
+ <div class="kb-cardp-foot"><code>{{cardPreview.srcLabel}}</code><sc-if value="{{cardPreview.open}}" hint-placeholder-val="{{ false }}"><a href="{{cardPreview.open}}" target="_blank" rel="noopener">Open →</a></sc-if></div>
712
+ </div>
713
+ </sc-if>
714
+ <div class="kb-row">
715
+ <button class="kb-btn" onClick="{{downloadCard}}">Download card.json</button>
716
+ <button class="kb-btn" onClick="{{copyCard}}">Copy card.json</button>
717
+ </div>
718
+ <span class="kb-flabel">Columns: symbol (up to 6 characters), icon and color</span>
719
+ <sc-for list="{{badgeRows}}" as="br" hint-placeholder-count="3">
720
+ <div class="kb-badge-row">
721
+ <label class="kb-badge-col"><input type="checkbox" checked="{{br.included}}" onChange="{{br.toggle}}"><span>{{br.column}}</span></label>
722
+ <input class="kb-input" aria-label="{{br.symbolLabel}}" placeholder="Symbol" value="{{br.symbol}}" disabled="{{br.excluded}}" onChange="{{br.onSymbol}}">
723
+ <select aria-label="{{br.iconLabel}}" value="{{br.icon}}" disabled="{{br.excluded}}" onChange="{{br.onIcon}}"><sc-for list="{{br.icons}}" as="op"><option value="{{op.value}}">{{op.label}}</option></sc-for></select>
724
+ <input type="color" aria-label="{{br.colorLabel}}" value="{{br.fill}}" disabled="{{br.excluded}}" onChange="{{br.onColor}}">
725
+ </div>
726
+ <sc-if value="{{br.error}}" hint-placeholder-val="{{ false }}"><p class="kb-field-error">{{br.error}}</p></sc-if>
727
+ </sc-for>
728
+ <button class="kb-link" onClick="{{resetBadge}}">Reset to all columns</button>
729
+ </div>
730
+ </div>
731
+ </sc-if>
732
+
733
+ <sc-if value="{{toast}}" hint-placeholder-val="{{ false }}">
734
+ <div class="kb-toast kb-toast-info" role="status">{{toast}}</div>
735
+ </sc-if>
736
+ <sc-if value="{{opError}}" hint-placeholder-val="{{ false }}">
737
+ <div class="kb-toast" role="alert">
738
+ <span>{{opError}}</span>
739
+ <button class="kb-icon" aria-label="Dismiss error" onClick="{{dismissError}}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M6 6l12 12M18 6 6 18"></path></svg></button>
740
+ </div>
741
+ </sc-if>
742
+ </div>
743
+ </x-dc>
744
+ <script type="text/x-dc" data-dc-script data-props='{"startTheme":{"editor":"enum","options":["minimal","paper","terminal","ocean","ballpit","graph","night","blueprint","ledger"],"default":"minimal","section":"Board"},"$preview":{"width":1440,"height":900}}'>
745
+ /* =====================================================================
746
+ * Markdown agile board.
747
+ * Layers: (1) schema + validation, (2) markdown parse/serialize,
748
+ * (3) pure board operations, (4) themes, (5) WebGL effects,
749
+ * (6) the Component, which is the only place with IO (clock, DOM,
750
+ * storage, animation frames).
751
+ * ===================================================================== */
752
+
753
+ function fail(message) { throw new Error(message); }
754
+ function bug(message) { throw new Error('bug: this should never happen: ' + message); }
755
+
756
+ /* ---------- (1) Schema: a tiny TypeBox-style builder that validates ---------- */
757
+
758
+ const T = {
759
+ String: (o) => ({ kind: 'string', ...o }),
760
+ Array: (items, o) => ({ kind: 'array', items, ...o }),
761
+ Object: (props, o) => ({ kind: 'object', props, ...o }),
762
+ /** For shapes the builder can't express (records keyed by registry ids); `validate(value, path)` throws. */
763
+ Custom: (o) => ({ kind: 'custom', ...o }),
764
+ };
765
+
766
+ function check(schema, value, path) {
767
+ switch (schema.kind) {
768
+ case 'string': {
769
+ if (typeof value !== 'string') fail(`${path}: expected text, got ${typeof value}`);
770
+ if (schema.minLength !== undefined && value.length < schema.minLength) fail(`${path}: can't be empty`);
771
+ if (schema.pattern !== undefined && !schema.pattern.test(value)) fail(`${path}: "${value}" ${schema.patternHint}`);
772
+ if (schema.refine !== undefined) schema.refine(value, path);
773
+ return;
774
+ }
775
+ case 'array': {
776
+ if (!Array.isArray(value)) fail(`${path}: expected a list`);
777
+ if (schema.minItems !== undefined && value.length < schema.minItems) fail(`${path}: needs at least ${schema.minItems} entr${schema.minItems === 1 ? 'y' : 'ies'}`);
778
+ value.forEach((v, i) => check(schema.items, v, `${path}[${i}]`));
779
+ if (schema.unique === true && new Set(value).size !== value.length) fail(`${path}: contains duplicates`);
780
+ return;
781
+ }
782
+ case 'object': {
783
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) fail(`${path}: expected an object`);
784
+ for (const key of Object.keys(value)) if (!(key in schema.props)) fail(`${path}: unknown field "${key}"`);
785
+ for (const [key, sub] of Object.entries(schema.props)) {
786
+ if (!(key in value)) fail(`${path}: missing field "${key}"`);
787
+ check(sub, value[key], `${path}.${key}`);
788
+ }
789
+ return;
790
+ }
791
+ case 'custom': schema.validate(value, path); return;
792
+ default: bug(`unknown schema kind "${schema.kind}"`);
793
+ }
794
+ }
795
+
796
+ const SINGLE_LINE = /^[^\r\n]*$/;
797
+ const noOuterSpace = (v, path) => { if (v !== v.trim()) fail(`${path}: remove leading or trailing spaces`); };
798
+
799
+ const Stamp = T.String({
800
+ doc: 'UTC instant the task entered a column. Written by the app at the moment of the move (the clock is read only at the UI edge and passed in), so it sorts as text and round-trips exactly.',
801
+ example: '2026-10-27T10:02:00.000Z',
802
+ pattern: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?Z$/,
803
+ patternHint: 'is not a UTC timestamp like 2026-10-27T10:02:00Z',
804
+ refine: (v, path) => { if (Number.isNaN(Date.parse(v))) fail(`${path}: "${v}" is not a real date`); },
805
+ });
806
+
807
+ const OwnerName = T.String({
808
+ doc: 'Display name of whoever is responsible. Empty string means unassigned. Free text, so the board needs no user directory.',
809
+ example: 'Aaron', pattern: SINGLE_LINE, patternHint: 'must be one line', refine: noOuterSpace,
810
+ });
811
+
812
+ const HistoryEntry = T.Object({
813
+ column: T.String({
814
+ doc: 'Column name at the moment of entry. Stored as a name, not an id, so the markdown stays readable and history stays truthful after a rename or delete.',
815
+ example: 'Doing', minLength: 1, pattern: SINGLE_LINE, patternHint: 'must be one line', refine: noOuterSpace,
816
+ }),
817
+ at: Stamp,
818
+ owner: { ...OwnerName, doc: 'Owner at the moment of entry ("" = unassigned): who had the task while it sat in this column.' },
819
+ }, { doc: 'One arrival. The first entry is creation; each later entry is a move to a different column (reordering within a column adds nothing). A same-column entry with a new owner is a reassignment. Written as " - Doing @ 2026-10-27T10:02:00Z by Aaron" ("by …" left off when unassigned).' });
820
+
821
+ const Tag = T.String({
822
+ doc: 'Free-form category label shown as a pill and used by the Tags filter. Commas separate tags in markdown, so a tag can\'t contain one.',
823
+ example: 'frontend', minLength: 1, pattern: /^[^,\r\n]+$/, patternHint: 'can\'t contain commas or line breaks', refine: noOuterSpace,
824
+ });
825
+
826
+ const Task = T.Object({
827
+ id: T.String({
828
+ doc: 'Stable identity for drag/drop, editing and markdown round-trips. Unique across the board. New tasks get the next t-NN.',
829
+ example: 't-07', pattern: /^[A-Za-z0-9_-]+$/, patternHint: 'may only use letters, digits, "-" and "_"',
830
+ }),
831
+ title: T.String({
832
+ doc: 'One-line summary shown on the card; also the "### " heading in markdown.',
833
+ example: 'Wire up login', minLength: 1, pattern: SINGLE_LINE, patternHint: 'must be one line', refine: noOuterSpace,
834
+ }),
835
+ description: T.String({
836
+ doc: 'Markdown body (bold, italics, lists, checklists, quotes, code). Stored in the file inside a ```md fence under the metadata, so headings and lists in it never clash with the board structure. The serializer lengthens the fence if the text itself contains ``` lines. Empty string = no fence written.',
837
+ example: 'Hook the form up to **/api/session**.\n\n- [ ] happy path\n- [x] error states',
838
+ }),
839
+ owner: OwnerName,
840
+ tags: T.Array(Tag, { unique: true, doc: 'Categories for filtering; order is kept as entered.' }),
841
+ history: T.Array(HistoryEntry, { minItems: 1, doc: 'Append-only arrival log, oldest first.' }),
842
+ parent: T.String({
843
+ doc: 'Id of the task this one was split out of ("" = top level). Set when the child is created. In the same column a child shows indented under its parent; elsewhere it shows "↳ parent title". Written as "- parent: t-03", left out when empty.',
844
+ example: 't-03', pattern: /^[A-Za-z0-9_-]*$/, patternHint: 'must be a task id',
845
+ }),
846
+ }, { doc: 'A card on the board.' });
847
+
848
+ const Column = T.Object({
849
+ id: T.String({
850
+ doc: 'Session-local identity for drag targets and drafts. Not written to markdown; re-derived from position (c1, c2, ...) on parse.',
851
+ example: 'c2', pattern: /^c\d+$/, patternHint: 'must look like c1, c2, ...',
852
+ }),
853
+ name: T.String({
854
+ doc: 'Heading shown above the column and the "## " line in markdown. Duplicates are allowed but make history ambiguous.',
855
+ example: 'Doing', minLength: 1, pattern: SINGLE_LINE, patternHint: 'must be one line', refine: noOuterSpace,
856
+ }),
857
+ tasks: T.Array(Task, { doc: 'Cards in display order, top to bottom.' }),
858
+ }, { doc: 'A swimlane; column order is board.columns order.' });
859
+
860
+ /**
861
+ * Board-level settings, written as YAML-style front matter at the top of the file:
862
+ * ---
863
+ * version: 1
864
+ * theme: ocean
865
+ * ocean.swell: 0.6
866
+ * effects.complete: fireworks
867
+ * ---
868
+ * "version" stamps the file format (DATA_VERSION) and is always written; it isn't kept in memory because
869
+ * parsing brings any older file up to date. Files without it are version 1.
870
+ * The rest lists only values that differ from the defaults; anything absent means "default".
871
+ * In memory every value is present, so the UI never has to ask "is this set?".
872
+ */
873
+ const Settings = T.Object({
874
+ theme: T.String({
875
+ doc: 'Id of the active style (see THEMES). Written as "theme: <id>".',
876
+ example: 'ocean', refine: (v, path) => { if (!THEMES.some((t) => t.id === v)) fail(`${path}: unknown theme "${v}" (expected ${THEMES.map((t) => t.id).join(', ')})`); },
877
+ }),
878
+ themes: T.Custom({
879
+ doc: 'Every style\'s settings, keyed by theme id then setting key. Lets you switch styles without losing tweaks. Written as "<theme>.<setting>: value" lines, non-defaults only.',
880
+ example: { ocean: { swell: 0.6 } },
881
+ validate: (v, path) => {
882
+ if (v === null || typeof v !== 'object') fail(`${path}: expected an object`);
883
+ for (const id of Object.keys(v)) if (!THEMES.some((t) => t.id === id)) fail(`${path}: unknown theme "${id}"`);
884
+ for (const t of THEMES) {
885
+ const s = v[t.id];
886
+ if (s === undefined) fail(`${path}: missing settings for "${t.id}"`);
887
+ for (const k of Object.keys(s)) if (!(k in t.settings)) fail(`${path}.${t.id}: unknown setting "${k}"`);
888
+ for (const [k, def] of Object.entries(t.settings)) {
889
+ if (!(k in s)) fail(`${path}.${t.id}: missing "${k}"`);
890
+ if (coerceSetting(def, s[k]) !== s[k]) fail(`${path}.${t.id}.${k}: wrong type`);
891
+ }
892
+ }
893
+ },
894
+ }),
895
+ effects: T.Custom({
896
+ doc: 'Effect choice per event (create, delete, complete): one of that event\'s effects, "random" or "none". Written as "effects.<event>: value".',
897
+ example: { create: 'pop', delete: 'burn', complete: 'random' },
898
+ validate: (v, path) => {
899
+ if (v === null || typeof v !== 'object') fail(`${path}: expected an object`);
900
+ for (const k of Object.keys(v)) if (!(k in EVENT_EFFECTS)) fail(`${path}: unknown event "${k}"`);
901
+ for (const event of Object.keys(EVENT_EFFECTS)) {
902
+ if (!(event in v)) fail(`${path}: missing "${event}"`);
903
+ if (!effectChoices(event).includes(v[event])) fail(`${path}.${event}: "${v[event]}" is not one of ${effectChoices(event).join(', ')}`);
904
+ }
905
+ },
906
+ }),
907
+ badge: T.Custom({
908
+ doc: 'The badge\'s segments: null shows every column with default symbols and icons; otherwise only the listed columns, in board order. Written as "badge: [[column, symbol, icon, color], …]" (JSON), left out when null. An empty color means the default palette.',
909
+ example: [{ column: 'Backlog', symbol: 'B', icon: '📋', color: '#3b6fd8' }],
910
+ validate: (v, path) => {
911
+ if (v === null) return;
912
+ if (!Array.isArray(v)) fail(`${path}: expected a list`);
913
+ v.forEach((item, i) => {
914
+ const at = `${path}[${i}]`;
915
+ if (item === null || typeof item !== 'object' || ['column', 'symbol', 'icon', 'color'].some((k) => typeof item[k] !== 'string')) fail(`${at}: expected column, symbol, icon and color text`);
916
+ for (const k of ['column', 'symbol', 'icon']) if (!SINGLE_LINE.test(item[k])) fail(`${at}.${k}: must be one line`);
917
+ if (Array.from(item.symbol).length > BADGE_SYMBOL_MAX) fail(`symbol can be at most ${BADGE_SYMBOL_MAX} characters`);
918
+ if (!/^(#[0-9a-f]{6})?$/i.test(item.color)) fail(`color must be like #3b6fd8, or empty for the default`);
919
+ if (Array.from(item.icon).length > BADGE_ICON_MAX) fail(`icon can be at most ${BADGE_ICON_MAX} characters`);
920
+ });
921
+ },
922
+ }),
923
+ }, { doc: 'Look and feel that travels with the board file.' });
924
+ const BADGE_SYMBOL_MAX = 6;
925
+ const BADGE_ICON_MAX = 8; // code points: one emoji can be several (skin tones, ZWJ sequences)
926
+ /** Icons offered in the badge settings ('' = none). Any other emoji can still be written in the file. */
927
+ const BADGE_ICONS = ['', '📋', '⏳', '✅', '🚧', '🐛', '🔥', '🚀', '👀', '🧪', '📦', '⭐', '❗', '💡', '📝', '🔍', '🎯', '⚠️', '🔒', '🛠️', '🎉', '❌', '🟢', '🟡', '🔴'];
928
+
929
+ /** Markdown format version. Bump it when the format changes, and upgrade older versions in parseSettings/parseBoard. */
930
+ const DATA_VERSION = 1;
931
+
932
+ const DEFAULT_THEME = 'minimal';
933
+ function defaultBoardSettings() {
934
+ return {
935
+ theme: DEFAULT_THEME,
936
+ themes: Object.fromEntries(THEMES.map((t) => [t.id, defaultSettings(t)])),
937
+ effects: Object.fromEntries(Object.entries(EVENT_EFFECTS).map(([event, spec]) => [event, spec.default])),
938
+ badge: null,
939
+ };
940
+ }
941
+
942
+ const Board = T.Object({
943
+ title: T.String({
944
+ doc: 'Board name; the single "# " line at the top of the markdown.',
945
+ example: 'Sprint 42', minLength: 1, pattern: SINGLE_LINE, patternHint: 'must be one line', refine: noOuterSpace,
946
+ }),
947
+ settings: Settings,
948
+ columns: T.Array(Column, { doc: 'Columns left to right.' }),
949
+ archive: T.Array(Task, {
950
+ doc: 'Completed tasks, oldest first. Hidden from the board, shown in the Archive view. Written last as "## Archive <!-- archive -->" with tasks in the usual format.',
951
+ }),
952
+ }, { doc: 'The whole board. The markdown file is the canonical form; this is its parsed shape.' });
953
+
954
+ function validateBoard(board) {
955
+ check(Board, board, 'board');
956
+ const seenTasks = new Set();
957
+ const seenCols = new Set();
958
+ for (const col of board.columns) {
959
+ if (seenCols.has(col.id)) fail(`board: duplicate column id "${col.id}"`);
960
+ seenCols.add(col.id);
961
+ }
962
+ const every = [...board.columns.flatMap((c) => c.tasks), ...board.archive];
963
+ for (const t of every) {
964
+ if (seenTasks.has(t.id)) fail(`board: task id "${t.id}" is used twice`);
965
+ seenTasks.add(t.id);
966
+ }
967
+ const parentOf = new Map(every.map((t) => [t.id, t.parent]));
968
+ for (const t of every) {
969
+ if (t.parent === '') continue;
970
+ if (!seenTasks.has(t.parent)) fail(`board: task "${t.id}" has parent "${t.parent}", which doesn't exist`);
971
+ // Walk up; seeing t again means a loop.
972
+ for (let p = t.parent, steps = 0; p !== ''; p = parentOf.get(p), steps++) {
973
+ if (p === t.id || steps > every.length) fail(`board: task "${t.id}" is its own ancestor`);
974
+ }
975
+ }
976
+ return board;
977
+ }
978
+
979
+ /** Pixels a child card sits right of its parent (the tree lines are drawn in that gap). */
980
+ const INDENT = 18;
981
+
982
+ /** Parents first, each followed by its children (only those in the same list), keeping the list's order otherwise. */
983
+ function treeOrder(tasks) {
984
+ const here = new Set(tasks.map((t) => t.id));
985
+ const kids = new Map();
986
+ for (const t of tasks) if (here.has(t.parent)) kids.set(t.parent, [...(kids.get(t.parent) ?? []), t]);
987
+ const out = [];
988
+ const walk = (t, depth) => { out.push({ task: t, depth }); for (const k of kids.get(t.id) ?? []) walk(k, depth + 1); };
989
+ for (const t of tasks) if (!here.has(t.parent)) walk(t, 0);
990
+ return out;
991
+ }
992
+
993
+ /* ---------- (2) Markdown <-> Board ---------- */
994
+
995
+ const META_KEYS = ['id', 'parent', 'owner', 'tags', 'history'];
996
+
997
+ /** Front matter lines -> full settings. `lines` are the lines between the "---" markers; `first` is the 0-based line of the first. */
998
+ function parseSettings(lines, first) {
999
+ const settings = defaultBoardSettings();
1000
+ const seen = new Map();
1001
+ lines.forEach((raw, k) => {
1002
+ const i = first + k;
1003
+ const line = raw.trim();
1004
+ if (line === '' || line.startsWith('#')) return;
1005
+ const m = /^([a-z][a-z0-9-]*(?:\.[a-z][a-zA-Z0-9-]*)?):\s*(.*)$/.exec(line);
1006
+ if (m === null) fail(`Line ${i + 1}: front matter lines look like "theme: ocean" or "ocean.swell: 0.6"`);
1007
+ const [, key, value] = m;
1008
+ if (seen.has(key)) fail(`Line ${i + 1}: "${key}" is already set on line ${seen.get(key) + 1}`);
1009
+ seen.set(key, i);
1010
+ const where = (msg) => fail(`Line ${i + 1}: ${msg}`);
1011
+ if (key === 'version') {
1012
+ if (!/^[1-9][0-9]*$/.test(value)) where(`version must be a whole number like ${DATA_VERSION}`);
1013
+ if (Number(value) > DATA_VERSION) where(`this board is format version ${value}, newer than this app understands (${DATA_VERSION}); open it with a newer copy`);
1014
+ return;
1015
+ }
1016
+ if (key === 'theme') {
1017
+ if (!THEMES.some((t) => t.id === value)) where(`unknown theme "${value}" (expected ${THEMES.map((t) => t.id).join(', ')})`);
1018
+ settings.theme = value;
1019
+ return;
1020
+ }
1021
+ if (key === 'badge') {
1022
+ let list;
1023
+ try { list = JSON.parse(value); } catch (err) { where('badge must be a list like [["Backlog", "B", "📋", "#3b6fd8"]]'); }
1024
+ if (!Array.isArray(list) || !list.every((x) => Array.isArray(x) && (x.length === 3 || x.length === 4))) where('badge must be a list like [["Backlog", "B", "📋", "#3b6fd8"]]');
1025
+ settings.badge = list.map(([column, symbol, icon, color = '']) => ({ column, symbol, icon, color })); // entries from before colors have three values
1026
+ try { check(Settings.props.badge, settings.badge, 'badge'); } catch (err) { where(err.message); }
1027
+ return;
1028
+ }
1029
+ const [scope, name] = key.split('.');
1030
+ if (name === undefined) where(`unknown setting "${key}" (expected version, theme, badge, effects.<event> or <theme>.<setting>)`);
1031
+ if (scope === 'effects') {
1032
+ if (!(name in EVENT_EFFECTS)) where(`unknown effect event "${name}" (expected ${Object.keys(EVENT_EFFECTS).join(', ')})`);
1033
+ if (!effectChoices(name).includes(value)) where(`"${value}" is not an effect for ${name} (expected ${effectChoices(name).join(', ')})`);
1034
+ settings.effects[name] = value;
1035
+ return;
1036
+ }
1037
+ const theme = THEMES.find((t) => t.id === scope);
1038
+ if (theme === undefined) where(`unknown theme "${scope}" in "${key}"`);
1039
+ const def = theme.settings[name];
1040
+ if (def === undefined) where(`"${theme.name}" has no setting "${name}" (expected ${Object.keys(theme.settings).join(', ')})`);
1041
+ let typed = value;
1042
+ if (def.type === 'boolean') {
1043
+ if (value !== 'true' && value !== 'false') where(`${key} must be true or false`);
1044
+ typed = value === 'true';
1045
+ }
1046
+ try { settings.themes[theme.id][name] = coerceSetting(def, typed); } catch (err) { where(`${key}: ${err.message}`); }
1047
+ });
1048
+ return settings;
1049
+ }
1050
+
1051
+ function serializeSettings(settings) {
1052
+ const defaults = defaultBoardSettings();
1053
+ const out = [`version: ${DATA_VERSION}`];
1054
+ if (settings.theme !== defaults.theme) out.push(`theme: ${settings.theme}`);
1055
+ for (const t of THEMES) {
1056
+ for (const k of Object.keys(t.settings)) {
1057
+ const v = settings.themes[t.id][k];
1058
+ if (v !== defaults.themes[t.id][k]) out.push(`${t.id}.${k}: ${String(v)}`);
1059
+ }
1060
+ }
1061
+ for (const event of Object.keys(EVENT_EFFECTS)) if (settings.effects[event] !== defaults.effects[event]) out.push(`effects.${event}: ${settings.effects[event]}`);
1062
+ if (settings.badge !== null) out.push(`badge: ${JSON.stringify(settings.badge.map((b) => [b.column, b.symbol, b.icon, b.color]))}`);
1063
+ return out;
1064
+ }
1065
+
1066
+ function parseBoard(src) {
1067
+ if (typeof src !== 'string') bug('parseBoard needs a string');
1068
+ const lines = src.replace(/\r\n?/g, '\n').split('\n');
1069
+ let settings = defaultBoardSettings();
1070
+ let bodyStart = 0;
1071
+ if (lines[0] === '---') {
1072
+ const close = lines.indexOf('---', 1);
1073
+ if (close < 0) fail('Line 1: front matter opened with "---" is never closed with another "---" line');
1074
+ settings = parseSettings(lines.slice(1, close), 1);
1075
+ bodyStart = close + 1;
1076
+ }
1077
+ let title = null;
1078
+ const columns = [];
1079
+ let archive = null; // the archive section, once its heading is seen
1080
+ let col = null;
1081
+ let task = null; // { line, title, meta: {}, history: null | [], desc: null | [], fenceLine, fenceLen }
1082
+ let phase = 'none'; // 'none' | 'meta' | 'history' | 'gap' | 'fence'
1083
+ const idLines = new Map();
1084
+ const at = (i, msg) => fail(`Line ${i + 1}: ${msg}`);
1085
+
1086
+ const finishTask = () => {
1087
+ if (task === null) return;
1088
+ const where = `Line ${task.line + 1} (task "${task.title}")`;
1089
+ for (const key of ['id', 'owner', 'tags']) if (!(key in task.meta)) fail(`${where}: missing "- ${key}:" line`);
1090
+ if (task.history === null) fail(`${where}: missing "- history:" with at least one " - Column @ timestamp" entry`);
1091
+ const built = {
1092
+ id: task.meta.id,
1093
+ title: task.title,
1094
+ description: task.desc === null ? '' : task.desc.join('\n').replace(/^\n+/, '').replace(/\s+$/, ''),
1095
+ owner: task.meta.owner,
1096
+ tags: task.meta.tags === '' ? [] : task.meta.tags.split(',').map((s) => s.trim()),
1097
+ history: task.history,
1098
+ parent: task.meta.parent ?? '',
1099
+ };
1100
+ check(Task, built, where);
1101
+ if (idLines.has(built.id)) fail(`${where}: id "${built.id}" is already used on line ${idLines.get(built.id) + 1}`);
1102
+ idLines.set(built.id, task.line);
1103
+ col.tasks.push(built);
1104
+ task = null;
1105
+ phase = 'none';
1106
+ };
1107
+
1108
+ lines.forEach((raw, i) => {
1109
+ if (i < bodyStart) return;
1110
+ const line = raw.replace(/\s+$/, '');
1111
+ let m;
1112
+ if (phase === 'fence') {
1113
+ // Inside the description fence everything is description, including "#" lines.
1114
+ if ((m = /^(`{3,})$/.exec(line)) !== null && m[1].length >= task.fenceLen) { phase = 'gap'; return; }
1115
+ task.desc.push(line);
1116
+ return;
1117
+ }
1118
+ if (line === '---') at(i, 'front matter ("---" block) must start on the very first line');
1119
+ if ((m = /^# (.*)$/.exec(line)) !== null) {
1120
+ if (title !== null) at(i, 'only one "# Board title" line is allowed');
1121
+ if (columns.length > 0) at(i, '"# Board title" must come before the first column');
1122
+ title = m[1].trim();
1123
+ if (title === '') at(i, 'board title is empty');
1124
+ return;
1125
+ }
1126
+ if ((m = /^## (.*)$/.exec(line)) !== null) {
1127
+ finishTask();
1128
+ if (title === null) at(i, 'expected "# Board title" before the first column');
1129
+ if (archive !== null) at(i, 'the "## Archive <!-- archive -->" section must be the last section');
1130
+ if (/<!--\s*archive\s*-->$/.test(m[1])) {
1131
+ archive = { id: null, name: 'Archive', tasks: [] };
1132
+ col = archive;
1133
+ return;
1134
+ }
1135
+ const name = m[1].trim();
1136
+ if (name === '') at(i, 'column name is empty');
1137
+ if (/<!--/.test(name)) at(i, `column headings are plain names; remove the "<!-- … -->" comment from "${name}"`);
1138
+ col = { id: `c${columns.length + 1}`, name, tasks: [] };
1139
+ columns.push(col);
1140
+ return;
1141
+ }
1142
+ if ((m = /^### (.*)$/.exec(line)) !== null) {
1143
+ finishTask();
1144
+ if (col === null) at(i, 'task appears before any "## Column"');
1145
+ const t = m[1].trim();
1146
+ if (t === '') at(i, 'task title is empty');
1147
+ task = { line: i, title: t, meta: {}, history: null, desc: null, fenceLine: -1, fenceLen: 0 };
1148
+ phase = 'meta';
1149
+ return;
1150
+ }
1151
+ if (/^#{1,3}$/.test(line)) at(i, 'heading marker with no text');
1152
+ if (task === null) {
1153
+ if (line.trim() === '') return;
1154
+ if (title === null) at(i, 'expected "# Board title" as the first line (after any front matter)');
1155
+ if (col === null) at(i, 'only blank lines may sit between the board title and the first "## Column"');
1156
+ at(i, 'text inside a column must belong to a "### Task"');
1157
+ }
1158
+ if (phase === 'gap') {
1159
+ if (line.trim() === '') return;
1160
+ if ((m = /^(`{3,})\s*(md|markdown)?$/.exec(line)) !== null) {
1161
+ if (task.desc !== null) at(i, `task "${task.title}" already has a description block (line ${task.fenceLine + 1})`);
1162
+ task.desc = [];
1163
+ task.fenceLine = i;
1164
+ task.fenceLen = m[1].length;
1165
+ phase = 'fence';
1166
+ return;
1167
+ }
1168
+ if (/^`{3,}/.test(line)) at(i, 'description fences open with ``` or ```md');
1169
+ at(i, 'task descriptions go inside a fence: a "```md" line, the text, then a "```" line');
1170
+ }
1171
+ if (phase === 'meta' || phase === 'history') {
1172
+ if (line.trim() === '') { phase = 'gap'; return; }
1173
+ if (phase === 'history' && /^\s+- /.test(line)) {
1174
+ const h = /^\s+- (.+?) @ (\S+)(?: by (.+))?$/.exec(line);
1175
+ if (h === null) at(i, 'history entries look like " - Doing @ 2026-10-27T10:02:00Z by Aaron" ("by …" is left off when unassigned)');
1176
+ task.history.push({ column: h[1].trim(), at: h[2], owner: h[3] === undefined ? '' : h[3].trim() });
1177
+ return;
1178
+ }
1179
+ if ((m = /^- ([a-z]+):(?: (.*))?$/.exec(line)) !== null) {
1180
+ const key = m[1];
1181
+ const val = (m[2] === undefined ? '' : m[2]).trim();
1182
+ if (!META_KEYS.includes(key)) at(i, `unknown field "${key}" (expected ${META_KEYS.join(', ')})`);
1183
+ if (key === 'history') {
1184
+ if (task.history !== null) at(i, 'duplicate "- history:"');
1185
+ if (val !== '') at(i, 'put history entries on the indented lines below "- history:"');
1186
+ task.history = [];
1187
+ phase = 'history';
1188
+ return;
1189
+ }
1190
+ if (key in task.meta) at(i, `duplicate "- ${key}:"`);
1191
+ task.meta[key] = val;
1192
+ phase = 'meta';
1193
+ return;
1194
+ }
1195
+ at(i, 'expected "- key: value" metadata, or a blank line before the description');
1196
+ }
1197
+ bug(`parser reached phase "${phase}" on line ${i + 1}`);
1198
+ });
1199
+ if (phase === 'fence') fail(`Line ${task.fenceLine + 1}: description fence for "${task.title}" is never closed with a ${'`'.repeat(task.fenceLen)} line`);
1200
+ finishTask();
1201
+ if (title === null) fail(`Line ${bodyStart + 1}: expected "# Board title"`);
1202
+ return validateBoard({ title, settings, columns, archive: archive === null ? [] : archive.tasks });
1203
+ }
1204
+
1205
+ function serializeTask(t) {
1206
+ const out = [`### ${t.title}`, `- id: ${t.id}`, ...(t.parent === '' ? [] : [`- parent: ${t.parent}`]), t.owner === '' ? '- owner:' : `- owner: ${t.owner}`, t.tags.length === 0 ? '- tags:' : `- tags: ${t.tags.join(', ')}`, '- history:'];
1207
+ for (const h of t.history) out.push(` - ${h.column} @ ${h.at}${h.owner === '' ? '' : ` by ${h.owner}`}`);
1208
+ const desc = t.description.replace(/^\n+/, '').replace(/\s+$/, '');
1209
+ if (desc !== '') {
1210
+ const body = desc.split('\n').map((l) => l.replace(/\s+$/, ''));
1211
+ const longest = body.reduce((n, l) => { const m = /^(`{3,})/.exec(l); return m === null ? n : Math.max(n, m[1].length); }, 0);
1212
+ const fence = '`'.repeat(Math.max(3, longest + 1));
1213
+ out.push('', `${fence}md`, ...body, fence);
1214
+ }
1215
+ out.push('');
1216
+ return out;
1217
+ }
1218
+
1219
+ function serializeBoard(board) {
1220
+ validateBoard(board);
1221
+ const front = serializeSettings(board.settings);
1222
+ const out = ['---', ...front, '---'];
1223
+ out.push(`# ${board.title}`, '');
1224
+ for (const col of board.columns) {
1225
+ out.push(`## ${col.name}`, '');
1226
+ for (const t of col.tasks) out.push(...serializeTask(t));
1227
+ }
1228
+ if (board.archive.length > 0) {
1229
+ out.push('## Archive <!-- archive -->', '');
1230
+ for (const t of board.archive) out.push(...serializeTask(t));
1231
+ }
1232
+ return out.join('\n').replace(/\n+$/, '\n');
1233
+ }
1234
+
1235
+ /* ---------- (3) Pure board operations (time is always passed in) ---------- */
1236
+
1237
+ /** Where a task lives: `col` is its column, or null when it is in the archive. */
1238
+ function findTask(board, taskId) {
1239
+ for (const col of board.columns) {
1240
+ const index = col.tasks.findIndex((t) => t.id === taskId);
1241
+ if (index >= 0) return { col, index, task: col.tasks[index], archived: false };
1242
+ }
1243
+ const index = board.archive.findIndex((t) => t.id === taskId);
1244
+ if (index >= 0) return { col: null, index, task: board.archive[index], archived: true };
1245
+ return fail(`No task with id "${taskId}"`);
1246
+ }
1247
+ function findColumn(board, colId) {
1248
+ const col = board.columns.find((c) => c.id === colId);
1249
+ return col === undefined ? fail(`No column with id "${colId}"`) : col;
1250
+ }
1251
+ const allTasks = (board) => [...board.columns.flatMap((c) => c.tasks), ...board.archive];
1252
+ function nextNumbered(ids, re, make) {
1253
+ const max = ids.reduce((acc, id) => { const m = re.exec(id); return m === null ? acc : Math.max(acc, Number(m[1])); }, 0);
1254
+ return make(max + 1);
1255
+ }
1256
+ function nextTaskId(board) {
1257
+ return nextNumbered(allTasks(board).map((t) => t.id), /^t-(\d+)$/, (n) => `t-${String(n).padStart(2, '0')}`);
1258
+ }
1259
+ function nextColumnId(board) {
1260
+ return nextNumbered(board.columns.map((c) => c.id), /^c(\d+)$/, (n) => `c${n}`);
1261
+ }
1262
+ /** Every column change goes through here, so each column always lists parents before their children. */
1263
+ const withColumns = (board, columns) => validateBoard({ ...board, columns: columns.map((c) => ({ ...c, tasks: treeOrder(c.tasks).map((x) => x.task) })) });
1264
+ /** Replace one task wherever it lives (column or archive). */
1265
+ function mapTask(board, taskId, f) {
1266
+ findTask(board, taskId);
1267
+ const swap = (t) => (t.id === taskId ? f(t) : t);
1268
+ return validateBoard({ ...board, columns: board.columns.map((c) => ({ ...c, tasks: c.tasks.map(swap) })), archive: board.archive.map(swap) });
1269
+ }
1270
+ /** Where a history entry made now would say the task is. */
1271
+ const placeOf = (found) => ({ column: found.col === null ? 'Archive' : found.col.name });
1272
+
1273
+ function setBoardTitle(board, title) { return validateBoard({ ...board, title }); }
1274
+
1275
+ function addTask(board, colId, title, at, parent = '') {
1276
+ const col = findColumn(board, colId);
1277
+ const id = nextTaskId(board);
1278
+ const task = { id, title, description: '', owner: '', tags: [], history: [{ column: col.name, at, owner: '' }], parent };
1279
+ return { board: withColumns(board, board.columns.map((c) => (c.id === colId ? { ...c, tasks: [...c.tasks, task] } : c))), id };
1280
+ }
1281
+
1282
+ /** Owner goes through reassignTask so each handover is recorded; the other fields are plain edits. */
1283
+ const EDITABLE_TASK_FIELDS = ['title', 'description', 'tags'];
1284
+ function updateTask(board, taskId, patch) {
1285
+ for (const key of Object.keys(patch)) if (!EDITABLE_TASK_FIELDS.includes(key)) bug(`updateTask can't change "${key}"`);
1286
+ return mapTask(board, taskId, (t) => ({ ...t, ...patch }));
1287
+ }
1288
+
1289
+ /** Change the owner and log it as a history entry in the task's current place. Same owner = unchanged board. */
1290
+ function reassignTask(board, taskId, owner, at) {
1291
+ const found = findTask(board, taskId);
1292
+ if (found.task.owner === owner) return board;
1293
+ return mapTask(board, taskId, (t) => ({ ...t, owner, history: [...t.history, { ...placeOf(found), at, owner }] }));
1294
+ }
1295
+
1296
+ /** Its children move up to its own parent. */
1297
+ function deleteTask(board, taskId) {
1298
+ const { task } = findTask(board, taskId);
1299
+ const keep = (tasks) => tasks.filter((t) => t.id !== taskId).map((t) => (t.parent === taskId ? { ...t, parent: task.parent } : t));
1300
+ return withColumns({ ...board, archive: keep(board.archive) }, board.columns.map((c) => ({ ...c, tasks: keep(c.tasks) })));
1301
+ }
1302
+
1303
+ /** Move a task before `beforeId` in `toColId` (null = append). Crossing columns appends a history entry at `at`. */
1304
+ function moveTask(board, taskId, toColId, beforeId, at) {
1305
+ if (beforeId === taskId) bug('a task cannot be placed before itself');
1306
+ const { col: from, task } = findTask(board, taskId);
1307
+ if (from === null) bug('moveTask on an archived task; use restoreTask');
1308
+ const to = findColumn(board, toColId);
1309
+ const moved = from.id === to.id ? task : { ...task, history: [...task.history, { column: to.name, at, owner: task.owner }] };
1310
+ return withColumns(board, board.columns.map((c) => {
1311
+ const rest = c.tasks.filter((t) => t.id !== taskId);
1312
+ if (c.id !== to.id) return rest.length === c.tasks.length ? c : { ...c, tasks: rest };
1313
+ const idx = beforeId === null ? rest.length : rest.findIndex((t) => t.id === beforeId);
1314
+ if (idx < 0) fail(`No task "${beforeId}" in column "${to.name}"`);
1315
+ return { ...c, tasks: [...rest.slice(0, idx), moved, ...rest.slice(idx)] };
1316
+ }));
1317
+ }
1318
+
1319
+ /** Completing = moving the task into the hidden archive, logged as a history entry named "Archive". */
1320
+ function archiveTask(board, taskId, at) {
1321
+ const { col, task } = findTask(board, taskId);
1322
+ if (col === null) fail(`"${task.title}" is already archived`);
1323
+ const archived = { ...task, history: [...task.history, { column: 'Archive', at, owner: task.owner }] };
1324
+ return withColumns({ ...board, archive: [...board.archive, archived] }, board.columns.map((c) => (c.id === col.id ? { ...c, tasks: c.tasks.filter((t) => t.id !== taskId) } : c)));
1325
+ }
1326
+
1327
+ /** Bring an archived task back to the end of `colId`. */
1328
+ function restoreTask(board, taskId, colId, at) {
1329
+ const { col: from, task } = findTask(board, taskId);
1330
+ if (from !== null) fail(`"${task.title}" isn't archived`);
1331
+ const to = findColumn(board, colId);
1332
+ const restored = { ...task, history: [...task.history, { column: to.name, at, owner: task.owner }] };
1333
+ return withColumns({ ...board, archive: board.archive.filter((t) => t.id !== taskId) }, board.columns.map((c) => (c.id === to.id ? { ...c, tasks: [...c.tasks, restored] } : c)));
1334
+ }
1335
+
1336
+ /* Settings operations: the markdown header is the single home for these. */
1337
+ const withSettings = (board, settings) => validateBoard({ ...board, settings });
1338
+ function setTheme(board, themeId) { themeById(themeId); return withSettings(board, { ...board.settings, theme: themeId }); }
1339
+ function setThemeSetting(board, themeId, key, raw) {
1340
+ const theme = themeById(themeId);
1341
+ const def = theme.settings[key] ?? bug(`theme "${themeId}" has no setting "${key}"`);
1342
+ const value = coerceSetting(def, raw);
1343
+ return withSettings(board, { ...board.settings, themes: { ...board.settings.themes, [themeId]: { ...board.settings.themes[themeId], [key]: value } } });
1344
+ }
1345
+ /* Badge: a pill of "<symbol>: <count> <icon>" segments, one per chosen column. */
1346
+ const BADGE_COLORS = ['#3b6fd8', '#b7791f', '#7c4dcc', '#16808c', '#c53030'];
1347
+ const BADGE_DONE = '#2f855a'; // the last segment is green: it's usually the done column
1348
+ /** One row per column: whether it's in the badge, its symbol, icon and color (stored, or the defaults), and the color it's drawn in (`fill`). */
1349
+ function badgeRows(board) {
1350
+ const stored = board.settings.badge;
1351
+ const n = board.columns.length;
1352
+ const rows = board.columns.map((col, i) => {
1353
+ const item = stored?.find((b) => b.column === col.name);
1354
+ const icon = i === n - 1 ? '✅' : i === 0 ? '📋' : '⏳';
1355
+ return { column: col.name, count: col.tasks.length, included: stored === null || item !== undefined, symbol: item?.symbol ?? Array.from(col.name)[0].toUpperCase(), icon: item?.icon ?? icon, color: item?.color ?? '' };
1356
+ });
1357
+ // Unset colors follow the palette by position among the shown segments; the last is green.
1358
+ const shown = rows.filter((r) => r.included);
1359
+ return rows.map((r) => { const k = shown.indexOf(r); return { ...r, fill: r.color !== '' ? r.color : k === shown.length - 1 ? BADGE_DONE : BADGE_COLORS[Math.max(k, 0) % BADGE_COLORS.length] }; });
1360
+ }
1361
+ function setBadgeRow(board, index, patch) {
1362
+ const rows = badgeRows(board);
1363
+ if (rows[index] === undefined) bug(`no column ${index} for the badge`);
1364
+ const badge = rows.map((r, i) => (i === index ? { ...r, ...patch } : r)).filter((r) => r.included).map(({ column, symbol, icon, color }) => ({ column, symbol, icon, color }));
1365
+ return withSettings(board, { ...board.settings, badge });
1366
+ }
1367
+ const resetBadge = (board) => withSettings(board, { ...board.settings, badge: null });
1368
+ /** Rough Verdana 11px widths, enough to size the segments (emoji are wider; joiners and variation selectors take none). */
1369
+ const badgeTextWidth = (s) => Array.from(s).reduce((w, ch) => w + (/[\u200d\ufe0f]/.test(ch) ? 0 : /\p{Extended_Pictographic}/u.test(ch) ? 14 : 7), 0);
1370
+ const xmlEscape = (s) => s.replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' })[c]);
1371
+ function badgeSvg(board) {
1372
+ let segs = badgeRows(board).filter((r) => r.included)
1373
+ .map((r) => ({ text: [r.symbol === '' ? `${r.count}` : `${r.symbol}: ${r.count}`, r.icon].filter((x) => x !== '').join(' '), color: r.fill }));
1374
+ if (segs.length === 0) segs = [{ text: 'no columns', color: '#6b7280' }];
1375
+ let x = 0;
1376
+ const parts = segs.map((sg) => { const w = badgeTextWidth(sg.text) + 16; const p = { ...sg, x, w }; x += w; return p; });
1377
+ const label = xmlEscape(segs.map((sg) => sg.text).join(' | '));
1378
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${x}" height="20" role="img" aria-label="${label}"><title>${label}</title>`
1379
+ + `<clipPath id="kb-badge-r"><rect width="${x}" height="20" rx="10"/></clipPath><g clip-path="url(#kb-badge-r)">`
1380
+ + parts.map((p) => `<rect x="${p.x}" width="${p.w}" height="20" fill="${p.color}"/>`).join('')
1381
+ + '</g><g fill="#fff" font-family="Verdana,DejaVu Sans,sans-serif" font-size="11" text-anchor="middle">'
1382
+ + parts.map((p) => `<text x="${p.x + p.w / 2}" y="14">${xmlEscape(p.text)}</text>`).join('')
1383
+ + '</g></svg>';
1384
+ }
1385
+ /** The hosted app that card links open; the CLI takes AGILE_HOST from the environment to point elsewhere. */
1386
+ const AGILE_HOST = 'https://aaronp.github.io/agile/';
1387
+ /** The app at `host` showing the board at `src` (a URL, or a path relative to host). */
1388
+ const boardLink = (host, src) => `${host}?src=${encodeURIComponent(src).replace(/%2F/gi, '/').replace(/%3A/gi, ':')}`;
1389
+ /**
1390
+ * The board as a dashboard card (card.json, the same tool-neutral format as Decision Ledger's): title, a status pill,
1391
+ * one big number and a legend with a count per item. The legend is the badge's columns, in its colors; the last column counts as done.
1392
+ */
1393
+ function boardCard(board, today, source) {
1394
+ const rows = badgeRows(board).filter((r) => r.included);
1395
+ const total = board.columns.reduce((n, c) => n + c.tasks.length, 0);
1396
+ const done = board.columns[board.columns.length - 1]?.tasks.length ?? 0;
1397
+ return {
1398
+ version: 1,
1399
+ title: board.title,
1400
+ subtitle: 'Kanban board',
1401
+ status: total === done ? { label: 'All done', tone: 'good' } : { label: `${total - done} open`, tone: 'neutral' },
1402
+ heading: { primary: `${done}/${total}`, label: 'tasks done' },
1403
+ legend: rows.map((r) => ({ id: r.column, label: r.column, color: r.fill })),
1404
+ report: Object.fromEntries(rows.map((r) => [r.column, r.count])),
1405
+ source,
1406
+ updated: today,
1407
+ };
1408
+ }
1409
+ function resetThemeSettings(board, themeId) {
1410
+ return withSettings(board, { ...board.settings, themes: { ...board.settings.themes, [themeId]: defaultSettings(themeById(themeId)) } });
1411
+ }
1412
+ function setEffect(board, event, choice) {
1413
+ if (!effectChoices(event).includes(choice)) bug(`"${choice}" is not an effect for ${event}`);
1414
+ return withSettings(board, { ...board.settings, effects: { ...board.settings.effects, [event]: choice } });
1415
+ }
1416
+
1417
+ function addColumn(board, name) {
1418
+ const id = nextColumnId(board);
1419
+ return { board: withColumns(board, [...board.columns, { id, name, tasks: [] }]), id };
1420
+ }
1421
+ function renameColumn(board, colId, name) {
1422
+ const old = findColumn(board, colId).name;
1423
+ const badge = board.settings.badge?.map((b) => (b.column === old ? { ...b, column: name } : b)) ?? null; // the badge follows the rename
1424
+ return withColumns(badge === board.settings.badge ? board : { ...board, settings: { ...board.settings, badge } }, board.columns.map((c) => (c.id === colId ? { ...c, name } : c)));
1425
+ }
1426
+ function moveColumn(board, colId, beforeColId) {
1427
+ if (beforeColId === colId) bug('a column cannot be placed before itself');
1428
+ const col = findColumn(board, colId);
1429
+ const rest = board.columns.filter((c) => c.id !== colId);
1430
+ const idx = beforeColId === null ? rest.length : rest.findIndex((c) => c.id === beforeColId);
1431
+ if (idx < 0) fail(`No column "${beforeColId}"`);
1432
+ return withColumns(board, [...rest.slice(0, idx), col, ...rest.slice(idx)]);
1433
+ }
1434
+ function deleteColumn(board, colId) {
1435
+ const col = findColumn(board, colId);
1436
+ if (col.tasks.length > 0) fail(`Column "${col.name}" still has ${col.tasks.length} task(s). Move or delete them first.`);
1437
+ return withColumns(board, board.columns.filter((c) => c.id !== colId));
1438
+ }
1439
+
1440
+ /** Filter = { query: string, tags: string[], owners: string[] ('' = unassigned) }. Tags match any-of. */
1441
+ function taskMatches(task, filter) {
1442
+ const words = filter.query.trim().toLowerCase().split(/\s+/).filter((w) => w !== '');
1443
+ if (words.length > 0) {
1444
+ const hay = [task.title, task.description, task.owner, ...task.tags].join('\n').toLowerCase();
1445
+ if (!words.every((w) => hay.includes(w))) return false;
1446
+ }
1447
+ if (filter.tags.length > 0 && !filter.tags.some((t) => task.tags.includes(t))) return false;
1448
+ if (filter.owners.length > 0 && !filter.owners.includes(task.owner)) return false;
1449
+ return true;
1450
+ }
1451
+
1452
+ const normalizeOwner = (raw) => raw.trim().replace(/\s+/g, ' ');
1453
+
1454
+ function hashString(s) {
1455
+ let h = 2166136261;
1456
+ for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
1457
+ return h >>> 0;
1458
+ }
1459
+ const hueOf = (s) => hashString(s) % 360;
1460
+ const initialsOf = (name) => name.split(/\s+/).filter((w) => w !== '').slice(0, 2).map((w) => w[0].toUpperCase()).join('');
1461
+
1462
+ function formatDuration(ms) {
1463
+ if (ms < 0) return 'clock went backwards';
1464
+ if (ms < 60000) return '<1m';
1465
+ const min = Math.round(ms / 60000);
1466
+ if (min < 60) return `${min}m`;
1467
+ const h = Math.floor(min / 60);
1468
+ if (h < 48) return `${h}h ${min % 60}m`;
1469
+ const d = Math.floor(h / 24);
1470
+ return `${d}d ${h % 24}h`;
1471
+ }
1472
+ const STAMP_FORMAT = new Intl.DateTimeFormat('en-GB', { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit', timeZone: 'UTC' });
1473
+ const formatStamp = (iso) => `${STAMP_FORMAT.format(new Date(iso))} UTC`;
1474
+
1475
+ /** `nowMs` is passed in (the UI ticks it), so the open-ended last stay is measured without reading the clock here. */
1476
+ /**
1477
+ * The board as its history says it stood at `at` (ISO): each task in the column it last entered by then, with the owner logged
1478
+ * there; tasks logged into "Archive" by then are in the archive. Tasks added later are left out, and so are deleted ones (the file
1479
+ * doesn't keep them). Titles, tags and descriptions are today's. Columns since renamed or removed come back, after today's.
1480
+ */
1481
+ function boardAt(board, at) {
1482
+ const t = Date.parse(at);
1483
+ const columns = board.columns.map((c) => ({ ...c, tasks: [] }));
1484
+ const archive = [];
1485
+ for (const task of allTasks(board)) {
1486
+ const past = task.history.filter((h) => Date.parse(h.at) <= t);
1487
+ if (past.length === 0) continue;
1488
+ const last = past[past.length - 1];
1489
+ const then = { ...task, owner: last.owner, history: past };
1490
+ if (last.column === 'Archive') { archive.push(then); continue; }
1491
+ let col = columns.find((c) => c.name === last.column);
1492
+ if (col === undefined) { col = { id: `c${columns.length + 1}`, name: last.column, tasks: [] }; columns.push(col); }
1493
+ col.tasks.push(then);
1494
+ }
1495
+ const ids = new Set([...columns.flatMap((c) => c.tasks), ...archive].map((x) => x.id));
1496
+ const orphan = (x) => (x.parent === '' || ids.has(x.parent) ? x : { ...x, parent: '' }); // a parent added later
1497
+ return { ...board, columns: columns.map((c) => ({ ...c, tasks: c.tasks.map(orphan) })), archive: archive.map(orphan) };
1498
+ }
1499
+ /** Every history entry on the board, oldest first: the time slider's steps. */
1500
+ const historyEvents = (board) => allTasks(board).flatMap((task) => task.history.map((h) => ({ ...h, title: task.title })))
1501
+ .sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
1502
+ function historyView(task, nowMs) {
1503
+ return task.history.map((h, i) => {
1504
+ const next = task.history[i + 1];
1505
+ const end = next === undefined ? nowMs : Date.parse(next.at);
1506
+ const dur = formatDuration(end - Date.parse(h.at));
1507
+ const prev = task.history[i - 1];
1508
+ const reassigned = prev !== undefined && prev.column === h.column && prev.owner !== h.owner;
1509
+ return {
1510
+ column: h.column,
1511
+ title: reassigned ? `Reassigned to ${h.owner === '' ? 'nobody' : h.owner}` : h.column,
1512
+ label: i === 0 ? `Created ${formatStamp(h.at)}` : formatStamp(h.at),
1513
+ owner: h.owner === '' ? 'Unassigned' : h.owner,
1514
+ duration: next === undefined ? `${dur} so far` : `${dur} here`,
1515
+ };
1516
+ });
1517
+ }
1518
+
1519
+ /** Total time per column name, summed over every stay (the current one runs to nowMs), in order of first visit. */
1520
+ function historySummary(task, nowMs) {
1521
+ const totals = new Map();
1522
+ task.history.forEach((h, i) => {
1523
+ const next = task.history[i + 1];
1524
+ const end = next === undefined ? nowMs : Date.parse(next.at);
1525
+ totals.set(h.column, (totals.get(h.column) ?? 0) + Math.max(0, end - Date.parse(h.at)));
1526
+ });
1527
+ return [...totals].map(([column, ms]) => ({ column, duration: formatDuration(ms) }));
1528
+ }
1529
+
1530
+ /* ---------- (3b) Description markdown: a small, safe renderer (no HTML, data only) ---------- */
1531
+
1532
+ const MD_LIST = /^(\s*)([-*+]|\d+[.)])\s+(?:\[( |x|X)\]\s+)?(.*)$/;
1533
+ const MD_FENCE = /^\s*(`{3,}|~{3,})/;
1534
+ const MD_HEADING = /^(#{1,6})\s+(.*)$/;
1535
+ const MD_RULE = /^\s{0,3}([-*_])(\s*\1){2,}\s*$/;
1536
+ const MD_QUOTE = /^\s*>/;
1537
+ const isMdBlockStart = (l) => MD_FENCE.test(l) || MD_HEADING.test(l) || MD_RULE.test(l) || MD_QUOTE.test(l) || MD_LIST.test(l);
1538
+
1539
+ /**
1540
+ * Block = { type: 'para'|'heading'|'quote'|'code'|'rule'|'list', text?, level?,
1541
+ * items?: [{ indent, marker, check: null|boolean, text, line }] }.
1542
+ * `line` is the item's 0-based line in `text`, so a checkbox click can flip exactly that line.
1543
+ */
1544
+ function parseMarkdown(text) {
1545
+ const lines = text.split('\n');
1546
+ const blocks = [];
1547
+ let i = 0;
1548
+ while (i < lines.length) {
1549
+ const line = lines[i];
1550
+ let m;
1551
+ if (line.trim() === '') { i++; continue; }
1552
+ if ((m = MD_FENCE.exec(line)) !== null) {
1553
+ const close = new RegExp(`^\\s*\\${m[1][0]}{${m[1].length},}\\s*$`);
1554
+ const body = [];
1555
+ i++;
1556
+ while (i < lines.length && !close.test(lines[i])) { body.push(lines[i]); i++; }
1557
+ i++;
1558
+ blocks.push({ type: 'code', text: body.join('\n') });
1559
+ continue;
1560
+ }
1561
+ if ((m = MD_HEADING.exec(line)) !== null) { blocks.push({ type: 'heading', level: m[1].length, text: m[2].replace(/\s+#+\s*$/, '') }); i++; continue; }
1562
+ if (MD_RULE.test(line)) { blocks.push({ type: 'rule' }); i++; continue; }
1563
+ if (MD_QUOTE.test(line)) {
1564
+ const body = [];
1565
+ while (i < lines.length && MD_QUOTE.test(lines[i])) { body.push(lines[i].replace(/^\s*>\s?/, '')); i++; }
1566
+ blocks.push({ type: 'quote', text: body.join('\n') });
1567
+ continue;
1568
+ }
1569
+ if (MD_LIST.test(line)) {
1570
+ const items = [];
1571
+ while (i < lines.length) {
1572
+ const lm = MD_LIST.exec(lines[i]);
1573
+ if (lm !== null) {
1574
+ items.push({ indent: lm[1].replace(/\t/g, ' ').length, marker: lm[2], check: lm[3] === undefined ? null : lm[3] !== ' ', text: lm[4], line: i });
1575
+ i++;
1576
+ continue;
1577
+ }
1578
+ if (lines[i].trim() !== '' && /^\s+/.test(lines[i])) { items[items.length - 1].text += `\n${lines[i].trim()}`; i++; continue; }
1579
+ break;
1580
+ }
1581
+ blocks.push({ type: 'list', items });
1582
+ continue;
1583
+ }
1584
+ const body = [];
1585
+ while (i < lines.length && lines[i].trim() !== '' && (body.length === 0 || !isMdBlockStart(lines[i]))) { body.push(lines[i]); i++; }
1586
+ blocks.push({ type: 'para', text: body.join('\n') });
1587
+ }
1588
+ return blocks;
1589
+ }
1590
+
1591
+ const safeHref = (url) => (/^(https?:\/\/|mailto:)/i.test(url) ? url : null);
1592
+
1593
+ /** Inline markdown -> flat spans { text, bold, italic, strike, code, href }. Escapes with backslash. */
1594
+ function parseInline(text, flags) {
1595
+ const base = flags ?? { bold: false, italic: false, strike: false, code: false, href: null };
1596
+ const out = [];
1597
+ let buf = '';
1598
+ let i = 0;
1599
+ const flush = () => { if (buf !== '') { out.push({ ...base, text: buf }); buf = ''; } };
1600
+ while (i < text.length) {
1601
+ const rest = text.slice(i);
1602
+ const prev = i === 0 ? '' : text[i - 1];
1603
+ let m;
1604
+ if (rest[0] === '\\' && rest.length > 1 && /[\\`*_~[\]()#>!-]/.test(rest[1])) { buf += rest[1]; i += 2; continue; }
1605
+ if ((m = /^`([^`]+)`/.exec(rest)) !== null) { flush(); out.push({ ...base, code: true, text: m[1] }); i += m[0].length; continue; }
1606
+ if ((m = /^\[([^\]]+)\]\(([^)\s]+)\)/.exec(rest)) !== null) {
1607
+ flush();
1608
+ out.push(...parseInline(m[1], { ...base, href: safeHref(m[2]) }));
1609
+ i += m[0].length;
1610
+ continue;
1611
+ }
1612
+ if ((m = /^\*\*\*(?=\S)([\s\S]*?\S)\*\*\*/.exec(rest)) !== null) { flush(); out.push(...parseInline(m[1], { ...base, bold: true, italic: true })); i += m[0].length; continue; }
1613
+ if ((m = /^(\*\*|__)(?=\S)([\s\S]*?\S)\1(?![*_])/.exec(rest)) !== null && !(m[1] === '__' && /\w/.test(prev))) { flush(); out.push(...parseInline(m[2], { ...base, bold: true })); i += m[0].length; continue; }
1614
+ if ((m = /^~~(?=\S)([\s\S]*?\S)~~/.exec(rest)) !== null) { flush(); out.push(...parseInline(m[1], { ...base, strike: true })); i += m[0].length; continue; }
1615
+ if ((m = /^(\*|_)(?=\S)([\s\S]*?\S)\1(?!\1)/.exec(rest)) !== null && !(m[1] === '_' && /\w/.test(prev))) { flush(); out.push(...parseInline(m[2], { ...base, italic: true })); i += m[0].length; continue; }
1616
+ buf += rest[0];
1617
+ i++;
1618
+ }
1619
+ flush();
1620
+ return out;
1621
+ }
1622
+
1623
+ /** Render-ready view of description markdown. `opts.links`: real anchors; `opts.onToggle(line)`: checkbox handler. */
1624
+ function markdownView(text, opts) {
1625
+ const spans = (s) => parseInline(s).map((sp) => {
1626
+ const cls = ['md-span', sp.bold ? 'md-b' : '', sp.italic ? 'md-i' : '', sp.strike ? 'md-s' : '', sp.code ? 'md-code' : '', sp.href !== null ? 'md-a' : ''].filter((c) => c !== '').join(' ');
1627
+ const isLink = opts.links && sp.href !== null;
1628
+ return { text: sp.text, cls, isLink, isPlain: !isLink, href: sp.href ?? '' };
1629
+ });
1630
+ return parseMarkdown(text).map((b) => ({
1631
+ isPara: b.type === 'para', isHeading: b.type === 'heading', isQuote: b.type === 'quote', isCode: b.type === 'code', isRule: b.type === 'rule', isList: b.type === 'list',
1632
+ spans: b.type === 'para' || b.type === 'heading' || b.type === 'quote' ? spans(b.text) : [],
1633
+ text: b.type === 'code' ? b.text : '',
1634
+ items: b.type !== 'list' ? [] : b.items.map((it) => {
1635
+ const level = Math.min(Math.floor(it.indent / 2), 4);
1636
+ return {
1637
+ style: `padding-left: ${level * 16}px`,
1638
+ isCheck: it.check !== null, isMarker: it.check === null, checked: it.check === true,
1639
+ checkLabel: it.check === true ? 'Mark not done' : 'Mark done',
1640
+ marker: /\d/.test(it.marker) ? it.marker.replace(')', '.') : level === 0 ? '•' : '◦',
1641
+ bodyCls: it.check === true ? 'md-li-body md-done' : 'md-li-body',
1642
+ spans: spans(it.text),
1643
+ toggle: () => opts.onToggle(it.line),
1644
+ };
1645
+ }),
1646
+ }));
1647
+ }
1648
+
1649
+ function toggleCheckLine(text, line) {
1650
+ const lines = text.split('\n');
1651
+ if (line < 0 || line >= lines.length) bug(`checkbox line ${line} is outside the description`);
1652
+ const m = /^(\s*(?:[-*+]|\d+[.)])\s+)\[( |x|X)\]/.exec(lines[line]);
1653
+ if (m === null) bug(`line ${line} has no checkbox`);
1654
+ lines[line] = `${m[1]}[${m[2] === ' ' ? 'x' : ' '}]${lines[line].slice(m[0].length)}`;
1655
+ return lines.join('\n');
1656
+ }
1657
+
1658
+ /* Editor formatting: pure (text, selection) -> (text, selection) transforms behind the toolbar and shortcuts. */
1659
+
1660
+ const INLINE_MARKS = { bold: '**', italic: '*', strike: '~~', code: '`' };
1661
+ const LINE_FORMATS = {
1662
+ heading: { re: /^#{1,6}\s+/, make: () => '### ' },
1663
+ bullet: { re: /^(\s*)[-*+]\s+(?!\[[ xX]\]\s)/, make: (indent) => `${indent}- ` },
1664
+ number: { re: /^(\s*)\d+[.)]\s+/, make: (indent, n) => `${indent}${n}. ` },
1665
+ check: { re: /^(\s*)[-*+]\s+\[[ xX]\]\s+/, make: (indent) => `${indent}- [ ] ` },
1666
+ quote: { re: /^>\s?/, make: () => '> ' },
1667
+ };
1668
+ const ANY_LINE_PREFIX = /^(\s*)(?:#{1,6}\s+|>\s?|[-*+]\s+\[[ xX]\]\s+|[-*+]\s+|\d+[.)]\s+)/;
1669
+
1670
+ function applyFormat(text, start, end, kind) {
1671
+ if (start > end) bug('selection start after end');
1672
+ if (kind in INLINE_MARKS) {
1673
+ const mark = INLINE_MARKS[kind];
1674
+ let s = start;
1675
+ let e = end;
1676
+ while (s < e && /\s/.test(text[s])) s++;
1677
+ while (e > s && /\s/.test(text[e - 1])) e--;
1678
+ const n = mark.length;
1679
+ const sel = text.slice(s, e);
1680
+ const wrappedOutside = text.slice(s - n, s) === mark && text.slice(e, e + n) === mark
1681
+ && !(kind === 'italic' && text[s - n - 1] === '*' && text[e + n] === '*' && text.slice(s - 3, s) !== '***');
1682
+ if (wrappedOutside) return { text: text.slice(0, s - n) + sel + text.slice(e + n), start: s - n, end: e - n };
1683
+ if (sel.length >= 2 * n && sel.startsWith(mark) && sel.endsWith(mark)) {
1684
+ const inner = sel.slice(n, sel.length - n);
1685
+ return { text: text.slice(0, s) + inner + text.slice(e), start: s, end: s + inner.length };
1686
+ }
1687
+ return { text: `${text.slice(0, s)}${mark}${sel}${mark}${text.slice(e)}`, start: s + n, end: e + n };
1688
+ }
1689
+ if (kind === 'link') {
1690
+ const sel = text.slice(start, end);
1691
+ if (sel === '') {
1692
+ const ins = '[link text](https://)';
1693
+ return { text: text.slice(0, start) + ins + text.slice(end), start: start + 1, end: start + 10 };
1694
+ }
1695
+ const ins = `[${sel}](https://)`;
1696
+ const urlStart = start + sel.length + 3;
1697
+ return { text: text.slice(0, start) + ins + text.slice(end), start: urlStart, end: urlStart + 8 };
1698
+ }
1699
+ const fmt = LINE_FORMATS[kind];
1700
+ if (fmt === undefined) bug(`unknown format "${kind}"`);
1701
+ const lineStart = text.lastIndexOf('\n', start - 1) + 1;
1702
+ const endAt = end > start && text[end - 1] === '\n' ? end - 1 : end;
1703
+ const nl = text.indexOf('\n', endAt);
1704
+ const lineEnd = nl === -1 ? text.length : nl;
1705
+ const lines = text.slice(lineStart, lineEnd).split('\n');
1706
+ const content = lines.filter((l) => l.trim() !== '');
1707
+ const allHave = content.length > 0 && content.every((l) => fmt.re.test(l));
1708
+ let n = 0;
1709
+ const next = lines.map((l) => {
1710
+ if (allHave) return l.replace(fmt.re, (all, indent) => (kind === 'heading' || kind === 'quote' ? '' : indent ?? ''));
1711
+ if (l.trim() === '' && lines.length > 1) return l;
1712
+ const pm = ANY_LINE_PREFIX.exec(l);
1713
+ const indent = pm === null ? (/^\s*/.exec(l)[0]) : pm[1];
1714
+ const body = pm === null ? l.trimStart() : l.slice(pm[0].length);
1715
+ n++;
1716
+ return fmt.make(kind === 'heading' || kind === 'quote' ? '' : indent, n) + body;
1717
+ });
1718
+ const block = next.join('\n');
1719
+ const single = lines.length === 1 && start === end;
1720
+ const caret = lineStart + block.length;
1721
+ return { text: text.slice(0, lineStart) + block + text.slice(lineEnd), start: single ? caret : lineStart, end: caret };
1722
+ }
1723
+
1724
+ /** Enter inside a list or quote line: continue it, or end it when the item is empty. null = not a list line. */
1725
+ function continueList(text, start, end) {
1726
+ if (start !== end) return null;
1727
+ const lineStart = text.lastIndexOf('\n', start - 1) + 1;
1728
+ const nl = text.indexOf('\n', start);
1729
+ const line = text.slice(lineStart, nl === -1 ? text.length : nl);
1730
+ const m = /^(\s*)(?:([-*+])|(\d+)([.)]))\s+(\[[ xX]\]\s+)?/.exec(line) ?? /^(>\s?)/.exec(line);
1731
+ if (m === null) return null;
1732
+ if (start < lineStart + m[0].length) return null;
1733
+ if (line.slice(m[0].length).trim() === '') {
1734
+ const t = text.slice(0, lineStart) + text.slice(lineStart + m[0].length);
1735
+ return { text: t, start: lineStart, end: lineStart };
1736
+ }
1737
+ const prefix = m[0].startsWith('>') ? '> ' : `${m[1]}${m[2] !== undefined ? m[2] : `${Number(m[3]) + 1}${m[4]}`} ${m[5] !== undefined ? '[ ] ' : ''}`;
1738
+ const ins = `\n${prefix}`;
1739
+ return { text: text.slice(0, start) + ins + text.slice(end), start: start + ins.length, end: start + ins.length };
1740
+ }
1741
+
1742
+ const FORMAT_BUTTONS = [
1743
+ { kind: 'bold', label: 'Bold', keys: 'Ctrl/⌘ B', d: 'M7 5h6a3.5 3.5 0 0 1 0 7H7z M7 12h7a3.5 3.5 0 0 1 0 7H7z' },
1744
+ { kind: 'italic', label: 'Italic', keys: 'Ctrl/⌘ I', d: 'M19 4h-9 M14 20H5 M15 4 9 20' },
1745
+ { kind: 'strike', label: 'Strikethrough', keys: 'Ctrl/⌘ Shift X', d: 'M16 5H10a3 3 0 0 0-1 5.8 M14 12a3.5 3.5 0 0 1-1 7H7 M4 12h16' },
1746
+ { kind: 'code', label: 'Inline code', keys: 'Ctrl/⌘ E', d: 'm16 18 6-6-6-6 M8 6l-6 6 6 6' },
1747
+ { kind: 'link', label: 'Link', keys: 'Ctrl/⌘ K', d: 'M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7 M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7', sep: true },
1748
+ { kind: 'heading', label: 'Heading', keys: '', d: 'M6 4v16 M18 4v16 M6 12h12' },
1749
+ { kind: 'bullet', label: 'Bulleted list', keys: '', d: 'M9 6h12 M9 12h12 M9 18h12 M4 6h.01 M4 12h.01 M4 18h.01' },
1750
+ { kind: 'number', label: 'Numbered list', keys: '', d: 'M10 6h11 M10 12h11 M10 18h11 M4 4h1v5 M4 9h2 M6 19H4c0-1.5 2-2 2-3.3 0-.8-.6-1.2-1.2-1.2-.6 0-1 .3-1.2.8' },
1751
+ { kind: 'check', label: 'Checklist', keys: '', d: 'm3 6 2 2 3-3 M3 16l2 2 3-3 M12 7h9 M12 17h9' },
1752
+ { kind: 'quote', label: 'Quote', keys: '', d: 'M4 5v14 M9 7h11 M9 12h11 M9 17h7' },
1753
+ ];
1754
+
1755
+ /* ---------- (4) Themes: registry of settings schemas + CSS variable mappers ---------- */
1756
+
1757
+ const DENSITY = {
1758
+ compact: { pad: '8px 10px', gap: '6px', colPad: '8px', title: '13px' },
1759
+ comfortable: { pad: '12px', gap: '8px', colPad: '10px', title: '14px' },
1760
+ roomy: { pad: '16px', gap: '12px', colPad: '12px', title: '15px' },
1761
+ };
1762
+ const BALL_PALETTES = {
1763
+ candy: ['#ff5d73', '#ffb347', '#ffd93d', '#4cc9f0', '#7b6cf6', '#45d483'],
1764
+ primary: ['#e63946', '#f4c430', '#1d4ed8', '#1b1b1b'],
1765
+ sea: ['#0b6e99', '#14a3c7', '#7fd1e3', '#f2f2ea', '#f4a259'],
1766
+ mono: ['#222222', '#555555', '#8a8a8a', '#c4c4c4'],
1767
+ };
1768
+
1769
+ function hexToRgb(hex) {
1770
+ const m = /^#([0-9a-f]{6})$/i.exec(hex);
1771
+ if (m === null) fail(`"${hex}" is not a #rrggbb colour`);
1772
+ const n = parseInt(m[1], 16);
1773
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
1774
+ }
1775
+ const rgba = (hex, a) => { const [r, g, b] = hexToRgb(hex); return `rgba(${r}, ${g}, ${b}, ${a})`; };
1776
+ const luminance = (hex) => {
1777
+ const lin = hexToRgb(hex).map((c) => { const s = c / 255; return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4; });
1778
+ return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2];
1779
+ };
1780
+ const readableOn = (hex) => (luminance(hex) > 0.4 ? '#111111' : '#ffffff');
1781
+
1782
+ const FONT_SANS = "'Geist', ui-sans-serif, system-ui, sans-serif";
1783
+ const FONT_MONO = "'Geist Mono', ui-monospace, Menlo, monospace";
1784
+
1785
+ const BASE_VARS = {
1786
+ '--font': FONT_SANS, '--font-title': FONT_SANS, '--mono': FONT_MONO,
1787
+ '--glow': 'none', '--header-blur': 'none', '--card-blur': 'none',
1788
+ '--col-w': '296px', '--col-gap': '14px', '--col-border': '1px solid transparent',
1789
+ // Controls and borders on panels (drawer, style, dialogs); a theme whose panel differs from its board sets its own.
1790
+ '--panel-control': 'var(--control)', '--panel-line': 'var(--line)',
1791
+ '--col-head-shadow': 'none', '--danger-bg': '#fde8e8', '--danger-fg': '#9b1c1c', '--tilt': '0', '--code-bg': 'rgba(127,127,127,.16)',
1792
+ };
1793
+
1794
+ /**
1795
+ * The Decision Ledger styles (aaronp.github.io/adr): one palette each, mapped onto the board's variables.
1796
+ * `grid` draws the ruled-paper background.
1797
+ */
1798
+ const PLEX_SANS = "'IBM Plex Sans', system-ui, -apple-system, 'Segoe UI', sans-serif";
1799
+ const PLEX_MONO = "'IBM Plex Mono', ui-monospace, SFMono-Regular, Menlo, monospace";
1800
+ function ledgerTheme({ id, name, blurb, dark, grid, radius, display, c }) {
1801
+ return {
1802
+ id, name, blurb, effect: null,
1803
+ settings: {
1804
+ accent: { type: 'color', label: 'Accent', default: c.mark, doc: 'Selection, focus rings, active toggles.' },
1805
+ grid: { type: 'boolean', label: 'Grid', default: grid, doc: 'Ruled grid behind the columns.' },
1806
+ },
1807
+ vars: (s) => ({
1808
+ '--bg': s.grid ? `linear-gradient(${c.grid} 1px, transparent 1px) 0 0 / 24px 24px, linear-gradient(90deg, ${c.grid} 1px, transparent 1px) 0 0 / 24px 24px, ${c.bg}` : c.bg,
1809
+ '--fg': c.ink, '--muted': c.muted, '--line': c.border, '--surface': rgba(c.mutedBg, 0.7), '--control': c.surface,
1810
+ '--card': c.surface, '--card-fg': c.ink, '--card-muted': c.muted, '--card-border': c.border,
1811
+ '--card-shadow': dark ? 'none' : '0 1px 2px rgba(0,0,0,.06)', '--card-shadow-hover': `0 0 0 1px ${c.borderStrong}`,
1812
+ '--header-bg': c.bg, '--panel': c.surface, '--panel-fg': c.ink, '--panel-muted': c.muted,
1813
+ '--panel-control': c.surface2, '--panel-line': c.controlBorder,
1814
+ '--source-bg': c.surface, '--placeholder': c.highlight, '--col-head-fg': c.ink,
1815
+ '--accent': s.accent, '--accent-fg': readableOn(s.accent), '--radius': radius,
1816
+ '--pad': '12px', '--gap': '10px', '--col-pad': '10px', '--card-title-size': '14px',
1817
+ '--font': PLEX_SANS, '--font-title': display, '--mono': PLEX_MONO,
1818
+ '--tag-l': dark ? '0.36' : '0.92', '--tag-c': dark ? '0.07' : '0.05', '--tag-fg': c.ink,
1819
+ '--danger-bg': c.badBg, '--danger-fg': c.badFg, '--code-bg': c.mutedBg,
1820
+ }),
1821
+ swatch: (s) => [c.bg, c.ink, s.accent],
1822
+ };
1823
+ }
1824
+ const BRICOLAGE = "'Bricolage Grotesque', system-ui, sans-serif";
1825
+
1826
+ /**
1827
+ * Theme = {
1828
+ * id: stable key (stored with the user's choice),
1829
+ * name / blurb: picker copy,
1830
+ * effect: null | 'ocean' | 'ballpit' (which WebGL background to run),
1831
+ * settings: { key: Setting } where Setting = { type: 'color'|'range'|'select'|'boolean', label, default, doc, ...range/select extras },
1832
+ * vars(settings) -> CSS custom properties applied to the board root,
1833
+ * swatch(settings) -> 3 colours for the picker tile.
1834
+ * }
1835
+ * Add a style by appending to THEMES; nothing else needs to change.
1836
+ */
1837
+ const THEMES = [
1838
+ {
1839
+ id: 'minimal', name: 'Minimal', blurb: 'Hairlines and type, no effects.', effect: null,
1840
+ settings: {
1841
+ accent: { type: 'color', label: 'Accent', default: '#2f5bea', doc: 'Selection, focus rings, active toggles.' },
1842
+ dark: { type: 'boolean', label: 'Dark', default: false, doc: 'Near-black ground for low light.' },
1843
+ radius: { type: 'range', label: 'Corners', min: 0, max: 16, step: 1, unit: 'px', default: 6, doc: 'Rounding of cards, columns and controls.' },
1844
+ density: { type: 'select', label: 'Density', options: ['compact', 'comfortable', 'roomy'], default: 'comfortable', doc: 'Card padding and gaps.' },
1845
+ },
1846
+ vars: (s) => {
1847
+ const d = DENSITY[s.density] ?? bug(`density "${s.density}"`);
1848
+ const dark = s.dark;
1849
+ return {
1850
+ '--bg': dark ? '#111113' : '#fafaf9', '--fg': dark ? '#ececee' : '#18181b', '--muted': dark ? '#a1a1aa' : '#63636b',
1851
+ '--line': dark ? '#2c2c31' : '#e4e4e7', '--surface': dark ? '#18181b' : '#f2f2f1', '--control': dark ? '#1c1c20' : '#ffffff',
1852
+ '--card': dark ? '#202024' : '#ffffff', '--card-fg': dark ? '#ececee' : '#18181b', '--card-muted': dark ? '#a1a1aa' : '#5f5f67',
1853
+ '--card-border': dark ? '#2c2c31' : '#e4e4e7', '--card-shadow': dark ? 'none' : '0 1px 0 rgba(0,0,0,.04)', '--card-shadow-hover': dark ? '0 0 0 1px #3a3a40' : '0 2px 8px rgba(0,0,0,.08)',
1854
+ '--header-bg': dark ? '#111113' : '#fafaf9', '--panel': dark ? '#18181b' : '#ffffff', '--panel-fg': dark ? '#ececee' : '#18181b', '--panel-muted': dark ? '#a1a1aa' : '#63636b',
1855
+ '--source-bg': dark ? '#141416' : '#ffffff', '--placeholder': 'transparent',
1856
+ '--col-head-fg': dark ? '#ececee' : '#18181b',
1857
+ '--accent': s.accent, '--accent-fg': readableOn(s.accent), '--radius': `${s.radius}px`,
1858
+ '--pad': d.pad, '--gap': d.gap, '--col-pad': d.colPad, '--card-title-size': d.title,
1859
+ '--tag-l': dark ? '0.36' : '0.93', '--tag-c': dark ? '0.06' : '0.045', '--tag-fg': dark ? '#ececee' : '#27272a',
1860
+ ...(dark ? { '--danger-bg': '#3b1414', '--danger-fg': '#fca5a5' } : {}),
1861
+ };
1862
+ },
1863
+ swatch: (s) => [s.dark ? '#111113' : '#fafaf9', s.dark ? '#202024' : '#ffffff', s.accent],
1864
+ },
1865
+ {
1866
+ id: 'paper', name: 'Paper', blurb: 'Index cards on a warm desk.', effect: null,
1867
+ settings: {
1868
+ paper: { type: 'color', label: 'Desk', default: '#efe8dc', doc: 'Ground colour behind the columns.' },
1869
+ ink: { type: 'color', label: 'Ink', default: '#2f4b8f', doc: 'Accent and selected states, like a fountain pen.' },
1870
+ shadow: { type: 'range', label: 'Shadow', min: 0, max: 1, step: 0.05, default: 0.5, doc: 'How far the cards lift off the desk.' },
1871
+ tilt: { type: 'range', label: 'Tilt', min: 0, max: 2, step: 0.1, unit: '°', default: 0.6, doc: 'Hand-placed rotation of cards.' },
1872
+ },
1873
+ vars: (s) => ({
1874
+ '--bg': s.paper, '--fg': '#2b2622', '--muted': '#5f574e', '--line': 'rgba(60,45,30,.18)', '--surface': 'rgba(60,45,30,.045)',
1875
+ '--control': '#fffdf8', '--card': '#fffdf7', '--card-fg': '#2b2622', '--card-muted': '#5f574e', '--card-border': 'rgba(60,45,30,.12)',
1876
+ '--card-shadow': `0 1px 2px rgba(60,40,20,.10), 0 ${Math.round(2 + s.shadow * 10)}px ${Math.round(4 + s.shadow * 22)}px rgba(60,40,20,${(s.shadow * 0.2).toFixed(2)})`,
1877
+ '--card-shadow-hover': `0 2px 4px rgba(60,40,20,.12), 0 ${Math.round(4 + s.shadow * 14)}px ${Math.round(8 + s.shadow * 28)}px rgba(60,40,20,${(s.shadow * 0.26).toFixed(2)})`,
1878
+ '--header-bg': 'transparent', '--panel': '#fffdf8', '--panel-fg': '#2b2622', '--panel-muted': '#5f574e', '--source-bg': '#fffdf8', '--placeholder': 'rgba(47,75,143,.05)',
1879
+ '--col-head-fg': '#2b2622', '--accent': s.ink, '--accent-fg': readableOn(s.ink), '--radius': '2px',
1880
+ '--pad': '14px', '--gap': '12px', '--col-pad': '10px', '--card-title-size': '17px',
1881
+ '--font-title': "'Newsreader', Georgia, 'Times New Roman', serif", '--tilt': String(s.tilt),
1882
+ '--tag-l': '0.9', '--tag-c': '0.05', '--tag-fg': '#2b2622',
1883
+ }),
1884
+ swatch: (s) => [s.paper, '#fffdf7', s.ink],
1885
+ },
1886
+ {
1887
+ id: 'terminal', name: 'Terminal', blurb: 'Phosphor on black, monospace.', effect: null,
1888
+ settings: {
1889
+ phosphor: { type: 'color', label: 'Phosphor', default: '#4cf08a', doc: 'Text and line colour.' },
1890
+ glow: { type: 'range', label: 'Glow', min: 0, max: 1, step: 0.05, default: 0.4, doc: 'Bloom around text.' },
1891
+ scanlines: { type: 'boolean', label: 'Scanlines', default: true, doc: 'CRT line overlay.' },
1892
+ },
1893
+ vars: (s) => {
1894
+ const p = s.phosphor;
1895
+ return {
1896
+ '--bg': '#070907', '--fg': p, '--muted': rgba(p, 0.72), '--line': rgba(p, 0.32), '--surface': 'transparent', '--control': '#0b0f0b',
1897
+ '--card': 'rgba(7,9,7,.85)', '--card-fg': p, '--card-muted': rgba(p, 0.72), '--card-border': rgba(p, 0.45), '--card-shadow': 'none', '--card-shadow-hover': `0 0 0 1px ${p}`,
1898
+ '--header-bg': '#070907', '--panel': '#0a0d0a', '--panel-fg': p, '--panel-muted': rgba(p, 0.72), '--source-bg': '#070907', '--placeholder': rgba(p, 0.06),
1899
+ '--col-head-fg': p, '--col-border': `1px dashed ${rgba(p, 0.25)}`, '--accent': p, '--accent-fg': '#070907', '--radius': '0px',
1900
+ '--pad': '10px 12px', '--gap': '8px', '--col-pad': '10px', '--card-title-size': '13px',
1901
+ '--font': "'JetBrains Mono', ui-monospace, Menlo, monospace", '--font-title': "'JetBrains Mono', ui-monospace, Menlo, monospace", '--mono': "'JetBrains Mono', ui-monospace, Menlo, monospace",
1902
+ '--glow': s.glow > 0 ? `0 0 ${(s.glow * 8).toFixed(1)}px ${rgba(p, 0.7)}` : 'none',
1903
+ '--tag-l': '0.2', '--tag-c': '0', '--tag-fg': p, '--danger-bg': '#2a0b0b', '--danger-fg': '#ff8a8a',
1904
+ };
1905
+ },
1906
+ swatch: (s) => ['#070907', s.phosphor, rgba(s.phosphor, 0.4)],
1907
+ },
1908
+ {
1909
+ id: 'ocean', name: 'Ocean', blurb: 'WebGL water; drag cards to make wakes.', effect: 'ocean',
1910
+ settings: {
1911
+ deep: { type: 'color', label: 'Deep water', default: '#06283d', doc: 'Colour in the troughs.' },
1912
+ shallow: { type: 'color', label: 'Shallows', default: '#1f8fb3', doc: 'Colour on the crests and highlights.' },
1913
+ swell: { type: 'range', label: 'Swell', min: 0, max: 1, step: 0.05, default: 0.45, doc: 'Height of the ambient waves.' },
1914
+ wake: { type: 'range', label: 'Wake', min: 0, max: 2, step: 0.05, default: 1, doc: 'How hard a dragged card pushes the water.' },
1915
+ damping: { type: 'range', label: 'Calm', min: 0.95, max: 0.998, step: 0.001, default: 0.985, doc: 'How long ripples last (higher = longer).' },
1916
+ glass: { type: 'range', label: 'Card glass', min: 0.6, max: 1, step: 0.02, default: 0.86, doc: 'Card opacity; lower shows more water.' },
1917
+ mouse: { type: 'boolean', label: 'Mouse affects style', default: true, doc: 'Moving the mouse makes wakes, not just dragging cards.' },
1918
+ },
1919
+ vars: (s) => ({
1920
+ '--bg': s.deep, '--fg': '#f1f8fb', '--muted': '#c3dbe5', '--line': 'rgba(255,255,255,.22)', '--surface': 'transparent', '--control': 'rgba(4,28,42,.55)',
1921
+ '--card': `rgba(248,252,254,${s.glass})`, '--card-fg': '#0b2533', '--card-muted': '#36505d', '--card-border': 'rgba(255,255,255,.6)',
1922
+ '--card-shadow': '0 6px 18px rgba(0,20,35,.25)', '--card-shadow-hover': '0 10px 26px rgba(0,20,35,.35)', '--card-blur': 'blur(8px)',
1923
+ '--header-bg': 'rgba(3,22,34,.45)', '--header-blur': 'blur(10px)', '--panel': '#f6fbfd', '--panel-fg': '#0b2533', '--panel-muted': '#3e5a68',
1924
+ '--panel-control': '#ffffff', '--panel-line': 'rgba(11,37,51,.18)',
1925
+ '--source-bg': 'rgba(3,22,34,.72)', '--placeholder': 'rgba(255,255,255,.12)', '--col-head-fg': '#ffffff', '--col-head-shadow': '0 1px 3px rgba(0,0,0,.5)',
1926
+ '--accent': '#7fe3ff', '--accent-fg': '#04202e', '--radius': '10px',
1927
+ '--pad': '12px', '--gap': '10px', '--col-pad': '10px', '--card-title-size': '14px',
1928
+ '--tag-l': '0.9', '--tag-c': '0.06', '--tag-fg': '#0b2533',
1929
+ }),
1930
+ swatch: (s) => [s.deep, s.shallow, '#f8fcfe'],
1931
+ },
1932
+ {
1933
+ id: 'ballpit', name: 'Ball pit', blurb: 'WebGL balls that bounce off cards.', effect: 'ballpit',
1934
+ settings: {
1935
+ background: { type: 'color', label: 'Ground', default: '#f4f1ec', doc: 'Colour behind the balls.' },
1936
+ count: { type: 'range', label: 'Balls', min: 20, max: 400, step: 10, default: 160, doc: 'Number of balls (respawns them).' },
1937
+ size: { type: 'range', label: 'Ball size', min: 6, max: 30, step: 1, unit: 'px', default: 13, doc: 'Average radius (respawns them).' },
1938
+ gravity: { type: 'range', label: 'Gravity', min: 0, max: 2000, step: 50, default: 900, doc: 'Downward pull in px/s².' },
1939
+ bounce: { type: 'range', label: 'Bounciness', min: 0, max: 0.95, step: 0.05, default: 0.6, doc: 'Energy kept per bounce.' },
1940
+ palette: { type: 'select', label: 'Palette', options: Object.keys(BALL_PALETTES), default: 'candy', doc: 'Ball colours (respawns them).' },
1941
+ mouse: { type: 'boolean', label: 'Mouse affects style', default: true, doc: 'Moving the mouse pushes balls, not just dragging cards.' },
1942
+ },
1943
+ vars: (s) => ({
1944
+ '--bg': s.background, '--fg': '#1d1b18', '--muted': '#5c574f', '--line': 'rgba(0,0,0,.12)', '--surface': 'transparent', '--control': 'rgba(255,255,255,.85)',
1945
+ '--card': '#ffffff', '--card-fg': '#1d1b18', '--card-muted': '#5c574f', '--card-border': 'rgba(0,0,0,.06)',
1946
+ '--card-shadow': '0 2px 6px rgba(0,0,0,.08)', '--card-shadow-hover': '0 6px 16px rgba(0,0,0,.12)',
1947
+ '--header-bg': 'rgba(255,255,255,.7)', '--header-blur': 'blur(8px)', '--panel': '#ffffff', '--panel-fg': '#1d1b18', '--panel-muted': '#5c574f',
1948
+ '--source-bg': 'rgba(255,255,255,.9)', '--placeholder': 'rgba(0,0,0,.03)', '--col-head-fg': '#1d1b18',
1949
+ '--accent': '#5b4cf0', '--accent-fg': '#ffffff', '--radius': '14px',
1950
+ '--pad': '12px 14px', '--gap': '10px', '--col-pad': '8px', '--card-title-size': '14px',
1951
+ '--tag-l': '0.92', '--tag-c': '0.07', '--tag-fg': '#1d1b18',
1952
+ }),
1953
+ swatch: (s) => [s.background, ...BALL_PALETTES[s.palette].slice(0, 2)],
1954
+ },
1955
+ ledgerTheme({
1956
+ id: 'graph', name: 'Graph paper', blurb: 'Ruled grid, crisp ink.', dark: false, grid: true, radius: '6px', display: BRICOLAGE,
1957
+ c: { bg: '#f2f4f3', surface: '#ffffff', surface2: '#f7f8f7', mutedBg: '#ecefed', grid: '#dfe3e1', border: '#d9dddb', controlBorder: '#c5cbc8', borderStrong: '#8a9197', ink: '#15181c', muted: '#4d555c', mark: '#e0662b', highlight: '#f1f5fe', badBg: '#f8e1e3', badFg: '#7e1f2f' },
1958
+ }),
1959
+ ledgerTheme({
1960
+ id: 'night', name: 'Night shift', blurb: 'Graph paper after dark.', dark: true, grid: false, radius: '6px', display: BRICOLAGE,
1961
+ c: { bg: '#111316', surface: '#1a1d21', surface2: '#20242a', mutedBg: '#23272d', grid: '#2c3137', border: '#2e333a', controlBorder: '#444b53', borderStrong: '#6b737b', ink: '#ecefed', muted: '#a9b0b6', mark: '#ff8a4c', highlight: '#1e2635', badBg: '#3a1d22', badFg: '#ffc2ca' },
1962
+ }),
1963
+ ledgerTheme({
1964
+ id: 'blueprint', name: 'Blueprint', blurb: 'White lines on drafting blue.', dark: true, grid: true, radius: '2px', display: PLEX_MONO,
1965
+ c: { bg: '#0f2747', surface: '#133059', surface2: '#17386a', mutedBg: '#0c2240', grid: '#1d4072', border: '#2a4f84', controlBorder: '#4a74b0', borderStrong: '#7fa3d6', ink: '#f1f6ff', muted: '#b4c8e8', mark: '#ffb347', highlight: '#1c4479', badBg: '#4a1f33', badFg: '#ffd0d6' },
1966
+ }),
1967
+ ledgerTheme({
1968
+ id: 'ledger', name: 'Warm ledger', blurb: 'Cream stock, rust ink, serif heads.', dark: false, grid: false, radius: '4px', display: "'Fraunces', Georgia, 'Times New Roman', serif",
1969
+ c: { bg: '#f5f0e6', surface: '#fffdf8', surface2: '#f9f4ea', mutedBg: '#ede5d6', grid: '#e2d8c5', border: '#ddd2be', controlBorder: '#c9bba3', borderStrong: '#8f806a', ink: '#231c14', muted: '#5c5044', mark: '#c8642b', highlight: '#f7ebdd', badBg: '#f3dcd6', badFg: '#7a1f1f' },
1970
+ }),
1971
+ ];
1972
+
1973
+ function themeById(id) {
1974
+ const t = THEMES.find((x) => x.id === id);
1975
+ return t === undefined ? fail(`Unknown theme "${id}"`) : t;
1976
+ }
1977
+ function defaultSettings(theme) {
1978
+ return Object.fromEntries(Object.entries(theme.settings).map(([k, def]) => [k, def.default]));
1979
+ }
1980
+ function coerceSetting(def, raw) {
1981
+ switch (def.type) {
1982
+ case 'color': return /^#[0-9a-f]{6}$/i.test(raw) ? raw : fail(`"${raw}" is not a colour`);
1983
+ case 'range': { const n = Number(raw); return Number.isFinite(n) && n >= def.min && n <= def.max ? n : fail(`${def.label} must be between ${def.min} and ${def.max}`); }
1984
+ case 'select': return def.options.includes(raw) ? raw : fail(`${def.label} must be one of ${def.options.join(', ')}`);
1985
+ case 'boolean': return typeof raw === 'boolean' ? raw : fail(`${def.label} must be on or off`);
1986
+ default: return bug(`setting type "${def.type}"`);
1987
+ }
1988
+ }
1989
+ const toStyle = (vars) => Object.entries(vars).map(([k, v]) => `${k}: ${v}`).join('; ');
1990
+
1991
+ /* ---------- (5) WebGL effects. Each factory returns a fully initialised effect. ---------- */
1992
+
1993
+ function mulberry32(seed) {
1994
+ let a = seed >>> 0;
1995
+ return () => {
1996
+ a = (a + 0x6d2b79f5) >>> 0;
1997
+ let t = a;
1998
+ t = Math.imul(t ^ (t >>> 15), t | 1);
1999
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
2000
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
2001
+ };
2002
+ }
2003
+
2004
+ function compileProgram(gl, vsSrc, fsSrc) {
2005
+ const make = (type, src) => {
2006
+ const sh = gl.createShader(type);
2007
+ gl.shaderSource(sh, src);
2008
+ gl.compileShader(sh);
2009
+ if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) { const log = gl.getShaderInfoLog(sh); gl.deleteShader(sh); fail(`Shader failed to compile: ${log}`); }
2010
+ return sh;
2011
+ };
2012
+ const vs = make(gl.VERTEX_SHADER, vsSrc);
2013
+ const fs = make(gl.FRAGMENT_SHADER, fsSrc);
2014
+ const prog = gl.createProgram();
2015
+ gl.attachShader(prog, vs);
2016
+ gl.attachShader(prog, fs);
2017
+ gl.linkProgram(prog);
2018
+ gl.deleteShader(vs);
2019
+ gl.deleteShader(fs);
2020
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) fail(`Shader program failed to link: ${gl.getProgramInfoLog(prog)}`);
2021
+ return prog;
2022
+ }
2023
+ const rgb01 = (hex) => hexToRgb(hex).map((c) => c / 255);
2024
+ const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
2025
+
2026
+ const OCEAN_VS = `#version 300 es
2027
+ in vec2 aPos;
2028
+ out vec2 vUv;
2029
+ void main() {
2030
+ vUv = vec2(aPos.x * 0.5 + 0.5, 0.5 - aPos.y * 0.5);
2031
+ gl_Position = vec4(aPos, 0.0, 1.0);
2032
+ }`;
2033
+
2034
+ const OCEAN_FS = `#version 300 es
2035
+ precision highp float;
2036
+ uniform sampler2D uH;
2037
+ uniform vec2 uRes;
2038
+ uniform vec2 uTexel;
2039
+ uniform float uTime;
2040
+ uniform float uSwell;
2041
+ uniform vec3 uDeep;
2042
+ uniform vec3 uShallow;
2043
+ in vec2 vUv;
2044
+ out vec4 outColor;
2045
+
2046
+ float swell(vec2 p) {
2047
+ float t = uTime;
2048
+ return sin(p.x * 0.011 + t * 0.8) * 0.5
2049
+ + sin(p.y * 0.016 - t * 0.65 + p.x * 0.004) * 0.35
2050
+ + sin((p.x + p.y) * 0.023 + t * 1.25) * 0.15
2051
+ + sin((p.x * 0.7 - p.y) * 0.041 - t * 1.9) * 0.06;
2052
+ }
2053
+
2054
+ void main() {
2055
+ vec2 p = vUv * uRes;
2056
+ float hL = texture(uH, vUv - vec2(uTexel.x, 0.0)).r;
2057
+ float hR = texture(uH, vUv + vec2(uTexel.x, 0.0)).r;
2058
+ float hU = texture(uH, vUv - vec2(0.0, uTexel.y)).r;
2059
+ float hD = texture(uH, vUv + vec2(0.0, uTexel.y)).r;
2060
+ float hC = texture(uH, vUv).r;
2061
+ float e = 3.0;
2062
+ float sx = (swell(p + vec2(e, 0.0)) - swell(p - vec2(e, 0.0))) / (2.0 * e);
2063
+ float sy = (swell(p + vec2(0.0, e)) - swell(p - vec2(0.0, e))) / (2.0 * e);
2064
+ vec2 grad = vec2(hR - hL, hD - hU) * 2.2 + vec2(sx, sy) * uSwell * 28.0;
2065
+ vec3 n = normalize(vec3(-grad.x, grad.y, 1.0));
2066
+ vec3 L = normalize(vec3(-0.35, 0.55, 0.75));
2067
+ float diff = clamp(dot(n, L), 0.0, 1.0);
2068
+ vec3 H = normalize(L + vec3(0.0, 0.0, 1.0));
2069
+ float spec = pow(max(dot(n, H), 0.0), 90.0);
2070
+ float height = hC * 0.5 + swell(p) * uSwell * 0.35;
2071
+ float mixAmt = clamp(0.35 + height * 0.5 + (diff - 0.7) * 0.9, 0.0, 1.0);
2072
+ vec3 col = mix(uDeep, uShallow, mixAmt);
2073
+ float foam = smoothstep(0.18, 0.55, length(vec2(hR - hL, hD - hU)));
2074
+ col += vec3(spec * 0.55) + vec3(foam * 0.35);
2075
+ float vignette = smoothstep(1.25, 0.35, length(vUv - 0.5));
2076
+ col *= mix(0.78, 1.0, vignette);
2077
+ outColor = vec4(col, 1.0);
2078
+ }`;
2079
+
2080
+ /** Ocean: CPU ripple simulation on a coarse grid + shader lighting. Static cards act as walls; dragged cards push the water. */
2081
+ function createOceanEffect(gl) {
2082
+ const prog = compileProgram(gl, OCEAN_VS, OCEAN_FS);
2083
+ const vao = gl.createVertexArray();
2084
+ const buf = gl.createBuffer();
2085
+ gl.bindVertexArray(vao);
2086
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
2087
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
2088
+ const aPos = gl.getAttribLocation(prog, 'aPos');
2089
+ gl.enableVertexAttribArray(aPos);
2090
+ gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);
2091
+ gl.bindVertexArray(null);
2092
+ const tex = gl.createTexture();
2093
+ const U = Object.fromEntries(['uH', 'uRes', 'uTexel', 'uTime', 'uSwell', 'uDeep', 'uShallow'].map((n) => [n, gl.getUniformLocation(prog, n)]));
2094
+ const GW = 160;
2095
+ let grid = null;
2096
+ let time = 0;
2097
+ let acc = 0;
2098
+ let lastDragged = new Map();
2099
+
2100
+ const ensureGrid = (w, h) => {
2101
+ const gh = clamp(Math.round((GW * h) / Math.max(w, 1)), 24, 260);
2102
+ if (grid !== null && grid.gh === gh) return;
2103
+ const size = GW * gh;
2104
+ grid = { gw: GW, gh, cur: new Float32Array(size), prev: new Float32Array(size), next: new Float32Array(size), mask: new Uint8Array(size) };
2105
+ gl.bindTexture(gl.TEXTURE_2D, tex);
2106
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
2107
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.R16F, GW, gh, 0, gl.RED, gl.FLOAT, grid.cur);
2108
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
2109
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
2110
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
2111
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
2112
+ };
2113
+ const cellsOf = (r, w, h, inset) => {
2114
+ const { gw, gh } = grid;
2115
+ return {
2116
+ x0: clamp(Math.ceil((r.x / w) * gw) + inset, 1, gw - 2), x1: clamp(Math.floor(((r.x + r.w) / w) * gw) - inset, 1, gw - 2),
2117
+ y0: clamp(Math.ceil((r.y / h) * gh) + inset, 1, gh - 2), y1: clamp(Math.floor(((r.y + r.h) / h) * gh) - inset, 1, gh - 2),
2118
+ };
2119
+ };
2120
+ const addTo = (r, amount, w, h) => {
2121
+ const c = cellsOf(r, w, h, 0);
2122
+ for (let y = c.y0; y <= c.y1; y++) for (let x = c.x0; x <= c.x1; x++) grid.cur[y * grid.gw + x] += amount;
2123
+ };
2124
+ const simulate = (damping) => {
2125
+ const { gw, gh, cur, prev, next, mask } = grid;
2126
+ for (let y = 1; y < gh - 1; y++) {
2127
+ for (let x = 1; x < gw - 1; x++) {
2128
+ const i = y * gw + x;
2129
+ next[i] = mask[i] === 1 ? 0 : ((cur[i - 1] + cur[i + 1] + cur[i - gw] + cur[i + gw]) * 0.5 - prev[i]) * damping;
2130
+ }
2131
+ }
2132
+ grid.prev = cur; grid.cur = next; grid.next = prev;
2133
+ };
2134
+
2135
+ return {
2136
+ kind: 'ocean',
2137
+ step(dt, frame, s) {
2138
+ const { width: w, height: h } = frame;
2139
+ time += dt;
2140
+ ensureGrid(w, h);
2141
+ grid.mask.fill(0);
2142
+ const dragged = new Map();
2143
+ for (const o of frame.obstacles) {
2144
+ if (o.dragging) { dragged.set(o.id, o); continue; }
2145
+ const c = cellsOf(o, w, h, 1);
2146
+ for (let y = c.y0; y <= c.y1; y++) for (let x = c.x0; x <= c.x1; x++) grid.mask[y * grid.gw + x] = 1;
2147
+ }
2148
+ for (const o of dragged.values()) {
2149
+ const speed = Math.hypot(o.vx, o.vy);
2150
+ if (speed > 15) addTo(o, -s.wake * Math.min(speed / 1400, 1.2) * 0.45, w, h);
2151
+ }
2152
+ for (const [id, o] of lastDragged) {
2153
+ if (!dragged.has(id)) addTo({ x: o.x - 16, y: o.y - 16, w: o.w + 32, h: o.h + 32 }, s.wake * 1.4, w, h);
2154
+ }
2155
+ lastDragged = dragged;
2156
+ acc = Math.min(acc + dt, 4 / 60);
2157
+ while (acc >= 1 / 60) { simulate(s.damping); acc -= 1 / 60; }
2158
+
2159
+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
2160
+ gl.disable(gl.BLEND);
2161
+ gl.useProgram(prog);
2162
+ gl.activeTexture(gl.TEXTURE0);
2163
+ gl.bindTexture(gl.TEXTURE_2D, tex);
2164
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, grid.gw, grid.gh, gl.RED, gl.FLOAT, grid.cur);
2165
+ gl.uniform1i(U.uH, 0);
2166
+ gl.uniform2f(U.uRes, w, h);
2167
+ gl.uniform2f(U.uTexel, 1 / grid.gw, 1 / grid.gh);
2168
+ gl.uniform1f(U.uTime, time);
2169
+ gl.uniform1f(U.uSwell, s.swell);
2170
+ gl.uniform3fv(U.uDeep, rgb01(s.deep));
2171
+ gl.uniform3fv(U.uShallow, rgb01(s.shallow));
2172
+ gl.bindVertexArray(vao);
2173
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
2174
+ gl.bindVertexArray(null);
2175
+ },
2176
+ dispose() { gl.deleteProgram(prog); gl.deleteBuffer(buf); gl.deleteVertexArray(vao); gl.deleteTexture(tex); },
2177
+ };
2178
+ }
2179
+
2180
+ const BALL_VS = `#version 300 es
2181
+ in vec2 aPos;
2182
+ in float aR;
2183
+ in vec3 aCol;
2184
+ uniform vec2 uRes;
2185
+ uniform float uDpr;
2186
+ out vec3 vCol;
2187
+ out float vSize;
2188
+ void main() {
2189
+ vec2 clip = (aPos / uRes) * 2.0 - 1.0;
2190
+ gl_Position = vec4(clip.x, -clip.y, 0.0, 1.0);
2191
+ vSize = aR * 2.0 * uDpr + 2.0;
2192
+ gl_PointSize = vSize;
2193
+ vCol = aCol;
2194
+ }`;
2195
+
2196
+ const BALL_FS = `#version 300 es
2197
+ precision highp float;
2198
+ in vec3 vCol;
2199
+ in float vSize;
2200
+ out vec4 outColor;
2201
+ void main() {
2202
+ vec2 c = gl_PointCoord * 2.0 - 1.0;
2203
+ float d = length(c);
2204
+ float aa = 3.0 / vSize;
2205
+ float a = 1.0 - smoothstep(1.0 - aa, 1.0, d);
2206
+ if (a <= 0.0) discard;
2207
+ vec3 n = vec3(c.x, -c.y, sqrt(max(0.0, 1.0 - d * d)));
2208
+ vec3 L = normalize(vec3(-0.45, 0.6, 0.75));
2209
+ float diff = max(dot(n, L), 0.0);
2210
+ float spec = pow(max(dot(reflect(-L, n), vec3(0.0, 0.0, 1.0)), 0.0), 28.0);
2211
+ vec3 col = vCol * (0.42 + 0.68 * diff) + vec3(spec * 0.5);
2212
+ outColor = vec4(col * a, a);
2213
+ }`;
2214
+
2215
+ /** Ball pit: deterministic spawn from `seed`; circles collide with each other, the walls and every card rect (moving rects transfer their velocity). */
2216
+ function createBallPitEffect(gl, seed) {
2217
+ const prog = compileProgram(gl, BALL_VS, BALL_FS);
2218
+ const vao = gl.createVertexArray();
2219
+ const buf = gl.createBuffer();
2220
+ gl.bindVertexArray(vao);
2221
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
2222
+ const STRIDE = 6 * 4;
2223
+ const attr = (name, size, offset) => { const loc = gl.getAttribLocation(prog, name); gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, size, gl.FLOAT, false, STRIDE, offset); };
2224
+ attr('aPos', 2, 0); attr('aR', 1, 8); attr('aCol', 3, 12);
2225
+ gl.bindVertexArray(null);
2226
+ const uRes = gl.getUniformLocation(prog, 'uRes');
2227
+ const uDpr = gl.getUniformLocation(prog, 'uDpr');
2228
+ let balls = null;
2229
+ let spawnKey = '';
2230
+ let gpu = new Float32Array(0);
2231
+ const MAX_SPEED = 3200;
2232
+
2233
+ const spawn = (s, w, h) => {
2234
+ const rng = mulberry32(seed);
2235
+ const palette = BALL_PALETTES[s.palette] ?? bug(`palette "${s.palette}"`);
2236
+ const n = s.count;
2237
+ balls = { n, x: new Float32Array(n), y: new Float32Array(n), vx: new Float32Array(n), vy: new Float32Array(n), r: new Float32Array(n), col: new Float32Array(n * 3) };
2238
+ for (let i = 0; i < n; i++) {
2239
+ const r = s.size * (0.75 + rng() * 0.5);
2240
+ balls.r[i] = r;
2241
+ balls.x[i] = r + rng() * Math.max(w - 2 * r, 1);
2242
+ balls.y[i] = r + rng() * Math.max(h * 0.5, 1);
2243
+ balls.vx[i] = (rng() - 0.5) * 240;
2244
+ balls.vy[i] = (rng() - 0.5) * 120;
2245
+ const c = rgb01(palette[Math.floor(rng() * palette.length)]);
2246
+ balls.col.set(c, i * 3);
2247
+ }
2248
+ gpu = new Float32Array(n * 6);
2249
+ };
2250
+
2251
+ const physics = (h, s, W, H, rects) => {
2252
+ const { n, x, y, vx, vy, r } = balls;
2253
+ const e = s.bounce;
2254
+ for (let i = 0; i < n; i++) {
2255
+ vy[i] += s.gravity * h;
2256
+ vx[i] *= 0.9995; vy[i] *= 0.9995;
2257
+ x[i] += vx[i] * h; y[i] += vy[i] * h;
2258
+ const ri = r[i];
2259
+ if (x[i] < ri) { x[i] = ri; if (vx[i] < 0) vx[i] = -vx[i] * e; }
2260
+ if (x[i] > W - ri) { x[i] = W - ri; if (vx[i] > 0) vx[i] = -vx[i] * e; }
2261
+ if (y[i] < ri) { y[i] = ri; if (vy[i] < 0) vy[i] = -vy[i] * e; }
2262
+ if (y[i] > H - ri) { y[i] = H - ri; if (vy[i] > 0) { vy[i] = -vy[i] * e; vx[i] *= 0.985; } }
2263
+ for (const o of rects) {
2264
+ const cx = clamp(x[i], o.x, o.x + o.w);
2265
+ const cy = clamp(y[i], o.y, o.y + o.h);
2266
+ let dx = x[i] - cx; let dy = y[i] - cy;
2267
+ const d2 = dx * dx + dy * dy;
2268
+ if (d2 >= ri * ri) continue;
2269
+ let nx; let ny; let pen;
2270
+ if (d2 > 1e-6) {
2271
+ const d = Math.sqrt(d2); nx = dx / d; ny = dy / d; pen = ri - d;
2272
+ } else {
2273
+ const l = x[i] - o.x; const rr = o.x + o.w - x[i]; const t = y[i] - o.y; const b = o.y + o.h - y[i];
2274
+ const m = Math.min(l, rr, t, b);
2275
+ if (m === l) { nx = -1; ny = 0; pen = l + ri; } else if (m === rr) { nx = 1; ny = 0; pen = rr + ri; } else if (m === t) { nx = 0; ny = -1; pen = t + ri; } else { nx = 0; ny = 1; pen = b + ri; }
2276
+ }
2277
+ x[i] += nx * pen; y[i] += ny * pen;
2278
+ const rvx = vx[i] - o.vx; const rvy = vy[i] - o.vy;
2279
+ const vn = rvx * nx + rvy * ny;
2280
+ if (vn < 0) {
2281
+ const k = (1 + (o.dragging ? Math.max(e, 0.8) : e)) * vn;
2282
+ vx[i] = rvx - k * nx + o.vx; vy[i] = rvy - k * ny + o.vy;
2283
+ }
2284
+ }
2285
+ }
2286
+ for (let i = 0; i < n; i++) {
2287
+ for (let j = i + 1; j < n; j++) {
2288
+ const dx = x[j] - x[i];
2289
+ const rs = r[i] + r[j];
2290
+ if (dx > rs || dx < -rs) continue;
2291
+ const dy = y[j] - y[i];
2292
+ const d2 = dx * dx + dy * dy;
2293
+ if (d2 >= rs * rs || d2 < 1e-6) continue;
2294
+ const d = Math.sqrt(d2); const nx = dx / d; const ny = dy / d;
2295
+ const mi = r[i] * r[i]; const mj = r[j] * r[j]; const mt = mi + mj;
2296
+ const overlap = rs - d;
2297
+ x[i] -= nx * overlap * (mj / mt); y[i] -= ny * overlap * (mj / mt);
2298
+ x[j] += nx * overlap * (mi / mt); y[j] += ny * overlap * (mi / mt);
2299
+ const rv = (vx[j] - vx[i]) * nx + (vy[j] - vy[i]) * ny;
2300
+ if (rv < 0) {
2301
+ const jimp = (-(1 + e) * rv) / (1 / mi + 1 / mj);
2302
+ vx[i] -= (jimp * nx) / mi; vy[i] -= (jimp * ny) / mi;
2303
+ vx[j] += (jimp * nx) / mj; vy[j] += (jimp * ny) / mj;
2304
+ }
2305
+ }
2306
+ }
2307
+ for (let i = 0; i < n; i++) {
2308
+ const sp = Math.hypot(vx[i], vy[i]);
2309
+ if (sp > MAX_SPEED) { vx[i] *= MAX_SPEED / sp; vy[i] *= MAX_SPEED / sp; }
2310
+ }
2311
+ };
2312
+
2313
+ return {
2314
+ kind: 'ballpit',
2315
+ step(dt, frame, s) {
2316
+ const { width: W, height: H, dpr } = frame;
2317
+ const key = `${s.count}|${s.size}|${s.palette}`;
2318
+ if (balls === null || key !== spawnKey) { spawn(s, W, H); spawnKey = key; }
2319
+ const SUB = 4;
2320
+ const h = Math.min(dt, 1 / 30) / SUB;
2321
+ for (let k = 0; k < SUB; k++) physics(h, s, W, H, frame.obstacles);
2322
+ const { n, x, y, r, col } = balls;
2323
+ for (let i = 0; i < n; i++) {
2324
+ const o = i * 6;
2325
+ gpu[o] = x[i]; gpu[o + 1] = y[i]; gpu[o + 2] = r[i];
2326
+ gpu[o + 3] = col[i * 3]; gpu[o + 4] = col[i * 3 + 1]; gpu[o + 5] = col[i * 3 + 2];
2327
+ }
2328
+ gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
2329
+ gl.clearColor(0, 0, 0, 0);
2330
+ gl.clear(gl.COLOR_BUFFER_BIT);
2331
+ gl.enable(gl.BLEND);
2332
+ gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
2333
+ gl.useProgram(prog);
2334
+ gl.uniform2f(uRes, W, H);
2335
+ gl.uniform1f(uDpr, dpr);
2336
+ gl.bindVertexArray(vao);
2337
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
2338
+ gl.bufferData(gl.ARRAY_BUFFER, gpu, gl.DYNAMIC_DRAW);
2339
+ gl.drawArrays(gl.POINTS, 0, n);
2340
+ gl.bindVertexArray(null);
2341
+ },
2342
+ dispose() { gl.deleteProgram(prog); gl.deleteBuffer(buf); gl.deleteVertexArray(vao); },
2343
+ };
2344
+ }
2345
+
2346
+ const EFFECT_FACTORIES = {
2347
+ ocean: (gl) => createOceanEffect(gl),
2348
+ ballpit: (gl, seed) => createBallPitEffect(gl, seed),
2349
+ };
2350
+
2351
+ /* ---------- (5b) Event effects: 2D particle bursts on an overlay canvas ----------
2352
+ * Each burst factory takes (rect, env, rng) and returns a fully initialised { step(dt) -> alive, draw(ctx) }.
2353
+ * rect is in board-local px; env holds theme colours read at the edge; rng is seeded at the edge.
2354
+ */
2355
+
2356
+ const FX_COLORS = ['#ff5d73', '#ffd93d', '#4cc9f0', '#45d483', '#7b6cf6', '#ff9f45'];
2357
+ const pick = (rng, list) => list[Math.floor(rng() * list.length)];
2358
+ const TAU = Math.PI * 2;
2359
+
2360
+ /** Event -> effect choices. 'random' picks one of `options` each time; 'none' plays nothing. */
2361
+ const EVENT_EFFECTS = {
2362
+ create: { label: 'New task', options: ['pop', 'supernova'], default: 'pop', doc: 'Plays on the new card when a task is added from a column.' },
2363
+ delete: { label: 'Delete', options: ['explode', 'burn'], default: 'explode', doc: 'Plays where the card was when a task is deleted.' },
2364
+ complete: { label: 'Complete', options: ['confetti', 'fireworks', 'bubbles', 'balloons'], default: 'confetti', doc: 'Plays where the card was when "Mark complete" sends a task to the archive.' },
2365
+ };
2366
+ const EFFECT_LABELS = {
2367
+ pop: 'Pop in', supernova: 'Supernova', explode: 'Explode', burn: 'Burn up',
2368
+ confetti: 'Confetti', fireworks: 'Fireworks', bubbles: 'Bubbles', balloons: 'Balloons', random: 'Random', none: 'None',
2369
+ };
2370
+ const ENTRY_CLASS = { pop: 'kb-anim-pop', supernova: 'kb-anim-nova' };
2371
+ const effectChoices = (event) => [...(EVENT_EFFECTS[event] ?? bug(`unknown effect event "${event}"`)).options, 'random', 'none'];
2372
+ function resolveEffect(event, choice, rng) {
2373
+ const spec = EVENT_EFFECTS[event] ?? bug(`unknown effect event "${event}"`);
2374
+ if (choice === 'none') return null;
2375
+ if (choice === 'random') return pick(rng, spec.options);
2376
+ if (!spec.options.includes(choice)) bug(`effect "${choice}" is not valid for ${event}`);
2377
+ return choice;
2378
+ }
2379
+
2380
+ function burstExplode(r, env, rng) {
2381
+ const cols = clamp(Math.round(r.w / 34), 4, 10);
2382
+ const rows = clamp(Math.round(r.h / 22), 2, 8);
2383
+ const cx = r.x + r.w / 2;
2384
+ const cy = r.y + r.h / 2;
2385
+ const sw = r.w / cols;
2386
+ const sh = r.h / rows;
2387
+ const shards = [];
2388
+ for (let j = 0; j < rows; j++) {
2389
+ for (let i = 0; i < cols; i++) {
2390
+ const x = r.x + sw * (i + 0.5);
2391
+ const y = r.y + sh * (j + 0.5);
2392
+ const d = Math.hypot(x - cx, y - cy) || 1;
2393
+ const sp = 250 + rng() * 650;
2394
+ shards.push({ x, y, vx: ((x - cx) / d) * sp + (rng() - 0.5) * 200, vy: ((y - cy) / d) * sp - 250 - rng() * 250, rot: 0, vr: (rng() - 0.5) * 18, life: 1 + rng() * 0.7, w: sw * (0.7 + rng() * 0.5), h: sh * (0.7 + rng() * 0.5) });
2395
+ }
2396
+ }
2397
+ const sparks = Array.from({ length: 50 }, () => {
2398
+ const a = rng() * TAU;
2399
+ const sp = 300 + rng() * 900;
2400
+ return { x: cx + (rng() - 0.5) * r.w * 0.6, y: cy, vx: Math.cos(a) * sp, vy: Math.sin(a) * sp, life: 0.3 + rng() * 0.5 };
2401
+ });
2402
+ const R = Math.max(r.w, r.h);
2403
+ let t = 0;
2404
+ return {
2405
+ step(dt) {
2406
+ t += dt;
2407
+ for (const s of shards) { s.vy += 1500 * dt; s.vx *= 0.995; s.x += s.vx * dt; s.y += s.vy * dt; s.rot += s.vr * dt; s.life -= dt; }
2408
+ for (const p of sparks) { p.vx *= 0.94; p.vy = p.vy * 0.94 + 600 * dt; p.x += p.vx * dt; p.y += p.vy * dt; p.life -= dt; }
2409
+ return shards.some((s) => s.life > 0) || sparks.some((p) => p.life > 0);
2410
+ },
2411
+ draw(ctx) {
2412
+ if (t < 0.18) {
2413
+ const a = 1 - t / 0.18;
2414
+ const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, R);
2415
+ g.addColorStop(0, `rgba(255,240,200,${0.9 * a})`);
2416
+ g.addColorStop(1, 'rgba(255,200,120,0)');
2417
+ ctx.fillStyle = g;
2418
+ ctx.beginPath(); ctx.arc(cx, cy, R, 0, TAU); ctx.fill();
2419
+ }
2420
+ for (const s of shards) {
2421
+ if (s.life <= 0) continue;
2422
+ ctx.save();
2423
+ ctx.globalAlpha = clamp(s.life / 0.4, 0, 1);
2424
+ ctx.translate(s.x, s.y); ctx.rotate(s.rot);
2425
+ ctx.fillStyle = env.card; ctx.strokeStyle = env.cardBorder; ctx.lineWidth = 1;
2426
+ ctx.fillRect(-s.w / 2, -s.h / 2, s.w, s.h); ctx.strokeRect(-s.w / 2, -s.h / 2, s.w, s.h);
2427
+ ctx.restore();
2428
+ }
2429
+ ctx.globalCompositeOperation = 'lighter';
2430
+ ctx.strokeStyle = '#ffb347'; ctx.lineWidth = 2;
2431
+ for (const p of sparks) {
2432
+ if (p.life <= 0) continue;
2433
+ ctx.globalAlpha = clamp(p.life / 0.3, 0, 1);
2434
+ ctx.beginPath(); ctx.moveTo(p.x, p.y); ctx.lineTo(p.x - p.vx * 0.02, p.y - p.vy * 0.02); ctx.stroke();
2435
+ }
2436
+ },
2437
+ };
2438
+ }
2439
+
2440
+ function burstBurn(r, env, rng) {
2441
+ const DUR = 1.5;
2442
+ const seeds = [rng() * 10, rng() * 10, rng() * 10];
2443
+ let t = 0;
2444
+ let flames = [];
2445
+ let smoke = [];
2446
+ const edgeY = (x, p) => {
2447
+ let n = 0;
2448
+ for (let k = 0; k < 3; k++) n += Math.sin(x * (0.05 + k * 0.04) + seeds[k] + t * (3 + k * 2)) * (5 - k * 1.5);
2449
+ return r.y + r.h * (1 - p) + n * Math.min(1, p * 4);
2450
+ };
2451
+ const edgePoints = (p) => {
2452
+ const pts = [];
2453
+ for (let x = r.x; x < r.x + r.w; x += 6) pts.push([x, Math.max(r.y, edgeY(x, p))]);
2454
+ pts.push([r.x + r.w, Math.max(r.y, edgeY(r.x + r.w, p))]);
2455
+ return pts;
2456
+ };
2457
+ return {
2458
+ step(dt) {
2459
+ t += dt;
2460
+ const p = Math.min(t / DUR, 1);
2461
+ if (p < 1) {
2462
+ const n = Math.ceil((r.w / 6) * dt * 30);
2463
+ for (let i = 0; i < n; i++) {
2464
+ const x = r.x + rng() * r.w;
2465
+ const y = edgeY(x, p);
2466
+ flames.push({ x, y, vx: (rng() - 0.5) * 40, vy: -(80 + rng() * 140), life: 0.35 + rng() * 0.5, max: 0.85, size: 5 + rng() * 9, ember: false });
2467
+ if (rng() < 0.12) smoke.push({ x, y, vx: (rng() - 0.5) * 20, vy: -(30 + rng() * 40), life: 1.2 + rng(), max: 2.2, size: 6 + rng() * 6 });
2468
+ if (rng() < 0.06) flames.push({ x, y, vx: (rng() - 0.5) * 120, vy: -(150 + rng() * 200), life: 1 + rng(), max: 2, size: 1.6, ember: true });
2469
+ }
2470
+ }
2471
+ for (const f of flames) { f.vx += (rng() - 0.5) * 600 * dt; f.x += f.vx * dt; f.y += f.vy * dt; f.life -= dt; }
2472
+ for (const s of smoke) { s.x += s.vx * dt; s.y += s.vy * dt; s.size += 14 * dt; s.life -= dt; }
2473
+ flames = flames.filter((f) => f.life > 0);
2474
+ smoke = smoke.filter((s) => s.life > 0);
2475
+ return p < 1 || flames.length > 0 || smoke.length > 0;
2476
+ },
2477
+ draw(ctx) {
2478
+ const p = Math.min(t / DUR, 1);
2479
+ if (p < 1) {
2480
+ const pts = edgePoints(p);
2481
+ ctx.save();
2482
+ ctx.beginPath(); ctx.moveTo(r.x, r.y); ctx.lineTo(r.x + r.w, r.y);
2483
+ for (let i = pts.length - 1; i >= 0; i--) ctx.lineTo(pts[i][0], pts[i][1]);
2484
+ ctx.closePath();
2485
+ ctx.fillStyle = env.card; ctx.fill(); ctx.clip();
2486
+ const band = r.y + r.h * (1 - p);
2487
+ const g = ctx.createLinearGradient(0, band - 22, 0, band + 6);
2488
+ g.addColorStop(0, 'rgba(60,30,10,0)'); g.addColorStop(1, 'rgba(40,18,6,.85)');
2489
+ ctx.fillStyle = g; ctx.fillRect(r.x, r.y, r.w, r.h);
2490
+ ctx.restore();
2491
+ ctx.save();
2492
+ ctx.globalCompositeOperation = 'lighter';
2493
+ ctx.strokeStyle = 'rgba(255,140,40,.9)'; ctx.lineWidth = 2.5; ctx.shadowColor = '#ff7a1a'; ctx.shadowBlur = 12;
2494
+ ctx.beginPath(); pts.forEach(([x, y], i) => (i === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y))); ctx.stroke();
2495
+ ctx.restore();
2496
+ }
2497
+ for (const s of smoke) {
2498
+ ctx.fillStyle = `rgba(90,90,90,${(0.2 * clamp((s.life / s.max) * 2, 0, 1)).toFixed(3)})`;
2499
+ ctx.beginPath(); ctx.arc(s.x, s.y, s.size, 0, TAU); ctx.fill();
2500
+ }
2501
+ ctx.globalCompositeOperation = 'lighter';
2502
+ for (const f of flames) {
2503
+ const q = f.life / f.max;
2504
+ ctx.globalAlpha = clamp(q * 1.4, 0, 1);
2505
+ ctx.fillStyle = f.ember ? '#ffcf70' : q > 0.6 ? '#fff0a8' : q > 0.3 ? '#ffa53a' : '#e2401c';
2506
+ ctx.beginPath(); ctx.arc(f.x, f.y, f.size * (0.4 + q * 0.6), 0, TAU); ctx.fill();
2507
+ }
2508
+ },
2509
+ };
2510
+ }
2511
+
2512
+ function burstConfetti(r, env, rng) {
2513
+ const cx = r.x + r.w / 2;
2514
+ const cy = r.y + r.h * 0.3;
2515
+ const ps = Array.from({ length: 140 }, () => {
2516
+ const a = -Math.PI / 2 + (rng() - 0.5) * Math.PI * 0.9;
2517
+ const sp = 450 + rng() * 750;
2518
+ return { x: cx + (rng() - 0.5) * r.w * 0.6, y: cy, vx: Math.cos(a) * sp, vy: Math.sin(a) * sp, rot: rng() * TAU, vr: (rng() - 0.5) * 14, ph: rng() * TAU, vph: 6 + rng() * 10, w: 6 + rng() * 6, h: 3 + rng() * 4, color: pick(rng, FX_COLORS), life: 2.2 + rng() * 1.3 };
2519
+ });
2520
+ return {
2521
+ step(dt) {
2522
+ for (const p of ps) {
2523
+ p.vx *= Math.pow(0.35, dt);
2524
+ p.vy = p.vy * Math.pow(0.5, dt) + 1100 * dt;
2525
+ p.ph += p.vph * dt;
2526
+ p.x += p.vx * dt + Math.sin(p.ph) * 30 * dt;
2527
+ p.y += p.vy * dt;
2528
+ p.rot += p.vr * dt;
2529
+ p.life -= dt;
2530
+ }
2531
+ return ps.some((p) => p.life > 0);
2532
+ },
2533
+ draw(ctx) {
2534
+ for (const p of ps) {
2535
+ if (p.life <= 0) continue;
2536
+ ctx.save();
2537
+ ctx.globalAlpha = clamp(p.life / 0.5, 0, 1);
2538
+ ctx.translate(p.x, p.y); ctx.rotate(p.rot); ctx.scale(1, Math.cos(p.ph));
2539
+ ctx.fillStyle = p.color; ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);
2540
+ ctx.restore();
2541
+ }
2542
+ },
2543
+ };
2544
+ }
2545
+
2546
+ const easeOutCubic = (p) => 1 - Math.pow(1 - p, 3);
2547
+ const easeOutQuart = (p) => 1 - Math.pow(1 - p, 4);
2548
+
2549
+ /** Rockets fly a curved (quadratic) path that eases out to a near-stop at the apex, then burst. */
2550
+ function burstFireworks(r, env, rng) {
2551
+ const cx = r.x + r.w / 2;
2552
+ const rockets = Array.from({ length: 4 }, (_, i) => {
2553
+ const x0 = cx + (rng() - 0.5) * Math.max(120, r.w * 0.8);
2554
+ const y0 = r.y;
2555
+ const rise = 220 + rng() * 160;
2556
+ const drift = (rng() < 0.5 ? -1 : 1) * (50 + rng() * 120);
2557
+ const y1 = Math.max(40, y0 - rise);
2558
+ return {
2559
+ delay: i * 0.22, t: 0, dur: 0.85 + rng() * 0.35,
2560
+ p0: [x0, y0],
2561
+ c: [x0 - drift * 0.35, y0 - (y0 - y1) * 0.85], // pulls the path one way first, so it bows into an arc
2562
+ p1: [x0 + drift, y1],
2563
+ x: x0, y: y0, color: pick(rng, FX_COLORS), exploded: false, trail: [],
2564
+ };
2565
+ });
2566
+ const along = (k, e) => {
2567
+ const u = 1 - e;
2568
+ return [u * u * k.p0[0] + 2 * u * e * k.c[0] + e * e * k.p1[0], u * u * k.p0[1] + 2 * u * e * k.c[1] + e * e * k.p1[1]];
2569
+ };
2570
+ let sparks = [];
2571
+ return {
2572
+ step(dt) {
2573
+ for (const k of rockets) {
2574
+ if (k.delay > 0) { k.delay -= dt; continue; }
2575
+ if (k.exploded) continue;
2576
+ k.t = Math.min(k.t + dt, k.dur);
2577
+ [k.x, k.y] = along(k, easeOutCubic(k.t / k.dur));
2578
+ k.trail.push([k.x, k.y]);
2579
+ if (k.trail.length > 12) k.trail.shift();
2580
+ if (k.t >= k.dur) {
2581
+ k.exploded = true;
2582
+ const n = 70;
2583
+ for (let j = 0; j < n; j++) {
2584
+ const a = (j / n) * TAU + rng() * 0.1;
2585
+ const sp = 120 + rng() * 240;
2586
+ sparks.push({ x: k.x, y: k.y, px: k.x, py: k.y, vx: Math.cos(a) * sp, vy: Math.sin(a) * sp, life: 0.9 + rng() * 0.6, max: 1.5, color: rng() < 0.15 ? '#ffffff' : k.color });
2587
+ }
2588
+ }
2589
+ }
2590
+ for (const s of sparks) {
2591
+ s.px = s.x; s.py = s.y;
2592
+ s.vx *= Math.pow(0.3, dt); s.vy = s.vy * Math.pow(0.3, dt) + 180 * dt;
2593
+ s.x += s.vx * dt; s.y += s.vy * dt; s.life -= dt;
2594
+ }
2595
+ sparks = sparks.filter((s) => s.life > 0);
2596
+ return rockets.some((k) => !k.exploded) || sparks.length > 0;
2597
+ },
2598
+ draw(ctx) {
2599
+ ctx.globalCompositeOperation = 'lighter';
2600
+ ctx.lineCap = 'round';
2601
+ ctx.lineJoin = 'round';
2602
+ for (const k of rockets) {
2603
+ if (k.delay > 0 || k.exploded || k.trail.length < 2) continue;
2604
+ // The trail tapers: older points are fainter, so the curve reads clearly.
2605
+ for (let j = 1; j < k.trail.length; j++) {
2606
+ ctx.globalAlpha = (j / k.trail.length) * 0.8;
2607
+ ctx.strokeStyle = k.color; ctx.lineWidth = 1 + (j / k.trail.length) * 1.5;
2608
+ ctx.beginPath(); ctx.moveTo(k.trail[j - 1][0], k.trail[j - 1][1]); ctx.lineTo(k.trail[j][0], k.trail[j][1]); ctx.stroke();
2609
+ }
2610
+ ctx.fillStyle = '#ffffff'; ctx.globalAlpha = 1;
2611
+ ctx.beginPath(); ctx.arc(k.x, k.y, 2.5, 0, TAU); ctx.fill();
2612
+ }
2613
+ for (const s of sparks) {
2614
+ const q = s.life / s.max;
2615
+ ctx.globalAlpha = clamp(q * 1.3, 0, 1) * (0.7 + 0.3 * Math.sin(s.life * 40));
2616
+ ctx.strokeStyle = s.color; ctx.lineWidth = 2;
2617
+ ctx.beginPath(); ctx.moveTo(s.px - s.vx * 0.03, s.py - s.vy * 0.03); ctx.lineTo(s.x, s.y); ctx.stroke();
2618
+ }
2619
+ },
2620
+ };
2621
+ }
2622
+
2623
+ function burstBubbles(r, env, rng) {
2624
+ const bs = Array.from({ length: 28 }, () => ({
2625
+ x0: r.x + rng() * r.w, y: r.y + r.h * (0.3 + rng() * 0.7), rad: 5 + rng() * 14, vy: -(50 + rng() * 110),
2626
+ amp: 6 + rng() * 14, f: 1.5 + rng() * 2.5, ph: rng() * TAU, life: 1.2 + rng() * 2.2, t: 0, popped: false, popT: 0, color: pick(rng, FX_COLORS),
2627
+ delay: rng() * 0.45,
2628
+ }));
2629
+ const FADE_IN = 0.35;
2630
+ const xOf = (b) => b.x0 + Math.sin(b.t * b.f + b.ph) * b.amp;
2631
+ return {
2632
+ step(dt) {
2633
+ for (const b of bs) {
2634
+ if (b.delay > 0) { b.delay -= dt; continue; }
2635
+ b.t += dt;
2636
+ if (!b.popped) { b.vy *= Math.pow(1.2, dt); b.y += b.vy * dt; b.life -= dt; if (b.life <= 0) b.popped = true; } else b.popT += dt;
2637
+ }
2638
+ return bs.some((b) => !b.popped || b.popT < 0.25);
2639
+ },
2640
+ draw(ctx) {
2641
+ for (const b of bs) {
2642
+ if (b.delay > 0) continue;
2643
+ const x = xOf(b);
2644
+ if (!b.popped) {
2645
+ const fade = easeOutCubic(Math.min(1, b.t / FADE_IN));
2646
+ const rad = b.rad * (0.55 + 0.45 * fade);
2647
+ ctx.globalAlpha = fade;
2648
+ ctx.fillStyle = rgba(b.color, 0.14); ctx.strokeStyle = rgba(b.color, 0.85); ctx.lineWidth = 1.5;
2649
+ ctx.beginPath(); ctx.arc(x, b.y, rad, 0, TAU); ctx.fill(); ctx.stroke();
2650
+ ctx.fillStyle = 'rgba(255,255,255,.85)';
2651
+ ctx.beginPath(); ctx.arc(x - rad * 0.35, b.y - rad * 0.35, rad * 0.22, 0, TAU); ctx.fill();
2652
+ } else if (b.popT < 0.25) {
2653
+ const q = b.popT / 0.25;
2654
+ ctx.globalAlpha = 1 - q; ctx.strokeStyle = b.color; ctx.lineWidth = 1.5;
2655
+ for (let k = 0; k < 6; k++) {
2656
+ const a = (k / 6) * TAU;
2657
+ const r0 = b.rad * (1 + q * 0.6);
2658
+ const r1 = b.rad * (1.3 + q * 1.2);
2659
+ ctx.beginPath(); ctx.moveTo(x + Math.cos(a) * r0, b.y + Math.sin(a) * r0); ctx.lineTo(x + Math.cos(a) * r1, b.y + Math.sin(a) * r1); ctx.stroke();
2660
+ }
2661
+ }
2662
+ }
2663
+ },
2664
+ };
2665
+ }
2666
+
2667
+ function burstBalloons(r, env, rng) {
2668
+ const N = 7;
2669
+ const bs = Array.from({ length: N }, (_, i) => ({
2670
+ x0: r.x + (r.w * (i + 0.5)) / N + (rng() - 0.5) * 20, y: r.y + r.h * 0.5 + rng() * 20, rad: 15 + rng() * 7, vy: -(70 + rng() * 60),
2671
+ sway: 8 + rng() * 10, f: 0.8 + rng() * 0.8, ph: rng() * TAU, delay: rng() * 0.35, color: FX_COLORS[i % FX_COLORS.length], t: 0, scale: 0,
2672
+ }));
2673
+ return {
2674
+ step(dt) {
2675
+ for (const b of bs) {
2676
+ if (b.delay > 0) { b.delay -= dt; continue; }
2677
+ b.t += dt; b.scale = Math.min(1, b.scale + dt * 4); b.vy -= 40 * dt; b.y += b.vy * dt;
2678
+ }
2679
+ return bs.some((b) => b.y + b.rad * 4 > 0 && b.t < 7);
2680
+ },
2681
+ draw(ctx) {
2682
+ for (const b of bs) {
2683
+ if (b.delay > 0) continue;
2684
+ const x = b.x0 + Math.sin(b.t * b.f + b.ph) * b.sway;
2685
+ ctx.save();
2686
+ ctx.translate(x, b.y); ctx.scale(b.scale, b.scale);
2687
+ const ry = b.rad * 1.2;
2688
+ ctx.strokeStyle = env.fg; ctx.globalAlpha = 0.45; ctx.lineWidth = 1;
2689
+ ctx.beginPath(); ctx.moveTo(0, ry + 4); ctx.quadraticCurveTo(Math.sin(b.t * 2 + b.ph) * 10, ry + 26, Math.sin(b.t * 1.4 + b.ph) * 6, ry + 50); ctx.stroke();
2690
+ ctx.globalAlpha = 1; ctx.fillStyle = b.color;
2691
+ ctx.beginPath(); ctx.moveTo(-3, ry + 5); ctx.lineTo(3, ry + 5); ctx.lineTo(0, ry - 1); ctx.closePath(); ctx.fill();
2692
+ ctx.beginPath(); ctx.ellipse(0, 0, b.rad, ry, 0, 0, TAU); ctx.fill();
2693
+ ctx.fillStyle = 'rgba(255,255,255,.5)';
2694
+ ctx.beginPath(); ctx.ellipse(-b.rad * 0.35, -ry * 0.4, b.rad * 0.2, ry * 0.3, -0.4, 0, TAU); ctx.fill();
2695
+ ctx.restore();
2696
+ }
2697
+ },
2698
+ };
2699
+ }
2700
+
2701
+ function burstPop(r, env, rng) {
2702
+ const cx = r.x + r.w / 2;
2703
+ const cy = r.y + r.h / 2;
2704
+ const dots = Array.from({ length: 16 }, (_, i) => {
2705
+ const a = (i / 16) * TAU + rng() * 0.2;
2706
+ return { a, d: 0, sp: 90 + rng() * 80, size: 2 + rng() * 2.5 };
2707
+ });
2708
+ let t = 0;
2709
+ return {
2710
+ step(dt) { t += dt; for (const d of dots) d.d += d.sp * dt; return t < 0.55; },
2711
+ draw(ctx) {
2712
+ const q = t / 0.55;
2713
+ const grow = 6 + q * 22;
2714
+ ctx.globalAlpha = 1 - q; ctx.strokeStyle = env.accent; ctx.lineWidth = 2;
2715
+ ctx.strokeRect(r.x - grow, r.y - grow, r.w + grow * 2, r.h + grow * 2);
2716
+ ctx.fillStyle = env.accent;
2717
+ for (const d of dots) {
2718
+ const ex = (r.w / 2) * Math.abs(Math.cos(d.a)) + d.d;
2719
+ const ey = (r.h / 2) * Math.abs(Math.sin(d.a)) + d.d;
2720
+ ctx.beginPath(); ctx.arc(cx + Math.sign(Math.cos(d.a)) * ex, cy + Math.sign(Math.sin(d.a)) * ey, d.size * (1 - q * 0.6), 0, TAU); ctx.fill();
2721
+ }
2722
+ },
2723
+ };
2724
+ }
2725
+
2726
+ /** Flash, shockwave and sparks all rush out and then decelerate (ease-out) to a stop. */
2727
+ function burstSupernova(r, env, rng) {
2728
+ const cx = r.x + r.w / 2;
2729
+ const cy = r.y + r.h / 2;
2730
+ const R = Math.max(r.w, r.h) * 1.4;
2731
+ const colors = ['#ffffff', env.accent, '#ffd27a'];
2732
+ const ps = Array.from({ length: 80 }, () => ({
2733
+ a: rng() * TAU, reach: R * (0.4 + rng() * 0.9), dur: 0.9 + rng() * 0.6, color: pick(rng, colors),
2734
+ }));
2735
+ const DUR = 1.6;
2736
+ let t = 0;
2737
+ return {
2738
+ step(dt) { t += dt; return t < DUR; },
2739
+ draw(ctx) {
2740
+ ctx.globalCompositeOperation = 'lighter';
2741
+ const CORE = 0.6;
2742
+ if (t < CORE) {
2743
+ const q = t / CORE;
2744
+ const rad = Math.max(1, R * 0.9 * easeOutQuart(q));
2745
+ const g = ctx.createRadialGradient(cx, cy, 0, cx, cy, rad);
2746
+ g.addColorStop(0, `rgba(255,255,255,${1 - q})`); g.addColorStop(0.4, `rgba(255,230,180,${0.6 * (1 - q)})`); g.addColorStop(1, 'rgba(255,200,120,0)');
2747
+ ctx.fillStyle = g; ctx.beginPath(); ctx.arc(cx, cy, rad, 0, TAU); ctx.fill();
2748
+ }
2749
+ const RING = 1.2;
2750
+ if (t < RING) {
2751
+ const q = t / RING;
2752
+ ctx.globalAlpha = Math.pow(1 - q, 1.5); ctx.strokeStyle = env.accent; ctx.lineWidth = 6 * (1 - q) + 1;
2753
+ ctx.beginPath(); ctx.arc(cx, cy, R * 1.3 * easeOutQuart(q), 0, TAU); ctx.stroke();
2754
+ }
2755
+ ctx.lineWidth = 2; ctx.lineCap = 'round';
2756
+ for (const p of ps) {
2757
+ const q = Math.min(1, t / p.dur);
2758
+ if (q >= 1) continue;
2759
+ const d = p.reach * easeOutQuart(q);
2760
+ const speed = 4 * Math.pow(1 - q, 3); // derivative of easeOutQuart: streaks shrink as sparks slow
2761
+ const tail = Math.min(d, p.reach * speed * 0.08);
2762
+ ctx.globalAlpha = Math.pow(1 - q, 0.8);
2763
+ ctx.strokeStyle = p.color;
2764
+ ctx.beginPath();
2765
+ ctx.moveTo(cx + Math.cos(p.a) * (d - tail), cy + Math.sin(p.a) * (d - tail));
2766
+ ctx.lineTo(cx + Math.cos(p.a) * d + 0.01, cy + Math.sin(p.a) * d);
2767
+ ctx.stroke();
2768
+ }
2769
+ },
2770
+ };
2771
+ }
2772
+
2773
+ const BURSTS = {
2774
+ explode: burstExplode, burn: burstBurn,
2775
+ confetti: burstConfetti, fireworks: burstFireworks, bubbles: burstBubbles, balloons: burstBalloons,
2776
+ pop: burstPop, supernova: burstSupernova,
2777
+ };
2778
+
2779
+ /** Side of the square obstacle the cursor becomes when a theme's "mouse" setting is on. */
2780
+ const MOUSE_SIZE = 36;
2781
+
2782
+ /** Pure: attach px/s velocities to obstacle rects using the previous frame's positions. */
2783
+ function withVelocities(prev, rects, dt) {
2784
+ const next = new Map();
2785
+ const out = rects.map((o) => {
2786
+ const p = prev.get(o.id);
2787
+ const vx = p === undefined ? 0 : p.vx * 0.5 + ((o.x - p.x) / dt) * 0.5;
2788
+ const vy = p === undefined ? 0 : p.vy * 0.5 + ((o.y - p.y) / dt) * 0.5;
2789
+ const v = { ...o, vx, vy };
2790
+ next.set(o.id, v);
2791
+ return v;
2792
+ });
2793
+ return { obstacles: out, memory: next };
2794
+ }
2795
+
2796
+ /* ---------- Seed board ---------- */
2797
+
2798
+ const SEED_MD = `---
2799
+ version: 1
2800
+ effects.complete: random
2801
+ ---
2802
+ # Sprint 14
2803
+
2804
+ ## Backlog
2805
+
2806
+ ### Export board as a .md file
2807
+ - id: t-01
2808
+ - owner: Aaron
2809
+ - tags: feature
2810
+ - history:
2811
+ - Backlog @ 2026-10-19T09:12:00Z by Aaron
2812
+
2813
+ \`\`\`md
2814
+ Download the current markdown, named after the **board title**.
2815
+ \`\`\`
2816
+
2817
+ ### Keyboard moves between columns
2818
+ - id: t-02
2819
+ - owner:
2820
+ - tags: a11y, feature
2821
+ - history:
2822
+ - Backlog @ 2026-10-20T14:30:00Z
2823
+
2824
+ \`\`\`md
2825
+ \`Alt\` + arrow keys move the focused card one column *left* or *right*.
2826
+ \`\`\`
2827
+
2828
+ ## To Do
2829
+
2830
+ ### Remember theme per board
2831
+ - id: t-03
2832
+ - owner: Priya
2833
+ - tags: themes
2834
+ - history:
2835
+ - Backlog @ 2026-10-19T09:40:00Z
2836
+ - To Do @ 2026-10-22T11:05:00Z by Priya
2837
+
2838
+ ### Line numbers in parse errors
2839
+ - id: t-04
2840
+ - owner: Sam
2841
+ - tags: markdown, bug
2842
+ - history:
2843
+ - To Do @ 2026-10-23T16:20:00Z by Sam
2844
+
2845
+ ## Doing
2846
+
2847
+ ### Tune ocean wake strength
2848
+ - id: t-05
2849
+ - owner: Aaron
2850
+ - tags: themes, webgl
2851
+ - history:
2852
+ - Backlog @ 2026-10-19T10:00:00Z
2853
+ - To Do @ 2026-10-21T09:00:00Z by Priya
2854
+ - Doing @ 2026-10-26T13:45:00Z by Aaron
2855
+
2856
+ \`\`\`md
2857
+ Small cards barely disturb the water.
2858
+
2859
+ - [x] Push water while dragging
2860
+ - [x] Splash on drop
2861
+ - [ ] Scale the push by **card area**
2862
+ \`\`\`
2863
+
2864
+ ### Tag pill colours
2865
+ - id: t-06
2866
+ - owner: Priya
2867
+ - tags: design
2868
+ - history:
2869
+ - To Do @ 2026-10-22T11:10:00Z by Priya
2870
+ - Doing @ 2026-10-24T10:30:00Z by Priya
2871
+
2872
+ ## Done
2873
+
2874
+ ### Markdown round-trip
2875
+ - id: t-07
2876
+ - owner: Sam
2877
+ - tags: markdown
2878
+ - history:
2879
+ - Backlog @ 2026-10-15T08:00:00Z
2880
+ - To Do @ 2026-10-16T09:30:00Z by Sam
2881
+ - Doing @ 2026-10-17T10:00:00Z by Sam
2882
+ - Done @ 2026-10-21T17:15:00Z by Sam
2883
+
2884
+ \`\`\`md
2885
+ Board → markdown → board gives back the *same* board.
2886
+
2887
+ > Descriptions live in a fenced block, so headings and lists in them never clash with the board's own headings.
2888
+ \`\`\`
2889
+
2890
+ ## Archive <!-- archive -->
2891
+
2892
+ ### Board title in the browser tab
2893
+ - id: t-08
2894
+ - owner: Sam
2895
+ - tags: feature
2896
+ - history:
2897
+ - To Do @ 2026-10-14T09:00:00Z by Priya
2898
+ - Doing @ 2026-10-15T10:20:00Z by Priya
2899
+ - Doing @ 2026-10-16T08:05:00Z by Sam
2900
+ - Done @ 2026-10-16T15:40:00Z by Sam
2901
+ - Archive @ 2026-10-18T09:00:00Z by Sam
2902
+ `;
2903
+
2904
+ const STORAGE_BOARD = 'kb-board-md:v4';
2905
+ const STORAGE_BOARD_V3 = 'kb-board-md:v3';
2906
+ const STORAGE_BOARD_V2 = 'kb-board-md:v2';
2907
+ const STORAGE_BOARD_V1 = 'kb-board-md:v1';
2908
+
2909
+ /** v3 files carried column stages ("<!-- stage: … -->" on headings, "[stage]" in history). v4 drops them. */
2910
+ function migrateV3(md) {
2911
+ return md.replace(/^(## .*?)\s*<!--\s*stage:\s*[a-z-]+\s*-->\s*$/gm, '$1').replace(/^(\s+- .+? @ \S+) \[[a-z-]+\]/gm, '$1');
2912
+ }
2913
+
2914
+ /** v1 files had bare description text after the metadata; v2 fences it. Pure text transform. */
2915
+ function migrateV1(md) {
2916
+ const out = [];
2917
+ let state = 'none'; // 'none' | 'meta' | 'desc'
2918
+ let desc = [];
2919
+ const flush = () => {
2920
+ while (desc.length > 0 && desc[desc.length - 1].trim() === '') desc.pop();
2921
+ if (desc.length > 0) out.push('```md', ...desc, '```', '');
2922
+ desc = [];
2923
+ };
2924
+ for (const line of md.replace(/\r\n?/g, '\n').split('\n')) {
2925
+ if (/^#{1,3} /.test(line)) { flush(); out.push(line); state = line.startsWith('### ') ? 'meta' : 'none'; continue; }
2926
+ if (state === 'meta') { out.push(line); if (line.trim() === '') state = 'desc'; continue; }
2927
+ if (state === 'desc') { desc.push(line); continue; }
2928
+ out.push(line);
2929
+ }
2930
+ flush();
2931
+ return out.join('\n');
2932
+ }
2933
+ const STORAGE_THEME_LEGACY = 'kb-theme:v1';
2934
+ const STORAGE_EFFECTS_LEGACY = 'kb-effects:v1';
2935
+ const MODES = [{ id: 'board', label: 'Board' }, { id: 'split', label: 'Split' }, { id: 'archive', label: 'Archive' }, { id: 'source', label: 'Markdown' }];
2936
+ /** How each mode is spelled in ?view=. */
2937
+ const VIEW_PARAM = { board: 'board', split: 'split', archive: 'archive', source: 'markdown' };
2938
+ /** Files and URLs opened from the Open dialog, newest first: { name, url } or { name, md } (a file's text, since its handle can't be stored). */
2939
+ /** What New starts from (it keeps the current style). */
2940
+ const BLANK_MD = '# Untitled board\n\n## To Do\n\n## Doing\n\n## Done\n';
2941
+ const STORAGE_RECENTS = 'kb-recents:v1';
2942
+ const STORAGE_DRAWER_WIDTH = 'kb-drawer-width:v1';
2943
+ const DRAWER_MIN_WIDTH = 320;
2944
+ const MAX_RECENTS = 8;
2945
+ const MAX_UNDO = 100;
2946
+ /** A shared link carries the board in the hash (#board=…), so it never reaches the server and isn't bound by its URL limits. */
2947
+ const SHARE_PREFIX = '#board=';
2948
+ const TOAST_MS = 2500;
2949
+ const SHARE_WARN_LENGTH = 2000;
2950
+ /** Markdown → deflate-raw → base64url, and back. */
2951
+ async function encodeShare(md) {
2952
+ const bytes = new Uint8Array(await new Response(new Blob([md]).stream().pipeThrough(new CompressionStream('deflate-raw'))).arrayBuffer());
2953
+ let bin = '';
2954
+ for (const b of bytes) bin += String.fromCharCode(b);
2955
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
2956
+ }
2957
+ async function decodeShare(s) {
2958
+ const bytes = Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/')), (c) => c.charCodeAt(0));
2959
+ return new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('deflate-raw'))).text();
2960
+ }
2961
+
2962
+ /* ---------- (6) Component: the IO edge ---------- */
2963
+
2964
+ class Component extends DCLogic {
2965
+ constructor(props) {
2966
+ super(props);
2967
+ this.uid = `kb${Math.floor(Math.random() * 1e9).toString(36)}`;
2968
+ this.fxSeed = 1337;
2969
+ const loaded = Component.loadInitial(props);
2970
+ // The address bar is the source of the file (?src=) and the selections; see fromQuery.
2971
+ const p = Component.fromQuery(location.search);
2972
+ this.src = p.src;
2973
+ this.shared = location.hash.startsWith(SHARE_PREFIX) ? location.hash.slice(SHARE_PREFIX.length) : null; // a board from a shared link, until another is opened
2974
+ this.fileHandle = null;
2975
+ this.writable = null; // the ?src URL when the server that sent it takes it back (x-agile-writable: the agile CLI or make dev)
2976
+ this.lastEditKey = null; // the field last typed into: further typing there extends the same undo step
2977
+ this.pageKey = `${p.mode}|${p.task}`;
2978
+ this.state = {
2979
+ board: loaded.board,
2980
+ saveStatus: this.shared !== null ? 'Loading shared board…' : p.src === null ? loaded.saveStatus : `Loading ${p.src}…`,
2981
+ storageWarning: loaded.storageWarning,
2982
+ fresh: null,
2983
+ restoreTargets: {},
2984
+ mode: p.mode,
2985
+ sourceDraft: null,
2986
+ parseError: null,
2987
+ query: p.query,
2988
+ filterOpen: false,
2989
+ tagFilter: p.tags,
2990
+ ownerFilter: p.owners,
2991
+ pickerOpen: false,
2992
+ editingTaskId: p.task,
2993
+ drafts: {},
2994
+ fieldErrors: {},
2995
+ tagInput: '',
2996
+ descTab: 'preview',
2997
+ historyOpen: false,
2998
+ timeOpen: false, // the time slider
2999
+ timeAt: null, // the ISO time the board is shown at; null = now (editable)
3000
+ now: Date.now(),
3001
+ drag: null,
3002
+ opError: null,
3003
+ toast: null, // a short-lived note after a file action (see notify)
3004
+ effectError: null,
3005
+ copyLabel: 'Copy',
3006
+ themeOverride: p.theme,
3007
+ menuOpen: false,
3008
+ badgeOpen: false,
3009
+ completeDialogFor: null,
3010
+ drawerWidth: Component.loadDrawerWidth(),
3011
+ collapsed: [], // ids of tasks whose children are folded away (this session only)
3012
+ past: [], future: [], // undo/redo: earlier and undone boards, nearest last / first
3013
+ recents: Component.loadRecents(),
3014
+ openOpen: false, openUrl: p.src ?? '', openBusy: false, openError: null, openDragging: false,
3015
+ };
3016
+ }
3017
+
3018
+ static KEYS = { board: STORAGE_BOARD, recents: STORAGE_RECENTS };
3019
+
3020
+ /**
3021
+ * ?src=<url> the markdown to show (absolute, or relative to the page; GitHub file links work). Not autosaved.
3022
+ * ?view=board|split|archive|markdown ?q=<search> ?tags=a,b ?owners=a,b ?task=<id> (open in the editor)
3023
+ * ?theme=<id> shows the board in that style without changing the file. Unknown values are ignored.
3024
+ */
3025
+ static fromQuery(search) {
3026
+ const q = new URLSearchParams(search);
3027
+ const list = (k) => (q.get(k) ?? '').split(',').map((x) => x.trim()).filter((x) => x !== '');
3028
+ const mode = MODES.find((m) => VIEW_PARAM[m.id] === q.get('view'));
3029
+ const theme = q.get('theme');
3030
+ return {
3031
+ src: q.get('src'), mode: mode === undefined ? 'board' : mode.id, query: q.get('q') ?? '',
3032
+ tags: list('tags'), owners: list('owners'), task: q.get('task'), theme: THEMES.some((t) => t.id === theme) ? theme : null,
3033
+ };
3034
+ }
3035
+ /** The query string for a state, keeping unrelated params. */
3036
+ static toQuery(s, src, search) {
3037
+ const q = new URLSearchParams(search);
3038
+ for (const k of ['src', 'view', 'q', 'tags', 'owners', 'task', 'theme']) q.delete(k);
3039
+ const owners = s.ownerFilter.filter((o) => o !== '');
3040
+ if (src !== null) q.set('src', src);
3041
+ if (s.mode !== 'board') q.set('view', VIEW_PARAM[s.mode]);
3042
+ if (s.query !== '') q.set('q', s.query);
3043
+ if (s.tagFilter.length > 0) q.set('tags', s.tagFilter.join(','));
3044
+ if (owners.length > 0) q.set('owners', owners.join(','));
3045
+ if (s.editingTaskId !== null) q.set('task', s.editingTaskId);
3046
+ if (s.themeOverride !== null) q.set('theme', s.themeOverride);
3047
+ const out = q.toString().replace(/%2F/gi, '/').replace(/%3A/gi, ':').replace(/%2C/gi, ',');
3048
+ return out === '' ? '' : `?${out}`;
3049
+ }
3050
+ static loadDrawerWidth() {
3051
+ try { const w = Number(window.localStorage.getItem(STORAGE_DRAWER_WIDTH)); return w >= DRAWER_MIN_WIDTH ? w : 400; } catch (err) { return 400; } // blocked storage: default width
3052
+ }
3053
+ /** Drag the drawer's left edge; the width is remembered in this browser. */
3054
+ resizeDrawer(e) {
3055
+ e.preventDefault();
3056
+ const startX = e.clientX;
3057
+ const startW = this.state.drawerWidth;
3058
+ const move = (ev) => this.setState({ drawerWidth: Math.max(DRAWER_MIN_WIDTH, Math.min(window.innerWidth - 40, startW + startX - ev.clientX)) });
3059
+ const up = () => {
3060
+ window.removeEventListener('pointermove', move);
3061
+ window.removeEventListener('pointerup', up);
3062
+ try { window.localStorage.setItem(STORAGE_DRAWER_WIDTH, String(Math.round(this.state.drawerWidth))); } catch (err) { /* blocked storage: width lasts this session */ }
3063
+ };
3064
+ window.addEventListener('pointermove', move);
3065
+ window.addEventListener('pointerup', up);
3066
+ }
3067
+ static loadRecents() {
3068
+ try {
3069
+ const v = JSON.parse(window.localStorage.getItem(STORAGE_RECENTS) ?? '[]');
3070
+ return Array.isArray(v) ? v.filter((r) => typeof r.name === 'string' && (typeof r.url === 'string' || typeof r.md === 'string')) : [];
3071
+ } catch (err) { return []; } // unreadable or blocked storage: start with no recents
3072
+ }
3073
+ shownTheme() { return themeById(this.state.themeOverride ?? this.state.board.settings.theme); }
3074
+
3075
+ static loadInitial(props) {
3076
+ let board = parseBoard(SEED_MD);
3077
+ if (props.startTheme !== undefined) board = setTheme(board, props.startTheme);
3078
+ let saveStatus = 'Saved in this browser';
3079
+ let storageWarning = null;
3080
+ try {
3081
+ const md = window.localStorage.getItem(STORAGE_BOARD);
3082
+ // Older saves, newest first: v3 had column stages, v2 is already valid, v1 had unfenced descriptions.
3083
+ const legacy = [[STORAGE_BOARD_V3, migrateV3], [STORAGE_BOARD_V2, (x) => x], [STORAGE_BOARD_V1, migrateV1]]
3084
+ .map(([key, up]) => ({ text: window.localStorage.getItem(key), up })).find((x) => x.text !== null);
3085
+ if (md !== null) {
3086
+ try { board = parseBoard(md); } catch (err) { saveStatus = `Stored board didn't parse, showing the sample instead: ${err.message}`; }
3087
+ } else if (legacy !== undefined) {
3088
+ try {
3089
+ board = parseBoard(legacy.up(legacy.text));
3090
+ saveStatus = 'Upgraded your saved board to the current format';
3091
+ } catch (err) { saveStatus = `Older saved board couldn't be upgraded, showing the sample instead: ${err.message}`; }
3092
+ }
3093
+ // Style and effect choices used to live in their own browser keys; fold them into the board header once.
3094
+ const legacyTheme = window.localStorage.getItem(STORAGE_THEME_LEGACY);
3095
+ const legacyFx = window.localStorage.getItem(STORAGE_EFFECTS_LEGACY);
3096
+ if (legacyTheme !== null || legacyFx !== null) {
3097
+ try {
3098
+ if (legacyTheme !== null) {
3099
+ const stored = JSON.parse(legacyTheme);
3100
+ board = setTheme(board, stored.themeId);
3101
+ for (const t of THEMES) {
3102
+ const saved = stored.settings[t.id] ?? {};
3103
+ for (const k of Object.keys(t.settings)) if (k in saved) board = setThemeSetting(board, t.id, k, saved[k]);
3104
+ }
3105
+ }
3106
+ if (legacyFx !== null) {
3107
+ const stored = JSON.parse(legacyFx);
3108
+ for (const event of Object.keys(EVENT_EFFECTS)) if (event in stored) board = setEffect(board, event, stored[event]);
3109
+ }
3110
+ } catch (err) { storageWarning = `Earlier style settings couldn't be carried over: ${err.message}`; }
3111
+ window.localStorage.removeItem(STORAGE_THEME_LEGACY);
3112
+ window.localStorage.removeItem(STORAGE_EFFECTS_LEGACY);
3113
+ }
3114
+ window.localStorage.setItem(STORAGE_BOARD, serializeBoard(board));
3115
+ } catch (err) {
3116
+ saveStatus = `Not saved: this browser blocked storage (${err.message}). Copy the markdown to keep it.`;
3117
+ }
3118
+ return { board, saveStatus, storageWarning };
3119
+ }
3120
+
3121
+ /* ---- lifecycle ---- */
3122
+ componentDidMount() {
3123
+ this.alive = true;
3124
+ this.fx = null;
3125
+ this.gl = null;
3126
+ this.fxFailedFor = null;
3127
+ this.obstacleMemory = new Map();
3128
+ this.lastTs = null;
3129
+ this.suppressClick = false;
3130
+ this.bursts = [];
3131
+ this.burstDirty = false;
3132
+ this.mouse = null;
3133
+ this.onWinMove = (e) => { this.mouse = { x: e.clientX, y: e.clientY }; this.handlePointerMove(e); };
3134
+ this.onWinUp = (e) => this.handlePointerUp(e);
3135
+ window.addEventListener('pointermove', this.onWinMove);
3136
+ window.addEventListener('pointerup', this.onWinUp);
3137
+ window.addEventListener('pointercancel', this.onWinUp);
3138
+ // The history summary measures open-ended stays against "now"; tick it here at the edge.
3139
+ this.clock = window.setInterval(() => this.setState({ now: Date.now() }), 30000);
3140
+ const loop = (ts) => {
3141
+ if (!this.alive) return;
3142
+ this.frame(ts);
3143
+ this.raf = window.requestAnimationFrame(loop);
3144
+ };
3145
+ this.raf = window.requestAnimationFrame(loop);
3146
+ this.onPop = () => {
3147
+ const p = Component.fromQuery(location.search);
3148
+ if (p.src !== this.src) { window.location.reload(); return; }
3149
+ this.pageKey = `${p.mode}|${p.task}`;
3150
+ this.setState({ mode: p.mode, query: p.query, tagFilter: p.tags, ownerFilter: p.owners, editingTaskId: p.task, themeOverride: p.theme });
3151
+ };
3152
+ this.onKey = (e) => {
3153
+ if (!(e.metaKey || e.ctrlKey) || e.altKey) return;
3154
+ const key = e.key.toLowerCase();
3155
+ if (key === 's') { e.preventDefault(); this.save(); return; }
3156
+ // Cmd/Ctrl+Enter is the task drawer's Ok.
3157
+ if (key === 'enter' && this.state.editingTaskId !== null && this.state.completeDialogFor === null) { e.preventDefault(); this.setState({ editingTaskId: null, drafts: {}, fieldErrors: {}, tagInput: '' }); return; }
3158
+ if (key !== 'z' && key !== 'y') return;
3159
+ // Text fields keep the browser's own undo for what's being typed.
3160
+ if (typeof e.target?.closest === 'function' && e.target.closest('input,textarea,select,[contenteditable]') !== null) return;
3161
+ e.preventDefault();
3162
+ if (key === 'y' || e.shiftKey) this.redo(); else this.undo();
3163
+ };
3164
+ this.onHash = () => { if (location.hash.startsWith(SHARE_PREFIX)) window.location.reload(); }; // another shared link pasted into this tab
3165
+ window.addEventListener('popstate', this.onPop);
3166
+ window.addEventListener('hashchange', this.onHash);
3167
+ window.addEventListener('keydown', this.onKey);
3168
+ if (this.shared !== null) {
3169
+ decodeShare(this.shared).then((md) => { const board = parseBoard(md); this.setState({ board, saveStatus: this.persistBoard(board), now: Date.now() }); })
3170
+ .catch((err) => { this.shared = null; this.setState({ opError: `Can't open the shared link: ${err.message}`, saveStatus: this.persistBoard(this.state.board) }); });
3171
+ } else if (this.src !== null) {
3172
+ const src = this.src;
3173
+ this.openUrl(src).catch((err) => {
3174
+ this.src = null;
3175
+ this.setState({ openOpen: true, openError: `Can't load ${src}: ${err.message}`, saveStatus: this.persistBoard(this.state.board) });
3176
+ });
3177
+ }
3178
+ }
3179
+ /** Keep the address bar in step: a new view or task is a history entry, anything else replaces it. */
3180
+ componentDidUpdate() {
3181
+ this.syncSharedHash();
3182
+ const next = Component.toQuery(this.state, this.src, location.search);
3183
+ const key = `${this.state.mode}|${this.state.editingTaskId}`;
3184
+ const isNewPage = key !== this.pageKey;
3185
+ this.pageKey = key;
3186
+ const hash = this.shared === null && location.hash.startsWith(SHARE_PREFIX) ? '' : location.hash; // drop the shared board once another is opened
3187
+ if (next === location.search && hash === location.hash) return;
3188
+ const url = location.pathname + next + hash;
3189
+ if (isNewPage) history.pushState(null, '', url); else history.replaceState(null, '', url);
3190
+ }
3191
+ /** While a shared board is shown, #board= follows its edits, so the address bar (and a reload) has the current board. */
3192
+ syncSharedHash() {
3193
+ const board = this.state.board;
3194
+ if (this.shared === null || board === this.hashedBoard) return;
3195
+ this.hashedBoard = board;
3196
+ encodeShare(serializeBoard(board)).then((enc) => {
3197
+ if (this.shared === null || this.state.board !== board) return; // another board, or a newer edit, took over
3198
+ this.shared = enc;
3199
+ history.replaceState(null, '', location.pathname + location.search + SHARE_PREFIX + enc);
3200
+ }, (err) => this.setState({ opError: `Couldn't update the link in the address bar: ${err.message}` }));
3201
+ }
3202
+ componentWillUnmount() {
3203
+ window.removeEventListener('popstate', this.onPop);
3204
+ window.removeEventListener('hashchange', this.onHash);
3205
+ window.removeEventListener('keydown', this.onKey);
3206
+ this.alive = false;
3207
+ window.clearTimeout(this.toastTimer);
3208
+ window.cancelAnimationFrame(this.raf);
3209
+ window.clearInterval(this.clock);
3210
+ window.removeEventListener('pointermove', this.onWinMove);
3211
+ window.removeEventListener('pointerup', this.onWinUp);
3212
+ window.removeEventListener('pointercancel', this.onWinUp);
3213
+ if (this.fx !== null) { this.fx.dispose(); this.fx = null; }
3214
+ }
3215
+
3216
+ /* ---- DOM geometry (local, unscaled coordinates relative to the board root) ---- */
3217
+ rootEl() { return document.querySelector(`[data-kb-root="${this.uid}"]`); }
3218
+ geometry() {
3219
+ const root = this.rootEl();
3220
+ if (root === null) bug('board root missing while handling input');
3221
+ const r = root.getBoundingClientRect();
3222
+ const scale = root.offsetWidth > 0 ? r.width / root.offsetWidth : 1;
3223
+ return { root, left: r.left, top: r.top, scale, local: (rect) => ({ x: (rect.left - r.left) / scale, y: (rect.top - r.top) / scale, w: rect.width / scale, h: rect.height / scale }) };
3224
+ }
3225
+
3226
+ /* ---- animation frame: WebGL effect + drag autoscroll ---- */
3227
+ frame(ts) {
3228
+ const dt = this.lastTs === null ? 1 / 60 : Math.min((ts - this.lastTs) / 1000, 0.05);
3229
+ this.lastTs = ts;
3230
+ const root = this.rootEl();
3231
+ if (root === null) return; // not mounted into the document yet (first frame)
3232
+ this.autoScroll(root);
3233
+ try {
3234
+ this.stepBursts(root, dt);
3235
+ } catch (err) {
3236
+ this.bursts = [];
3237
+ this.setState({ opError: `Effect stopped: ${err.message}` });
3238
+ }
3239
+ const theme = this.shownTheme();
3240
+ if (theme.effect === null) {
3241
+ if (this.fx !== null) { this.fx.dispose(); this.fx = null; }
3242
+ return;
3243
+ }
3244
+ if (this.fxFailedFor === theme.id) return;
3245
+ const canvas = root.querySelector('[data-kb-canvas]');
3246
+ if (canvas === null) bug('effect canvas missing');
3247
+ if (this.gl === null) {
3248
+ this.gl = canvas.getContext('webgl2', { antialias: true, alpha: true, premultipliedAlpha: true });
3249
+ if (this.gl === null) {
3250
+ this.fxFailedFor = theme.id;
3251
+ this.setState({ effectError: `${theme.name} needs WebGL2, which this browser didn't provide. The board works; pick a non-WebGL style for a cleaner look.` });
3252
+ return;
3253
+ }
3254
+ }
3255
+ try {
3256
+ if (this.fx === null || this.fx.kind !== theme.effect) {
3257
+ if (this.fx !== null) this.fx.dispose();
3258
+ this.fx = null;
3259
+ const factory = EFFECT_FACTORIES[theme.effect] ?? bug(`no effect factory "${theme.effect}"`);
3260
+ this.fx = factory(this.gl, this.fxSeed);
3261
+ }
3262
+ const geo = this.geometry();
3263
+ const w = root.offsetWidth;
3264
+ const h = root.offsetHeight;
3265
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
3266
+ const cw = Math.max(1, Math.round(w * dpr));
3267
+ const ch = Math.max(1, Math.round(h * dpr));
3268
+ if (canvas.width !== cw || canvas.height !== ch) { canvas.width = cw; canvas.height = ch; }
3269
+ const rects = Array.from(root.querySelectorAll('[data-obstacle]')).map((el) => {
3270
+ const id = el.getAttribute('data-obstacle');
3271
+ return { id, dragging: id.startsWith('drag:'), ...geo.local(el.getBoundingClientRect()) };
3272
+ });
3273
+ const s = this.state.board.settings.themes[theme.id];
3274
+ // The cursor acts like a small dragged card (skipped while a real drag is moving the water/balls).
3275
+ if (s.mouse && this.mouse !== null && this.state.drag === null) {
3276
+ const x = (this.mouse.x - geo.left) / geo.scale;
3277
+ const y = (this.mouse.y - geo.top) / geo.scale;
3278
+ rects.push({ id: 'drag:mouse', dragging: true, x: x - MOUSE_SIZE / 2, y: y - MOUSE_SIZE / 2, w: MOUSE_SIZE, h: MOUSE_SIZE });
3279
+ }
3280
+ const { obstacles, memory } = withVelocities(this.obstacleMemory, rects, dt);
3281
+ this.obstacleMemory = memory;
3282
+ this.fx.step(dt, { width: w, height: h, dpr, obstacles }, s);
3283
+ } catch (err) {
3284
+ this.fxFailedFor = theme.id;
3285
+ if (this.fx !== null) { this.fx.dispose(); this.fx = null; }
3286
+ this.setState({ effectError: `${theme.name} effect stopped: ${err.message}` });
3287
+ }
3288
+ }
3289
+
3290
+ /* ---- event effects (overlay canvas) ---- */
3291
+ randomSeed() { return Math.floor(Math.random() * 4294967296); }
3292
+ pickEffect(event) { return resolveEffect(event, this.state.board.settings.effects[event], mulberry32(this.randomSeed())); }
3293
+ cardRect(taskId) {
3294
+ const geo = this.geometry();
3295
+ const el = geo.root.querySelector(`[data-card-slot="${taskId}"]`);
3296
+ return el === null ? null : geo.local(el.getBoundingClientRect());
3297
+ }
3298
+ elRect(el) { return this.geometry().local(el.getBoundingClientRect()); }
3299
+ playEffect(kind, rect) {
3300
+ if (kind === null) return; // the user chose "None"
3301
+ if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; // respect the OS setting
3302
+ const root = this.rootEl();
3303
+ if (root === null) bug('board root missing while starting an effect');
3304
+ const cs = window.getComputedStyle(root);
3305
+ const v = (name) => cs.getPropertyValue(name).trim();
3306
+ const env = { card: v('--card'), cardBorder: v('--card-border'), accent: v('--accent'), fg: v('--fg') };
3307
+ const make = BURSTS[kind] ?? bug(`no burst named "${kind}"`);
3308
+ this.bursts = [...this.bursts, make(rect, env, mulberry32(this.randomSeed()))];
3309
+ }
3310
+ stepBursts(root, dt) {
3311
+ const canvas = root.querySelector('[data-kb-burst]');
3312
+ if (canvas === null) bug('effect overlay canvas missing');
3313
+ if (this.bursts.length === 0) {
3314
+ if (this.burstDirty) { canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height); this.burstDirty = false; }
3315
+ return;
3316
+ }
3317
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
3318
+ const cw = Math.max(1, Math.round(root.offsetWidth * dpr));
3319
+ const ch = Math.max(1, Math.round(root.offsetHeight * dpr));
3320
+ if (canvas.width !== cw || canvas.height !== ch) { canvas.width = cw; canvas.height = ch; }
3321
+ const ctx = canvas.getContext('2d');
3322
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
3323
+ ctx.clearRect(0, 0, cw, ch);
3324
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
3325
+ this.bursts = this.bursts.filter((b) => b.step(dt));
3326
+ for (const b of this.bursts) { ctx.save(); b.draw(ctx); ctx.restore(); }
3327
+ this.burstDirty = true;
3328
+ }
3329
+
3330
+ autoScroll(root) {
3331
+ const d = this.state.drag;
3332
+ if (d === null || !d.active) return;
3333
+ const scroller = root.querySelector('[data-kb-scroller]');
3334
+ if (scroller === null) return;
3335
+ const geo = this.geometry();
3336
+ const r = geo.local(scroller.getBoundingClientRect());
3337
+ const edge = 60;
3338
+ if (d.x < r.x + edge) scroller.scrollLeft -= 14;
3339
+ else if (d.x > r.x + r.w - edge) scroller.scrollLeft += 14;
3340
+ }
3341
+
3342
+ /* ---- commits ---- */
3343
+ nowIso() { return new Date().toISOString(); }
3344
+ persistBoard(board) {
3345
+ if (this.shared !== null) return 'Not saved in this browser: opened from a shared link. Save or Download to keep changes.';
3346
+ if (this.src !== null) return `Not saved in this browser: opened from ${this.src}. Save or Download to keep changes.`;
3347
+ try {
3348
+ window.localStorage.setItem(STORAGE_BOARD, serializeBoard(board));
3349
+ return 'Saved in this browser';
3350
+ } catch (err) {
3351
+ return `Not saved: this browser blocked storage (${err.message}). Copy the markdown to keep it.`;
3352
+ }
3353
+ }
3354
+ /** Run a pure board transform; on success save and clear the source draft, on failure show the error. Returns true on success. */
3355
+ /** True (and says so) while the board is shown at a past time: the past is read-only. */
3356
+ inPast() {
3357
+ if (this.state.timeAt === null) return false;
3358
+ this.notify('Viewing the past: go back to Now to edit');
3359
+ return true;
3360
+ }
3361
+ commit(transform, extraState, after) {
3362
+ if (this.inPast()) return false;
3363
+ try {
3364
+ const board = transform(this.state.board);
3365
+ this.setState({ ...this.undoStep(board, null), board, now: Date.now(), sourceDraft: null, parseError: null, opError: null, saveStatus: this.persistBoard(board), ...(extraState ?? {}) }, after);
3366
+ return true;
3367
+ } catch (err) {
3368
+ this.setState({ opError: err.message });
3369
+ return false;
3370
+ }
3371
+ }
3372
+ /** Edit a text field with a draft: the input always shows what was typed; the board updates whenever the value is valid. */
3373
+ editField(key, raw, transform, after) {
3374
+ if (this.inPast()) return;
3375
+ const drafts = { ...this.state.drafts, [key]: raw };
3376
+ try {
3377
+ const board = transform(this.state.board);
3378
+ const fieldErrors = { ...this.state.fieldErrors };
3379
+ delete fieldErrors[key];
3380
+ this.setState({ ...this.undoStep(board, key), board, drafts, fieldErrors, sourceDraft: null, parseError: null, saveStatus: this.persistBoard(board) }, after);
3381
+ } catch (err) {
3382
+ this.setState({ drafts, fieldErrors: { ...this.state.fieldErrors, [key]: err.message.replace(/^board(\.[\w[\]]+)*: /, '') } }, after);
3383
+ }
3384
+ }
3385
+
3386
+ /* ---- undo / redo ---- */
3387
+ /** State patch recording the board that `board` replaces. Repeated typing in one field (same key) stays one step. */
3388
+ undoStep(board, key) {
3389
+ const s = this.state;
3390
+ if (board === s.board) return {};
3391
+ const extend = key !== null && key === this.lastEditKey;
3392
+ this.lastEditKey = key;
3393
+ return extend ? { future: [] } : { past: [...s.past, s.board].slice(-MAX_UNDO), future: [] };
3394
+ }
3395
+ /** Moves one step back (dir -1) or forward (+1). Field drafts are dropped so inputs show the restored board. */
3396
+ travel(dir) {
3397
+ if (this.inPast()) return;
3398
+ const s = this.state;
3399
+ const from = dir < 0 ? s.past : s.future;
3400
+ if (from.length === 0) return;
3401
+ const board = dir < 0 ? from[from.length - 1] : from[0];
3402
+ const past = dir < 0 ? s.past.slice(0, -1) : [...s.past, s.board];
3403
+ const future = dir < 0 ? [s.board, ...s.future] : s.future.slice(1);
3404
+ this.lastEditKey = null;
3405
+ this.setState({ board, past, future, saveStatus: this.persistBoard(board), sourceDraft: null, parseError: null, drafts: {}, fieldErrors: {}, drag: null, now: Date.now() });
3406
+ }
3407
+ undo() { this.travel(-1); }
3408
+ redo() { this.travel(1); }
3409
+
3410
+ /* ---- open, save, download ---- */
3411
+ openFile(file) {
3412
+ if (file === undefined) { this.setState({ openError: 'Drop or choose a .md file.' }); return; }
3413
+ if (!/\.(md|markdown|txt)$/i.test(file.name)) { this.setState({ openError: `"${file.name}" is not a markdown file (.md).` }); return; }
3414
+ file.text().then((text) => this.adopt(text, { name: file.name, md: text }, null))
3415
+ .catch((err) => this.setState({ openError: `Can't open ${file.name}: ${err.message}` }));
3416
+ }
3417
+ /** Fetches and shows a board (absolute, or relative to the page; GitHub "blob" links are fetched raw). Other hosts must allow CORS. */
3418
+ async openUrl(raw) {
3419
+ const url = new URL(raw.trim(), location.href).href.replace(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/blob\//, 'https://raw.githubusercontent.com/$1/$2/');
3420
+ const res = await fetch(url);
3421
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
3422
+ const text = await res.text();
3423
+ if (/^\s*<(!doctype|html)/i.test(text)) throw new Error('that is a web page, not a markdown file');
3424
+ this.adopt(text, { name: url.split('/').pop() || url, url: raw.trim() }, raw.trim());
3425
+ if (res.headers.get('x-agile-writable') !== null) this.writable = url;
3426
+ }
3427
+ submitOpenUrl() {
3428
+ const raw = this.state.openUrl.trim();
3429
+ if (raw === '' || this.state.openBusy) return;
3430
+ this.setState({ openBusy: true, openError: null });
3431
+ this.openUrl(raw).then(() => this.setState({ openBusy: false }), (err) => this.setState({ openBusy: false, openError: `Can't open ${raw}: ${err.message}` }));
3432
+ }
3433
+ openRecent(r) {
3434
+ if (r.url === undefined) { try { this.adopt(r.md, r, null); } catch (err) { this.setState({ openError: `Can't open ${r.name}: ${err.message}` }); } return; }
3435
+ this.setState({ openUrl: r.url });
3436
+ this.openUrl(r.url).catch((err) => this.setState({ openOpen: true, openError: `Can't open ${r.url}: ${err.message}` }));
3437
+ }
3438
+ /** Shows an opened board. A URL (src) is shown via ?src= and not autosaved; a file (src null) replaces the board saved in this browser. Throws if it doesn't parse. */
3439
+ adopt(text, recent, src) {
3440
+ const board = parseBoard(text);
3441
+ this.src = src;
3442
+ this.shared = null;
3443
+ this.fileHandle = null;
3444
+ this.writable = null; // the ?src URL when the server that sent it takes it back (x-agile-writable: the agile CLI or make dev)
3445
+ const same = (r) => (recent.url !== undefined ? r.url === recent.url : r.url === undefined && r.name === recent.name);
3446
+ const recents = [recent, ...this.state.recents.filter((r) => !same(r))].slice(0, MAX_RECENTS);
3447
+ try { window.localStorage.setItem(STORAGE_RECENTS, JSON.stringify(recents)); } catch (err) { /* blocked storage: recents last this session only */ }
3448
+ this.lastEditKey = null;
3449
+ this.setState({ board, recents, past: [], future: [], timeAt: null, timeOpen: false, saveStatus: this.persistBoard(board), sourceDraft: null, parseError: null, drag: null, now: Date.now(), openOpen: false, openError: null, openDragging: false });
3450
+ }
3451
+ newBoard() {
3452
+ const ok = window.confirm(this.src === null
3453
+ ? 'Start a new board? It replaces the board saved in this browser, so Save or Download this one first to keep it.'
3454
+ : "Start a new board? Changes to this one that you haven't saved or downloaded will be lost.");
3455
+ if (!ok) return;
3456
+ const board = validateBoard({ ...parseBoard(BLANK_MD), settings: this.state.board.settings });
3457
+ this.src = null;
3458
+ this.shared = null;
3459
+ this.fileHandle = null;
3460
+ this.writable = null; // the ?src URL when the server that sent it takes it back (x-agile-writable: the agile CLI or make dev)
3461
+ this.lastEditKey = null;
3462
+ this.setState({ board, past: [], future: [], timeAt: null, timeOpen: false, saveStatus: this.persistBoard(board), sourceDraft: null, parseError: null, drag: null, editingTaskId: null, now: Date.now() });
3463
+ }
3464
+ fileName() { return (this.state.board.title.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'board') + '.md'; }
3465
+ download() { return this.downloadText(this.fileName(), serializeBoard(this.state.board), 'text/markdown;charset=utf-8'); }
3466
+ downloadBadge() { return this.downloadText(this.fileName().replace(/\.md$/, '-badge.svg'), badgeSvg(this.state.board), 'image/svg+xml'); }
3467
+ copyBadge() {
3468
+ const done = (msg) => this.notify(msg);
3469
+ if (navigator.clipboard === undefined) { done('Clipboard blocked: download the badge instead'); return; }
3470
+ navigator.clipboard.writeText(badgeSvg(this.state.board)).then(() => done('Badge SVG copied'), () => done('Clipboard blocked: download the badge instead'));
3471
+ }
3472
+ /** The card as the browser sees it: linked to this page on the ?src board, if there is one. */
3473
+ card() {
3474
+ const source = this.src === null ? { label: this.fileName() } : { label: this.src, url: boardLink(location.href.split(/[?#]/)[0], new URL(this.src, location.href).href) };
3475
+ return boardCard(this.state.board, new Date().toLocaleDateString('en-CA'), source);
3476
+ }
3477
+ downloadCard() { return this.downloadText('card.json', JSON.stringify(this.card(), null, 2) + '\n', 'application/json'); }
3478
+ copyCard() {
3479
+ const done = (msg) => this.notify(msg);
3480
+ if (navigator.clipboard === undefined) { done('Clipboard blocked: download card.json instead'); return; }
3481
+ navigator.clipboard.writeText(JSON.stringify(this.card(), null, 2)).then(() => done('card.json copied'), () => done('Clipboard blocked: download card.json instead'));
3482
+ }
3483
+ /** Shows a file action's result (saved, copied, downloaded) as a toast for a moment; it stays in the status line. */
3484
+ notify(msg) {
3485
+ window.clearTimeout(this.toastTimer);
3486
+ this.toastTimer = window.setTimeout(() => this.setState({ toast: null }), TOAST_MS);
3487
+ this.setState({ saveStatus: msg, toast: msg });
3488
+ }
3489
+ downloadText(name, text, type) {
3490
+ const a = document.createElement('a');
3491
+ a.href = URL.createObjectURL(new Blob([text], { type }));
3492
+ a.download = name;
3493
+ document.body.appendChild(a);
3494
+ a.click();
3495
+ a.remove();
3496
+ window.setTimeout(() => URL.revokeObjectURL(a.href), 0);
3497
+ return name;
3498
+ }
3499
+ /** A link with the whole board compressed into it (plus the current view and filters); copied, or shown to copy if the clipboard is blocked. */
3500
+ async shareLink() {
3501
+ const u = new URL(location.href);
3502
+ u.search = Component.toQuery(this.state, null, location.search);
3503
+ u.hash = SHARE_PREFIX + await encodeShare(serializeBoard(this.state.board));
3504
+ return u.href;
3505
+ }
3506
+ /**
3507
+ * Safari only lets a click write to the clipboard straight away, and the link is made asynchronously, so the
3508
+ * clipboard is handed a ClipboardItem holding the pending link. Without one, writeText; if both fail, a prompt shows it.
3509
+ */
3510
+ copyLink() {
3511
+ const link = this.shareLink();
3512
+ // ponytail: fixed threshold; some chat apps and older browsers cut links past ~2000 characters
3513
+ const report = (l, how) => this.notify(`Link ${how}${l.length > SHARE_WARN_LENGTH ? ` (${l.length} characters: some apps cut long links, so share the .md if it breaks)` : ''}`);
3514
+ const failed = (err) => this.setState({ opError: `Couldn't make a link: ${err.message}` });
3515
+ const shown = () => link.then((l) => { window.prompt('Copy this link to share the board:', l); report(l, 'shown'); }, failed);
3516
+ const clip = navigator.clipboard;
3517
+ const write = clip === undefined ? Promise.reject(new Error('no clipboard'))
3518
+ : typeof ClipboardItem === 'function' && typeof clip.write === 'function'
3519
+ ? clip.write([new ClipboardItem({ 'text/plain': link.then((l) => new Blob([l], { type: 'text/plain' })) })])
3520
+ : link.then((l) => clip.writeText(l));
3521
+ write.then(() => link.then((l) => report(l, 'copied')), shown);
3522
+ }
3523
+ /** On the agile CLI or make dev, writes the ?src file back. Otherwise writes the board to a file picked once, then the same file on each save (Chrome, Edge). Elsewhere, downloads it. */
3524
+ async save() {
3525
+ if (this.writable !== null) {
3526
+ const url = this.writable;
3527
+ try {
3528
+ const res = await fetch(url, { method: 'PUT', headers: { 'content-type': 'text/markdown; charset=utf-8' }, body: serializeBoard(this.state.board) });
3529
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
3530
+ this.notify(`${url.split('/').pop()} saved`);
3531
+ } catch (err) { this.setState({ opError: `Couldn't save to ${url}: ${err.message}` }); }
3532
+ return;
3533
+ }
3534
+ if (typeof window.showSaveFilePicker !== 'function') { this.notify(`Downloaded ${this.download()}`); return; }
3535
+ try {
3536
+ if (this.fileHandle === null) {
3537
+ this.fileHandle = await window.showSaveFilePicker({ suggestedName: this.fileName(), types: [{ description: 'Markdown', accept: { 'text/markdown': ['.md'] } }] });
3538
+ }
3539
+ const w = await this.fileHandle.createWritable();
3540
+ await w.write(serializeBoard(this.state.board));
3541
+ await w.close();
3542
+ this.notify(`${this.fileHandle.name} saved`);
3543
+ } catch (err) {
3544
+ if (err.name !== 'AbortError') this.setState({ opError: `Couldn't save: ${err.message}` });
3545
+ }
3546
+ }
3547
+
3548
+ openTask(id) { this.setState({ editingTaskId: id, descTab: 'preview', tagInput: '', drafts: {}, fieldErrors: {}, pickerOpen: false, historyOpen: false }); }
3549
+
3550
+ /* ---- description editor (toolbar, shortcuts, list continuation) ---- */
3551
+ setDescription(taskId, res) {
3552
+ this.editField(`task.${taskId}.description`, res.text, (b) => updateTask(b, taskId, { description: res.text }), () => {
3553
+ const el = document.querySelector(`[data-kb-desc="${this.uid}"]`);
3554
+ if (el === null) return; // the panel was closed before the update landed
3555
+ el.focus();
3556
+ el.setSelectionRange(res.start, res.end);
3557
+ });
3558
+ }
3559
+ formatDescription(taskId, kind) {
3560
+ const el = document.querySelector(`[data-kb-desc="${this.uid}"]`);
3561
+ if (el === null) bug('format button pressed with no description editor on screen');
3562
+ this.setDescription(taskId, applyFormat(el.value, el.selectionStart, el.selectionEnd, kind));
3563
+ }
3564
+ handleDescriptionKey(e, taskId) {
3565
+ const el = e.target;
3566
+ const key = e.key.toLowerCase();
3567
+ if ((e.metaKey || e.ctrlKey) && !e.altKey) {
3568
+ const kind = e.shiftKey ? (key === 'x' ? 'strike' : null) : ({ b: 'bold', i: 'italic', e: 'code', k: 'link' })[key] ?? null;
3569
+ if (kind === null) return;
3570
+ e.preventDefault();
3571
+ this.setDescription(taskId, applyFormat(el.value, el.selectionStart, el.selectionEnd, kind));
3572
+ return;
3573
+ }
3574
+ if (e.key === 'Enter' && !e.shiftKey && !e.altKey) {
3575
+ const res = continueList(el.value, el.selectionStart, el.selectionEnd);
3576
+ if (res === null) return;
3577
+ e.preventDefault();
3578
+ this.setDescription(taskId, res);
3579
+ }
3580
+ }
3581
+ endField(key) {
3582
+ this.lastEditKey = null;
3583
+ const drafts = { ...this.state.drafts };
3584
+ const fieldErrors = { ...this.state.fieldErrors };
3585
+ delete drafts[key];
3586
+ delete fieldErrors[key];
3587
+ this.setState({ drafts, fieldErrors });
3588
+ }
3589
+
3590
+ /* ---- pointer drag (tasks and columns) ---- */
3591
+ beginDrag(e, kind, id, el) {
3592
+ if (e.button !== 0) return;
3593
+ if (this.state.parseError !== null) return;
3594
+ const geo = this.geometry();
3595
+ const p = { x: (e.clientX - geo.left) / geo.scale, y: (e.clientY - geo.top) / geo.scale };
3596
+ const r = geo.local(el.getBoundingClientRect());
3597
+ this.setState({ drag: { kind, id, pointerId: e.pointerId, startX: p.x, startY: p.y, x: p.x, y: p.y, offX: p.x - r.x, offY: p.y - r.y, w: r.w, h: r.h, active: false, target: null } });
3598
+ }
3599
+ handlePointerMove(e) {
3600
+ const d = this.state.drag;
3601
+ if (d === null || e.pointerId !== d.pointerId) return;
3602
+ const geo = this.geometry();
3603
+ const x = (e.clientX - geo.left) / geo.scale;
3604
+ const y = (e.clientY - geo.top) / geo.scale;
3605
+ const active = d.active || Math.hypot(x - d.startX, y - d.startY) > 5;
3606
+ if (!active) return;
3607
+ const target = d.kind === 'task' ? this.taskTarget(geo, x, y) : this.columnTarget(geo, x);
3608
+ this.setState({ drag: { ...d, x, y, active, target } });
3609
+ }
3610
+ taskTarget(geo, x, y) {
3611
+ const cols = Array.from(geo.root.querySelectorAll('[data-col-drop]')).map((el) => ({ id: el.getAttribute('data-col-drop'), el, r: geo.local(el.getBoundingClientRect()) }));
3612
+ if (cols.length === 0) return null;
3613
+ const best = cols.reduce((a, c) => {
3614
+ const dist = x < c.r.x ? c.r.x - x : x > c.r.x + c.r.w ? x - (c.r.x + c.r.w) : 0;
3615
+ return dist < a.dist ? { c, dist } : a;
3616
+ }, { c: null, dist: Infinity }).c;
3617
+ const cards = Array.from(best.el.querySelectorAll('[data-card-slot]')).map((el) => ({ id: el.getAttribute('data-card-slot'), r: geo.local(el.getBoundingClientRect()) }));
3618
+ const before = cards.find((c) => y < c.r.y + c.r.h / 2);
3619
+ return { colId: best.id, beforeId: before === undefined ? null : before.id };
3620
+ }
3621
+ columnTarget(geo, x) {
3622
+ const cols = Array.from(geo.root.querySelectorAll('[data-col-drop]')).map((el) => ({ id: el.getAttribute('data-col-drop'), r: geo.local(el.getBoundingClientRect()) }));
3623
+ const before = cols.find((c) => x < c.r.x + c.r.w / 2);
3624
+ return { beforeId: before === undefined ? null : before.id };
3625
+ }
3626
+ handlePointerUp(e) {
3627
+ const d = this.state.drag;
3628
+ if (d === null || e.pointerId !== d.pointerId) return;
3629
+ if (!d.active || d.target === null) { this.setState({ drag: null }); return; }
3630
+ this.suppressClick = true;
3631
+ window.setTimeout(() => { this.suppressClick = false; }, 0);
3632
+ const at = this.nowIso();
3633
+ if (d.kind === 'task') {
3634
+ this.commit((b) => moveTask(b, d.id, d.target.colId, d.target.beforeId, at), { drag: null });
3635
+ }
3636
+ else if (d.kind === 'column') this.commit((b) => moveColumn(b, d.id, d.target.beforeId), { drag: null });
3637
+ else bug(`drag kind "${d.kind}"`);
3638
+ }
3639
+
3640
+ /** Scroll a board card into view, focus it and flash it (the dotted stand-ins link here). */
3641
+ focusCard(id) {
3642
+ const el = this.rootEl()?.querySelector(`[data-card-slot="${id}"]`) ?? null;
3643
+ if (el === null) return;
3644
+ el.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
3645
+ el.querySelector('.kb-card-title')?.focus({ preventScroll: true });
3646
+ this.setState({ fresh: { id, cls: 'kb-card-flash' } });
3647
+ window.setTimeout(() => { if (this.state.fresh !== null && this.state.fresh.id === id) this.setState({ fresh: null }); }, 1200);
3648
+ }
3649
+
3650
+ /** New task (a child when `parent` is set) in `colId`, then open it with its title selected. */
3651
+ createTask(colId, parent) {
3652
+ const at = this.nowIso();
3653
+ const kind = this.pickEffect('create');
3654
+ let created = null;
3655
+ const ok = this.commit((b) => { created = addTask(b, colId, parent === '' ? 'New task' : 'New child task', at, parent); return created.board; });
3656
+ if (!ok) return;
3657
+ const id = created.id;
3658
+ this.setState({ editingTaskId: id, descTab: 'preview', drafts: {}, fieldErrors: {}, tagInput: '', pickerOpen: false, historyOpen: false, fresh: kind === null ? null : { id, cls: ENTRY_CLASS[kind] } }, () => {
3659
+ // Focus the title with its placeholder text selected, so typing replaces it (next frame: the panel has rendered by then).
3660
+ window.requestAnimationFrame(() => {
3661
+ const input = document.querySelector(`[data-kb-title="${this.uid}"]`);
3662
+ if (input !== null) { input.focus(); input.select(); }
3663
+ });
3664
+ // A filter can hide the new card; then there is nothing on screen to animate and only the panel opens.
3665
+ const rect = this.cardRect(id);
3666
+ if (rect !== null) this.playEffect(kind, rect);
3667
+ window.setTimeout(() => { if (this.state.fresh !== null && this.state.fresh.id === id) this.setState({ fresh: null }); }, 1000);
3668
+ });
3669
+ }
3670
+
3671
+ /* ---- render ---- */
3672
+ renderVals() {
3673
+ const s = this.state;
3674
+ const theme = this.shownTheme();
3675
+ const settings = s.board.settings.themes[theme.id];
3676
+ const board = s.timeAt === null ? s.board : boardAt(s.board, s.timeAt); // the past is shown read-only
3677
+ const filter = { query: s.query, tags: s.tagFilter, owners: s.ownerFilter };
3678
+ const drag = s.drag !== null && s.drag.active ? s.drag : null;
3679
+
3680
+ const everyTask = allTasks(board);
3681
+ const allTags = [...new Set(everyTask.flatMap((t) => t.tags))].sort((a, b) => a.localeCompare(b));
3682
+ const allOwners = [...new Set(everyTask.map((t) => t.owner))].sort((a, b) => (a === '' ? 1 : b === '' ? -1 : a.localeCompare(b)));
3683
+ const tagStyle = (tag) => `background: oklch(var(--tag-l) var(--tag-c) ${hueOf(tag)}); color: var(--tag-fg)`;
3684
+ const tagPills = (tags) => tags.map((t) => ({ label: t, style: tagStyle(t) }));
3685
+ const cardView = (t, interactive) => ({
3686
+ id: t.id, title: t.title, hasDescription: t.description !== '',
3687
+ descClass: t.description.split('\n').length > 5 || t.description.length > 220 ? 'kb-card-desc md kb-desc-long' : 'kb-card-desc md',
3688
+ desc: t.description === '' ? [] : markdownView(t.description, {
3689
+ links: false,
3690
+ onToggle: interactive
3691
+ ? (line) => this.commit((b) => updateTask(b, t.id, { description: toggleCheckLine(findTask(b, t.id).task.description, line) }))
3692
+ : (line) => bug(`checkbox clicked on a drag preview (line ${line})`),
3693
+ }),
3694
+ owner: t.owner, hasOwner: t.owner !== '', initials: initialsOf(t.owner), avatarStyle: tagStyle(t.owner),
3695
+ tags: tagPills(t.tags), hasFoot: t.owner !== '' || t.tags.length > 0,
3696
+ });
3697
+
3698
+ const filterActive = s.query.trim() !== '' || s.tagFilter.length > 0 || s.ownerFilter.length > 0;
3699
+ const placeholder = (w, h) => ({ isPlaceholder: true, isTask: false, isAway: false, isColumn: false, phStyle: `height: ${Math.round(h)}px; min-height: ${Math.round(h)}px` + (w === null ? '' : `; width: ${Math.round(w)}px`) });
3700
+
3701
+ // Every task above the open one, so its whole chain of parents lights up.
3702
+ const ancestors = new Set();
3703
+ for (let p = everyTask.find((t) => t.id === s.editingTaskId)?.parent ?? ''; p !== ''; p = everyTask.find((t) => t.id === p).parent) ancestors.add(p);
3704
+ const columnViews = board.columns.flatMap((col) => {
3705
+ if (drag !== null && drag.kind === 'column' && drag.id === col.id) return [];
3706
+ const visible = col.tasks.filter((t) => taskMatches(t, filter));
3707
+ const shown = visible.filter((t) => !(drag !== null && drag.kind === 'task' && drag.id === t.id));
3708
+ // Each task, then its children: the ones in this column, then dotted stand-ins for ones moved to another column.
3709
+ const here = new Set(shown.map((t) => t.id));
3710
+ const elsewhere = board.columns.filter((c) => c.id !== col.id).flatMap((c) => c.tasks.map((t) => ({ t, colName: c.name })))
3711
+ .filter(({ t }) => !(drag !== null && drag.kind === 'task' && drag.id === t.id) && taskMatches(t, filter));
3712
+ const rows = [];
3713
+ const walk = (t, depth) => {
3714
+ const kids = shown.filter((k) => k.parent === t.id);
3715
+ const away = elsewhere.filter((e) => e.t.parent === t.id);
3716
+ const folded = s.collapsed.includes(t.id);
3717
+ rows.push({ task: t, depth, kidCount: kids.length + away.length, folded });
3718
+ if (folded) return;
3719
+ for (const k of kids) walk(k, depth + 1);
3720
+ for (const e of away) rows.push({ task: e.t, depth: depth + 1, awayIn: e.colName });
3721
+ };
3722
+ for (const t of shown) if (!here.has(t.parent)) walk(t, 0);
3723
+ // A row's line carries on past it when a sibling (same depth) follows before anything shallower.
3724
+ const carries = rows.map((r, i) => { for (const n of rows.slice(i + 1)) { if (n.depth <= r.depth) return n.depth === r.depth; } return false; });
3725
+ const ancestorCarries = []; // [depth] = whether the latest row at that depth has a sibling still to come
3726
+ const items = rows.map(({ task: t, depth, kidCount, folded, awayIn }, i) => {
3727
+ ancestorCarries.length = depth;
3728
+ // One vertical line per level: passing through for open ancestors, ├ / └ into this card at its own level.
3729
+ const rails = [];
3730
+ for (let k = 1; k <= depth; k++) {
3731
+ const kind = k < depth ? (ancestorCarries[k] ? 'pass' : null) : (carries[i] ? 'tee' : 'end');
3732
+ if (kind !== null) rails.push({ cls: `kb-rail kb-rail-${kind}`, style: `left: ${(k - 1 - depth) * INDENT + INDENT / 2 - 1}px` });
3733
+ }
3734
+ ancestorCarries[depth] = carries[i];
3735
+ const indentStyle = depth === 0 ? '' : `margin-left: ${depth * INDENT}px`;
3736
+ if (awayIn !== undefined) {
3737
+ return {
3738
+ id: `away:${t.id}`, isPlaceholder: false, isTask: false, isAway: true, rails, indentStyle,
3739
+ title: t.title, awayIn: `→ ${awayIn}`, focusLabel: `Go to ${t.title} in ${awayIn}`,
3740
+ focus: () => this.focusCard(t.id),
3741
+ };
3742
+ }
3743
+ const parent = depth === 0 && t.parent !== '' ? everyTask.find((p) => p.id === t.parent) : undefined;
3744
+ return {
3745
+ ...cardView(t, true), isPlaceholder: false, isTask: true, isAway: false, obstacleId: `card:${t.id}`,
3746
+ indentStyle, rails,
3747
+ hasKids: kidCount > 0, expanded: !folded,
3748
+ foldText: folded ? String(kidCount) : '',
3749
+ foldLabel: `${folded ? 'Show' : 'Hide'} ${kidCount} child task${kidCount === 1 ? '' : 's'} of ${t.title}`,
3750
+ toggleFold: () => { if (!this.suppressClick) this.setState({ collapsed: folded ? s.collapsed.filter((id) => id !== t.id) : [...s.collapsed, t.id] }); },
3751
+ // A child away from its parent (another column, the archive, filtered out) still names it.
3752
+ hasParentHint: parent !== undefined, parentHint: parent === undefined ? '' : `↳ ${parent.title}`,
3753
+ openParent: () => { if (!this.suppressClick) this.openTask(t.parent); },
3754
+ addChildLabel: `Add child task to ${t.title}`,
3755
+ onAddChild: () => { if (!this.suppressClick) this.createTask(col.id, t.id); },
3756
+ cardClass: ['kb-card', ...(kidCount > 0 ? ['kb-card-haskids'] : []), ...(s.fresh !== null && s.fresh.id === t.id ? [s.fresh.cls] : []), ...(ancestors.has(t.id) ? ['kb-card-ancestor'] : [])].join(' '),
3757
+ onPointerDown: (e) => {
3758
+ if (e.target instanceof Element && e.target.closest('input,textarea,select') !== null) return;
3759
+ this.beginDrag(e, 'task', t.id, e.currentTarget);
3760
+ },
3761
+ open: () => { if (!this.suppressClick) this.openTask(t.id); },
3762
+ };
3763
+ });
3764
+ if (drag !== null && drag.kind === 'task' && drag.target !== null && drag.target.colId === col.id) {
3765
+ const idx = drag.target.beforeId === null ? items.length : items.findIndex((it) => it.id === drag.target.beforeId);
3766
+ items.splice(idx < 0 ? items.length : idx, 0, placeholder(null, drag.h));
3767
+ }
3768
+ const nameKey = `col.${col.id}.name`;
3769
+ const hidden = col.tasks.length - visible.length;
3770
+ const view = {
3771
+ isPlaceholder: false, isColumn: true, id: col.id,
3772
+ nameValue: nameKey in s.drafts ? s.drafts[nameKey] : col.name,
3773
+ nameRef: `${this.uid}.${col.id}`,
3774
+ nameError: s.fieldErrors[nameKey] ?? null,
3775
+ countLabel: hidden > 0 ? `${visible.length}/${col.tasks.length}` : String(col.tasks.length),
3776
+ gripLabel: `Drag column ${col.name}`,
3777
+ deleteLabel: `Delete column ${col.name}`,
3778
+ deleteDisabled: col.tasks.length > 0,
3779
+ deleteTitle: col.tasks.length > 0 ? 'Move or delete its tasks first' : `Delete ${col.name}`,
3780
+ items,
3781
+ showEmpty: items.length === 0,
3782
+ emptyLabel: col.tasks.length === 0 ? 'No tasks' : 'No tasks match the filters',
3783
+ onGrip: (e) => { e.preventDefault(); this.beginDrag(e, 'column', col.id, e.currentTarget.closest('[data-col-drop]')); },
3784
+ onName: (e) => { const raw = e.target.value; this.editField(nameKey, raw, (b) => renameColumn(b, col.id, raw.trim())); },
3785
+ onNameBlur: () => this.endField(nameKey),
3786
+ onDelete: () => this.commit((b) => deleteColumn(b, col.id)),
3787
+ onAddTask: () => this.createTask(col.id, ''),
3788
+ };
3789
+ return [view];
3790
+ });
3791
+ if (drag !== null && drag.kind === 'column' && drag.target !== null) {
3792
+ const idx = drag.target.beforeId === null ? columnViews.length : columnViews.findIndex((c) => c.id === drag.target.beforeId);
3793
+ columnViews.splice(idx < 0 ? columnViews.length : idx, 0, placeholder(drag.w, drag.h));
3794
+ }
3795
+
3796
+ let ghost = { isTask: false, isColumn: false };
3797
+ if (drag !== null && drag.kind === 'task') {
3798
+ const { task } = findTask(board, drag.id);
3799
+ ghost = { ...cardView(task, false), isTask: true, isColumn: false, obstacleId: `drag:${task.id}` };
3800
+ } else if (drag !== null && drag.kind === 'column') {
3801
+ const col = findColumn(board, drag.id);
3802
+ ghost = { isTask: false, isColumn: true, name: col.name, countLabel: String(col.tasks.length), obstacleId: `drag:${col.id}` };
3803
+ }
3804
+
3805
+ // c is the task's column, or null while it sits in the archive.
3806
+ const editingTask = s.editingTaskId === null || !everyTask.some((t) => t.id === s.editingTaskId) ? null : (({ task, col }) => ({ t: task, c: col }))(findTask(board, s.editingTaskId));
3807
+ let editor = null;
3808
+ if (editingTask !== null) {
3809
+ const { t, c } = editingTask;
3810
+ const summary = historySummary(t, s.now);
3811
+ const k = (f) => `task.${t.id}.${f}`;
3812
+ const field = (f) => (k(f) in s.drafts ? s.drafts[k(f)] : t[f]);
3813
+ const descText = field('description');
3814
+ editor = {
3815
+ isWrite: s.descTab === 'write',
3816
+ isPreview: s.descTab === 'preview',
3817
+ showWrite: () => this.setState({ descTab: 'write' }),
3818
+ showPreview: () => this.setState({ descTab: 'preview' }),
3819
+ editFromPreview: (e) => {
3820
+ if (e.target.closest('a') !== null) return; // let links open
3821
+ this.setState({ descTab: 'write' }, () => document.querySelector(`[data-kb-desc="${this.uid}"]`)?.focus());
3822
+ },
3823
+ formatButtons: FORMAT_BUTTONS.map((fb) => ({
3824
+ label: fb.label, d: fb.d,
3825
+ title: fb.keys === '' ? fb.label : `${fb.label} (${fb.keys})`,
3826
+ cls: fb.sep === true ? 'kb-fmt kb-fmt-sep' : 'kb-fmt',
3827
+ keepFocus: (e) => e.preventDefault(),
3828
+ apply: () => this.formatDescription(t.id, fb.kind),
3829
+ })),
3830
+ onDescriptionKey: (e) => this.handleDescriptionKey(e, t.id),
3831
+ preview: markdownView(descText, {
3832
+ links: true,
3833
+ onToggle: (line) => { const next = toggleCheckLine(descText, line); this.editField(k('description'), next, (b) => updateTask(b, t.id, { description: next })); },
3834
+ }),
3835
+ previewEmpty: descText.trim() === '',
3836
+ id: t.id, columnName: c === null ? 'Archive' : c.name,
3837
+ title: field('title'), owner: field('owner'), description: field('description'),
3838
+ titleError: s.fieldErrors[k('title')] ?? null, ownerError: s.fieldErrors[k('owner')] ?? null, descriptionError: s.fieldErrors[k('description')] ?? null,
3839
+ onTitle: (e) => { const raw = e.target.value; this.editField(k('title'), raw, (b) => updateTask(b, t.id, { title: raw.trim() })); },
3840
+ // Owner is a draft while typing and is committed once (blur or Enter), so each handover is one history entry.
3841
+ onOwner: (e) => {
3842
+ const raw = e.target.value;
3843
+ let error = null;
3844
+ try { check(OwnerName, normalizeOwner(raw), 'owner'); } catch (err) { error = err.message.replace(/^owner: /, ''); }
3845
+ const fieldErrors = { ...this.state.fieldErrors };
3846
+ if (error === null) delete fieldErrors[k('owner')]; else fieldErrors[k('owner')] = error;
3847
+ this.setState({ drafts: { ...this.state.drafts, [k('owner')]: raw }, fieldErrors });
3848
+ },
3849
+ onOwnerKey: (e) => { if (e.key === 'Enter') { e.preventDefault(); e.target.blur(); } },
3850
+ onDescription: (e) => { const raw = e.target.value; this.editField(k('description'), raw, (b) => updateTask(b, t.id, { description: raw })); },
3851
+ onBlurTitle: () => this.endField(k('title')),
3852
+ // Enter closes the drawer, once the title is valid (an invalid one stays open with its error).
3853
+ onTitleKey: (e) => {
3854
+ if (e.key !== 'Enter') return;
3855
+ e.preventDefault();
3856
+ if (!(k('title') in this.state.fieldErrors)) this.setState({ editingTaskId: null, drafts: {}, fieldErrors: {}, tagInput: '' });
3857
+ },
3858
+ onBlurOwner: () => {
3859
+ const key = k('owner');
3860
+ const raw = this.state.drafts[key];
3861
+ if (raw !== undefined && this.state.fieldErrors[key] === undefined) {
3862
+ const at = this.nowIso();
3863
+ this.commit((b) => reassignTask(b, t.id, normalizeOwner(raw), at));
3864
+ }
3865
+ this.endField(key);
3866
+ },
3867
+ onBlurDescription: () => this.endField(k('description')),
3868
+ tags: t.tags.map((tag) => ({
3869
+ label: tag, style: tagStyle(tag), removeLabel: `Remove tag ${tag}`,
3870
+ remove: () => this.commit((b) => updateTask(b, t.id, { tags: t.tags.filter((x) => x !== tag) })),
3871
+ })),
3872
+ history: historyView(t, s.now),
3873
+ onDelete: (e) => {
3874
+ const kind = this.pickEffect('delete');
3875
+ // Burst where the card was; the button stands in when the card isn't on screen (filtered out, markdown view).
3876
+ const rect = this.cardRect(t.id) ?? this.elRect(e.currentTarget);
3877
+ if (this.commit((b) => deleteTask(b, t.id), { editingTaskId: null, completeDialogFor: null })) this.playEffect(kind, rect);
3878
+ },
3879
+ // Keyed to the task so the dialog never reappears for another task.
3880
+ completeDialogOpen: s.completeDialogFor === t.id,
3881
+ completeDialogTitle: `Finish "${t.title}"`,
3882
+ openCompleteDialog: () => this.setState({ completeDialogFor: t.id }, () => window.requestAnimationFrame(() => {
3883
+ // Focus inside the dialog so Escape reaches it; the first enabled choice.
3884
+ const done = document.querySelector(`[data-kb-complete="${this.uid}"]`);
3885
+ if (done !== null) (done.disabled ? done.nextElementSibling : done).focus();
3886
+ })),
3887
+ closeCompleteDialog: () => this.setState({ completeDialogFor: null }),
3888
+ completeDialogBackdrop: (e) => { if (e.target === e.currentTarget) this.setState({ completeDialogFor: null }); },
3889
+ completeDialogKey: (e) => { if (e.key === 'Escape') { e.stopPropagation(); this.setState({ completeDialogFor: null }); } },
3890
+ completeDisabled: c === null,
3891
+ addChildTitle: c === null ? 'Restore it first' : 'A new task under this one, in the same column',
3892
+ onAddChild: () => { if (c !== null) this.createTask(c.id, t.id); },
3893
+ completeLabel: c === null ? 'Archived' : 'Mark complete',
3894
+ completeTitle: c === null ? 'Already in the archive' : 'Moves it to the archive (see the Archive view)',
3895
+ historyOpen: s.historyOpen,
3896
+ toggleHistory: () => this.setState({ historyOpen: !s.historyOpen }),
3897
+ summary,
3898
+ onComplete: (e) => {
3899
+ const kind = this.pickEffect('complete');
3900
+ // The card leaves the board, so celebrate where it was (or at the button when it isn't on screen).
3901
+ const rect = this.cardRect(t.id) ?? this.elRect(e.currentTarget);
3902
+ const at = this.nowIso();
3903
+ if (this.commit((b) => archiveTask(b, t.id, at), { editingTaskId: null, completeDialogFor: null })) this.playEffect(kind, rect);
3904
+ },
3905
+ };
3906
+ }
3907
+ const archivedViews = [...board.archive].reverse().filter((t) => taskMatches(t, filter)).map((t) => {
3908
+ const lastPlace = [...t.history].reverse().find((h) => h.column !== 'Archive');
3909
+ const prevCol = lastPlace === undefined ? undefined : board.columns.find((c) => c.name === lastPlace.column);
3910
+ const chosen = s.restoreTargets[t.id];
3911
+ // Preselect the chosen column, else the column it was archived from, else the first one.
3912
+ const target = chosen !== undefined && board.columns.some((c) => c.id === chosen) ? chosen : (prevCol ?? board.columns[0] ?? { id: '' }).id;
3913
+ const archivedAt = [...t.history].reverse().find((h) => h.column === 'Archive') ?? bug(`archived task ${t.id} has no Archive entry`);
3914
+ return {
3915
+ ...cardView(t, true),
3916
+ completedAgo: `Completed ${formatDuration(s.now - Date.parse(archivedAt.at))} ago`,
3917
+ restoreTo: target,
3918
+ restoreOptions: board.columns.map((c) => ({ value: c.id, label: c.name })),
3919
+ restoreDisabled: board.columns.length === 0,
3920
+ restoreLabel: `Column to restore ${t.title} to`,
3921
+ onRestoreTo: (e) => this.setState({ restoreTargets: { ...this.state.restoreTargets, [t.id]: e.target.value } }),
3922
+ restore: () => { const at = this.nowIso(); this.commit((b) => restoreTask(b, t.id, target, at)); },
3923
+ open: () => this.openTask(t.id),
3924
+ };
3925
+ });
3926
+
3927
+ const addTags = (raw) => {
3928
+ if (editingTask === null) bug('adding a tag with no task open');
3929
+ const t = editingTask.t;
3930
+ const fresh = raw.split(',').map((x) => x.trim()).filter((x) => x !== '' && !t.tags.includes(x));
3931
+ if (fresh.length === 0) { this.setState({ tagInput: '' }); return; }
3932
+ if (this.commit((b) => updateTask(b, t.id, { tags: [...t.tags, ...new Set(fresh)] }))) this.setState({ tagInput: '' });
3933
+ };
3934
+
3935
+ const controls = Object.entries(theme.settings).map(([key, def]) => {
3936
+ const value = settings[key];
3937
+ const apply = (raw) => this.commit((b) => setThemeSetting(b, theme.id, key, raw));
3938
+ return {
3939
+ label: def.label,
3940
+ isRange: def.type === 'range', isColor: def.type === 'color', isSelect: def.type === 'select', isBoolean: def.type === 'boolean',
3941
+ min: def.min, max: def.max, step: def.step,
3942
+ value: def.type === 'boolean' ? '' : String(value), checked: def.type === 'boolean' ? value : false,
3943
+ options: def.type === 'select' ? def.options.map((o) => ({ value: o, label: o[0].toUpperCase() + o.slice(1) })) : [],
3944
+ valueLabel: def.type === 'range' ? `${Number(value.toFixed(3))}${def.unit ?? ''}` : def.type === 'color' ? value : '',
3945
+ onChange: (e) => apply(def.type === 'boolean' ? e.target.checked : e.target.value),
3946
+ };
3947
+ });
3948
+
3949
+ const toggleIn = (list, v) => (list.includes(v) ? list.filter((x) => x !== v) : [...list, v]);
3950
+ const sourceText = s.sourceDraft !== null ? s.sourceDraft : serializeBoard(board);
3951
+ const bodyVars = { ...BASE_VARS, ...theme.vars(settings) };
3952
+
3953
+ return {
3954
+ uid: this.uid,
3955
+ themeId: theme.id,
3956
+ themeName: theme.name,
3957
+ rootStyle: toStyle(bodyVars),
3958
+ rootClass: (drag !== null ? 'kb kb-dragging' : 'kb') + (s.timeAt !== null ? ' kb-past' : ''),
3959
+ canvasClass: theme.effect === null ? 'kb-fx kb-fx-off' : 'kb-fx',
3960
+ mainClass: `kb-main kb-mode-${s.mode}`,
3961
+ boardClass: s.parseError !== null ? 'kb-board kb-locked' : 'kb-board',
3962
+ ownerListId: `${this.uid}-owners`,
3963
+ tagListId: `${this.uid}-tags`,
3964
+
3965
+ titleValue: 'board.title' in s.drafts ? s.drafts['board.title'] : board.title,
3966
+ onTitle: (e) => { const raw = e.target.value; this.editField('board.title', raw, (b) => setBoardTitle(b, raw.trim())); },
3967
+ onTitleBlur: () => this.endField('board.title'),
3968
+
3969
+ query: s.query,
3970
+ onQuery: (e) => this.setState({ query: e.target.value }),
3971
+ filterOpen: s.filterOpen,
3972
+ toggleFilter: () => this.setState({ filterOpen: !s.filterOpen }),
3973
+ hasActiveFilters: filterActive,
3974
+ activeFilterCount: s.tagFilter.length + s.ownerFilter.length + (s.query.trim() !== '' ? 1 : 0),
3975
+ tagOptions: allTags.map((tag) => ({ label: tag, style: tagStyle(tag), pressed: s.tagFilter.includes(tag), toggle: () => this.setState({ tagFilter: toggleIn(s.tagFilter, tag) }) })),
3976
+ noTags: allTags.length === 0,
3977
+ ownerOptions: allOwners.map((o) => ({ label: o === '' ? 'Unassigned' : o, pressed: s.ownerFilter.includes(o), toggle: () => this.setState({ ownerFilter: toggleIn(s.ownerFilter, o) }) })),
3978
+ clearFilters: () => this.setState({ query: '', tagFilter: [], ownerFilter: [] }),
3979
+
3980
+ modes: MODES.map((m) => ({ label: m.label, pressed: s.mode === m.id, pick: () => this.setState({ mode: m.id }) })),
3981
+ showBoard: s.mode === 'board' || s.mode === 'split',
3982
+ showSource: s.mode === 'split' || s.mode === 'source',
3983
+ showArchive: s.mode === 'archive',
3984
+ archived: archivedViews,
3985
+ archiveEmpty: archivedViews.length === 0,
3986
+ archiveEmptyLabel: board.archive.length === 0 ? 'Nothing archived yet. "Mark complete" on a task sends it here.' : 'No archived tasks match the filters',
3987
+ archiveCountLabel: board.archive.length === 1 ? '1 task' : `${board.archive.length} tasks`,
3988
+
3989
+ columns: columnViews,
3990
+ addColumn: () => {
3991
+ let id = null;
3992
+ // Focus the new name with its placeholder text selected, so typing replaces it (next frame: the column has rendered by then).
3993
+ this.commit((b) => { const r = addColumn(b, `Column ${b.columns.length + 1}`); id = r.id; return r.board; }, null, () => window.requestAnimationFrame(() => {
3994
+ const input = document.querySelector(`[data-kb-col="${this.uid}.${id}"]`);
3995
+ if (input !== null) { input.focus(); input.select(); }
3996
+ }));
3997
+ },
3998
+
3999
+ sourceText,
4000
+ saveStatus: s.saveStatus,
4001
+ copyLabel: s.copyLabel,
4002
+ hasParseError: s.parseError !== null,
4003
+ parseError: s.parseError ?? '',
4004
+ onSource: (e) => {
4005
+ if (this.inPast()) return;
4006
+ const text = e.target.value;
4007
+ try {
4008
+ const parsed = parseBoard(text);
4009
+ this.setState({ ...this.undoStep(parsed, 'source'), sourceDraft: text, parseError: null, board: parsed, saveStatus: this.persistBoard(parsed), drag: null });
4010
+ } catch (err) {
4011
+ this.setState({ sourceDraft: text, parseError: err.message });
4012
+ }
4013
+ },
4014
+ onSourceBlur: () => { this.lastEditKey = null; if (this.state.parseError === null) this.setState({ sourceDraft: null }); },
4015
+ copySource: () => {
4016
+ const done = (label) => { this.setState({ copyLabel: label }); window.setTimeout(() => this.setState({ copyLabel: 'Copy' }), 1800); };
4017
+ if (navigator.clipboard === undefined) { done('Clipboard blocked: select the text and copy'); return; }
4018
+ navigator.clipboard.writeText(sourceText).then(() => done('Copied'), () => done('Clipboard blocked: select the text and copy'));
4019
+ },
4020
+
4021
+ pickerOpen: s.pickerOpen,
4022
+ closePicker: () => this.setState({ pickerOpen: false }),
4023
+ pickerKey: (e) => { if (e.key === 'Escape') this.setState({ pickerOpen: false }); },
4024
+ themeOptions: THEMES.map((t) => ({
4025
+ name: t.name, blurb: t.blurb, pressed: t.id === theme.id,
4026
+ swatch: t.swatch(board.settings.themes[t.id]).map((c) => ({ style: `background: ${c}` })),
4027
+ pick: () => {
4028
+ this.fxFailedFor = null;
4029
+ this.commit((b) => setTheme(b, t.id), { effectError: null, themeOverride: null });
4030
+ },
4031
+ })),
4032
+ settingControls: controls,
4033
+ resetTheme: () => this.commit((b) => resetThemeSettings(b, theme.id)),
4034
+ effectControls: Object.entries(EVENT_EFFECTS).map(([event, spec]) => ({
4035
+ label: spec.label,
4036
+ value: board.settings.effects[event],
4037
+ options: effectChoices(event).map((o) => ({ value: o, label: EFFECT_LABELS[o] })),
4038
+ onChange: (e) => { const v = e.target.value; this.commit((b) => setEffect(b, event, v)); },
4039
+ tryLabel: `Try the ${spec.label.toLowerCase()} effect`,
4040
+ tryDisabled: board.settings.effects[event] === 'none',
4041
+ tryIt: () => {
4042
+ const root = this.rootEl();
4043
+ if (root === null) bug('board root missing');
4044
+ const w = root.offsetWidth;
4045
+ const h = root.offsetHeight;
4046
+ this.playEffect(this.pickEffect(event), { x: w / 2 - 140, y: h / 2 - 45, w: 280, h: 90 });
4047
+ },
4048
+ })),
4049
+ storageWarning: s.storageWarning,
4050
+ effectError: s.effectError,
4051
+
4052
+ isDragging: drag !== null,
4053
+ ghostStyle: drag === null ? '' : `left: ${Math.round(drag.x - drag.offX)}px; top: ${Math.round(drag.y - drag.offY)}px; width: ${Math.round(drag.w)}px`,
4054
+ ghost,
4055
+
4056
+ editorOpen: editor !== null,
4057
+ editor: editor ?? {},
4058
+ drawerStyle: `width: ${s.drawerWidth}px`,
4059
+ onDrawerResize: (e) => this.resizeDrawer(e),
4060
+ closeEditor: () => this.setState({ editingTaskId: null, drafts: {}, fieldErrors: {}, tagInput: '' }),
4061
+ ownerNames: allOwners.filter((o) => o !== ''),
4062
+ tagNames: allTags,
4063
+ tagInput: s.tagInput,
4064
+ onTagInput: (e) => {
4065
+ const v = e.target.value;
4066
+ if (v.includes(',')) { addTags(v); return; }
4067
+ this.setState({ tagInput: v });
4068
+ },
4069
+ onTagKey: (e) => {
4070
+ if (e.key === 'Enter') { e.preventDefault(); addTags(e.target.value); return; }
4071
+ if (e.key === 'Backspace' && e.target.value === '' && editingTask !== null && editingTask.t.tags.length > 0) {
4072
+ const t = editingTask.t;
4073
+ this.commit((b) => updateTask(b, t.id, { tags: t.tags.slice(0, -1) }));
4074
+ }
4075
+ },
4076
+
4077
+ opError: s.opError,
4078
+ dismissError: () => this.setState({ opError: null }),
4079
+ timeOpen: s.timeOpen,
4080
+ toggleTime: () => this.setState({ timeOpen: !s.timeOpen, timeAt: null }),
4081
+ time: s.timeOpen && (() => {
4082
+ const ev = historyEvents(s.board);
4083
+ const i = s.timeAt === null ? ev.length : ev.findLastIndex((e) => Date.parse(e.at) <= Date.parse(s.timeAt));
4084
+ const e = ev[i];
4085
+ return {
4086
+ max: ev.length, value: i, atNow: s.timeAt === null,
4087
+ label: e === undefined ? 'Now' : `${new Date(e.at).toLocaleString()} · ${e.title} → ${e.column}${e.owner === '' ? '' : ` (${e.owner})`}`,
4088
+ onChange: (x) => { const k = Number(x.target.value); this.setState({ timeAt: k >= ev.length ? null : ev[k].at }); },
4089
+ now: () => this.setState({ timeAt: null }),
4090
+ };
4091
+ })(),
4092
+ toast: s.opError === null && s.toast, // an error toast takes the spot
4093
+
4094
+ canUndo: s.past.length > 0,
4095
+ canRedo: s.future.length > 0,
4096
+ undoDisabled: s.past.length === 0,
4097
+ redoDisabled: s.future.length === 0,
4098
+ undo: () => this.undo(),
4099
+ redo: () => this.redo(),
4100
+ menuOpen: s.menuOpen,
4101
+ toggleMenu: () => this.setState({ menuOpen: !s.menuOpen }),
4102
+ closeMenu: () => this.setState({ menuOpen: false }),
4103
+ menuKey: (e) => { if (e.key === 'Escape') this.setState({ menuOpen: false }); },
4104
+ badgeSrc: `data:image/svg+xml;charset=utf-8,${encodeURIComponent(badgeSvg(board))}`,
4105
+ badgeAlt: badgeRows(board).filter((r) => r.included).map((r) => `${r.symbol}: ${r.count} ${r.icon}`).join(' | '),
4106
+ openBadge: () => this.setState({ menuOpen: false, badgeOpen: true, pickerOpen: false }),
4107
+ badgeOpen: s.badgeOpen,
4108
+ hideBadge: () => this.setState({ badgeOpen: false }),
4109
+ badgeBackdrop: (e) => { if (e.target === e.currentTarget) this.setState({ badgeOpen: false }); },
4110
+ badgeKey: (e) => { if (e.key === 'Escape') this.setState({ badgeOpen: false }); },
4111
+ downloadBadge: () => this.notify(`Downloaded ${this.downloadBadge()}`),
4112
+ copyBadge: () => this.copyBadge(),
4113
+ downloadCard: () => this.notify(`Downloaded ${this.downloadCard()}`),
4114
+ copyCard: () => this.copyCard(),
4115
+ cardPreview: (() => {
4116
+ if (!s.badgeOpen) return null;
4117
+ const c = this.card();
4118
+ const sum = Object.values(c.report).reduce((a, b) => a + b, 0) || 1;
4119
+ return { title: c.title, subtitle: c.subtitle, pill: c.status.label, big: c.heading.primary, bigLabel: c.heading.label, srcLabel: c.source.label, tone: `kb-card-pill kb-tone-${c.status.tone}`, open: c.source.url ?? false,
4120
+ items: c.legend.map((l) => ({ label: l.label, n: c.report[l.id], dot: `background:${l.color}`, seg: `background:${l.color};flex:${c.report[l.id] / sum} 1 0` })) };
4121
+ })(),
4122
+ resetBadge: () => this.commit(resetBadge, { drafts: {}, fieldErrors: {} }),
4123
+ badgeRows: badgeRows(board).map((r, i) => {
4124
+ const key = (f) => `badge.${i}.${f}`;
4125
+ const draft = (f) => (key(f) in s.drafts ? s.drafts[key(f)] : r[f]);
4126
+ const edit = (f) => (e) => { const v = e.target.value; this.editField(key(f), v, (b) => setBadgeRow(b, i, { [f]: v })); };
4127
+ return {
4128
+ column: r.column, included: r.included, excluded: !r.included,
4129
+ symbol: draft('symbol'), icon: r.icon, fill: r.fill,
4130
+ icons: (BADGE_ICONS.includes(r.icon) ? BADGE_ICONS : [...BADGE_ICONS, r.icon]).map((v) => ({ value: v, label: v === '' ? 'None' : v })),
4131
+ symbolLabel: `Symbol for ${r.column}`, iconLabel: `Icon for ${r.column}`, colorLabel: `Color for ${r.column}`,
4132
+ error: s.fieldErrors[key('symbol')] ?? false,
4133
+ toggle: () => this.commit((b) => setBadgeRow(b, i, { included: !r.included })),
4134
+ onSymbol: edit('symbol'),
4135
+ onIcon: (e) => { const v = e.target.value; this.commit((b) => setBadgeRow(b, i, { icon: v })); },
4136
+ onColor: edit('color'), // dragging the picker fires repeatedly: one undo step
4137
+ };
4138
+ }),
4139
+ menuItems: [
4140
+ { label: 'New', hint: 'Blank board', run: () => this.newBoard() },
4141
+ { label: 'Open…', hint: 'File, URL or recent', run: () => this.setState({ openOpen: true, openError: null, pickerOpen: false }) },
4142
+ { label: 'Save', hint: this.writable !== null ? `Writes ${this.writable.split('/').pop()}` : 'Ctrl/⌘ S', run: () => this.save() },
4143
+ { label: 'Download', hint: this.fileName(), run: () => this.notify(`Downloaded ${this.download()}`) },
4144
+ { label: 'Copy link', hint: 'Board in the URL', run: () => this.copyLink() },
4145
+ { label: 'Style', hint: theme.name, run: () => this.setState({ pickerOpen: true }) },
4146
+ ].map((m) => ({ label: m.label, hint: m.hint, pick: () => { this.setState({ menuOpen: false }); m.run(); } })),
4147
+ fromSrc: this.src !== null,
4148
+ srcName: this.src === null ? '' : this.src.split('/').pop(),
4149
+ srcTitle: this.src === null ? '' : `Opened from ${this.src}. Changes aren't saved in this browser: use Save or Download.`,
4150
+ save: () => this.save(),
4151
+ download: () => this.download(),
4152
+ fileName: this.fileName(),
4153
+ openOpen: s.openOpen,
4154
+ showOpen: () => this.setState({ openOpen: true, openError: null, pickerOpen: false }),
4155
+ hideOpen: () => this.setState({ openOpen: false }),
4156
+ openBackdrop: (e) => { if (e.target === e.currentTarget) this.setState({ openOpen: false }); },
4157
+ openKey: (e) => { if (e.key === 'Escape') this.setState({ openOpen: false }); },
4158
+ openDragOver: (e) => { e.preventDefault(); if (!s.openDragging) this.setState({ openDragging: true }); },
4159
+ openDragLeave: () => this.setState({ openDragging: false }),
4160
+ openDrop: (e) => { e.preventDefault(); this.setState({ openDragging: false }); this.openFile(e.dataTransfer.files[0]); },
4161
+ dropClass: s.openDragging ? 'kb-drop kb-drop-on' : 'kb-drop',
4162
+ onMdFile: (e) => { const f = e.target.files[0]; e.target.value = ''; this.openFile(f); },
4163
+ openUrl: s.openUrl,
4164
+ onOpenUrl: (e) => this.setState({ openUrl: e.target.value }),
4165
+ openUrlSubmit: (e) => { e.preventDefault(); this.submitOpenUrl(); },
4166
+ openUrlDisabled: s.openUrl.trim() === '' || s.openBusy,
4167
+ openUrlLabel: s.openBusy ? 'Opening…' : 'Open',
4168
+ openError: s.openError,
4169
+ hasRecents: s.recents.length > 0,
4170
+ recents: s.recents.map((r) => ({ name: r.name, detail: r.url ?? 'File, kept in this browser', open: () => this.openRecent(r) })),
4171
+ };
4172
+ }
4173
+ }
4174
+ </script>
4175
+ </body>
4176
+ </html>