source: Klonkt/src/assets/js/guardian.js@ 0202104

main
Last change on this file since 0202104 was 0202104, checked in by Robin Genis <roboburr@…>, 6 weeks ago

De gebruikerskant van 3.6: de ward ziet zijn vangnet, de guardian handelt

Drie oppervlakken rondgemaakt op de beschikbaarheid die er sinds vanmorgen
server-side in zit.

Berichten (de ward): de guardians-balk toont per guardian de buddy-list-stip
met het label erbij: beschikbaar, afwezig tot een datum, offline. Het kind ziet
de echte omvang van zijn vangnet, niet alleen de namen. Owner-only omdat de
pagina dat is.

De Guardian-PWA (de guardian): in het paneel per kind staan de mede-guardians
met dezelfde stippen; op een slapende verschijnt de bewuste, zeldzame
vervolgstap "Voorstel: loslaten bij afwezigheid", die langs dezelfde
C2S-pijplijn loopt als de Shaer-apps (Offer van shaer:Lapse, lokaal ward opent
direct, remote ward krijgt het voorstel bezorgd). Lopende lapses staan als
kaart bij de aanvragen, met Eens/Oneens over de bestaande offer-draad en de zin
die het frame bewaakt. En "Even afwezig": een week of een maand, een directe
note met shaer:away naar alle wards, lokaal direct toegepast.

Shaer (beide apps): de lapse-kaart toont stemknoppen alleen aan leden van de
set. De ward kijkt mee naar wat zijn guardians beslissen; het is daar niet de
rechter, om precies de reden uit de editor's note van 3.6.3.

Onderweg gerepareerd: parseStamp kende alleen strings, waardoor een epoch-ms
endTime als lege datum rendde ("unavailable till" zonder datum).

Changed files:
src/routes/posts.js

  • /messages geeft de guardians hun beschikbaarheid mee

src/views/pages/messages.ejs

  • de stip en het label per guardian, met de opmaak erbij

src/routes/guardian.js

  • dashboardState: mede-guardians met status per lokaal kind, plus lapses
  • POST /guardian/api/away en /guardian/api/lapse
  • de nieuwe labels in uiStrings

src/assets/js/guardian.js

  • de guardians-sectie in het paneel, de lapse-kaart, de afwezig-knoppen

src/views/pages/guardian.ejs

  • de "Even afwezig"-sectie

src/assets/css/guardian.css

  • de stippen en de lapse-kaart

src/middleware/render.js

  • parseStamp accepteert epoch ms

src/services/i18n.js

  • de labels en teksten in nl, en, de

remarks: end-to-end in de browser nagelopen op de wegwerp-database: het kind
ziet oma afwezig-tot, opa offline en guard beschikbaar; de guardian opent het
paneel, stelt de lapse voor op de slapende opa (kaart verschijnt, eigen stem
geteld), drukt "A week", en bij het kind staat guard meteen op afwezig tot
5 augustus. 276 tests groen. Niet uitgerold.

-robo
Co-Authored-By: Claude Fable 5 <noreply@…>

  • Property mode set to 100644
File size: 28.6 KB
Line 
1/* Guardian PWA client (FEP-633c): renders the dashboard, adopts wards, and
2 manages the guardian push channel. No framework, no inline scripts (CSP).
3 All user-facing text comes from state.strings (server i18n). */
4(function () {
5 'use strict';
6 // A crash here used to fail silently (buttons just do nothing). Surface it on
7 // the page AND the console so the cause is visible instead of "everything hangs".
8 function fatal(msg) {
9 try {
10 var b = document.getElementById('g-fatal') || document.createElement('div');
11 b.id = 'g-fatal'; b.className = 'g-msg err';
12 b.style.cssText = 'display:block;margin:12px 0;padding:10px 14px';
13 b.textContent = 'Guardian: ' + msg;
14 var root = document.querySelector('main') || document.body;
15 if (!b.parentNode && root) root.insertBefore(b, root.firstChild);
16 } catch (e) { /* last resort */ }
17 try { console.error('[guardian]', msg); } catch (e) { /* no console */ }
18 }
19 try {
20 var S = JSON.parse(document.getElementById('guardian-state').textContent || '{}');
21 var T = S.strings || {};
22
23 function el(tag, cls, text) {
24 var n = document.createElement(tag);
25 if (cls) n.className = cls;
26 if (text != null) n.textContent = text;
27 return n;
28 }
29 function handleOf(uri, cached) {
30 if (cached && cached.charAt(0) === '@') return cached; // trust only real @handles
31 try { var u = new URL(uri); return '@' + u.pathname.split('/').filter(Boolean).pop() + '@' + u.host; }
32 catch (e) { return uri; }
33 }
34 // The server hands over a timestamp already formatted in the site's timezone
35 // (Beheer -> Instellingen), the same clock de Krant and Berichten show. The
36 // slice is only a fallback for a row that predates that field: it shows raw
37 // UTC, which is what made a 20:20 call for help read 18:20.
38 function when(item, raw) {
39 if (item && item.when_text) return item.when_text;
40 return String(raw || '').slice(0, 16).replace('T', ' ');
41 }
42 function show(id, on) { document.getElementById(id).hidden = !on; }
43
44 // ── 1. Help requests ───────────────────────────────────────────────────
45 // A call for help is not an alarm: it may well be settled quietly between a
46 // guardian and the child. So the card carries no siren, it just has to be
47 // impossible to miss. It shows up twice on purpose (Robins keuze): the recent
48 // ones across all children at the top, the full history of one child in that
49 // child's panel.
50 var HELP_TOP = 5;
51
52 function helpCard(h) {
53 var card = el('div', 'g-card help');
54 var row = el('div', 'row');
55 var who = el('span', 'who grow');
56 // name_html carries the custom emojis (FEP-9098) of the display name, the
57 // same way de Krant renders a byline. Falls back to the plain name.
58 if (h.name_html) who.innerHTML = h.name_html;
59 else who.textContent = h.actor_name || handleOf(h.actor_uri, h.actor_handle);
60 row.appendChild(who);
61 row.appendChild(el('span', 'when', when(h, h.published || h.created_at)));
62 card.appendChild(row);
63 var body = el('div', 'body g-note');
64 // body_html is the shared note-body partial, rendered server-side: the
65 // content with its emojis, the quote / link-preview card and the media.
66 // Falls back to the bare content for rows stored before that existed.
67 body.innerHTML = h.body_html || h.content || ''; // sanitized server-side on ingest
68 card.appendChild(body);
69 if (h.note_url) {
70 var a = el('a', 'g-link', T.open || 'open');
71 a.href = h.note_url; a.target = '_blank'; a.rel = 'noopener';
72 card.appendChild(a);
73 }
74 return card;
75 }
76
77 function renderHelp() {
78 var list = document.getElementById('help-list');
79 list.textContent = '';
80 var help = S.help || [];
81 help.slice(0, HELP_TOP).forEach(function (h) { list.appendChild(helpCard(h)); });
82 if (help.length > HELP_TOP) {
83 list.appendChild(el('p', 'g-sec-sub', '+ ' + (help.length - HELP_TOP) + ' — ' + (T.panel_help || '')));
84 }
85 var badge = document.getElementById('help-count');
86 badge.textContent = help.length; badge.hidden = help.length === 0;
87 show('help-empty', help.length === 0);
88 }
89
90 // ── 3. Offers I am a party to (sent, or a co-guardianship to co-approve) ─
91 function answer(offerId, decision, btn) {
92 if (btn) btn.disabled = true;
93 fetch('/guardian/offer', {
94 method: 'POST', headers: { 'Content-Type': 'application/json' },
95 body: JSON.stringify({ offer: offerId, answer: decision, site: S.site }),
96 }).then(refresh);
97 }
98 function offerCard(o) {
99 var card = el('div', 'g-card');
100 var row = el('div', 'row');
101 var subject = o['shaer:iAmCandidate']
102 ? handleOf(o['shaer:ward'], o['shaer:wardHandle']) // my sent offer: about the ward
103 : handleOf(o['shaer:candidate'], o['shaer:candidateHandle']); // co-guard: who wants in
104 row.appendChild(el('span', 'who grow', subject));
105 if (o['shaer:iAmCandidate']) {
106 // My own offer, waiting for the others to accept.
107 row.appendChild(el('span', 'tag wait', T.pending));
108 var rt = el('button', 'quiet small', T.retract);
109 rt.addEventListener('click', function () { answer(o.id, 'reject', rt); });
110 row.appendChild(rt);
111 } else if (o['shaer:needsMyAccept']) {
112 // A co-guardianship offer for a ward I already guard: my call.
113 row.appendChild(el('span', 'tag co', T.coguard));
114 var ac = el('button', 'small', T.accept);
115 ac.addEventListener('click', function () { answer(o.id, 'accept', ac); });
116 var rj = el('button', 'quiet small', T.reject);
117 rj.addEventListener('click', function () { answer(o.id, 'reject', rj); });
118 row.appendChild(ac); row.appendChild(rj);
119 } else {
120 row.appendChild(el('span', 'tag wait', T.awaiting_others));
121 }
122 card.appendChild(row);
123 return card;
124 }
125 /** A running lapse (FEP-633c 3.6.3): the available co-guardians deciding
126 * to release a dormant one. Votes ride the same Accept/Reject wire as the
127 * offers; buttons appear only for set members (the ward watches, it does
128 * not vote). */
129 function lapseCard(l) {
130 var card = el('div', 'g-card lapse');
131 card.appendChild(el('div', 'who', (T.lapse_line || '{who} has stopped answering as a guardian of {ward}.')
132 .replace('{who}', handleOf(l.object.object)).replace('{ward}', handleOf(l.object['shaer:ward']))));
133 card.appendChild(el('div', 'g-avlabel', (T.lapse_tally || '{n} of {need} agreed; closes {date}.')
134 .replace('{n}', l['shaer:accepts']).replace('{need}', l['shaer:threshold'])
135 .replace('{date}', new Date(l['shaer:closesAt']).toLocaleDateString())));
136 var row = el('div', 'row');
137 var inSet = (l['shaer:set'] || []).indexOf(S.me) >= 0;
138 if (inSet && !l['shaer:myVote']) {
139 var yes = el('button', 'small', T.lapse_agree || 'Agree');
140 yes.addEventListener('click', function () { answer(l.id, 'accept', yes); });
141 var no = el('button', 'quiet small', T.lapse_disagree || 'Disagree');
142 no.addEventListener('click', function () { answer(l.id, 'reject', no); });
143 row.appendChild(yes); row.appendChild(no);
144 } else if (inSet) {
145 row.appendChild(el('span', 'g-avlabel', T.voted || 'You voted'));
146 }
147 card.appendChild(row);
148 card.appendChild(el('p', 'g-empty small', T.lapse_note || ''));
149 return card;
150 }
151
152 function renderPending() {
153 var list = document.getElementById('pending-list');
154 list.textContent = '';
155 var offers = S.offers || [];
156 // The offers state carries the adoption offers; the lapse proposals ride
157 // separately so a lapse never renders as an adoption.
158 var lapses = (S.lapses || []).filter(function (l) { return l['shaer:outcome'] === 'open'; });
159 offers.forEach(function (o) {
160 if (o.object && o.object.type === 'shaer:Lapse') return; // rendered below
161 list.appendChild(offerCard(o));
162 });
163 lapses.forEach(function (l) { list.appendChild(lapseCard(l)); });
164 show('pending-section', offers.length > 0 || lapses.length > 0);
165 }
166
167 // ── 4. Accepted wards: one panel per child ─────────────────────────────
168 // A guardian thinks per child, not per function, so everything about one
169 // child sits behind that child's row: the gated settings, the follow requests
170 // waiting on them, their calls for help, their recent posts. The row itself
171 // carries counts, so nothing that needs an answer hides inside a closed
172 // panel.
173 var openPanels = {}; // ward uri -> open, so a refresh does not close it
174 // The follow requests and the wards' posts arrive from their own endpoints
175 // and are grouped into the panels by ward, so they are cached here rather
176 // than rendered into a section of their own.
177 var FEED = [], FOLLOWS = [];
178
179 function sectionInto(panel, title, items, empty, build) {
180 var h = el('div', 'g-panel-sec');
181 h.appendChild(el('h3', null, title));
182 if (!items.length) h.appendChild(el('p', 'g-empty small', empty));
183 else items.forEach(function (it) { h.appendChild(build(it)); });
184 panel.appendChild(h);
185 return h;
186 }
187
188 function embedsButton(w) {
189 // Gated feature: external (non-fediverse) embeds. Off by default for a
190 // ward; only a guardian can open it, and the gate is enforced server-side
191 // when the feed is built, so this button is the only thing that moves it.
192 // Shown for EVERY ward, including one on another server. There the value is
193 // unknown (it lives on the ward's server), but proposing is exactly as
194 // possible: the proposal travels, the ward's server tallies the guardians
195 // and enforces. A guardian next door must not have more say than one far
196 // away.
197 var known = w.embeds === true || w.embeds === false;
198 var emb = el('button', 'quiet small',
199 (known ? (w.embeds ? T.embeds_on : T.embeds_off) : T.embeds_propose) || 'Link previews');
200 emb.addEventListener('click', function () {
201 emb.disabled = true;
202 fetch('/guardian/wards/embeds', {
203 method: 'POST', headers: { 'Content-Type': 'application/json' },
204 body: JSON.stringify({ uri: w.other_uri, allow: known ? !w.embeds : true }),
205 }).then(function (r) { return r.json(); })
206 .then(function (j) {
207 // Not settled yet: the other guardians still have to answer.
208 if (j && j.state === 'open') {
209 emb.textContent = (T.embeds_waiting || 'waiting for the other guardians');
210 emb.disabled = true;
211 return;
212 }
213 refresh();
214 })
215 .catch(function () { emb.disabled = false; });
216 });
217 return emb;
218 }
219
220 /**
221 * The second step of releasing a ward: what it does, then yes or no.
222 *
223 * The warning is assembled from what the server found, not from a fixed
224 * sentence, because releasing means two different things (FEP-633c): stepping
225 * down while other guardians remain (§3.3), or being the last one, which is
226 * emancipation and explicitly not one guardian's call (§3.4). And as long as
227 * the Undo does not federate, the ward's server keeps listing you either way
228 * — a guardian has to know that before pressing, not after.
229 */
230 function releaseStep(w, check, host, relBtn) {
231 var uri = w.other_uri;
232 var who = handleOf(uri, w.other_handle);
233 var box = el('div', 'g-warn');
234 box.appendChild(el('strong', null, (T.release_title || 'Release {who}?').replace('{who}', who)));
235 box.appendChild(el('p', null, T.release_effect || ''));
236 if (check.last === true) box.appendChild(el('p', 'grave', T.release_last || ''));
237 else if (check.last === false) box.appendChild(el('p', null, T.release_step_down || ''));
238 else box.appendChild(el('p', 'grave', T.release_unknown || ''));
239 box.appendChild(el('p', null, T.release_local || ''));
240
241 var row = el('div', 'row');
242 var no = el('button', 'small', T.release_no || 'No');
243 no.addEventListener('click', function () {
244 host.removeChild(box);
245 relBtn.hidden = false; relBtn.disabled = false;
246 });
247 // No first: the way out should be the easy one to hit.
248 row.appendChild(no);
249 // Being the last guardian is not a warning but a wall: the server refuses
250 // it (§3.4), so offering a yes here would only produce an error. The text
251 // above already says what has to happen instead.
252 if (check.last !== true) {
253 var yes = el('button', 'danger small', T.release_yes || 'Yes');
254 yes.addEventListener('click', function () {
255 yes.disabled = true;
256 remove(uri, yes, function (err) {
257 // The guardian set can change between the check and the click.
258 yes.disabled = false;
259 box.appendChild(el('p', 'grave', err === 'would_emancipate' ? (T.release_last || '') : (T.failed || '')));
260 if (err === 'would_emancipate') yes.remove();
261 });
262 });
263 row.appendChild(yes);
264 }
265 box.appendChild(row);
266 return box;
267 }
268
269 /** The availability dot (FEP-633c 3.6): buddy-list language on the
270 * responsibility axis. Green available, yellow declared away with an end,
271 * grey observed dormant (one answer restores). */
272 function availLabel(g) {
273 if (g.availability === 'away') {
274 var date = g.awayUntil ? new Date(g.awayUntil).toLocaleDateString() : '?';
275 return (T.avail_away || 'Unavailable till {date}').replace('{date}', date);
276 }
277 if (g.availability === 'dormant') return T.avail_dormant || 'Offline';
278 return T.avail_available || 'Available';
279 }
280 function availRow(g, wardUri) {
281 var row = el('div', 'row g-guard');
282 var dot = el('span', 'g-avdot ' + (g.availability === 'away' ? 'is-away' : g.availability === 'dormant' ? 'is-dormant' : 'is-active'));
283 row.appendChild(dot);
284 row.appendChild(el('span', 'who grow', handleOf(g.uri, g.handle)));
285 row.appendChild(el('span', 'g-avlabel', availLabel(g)));
286 // A dormant fellow guardian without a running lapse: the deliberate,
287 // rare next step (3.6.3). Never shown for anyone still answering.
288 if (g.availability === 'dormant' && !g.lapse && g.uri !== S.me) {
289 var btn = el('button', 'quiet small', T.lapse_propose || 'Propose release');
290 btn.addEventListener('click', function () {
291 btn.disabled = true;
292 fetch('/guardian/api/lapse', {
293 method: 'POST', headers: { 'Content-Type': 'application/json' },
294 body: JSON.stringify({ ward: wardUri, target: g.uri, site: S.site }),
295 }).then(refresh).catch(function () { btn.disabled = false; });
296 });
297 row.appendChild(btn);
298 }
299 return row;
300 }
301
302 function wardPanel(w) {
303 var uri = w.other_uri;
304 var panel = el('div', 'g-panel');
305 panel.hidden = !openPanels[uri];
306
307 var set = el('div', 'g-panel-sec');
308 set.appendChild(el('h3', null, T.settings_title || 'Settings'));
309 var setRow = el('div', 'row');
310 setRow.appendChild(embedsButton(w));
311 set.appendChild(setRow);
312 panel.appendChild(set);
313
314 // The fellow guardians of this child, with availability (3.6). For a
315 // ward on another server the states live there, and saying so honestly
316 // beats guessing.
317 var gsec = el('div', 'g-panel-sec');
318 gsec.appendChild(el('h3', null, T.panel_guards || 'Guardians of this child'));
319 if (w.guardians && w.guardians.length) {
320 w.guardians.forEach(function (g) { gsec.appendChild(availRow(g, uri)); });
321 } else {
322 gsec.appendChild(el('p', 'g-empty small', T.panel_guards_remote || ''));
323 }
324 panel.appendChild(gsec);
325
326 sectionInto(panel, T.panel_follow || 'Follow requests',
327 FOLLOWS.filter(function (f) { return f.wardUri === uri; }),
328 T.panel_follow_empty || '', followCard);
329
330 sectionInto(panel, T.panel_help || 'Calls for help',
331 (S.help || []).filter(function (h) { return h.actor_uri === uri; }),
332 T.panel_help_empty || '', helpCard);
333
334 sectionInto(panel, T.panel_posts || 'Recent posts',
335 FEED.filter(function (p) { return p.authorUri === uri; }),
336 T.panel_posts_empty || '', feedCard);
337
338 var act = el('div', 'g-panel-sec');
339 act.appendChild(el('h3', null, T.panel_actions || 'Actions'));
340 var actRow = el('div', 'row');
341 var wave = el('button', 'small', T.wave || '👋 Wave');
342 wave.addEventListener('click', function () { sendWave(uri, wave); });
343 actRow.appendChild(wave);
344 var rel = el('button', 'quiet small', T.release);
345 // Letting a child go is a decision, not a click. It opens a step that first
346 // asks the server what releasing this particular ward actually does, then
347 // says it plainly and asks yes or no. Never window.confirm: that hides a
348 // long explanation behind an OK button people press to make it go away.
349 rel.addEventListener('click', function () {
350 rel.disabled = true;
351 // site matters: with several of your own sites the server would otherwise
352 // check this ward against the wrong one and answer "not my ward".
353 fetch('/guardian/wards/release-check?site=' + encodeURIComponent(S.site) + '&uri=' + encodeURIComponent(uri))
354 .then(function (r) { return r.json(); })
355 .then(function (c) {
356 rel.hidden = true;
357 act.appendChild(releaseStep(w, c || {}, act, rel));
358 })
359 .catch(function () { rel.disabled = false; });
360 });
361 actRow.appendChild(rel);
362 act.appendChild(actRow);
363 panel.appendChild(act);
364 return panel;
365 }
366
367 function renderWards() {
368 var list = document.getElementById('wards-list');
369 list.textContent = '';
370 var wards = S.wards || [];
371 wards.forEach(function (w) {
372 var uri = w.other_uri;
373 var card = el('div', 'g-card ward');
374 var row = el('div', 'row');
375 row.appendChild(el('span', 'who grow', handleOf(uri, w.other_handle)));
376 // Counts on the row: whatever is waiting must be visible with the panel shut.
377 var nHelp = (S.help || []).filter(function (h) { return h.actor_uri === uri; }).length;
378 var nFollow = FOLLOWS.filter(function (f) { return f.wardUri === uri; }).length;
379 if (nHelp) row.appendChild(el('span', 'tag help', '🛟 ' + nHelp));
380 if (nFollow) row.appendChild(el('span', 'tag co', nFollow + ' ' + (nFollow === 1 ? (T.badge_follow_one || '') : (T.badge_follow || ''))));
381 row.appendChild(el('span', 'tag ok', T.active));
382 var toggle = el('button', 'quiet small', openPanels[uri] ? T.panel_close : T.panel_open);
383 row.appendChild(toggle);
384 card.appendChild(row);
385 var panel = wardPanel(w);
386 card.appendChild(panel);
387 toggle.addEventListener('click', function () {
388 openPanels[uri] = !openPanels[uri];
389 panel.hidden = !openPanels[uri];
390 toggle.textContent = openPanels[uri] ? T.panel_close : T.panel_open;
391 });
392 list.appendChild(card);
393 });
394 show('wards-empty', wards.length === 0);
395 // Step away (3.6.1) only means something with wards to tell.
396 show('away-section', wards.length > 0);
397 }
398
399 // ── 4b. Step away (FEP-633c 3.6.1) ─────────────────────────────────────
400 function declareAway(days, btn) {
401 btn.disabled = true;
402 fetch('/guardian/api/away', {
403 method: 'POST', headers: { 'Content-Type': 'application/json' },
404 body: JSON.stringify({ days: days, site: S.site }),
405 }).then(function (r) { return r.json(); })
406 .then(function (j) {
407 btn.disabled = false;
408 var msg = document.getElementById('away-msg');
409 msg.hidden = false;
410 if (j && j.ok) {
411 msg.className = 'g-msg';
412 msg.textContent = (T.away_done || 'Your wards know you are unavailable until {date}.')
413 .replace('{date}', new Date(j.until).toLocaleDateString());
414 } else {
415 msg.className = 'g-msg err';
416 msg.textContent = (j && j.error) || (T.failed || 'failed');
417 }
418 })
419 .catch(function () { btn.disabled = false; });
420 }
421 var awayWeek = document.getElementById('away-week');
422 var awayMonth = document.getElementById('away-month');
423 if (awayWeek) awayWeek.addEventListener('click', function () { declareAway(7, awayWeek); });
424 if (awayMonth) awayMonth.addEventListener('click', function () { declareAway(30, awayMonth); });
425
426 function sendWave(uri, btn) {
427 btn.disabled = true;
428 fetch('/guardian/api/wave', {
429 method: 'POST', headers: { 'Content-Type': 'application/json' },
430 body: JSON.stringify({ ward: uri, site: S.site }),
431 }).then(function (r) { return r.json(); })
432 .then(function (j) { btn.disabled = false; btn.textContent = (j && j.ok) ? (T.waved || '👋 sent') : (T.wave || '👋 Wave'); })
433 .catch(function () { btn.disabled = false; });
434 }
435
436 function remove(uri, btn, onError) {
437 btn.disabled = true;
438 fetch('/guardian/wards/remove', {
439 method: 'POST', headers: { 'Content-Type': 'application/json' },
440 body: JSON.stringify({ uri: uri, site: S.site }),
441 }).then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
442 .then(function (res) {
443 // The server can refuse: emptying shaer:guardians is emancipation and
444 // not one guardian's call (§3.4). Say so instead of silently redrawing.
445 if (!res.ok) { if (onError) onError(res.j && res.j.error); return; }
446 refresh();
447 })
448 .catch(function () { if (onError) onError('network'); else btn.disabled = false; });
449 }
450
451 function renderAll() { renderHelp(); renderPending(); renderWards(); }
452
453 // ── 0. Wards' corner: read-only feed of your wards' posts ───────────────
454 // Lives inside each child's panel now, so the fetches only fill a cache and
455 // ask the ward list to redraw. A guardian watches, it does not publish.
456 function feedCard(p) {
457 var card = el('div', 'g-card feed');
458 var head = el('div', 'row');
459 head.appendChild(el('span', 'who grow', p.author));
460 if (p.published) head.appendChild(el('span', 'g-when', when(p, p.published)));
461 card.appendChild(head);
462 var body = el('div', 'feed-body');
463 if (p.cw) {
464 var d = document.createElement('details');
465 var sum = document.createElement('summary'); sum.textContent = p.cw; d.appendChild(sum);
466 var inner = el('div'); inner.innerHTML = p.content || ''; d.appendChild(inner);
467 body.appendChild(d);
468 } else {
469 body.innerHTML = p.content || ''; // server-sanitized HTML (same as Berichten)
470 }
471 card.appendChild(body);
472 return card;
473 }
474
475 function loadFeed() {
476 return fetch('/guardian/api/feed?site=' + encodeURIComponent(S.site))
477 .then(function (r) { return r.json(); })
478 .then(function (f) { if (f && !f.error) { FEED = f.items || []; renderWards(); } })
479 .catch(function () { /* panels just show "nothing yet" */ });
480 }
481
482 // ── 0b. Follow requests on your wards (§5.3) ────────────────────────────
483 function answerFollow(id, decision, btn) {
484 if (btn) btn.disabled = true;
485 fetch('/guardian/api/follow/' + encodeURIComponent(id), {
486 method: 'POST', headers: { 'Content-Type': 'application/json' },
487 body: JSON.stringify({ decision: decision, site: S.site }),
488 }).then(loadFollowReqs);
489 }
490 function followCard(f) {
491 var card = el('div', 'g-card');
492 var row = el('div', 'row');
493 // Inside the child's own panel the ward name is a given, so only the
494 // person asking is named here.
495 row.appendChild(el('span', 'who grow', f.follower));
496 var ok = el('button', 'small', T.accept || 'Accept');
497 ok.addEventListener('click', function () { answerFollow(f.id, 'approve', ok); });
498 var no = el('button', 'quiet small', T.reject || 'Deny');
499 no.addEventListener('click', function () { answerFollow(f.id, 'reject', no); });
500 row.appendChild(ok); row.appendChild(no);
501 card.appendChild(row);
502 return card;
503 }
504 function loadFollowReqs() {
505 return fetch('/guardian/api/follow-requests?site=' + encodeURIComponent(S.site))
506 .then(function (r) { return r.json(); })
507 .then(function (f) { if (f && !f.error) { FOLLOWS = f.items || []; renderWards(); } })
508 .catch(function () { /* panels just show "none waiting" */ });
509 }
510
511 function refresh() {
512 return fetch('/guardian/api/state?site=' + encodeURIComponent(S.site))
513 .then(function (r) { return r.json(); })
514 .then(function (s) { if (s && !s.error) { S = s; T = s.strings || T; renderAll(); } })
515 .then(loadFeed).then(loadFollowReqs);
516 }
517
518 // ── 2. Adopt ───────────────────────────────────────────────────────────
519 var form = document.getElementById('adopt-form');
520 var input = document.getElementById('adopt-handle');
521 var adoptBtn = document.getElementById('adopt-btn');
522 var msg = document.getElementById('adopt-msg');
523 function setMsg(text, isErr) { msg.hidden = false; msg.className = 'g-msg' + (isErr ? ' err' : ''); msg.textContent = text; }
524
525 form.addEventListener('submit', function (ev) {
526 ev.preventDefault();
527 var handle = input.value.trim();
528 if (!handle) return;
529 adoptBtn.disabled = true;
530 setMsg(T.sending || '…', false);
531 fetch('/guardian/adopt', {
532 method: 'POST', headers: { 'Content-Type': 'application/json' },
533 body: JSON.stringify({ handle: handle, site: S.site }),
534 }).then(function (r) { return r.json().then(function (j) { return { ok: r.ok, j: j }; }); })
535 .then(function (res) {
536 adoptBtn.disabled = false;
537 if (res.ok) {
538 input.value = '';
539 // Always refresh: the offer is recorded even if delivery is still
540 // in flight. Show it under "Verzonden aanvragen".
541 setMsg(res.j.delivered === false ? T.sent_retry : T.sent, false);
542 refresh();
543 } else {
544 setMsg((res.j.error === 'not_found' ? T.not_found : T.failed) , true);
545 }
546 })
547 .catch(function () { adoptBtn.disabled = false; setMsg(T.network, true); });
548 });
549
550 // ── Site picker ────────────────────────────────────────────────────────
551 var picker = document.getElementById('site-picker');
552 if (picker) picker.addEventListener('change', function () {
553 location.href = '/guardian?site=' + encodeURIComponent(picker.value);
554 });
555
556 // ── 5. Push ────────────────────────────────────────────────────────────
557 var toggle = document.getElementById('push-toggle');
558 var pmsg = document.getElementById('push-msg');
559 function pushState() {
560 if (!('serviceWorker' in navigator) || !('PushManager' in window)) { toggle.disabled = true; return; }
561 navigator.serviceWorker.register('/sw.js').catch(function () {});
562 navigator.serviceWorker.ready
563 .then(function (reg) { return reg.pushManager.getSubscription(); })
564 .then(function (sub) {
565 toggle.textContent = sub ? toggle.dataset.onLabel : toggle.dataset.offLabel;
566 toggle.dataset.subscribed = sub ? '1' : '';
567 toggle.classList.toggle('is-on', !!sub);
568 });
569 }
570 function urlB64(base64) {
571 var pad = '='.repeat((4 - (base64.length % 4)) % 4);
572 var b = (base64 + pad).replace(/-/g, '+').replace(/_/g, '/');
573 var raw = atob(b); var arr = new Uint8Array(raw.length);
574 for (var i = 0; i < raw.length; i++) arr[i] = raw.charCodeAt(i);
575 return arr;
576 }
577 toggle.addEventListener('click', function () {
578 pmsg.hidden = true;
579 navigator.serviceWorker.ready.then(function (reg) {
580 if (toggle.dataset.subscribed) {
581 reg.pushManager.getSubscription().then(function (sub) {
582 if (!sub) return;
583 fetch('/push/unsubscribe', {
584 method: 'POST', headers: { 'Content-Type': 'application/json' },
585 body: JSON.stringify({ endpoint: sub.endpoint }),
586 }).then(function () { return sub.unsubscribe(); }).then(pushState);
587 });
588 return;
589 }
590 fetch('/push/vapid').then(function (r) { return r.json(); }).then(function (v) {
591 if (!v.publicKey) throw new Error('no key');
592 return reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlB64(v.publicKey) });
593 }).then(function (sub) {
594 return fetch('/push/subscribe', {
595 method: 'POST', headers: { 'Content-Type': 'application/json' },
596 body: JSON.stringify({
597 subscription: sub.toJSON(),
598 alerts: { help: 1, guardian: 1, dm: 1, follow: 0, reply: 0, like: 0, boost: 0 },
599 uaLabel: 'Guardian PWA',
600 }),
601 });
602 }).then(pushState).catch(function (e) {
603 pmsg.hidden = false; pmsg.className = 'g-msg err';
604 pmsg.textContent = (T.push_unavailable || 'Push unavailable') + ': ' + e.message;
605 });
606 });
607 });
608
609 renderAll(); pushState(); loadFeed(); loadFollowReqs();
610 setInterval(refresh, 45000); // live-ish while open
611 } catch (e) {
612 fatal((e && e.message) || String(e));
613 }
614})();
Note: See TracBrowser for help on using the repository browser.