-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathindex.js
More file actions
1613 lines (1504 loc) · 78.1 KB
/
Copy pathindex.js
File metadata and controls
1613 lines (1504 loc) · 78.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createMembraneScene, CUBE_SCALE, MEMBRANE_FOV, MEMBRANE_CAMERA_Z } from './scene.js';
// NOTE: rubiks.js (+ its vendored GLTFLoader / cube-solver / postprocessing tree)
// is imported DYNAMICALLY in ensureRubiks(), NOT statically here. A static import
// would pull that whole subtree into boot.js's eager module graph, evaluated
// before boot() runs — keeping the easter egg off the boot critical path.
import { createSoundDirector } from './sound.js';
import { BLOB_IDS, BLOB_PROFILES, SHAPE_NAMES, TARGET_R } from './cube.js';
// World edge-length of the die's d6 (the cube shape the easter egg replaces):
// a unit BoxGeometry normalized to bounding-sphere TARGET_R, then group-scaled.
// The Rubik's cube body is matched to this — then bumped 20% larger by request.
const DIE_CUBE_EDGE = TARGET_R * (2 / Math.sqrt(3)) * CUBE_SCALE * 1.2;
import { askAgeLabel, askIsOpen, askStatus, askTopic, isAskMine, resolveAskAuthor, askVerbIconSvg, askVerbVars } from '../asks.js';
import { computeIncoming, acknowledgeIncoming } from './calendar-watch.mjs';
import { submitFeedback, FEEDBACK_MIN_LENGTH, FEEDBACK_MAX_LENGTH } from '../supabase-feedback.mjs';
// Headless smoke-test boot tracing (gated on ?smoke=1; no-op for real launches).
// Mirrors boot.js cp(): pinpoints whether the deferred membrane mount blocks.
const __SMOKE = (() => { try { return new URLSearchParams(location.search).has('smoke'); } catch { return false; } })();
const cp = (label) => {
try { window.api?.smokeTrace?.(label); } catch {}
if (__SMOKE) { try { console.error('[smoke-cp] ' + label); } catch {} }
};
function up(s) { return String(s ?? '').toUpperCase(); }
// Remembered die shape, module-scoped so it survives leaving + returning to the
// membrane page (the scene is destroyed/re-mounted but this module stays loaded).
// Restored as the die's starting shape on mount; updated on every morph. The
// Rubik's cube is deliberately NOT persisted — leaving and coming back drops back
// to the shapes (a fresh scene), which is the only way to reset the cube.
let savedFaces = null;
// ── dismissable ambient notifications ──────────────────────────────────────
// The left feed and right agenda are peripheral notification rails. Each card
// carries a quiet dismiss control (hidden at rest, revealed on hover/focus —
// see .mfeed-dismiss / .magenda-dismiss in membrane.css). A dismissed card is
// remembered by a stable per-occurrence key so it stays gone across the
// once-a-minute / on-data re-renders. Occurrence keys embed the item's date,
// so dismissing one calendar instance never suppresses a future recurrence.
//
// Storage is SESSION-scoped on purpose: dismissals reset on the next app
// launch rather than being permanent. We're not committing to "gone forever"
// until we've seen how the affordance gets used — flip the `kind` arg to
// 'local' (below) to make dismissals persist across relaunches.
const DISMISS_X = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
// Calendar-plus glyph for the right-rail "add to calendar" control (Lucide,
// same family as the feed icons). Tinted by the card's --c2-acc in CSS.
const CAL_PLUS = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/><path d="M12 14v4"/><path d="M10 16h4"/></svg>';
// Total close-animation budget (ms) — matches the membrane fold-recede in
// membrane.css (.is-dismissing). The card is removed only after it has fully
// receded into the field, so the dissolve never snaps.
const DISMISS_MS = 460;
function makeDismissStore(key, kind = 'session') {
// Resolve the backing Storage lazily + defensively — sessionStorage can be
// absent/blocked; on failure the Set just lives in memory (still resets on
// reload, which is the session-scoped behavior we want anyway).
const store = () => {
try { return kind === 'local' ? localStorage : sessionStorage; } catch { return null; }
};
let set = new Set();
try {
const s = store();
const raw = s && s.getItem(key);
if (raw) { const arr = JSON.parse(raw); if (Array.isArray(arr)) set = new Set(arr); }
} catch {}
return {
has: (k) => set.has(k),
add(k) {
if (!k || set.has(k)) return;
set.add(k);
// Cap the ledger so a long session can't grow it unbounded; keep the
// most-recent dismissals (newest pushed last).
if (set.size > 400) set = new Set([...set].slice(-400));
try { const s = store(); if (s) s.setItem(key, JSON.stringify([...set])); } catch {}
},
};
}
// Fold a card out — it recedes into the field like the membrane panel does
// (perspective + rotateY, the membrane's signature exit), direction set in CSS
// by the host rail. The element is REMOVED once it has receded, then `done`
// re-renders to reconcile (tail-taper, day groups). Honors reduced-motion by
// collapsing the wait to a tick. Exit styles live on the `.is-dismissing`
// class. Removing-then-rendering also lets renderFeed/renderAgenda skip a
// rebuild while any card is mid-recede (so the fold is never snapped).
// Source-of-truth reduced-motion check: the in-app toggle (data-reduce-motion
// on <html>, what motion.js/ux.js read) OR the OS-level media query.
function prefersReducedMotion() {
try {
if (document.documentElement.getAttribute('data-reduce-motion') === '1') return true;
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
} catch { return false; }
}
// After a notification stream re-renders (the render path replaces innerHTML
// wholesale), slide in ONLY the rows whose stable data-row-key wasn't present
// last pass — so the once-a-minute rebuild doesn't re-animate the whole
// stream. Returns the new key set to store for next time. prevKeys === null
// (first render after mount / switching into the membrane) marks nothing: the
// surface populates instantly on entry, and only cards that arrive WHILE you
// are watching animate in. Honors reduced-motion.
function markEnteringRows(rootEl, prevKeys, selector) {
if (!rootEl) return prevKeys;
const current = new Set();
const reduce = prefersReducedMotion();
rootEl.querySelectorAll(`${selector}[data-row-key]`).forEach((row) => {
const k = row.getAttribute('data-row-key');
if (k == null) return;
current.add(k);
if (prevKeys && !reduce && !prevKeys.has(k)) row.classList.add('is-entering');
});
// Never promote null → empty: if we've never tracked cards and still see
// none (data not loaded yet), stay in the "first render" state so the
// eventual first population is instant, not a stagger-storm.
if (prevKeys === null && current.size === 0) return null;
return current;
}
function dismissCard(el, done) {
if (!el) { done?.(); return; }
let reduce = false;
try { reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches; } catch {}
el.classList.add('is-dismissing');
el.style.pointerEvents = 'none';
setTimeout(() => { try { el.remove(); } catch {} done?.(); }, reduce ? 0 : DISMISS_MS);
}
// Per-blob panel content. `inline` renderer is called with (data) and
// returns the inline-content HTML. cohort intentionally keeps jump-only —
// user explicitly wants peer browsing in the legacy constellation view.
const PANEL_TEMPLATES = {
self: {
eyebrow: 'your shape',
// Title is the user's real name (falls back through the chain).
title: (data) => {
const p = data?.profile || {};
return p.name || p.display_name || p.handle || p.gh_handle || 'unclaimed';
},
// No copy for self — the user's name + avatar are the identity.
copy: '',
// Avatar pinned to the top-right of the card, same row as the title.
headAccessory: (data) => renderAvatar(data?.profile || {}),
stats: [],
inline: (data) => renderSelfInline(data),
actions: [],
},
cohort: {
eyebrow: 'the constellation',
title: 'cohort',
copy: 'every peer perturbs this membrane. pick a lens to read the network.',
stats: [
{ key: 'peers', val: '—', dataKey: 'peerCount' },
{ key: 'online', val: '—', dataKey: 'onlineCount' },
],
// Each constellation lens + the full roster gets a real card you can
// click — replaces the old hair-thin "open network →" links that were
// lost in blank space. Wired in renderPanelFor via [data-const]/[data-shapes].
inline: (data) => renderCohortViews(data),
actions: [],
},
events: {
eyebrow: 'who is here when',
title: 'events',
copy: 'time is the pressure here. a bright contour ring drifts toward now. past sessions recede as scars; upcoming as ridges building under the skin.',
stats: [
{ key: 'this week', val: '—', dataKey: 'eventsThisWeek' },
],
inline: (data) => renderEventsInline(data),
actions: [
{ label: 'open full calendar →', mode: 'calendar' },
{ label: 'program info →', mode: 'program' },
],
},
asks: {
eyebrow: 'open pairings',
title: 'asks',
copy: 'each open ask is a bubbling point of pressure on the surface. fresh asks rise sharp; expiring asks sink back into the membrane.',
stats: [
{ key: 'open', val: '—', dataKey: 'openAskCount', details: (data) => renderAsksInline(data), open: true },
{ key: 'mine', val: '—', dataKey: 'myAskCount' },
{ key: 'ask', label: 'post ask', mode: 'asks', opts: { openComposer: true } },
],
inline: null,
actions: [],
},
};
// ─── per-blob inline renderers ──────────────────────────────────────────
function escHtml(s) {
return String(s ?? '').replace(/[&<>"']/g, (c) => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
}[c]));
}
function isLinkBoundary(ch) {
return !ch || !/[a-z0-9_-]/i.test(ch);
}
function renderEntityLink(entity, label) {
return `<a class="membrane-entity-link" href="#${escHtml(entity.id)}" data-jump-profile="${escHtml(entity.id)}" data-jump-kind="${escHtml(entity.kind || '')}">${escHtml(label)}</a>`;
}
function renderLinkedText(text, entities = []) {
const source = String(text || '');
const options = [];
const seen = new Set();
for (const entity of Array.isArray(entities) ? entities : []) {
if (!entity?.id) continue;
for (const label of [entity.label, entity.name, entity.id]) {
const clean = String(label || '').trim();
const key = clean.toLowerCase();
if (clean.length < 3 || seen.has(key)) continue;
seen.add(key);
options.push({ entity, label: clean, lower: key });
}
}
options.sort((a, b) => b.label.length - a.label.length);
let out = '';
let i = 0;
let last = 0;
const lower = source.toLowerCase();
while (i < source.length) {
const match = options.find((opt) =>
lower.startsWith(opt.lower, i)
&& isLinkBoundary(source[i - 1])
&& isLinkBoundary(source[i + opt.label.length])
);
if (!match) { i += 1; continue; }
out += escHtml(source.slice(last, i));
out += renderEntityLink(match.entity, source.slice(i, i + match.label.length));
i += match.label.length;
last = i;
}
out += escHtml(source.slice(last));
return out;
}
const WD = ['sun','mon','tue','wed','thu','fri','sat'];
const MO = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];
// Minutes-into-day from an "HH:MM" (or "HH:MM–HH:MM", takes the start) label.
// null if there's no clock time (all-day / ongoing items).
function parseDayMinutes(t) {
const m = String(t || '').match(/(\d{1,2}):(\d{2})/);
return m ? (+m[1]) * 60 + (+m[2]) : null;
}
function pad2(n) { return String(n).padStart(2, '0'); }
// Lightweight event categoriser — mirrors the full calendar's c2Category
// (calendar.js) so the ambient agenda cards color-code off the SAME palette
// as the calendar tab. Returns a category key (or 'default'); the actual
// color lives in membrane.css's [data-cat] rules (hexes lifted from
// calendar.css). Kept local + minimal rather than importing the calendar
// module, which carries its whole sheet-parsing surface.
const AGENDA_CATS = [
['review', /demo review|product review|internal .*review/i],
['demo', /demo night|showcase|demo day/i],
['oh', /office hour|pmf check|\bcheck[ -]?point|\b1:1/i],
['salon', /salon/i],
['weekly', /\bweekly\b|what did you do/i],
['coord', /coordinat|attribution/i],
['hack', /\bhack|hackathon|open jam|\bfinals\b|submission|build night/i],
['anarchy', /anarchy|self-organ|no .*program|protected build|team-led/i],
];
function agendaCat(title) {
const t = String(title || '');
for (const [key, re] of AGENDA_CATS) if (re.test(t)) return key;
return 'default';
}
// Per-kind icon for "what's new" feed items so the type reads at a glance.
// Lucide (same set the rail/tabs use): github / git-commit / file-text /
// message-circle / calendar. Colored via the kind's --mfeed-color (muted tint)
// in CSS.
const LUCIDE_OPEN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">';
const FEED_ICON_PATHS = {
release: '<path d="M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4"/><path d="M9 18c-4.51 2-5-2-7-2"/>',
commit: '<circle cx="12" cy="12" r="3"/><line x1="3" x2="9" y1="12" y2="12"/><line x1="15" x2="21" y1="12" y2="12"/>',
transcript: '<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/>',
ask: '<path d="M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"/>',
event: '<path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/>',
// incoming-watch glyphs (keyed by card.icon): clock / user / calendar-plus /
// refresh-cw — for event-soon, person-soon, event-new, event-changed.
clock: '<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>',
user: '<path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>',
plus: '<path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/><path d="M12 14v4"/><path d="M10 16h4"/>',
swap: '<path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/>',
};
function feedIcon(kind) {
const p = FEED_ICON_PATHS[kind];
return p ? `<span class="mfeed-icon">${LUCIDE_OPEN}${p}</svg></span>` : '';
}
function fmtTimeOnly(t) {
const d = new Date(t);
const hr = d.getHours();
const mn = String(d.getMinutes()).padStart(2, '0');
const h12 = ((hr + 11) % 12) + 1;
const ap = hr >= 12 ? 'pm' : 'am';
return `${h12}:${mn}${ap}`;
}
function fmtDayTime(t) {
const d = new Date(t);
return `${WD[d.getDay()]} ${fmtTimeOnly(t)}`;
}
function fmtFullDate(t) {
const d = new Date(t);
const dy = String(d.getDate()).padStart(2, '0');
return `${WD[d.getDay()]} ${MO[d.getMonth()]} ${dy} · ${fmtTimeOnly(t)}`;
}
// Per-kind action verb for the left-feed hover layer — names what a click will
// do (the third interaction layer: glance → hover reveals destination → click
// commits). Terse; the arrow is appended in the row markup.
const FEED_CTA = {
release: 'open release', commit: 'open activity', ask: 'open ask',
event: 'open calendar', transcript: 'open readout',
'event-soon': 'open calendar', 'event-new': 'open calendar',
'event-changed': 'open calendar', 'person-soon': 'open profile',
};
function feedCta(kind) { return FEED_CTA[kind] || 'open'; }
// Build a Google Calendar "add event" template URL from an agenda item. The
// app's shell:openExternal is hard-restricted to http(s) (main.js), so a
// calendar.google.com TEMPLATE link is the one-click path — a data: .ics URL
// would be rejected there. dateStr is 'YYYY-MM-DD'; timeLabel is the agenda
// clock label ("19:00", "19:00–20:00", "all day", or empty).
function gcalDateRange(dateStr, timeLabel) {
const ymd = String(dateStr || '').slice(0, 10).replace(/-/g, '');
if (!/^\d{8}$/.test(ymd)) return null;
const times = String(timeLabel || '').match(/\d{1,2}:\d{2}/g) || [];
if (!times.length) {
// All-day: Google wants an exclusive end date (the following day).
const d = new Date(`${dateStr}T00:00:00`);
if (Number.isNaN(d.getTime())) return null;
const nd = new Date(d.getTime() + 86400000);
return `${ymd}/${nd.getFullYear()}${pad2(nd.getMonth() + 1)}${pad2(nd.getDate())}`;
}
// Emit 6-digit HHMMSS — a single-digit hour like "6:30" must become
// "063000", not "63000", or Google drops the prefilled time — and keep the
// range moving forward when an event crosses midnight (a "23:30" block ends
// on the next calendar day, not earlier the same day).
const toMin = (t) => { const [h, m] = t.split(':').map(Number); return h * 60 + m; };
const fmt = (min) => pad2(Math.floor(min / 60) % 24) + pad2(min % 60) + '00';
const startMin = toMin(times[0]);
let endMin = times[1] ? toMin(times[1]) : startMin + 60; // default 1-hour block
if (endMin <= startMin) endMin += 1440; // wraps past midnight
let endYmd = ymd;
if (endMin >= 1440) {
const d = new Date(`${dateStr}T00:00:00`);
d.setDate(d.getDate() + Math.floor(endMin / 1440));
endYmd = `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}`;
}
return `${ymd}T${fmt(startMin)}/${endYmd}T${fmt(endMin)}`;
}
function calendarAddUrl(title, dateStr, timeLabel) {
const range = gcalDateRange(dateStr, timeLabel);
const params = new URLSearchParams({ action: 'TEMPLATE', text: title || 'event' });
if (range) params.set('dates', range);
params.set('details', 'Added from Shape Rotator OS');
return `https://calendar.google.com/calendar/render?${params.toString()}`;
}
function renderEventsInline(data) {
// Today-only. computeMembraneData (alchemy.js) builds `eventsToday` by
// merging today's timed lines from the Phala calendar GRID (e.g. "19:00
// muse dinner") with cohort.events spans overlapping today (e.g. daily
// tea). We intentionally drop the this-week / upcoming sections — the
// panel answers "what's on right now?" and the full schedule lives in
// the calendar tab.
const today = Array.isArray(data?.eventsToday) ? data.eventsToday : [];
const rows = today.map((it) => {
const dateLabel = it.time || (it.ongoing ? 'today' : '·');
const meta = it.sub || (it.ongoing ? 'ongoing' : '');
return `
<li class="membrane-event-row">
<span class="membrane-event-date">${escHtml(dateLabel)}</span>
<span class="membrane-event-title">${escHtml(it.title || 'untitled')}</span>
<span class="membrane-event-meta">${escHtml(meta)}</span>
</li>`;
}).join('');
return `
<section class="membrane-section membrane-section-today">
<header class="membrane-section-head">
<h3 class="membrane-section-title">today</h3>
<span class="membrane-section-count">${today.length}</span>
</header>
${today.length === 0
? `<p class="membrane-empty">nothing scheduled today.</p>`
: `<ul class="membrane-event-list" role="list">${rows}</ul>`}
</section>`;
}
function renderAsksInline(data) {
const asks = Array.isArray(data?.asksList) ? data.asksList : [];
const people = Array.isArray(data?.peopleList) ? data.peopleList : [];
const askIdentity = { ...(data?.askIdentity || {}), people };
const open = asks.filter(askIsOpen);
if (open.length === 0) {
return `
<div class="membrane-open-asks">
<p class="membrane-empty">no open asks. things are quiet.</p>
</div>`;
}
const rows = open.slice(0, 24).map((a) => {
const title = askTopic(a) || 'untitled ask';
const author = resolveAskAuthor(a, people);
const owner = author ? (author.name || author.record_id) : (a.author || a.owner || '');
const mine = isAskMine(a, askIdentity);
const ago = askAgeLabel(a);
const verb = a.verb || 'ask';
const verbGlyph = Array.from(String(verb).trim())[0] || '·';
const verbVars = askVerbVars(verbGlyph);
const status = askStatus(a);
const statusBadge = status === 'open' && a._expired
? '<span class="membrane-ask-status membrane-ask-status-fading">fading</span>'
: status !== 'open'
? `<span class="membrane-ask-status">${escHtml(status)}</span>`
: '';
const chips = (Array.isArray(a.skill_areas) ? a.skill_areas : [])
.slice(0, 5)
.map((s) => `<span class="membrane-ask-chip">${escHtml(s)}</span>`)
.join('');
return `
<li class="membrane-ask-item" data-expired="${a._expired ? '1' : '0'}">
<details class="membrane-ask-row">
<summary class="membrane-ask-summary">
<span class="membrane-ask-verb${verbVars ? ' has-verb-color' : ''}"${verbVars ? ` style="${verbVars}"` : ''} title="${escHtml(verb)}">${askVerbIconSvg(verbGlyph) || escHtml(verbGlyph)}</span>
<span class="membrane-ask-body">
<span class="membrane-ask-title">${escHtml(title)}</span>
<span class="membrane-ask-meta">
${mine ? '<span class="ask-status-mine">mine</span> · ' : ''}${escHtml(owner)}${ago ? ' · ' + escHtml(ago) : ''}${statusBadge ? ' · ' + statusBadge : ''}
</span>
</span>
</summary>
<div class="membrane-ask-detail">
${chips ? `<div class="membrane-ask-chips">${chips}</div>` : ''}
</div>
</details>
</li>`;
}).join('');
return `
<div class="membrane-open-asks">
<ul class="membrane-ask-list" role="list">${rows}</ul>
</div>`;
}
// Tiny stable string hash for deterministic sigils (local; no crypto).
function sealHash(str) {
let h = 2166136261 >>> 0;
const s = String(str || 'shape');
for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
return h >>> 0;
}
// A deterministic geometric SIGIL drawn from the seed — your "shape" as a
// mark (cypherpunk: key→glyph; new-age: a personal seal). Monochrome; the
// oxide stroke + a tiny hand-touched rotation come from CSS. Drawn inside a
// vesica frame by renderSeal().
function renderSigilSVG(seed) {
let h = sealHash(seed);
const rnd = () => { h = (Math.imul(h, 1664525) + 1013904223) >>> 0; return h / 4294967296; };
const cx = 50, cy = 64, R = 21;
const n = 5 + Math.floor(rnd() * 4); // 5–8 nodes
const pts = [];
for (let i = 0; i < n; i++) {
const a = (i / n) * Math.PI * 2 - Math.PI / 2;
pts.push([cx + Math.cos(a) * R, cy + Math.sin(a) * R]);
}
const order = [...Array(n).keys()];
for (let i = n - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [order[i], order[j]] = [order[j], order[i]]; }
let d = '';
order.forEach((idx, i) => { const [x, y] = pts[idx]; d += `${i === 0 ? 'M' : 'L'}${x.toFixed(1)} ${y.toFixed(1)} `; });
d += 'Z';
const dots = pts.map(([x, y]) => `<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="1.7"/>`).join('');
return `<svg class="seal-sigil" viewBox="0 0 100 128" aria-hidden="true"><path class="seal-sigil-line" d="${d}"/><g class="seal-sigil-dots">${dots}</g></svg>`;
}
// The seal: a vesica-piscis mandorla framing the identity mark. When the
// user is claimed + has an avatar, the avatar IS the charged seal (a face);
// otherwise their deterministic sigil sits inside, awaiting the strike.
function renderSeal(profile, seed) {
const avatar = profile.avatarUrl || null;
const inner = avatar
? `<img class="seal-face" style="clip-path:url(#seal-vesica-clip)" src="${escHtml(avatar)}" alt="" referrerpolicy="no-referrer"
onerror="this.remove();this.parentElement.classList.add('no-face')" />`
: '';
return `
<div class="seal ${avatar ? 'has-face' : 'no-face'}">
<svg class="seal-vesica" viewBox="0 0 100 128" aria-hidden="true">
<defs><clipPath id="seal-vesica-clip" clipPathUnits="objectBoundingBox">
<path d="M.5 .04 C.2 .28 .2 .72 .5 .96 C.8 .72 .8 .28 .5 .04 Z"/>
</clipPath></defs>
<path class="seal-vesica-path" d="M50 6 C20 36 20 92 50 122 C80 92 80 36 50 6 Z"/>
</svg>
${renderSigilSVG(seed)}
${inner}
</div>`;
}
// Self profile as a SEAL — your shape as a sigil in a vesica, charged by
// your tonic. Claiming is a rite: strike your seal, cross the threshold.
// Blends shape-rotator geometry + alchemy + cypherpunk sovereignty +
// milady-intimate copy. (Container keeps .crewid for fill/foil/scan +
// the data-crewid-claim wiring.)
function renderSelfCard(data, tpl) {
const profile = data?.profile || {};
const connections = Array.isArray(data?.connections) ? data.connections : [];
const name = profile.name || profile.display_name || profile.handle || profile.gh_handle || profile.record_id || 'unclaimed';
const claimed = data?.claimed === true;
const handle = profile.handle || profile.gh_handle || (profile.links && profile.links.github) || '';
const role = profile.role || profile.title || (profile.is_mentor ? 'mentor' : '');
const circle = profile.team || (profile.kind === 'team' ? profile.record_id : '') || '—';
const edges = data?.edgeCount ?? 0;
const seed = profile.record_id || handle || name;
const readout = (k, v) => `<div class="crewid-row"><span class="crewid-k">${escHtml(k)}</span><span class="crewid-v">${escHtml(String(v))}</span></div>`;
const commsRows = connections.slice(0, 24).map((c) => `
<li class="crewid-comm" data-jump-profile="${escHtml(c.record_id)}" data-jump-kind="${escHtml(c.kind)}" tabindex="0" role="button" aria-label="open ${escHtml(c.name)}">
<span class="crewid-comm-rel">${escHtml(c.edgeType || 'link')}</span>
<span class="crewid-comm-name">${escHtml(c.name)}</span>
<span class="crewid-comm-meta">${escHtml(c.team || c.role || '')}</span>
</li>`).join('');
// Unclaimed → nothing to edit; the primary move is the rite. Claimed →
// full action set.
const actions = (tpl?.actions || [])
.filter((a) => claimed || a.mode !== 'profile')
.map((a) => `<button type="button" class="crewid-action" data-jump-mode="${a.mode}">${a.label}</button>`).join('');
const claimCta = claimed ? '' : `
<button type="button" class="crewid-claim seal-strike" data-crewid-claim="1">
<span class="cc-glyph" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 13V8.5C14 7 15 7 15 5a3 3 0 0 0-6 0c0 2 1 2 1 3.5V13"/><path d="M20 15.5a2.5 2.5 0 0 0-2.5-2.5h-11A2.5 2.5 0 0 0 4 15.5V17a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1z"/><path d="M5 22h14"/></svg></span>
<span class="cc-text">
<span class="cc-title">strike your seal</span>
<span class="cc-sub">identify · cross the threshold →</span>
</span>
</button>`;
// One intimate line under the name — sincere, not winking.
const tagline = claimed
? (role ? `${escHtml(role.toLowerCase())} · here` : 'here, and seen')
: 'a shape not yet struck';
return `
<article class="crewid seal-card ${claimed ? 'is-claimed' : 'is-unclaimed'}">
<div class="crewid-foil" aria-hidden="true"></div>
<div class="crewid-scan" aria-hidden="true"></div>
<div class="crewid-band">
<span class="crewid-issuer"><svg class="issuer-glyph" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg> shape rotator · alchemy</span>
<span class="crewid-doc">${claimed ? 'sealed' : 'unsealed'}</span>
</div>
<div class="seal-hero">
${renderSeal(profile, seed)}
<span class="crewid-eyebrow">your shape</span>
<h2 class="crewid-name">${escHtml(name)}</h2>
<span class="seal-tagline">${escHtml(tagline)}</span>
${claimed && handle ? `<span class="seal-handle">@${escHtml(handle)}</span>` : ''}
</div>
${claimCta}
<div class="crewid-readouts seal-readouts">
${readout('edges', edges)}
${readout('circle', circle)}
</div>
<div class="crewid-comms">
<div class="crewid-comms-head">
<span class="crewid-comms-title">constellation</span>
<span class="crewid-comms-count">${connections.length}</span>
</div>
${connections.length === 0
? `<div class="crewid-empty"><span class="ce-status">∅</span><span class="ce-msg">no edges yet — once you join a circle, your shape finds its others.</span></div>`
: `<ul class="crewid-comm-list" role="list">${commsRows}</ul>`}
</div>
<div class="seal-sovereign" aria-hidden="false">stored on this device · nothing leaves</div>
<div class="crewid-actions">${actions}</div>
</article>`;
}
function renderNetworkSection(data, connections = []) {
const edgeCount = String(data?.edgeCount ?? connections.length ?? 0);
const edgeSource = data?.edgeCountSource || (connections.length ? 'resolved self graph' : 'cohort graph');
const connectionCount = connections.length;
const tip = connectionCount > 0
? `${edgeCount} membrane edge${Number(edgeCount) === 1 ? '' : 's'}; ${connectionCount} named connection${connectionCount === 1 ? '' : 's'} available. source: ${edgeSource}.`
: `${edgeCount} membrane edge${Number(edgeCount) === 1 ? '' : 's'}; no named connections resolved yet. source: ${edgeSource}.`;
const countLabel = `${edgeCount} · ${connectionCount} connection${connectionCount === 1 ? '' : 's'}`;
const ordered = [...connections].sort((a, b) => {
const order = { 'teammate': 0, 'depends on': 1, 'depended by': 2 };
return (order[a.edgeType] ?? 9) - (order[b.edgeType] ?? 9);
});
const connectionRows = ordered.slice(0, 24).map((c) => `
<li class="membrane-event-row membrane-connection-row"
data-jump-profile="${escHtml(c.record_id)}"
data-jump-kind="${escHtml(c.kind)}"
tabindex="0" role="button"
aria-label="open ${escHtml(c.name)} in cohort view">
<span class="membrane-event-date">${escHtml(c.edgeType)}</span>
<span class="membrane-event-title">${escHtml(c.name)}</span>
<span class="membrane-event-meta">${escHtml(c.team || c.role || '')}</span>
</li>`).join('');
const body = connectionCount === 0
? `<p class="membrane-network-empty">no named connections yet — once this profile resolves to teammates, dependencies, or a shared cluster, named records appear here.</p>`
: `<ul class="membrane-event-list" role="list">${connectionRows}</ul>`;
return `
<details class="membrane-network">
<summary class="membrane-network-summary">
<span class="membrane-network-title">edges</span>
<span class="membrane-network-count" data-tip="${escHtml(tip)}">${escHtml(countLabel)}</span>
</summary>
<div class="membrane-network-detail">
${body}
</div>
</details>`;
}
function renderSelfInline(data) {
const profile = data?.profile || {};
const connections = Array.isArray(data?.connections) ? data.connections : [];
const read = data?.read || null;
const team = profile.team || (profile.kind === 'team' ? profile.record_id : '') || '';
const role = profile.role || profile.title || '';
const handle = profile.handle || profile.gh_handle || '';
const bio = profile.bio || profile.description || profile.about || '';
const truncatedBio = bio.length > 300 ? bio.slice(0, 280).trim() + '…' : bio;
// Identity meta strip — handle / team / role. Avatar + name already
// live in the panel head; this is the "rest" of the identity stack.
const metaRows = [];
if (handle) {
metaRows.push(`
<li class="membrane-event-row">
<span class="membrane-event-date">handle</span>
<span class="membrane-event-title">@${escHtml(handle)}</span>
<span class="membrane-event-meta">${escHtml(role)}</span>
</li>`);
}
if (team) {
metaRows.push(`
<li class="membrane-event-row">
<span class="membrane-event-date">team</span>
<span class="membrane-event-title">${escHtml(team)}</span>
<span class="membrane-event-meta"></span>
</li>`);
}
const identityBlock = (metaRows.length > 0 || truncatedBio) ? `
<section class="membrane-section">
${metaRows.length > 0 ? `<ul class="membrane-event-list" role="list">${metaRows.join('')}</ul>` : ''}
${truncatedBio ? `<p class="membrane-bio-line">${escHtml(truncatedBio)}</p>` : ''}
</section>` : '';
const readBlock = read?.text ? `
<section class="membrane-section membrane-section-system">
<header class="membrane-section-head">
<h3 class="membrane-section-title"${read.sourceDetail ? ` title="${escHtml(read.sourceDetail)}"` : ''}>system read</h3>
</header>
<p class="membrane-system-line${read.tone === 'uncalibrated' ? ' is-uncalibrated' : ''}">${renderLinkedText(read.text, read.entities)}</p>
</section>` : '';
return renderNetworkSection(data, connections) + identityBlock + readBlock;
}
// Cohort panel = a set of lenses onto the network. Each is a real card
// (glyph + name + one-line read) that jumps into the constellation in that
// sub-view, plus one card for the full roster. The mini line-glyphs echo
// each lens's actual shape (overlapping circles = clusters, a small DAG =
// dependencies, a rising scatter = journey, a dot-grid = the roster).
const COHORT_VIEWS = [
{
nav: 'const', mode: 'clusters',
title: 'clusters', desc: 'teams grouped by shared synergy',
glyph: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="1"/><path d="M20.2 20.2c2.04-2.03.02-7.36-4.5-11.9-4.54-4.52-9.87-6.54-11.9-4.5-2.04 2.03-.02 7.36 4.5 11.9 4.54 4.52 9.87 6.54 11.9 4.5Z"/><path d="M15.7 15.7c4.52-4.54 6.54-9.87 4.5-11.9-2.03-2.04-7.36-.02-11.9 4.5-4.52 4.54-6.54 9.87-4.5 11.9 2.03 2.04 7.36.02 11.9-4.5Z"/></svg>',
},
{
nav: 'const', mode: 'dependencies',
title: 'dependencies', desc: 'who relies on whom',
glyph: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z"/><rect x="3" y="14" width="7" height="7" rx="1"/><circle cx="17.5" cy="17.5" r="3.5"/></svg>',
},
{
nav: 'const', mode: 'journey',
title: 'journey', desc: 'every team’s PMF arc',
glyph: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z"/><path d="M15 5.764v15"/><path d="M9 3.236v15"/></svg>',
},
{
nav: 'shapes',
title: 'the full cohort', desc: 'every team + project, up close',
glyph: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><path d="M16 3.128a4 4 0 0 1 0 7.744"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><circle cx="9" cy="7" r="4"/></svg>',
},
];
function renderCohortViews() {
const cards = COHORT_VIEWS.map((v) => {
const attr = v.nav === 'shapes' ? 'data-shapes="1"' : `data-const="${v.mode}"`;
return `
<button type="button" class="cohort-view-card" ${attr}>
<span class="cvc-glyph" aria-hidden="true">${v.glyph}</span>
<span class="cvc-text">
<span class="cvc-title">${v.title}</span>
<span class="cvc-desc">${v.desc}</span>
</span>
<span class="cvc-arrow" aria-hidden="true">→</span>
</button>`;
}).join('');
return `<div class="cohort-view-grid">${cards}</div>`;
}
// ─── panel scaffolding ───────────────────────────────────────────────────
function renderStatList(template, data = {}) {
return template.stats.map((s) => {
const v = s.dataKey && data[s.dataKey] != null ? data[s.dataKey] : s.val;
if (typeof s.details === 'function') {
return `
<li class="membrane-panel-list-details">
<details class="mpl-details"${s.open ? ' open' : ''}>
<summary class="mpl-details-summary">
<span class="mpl-key">${escHtml(s.key)}</span>
<span class="mpl-detail-meta">
<span class="mpl-val">${escHtml(v)}</span>
<span class="mpl-caret" aria-hidden="true"></span>
</span>
</summary>
${s.details(data)}
</details>
</li>`;
}
if (s.mode) {
const opts = s.opts ? ` data-jump-opts="${escHtml(JSON.stringify(s.opts))}"` : '';
return `
<li class="membrane-panel-list-action">
<button type="button" class="mpl-action" data-jump-mode="${escHtml(s.mode)}"${opts}>
<span class="mpl-key">${escHtml(s.key)}</span>
<span class="mpl-val">${escHtml(s.label || s.val || 'open')}</span>
</button>
</li>`;
}
return `<li><span class="mpl-key">${escHtml(s.key)}</span><span class="mpl-val">${escHtml(v)}</span></li>`;
}).join('');
}
function renderActionList(template) {
return template.actions.map((a) =>
`<li><button type="button" class="mpa-btn" data-jump-mode="${a.mode}">${a.label}</button></li>`
).join('');
}
function renderPanelInner(template, data = {}) {
const inlineHtml = template.inline ? template.inline(data) : '';
const title = typeof template.title === 'function' ? template.title(data) : template.title;
const accessory = template.headAccessory ? template.headAccessory(data) : '';
const actionsHtml = renderActionList(template);
const statsHtml = Array.isArray(template.stats) && template.stats.length
? `<ul class="membrane-panel-list" role="list">${renderStatList(template, data)}</ul>`
: '';
return `
<header class="membrane-panel-head${accessory ? ' membrane-panel-head--with-accessory' : ''}">
<div class="membrane-panel-head-text">
<span class="membrane-panel-eyebrow">${template.eyebrow}</span>
<h2 class="membrane-panel-title">${escHtml(title)}</h2>
</div>
${accessory}
</header>
${template.copy ? `<p class="membrane-panel-note">${template.copy}</p>` : ''}
${statsHtml}
${inlineHtml}
${actionsHtml ? `<ul class="membrane-panel-actions" role="list">${actionsHtml}</ul>` : ''}
`;
}
// Avatar renderer — shared between the panel head and any other surface
// that wants the user's face. Falls back to initials when no GitHub link
// or the image fails (img onerror flips the parent data attribute).
function renderAvatar(profile) {
const name = profile.name || profile.display_name || profile.handle || profile.gh_handle || '?';
const avatarUrl = profile.avatarUrl || null;
const initials = (name || '?')
.split(/[\s_-]+/).map((s) => s[0] || '').filter(Boolean).slice(0, 2).join('').toUpperCase();
if (avatarUrl) {
return `
<div class="membrane-avatar membrane-avatar--head" data-has-img="true">
<img class="membrane-avatar-img"
src="${escHtml(avatarUrl)}"
alt="${escHtml(name)} avatar"
onerror="this.parentElement.removeAttribute('data-has-img'); this.remove();" />
<span class="membrane-avatar-initials" aria-hidden="true">${escHtml(initials)}</span>
</div>`;
}
return `
<div class="membrane-avatar membrane-avatar--head">
<span class="membrane-avatar-initials" aria-hidden="true">${escHtml(initials)}</span>
</div>`;
}
// ── OS feedback + idea box ──────────────────────────────────────────────────
// A small anonymous feedback pill pinned to the bottom-center window edge.
// Clicking it lifts the card a few pixels and blooms a textarea open; once more
// than 5 characters are typed the send button enables and posts ONE anonymous
// row to Supabase (message + coarse app context only — see
// ../supabase-feedback.mjs). Self-contained: returns a dispose() the membrane
// controller calls on teardown to clear timers + the outside-click listener
// (the DOM itself is dropped when the host innerHTML is cleared).
function setupFeedbackBox(container) {
const root = container.querySelector('[data-feedback]');
if (!root) return { dispose() {} };
const toggle = root.querySelector('[data-feedback-toggle]');
const input = root.querySelector('[data-feedback-input]');
const sendBtn = root.querySelector('[data-feedback-send]');
const statusEl = root.querySelector('[data-feedback-status]');
// Coarse, non-identifying app context, resolved once and best-effort: a
// failure just leaves both columns null (both are nullable in the table).
let appCtx = { appVersion: null, platform: null };
try {
Promise.resolve(window.api?.getAppInfo?.()).then((info) => {
if (info && typeof info === 'object') {
appCtx = { appVersion: info.version || null, platform: info.platform || null };
}
}).catch(() => {});
} catch {}
let cooldownTimer = null;
let collapseTimer = null;
let sending = false;
function setOpen(open) {
root.classList.toggle('is-open', open);
toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
if (open) setTimeout(() => { try { input.focus(); } catch {} }, 80);
}
function refreshSend() {
const valid = input.value.trim().length >= FEEDBACK_MIN_LENGTH;
sendBtn.disabled = sending || cooldownTimer != null || !valid;
}
function setStatus(text, tone) {
statusEl.textContent = text || '';
if (tone) statusEl.dataset.tone = tone; else delete statusEl.dataset.tone;
}
toggle.addEventListener('click', () => {
const open = !root.classList.contains('is-open');
if (collapseTimer) { clearTimeout(collapseTimer); collapseTimer = null; }
setOpen(open);
if (open) { setStatus('', null); refreshSend(); }
});
input.addEventListener('input', () => {
if (statusEl.textContent) setStatus('', null);
refreshSend();
});
async function send() {
if (sendBtn.disabled || sending) return;
sending = true;
refreshSend();
setStatus('sending…', 'pending');
const res = await submitFeedback({
message: input.value,
appVersion: appCtx.appVersion,
platform: appCtx.platform,
});
sending = false;
if (res && res.ok) {
input.value = '';
setStatus('thanks — sent.', 'ok');
// Brief client-side cooldown so the public insert endpoint can't be held
// down; the server-side length CHECK + RLS are the real guard.
cooldownTimer = setTimeout(() => { cooldownTimer = null; refreshSend(); }, 5000);
refreshSend();
collapseTimer = setTimeout(() => { setOpen(false); collapseTimer = null; }, 1500);
} else {
setStatus(
res && res.error === 'unconfigured'
? 'feedback isn’t set up here.'
: 'couldn’t send — try again.',
'err',
);
refreshSend();
}
}
sendBtn.addEventListener('click', send);
// Collapse on a click anywhere outside the box (only while open). Bound to the
// membrane host, not document, so it cannot outlive this mount; also removed
// in dispose() for good measure.
function onOutside(ev) {
if (!root.classList.contains('is-open')) return;
if (root.contains(ev.target)) return;
setOpen(false);
}
container.addEventListener('mousedown', onOutside);
return {
dispose() {
if (cooldownTimer) clearTimeout(cooldownTimer);
if (collapseTimer) clearTimeout(collapseTimer);
container.removeEventListener('mousedown', onOutside);
},
};
}
export function mountMembrane(container, opts = {}) {
cp('membrane:mount-start');
container.classList.add('membrane-host');
// Always start showing the shapes, never the Rubik's cube — clear any stale
// reveal state left on the (reused) container from a previous visit, so the
// cube overlay and its Scramble/Reset controls don't linger after coming back.
container.classList.remove('membrane-rubiks-active');
// The panel is retired — start folded so it never flashes in before the
// fold state below settles (see the "fold state" note further down).
container.classList.add('membrane-folded');
container.innerHTML = `
<div class="membrane-stage">
<div class="membrane-atmosphere" aria-hidden="true">
<div class="ma-throne-presence"></div>
</div>
<!-- Not aria-hidden: these rails hold operable, labelled controls (open
the calendar / a profile, dismiss). Hiding them from the a11y tree
while leaving focusable buttons inside is a broken contract — they
are named regions instead so keyboard/SR users reach them. -->
<div class="membrane-agenda" data-agenda role="region" aria-label="today's agenda"></div>
<div class="membrane-feed" data-feed role="region" aria-label="what's new"></div>
<canvas class="membrane-canvas"></canvas>
<canvas class="membrane-rubiks-canvas" aria-hidden="true"></canvas>
<!-- Bright light flash that blankets the die<->Rubik's swap. Fired ONLY by
revealRubiks()/hideRubiks() — the normal shape morphs never touch it. -->
<div class="membrane-flash" aria-hidden="true"></div>
<div class="membrane-rubiks-controls" aria-hidden="true">
<button type="button" class="primary" data-rubiks-scramble aria-label="Scramble">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M2 18h1.4c1.3 0 2.5-.6 3.3-1.7l6.1-8.6c.7-1.1 2-1.7 3.3-1.7H22"/>
<path d="m18 2 4 4-4 4"/>
<path d="M2 6h1.9c1.5 0 2.9.9 3.6 2.2"/>
<path d="M22 18h-5.9c-1.3 0-2.6-.7-3.3-1.8l-.5-.8"/>
<path d="m18 14 4 4-4 4"/>
</svg>
</button>
<button type="button" data-rubiks-reset aria-label="Reset">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/>
<path d="M3 3v5h5"/>
</svg>
</button>
</div>
<div class="membrane-shape-name" aria-hidden="true">
<span class="msn-name" data-shape-name></span>
<span class="msn-meta" data-shape-meta></span>
</div>
<aside class="membrane-panel" data-active-blob="self">
<div class="membrane-panel-content"></div>
<footer class="membrane-panel-foot">
<div class="membrane-foot-left">
<div class="membrane-blob-dots" role="tablist" aria-label="blobs">
${BLOB_IDS.map((id) => `
<button type="button" class="membrane-blob-dot" data-blob-jump="${id}" aria-label="${BLOB_PROFILES[id].label}">
<span class="mbd-label">${BLOB_PROFILES[id].label}</span>
</button>
`).join('')}
<button type="button" class="membrane-blob-dot membrane-footer-dot" data-footer-mode="profile" aria-label="edit profile">
<span class="mbd-label">edit profile</span>
</button>
<button type="button" class="membrane-blob-dot membrane-footer-dot" data-footer-mode="onboarding" aria-label="onboarding">
<span class="mbd-label">onboarding</span>
</button>
</div>
<div class="membrane-field-row" data-membrane-field-row></div>
</div>
<button type="button" class="membrane-sound-toggle" data-membrane-sound aria-pressed="false">
<span class="mst-glyph" aria-hidden="true"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 10v3"/><path d="M6 6v11"/><path d="M10 3v18"/><path d="M14 8v7"/><path d="M18 5v13"/><path d="M22 10v3"/></svg></span>
<span class="mst-label">hum</span>
<span class="mst-state">off</span>
</button>
</footer>
</aside>