repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

docs(nuguland): CalDAV calendar implementation plan

a31efe549b342b3bc25f2983adde6886c1a5d31e

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

10 tasks: caldav.js parser + buildSegments (node-tested), CalDav service
(config/discovery/fetch via curl+keyring), DI+refresh lifecycle, grid
(dots/pills), multi-day band overlay, today agenda, setup popup. Config
via FileView+JsonAdapter per codebase convention.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

Changed files (1)

quickshell/nuguland/docs/superpowers/plans/2026-06-28-caldav-calendar.md

Added
new file mode 100644
1 +# CalDAV Calendar Popup Implementation Plan
3 +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
5 +**Goal:** Replace the crude clock-popup calendar with a month grid (dots / all-day pills / multi-day bands) + today agenda that renders the user's real Nextcloud CalDAV calendars read-only.
7 +**Architecture:** A new `CalDav.qml` service owns all network IO: it reads credentials from the system keyring (`secret-tool`) and fetches calendars/events/tasks via `curl` in a `Process` (Qt QML `XMLHttpRequest` rejects the `REPORT` verb). Responses use server-side `<C:expand>`, so events come back flat (one VEVENT per occurrence, all UTC, no recurrence). Pure parsing/layout logic lives in `caldav.js` (node-testable, no Qt deps). `shell.qml` injects the service into `PopoutHost.qml`, whose `clockContent` is rewritten to render the grid + agenda.
9 +**Tech Stack:** Quickshell/QML, QtQuick, plain JS (`caldav.js`), `curl`, `secret-tool` (gnome-keyring), niri. Tests: `node` for pure JS; `qs ipc` + service restart + niri screenshots for QML.
11 +**Spec:** `docs/superpowers/specs/2026-06-28-caldav-calendar-design.md` — read it. This plan implements it.
13 +## Global Constraints
15 +- Read-only DAV only: `PROPFIND`, `REPORT`, `GET`. Never PUT/POST/DELETE/MKCALENDAR.
16 +- QML/JS only — **no Python or other external interpreter**. `curl` emits raw XML; JS parses.
17 +- Password lives only in the keyring + a transient shell variable on `curl`'s stdin. Never in argv, the config file, or QML memory beyond the `secret-tool store` call.
18 +- Credentials via `secret-tool`, attributes `service=caldav host=<host-from-url>`; app-password (never main password).
19 +- Non-secret config via `Quickshell.statePath("caldav.json")` + `FileView` + `JsonAdapter`.
20 +- Dependency injection through `shell.qml`; never `pragma Singleton`, never re-declare inherited required props (see codebase memory).
21 +- `stateJson()` is an additive IPC contract — add fields, never remove/rename.
22 +- Weekday header: single letters `M D M D F S S`, weekend dimmed (deliberate; do not "fix" to two-letter).
23 +- Timezone: timed events parse to UTC epoch ms, displayed via JS `Date` (system-local). **Never** apply timezone math to all-day `VALUE=DATE` values.
24 +- VTODO query MUST NOT use `<C:expand>` (Nextcloud #45333 drops tasks under expand).
25 +- After editing QML, verify with: `rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service` (stale qmlcache shows ghost TypeErrors).
26 +- `caldav.js` must be dual-mode: usable as a QML JS library AND `require()`-able from node. End the file with `if (typeof module !== 'undefined' && module.exports) module.exports = { ... }` guarded by `typeof module`.
28 +---
30 +### Task 1: `caldav.js` — iCal parser (pure JS, node-tested)
32 +**Files:**
33 +- Create: `quickshell/nuguland/caldav.js`
34 +- Test: `quickshell/nuguland/caldav.test.js`
36 +**Interfaces:**
37 +- Produces:
38 + - `decodeXmlEntities(s) -> string`
39 + - `unfold(text) -> string[]` (unfolded content lines)
40 + - `unescapeText(v) -> string`
41 + - `splitLine(line) -> { name, params, value }` (params raw string after first `;`, before first unquoted `:`)
42 + - `parseIcs(rawXml, defaults) -> Array<EventObj>` where `defaults = { cal, color, kind }` applied per `@@CAL` block; EventObj shape:
43 + `{ uid, summary, cal, color, kind: "event"|"task", allDay, startMs|null, endMs|null, date|null, endDate|null, done }`
44 + (`date`/`endDate` are `"YYYY-MM-DD"` strings; `startMs`/`endMs` are UTC epoch ms ints)
46 +- [ ] **Step 1: Write the failing test**
48 +Create `quickshell/nuguland/caldav.test.js`:
50 +```js
51 +const assert = require('assert');
52 +const C = require('./caldav.js');
54 +// --- unescapeText: single-pass, must survive adjacent backslashes ---
55 +assert.strictEqual(C.unescapeText('a\\,b'), 'a,b');
56 +assert.strictEqual(C.unescapeText('a\\;b'), 'a;b');
57 +assert.strictEqual(C.unescapeText('line1\\nline2'), 'line1\nline2');
58 +assert.strictEqual(C.unescapeText('back\\\\slash'), 'back\\slash');
59 +assert.strictEqual(C.unescapeText('lit\\\\nslash'), 'lit\\nslash'); // \\ then n => backslash + 'n', NOT newline
61 +// --- decodeXmlEntities ---
62 +assert.strictEqual(C.decodeXmlEntities('a&quot;b&amp;c&#13;'), 'a"b&c\r');
64 +// --- unfold: CRLF or LF, strip exactly one WS, keep further spaces ---
65 +assert.deepStrictEqual(C.unfold('AB\r\n CD\r\nEF'), ['ABCD', 'EF']);
66 +assert.deepStrictEqual(C.unfold('AB\n\tCD'), ['ABCD']);
67 +assert.deepStrictEqual(C.unfold('A\r\n B'), ['A B']); // two leading spaces -> one kept
69 +// --- splitLine: first unquoted colon ---
70 +let p = C.splitLine('DTSTART;TZID="A:B":20260101T000000');
71 +assert.strictEqual(p.name, 'DTSTART');
72 +assert.strictEqual(p.value, '20260101T000000');
74 +// --- parseIcs: timed UTC event ---
75 +const timedXml = '@@CAL /p/\t#5b8cff\tVEVENT\n<c:calendar-data>BEGIN:VEVENT\r\nUID:u1\r\nSUMMARY:Picnic\r\nDTSTART:20260622T152500Z\r\nDTEND:20260622T171500Z\r\nEND:VEVENT</c:calendar-data>';
76 +let ev = C.parseIcs(timedXml)[0];
77 +assert.strictEqual(ev.summary, 'Picnic');
78 +assert.strictEqual(ev.cal, '/p/');
79 +assert.strictEqual(ev.color, '#5b8cff');
80 +assert.strictEqual(ev.allDay, false);
81 +assert.strictEqual(ev.startMs, Date.UTC(2026, 5, 22, 15, 25, 0));
82 +assert.strictEqual(ev.endMs, Date.UTC(2026, 5, 22, 17, 15, 0));
84 +// --- parseIcs: all-day event, exclusive DTEND ---
85 +const allDayXml = '@@CAL /p/\t#43c08a\tVEVENT\n<c:calendar-data>BEGIN:VEVENT\nUID:u2\nSUMMARY:Office\nDTSTART;VALUE=DATE:20260602\nDTEND;VALUE=DATE:20260603\nEND:VEVENT</c:calendar-data>';
86 +let ad = C.parseIcs(allDayXml)[0];
87 +assert.strictEqual(ad.allDay, true);
88 +assert.strictEqual(ad.date, '2026-06-02');
89 +assert.strictEqual(ad.endDate, '2026-06-03');
90 +assert.strictEqual(ad.startMs, null);
92 +// --- parseIcs: VTODO task ---
93 +const todoXml = '@@CAL /r/\t#e0a93c\tVTODO\n<c:calendar-data>BEGIN:VTODO\nUID:t1\nSUMMARY:Pay rent\nDUE;VALUE=DATE:20260628\nSTATUS:NEEDS-ACTION\nEND:VTODO</c:calendar-data>';
94 +let td = C.parseIcs(todoXml)[0];
95 +assert.strictEqual(td.kind, 'task');
96 +assert.strictEqual(td.date, '2026-06-28');
97 +assert.strictEqual(td.done, false);
99 +// --- parseIcs: folded SUMMARY + entity + escape end to end ---
100 +const foldXml = '@@CAL /p/\t#fff\tVEVENT\n<c:calendar-data>BEGIN:VEVENT\r\nUID:u3\r\nSUMMARY:Team &quot;sync&quot;\\, part\r\n 2\r\nDTSTART:20260601T090000Z\r\nEND:VEVENT</c:calendar-data>';
101 +let fe = C.parseIcs(foldXml)[0];
102 +assert.strictEqual(fe.summary, 'Team "sync", part 2');
104 +// --- parseIcs: defensive, never throws on garbage ---
105 +assert.deepStrictEqual(C.parseIcs('not xml at all'), []);
106 +assert.deepStrictEqual(C.parseIcs(''), []);
108 +console.log('caldav.test.js: ALL PASS');
109 +```
111 +- [ ] **Step 2: Run test to verify it fails**
113 +Run: `cd quickshell/nuguland && node caldav.test.js`
114 +Expected: FAIL — `Cannot find module './caldav.js'`.
116 +- [ ] **Step 3: Write the implementation**
118 +Create `quickshell/nuguland/caldav.js`:
120 +```js
121 +.pragma library
123 +// --- XML entity decode (named subset + numeric) ---
124 +function decodeXmlEntities(s) {
125 + return String(s == null ? "" : s).replace(/&(#x?[0-9a-fA-F]+|[a-zA-Z]+);/g, function (m, body) {
126 + if (body[0] === '#') {
127 + var code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
128 + return isNaN(code) ? m : String.fromCharCode(code);
130 + var map = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
131 + return map.hasOwnProperty(body) ? map[body] : m;
132 + });
135 +// --- RFC 5545 §3.1 line unfolding: split CR/LF/CRLF, merge lines that
136 +// start with ONE space or tab (strip exactly one WS char, keep the rest). ---
137 +function unfold(text) {
138 + var raw = String(text == null ? "" : text).split(/\r\n|\r|\n/);
139 + var out = [];
140 + for (var i = 0; i < raw.length; i++) {
141 + var line = raw[i];
142 + while (i + 1 < raw.length && (raw[i + 1][0] === ' ' || raw[i + 1][0] === '\t')) {
143 + line += raw[i + 1].slice(1);
144 + i++;
146 + out.push(line);
148 + return out;
151 +// --- RFC 5545 §3.3.11 TEXT unescape: single left-to-right pass. ---
152 +function unescapeText(v) {
153 + return String(v == null ? "" : v).replace(/\\(.)/g, function (_, c) {
154 + return (c === 'n' || c === 'N') ? '\n' : c;
155 + });
158 +// --- split "NAME;params:value" on the first UNQUOTED colon ---
159 +function splitLine(line) {
160 + var colon = -1, inQuote = false;
161 + for (var i = 0; i < line.length; i++) {
162 + var ch = line[i];
163 + if (ch === '"') inQuote = !inQuote;
164 + else if (ch === ':' && !inQuote) { colon = i; break; }
166 + if (colon < 0) return { name: line, params: "", value: "" };
167 + var head = line.slice(0, colon);
168 + var value = line.slice(colon + 1);
169 + var semi = head.indexOf(';');
170 + if (semi < 0) return { name: head, params: "", value: value };
171 + return { name: head.slice(0, semi), params: head.slice(semi + 1), value: value };
174 +function pad2(n) { return (n < 10 ? "0" : "") + n; }
176 +// "20260602" -> "2026-06-02" (plain date string, NO timezone math)
177 +function dateStr(yyyymmdd) {
178 + var s = String(yyyymmdd).slice(0, 8);
179 + return s.slice(0, 4) + "-" + s.slice(4, 6) + "-" + s.slice(6, 8);
182 +// "20260622T152500Z" -> UTC epoch ms
183 +function utcMs(v) {
184 + var m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z?$/.exec(v);
185 + if (!m) return null;
186 + return Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]);
189 +// add one day to a "YYYY-MM-DD" string (for exclusive all-day end math callers)
190 +function addDays(dateString, n) {
191 + var p = dateString.split("-");
192 + var d = new Date(+p[0], +p[1] - 1, +p[2]);
193 + d.setDate(d.getDate() + n);
194 + return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate());
197 +// parse a single VEVENT/VTODO block (already unfolded array of lines)
198 +function parseBlock(lines, kind, cal, color) {
199 + var obj = { uid: "", summary: "", cal: cal, color: color,
200 + kind: kind === "VTODO" ? "task" : "event",
201 + allDay: false, startMs: null, endMs: null, date: null, endDate: null, done: false };
202 + for (var i = 0; i < lines.length; i++) {
203 + var p = splitLine(lines[i]);
204 + var name = p.name.toUpperCase();
205 + var isDate = /VALUE=DATE(;|$)/i.test(p.params) || /^\d{8}$/.test(p.value);
206 + if (name === "UID") obj.uid = unescapeText(p.value);
207 + else if (name === "SUMMARY") obj.summary = unescapeText(p.value);
208 + else if (name === "DTSTART") {
209 + if (isDate) { obj.allDay = true; obj.date = dateStr(p.value); }
210 + else obj.startMs = utcMs(p.value);
211 + } else if (name === "DTEND") {
212 + if (isDate) obj.endDate = dateStr(p.value);
213 + else obj.endMs = utcMs(p.value);
214 + } else if (name === "DUE") {
215 + if (isDate) { obj.allDay = true; obj.date = dateStr(p.value); }
216 + else { obj.startMs = utcMs(p.value); obj.date = obj.date; }
217 + } else if (name === "STATUS") {
218 + if (p.value.toUpperCase() === "COMPLETED") obj.done = true;
219 + } else if (name === "PERCENT-COMPLETE") {
220 + if (parseInt(p.value, 10) >= 100) obj.done = true;
223 + // task with a timed DUE: derive its local date for grid placement
224 + if (obj.kind === "task" && !obj.date && obj.startMs != null) {
225 + var d = new Date(obj.startMs);
226 + obj.date = d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate());
228 + return obj;
231 +// parse the whole concatenated XML (delimited by "@@CAL href\tcolor\tkind" lines)
232 +function parseIcs(rawXml) {
233 + var events = [];
234 + try {
235 + var text = String(rawXml == null ? "" : rawXml);
236 + // chunk by @@CAL delimiter; first chunk before any delimiter is ignored
237 + var chunks = text.split(/^@@CAL /m);
238 + for (var c = 0; c < chunks.length; c++) {
239 + var chunk = chunks[c];
240 + var nl = chunk.indexOf("\n");
241 + if (nl < 0) continue;
242 + var header = chunk.slice(0, nl).split("\t");
243 + if (header.length < 3) continue;
244 + var cal = header[0], color = header[1], compKind = header[2].trim();
245 + var body = decodeXmlEntities(chunk.slice(nl + 1));
246 + // pull each calendar-data text node
247 + var re = /<[^>]*calendar-data[^>]*>([\s\S]*?)<\/[^>]*calendar-data>/g, mm;
248 + while ((mm = re.exec(body)) !== null) {
249 + var lines = unfold(mm[1]);
250 + var cur = null, curKind = null;
251 + for (var i = 0; i < lines.length; i++) {
252 + var line = lines[i];
253 + if (line.indexOf("BEGIN:VEVENT") === 0) { cur = []; curKind = "VEVENT"; }
254 + else if (line.indexOf("BEGIN:VTODO") === 0) { cur = []; curKind = "VTODO"; }
255 + else if (line.indexOf("END:VEVENT") === 0 || line.indexOf("END:VTODO") === 0) {
256 + if (cur) events.push(parseBlock(cur, curKind, cal, color));
257 + cur = null; curKind = null;
258 + } else if (cur) cur.push(line);
262 + } catch (e) {
263 + return [];
265 + return events;
268 +if (typeof module !== 'undefined' && module.exports) {
269 + module.exports = { decodeXmlEntities: decodeXmlEntities, unfold: unfold,
270 + unescapeText: unescapeText, splitLine: splitLine, parseIcs: parseIcs,
271 + utcMs: utcMs, dateStr: dateStr, addDays: addDays };
273 +```
275 +Note: `.pragma library` must be the first line for QML; node ignores it as a comment-like directive? **No** — node will throw on `.pragma`. Resolve by putting `.pragma library` on its own first line and running node with a shim: the test `require` strips it. Simpler and chosen here: **omit `.pragma library`** (a plain QML `.js` without `.pragma library` is imported per-component, which is fine for stateless functions) so the same file is valid node. Delete the `.pragma library` line above.
277 +- [ ] **Step 4: Run test to verify it passes**
279 +Run: `cd quickshell/nuguland && node caldav.test.js`
280 +Expected: `caldav.test.js: ALL PASS`
282 +- [ ] **Step 5: Commit**
284 +```bash
285 +git add quickshell/nuguland/caldav.js quickshell/nuguland/caldav.test.js
286 +git commit -m "feat(nuguland): caldav.js iCal parser with node tests"
287 +```
289 +---
291 +### Task 2: `caldav.js` — multi-day band layout (`buildSegments`)
293 +**Files:**
294 +- Modify: `quickshell/nuguland/caldav.js`
295 +- Modify: `quickshell/nuguland/caldav.test.js`
297 +**Interfaces:**
298 +- Consumes: EventObj array from Task 1; `addDays`, `dateStr`.
299 +- Produces:
300 + - `coveredDates(ev) -> string[]` — list of `"YYYY-MM-DD"` a single event covers (all-day uses exclusive end; timed single-day = its local date; timed spanning = each local date).
301 + - `isMultiDay(ev) -> bool`
302 + - `buildSegments(events, gridStartDateStr) -> { segments: Segment[], laneCount: int }`
303 + where `gridStartDateStr` is the Monday "YYYY-MM-DD" of the 6-week grid, and
304 + `Segment = { row, colStart, colEnd, lane, color, summary, roundLeft, roundRight }`
305 + (`row` 0–5, `col` 0–6; `colEnd` inclusive; segments are split at week boundaries; lanes assigned greedily so no two segments overlap in the same lane).
307 +- [ ] **Step 1: Write the failing test** (append to `caldav.test.js` before the final `console.log`)
309 +```js
310 +// --- coveredDates: all-day exclusive end spans start..end-1 ---
311 +assert.deepStrictEqual(
312 + C.coveredDates({ allDay: true, date: '2026-06-10', endDate: '2026-06-13' }),
313 + ['2026-06-10', '2026-06-11', '2026-06-12']);
314 +// single all-day (no endDate)
315 +assert.deepStrictEqual(C.coveredDates({ allDay: true, date: '2026-06-02', endDate: null }), ['2026-06-02']);
316 +// timed single-day
317 +assert.deepStrictEqual(
318 + C.coveredDates({ allDay: false, startMs: Date.UTC(2026,5,22,15,0), endMs: Date.UTC(2026,5,22,17,0) }).length, 1);
320 +assert.strictEqual(C.isMultiDay({ allDay: true, date: '2026-06-10', endDate: '2026-06-13' }), true);
321 +assert.strictEqual(C.isMultiDay({ allDay: true, date: '2026-06-02', endDate: '2026-06-03' }), false);
323 +// --- buildSegments: a Wed..Fri band in week 0 (grid starts Mon 2026-06-01) ---
324 +const segOut = C.buildSegments(
325 + [{ allDay: true, date: '2026-06-10', endDate: '2026-06-13', color: '#5b8cff', summary: 'Urlaub' }],
326 + '2026-06-08'); // Mon of week containing the 10th
327 +assert.strictEqual(segOut.laneCount, 1);
328 +assert.strictEqual(segOut.segments.length, 1);
329 +let s = segOut.segments[0];
330 +assert.strictEqual(s.row, 0);
331 +assert.strictEqual(s.colStart, 2); // Wed
332 +assert.strictEqual(s.colEnd, 4); // Fri (covers 10,11,12)
333 +assert.strictEqual(s.lane, 0);
334 +assert.strictEqual(s.roundLeft, true);
335 +assert.strictEqual(s.roundRight, true);
337 +// --- buildSegments: week wrap Fri..Mon -> two segments, both inner ends square ---
338 +const wrap = C.buildSegments(
339 + [{ allDay: true, date: '2026-06-12', endDate: '2026-06-16', color: '#e06b9a', summary: 'Messe' }],
340 + '2026-06-08'); // covers 12,13,14,15 -> Fri,Sat,Sun (row0) + Mon (row1)
341 +assert.strictEqual(wrap.segments.length, 2);
342 +const r0 = wrap.segments.find(x => x.row === 0), r1 = wrap.segments.find(x => x.row === 1);
343 +assert.strictEqual(r0.colStart, 4); assert.strictEqual(r0.colEnd, 6);
344 +assert.strictEqual(r0.roundLeft, true); assert.strictEqual(r0.roundRight, false);
345 +assert.strictEqual(r1.colStart, 0); assert.strictEqual(r1.colEnd, 0);
346 +assert.strictEqual(r1.roundLeft, false); assert.strictEqual(r1.roundRight, true);
348 +// --- buildSegments: two overlapping events get distinct lanes ---
349 +const lanes = C.buildSegments([
350 + { allDay: true, date: '2026-06-09', endDate: '2026-06-12', color: '#aaa', summary: 'A' },
351 + { allDay: true, date: '2026-06-10', endDate: '2026-06-13', color: '#bbb', summary: 'B' }
352 +], '2026-06-08');
353 +assert.strictEqual(lanes.laneCount, 2);
354 +```
356 +- [ ] **Step 2: Run test to verify it fails**
358 +Run: `cd quickshell/nuguland && node caldav.test.js`
359 +Expected: FAIL — `C.coveredDates is not a function`.
361 +- [ ] **Step 3: Write the implementation** (add to `caldav.js` before the `module.exports` block; add the new names to the exports object)
363 +```js
364 +function localDateStr(ms) {
365 + var d = new Date(ms);
366 + return d.getFullYear() + "-" + pad2(d.getMonth() + 1) + "-" + pad2(d.getDate());
369 +function coveredDates(ev) {
370 + if (ev.allDay) {
371 + var start = ev.date;
372 + if (!start) return [];
373 + var endExclusive = ev.endDate || addDays(start, 1);
374 + var out = [], cur = start;
375 + // guard against pathological ranges
376 + for (var i = 0; i < 400 && cur < endExclusive; i++) { out.push(cur); cur = addDays(cur, 1); }
377 + return out;
379 + if (ev.startMs == null) return ev.date ? [ev.date] : [];
380 + var a = localDateStr(ev.startMs);
381 + var b = ev.endMs != null ? localDateStr(ev.endMs) : a;
382 + var dates = [a], c2 = a;
383 + for (var j = 0; j < 400 && c2 < b; j++) { c2 = addDays(c2, 1); dates.push(c2); }
384 + return dates;
387 +function isMultiDay(ev) { return coveredDates(ev).length > 1; }
389 +function buildSegments(events, gridStartDateStr) {
390 + // index every grid cell date -> absolute day number 0..41
391 + var dayIndex = {};
392 + for (var i = 0; i < 42; i++) dayIndex[addDays(gridStartDateStr, i)] = i;
394 + // multi-day events as absolute [first,last] ranges clamped to the grid
395 + var spans = [];
396 + for (var e = 0; e < events.length; e++) {
397 + var ev = events[e];
398 + var dates = coveredDates(ev);
399 + if (dates.length < 2) continue; // single-day handled by dots/pills, not bands
400 + var idxs = dates.map(function (d) { return dayIndex[d]; }).filter(function (x) { return x !== undefined; });
401 + if (!idxs.length) continue;
402 + var first = Math.min.apply(null, idxs), last = Math.max.apply(null, idxs);
403 + spans.push({ first: first, last: last, color: ev.color, summary: ev.summary,
404 + trueStart: dayIndex[dates[0]], trueEnd: dayIndex[dates[dates.length - 1]] });
407 + // greedy lane assignment over absolute ranges
408 + spans.sort(function (a, b) { return a.first - b.first || (b.last - b.first) - (a.last - a.first); });
409 + var laneEnds = []; // last occupied abs-day per lane
410 + for (var s2 = 0; s2 < spans.length; s2++) {
411 + var sp = spans[s2], lane = 0;
412 + while (lane < laneEnds.length && laneEnds[lane] >= sp.first) lane++;
413 + laneEnds[lane] = sp.last;
414 + sp.lane = lane;
417 + // split each span at week boundaries into row segments
418 + var segments = [];
419 + for (var s3 = 0; s3 < spans.length; s3++) {
420 + var span = spans[s3];
421 + for (var abs = span.first; abs <= span.last;) {
422 + var row = Math.floor(abs / 7);
423 + var col = abs % 7;
424 + var rowEndAbs = row * 7 + 6;
425 + var segEndAbs = Math.min(span.last, rowEndAbs);
426 + segments.push({
427 + row: row, colStart: col, colEnd: segEndAbs % 7, lane: span.lane,
428 + color: span.color, summary: span.summary,
429 + roundLeft: abs === span.trueStart,
430 + roundRight: segEndAbs === span.trueEnd
431 + });
432 + abs = segEndAbs + 1;
435 + return { segments: segments, laneCount: laneEnds.length };
437 +```
439 +- [ ] **Step 4: Run test to verify it passes**
441 +Run: `cd quickshell/nuguland && node caldav.test.js`
442 +Expected: `caldav.test.js: ALL PASS`
444 +- [ ] **Step 5: Commit**
446 +```bash
447 +git add quickshell/nuguland/caldav.js quickshell/nuguland/caldav.test.js
448 +git commit -m "feat(nuguland): multi-day band layout (buildSegments) with lane assignment"
449 +```
451 +---
453 +### Task 3: `CalDav.qml` service skeleton — config + status + stateJson
455 +**Files:**
456 +- Create: `quickshell/nuguland/CalDav.qml`
457 +- Modify: `quickshell/nuguland/shell.qml` (instantiate + DI + IPC) — see steps.
459 +**Interfaces:**
460 +- Produces (QML properties/functions consumed later):
461 + - `property string status` — one of `"needs-setup" | "loading" | "ok" | "offline"`
462 + - `property var events` — array of EventObj (from `caldav.js`)
463 + - `property var calendars` — array `{ href, displayName, color, components, enabled }`
464 + - `property bool stale`
465 + - `function refresh()`, `function discoverAndFetch()`, `function saveSetup(url, username, password)`
466 + - `function stateJson() -> string`
467 + - `function selfTest() -> string` (runs `caldav.js` assertions in-engine; returns JSON `{pass, fail, cases}`)
469 +- [ ] **Step 1: Write the failing test** (the test is an IPC self-test; first wire a minimal service that reports config presence)
471 +Create `quickshell/nuguland/CalDav.qml`:
473 +```qml
474 +import QtQuick
475 +import Quickshell
476 +import Quickshell.Io
477 +import "caldav.js" as Ical
479 +Item {
480 + id: root
482 + readonly property string configPath: Quickshell.statePath("caldav.json")
483 + // config is the JsonAdapter below (auto-loads + auto-persists, like Usage.qml).
484 + property alias config: cfgAdapter
485 + property var events: []
486 + property bool stale: false
487 + // needs-setup until config has url+username AND a fetch has succeeded/failed
488 + property string status: (cfgAdapter.url && cfgAdapter.username) ? "loading" : "needs-setup"
490 + readonly property string host: {
491 + const u = cfgAdapter.url ? String(cfgAdapter.url) : "";
492 + const m = /^https?:\/\/([^\/:]+)/.exec(u);
493 + return m ? m[1] : "";
496 + function stateJson() {
497 + return JSON.stringify({
498 + backend: "CalDav.qml",
499 + status: status,
500 + stale: stale,
501 + host: host,
502 + username: config ? config.username : "",
503 + calendarCount: config && config.calendars ? config.calendars.length : 0,
504 + eventCount: events ? events.length : 0
505 + });
508 + function selfTest() {
509 + const cases = [];
510 + function ok(name, cond) { cases.push({ name: name, pass: !!cond }); }
511 + try {
512 + ok("unescape-adjacent", Ical.unescapeText("lit\\\\nslash") === "lit\\nslash");
513 + ok("entity-decode", Ical.decodeXmlEntities("a&quot;b") === 'a"b');
514 + const ev = Ical.parseIcs('@@CAL /p/\t#5b8cff\tVEVENT\n<c:calendar-data>BEGIN:VEVENT\nUID:u\nSUMMARY:X\nDTSTART:20260601T090000Z\nEND:VEVENT</c:calendar-data>')[0];
515 + ok("parse-timed", ev && ev.summary === "X" && ev.allDay === false);
516 + const seg = Ical.buildSegments([{ allDay: true, date: "2026-06-10", endDate: "2026-06-13", color: "#fff", summary: "U" }], "2026-06-08");
517 + ok("segments", seg.segments.length === 1 && seg.segments[0].colStart === 2 && seg.segments[0].colEnd === 4);
518 + } catch (e) {
519 + ok("threw:" + e, false);
521 + const fail = cases.filter(c => !c.pass).length;
522 + return JSON.stringify({ pass: cases.length - fail, fail: fail, cases: cases });
525 + // write the adapter back to disk (also fires automatically on property change)
526 + function persistConfig() { cfgFile.writeAdapter(); }
528 + // placeholders fleshed out in later tasks
529 + function refresh() {}
530 + function discoverAndFetch() {}
531 + function saveSetup(url, username, password) {}
533 + FileView {
534 + id: cfgFile
535 + path: root.configPath
536 + onAdapterUpdated: writeAdapter()
538 + JsonAdapter {
539 + id: cfgAdapter
540 + property string url: ""
541 + property string username: ""
542 + property var calendars: []
546 +```
548 +In `shell.qml`, instantiate the service and add IPC. Add near the other service instances (search for an existing `Time {` / service instantiation block):
550 +```qml
551 +CalDav { id: caldavService }
552 +```
554 +Add an IPC handler block (mirror the existing `target: "usage"` handler at `shell.qml:613`):
556 +```qml
557 +IpcHandler {
558 + target: "caldav"
559 + function state() : string { return caldavService.stateJson(); }
560 + function selfTest() : string { return caldavService.selfTest(); }
561 + function refresh() : string { caldavService.refresh(); return caldavService.stateJson(); }
563 +```
565 +- [ ] **Step 2: Run to verify it fails**
567 +Run:
568 +```bash
569 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3
570 +qs ipc -c nuguland call caldav selfTest
571 +```
572 +Expected: FAIL — `caldav` target not found (handler not yet wired) OR a QML error in the journal. (If you ran before editing shell.qml, this confirms the handler is needed.)
574 +- [ ] **Step 3: Make it pass** — ensure the `shell.qml` edits above are saved (service instance + IPC handler).
576 +- [ ] **Step 4: Verify**
578 +Run:
579 +```bash
580 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3
581 +journalctl --user -u quickshell.service --since "10 seconds ago" -o cat | grep -iE "caldav|\.qml:|Error" | grep -v chipWidth || echo "no errors"
582 +qs ipc -c nuguland call caldav selfTest
583 +qs ipc -c nuguland call caldav state
584 +```
585 +Expected: `selfTest` → `{"pass":4,"fail":0,...}`; `state` → JSON with `"status":"needs-setup"` (no config yet) and `"backend":"CalDav.qml"`.
587 +- [ ] **Step 5: Commit**
589 +```bash
590 +git add quickshell/nuguland/CalDav.qml quickshell/nuguland/shell.qml
591 +git commit -m "feat(nuguland): CalDav service skeleton (config, status, stateJson, selfTest IPC)"
592 +```
594 +---
596 +### Task 4: Calendar discovery — PROPFIND via curl Process
598 +**Files:**
599 +- Modify: `quickshell/nuguland/CalDav.qml`
601 +**Interfaces:**
602 +- Consumes: `host`, `config`, `secret-tool`.
603 +- Produces: populated `config.calendars` (persisted via `persistConfig()` from Task 3 / auto `onAdapterUpdated`); `discoverAndFetch()` runs discovery then calls `refresh()` (refresh still a stub until Task 5).
605 +**Background:** The discovery request is a `PROPFIND` Depth 1 on `<url>/calendars/<username>/`. The password is read inside the shell script from the keyring and fed to `curl` via a `-K -` config on stdin — never in argv. Pass non-secret values as `Process.environment`.
607 +- [ ] **Step 1: Add a discovery self-test case** (extend `selfTest()` to parse a captured PROPFIND fixture). Append inside `selfTest()` try-block:
609 +```qml
610 + const propfind = '<d:multistatus xmlns:d="DAV:" xmlns:cal="urn:ietf:params:xml:ns:caldav" xmlns:ic="http://apple.com/ns/ical/"><d:response><d:href>/p/personal/</d:href><d:propstat><d:prop><d:displayname>Mine</d:displayname><ic:calendar-color>#5b8cff</ic:calendar-color><d:resourcetype><cal:calendar/></d:resourcetype><cal:supported-calendar-component-set><cal:comp name="VEVENT"/></cal:supported-calendar-component-set></d:prop></d:propstat></d:response></d:multistatus>';
611 + const cals = root.parseCalendars(propfind);
612 + ok("discover", cals.length === 1 && cals[0].displayName === "Mine" && cals[0].color === "#5b8cff" && cals[0].components.indexOf("VEVENT") >= 0);
613 +```
615 +- [ ] **Step 2: Run to verify it fails**
617 +Run: `rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3 && qs ipc -c nuguland call caldav selfTest`
618 +Expected: FAIL — `discover` case `pass:false` (or a thrown case `root.parseCalendars is not a function`).
620 +- [ ] **Step 3: Implement `parseCalendars`, the discovery Process, and `discoverAndFetch`** (add to `CalDav.qml`):
622 +```qml
623 + // parse a PROPFIND multistatus into calendar descriptors
624 + function parseCalendars(xml) {
625 + const out = [];
626 + const text = String(xml || "");
627 + const respRe = /<[^>]*:?response[^>]*>([\s\S]*?)<\/[^>]*:?response>/g;
628 + let m;
629 + while ((m = respRe.exec(text)) !== null) {
630 + const body = m[1];
631 + const href = (/<[^>]*:?href[^>]*>([\s\S]*?)<\/[^>]*:?href>/.exec(body) || [])[1];
632 + const name = (/<[^>]*:?displayname[^>]*>([\s\S]*?)<\/[^>]*:?displayname>/.exec(body) || [])[1];
633 + const color = (/<[^>]*calendar-color[^>]*>([\s\S]*?)<\/[^>]*calendar-color>/.exec(body) || [])[1];
634 + const isCal = /<[^>]*:?calendar\b[^>]*\/?>/.test(body);
635 + if (!href || !name || !isCal) continue; // skip inbox/outbox/trashbin (no displayname) + non-calendars
636 + const comps = [];
637 + const compRe = /<[^>]*:?comp[^>]*name="([^"]+)"/g;
638 + let cm;
639 + while ((cm = compRe.exec(body)) !== null) comps.push(cm[1]);
640 + out.push({
641 + href: Ical.decodeXmlEntities(href).trim(),
642 + displayName: Ical.decodeXmlEntities(name).trim(),
643 + color: (color ? String(color).trim().slice(0, 7) : "#888888"),
644 + components: comps,
645 + enabled: true
646 + });
648 + return out;
651 + function discoverAndFetch() {
652 + if (!root.host || !root.config.username) { root.status = "needs-setup"; return; }
653 + root.status = "loading";
654 + discoverProc.exec({
655 + command: ["sh", "-c", root.discoverScript()],
656 + environment: {
657 + CALDAV_HOST: root.host,
658 + CALDAV_USER: String(root.config.username),
659 + CALDAV_URL: String(root.config.url).replace(/\/+$/, "") + "/calendars/" + encodeURIComponent(String(root.config.username)) + "/"
661 + });
664 + function discoverScript() {
665 + // password read here, fed to curl via -K - on stdin; never in argv
666 + return 'PW="$(secret-tool lookup service caldav host "$CALDAV_HOST" 2>/dev/null)";' +
667 + 'if [ -z "$PW" ]; then echo __NO_SECRET__; exit 0; fi;' +
668 + 'curl -sS -X PROPFIND -H "Depth: 1" -H "Content-Type: application/xml" ' +
669 + '--data \'<d:propfind xmlns:d="DAV:" xmlns:c="urn:ietf:params:xml:ns:caldav" xmlns:i="http://apple.com/ns/ical/"><d:prop><d:resourcetype/><d:displayname/><i:calendar-color/><c:supported-calendar-component-set/></d:prop></d:propfind>\' ' +
670 + '-K - "$CALDAV_URL" <<EOF\nuser = "$CALDAV_USER:$PW"\nEOF';
673 + function applyDiscovery(text) {
674 + const t = String(text || "");
675 + if (t.indexOf("__NO_SECRET__") >= 0) { root.status = "needs-setup"; return; }
676 + const cals = root.parseCalendars(t);
677 + if (!cals.length) { root.status = "offline"; root.stale = true; return; }
678 + root.config.calendars = cals;
679 + root.persistConfig();
680 + root.refresh(); // Task 5 fills this in
683 + Process {
684 + id: discoverProc
685 + stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.applyDiscovery(this.text) }
686 + stderr: StdioCollector { waitForEnd: true; onStreamFinished: if (this.text.trim()) root.stale = true }
688 +```
690 +- [ ] **Step 4: Verify the self-test passes, then run live discovery**
692 +Run:
693 +```bash
694 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3
695 +qs ipc -c nuguland call caldav selfTest # expect fail:0
696 +```
697 +Then seed config for the live test (URL + username; password already in keyring from earlier setup):
698 +```bash
699 +qs ipc -c nuguland call caldav state # confirm host parsing once config exists
700 +```
701 +If config is empty, temporarily write it (Task 10 adds the popup):
702 +```bash
703 +cat > "$(qs ipc -c nuguland call caldav state >/dev/null 2>&1; echo ${XDG_STATE_HOME:-$HOME/.local/state}/quickshell/by-path)"/... 2>/dev/null # see note
704 +```
705 +**Live-test note:** Until Task 10's setup popup exists, seed config by hand: write `{"url":"https://box.bugabinga.net/cloud/remote.php/dav","username":"oliver@bugabinga.net","calendars":[]}` to the path printed by `qs ipc -c nuguland call caldav state` (`host` echoes once present). Then add a temporary IPC `function discover() : string { caldavService.discoverAndFetch(); return "ok"; }`, call it, wait 2s, and check `state` shows `calendarCount` ≥ 4. Remove the temporary IPC after.
707 +Expected live: `calendarCount` becomes 4–5 (personal, contact_birthdays, Reminders, Jan's). No password in `journalctl` or `ps`.
709 +- [ ] **Step 5: Commit**
711 +```bash
712 +git add quickshell/nuguland/CalDav.qml
713 +git commit -m "feat(nuguland): CalDAV calendar discovery via PROPFIND (curl, keyring stdin)"
714 +```
716 +---
718 +### Task 5: Event + task fetch — REPORT per calendar, one Process
720 +**Files:**
721 +- Modify: `quickshell/nuguland/CalDav.qml`
723 +**Interfaces:**
724 +- Consumes: `config.calendars`, `caldav.js` `parseIcs`, the fetch window (`gridStart`/`gridEnd`).
725 +- Produces: populated `events` (parsed); `status="ok"` on success; `refresh()` implemented; helpers `windowUtc()`, `gridStartDate()`.
727 +**Background:** One `Process` loops the enabled calendars. For each, it emits a `@@CAL <href>\t<color>\t<kind>` delimiter then the response. VEVENT calendars use `REPORT calendar-query` + `<C:expand>` over the window; VTODO calendars use `REPORT calendar-query` **without** expand. `parseIcs` (Task 1) handles the concatenated output.
729 +- [ ] **Step 1: Add a window self-test** (append to `selfTest()` try-block):
731 +```qml
732 + const w = root.windowUtc("2026-06-08"); // Monday grid start
733 + ok("window", /^20260608T000000Z$/.test(w.start) && /^20260720T000000Z$/.test(w.end)); // +42 days
734 +```
736 +- [ ] **Step 2: Run to verify it fails**
738 +Run: `rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3 && qs ipc -c nuguland call caldav selfTest`
739 +Expected: FAIL — `window` case false (`root.windowUtc` undefined → thrown case).
741 +- [ ] **Step 3: Implement window math, `refresh`, and the fetch Process** (add to `CalDav.qml`):
743 +```qml
744 + // Monday on-or-before the 1st of the currently displayed month, as "YYYY-MM-DD"
745 + function gridStartDate() {
746 + const now = new Date();
747 + const first = new Date(now.getFullYear(), now.getMonth(), 1);
748 + const dow = (first.getDay() + 6) % 7; // 0=Mon
749 + first.setDate(first.getDate() - dow);
750 + function p(n){ return (n<10?"0":"")+n; }
751 + return first.getFullYear() + "-" + p(first.getMonth()+1) + "-" + p(first.getDate());
754 + // window from a "YYYY-MM-DD" local grid start: [start, start+42d] as UTC ICAL stamps
755 + function windowUtc(gridStart) {
756 + const p = gridStart.split("-");
757 + const s = new Date(+p[0], +p[1]-1, +p[2], 0, 0, 0); // local midnight
758 + const e = new Date(s.getTime()); e.setDate(e.getDate() + 42);
759 + function fmt(d){
760 + function z(n){ return (n<10?"0":"")+n; }
761 + return d.getUTCFullYear()+z(d.getUTCMonth()+1)+z(d.getUTCDate())+"T"+z(d.getUTCHours())+z(d.getUTCMinutes())+z(d.getUTCSeconds())+"Z";
763 + return { start: fmt(s), end: fmt(e) };
766 + function refresh() {
767 + if (!root.host || !root.config.username) { root.status = "needs-setup"; return; }
768 + if (!root.config.calendars || !root.config.calendars.length) { root.discoverAndFetch(); return; }
769 + root.status = "loading";
770 + const gs = root.gridStartDate();
771 + const w = root.windowUtc(gs);
772 + const lines = [];
773 + const cals = root.config.calendars.filter(c => c.enabled !== false);
774 + for (let i = 0; i < cals.length; i++) {
775 + const isTask = (cals[i].components || []).indexOf("VTODO") >= 0 && (cals[i].components || []).indexOf("VEVENT") < 0;
776 + lines.push([cals[i].href, cals[i].color, isTask ? "VTODO" : "VEVENT"].join("\t"));
778 + fetchProc.exec({
779 + command: ["sh", "-c", root.fetchScript()],
780 + environment: {
781 + CALDAV_HOST: root.host,
782 + CALDAV_USER: String(root.config.username),
783 + CALDAV_BASE: String(root.config.url).replace(/\/+$/, ""),
784 + CALDAV_WIN_START: w.start,
785 + CALDAV_WIN_END: w.end,
786 + CALDAV_CALS: lines.join("\n")
788 + });
791 + function fetchScript() {
792 + // For each "href\tcolor\tkind" line: print delimiter, then curl REPORT.
793 + // VEVENT uses <c:expand>; VTODO must NOT (Nextcloud #45333 drops tasks).
794 + return 'PW="$(secret-tool lookup service caldav host "$CALDAV_HOST" 2>/dev/null)";' +
795 + 'if [ -z "$PW" ]; then echo __NO_SECRET__; exit 0; fi;' +
796 + 'printf %s "$CALDAV_CALS" | while IFS="\t" read -r HREF COLOR KIND; do ' +
797 + '[ -z "$HREF" ] && continue;' +
798 + 'printf "@@CAL %s\\t%s\\t%s\\n" "$HREF" "$COLOR" "$KIND";' +
799 + 'if [ "$KIND" = "VTODO" ]; then ' +
800 + 'BODY="<c:calendar-query xmlns:d=\\"DAV:\\" xmlns:c=\\"urn:ietf:params:xml:ns:caldav\\"><d:prop><c:calendar-data/></d:prop><c:filter><c:comp-filter name=\\"VCALENDAR\\"><c:comp-filter name=\\"VTODO\\"/></c:comp-filter></c:filter></c:calendar-query>";' +
801 + 'else ' +
802 + 'BODY="<c:calendar-query xmlns:d=\\"DAV:\\" xmlns:c=\\"urn:ietf:params:xml:ns:caldav\\"><d:prop><c:calendar-data><c:expand start=\\"$CALDAV_WIN_START\\" end=\\"$CALDAV_WIN_END\\"/></c:calendar-data></d:prop><c:filter><c:comp-filter name=\\"VCALENDAR\\"><c:comp-filter name=\\"VEVENT\\"><c:time-range start=\\"$CALDAV_WIN_START\\" end=\\"$CALDAV_WIN_END\\"/></c:comp-filter></c:comp-filter></c:filter></c:calendar-query>";' +
803 + 'fi;' +
804 + 'curl -sS -X REPORT -H "Depth: 1" -H "Content-Type: application/xml" --data "$BODY" -K - "$CALDAV_BASE$HREF" <<EOF\nuser = "$CALDAV_USER:$PW"\nEOF\n' +
805 + 'printf "\\n";' +
806 + 'done';
809 + function applyFetch(text) {
810 + const t = String(text || "");
811 + if (t.indexOf("__NO_SECRET__") >= 0) { root.status = "needs-setup"; return; }
812 + let parsed = [];
813 + try { parsed = Ical.parseIcs(t); } catch (e) { parsed = []; }
814 + if (!t.trim()) { root.status = "offline"; root.stale = true; return; } // keep last-good events
815 + // client-side window filter for tasks (VTODO has no server time-range)
816 + const gs = root.gridStartDate();
817 + const winStart = gs, winEnd = Ical.addDays(gs, 42);
818 + root.events = parsed.filter(function (ev) {
819 + if (ev.kind !== "task") return true;
820 + return ev.date && ev.date >= winStart && ev.date < winEnd;
821 + });
822 + root.status = "ok";
823 + root.stale = false;
826 + Process {
827 + id: fetchProc
828 + stdout: StdioCollector { waitForEnd: true; onStreamFinished: root.applyFetch(this.text) }
829 + stderr: StdioCollector { waitForEnd: true; onStreamFinished: if (this.text.trim()) { root.stale = true; if (root.status === "loading") root.status = "offline"; } }
831 +```
833 +Update `applyDiscovery` (Task 4) — its final `root.refresh()` now drives real fetching; no change needed, it already calls `refresh()`.
835 +- [ ] **Step 4: Verify self-test, then live fetch**
837 +Run:
838 +```bash
839 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3
840 +qs ipc -c nuguland call caldav selfTest # fail:0
841 +qs ipc -c nuguland call caldav refresh && sleep 3
842 +qs ipc -c nuguland call caldav state # eventCount > 0
843 +```
844 +Expected: `eventCount` in the dozens (live data); `status":"ok"`. Confirm no password leak: `journalctl --user -u quickshell.service --since "30 seconds ago" -o cat | grep -ci "$(secret-tool lookup service caldav host box.bugabinga.net | head -c4)"` should be `0`.
846 +- [ ] **Step 5: Commit**
848 +```bash
849 +git add quickshell/nuguland/CalDav.qml
850 +git commit -m "feat(nuguland): fetch events (REPORT+expand) and tasks (no expand) via one Process"
851 +```
853 +---
855 +### Task 6: Wire DI + refresh lifecycle (initial, periodic, on-open)
857 +**Files:**
858 +- Modify: `quickshell/nuguland/shell.qml` (pass `caldavService` into `PopoutHost`)
859 +- Modify: `quickshell/nuguland/CalDav.qml` (initial load + 15-min timer)
860 +- Modify: `quickshell/nuguland/PopoutHost.qml` (declare the property; refresh on clock popout open)
862 +**Interfaces:**
863 +- Consumes: `caldavService` from Task 3–5.
864 +- Produces: `PopoutHost.caldavService` injected prop; auto-refresh on load, every 15 min, and whenever `clockContent` is shown.
866 +- [ ] **Step 1: Add lifecycle to `CalDav.qml`** (inside the root `Item`):
868 +```qml
869 + Component.onCompleted: Qt.callLater(root.refresh)
871 + Timer {
872 + interval: 15 * 60 * 1000
873 + running: true
874 + repeat: true
875 + onTriggered: root.refresh()
877 +```
879 +- [ ] **Step 2: Inject via `shell.qml`** — find where `PopoutHost` is instantiated and add the property assignment:
881 +```qml
882 +// in the PopoutHost { ... } block
883 +caldavService: caldavService
884 +```
886 +- [ ] **Step 3: Declare the prop + refresh-on-open in `PopoutHost.qml`** — near the other `required property QtObject timeService` declarations (line ~12):
888 +```qml
889 +property QtObject caldavService
890 +```
892 +In the `clockContent` `Component`'s root `Column` (line ~252), add:
894 +```qml
895 +Component.onCompleted: if (root.caldavService) root.caldavService.refresh()
896 +```
898 +- [ ] **Step 4: Verify**
900 +Run:
901 +```bash
902 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 4
903 +qs ipc -c nuguland call caldav state # status ok, eventCount>0 WITHOUT manual refresh (initial load fired)
904 +journalctl --user -u quickshell.service --since "10 seconds ago" -o cat | grep -iE "caldav|\.qml:|Error" | grep -v chipWidth || echo "no errors"
905 +```
906 +Expected: events populate on their own; no QML errors; opening the clock popout triggers a refresh (observe a second fetch in logs if you toggle it).
908 +- [ ] **Step 5: Commit**
910 +```bash
911 +git add quickshell/nuguland/CalDav.qml quickshell/nuguland/shell.qml quickshell/nuguland/PopoutHost.qml
912 +git commit -m "feat(nuguland): inject CalDav, refresh on load/15min/popout-open"
913 +```
915 +---
917 +### Task 7: Redesign `clockContent` grid — header, today, dots, all-day pills
919 +**Files:**
920 +- Modify: `quickshell/nuguland/PopoutHost.qml` (`clockContent` Component, lines ~249–317)
922 +**Interfaces:**
923 +- Consumes: `timeService.calendar(y,m,d)` (existing 6×7 day skeleton: `{iso, day, inMonth, today, selected}`), `caldavService.events`, `caldav.js` helpers.
924 +- Produces: new grid UI. Per-day event lookup built once: `eventsByDate` map `"YYYY-MM-DD" -> { dots: [colors], allDay: [{color,summary}], hasTask: bool }`.
926 +**Note:** Import `caldav.js` at the top of `PopoutHost.qml` if not already: `import "caldav.js" as Ical`. Keep the multi-day band overlay for Task 8 — this task renders the cell base (number, dots, pills) only.
928 +- [ ] **Step 1: Replace the grid block.** In `clockContent`'s `Column`, replace the existing `Grid { objectName: "calendar-grid" … }` (lines ~279–308) and the trailing agenda `NuguText` (lines ~310–313 — agenda comes in Task 9) is left for now. Add a computed map property to the `Column` and rewrite the grid:
930 +```qml
931 + // event lookup, rebuilt when events or month change
932 + property var caldav: root.caldavService
933 + property var eventsByDate: buildEventsByDate(caldav ? caldav.events : [])
935 + function buildEventsByDate(events) {
936 + const map = {};
937 + function slot(d) { return map[d] || (map[d] = { dots: [], allDay: [], hasTask: false }); }
938 + for (let i = 0; i < (events ? events.length : 0); i++) {
939 + const ev = events[i];
940 + const dates = Ical.coveredDates(ev);
941 + if (ev.kind === "task") { if (ev.date) slot(ev.date).hasTask = true; continue; }
942 + if (dates.length > 1) continue; // multi-day -> bands (Task 8)
943 + const d = dates[0];
944 + if (!d) continue;
945 + if (ev.allDay) slot(d).allDay.push({ color: ev.color, summary: ev.summary });
946 + else { const s = slot(d); if (s.dots.indexOf(ev.color) < 0) s.dots.push(ev.color); }
948 + return map;
951 + // single-letter weekday header, weekend dimmed
952 + Row {
953 + spacing: 2
954 + Repeater {
955 + model: ["M","D","M","D","F","S","S"]
956 + NuguText {
957 + width: 26; horizontalAlignment: Text.AlignHCenter
958 + theme: root.theme; variant: "meta"
959 + text: modelData
960 + opacity: index >= 5 ? 0.4 : 0.7
965 + Grid {
966 + objectName: "calendar-grid"
967 + columns: 7
968 + spacing: 2
970 + Repeater {
971 + model: parent.parent.days
973 + Item {
974 + width: 26; height: 30
976 + readonly property var cell: parent.parent.parent.eventsByDate[modelData.iso] || ({ dots: [], allDay: [], hasTask: false })
978 + // today = filled accent circle
979 + Rectangle {
980 + anchors.centerIn: numberText
981 + visible: !!modelData.today
982 + width: 22; height: 22; radius: 11
983 + color: root.theme ? root.theme.ui.accent : "transparent"
985 + // all-day pill (first all-day event), behind number
986 + Rectangle {
987 + anchors { left: parent.left; right: parent.right; top: parent.top; topMargin: 22 }
988 + height: 4; radius: 2
989 + visible: cell.allDay.length > 0 && !modelData.today
990 + color: cell.allDay.length > 0 ? cell.allDay[0].color : "transparent"
993 + NuguText {
994 + id: numberText
995 + anchors.horizontalCenter: parent.horizontalCenter
996 + anchors.top: parent.top
997 + theme: root.theme; variant: "meta"
998 + text: modelData.day ? String(modelData.day) : ""
999 + opacity: modelData.inMonth ? 1 : 0.3
1000 + color: modelData.today && root.theme ? root.theme.ui.onAccent : (root.theme ? root.theme.ui.normal : "white")
1003 + // timed dots: up to 2 + overflow "+"
1004 + Row {
1005 + anchors.horizontalCenter: parent.horizontalCenter
1006 + anchors.bottom: parent.bottom
1007 + spacing: 2
1008 + Repeater {
1009 + model: Math.min(2, cell.dots.length)
1010 + Rectangle { width: 4; height: 4; radius: 2; color: cell.dots[index] }
1012 + NuguText {
1013 + visible: cell.dots.length > 2
1014 + theme: root.theme; variant: "meta"
1015 + font.pixelSize: 8
1016 + text: "+"
1022 +```
1024 +(If `root.theme.ui.onAccent` does not exist, use a readable constant like `"#ffffff"`; check `Theme.qml` for the accent-contrast color name.)
1026 +- [ ] **Step 2: Restart and screenshot**
1028 +Run:
1029 +```bash
1030 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3
1031 +# open the clock popout (use the bar clock IPC or click); then capture:
1032 +qs ipc -c nuguland call nuguland screenshotScreen /tmp/cal.png && echo saved
1033 +```
1034 +- [ ] **Step 3: Visually verify** `/tmp/cal.png` (Read the image): single-letter header with dimmed weekend, today filled circle, out-of-month dimmed, colored dots and all-day pills on the right days. Compare against live data (`qs ipc -c nuguland call caldav state`).
1036 +- [ ] **Step 4: Fix any layout issues** (sizing, color names) inline and re-screenshot until correct.
1038 +- [ ] **Step 5: Commit**
1040 +```bash
1041 +git add quickshell/nuguland/PopoutHost.qml
1042 +git commit -m "feat(nuguland): calendar grid with today circle, dots, all-day pills"
1043 +```
1045 +---
1047 +### Task 8: Multi-day band overlay
1049 +**Files:**
1050 +- Modify: `quickshell/nuguland/PopoutHost.qml` (`clockContent`)
1052 +**Interfaces:**
1053 +- Consumes: `caldav.js` `buildSegments`, the grid geometry from Task 7 (cell width 26 + spacing 2 = 28 px pitch; row height 30 + spacing 2 = 32 px pitch).
1054 +- Produces: a band overlay `Repeater` over computed `segments`, reserving vertical lane space.
1056 +- [ ] **Step 1: Compute segments + render overlay.** In `clockContent`'s `Column`, add a property and an overlay `Item` layered over the `Grid` (give the `Grid` an `id: monthGrid` so the overlay can anchor to it):
1058 +```qml
1059 + property string gridStartIso: days.length ? days[0].iso : ""
1060 + property var bandLayout: gridStartIso ? Ical.buildSegments(caldav ? caldav.events : [], gridStartIso) : ({ segments: [], laneCount: 0 })
1062 + // overlay sits on top of monthGrid; lane bands stack under the day number row
1063 + Item {
1064 + parent: monthGrid
1065 + anchors.fill: monthGrid
1066 + z: 1
1067 + Repeater {
1068 + model: parent.parent.bandLayout.segments
1069 + Rectangle {
1070 + readonly property real pitchX: 28
1071 + readonly property real pitchY: 32
1072 + x: modelData.colStart * pitchX
1073 + width: (modelData.colEnd - modelData.colStart + 1) * pitchX - 4
1074 + y: modelData.row * pitchY + 16 + modelData.lane * 6
1075 + height: 5
1076 + radius: 2.5
1077 + color: Qt.rgba(0,0,0,0) // set below
1078 + Component.onCompleted: color = Qt.alpha ? modelData.color : modelData.color
1079 + // translucent fill + border in the calendar color
1080 + Rectangle {
1081 + anchors.fill: parent; radius: parent.radius
1082 + color: modelData.color; opacity: 0.30
1083 + border.width: 1; border.color: modelData.color
1085 + topLeftRadius: modelData.roundLeft ? 2.5 : 0
1086 + bottomLeftRadius: modelData.roundLeft ? 2.5 : 0
1087 + topRightRadius: modelData.roundRight ? 2.5 : 0
1088 + bottomRightRadius: modelData.roundRight ? 2.5 : 0
1092 +```
1094 +(Adjust `pitchX/pitchY/y-offset` to match Task 7's actual cell metrics; the values above assume 26+2 and 30+2. If `topLeftRadius` et al. are unsupported in the Qt version, drop per-corner rounding and use a single `radius`.)
1096 +- [ ] **Step 2: Reserve lane space** — increase cell height in Task 7's delegate so bands don't overlap the dots when `laneCount` is high. Bind the delegate `Item.height` to `30 + Math.max(0, (parent.parent.parent.bandLayout.laneCount) * 6)` (cap considered in `buildSegments` is open; lanes are typically 1–2).
1098 +- [ ] **Step 3: Restart, screenshot, verify** a real multi-day event renders as a spanning band, wrapping correctly at week boundaries.
1100 +```bash
1101 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3
1102 +qs ipc -c nuguland call nuguland screenshotScreen /tmp/cal-bands.png
1103 +```
1104 +Read `/tmp/cal-bands.png`. If no multi-day event exists in the live window, temporarily inject one via a self-test fixture or verify against the `buildSegments` node tests (already green) + a single-week manual case.
1106 +- [ ] **Step 4: Fix geometry inline** until bands line up with cells.
1108 +- [ ] **Step 5: Commit**
1110 +```bash
1111 +git add quickshell/nuguland/PopoutHost.qml
1112 +git commit -m "feat(nuguland): multi-day event bands overlay with week-wrap segments"
1113 +```
1115 +---
1117 +### Task 9: Today agenda + stale indicator
1119 +**Files:**
1120 +- Modify: `quickshell/nuguland/PopoutHost.qml` (`clockContent`)
1122 +**Interfaces:**
1123 +- Consumes: `caldavService.events`, `caldavService.stale`, `caldav.js` helpers.
1124 +- Produces: an agenda `Column` listing today's events + tasks; stale `·` appended to the date line; empty state.
1126 +- [ ] **Step 1: Replace the placeholder agenda `NuguText`** (lines ~310–313) with a computed today list + rows:
1128 +```qml
1129 + property string todayIso: {
1130 + const n = new Date();
1131 + function p(x){ return (x<10?"0":"")+x; }
1132 + return n.getFullYear()+"-"+p(n.getMonth()+1)+"-"+p(n.getDate());
1134 + property var todayItems: buildToday(caldav ? caldav.events : [], todayIso)
1136 + function buildToday(events, iso) {
1137 + const rows = [];
1138 + for (let i = 0; i < (events ? events.length : 0); i++) {
1139 + const ev = events[i];
1140 + const covers = Ical.coveredDates(ev).indexOf(iso) >= 0 || ev.date === iso;
1141 + if (!covers) continue;
1142 + let time = "ganztg";
1143 + let sortKey = -1;
1144 + if (ev.kind === "task") time = "○";
1145 + else if (!ev.allDay && ev.startMs != null) {
1146 + const d = new Date(ev.startMs);
1147 + function p(x){ return (x<10?"0":"")+x; }
1148 + time = p(d.getHours())+":"+p(d.getMinutes());
1149 + sortKey = d.getHours()*60 + d.getMinutes();
1151 + rows.push({ time: time, color: ev.color, title: ev.summary || "(ohne Titel)",
1152 + done: !!ev.done, sortKey: sortKey });
1154 + rows.sort((a,b) => a.sortKey - b.sortKey);
1155 + return rows;
1158 + Column {
1159 + width: parent.width
1160 + spacing: 4
1161 + NuguText { theme: root.theme; variant: "meta"; text: "Heute"; opacity: 0.6 }
1162 + Repeater {
1163 + model: parent.parent.todayItems
1164 + Row {
1165 + spacing: 8
1166 + NuguText {
1167 + width: 44; theme: root.theme; variant: "meta"
1168 + text: modelData.time; opacity: 0.7
1169 + horizontalAlignment: Text.AlignRight
1171 + Rectangle { width: 3; height: 14; radius: 1.5; color: modelData.color; anchors.verticalCenter: parent.verticalCenter }
1172 + NuguText {
1173 + theme: root.theme; variant: "meta"
1174 + text: modelData.title
1175 + font.strikeout: modelData.done
1176 + opacity: modelData.done ? 0.5 : 1
1180 + NuguText {
1181 + visible: parent.parent.todayItems.length === 0
1182 + theme: root.theme; variant: "meta"
1183 + text: "Keine Termine"; opacity: 0.5; font.italic: true
1186 +```
1188 +- [ ] **Step 2: Stale indicator** — modify the date-line `NuguText` (line ~273–277) to append `·` when stale:
1190 +```qml
1191 + NuguText {
1192 + theme: root.theme
1193 + variant: "meta"
1194 + text: (parent.state.date ? parent.state.date.line : "calendar") + (root.caldavService && root.caldavService.stale ? " ·" : "")
1196 +```
1198 +- [ ] **Step 3: Restart, screenshot, verify** the agenda shows today's events sorted (all-day/tasks first via `sortKey=-1`, then timed), `○` for tasks, `Keine Termine` when empty, and a `·` after the date when offline.
1200 +```bash
1201 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3
1202 +qs ipc -c nuguland call nuguland screenshotScreen /tmp/cal-agenda.png
1203 +```
1204 +Read `/tmp/cal-agenda.png`.
1206 +- [ ] **Step 4: Fix inline** until correct.
1208 +- [ ] **Step 5: Commit**
1210 +```bash
1211 +git add quickshell/nuguland/PopoutHost.qml
1212 +git commit -m "feat(nuguland): today agenda (events + tasks) and stale indicator"
1213 +```
1215 +---
1217 +### Task 10: Setup popup + graceful keyring errors
1219 +**Files:**
1220 +- Modify: `quickshell/nuguland/CalDav.qml` (`saveSetup`, secret-store Process, secret-availability check)
1221 +- Modify: `quickshell/nuguland/PopoutHost.qml` (setup form shown when `status === "needs-setup"`)
1222 +- Modify: `quickshell/nuguland/shell.qml` (IPC `setup(url, user, pw)` for testing)
1224 +**Interfaces:**
1225 +- Consumes: `status` from the service.
1226 +- Produces: `saveSetup(url, username, password)` writes config (url/username) + stores the password via `secret-tool store` (password on **stdin**), then `discoverAndFetch()`; `secretError` string set when `secret-tool` is missing or the keyring is unavailable.
1228 +- [ ] **Step 1: Implement `saveSetup` + store Process** in `CalDav.qml`:
1230 +```qml
1231 + property string secretError: ""
1233 + function saveSetup(url, username, password) {
1234 + root.config.url = String(url).replace(/\/+$/, "");
1235 + root.config.username = String(username);
1236 + if (!root.config.calendars) root.config.calendars = [];
1237 + root.persistConfig();
1238 + root.secretError = "";
1239 + // store password on stdin; host derived from the new url
1240 + const h = (/^https?:\/\/([^\/:]+)/.exec(root.config.url) || [])[1] || "";
1241 + storeProc.stdinText = String(password);
1242 + storeProc.exec({
1243 + command: ["secret-tool", "store", "--label=Nuguland CalDAV",
1244 + "service", "caldav", "host", h, "account", String(username)],
1245 + environment: {}
1246 + });
1249 + Process {
1250 + id: storeProc
1251 + property string stdinText: ""
1252 + stdinEnabled: true
1253 + onStarted: { write(stdinText); stdinText = ""; if (typeof closeStdin === "function") closeStdin(); }
1254 + onExited: (code) => {
1255 + if (code !== 0) { root.secretError = "System keyring unavailable"; root.status = "needs-setup"; }
1256 + else { root.discoverAndFetch(); }
1258 + stderr: StdioCollector { waitForEnd: true; onStreamFinished: if (this.text.trim()) root.secretError = this.text.trim() }
1260 +```
1262 +(Verify the Quickshell `Process` stdin API names: `stdinEnabled`, `write()`, `closeStdin()` — check `Quickshell.Io.Process` docs; if the API differs, the fallback is `command: ["sh","-c","printf %s \"$NG_PW\" | secret-tool store … "]` with the password passed via `environment: { NG_PW: password }` so it stays out of argv.)
1264 +- [ ] **Step 2: Add the setup form to `PopoutHost.qml`.** In `clockContent`'s `Column`, prepend a setup panel shown when needs-setup:
1266 +```qml
1267 + Column {
1268 + visible: root.caldavService && root.caldavService.status === "needs-setup"
1269 + width: parent.width
1270 + spacing: 6
1271 + NuguText { theme: root.theme; variant: "meta"; text: "Connect calendar"; opacity: 0.8 }
1272 + NuguText {
1273 + theme: root.theme; variant: "meta"; wrapMode: Text.WordWrap; width: parent.width
1274 + text: "Use a Nextcloud app-password, not your main password."
1275 + opacity: 0.5
1277 + TextField { id: urlField; width: parent.width; placeholderText: "https://host/.../dav"; text: root.caldavService ? root.caldavService.config.url : "" }
1278 + TextField { id: userField; width: parent.width; placeholderText: "username" }
1279 + TextField { id: pwField; width: parent.width; placeholderText: "app-password"; echoMode: TextInput.Password }
1280 + NuguText {
1281 + visible: root.caldavService && root.caldavService.secretError.length > 0
1282 + theme: root.theme; variant: "meta"; color: "tomato"
1283 + text: root.caldavService ? root.caldavService.secretError : ""
1285 + MouseArea {
1286 + width: parent.width; height: 28
1287 + Rectangle { anchors.fill: parent; radius: 6; color: root.theme ? root.theme.ui.accent : "gray"
1288 + NuguText { anchors.centerIn: parent; theme: root.theme; variant: "meta"; text: "Save" } }
1289 + onClicked: if (root.caldavService) root.caldavService.saveSetup(urlField.text, userField.text, pwField.text)
1292 +```
1294 +- [ ] **Step 3: Add test IPC + verify graceful + happy paths** in `shell.qml`:
1296 +```qml
1297 +function setup(url: string, user: string, pw: string) : string { caldavService.saveSetup(url, user, pw); return caldavService.stateJson(); }
1298 +```
1300 +Run (happy path — keyring present, creds already valid):
1301 +```bash
1302 +rm -rf ~/.cache/quickshell/qmlcache && systemctl --user restart quickshell.service && sleep 3
1303 +qs ipc -c nuguland call caldav setup "https://box.bugabinga.net/cloud/remote.php/dav" "oliver@bugabinga.net" "PLACEHOLDER_APP_PW"
1304 +sleep 3
1305 +qs ipc -c nuguland call caldav state # status ok, calendarCount>0
1306 +```
1307 +(Use the real app-password only via this local IPC; it does not appear in QML source. Or rely on the already-stored secret and pass the same value.)
1309 +Graceful path (simulate missing service): the design must not crash if `secret-tool` errors. Confirm `secretError` populates and `status` stays `needs-setup` (cannot easily uninstall the daemon; instead verify by storing with a deliberately bad attribute set returns non-zero handled cleanly, or inspect that a non-zero `storeProc` exit sets `secretError`).
1311 +- [ ] **Step 4: Screenshot the setup form** when `status==needs-setup` (temporarily clear config to trigger it):
1312 +```bash
1313 +qs ipc -c nuguland call nuguland screenshotScreen /tmp/cal-setup.png
1314 +```
1315 +Read it; confirm URL/username/password fields and the app-password hint render.
1317 +- [ ] **Step 5: Commit**
1319 +```bash
1320 +git add quickshell/nuguland/CalDav.qml quickshell/nuguland/PopoutHost.qml quickshell/nuguland/shell.qml
1321 +git commit -m "feat(nuguland): CalDAV setup popup + keyring store with graceful errors"
1322 +```
1324 +---
1326 +## Self-Review
1328 +**Spec coverage:**
1329 +- §2 decisions → Tasks 1–10 (parser JS, curl/REPORT, separate service, color-coded calendars+VTODO, statePath config, keyring, setup popup, layout, single-letter header, dots+pills+bands, graceful failure, refresh cadence, tz). ✓
1330 +- §4 config/credentials → Task 3 (config), Task 10 (setup + secret store). ✓
1331 +- §5 requests (discovery/events/tasks/one-Process) → Tasks 4, 5. ✓
1332 +- §6 window math → Task 5 (`windowUtc`, `gridStartDate`). ✓
1333 +- §7 parser → Task 1. ✓
1334 +- §8 status/errors → Tasks 3 (status), 5 (offline keep-last-good), 10 (needs-setup/secretError). ✓
1335 +- §9 UI → Tasks 7 (grid), 9 (agenda, stale). ✓
1336 +- §10 band algorithm → Task 2 (`buildSegments`), Task 8 (render). ✓
1337 +- §12 IPC → Task 3 (`caldav` handler, additive). ✓
1338 +- §13 file structure → `caldav.js`, `CalDav.qml`, `shell.qml`, `PopoutHost.qml`; `Time.qml` untouched. ✓
1340 +**Type consistency:** EventObj shape identical across Tasks 1/2/5/7/8/9. `buildSegments(events, gridStartIso)` signature matches Task 2 def and Task 8 call. `parseIcs(rawXml)` matches. `status` string set is consistent (`needs-setup|loading|ok|offline`). `coveredDates`, `addDays` reused from `caldav.js` exports.
1342 +**Known verification caveats (not placeholders — real risks to confirm during implementation):**
1343 +- Quickshell `Process` stdin API (`stdinEnabled`/`write`/`closeStdin`) — Task 10 names the env-var fallback if the API differs.
1344 +- `Theme.qml` accent-contrast color name (`ui.onAccent`) — Task 7 names the constant fallback.
1345 +- Per-corner `Rectangle` radii (`topLeftRadius` …) require Qt 6.7+ — Task 8 names the single-radius fallback.
1346 +- Config uses `FileView` + `JsonAdapter` (auto-load/auto-persist), matching `Usage.qml:73-90`. `persistConfig()` calls `cfgFile.writeAdapter()`; assigning `config.calendars = …` also fires `onAdapterUpdated`. Reassign the array (don't mutate in place) so the change is detected.