Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them.
Page: /drakestapleton/aien-sovereign-core/blob/main/crates/spark-cockpit-rs/static/hive-wall.module.js
# aien-sovereign-core
Autonomous sovereign intelligence engine and runtime core for NVIDIA DGX Spark
Brought by drakestapleton
Sign in to star 0 stars 0 watching
About Files History Releases Proposed changes Issues For developers
branch `main` Branches Tags History
`aien-sovereign-core / crates / spark-cockpit-rs / static / hive-wall.module.js`
5969 lines · 277394 bytes Raw Blame History
1 export const HEX_DIRECTIONS = Object.freeze([
2 Object.freeze([1, 0]),
3 Object.freeze([1, -1]),
4 Object.freeze([0, -1]),
5 Object.freeze([-1, 0]),
6 Object.freeze([-1, 1]),
7 Object.freeze([0, 1]),
8 ]);
9
10 export const HEX_DIRECTION_LABELS = Object.freeze([
11 "east",
12 "northeast",
13 "northwest",
14 "west",
15 "southwest",
16 "southeast",
17 ]);
18
19 const PLACEMENT_INTENTS = new Set(["independent", "join", "branch", "meet"]);
20 const CONVERSATION_HUES = Object.freeze([34, 52, 76, 105, 137, 168, 196, 218, 244, 271, 298, 326, 8]);
21
22 export const WALL_LIMITS = Object.freeze({
23 maxRadius: 512,
24 bodyCharacters: 600,
25 chunkSize: 16,
26 // The floor is only the hard stop. The usable floor is computed per wall by
27 // fitZoom() so "zoom all the way out" always means "the whole Hive fits",
28 // never an arbitrary percentage that leaves combs off screen.
29 minZoom: 0.08,
30 maxZoom: 1.8,
31 });
32
33 // Reading text stops being possible long before the hexes stop being useful
34 // shapes, so the Wall drops detail in tiers instead of shrinking unreadable
35 // paragraphs. Each tier is a CSS contract, not a re-render.
36 export const DETAIL_TIERS = Object.freeze([
37 Object.freeze({ id: "full", minZoom: 0.62 }),
38 Object.freeze({ id: "compact", minZoom: 0.34 }),
39 Object.freeze({ id: "dot", minZoom: 0 }),
40 ]);
41
42 const SQRT_3 = Math.sqrt(3);
43 const DEFAULT_HEX_RADIUS = 88;
44 const WORLD_MARGIN = 170;
45 // Cap the chunk fan-out one viewport can request. Zoomed all the way out a
46 // large wall would otherwise ask for every chunk at once; the nearest chunks
47 // to the camera load first and the rest arrive as the viewer moves.
48 const MAX_VISIBLE_CHUNKS = 24;
49 const ZOOM_STEP = 1.28;
50 const PAN_KEY_STEP = 140;
51 const DRAFT_KEY = "hive_wall_draft_v1";
52 const EDIT_DRAFT_KEY = "hive_wall_edit_draft_v1";
53 const DRAFT_HANDOFF_KEY = "hive_wall_draft_handoff_v1";
54 const DRAFT_HANDOFF_TTL_MS = 20 * 60 * 1000;
55 const SEEN_KEY = "hive_wall_seen_v1";
56 const MODE_KEY = "hive_wall_mode_v1";
57 const MAX_CACHED_CHUNKS = 32;
58 const MAX_CACHED_CELLS = 5_000;
59 const MAX_LIST_RECONCILE_EVENTS = 256;
60
61 export function cellKey(q, r) {
62 return `${Number(q)}:${Number(r)}`;
63 }
64
65 export function hexDistance(q, r, otherQ = 0, otherR = 0) {
66 const dq = Number(q) - Number(otherQ);
67 const dr = Number(r) - Number(otherR);
68 return Math.max(Math.abs(dq), Math.abs(dr), Math.abs(dq + dr));
69 }
70
71 export function axialToPixel(q, r, radius = DEFAULT_HEX_RADIUS) {
72 return {
73 x: radius * SQRT_3 * (Number(q) + Number(r) / 2),
74 y: radius * 1.5 * Number(r),
75 };
76 }
77
78 export function roundAxial(q, r) {
79 let cubeX = Number(q);
80 let cubeZ = Number(r);
81 let cubeY = -cubeX - cubeZ;
82 let roundedX = Math.round(cubeX);
83 let roundedY = Math.round(cubeY);
84 let roundedZ = Math.round(cubeZ);
85 const dx = Math.abs(roundedX - cubeX);
86 const dy = Math.abs(roundedY - cubeY);
87 const dz = Math.abs(roundedZ - cubeZ);
88 if (dx > dy && dx > dz) roundedX = -roundedY - roundedZ;
89 else if (dy > dz) roundedY = -roundedX - roundedZ;
90 else roundedZ = -roundedX - roundedY;
91 return { q: roundedX, r: roundedZ };
92 }
93
94 export function pixelToAxial(x, y, radius = DEFAULT_HEX_RADIUS) {
95 const q = (SQRT_3 / 3 * Number(x) - Number(y) / 3) / radius;
96 const r = (2 / 3 * Number(y)) / radius;
97 return roundAxial(q, r);
98 }
99
100 export function neighbors(q, r) {
101 return HEX_DIRECTIONS.map(([dq, dr]) => ({ q: Number(q) + dq, r: Number(r) + dr }));
102 }
103
104 export function chunkFor(q, r, size = WALL_LIMITS.chunkSize) {
105 const qMin = Math.floor(Number(q) / size) * size;
106 const rMin = Math.floor(Number(r) / size) * size;
107 return Object.freeze({
108 key: `${qMin}:${rMin}`,
109 qMin,
110 qMax: qMin + size - 1,
111 rMin,
112 rMax: rMin + size - 1,
113 });
114 }
115
116 export function conversationChoices(cells, q, r, conversations = null) {
117 return adjacentConversationGroups(cells, q, r, conversations)
118 .map((group) => group.anchors[0]?.cell)
119 .filter(Boolean);
120 }
121
122 export function adjacentConversationGroups(cells, q, r, conversations = null) {
123 const groups = new Map();
124 neighbors(q, r).forEach((coordinate, direction) => {
125 const cell = cells instanceof Map ? cells.get(cellKey(coordinate.q, coordinate.r)) : null;
126 if (!cell?.conversationId || (cell.status && cell.status !== "visible")) return;
127 if (conversations instanceof Map) {
128 const conversation = conversations.get(cell.conversationId);
129 if (!conversation || conversation.status !== "open") return;
130 }
131 let group = groups.get(cell.conversationId);
132 if (!group) {
133 group = { conversationId: cell.conversationId, anchors: [] };
134 groups.set(cell.conversationId, group);
135 }
136 group.anchors.push({ cell, direction, directionLabel: HEX_DIRECTION_LABELS[direction] });
137 });
138 return [...groups.values()];
139 }
140
141 export function canonicalAnchorIds(anchorCellIds) {
142 return [...new Set((anchorCellIds || []).filter((value) => typeof value === "string" && value))].sort();
143 }
144
145 export function reconcileAccessibleListWindow(existing, incoming, conversationId = null) {
146 const byId = new Map();
147 for (const cell of [...(existing || []), ...(incoming || [])]) {
148 if (cell && cell.id) byId.set(cell.id, cell);
149 }
150 return [...byId.values()].sort(conversationId
151 ? (left, right) => left.seq - right.seq
152 : (left, right) => right.seq - left.seq);
153 }
154
155 export function accessibleListRefreshFrontier({
156 reset,
157 priorCells,
158 incomingCells,
159 priorBeforeSeq,
160 priorHasMore,
161 nextBeforeSeq,
162 nextHasMore,
163 }) {
164 const priorIds = new Set((priorCells || []).map((cell) => cell?.id).filter(Boolean));
165 const overlapsLoaded = Boolean(reset && priorIds.size
166 && (incomingCells || []).some((cell) => priorIds.has(cell?.id)));
167 return overlapsLoaded
168 ? { beforeSeq: priorBeforeSeq, hasMore: priorHasMore }
169 : { beforeSeq: nextBeforeSeq, hasMore: nextHasMore };
170 }
171
172 function clamp(value, minimum, maximum) {
173 return Math.min(maximum, Math.max(minimum, value));
174 }
175
176 function escapeSelectorValue(value) {
177 if (globalThis.CSS && typeof globalThis.CSS.escape === "function") return globalThis.CSS.escape(String(value));
178 return String(value).replace(/["\\]/g, "\\$&");
179 }
180
181 function setTextIfChanged(node, value) {
182 if (!node) return;
183 const next = String(value == null ? "" : value);
184 if (node.textContent !== next) node.textContent = next;
185 }
186
187 function validCoordinate(q, r, radius = WALL_LIMITS.maxRadius) {
188 return Number.isInteger(q) && Number.isInteger(r) && hexDistance(q, r) <= radius;
189 }
190
191 function safeJson(storage, key, fallback) {
192 try {
193 const parsed = JSON.parse(storage.getItem(key));
194 return parsed == null ? fallback : parsed;
195 } catch {
196 return fallback;
197 }
198 }
199
200 function safeSet(storage, key, value) {
201 try {
202 const encoded = JSON.stringify(value);
203 storage.setItem(key, encoded);
204 return storage.getItem(key) === encoded && storage.__hivePersistent !== false;
205 } catch {
206 // Private browsing and full storage must not break the wall.
207 return false;
208 }
209 }
210
211 function memoryStorage() {
212 const values = new Map();
213 return {
214 __hivePersistent: false,
215 getItem(key) { return values.has(key) ? values.get(key) : null; },
216 setItem(key, value) { values.set(key, String(value)); },
217 removeItem(key) { values.delete(key); },
218 };
219 }
220
221 function availableStorage(provided) {
222 if (provided) return provided;
223 try {
224 const storage = globalThis.localStorage;
225 const probe = "__hive_wall_storage_probe__";
226 storage.setItem(probe, "1");
227 storage.removeItem(probe);
228 return storage;
229 } catch {
230 return memoryStorage();
231 }
232 }
233
234 function availableSessionStorage(provided) {
235 if (provided) return provided;
236 try {
237 const storage = globalThis.sessionStorage;
238 const probe = "__hive_wall_session_probe__";
239 storage.setItem(probe, "1");
240 storage.removeItem(probe);
241 return storage;
242 } catch {
243 return memoryStorage();
244 }
245 }
246
247 function normalizedPlacementDraft(source, resetRequestId = false) {
248 if (!source || !validCoordinate(Number(source.q), Number(source.r))) return null;
249 const body = typeof source.body === "string"
250 ? [...source.body].slice(0, WALL_LIMITS.bodyCharacters).join("")
251 : "";
252 const inferredIntent = source.intent && PLACEMENT_INTENTS.has(source.intent)
253 ? source.intent
254 : source.conversationId ? "join" : "independent";
255 return {
256 q: Number(source.q),
257 r: Number(source.r),
258 body,
259 requestId: resetRequestId ? null : (typeof source.requestId === "string" ? source.requestId : null),
260 conversationId: typeof source.conversationId === "string" ? source.conversationId : null,
261 replyToId: typeof source.replyToId === "string" ? source.replyToId : null,
262 intent: inferredIntent,
263 anchorCellIds: canonicalAnchorIds(source.anchorCellIds),
264 choiceMade: source.choiceMade !== false,
265 choiceExplicit: source.choiceExplicit === true,
266 requiresConversationChoice: source.requiresConversationChoice === true,
267 mode: typeof source.mode === "string" ? source.mode : null,
268 updatedAt: Number(source.updatedAt) || Date.now(),
269 };
270 }
271
272 function randomRequestId() {
273 if (globalThis.crypto && typeof globalThis.crypto.randomUUID === "function") {
274 return globalThis.crypto.randomUUID();
275 }
276 const bytes = new Uint8Array(16);
277 if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
278 globalThis.crypto.getRandomValues(bytes);
279 } else {
280 for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
281 }
282 bytes[6] = (bytes[6] & 15) | 64;
283 bytes[8] = (bytes[8] & 63) | 128;
284 const hex = [...bytes].map((value) => value.toString(16).padStart(2, "0"));
285 return `${hex.slice(0, 4).join("")}-${hex.slice(4, 6).join("")}-${hex.slice(6, 8).join("")}-${hex.slice(8, 10).join("")}-${hex.slice(10).join("")}`;
286 }
287
288 function hueFor(value) {
289 let hash = `2166136261`;
290 for (const character of String(value || "hive")) {
291 hash ^= character.charCodeAt(0);
292 hash = Math.imul(hash, `16777619`);
293 }
294 return CONVERSATION_HUES[Math.abs(hash) % CONVERSATION_HUES.length];
295 }
296
297 function patternFor(value) {
298 let hash = 0;
299 for (const character of String(value || "hive")) hash = Math.imul(hash ^ character.charCodeAt(0), `16777619`);
300 return Math.abs(hash) % 4;
301 }
302
303 function timeLabel(timestamp) {
304 const value = Number(timestamp);
305 if (!Number.isFinite(value)) return "";
306 const elapsed = Date.now() - value;
307 if (elapsed < 60_000) return "just now";
308 if (elapsed < 3_600_000) return `${Math.max(1, Math.floor(elapsed / 60_000))}m`;
309 if (elapsed < 86_400_000) return `${Math.floor(elapsed / 3_600_000)}h`;
310 return new Date(value).toLocaleDateString(undefined, { month: "short", day: "numeric" });
311 }
312
313 function statusText(cell) {
314 if (cell.viewerHidden) return "Hidden after your private report";
315 if (cell.status === "author_removed") return "Message removed by its author";
316 if (cell.status === "quarantined") return "Message under review";
317 if (cell.status === "moderator_removed") return "Message removed by the Hive watch";
318 return cell.body || "";
319 }
320
321 function isEditableField(target) {
322 return target instanceof Element && Boolean(target.closest("input, textarea, select, [contenteditable='true']"));
323 }
324
325 function staticMarkup() {
326 return `
327
328
The Hive conversation wall
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
One wall · countless conversations
348
The page is the Hive.
349
Conversations grow beside each other instead of being sorted into a feed.
350
351 Start here · three simple steps
352
353
Pick a comb.Tap a message to read it, or choose Add a comb to begin.
354
Choose a direction.Continue nearby, start a branch, or let conversations meet.
355
Write and place it.Your message stays attached to the path you chose.
356
357
Drag to move around. Pinch or use the zoom controls to change the view. Prefer a straight reading order? Choose Read as list.
358
359
360
361 THE HIVE
362 Loading the wall…
363
364
Loading the shared Wall.
365
Use arrow keys to explore. For all six directions use E northeast, D east, C southeast, Z southwest, A west, and Q northwest. Hold Shift with an arrow key to glide the view without moving your place. Press plus to zoom in, minus to zoom out, and 0 to pull back until the whole Hive fits. Press Enter to open or write. Escape cancels choosing a branch.
366
367
368
369
370
371
+
372
373
374
375
376
377
378
379
380
381
Accessible wall view
Every comb with its connections
382
383
384
385
386
387
388
389
Click any open place in the honeycomb to leave a message.
390
391
392
418
419
461
462
485 `;
486 }
487
488 export class HiveWallController {
489 constructor(options = {}) {
490 if (!options.root) throw new Error("HiveWall needs a root element.");
491 if (!options.backend) throw new Error("HiveWall needs the shared backend.");
492 this.root = options.root;
493 this.backend = options.backend;
494 this.getUser = typeof options.getUser === "function" ? options.getUser : () => null;
495 this.requestIdentity = typeof options.requestIdentity === "function" ? options.requestIdentity : () => {};
496 this.toast = typeof options.toast === "function" ? options.toast : () => {};
497 this.onCellLink = typeof options.onCellLink === "function" ? options.onCellLink : null;
498 this.onPlaced = typeof options.onPlaced === "function" ? options.onPlaced : null;
499 this.storage = availableStorage(options.storage);
500 this.handoffStorage = availableSessionStorage(options.handoffStorage);
501 this.hexRadius = Number(options.hexRadius) || DEFAULT_HEX_RADIUS;
502 this.cells = new Map();
503 this.cellsById = new Map();
504 this.conversations = new Map();
505 this.nodes = new Map();
506 this.connectionNodes = new Map();
507 this.loadedChunks = new Set();
508 this.chunkAccess = new Map();
509 this.cellChunks = new Map();
510 this.dirtyChunks = new Set();
511 this.inflightChunks = new Map();
512 this.visibleChunkKeys = new Set();
513 this.pendingEvents = new Map();
514 this.retryEvents = new Map();
515 // One obligation per changed comb in the retained accessible-list window.
516 // These retry with bounded backoff until an authoritative cell read
517 // succeeds. Route/identity changes discard the retained list itself, so no
518 // stale hidden window can later reappear under a different context.
519 this.listReconcileEvents = new Map();
520 this.consumingEvents = new Map();
521 this.realtimeDrainQueue = new Map();
522 this.realtimeDrainPromise = null;
523 this.realtimeDrainDirty = false;
524 this.seenRealtimeEvents = new Set();
525 this.forceRefreshOnActivate = false;
526 this.publicCacheGeneration = 0;
527 this.wallWindowRevision = 0;
528 this.bounds = {
529 revision: 0,
530 viewerRevision: 0,
531 radius: 5,
532 messageCount: 0,
533 readOnly: true,
534 updatedAt: 0,
535 };
536 this.mode = this.storage && this.storage.getItem(MODE_KEY) === "list" ? "list" : "wall";
537 this.zoom = 1;
538 this.cameraX = 0;
539 // The Wall is a map the viewer flies over, so the camera owns both axes.
540 // Vertical movement used to be document scroll, which made "zoom out and
541 // look around" impossible once the plane was shorter than the page.
542 this.cameraY = 0;
543 this.world = { halfWidth: 0, halfHeight: 0, width: 0, height: 0, originX: 0, originY: 0 };
544 this.detailTier = null;
545 this.pinch = null;
546 this.selected = { q: 0, r: 0 };
547 this.selectedCellKey = null;
548 this.readerCell = null;
549 this.reportRequest = null;
550 this.operatorCaseRequest = null;
551 this.watchActionRequest = null;
552 this.composeState = null;
553 this.growthIntent = null;
554 this.placementIntentGeneration = 0;
555 this.focusGeneration = 0;
556 this.composeGeneration = 0;
557 this.readerGeneration = 0;
558 this.watchGeneration = 0;
559 this.watchQueueRequestGeneration = 0;
560 this.watchCaseRequestGeneration = 0;
561 this.watchActionGeneration = 0;
562 this.operatorProbeGeneration = 0;
563 this.scopeRequestGeneration = 0;
564 this.composeBusy = false;
565 this.readerBusy = false;
566 this.operator = null;
567 this.watchCase = null;
568 this.watchLoadingGeneration = 0;
569 this.watchBusy = false;
570 this.watchCases = [];
571 this.watchCursor = null;
572 this.watchHasMore = false;
573 this.watchPollTimer = null;
574 this.active = false;
575 this.mounted = false;
576 this.unsubscribe = null;
577 this.realtimeTeardown = Promise.resolve();
578 this.pollTimer = null;
579 this.eventTimer = null;
580 this.eventRetryTimer = null;
581 this.listReconcileTimer = null;
582 this.renderFrame = null;
583 this.glideTimer = null;
584 this.momentumFrame = null;
585 this.viewportRefreshPromise = null;
586 this.viewportRefreshDirty = false;
587 this.viewportRefreshForce = false;
588 this.focusFrame = null;
589 this.growthFitFrame = null;
590 this.announceFrame = null;
591 this.eventAbort = null;
592 this.dialogOpeners = new Map();
593 this.dialogFocusAnchors = new Map();
594 this.pointer = null;
595 this.activePointers = new Map();
596 this.suppressCellClickUntil = 0;
597 this.suppressBackdropClick = null;
598 this.listCells = [];
599 this.listBeforeSeq = null;
600 this.listHasMore = true;
601 this.listConversationId = null;
602 this.listWindowRevision = 0;
603 this.listRequestGeneration = 0;
604 this.boundsRequestGeneration = 0;
605 this.boundsSuccessGeneration = 0;
606 this.lastGoodAt = 0;
607 this.hasActivated = false;
608 this.activationGeneration = 0;
609 this.realtimeGeneration = 0;
610 this.transportState = "polling";
611 this.dataStale = false;
612 this.storageScope = null;
613 this.identityGeneration = 0;
614 this.seen = new Set();
615 this.draft = null;
616 this.editDraft = null;
617 this.draftPersistenceFailed = false;
618 this.editDraftPersistenceFailed = false;
619 this.draftFromHandoff = false;
620 this.quarantinedDrafts = new Map();
621 this.orphanedPrivateDraft = null;
622 this.viewportWidth = window.innerWidth;
623 this.boundViewport = (event) => {
624 this.updateVisualViewport();
625 const nextWidth = window.innerWidth;
626 if (this.growthIntent) {
627 this.viewportWidth = nextWidth;
628 if (this.growthFitFrame) cancelAnimationFrame(this.growthFitFrame);
629 this.growthFitFrame = requestAnimationFrame(() => {
630 this.growthFitFrame = null;
631 this.fitGrowthIntent();
632 });
633 this.scheduleViewport();
634 return;
635 }
636 // Page scroll moves the stage through the document but no longer changes
637 // which part of the wall the camera sees, so it needs no camera work and
638 // must not schedule any: this listener also fires from scrolls the wall
639 // itself performs.
640 if (event?.type === "scroll") return;
641 this.viewportWidth = nextWidth;
642 // A rotation or keyboard dismissal changes how much world fits, which
643 // changes the usable zoom floor. Re-settle the camera before repainting
644 // so a viewer who was zoomed all the way out stays zoomed all the way
645 // out instead of being left below the new floor.
646 this.setZoom(this.zoom, null, { announce: false });
647 };
648 this.boundVisualViewport = () => this.boundViewport({ type: "visualviewport" });
649 this.boundVisibility = () => {
650 if (document.visibilityState === "visible" && this.active) {
651 if (this.mode === "list") this.refreshList(true);
652 else this.refreshVisible(true);
653 this.wakeListReconciliation();
654 }
655 };
656 this.boundOnline = () => {
657 this.setConnectionState(navigator.onLine ? (this.dataStale ? "stale" : this.transportState) : "offline");
658 if (navigator.onLine) this.wakeListReconciliation();
659 };
660 }
661
662 mount() {
663 if (this.mounted) return;
664 this.eventAbort = new AbortController();
665 this.root.innerHTML = staticMarkup();
666 this.wall = this.root.querySelector(".honey-wall");
667 this.stage = this.root.querySelector("[data-wall-stage]");
668 this.plane = this.root.querySelector("[data-wall-plane]");
669 this.cellLayer = this.root.querySelector("[data-wall-cells]");
670 this.connectionLayer = this.root.querySelector("[data-wall-connections]");
671 this.growthSlots = this.root.querySelector("[data-wall-growth-slots]");
672 this.growthTray = this.root.querySelector("[data-wall-growth-tray]");
673 this.target = this.root.querySelector("[data-wall-target]");
674 this.live = this.root.querySelector("[data-wall-live]");
675 this.summary = this.root.querySelector("[data-wall-summary]");
676 this.newCount = this.root.querySelector("[data-wall-new-count]");
677 this.zoomOutput = this.root.querySelector("[data-wall-zoom]");
678 this.list = this.root.querySelector("[data-wall-list]");
679 this.listItems = this.root.querySelector("[data-wall-list-items]");
680 this.compose = this.root.querySelector("[data-wall-compose]");
681 this.composeBody = this.root.querySelector("[data-wall-compose-body]");
682 this.composeError = this.root.querySelector("[data-wall-compose-error]");
683 this.reader = this.root.querySelector("[data-wall-reader]");
684 this.watch = this.root.querySelector("[data-wall-watch]");
685 this.watchQueue = this.root.querySelector("[data-wall-watch-queue]");
686 this.watchDetail = this.root.querySelector("[data-wall-watch-detail]");
687 this.watchReason = this.root.querySelector("[data-wall-watch-reason]");
688 this.bindEvents();
689 this.applyMode();
690 this.updateWorldSize();
691 this.updateTarget();
692 this.mounted = true;
693 }
694
695 bindEvents() {
696 const listener = { signal: this.eventAbort.signal };
697 this.root.addEventListener("click", (event) => this.handleClick(event), listener);
698 this.root.addEventListener("keydown", (event) => {
699 if (event.key === "Escape" && this.growthIntent && !event.defaultPrevented) {
700 event.preventDefault();
701 this.cancelGrowthIntent();
702 }
703 }, listener);
704 this.stage.addEventListener("keydown", (event) => this.handleStageKey(event), listener);
705 this.stage.addEventListener("pointerdown", (event) => this.handlePointerDown(event), listener);
706 this.stage.addEventListener("pointermove", (event) => this.handlePointerMove(event), listener);
707 this.stage.addEventListener("pointerup", (event) => this.handlePointerUp(event), listener);
708 this.stage.addEventListener("pointercancel", (event) => this.cancelPointerGesture(event), listener);
709 this.stage.addEventListener("wheel", (event) => this.handleWheel(event), { ...listener, passive: false });
710 this.stage.addEventListener("dblclick", (event) => this.handleDoubleClick(event), listener);
711 this.stage.addEventListener("focusin", (event) => this.handleStageFocus(event), listener);
712 if (typeof globalThis.ResizeObserver === "function") {
713 this.trayObserver = new globalThis.ResizeObserver(() => {
714 const height = this.growthTray?.getBoundingClientRect?.().height || 0;
715 // Only a real height change matters, and only while a picker is open.
716 // Refitting on equal heights would spin against the viewport listener.
717 if (!this.growthIntent || Math.abs(height - (this.lastGrowthTrayHeight || 0)) < 1) return;
718 this.lastGrowthTrayHeight = height;
719 this.scheduleGrowthFit();
720 });
721 this.trayObserver.observe(this.growthTray);
722 }
723 this.root.querySelector("[data-wall-compose-form]").addEventListener("submit", (event) => {
724 event.preventDefault();
725 void this.submitCompose();
726 }, listener);
727 this.composeBody.addEventListener("input", () => {
728 this.root.querySelector("[data-wall-compose-count]").textContent = `${[...this.composeBody.value].length} / 600`;
729 if (this.composeState) this.composeState.requestId = null;
730 const persisted = this.composeState?.editing ? this.saveEditDraft() : this.saveDraft();
731 if (persisted !== false) this.hideComposeError();
732 }, listener);
733 this.composeBody.addEventListener("focus", () => this.updateVisualViewport(), listener);
734 this.root.querySelector("[data-wall-report-form]").addEventListener("submit", (event) => {
735 event.preventDefault();
736 void this.submitReport();
737 }, listener);
738 this.root.querySelector("[data-wall-report-reason]").addEventListener("change", () => {
739 this.reportRequest = null;
740 }, listener);
741 this.root.querySelector("[data-wall-operator-reason]").addEventListener("input", () => {
742 this.operatorCaseRequest = null;
743 }, listener);
744 this.root.querySelector("[data-wall-watch-reason]").addEventListener("input", () => {
745 this.watchActionRequest = null;
746 }, listener);
747 this.root.querySelector("[data-wall-operator-form]").addEventListener("submit", (event) => {
748 event.preventDefault();
749 void this.submitOperatorCase();
750 }, listener);
751 this.root.querySelector("[data-wall-compose-suggestion]").addEventListener("click", () => this.acceptComposeSuggestion(), listener);
752 for (const dialog of [this.compose, this.reader, this.watch]) {
753 dialog.addEventListener("cancel", (event) => {
754 event.preventDefault();
755 this.closeDialog(dialog);
756 }, listener);
757 dialog.addEventListener("click", (event) => {
758 if (event.target !== dialog) return;
759 const suppressed = this.suppressBackdropClick;
760 if (suppressed?.dialog === dialog && Date.now() <= suppressed.until) {
761 this.suppressBackdropClick = null;
762 event.preventDefault();
763 event.stopPropagation();
764 return;
765 }
766 if (suppressed?.dialog === dialog) this.suppressBackdropClick = null;
767 this.closeDialog(dialog);
768 }, listener);
769 }
770 }
771
772 async activate(options = {}) {
773 this.mount();
774 if (this.active) {
775 if (options.cellId) await this.focusCell(options.cellId);
776 return;
777 }
778 const generation = ++this.activationGeneration;
779 this.active = true;
780 this.wall.classList.add("is-active");
781 await this.syncStorageScope(false);
782 if (!this.isActivationCurrent(generation)) return;
783 window.addEventListener("resize", this.boundViewport, { passive: true });
784 window.addEventListener("scroll", this.boundViewport, { passive: true });
785 window.visualViewport?.addEventListener?.("resize", this.boundVisualViewport, { passive: true });
786 window.visualViewport?.addEventListener?.("scroll", this.boundVisualViewport, { passive: true });
787 window.addEventListener("online", this.boundOnline);
788 window.addEventListener("offline", this.boundOnline);
789 document.addEventListener("visibilitychange", this.boundVisibility);
790 this.updateVisualViewport();
791 try {
792 await this.startRealtime();
793 } catch {
794 this.unsubscribe = null;
795 this.transportState = "polling";
796 this.setConnectionState(navigator.onLine ? "polling" : "offline");
797 }
798 if (!this.isActivationCurrent(generation)) return;
799 await this.refreshBounds();
800 if (!this.isActivationCurrent(generation)) return;
801 const firstActivation = !this.hasActivated && !options.cellId;
802 if (firstActivation) this.revealCoordinate(0, 0, "auto");
803 this.hasActivated = true;
804 const forceVisibleRefresh = this.forceRefreshOnActivate;
805 this.forceRefreshOnActivate = false;
806 await this.refreshVisible(forceVisibleRefresh);
807 if (!this.isActivationCurrent(generation)) return;
808 if (firstActivation && this.mode === "wall" && this.viewportWidth <= 760) {
809 this.frameInitialPhoneView();
810 }
811 void this.probeOperator();
812 if (this.mode === "list") {
813 await this.refreshList(true);
814 if (!this.isActivationCurrent(generation)) return;
815 this.wakeListReconciliation();
816 }
817 if (this.pollTimer) window.clearInterval(this.pollTimer);
818 this.pollTimer = window.setInterval(() => {
819 if (this.active && document.visibilityState === "visible") {
820 if (this.mode === "list") void this.refreshList(true);
821 else void this.refreshVisible(true);
822 if (this.operator) void this.probeOperator();
823 }
824 }, 45_000);
825 if (options.cellId) {
826 await this.focusCell(options.cellId);
827 if (!this.isActivationCurrent(generation)) return;
828 }
829 if (this.draft && validCoordinate(this.draft.q, this.draft.r, WALL_LIMITS.maxRadius)) {
830 this.announce("Your unfinished wall message is still here.");
831 }
832 this.updateResumeDraftAction();
833 }
834
835 deactivate() {
836 this.activationGeneration += 1;
837 this.realtimeGeneration += 1;
838 this.scopeRequestGeneration += 1;
839 this.invalidatePrivateOperations({ saveDraft: true, closeDialogs: true });
840 if (!this.active) return;
841 this.active = false;
842 this.wall.classList.remove("is-active");
843 window.removeEventListener("resize", this.boundViewport);
844 window.removeEventListener("scroll", this.boundViewport);
845 window.visualViewport?.removeEventListener?.("resize", this.boundVisualViewport);
846 window.visualViewport?.removeEventListener?.("scroll", this.boundVisualViewport);
847 window.removeEventListener("online", this.boundOnline);
848 window.removeEventListener("offline", this.boundOnline);
849 document.removeEventListener("visibilitychange", this.boundVisibility);
850 this.cancelGrowthIntent({ restoreFocus: false, announce: false, restoreView: false });
851 void this.stopRealtime();
852 if (this.pollTimer) window.clearInterval(this.pollTimer);
853 if (this.eventTimer) window.clearTimeout(this.eventTimer);
854 if (this.eventRetryTimer) window.clearTimeout(this.eventRetryTimer);
855 if (this.listReconcileTimer) window.clearTimeout(this.listReconcileTimer);
856 if (this.renderFrame) cancelAnimationFrame(this.renderFrame);
857 if (this.focusFrame) cancelAnimationFrame(this.focusFrame);
858 if (this.growthFitFrame) cancelAnimationFrame(this.growthFitFrame);
859 this.growthFitFrame = null;
860 for (const event of [...this.pendingEvents.values(), ...this.retryEvents.values(), ...this.realtimeDrainQueue.values(), ...this.consumingEvents.values()]) {
861 if (event?.eventKey) this.seenRealtimeEvents.delete(event.eventKey);
862 if (validCoordinate(Number(event?.q), Number(event?.r))) {
863 const changedChunk = chunkFor(Number(event.q), Number(event.r));
864 this.loadedChunks.delete(changedChunk.key);
865 if (this.inflightChunks.has(changedChunk.key)) this.dirtyChunks.add(changedChunk.key);
866 }
867 }
868 // Realtime is intentionally disconnected while the Wall route is inactive,
869 // so every return must revalidate cached visible chunks even if no queued
870 // event was present at the moment of deactivation.
871 this.forceRefreshOnActivate = true;
872 this.pollTimer = null;
873 this.eventTimer = null;
874 this.eventRetryTimer = null;
875 this.listReconcileTimer = null;
876 this.renderFrame = null;
877 this.stopMomentum();
878 this.viewportRefreshPromise = null;
879 this.viewportRefreshDirty = false;
880 this.viewportRefreshForce = false;
881 this.realtimeDrainPromise = null;
882 this.realtimeDrainDirty = false;
883 this.focusFrame = null;
884 this.pendingEvents.clear();
885 this.retryEvents.clear();
886 this.realtimeDrainQueue?.clear?.();
887 this.consumingEvents.clear();
888 this.discardAccessibleListWindow();
889 }
890
891 isActivationCurrent(generation) {
892 return this.active && this.mounted && generation === this.activationGeneration;
893 }
894
895 isContextCurrent(activationGeneration, identityGeneration) {
896 return this.isActivationCurrent(activationGeneration)
897 && identityGeneration === this.identityGeneration;
898 }
899
900 closeDialogImmediately(dialog) {
901 if (!dialog) return;
902 if (typeof dialog.close === "function" && dialog.open) dialog.close();
903 else dialog.removeAttribute("open");
904 this.dialogOpeners.delete(dialog);
905 this.dialogFocusAnchors.delete(dialog);
906 }
907
908 invalidatePrivateOperations(options = {}) {
909 if (options.saveDraft && this.composeState) {
910 if (this.composeState.editing) this.saveEditDraft();
911 else this.saveDraft();
912 }
913 this.placementIntentGeneration += 1;
914 this.focusGeneration += 1;
915 this.composeGeneration += 1;
916 this.readerGeneration += 1;
917 this.watchGeneration += 1;
918 this.watchQueueRequestGeneration += 1;
919 this.watchCaseRequestGeneration += 1;
920 this.watchActionGeneration += 1;
921 this.operatorProbeGeneration += 1;
922 this.listRequestGeneration += 1;
923 this.composeBusy = false;
924 this.readerBusy = false;
925 this.watchBusy = false;
926 this.watchLoadingGeneration = 0;
927 this.composeState = null;
928 this.readerCell = null;
929 this.reportRequest = null;
930 this.operatorCaseRequest = null;
931 this.watchActionRequest = null;
932 this.watchCase = null;
933 this.operator = null;
934 const watchButton = this.root.querySelector?.('[data-wall-action="watch"]');
935 if (watchButton) watchButton.hidden = true;
936 if (this.watchPollTimer) window.clearInterval(this.watchPollTimer);
937 this.watchPollTimer = null;
938 this.watchCases = [];
939 this.watchCursor = null;
940 this.watchHasMore = false;
941 this.clearWatchDom();
942 if (options.closeDialogs) {
943 this.closeDialogImmediately(this.compose);
944 this.closeDialogImmediately(this.reader);
945 this.closeDialogImmediately(this.watch);
946 }
947 }
948
949 preserveUnpersistedDrafts(scope = this.storageScope) {
950 const hadPlacement = Boolean(this.draft || (this.composeState && !this.composeState.editing));
951 const hadEdit = Boolean(this.editDraft || this.composeState?.editing);
952 const placementSafe = !hadPlacement || this.saveDraft() !== false;
953 const editSafe = !hadEdit || this.saveEditDraft() !== false;
954 if (placementSafe && editSafe) return true;
955 const quarantined = {
956 draft: !placementSafe ? normalizedPlacementDraft(this.draft, true) : null,
957 editDraft: !editSafe && this.editDraft ? { ...this.editDraft } : null,
958 };
959 if (scope) {
960 const prior = this.quarantinedDrafts.get(scope) || {};
961 this.quarantinedDrafts.set(scope, {
962 draft: quarantined.draft || prior.draft || null,
963 editDraft: quarantined.editDraft || prior.editDraft || null,
964 });
965 } else {
966 this.orphanedPrivateDraft = quarantined;
967 }
968 return false;
969 }
970
971 resetIdentityState() {
972 if (!this.mounted) return;
973 this.publicCacheGeneration += 1;
974 this.preserveUnpersistedDrafts(this.storageScope);
975 this.invalidatePrivateOperations({ saveDraft: false, closeDialogs: true });
976 this.cancelGrowthIntent({ restoreFocus: false, announce: false, restoreView: false });
977 this.identityGeneration += 1;
978 this.scopeRequestGeneration += 1;
979 this.storageScope = null;
980 this.cells.clear();
981 this.cellsById.clear();
982 this.conversations.clear();
983 for (const node of this.nodes.values()) node.remove();
984 this.nodes.clear();
985 for (const line of this.connectionNodes?.values?.() || []) line.remove();
986 this.connectionNodes?.clear?.();
987 this.loadedChunks.clear();
988 this.chunkAccess.clear();
989 this.cellChunks.clear();
990 this.dirtyChunks.clear();
991 this.inflightChunks.clear();
992 this.pendingEvents.clear();
993 this.retryEvents.clear();
994 this.listReconcileEvents.clear();
995 this.realtimeDrainQueue?.clear?.();
996 this.consumingEvents.clear();
997 this.realtimeDrainPromise = null;
998 this.realtimeDrainDirty = false;
999 if (this.eventTimer) window.clearTimeout(this.eventTimer);
1000 if (this.eventRetryTimer) window.clearTimeout(this.eventRetryTimer);
1001 if (this.listReconcileTimer) window.clearTimeout(this.listReconcileTimer);
1002 this.eventTimer = null;
1003 this.eventRetryTimer = null;
1004 this.listReconcileTimer = null;
1005 this.seenRealtimeEvents.clear();
1006 this.listCells = [];
1007 this.listBeforeSeq = null;
1008 this.listHasMore = true;
1009 this.listConversationId = null;
1010 this.listWindowRevision = 0;
1011 this.wallWindowRevision = 0;
1012 this.bounds = { ...this.bounds, viewerRevision: 0 };
1013 this.listRequestGeneration += 1;
1014 this.seen.clear();
1015 this.draft = null;
1016 this.editDraft = null;
1017 this.draftPersistenceFailed = false;
1018 this.editDraftPersistenceFailed = false;
1019 this.draftFromHandoff = false;
1020 this.selected = { q: 0, r: 0 };
1021 this.cameraX = 0;
1022 this.hasActivated = false;
1023 if (this.composeBody) this.composeBody.value = "";
1024 this.hideComposeError();
1025 const reportReason = this.root.querySelector?.("[data-wall-report-reason]");
1026 const operatorReason = this.root.querySelector?.("[data-wall-operator-reason]");
1027 if (reportReason) reportReason.value = "";
1028 if (operatorReason) operatorReason.value = "";
1029 if (this.watchReason) this.watchReason.value = "";
1030 this.listItems?.replaceChildren();
1031 this.render();
1032 this.updateNewCount();
1033 this.updateTarget();
1034 this.updatePlaneTransform();
1035 this.updateResumeDraftAction();
1036 }
1037
1038 clearWatchDom() {
1039 this.watchActionRequest = null;
1040 if (this.watchQueue) this.watchQueue.replaceChildren();
1041 if (this.watchDetail) this.watchDetail.hidden = true;
1042 const clearText = (selector) => {
1043 const element = this.root.querySelector?.(selector);
1044 if (element) element.textContent = "";
1045 };
1046 clearText("[data-wall-watch-status]");
1047 clearText("[data-wall-watch-meta]");
1048 clearText("[data-wall-watch-evidence]");
1049 clearText("[data-wall-watch-current]");
1050 const reports = this.root.querySelector?.("[data-wall-watch-reports]");
1051 const events = this.root.querySelector?.("[data-wall-watch-events]");
1052 const actions = this.root.querySelector?.("[data-wall-watch-actions]");
1053 const more = this.root.querySelector?.("[data-wall-watch-more]");
1054 reports?.replaceChildren();
1055 events?.replaceChildren();
1056 actions?.replaceChildren();
1057 if (more) more.hidden = true;
1058 if (this.watchReason) this.watchReason.value = "";
1059 }
1060
1061 destroy() {
1062 this.deactivate();
1063 this.eventAbort?.abort();
1064 this.eventAbort = null;
1065 if (this.renderFrame) cancelAnimationFrame(this.renderFrame);
1066 if (this.focusFrame) cancelAnimationFrame(this.focusFrame);
1067 if (this.announceFrame) cancelAnimationFrame(this.announceFrame);
1068 if (this.eventTimer) window.clearTimeout(this.eventTimer);
1069 if (this.eventRetryTimer) window.clearTimeout(this.eventRetryTimer);
1070 if (this.listReconcileTimer) window.clearTimeout(this.listReconcileTimer);
1071 if (this.glideTimer) window.clearTimeout(this.glideTimer);
1072 this.trayObserver?.disconnect?.();
1073 this.trayObserver = null;
1074 this.stopMomentum();
1075 this.renderFrame = null;
1076 this.glideTimer = null;
1077 this.focusFrame = null;
1078 this.announceFrame = null;
1079 this.eventTimer = null;
1080 this.eventRetryTimer = null;
1081 this.listReconcileTimer = null;
1082 this.pendingEvents.clear();
1083 this.retryEvents.clear();
1084 this.listReconcileEvents.clear();
1085 this.realtimeDrainQueue?.clear?.();
1086 this.consumingEvents.clear();
1087 this.inflightChunks.clear();
1088 this.connectionNodes?.clear?.();
1089 this.nodes.clear();
1090 this.root.replaceChildren();
1091 this.mounted = false;
1092 }
1093
1094 prepareIdentityHandoff() {
1095 if (this.composeState?.editing || this.editDraft) {
1096 if (this.saveEditDraft() === false) {
1097 this.toast("Account switching stopped because this edit draft cannot be persisted safely.");
1098 return false;
1099 }
1100 if (!this.draft && (!this.composeState || this.composeState.editing)) {
1101 this.cancelIdentityHandoff();
1102 return null;
1103 }
1104 }
1105 const persisted = this.composeState && !this.composeState.editing ? this.saveDraft() : (this.draft ? this.saveDraft() : true);
1106 const draft = normalizedPlacementDraft(this.draft, true);
1107 if (!draft) {
1108 this.cancelIdentityHandoff();
1109 return null;
1110 }
1111 if (!this.storageScope) {
1112 this.toast("This draft is not attached to a verified Hive identity yet. Finish or copy it before switching accounts.");
1113 return false;
1114 }
1115 const approved = window.confirm("Carry your unfinished Wall draft into the saved account you are opening? Choose Cancel to keep it private to the current Hive identity.");
1116 if (!approved) {
1117 this.cancelIdentityHandoff();
1118 if (persisted === false) {
1119 this.toast("Account switching stopped because the draft cannot stay safely with this identity in this browser.");
1120 return false;
1121 }
1122 this.toast("The draft stays private to the Hive identity that started it.");
1123 return null;
1124 }
1125 const stored = safeSet(this.handoffStorage, DRAFT_HANDOFF_KEY, {
1126 fromScope: this.storageScope,
1127 createdAt: Date.now(),
1128 sourceApproved: true,
1129 draft,
1130 });
1131 if (!stored) this.toast("This browser could not safely hand the draft to another account. It remains with the current identity.");
1132 return stored;
1133 }
1134
1135 prepareIdentityExit() {
1136 this.cancelIdentityHandoff();
1137 if (!this.draft && !this.editDraft && !this.composeState) return true;
1138 if (!this.storageScope || !this.preserveUnpersistedDrafts(this.storageScope)) {
1139 this.toast("Starting fresh stopped because this browser cannot keep the unfinished Wall draft private to this identity.");
1140 return false;
1141 }
1142 return true;
1143 }
1144
1145 cancelIdentityHandoff() {
1146 try { this.handoffStorage.removeItem(DRAFT_HANDOFF_KEY); } catch { /* no-op */ }
1147 }
1148
1149 hasDraftHandoff() {
1150 const handoff = safeJson(this.handoffStorage, DRAFT_HANDOFF_KEY, null);
1151 const age = Date.now() - Number(handoff?.createdAt || 0);
1152 const valid = Boolean(handoff?.sourceApproved === true
1153 && typeof handoff.fromScope === "string"
1154 && normalizedPlacementDraft(handoff.draft, true)
1155 && age >= 0
1156 && age <= DRAFT_HANDOFF_TTL_MS);
1157 if (!valid && handoff) this.cancelIdentityHandoff();
1158 return valid;
1159 }
1160
1161 async restoreDraftHandoff(priorScope) {
1162 const expectedScope = this.storageScope;
1163 const expectedIdentityGeneration = this.identityGeneration;
1164 const handoff = safeJson(this.handoffStorage, DRAFT_HANDOFF_KEY, null);
1165 if (!handoff) return false;
1166 const removeHandoff = () => {
1167 try { this.handoffStorage.removeItem(DRAFT_HANDOFF_KEY); } catch { /* no-op */ }
1168 };
1169 const age = Date.now() - Number(handoff.createdAt || 0);
1170 const draft = normalizedPlacementDraft(handoff.draft, true);
1171 if (handoff.sourceApproved !== true || !draft || age < 0 || age > DRAFT_HANDOFF_TTL_MS) {
1172 removeHandoff();
1173 return false;
1174 }
1175 const fromScope = typeof handoff.fromScope === "string" ? handoff.fromScope : "";
1176 if (!fromScope) {
1177 removeHandoff();
1178 return false;
1179 }
1180 if (fromScope && fromScope === this.storageScope) {
1181 if (this.draft) {
1182 removeHandoff();
1183 return true;
1184 }
1185 const sameScopeKey = this.scopedStorageKey(DRAFT_KEY);
1186 if (sameScopeKey && safeSet(this.storage, sameScopeKey, draft)) {
1187 this.draft = draft;
1188 this.draftFromHandoff = false;
1189 removeHandoff();
1190 this.toast("Your unfinished Wall draft was recovered with a new safe request.");
1191 this.updateResumeDraftAction();
1192 return true;
1193 }
1194 this.draft = draft;
1195 this.draftFromHandoff = false;
1196 removeHandoff();
1197 this.toast("Your handoff draft is open in this tab. This browser cannot store it locally, so copy it before reloading.");
1198 this.updateResumeDraftAction();
1199 return true;
1200 }
1201 if (this.draft) {
1202 removeHandoff();
1203 this.toast("This saved account already has an unfinished wall draft. The other draft remains with the browser identity that started it.");
1204 return false;
1205 }
1206 if (expectedScope !== this.storageScope || expectedIdentityGeneration !== this.identityGeneration) return false;
1207 if (!this.storageScope) return false;
1208 const key = this.scopedStorageKey(DRAFT_KEY);
1209 if (!key || !safeSet(this.storage, key, draft)) {
1210 this.draft = draft;
1211 this.draftFromHandoff = false;
1212 removeHandoff();
1213 this.toast("The approved draft is open in this tab. This browser cannot store it locally, so copy it before reloading.");
1214 this.updateResumeDraftAction();
1215 return true;
1216 }
1217 this.draft = draft;
1218 this.draftFromHandoff = false;
1219 if (fromScope) {
1220 try { this.storage.removeItem(`${DRAFT_KEY}:${fromScope}`); } catch { /* no-op */ }
1221 this.quarantinedDrafts.delete(fromScope);
1222 }
1223 removeHandoff();
1224 this.toast("Draft restored for this saved account with a new safe request.");
1225 this.updateResumeDraftAction();
1226 return true;
1227 }
1228
1229 async resumeAfterIdentity(options = {}) {
1230 const activationGeneration = this.activationGeneration;
1231 if (!this.isActivationCurrent(activationGeneration)) return false;
1232 const priorScope = this.storageScope;
1233 await this.syncStorageScope(false);
1234 if (!this.isActivationCurrent(activationGeneration)) return false;
1235 const identityGeneration = this.identityGeneration;
1236 await this.restoreDraftHandoff(priorScope);
1237 if (!this.isContextCurrent(activationGeneration, identityGeneration)) return false;
1238 try {
1239 await this.startRealtime();
1240 } catch {
1241 this.unsubscribe = null;
1242 this.transportState = "polling";
1243 this.setConnectionState(navigator.onLine ? "polling" : "offline");
1244 }
1245 if (!this.isContextCurrent(activationGeneration, identityGeneration)) return false;
1246 void this.probeOperator();
1247 if (!this.active || !this.draft || !validCoordinate(this.draft.q, this.draft.r)) return false;
1248 return this.resumeCurrentDraft();
1249 }
1250
1251 async resumeCurrentDraft() {
1252 const activationGeneration = this.activationGeneration;
1253 const identityGeneration = this.identityGeneration;
1254 if (!this.isContextCurrent(activationGeneration, identityGeneration)) return false;
1255 const draft = normalizedPlacementDraft(this.draft);
1256 if (!draft) return false;
1257 this.selected = { q: draft.q, r: draft.r };
1258 this.updateTarget();
1259 this.revealCoordinate(draft.q, draft.r, "auto");
1260 const context = await this.hydratePlacement(draft.q, draft.r);
1261 if (!this.isContextCurrent(activationGeneration, identityGeneration)) return false;
1262 const groups = context.ok ? (context.groups || adjacentConversationGroups(this.cells, draft.q, draft.r, this.conversations)) : [];
1263 const isolatedIndependent = context.ok && groups.length === 0 && !draft.choiceExplicit;
1264 this.openComposer({
1265 ...draft,
1266 choices: context.ok ? context.choices : [],
1267 groups,
1268 intent: isolatedIndependent ? "independent" : draft.intent,
1269 choiceExplicit: draft.choiceExplicit || isolatedIndependent,
1270 placementVerified: context.ok,
1271 requiresConversationChoice: draft.requiresConversationChoice
1272 || (!draft.choiceExplicit && context.ok && groups.length > 0),
1273 choiceMade: Boolean(isolatedIndependent || (draft.choiceMade && draft.intent)),
1274 });
1275 if (!context.ok) {
1276 this.showComposeError("The exact comb and draft are open, but the Hive must reconnect and verify the nearby conversations before it can be placed.");
1277 }
1278 return true;
1279 }
1280
1281 updateResumeDraftAction() {
1282 const button = this.root.querySelector?.('[data-wall-action="resume"]');
1283 if (!button) return;
1284 const draft = normalizedPlacementDraft(this.draft, true);
1285 button.hidden = !draft;
1286 if (draft) button.textContent = `Resume draft at ${draft.q}, ${draft.r}`;
1287 }
1288
1289 setConnectionState(state) {
1290 if (!this.wall) return;
1291 const previous = this.wall.dataset.connection;
1292 this.wall.dataset.connection = state;
1293 this.updatePersistentStatus?.();
1294 if (previous === state) return;
1295 if (state === "offline") this.announce("Offline. The last loaded wall stays visible and drafts remain on this device.");
1296 }
1297
1298 updatePersistentStatus() {
1299 const status = this.root.querySelector?.("[data-wall-state-status]");
1300 if (!status) return;
1301 const connection = this.wall?.dataset?.connection || this.transportState || "polling";
1302 const connectionCopy = {
1303 live: "Live updates connected.",
1304 polling: "Checking periodically for shared changes.",
1305 reconnecting: "Reconnecting; the last verified Wall remains visible.",
1306 stale: "Connection interrupted; the last verified Wall remains visible.",
1307 offline: "Offline; the last verified Wall remains visible and drafts stay on this device.",
1308 }[connection] || "Checking the shared Wall.";
1309 const writeCopy = this.bounds?.readOnly
1310 ? "Reading is open. New combs remain closed until Hive Watch is staffed and verified."
1311 : "Reading and new combs are open.";
1312 setTextIfChanged(status, `${connectionCopy} ${writeCopy}`);
1313 }
1314
1315 async stopRealtime() {
1316 const unsubscribe = this.unsubscribe;
1317 this.unsubscribe = null;
1318 const prior = this.realtimeTeardown;
1319 const next = Promise.resolve(prior)
1320 .catch(() => undefined)
1321 .then(() => (typeof unsubscribe === "function" ? unsubscribe() : undefined));
1322 this.realtimeTeardown = Promise.resolve(next).catch(() => undefined);
1323 await this.realtimeTeardown;
1324 }
1325
1326 async startRealtime() {
1327 if (!this.active) return;
1328 const generation = ++this.realtimeGeneration;
1329 await this.stopRealtime();
1330 if (!this.active || generation !== this.realtimeGeneration) return;
1331 this.unsubscribe = this.backend.subscribeWallChanges(
1332 (event) => {
1333 if (this.active && generation === this.realtimeGeneration) this.queueRealtimeEvent(event);
1334 },
1335 (status) => {
1336 if (!this.active || generation !== this.realtimeGeneration) return;
1337 this.transportState = status === "SUBSCRIBED"
1338 ? "live"
1339 : status === "POLLING"
1340 ? "polling"
1341 : "reconnecting";
1342 this.setConnectionState(
1343 navigator.onLine ? (this.dataStale ? "stale" : this.transportState) : "offline",
1344 );
1345 },
1346 );
1347 }
1348
1349 scopedStorageKey(base) {
1350 return this.storageScope ? `${base}:${this.storageScope}` : null;
1351 }
1352
1353 async syncStorageScope(create) {
1354 const requestGeneration = ++this.scopeRequestGeneration;
1355 let nextScope = null;
1356 try {
1357 if (typeof this.backend.wallIdentityKey === "function") {
1358 nextScope = await this.backend.wallIdentityKey(Boolean(create));
1359 }
1360 } catch {
1361 this.dataStale = true;
1362 this.setConnectionState(navigator.onLine ? "stale" : "offline");
1363 return this.storageScope;
1364 }
1365 if (requestGeneration !== this.scopeRequestGeneration) return this.storageScope;
1366 if (nextScope === this.storageScope) return nextScope;
1367 const priorScope = this.storageScope;
1368 this.preserveUnpersistedDrafts(priorScope);
1369 this.invalidatePrivateOperations({ saveDraft: false, closeDialogs: true });
1370 this.identityGeneration += 1;
1371 this.publicCacheGeneration += 1;
1372 this.storageScope = nextScope;
1373 this.cells.clear();
1374 this.cellsById.clear();
1375 this.conversations.clear();
1376 for (const node of this.nodes.values()) node.remove();
1377 this.nodes.clear();
1378 for (const line of this.connectionNodes?.values?.() || []) line.remove();
1379 this.connectionNodes?.clear?.();
1380 this.loadedChunks.clear();
1381 this.chunkAccess.clear();
1382 this.cellChunks.clear();
1383 this.dirtyChunks.clear();
1384 this.inflightChunks.clear();
1385 if (this.eventTimer) window.clearTimeout(this.eventTimer);
1386 if (this.eventRetryTimer) window.clearTimeout(this.eventRetryTimer);
1387 if (this.listReconcileTimer) window.clearTimeout(this.listReconcileTimer);
1388 this.eventTimer = null;
1389 this.eventRetryTimer = null;
1390 this.listReconcileTimer = null;
1391 this.pendingEvents.clear();
1392 this.retryEvents.clear();
1393 this.realtimeDrainQueue?.clear?.();
1394 this.consumingEvents.clear();
1395 this.realtimeDrainPromise = null;
1396 this.realtimeDrainDirty = false;
1397 this.listReconcileEvents.clear();
1398 this.seenRealtimeEvents.clear();
1399 this.listCells = [];
1400 this.listBeforeSeq = null;
1401 this.listHasMore = true;
1402 this.listConversationId = null;
1403 this.listWindowRevision = 0;
1404 this.wallWindowRevision = 0;
1405 this.bounds = { ...this.bounds, viewerRevision: 0 };
1406 this.listRequestGeneration += 1;
1407 this.readerCell = null;
1408 this.reportRequest = null;
1409 const draftKey = this.scopedStorageKey(DRAFT_KEY);
1410 const editKey = this.scopedStorageKey(EDIT_DRAFT_KEY);
1411 const seenKey = this.scopedStorageKey(SEEN_KEY);
1412 const quarantined = nextScope ? this.quarantinedDrafts.get(nextScope) : null;
1413 this.draft = (draftKey ? safeJson(this.storage, draftKey, null) : null) || quarantined?.draft || null;
1414 this.editDraft = (editKey ? safeJson(this.storage, editKey, null) : null) || quarantined?.editDraft || null;
1415 if (nextScope && quarantined) this.quarantinedDrafts.delete(nextScope);
1416 const seen = seenKey ? safeJson(this.storage, seenKey, []) : [];
1417 this.seen = new Set(Array.isArray(seen) ? seen : []);
1418 this.draftPersistenceFailed = false;
1419 this.editDraftPersistenceFailed = false;
1420 this.draftFromHandoff = false;
1421 this.render();
1422 this.updateResumeDraftAction();
1423 return nextScope;
1424 }
1425
1426 updateVisualViewport() {
1427 if (!this.wall) return;
1428 const rootStyles = getComputedStyle(document.documentElement);
1429 const sharedHeight = rootStyles.getPropertyValue("--hive-vv-height").trim();
1430 const sharedInset = rootStyles.getPropertyValue("--hive-keyboard-inset").trim();
1431 if (sharedHeight) {
1432 this.wall.style.setProperty("--honey-visual-height", "var(--hive-vv-height)");
1433 this.wall.style.setProperty("--honey-keyboard-offset", sharedInset ? "var(--hive-keyboard-inset)" : "0px");
1434 return;
1435 }
1436 const viewport = window.visualViewport;
1437 const height = viewport ? viewport.height : window.innerHeight;
1438 const keyboardOffset = viewport ? Math.max(0, window.innerHeight - viewport.height - viewport.offsetTop) : 0;
1439 this.wall.style.setProperty("--honey-visual-height", `${Math.max(1, height)}px`);
1440 this.wall.style.setProperty("--honey-keyboard-offset", `${keyboardOffset}px`);
1441 }
1442
1443 async refreshBounds() {
1444 const identityGeneration = this.identityGeneration;
1445 const activationGeneration = this.activationGeneration;
1446 const requestGeneration = ++this.boundsRequestGeneration;
1447 const contextCurrent = () => (
1448 this.mounted
1449 && identityGeneration === this.identityGeneration
1450 && activationGeneration === this.activationGeneration
1451 );
1452 try {
1453 const incoming = await this.backend.wallBounds();
1454 if (!contextCurrent()) return this.bounds;
1455 if (!incoming || !Number.isSafeInteger(Number(incoming.revision))) throw new Error("The wall bounds were incomplete.");
1456 const viewerAdvanced = this.viewerProjectionAdvanced(incoming);
1457 if (!this.applyAuthoritativeBounds(incoming)) return this.bounds;
1458 if (viewerAdvanced && this.hasPublicProjection()) {
1459 // Private report visibility changes do not alter the shared Wall
1460 // revision. A per-viewer monotonic token makes another tab/device's
1461 // report invalidate every retained page and offscreen chunk safely.
1462 this.invalidatePublicProjectionCache({ resetConversation: false });
1463 }
1464 this.boundsSuccessGeneration = Math.max(this.boundsSuccessGeneration, requestGeneration);
1465 this.lastGoodAt = Date.now();
1466 this.dataStale = false;
1467 this.setConnectionState(navigator.onLine ? this.transportState : "offline");
1468 return this.bounds;
1469 } catch (error) {
1470 if (!contextCurrent() || requestGeneration < this.boundsSuccessGeneration) return this.bounds;
1471 this.dataStale = true;
1472 this.setConnectionState(navigator.onLine ? "stale" : "offline");
1473 if (!this.lastGoodAt) this.announce(`The shared wall is unavailable: ${error.message}`);
1474 return this.bounds;
1475 }
1476 }
1477
1478 applyAuthoritativeBounds(incoming) {
1479 const incomingRevision = Number(incoming?.revision);
1480 if (!Number.isSafeInteger(incomingRevision) || incomingRevision < 0) return false;
1481 const incomingViewerRevision = Number(incoming?.viewerRevision) || 0;
1482 if (!Number.isSafeInteger(incomingViewerRevision) || incomingViewerRevision < 0) return false;
1483 const currentRevision = Number(this.bounds.revision) || 0;
1484 const currentViewerRevision = Number(this.bounds.viewerRevision) || 0;
1485 const incomingUpdatedAt = Number(incoming.updatedAt) || 0;
1486 const currentUpdatedAt = Number(this.bounds.updatedAt) || 0;
1487 if (incomingRevision < currentRevision
1488 || incomingViewerRevision < currentViewerRevision
1489 || (incomingRevision === currentRevision && incomingUpdatedAt < currentUpdatedAt)) return false;
1490 const sameSnapshot = incomingRevision === currentRevision && incomingUpdatedAt === currentUpdatedAt;
1491 this.bounds = {
1492 revision: incomingRevision,
1493 viewerRevision: incomingViewerRevision,
1494 radius: Math.max(this.bounds.radius, clamp(Number(incoming.radius) || 5, 5, WALL_LIMITS.maxRadius)),
1495 messageCount: Math.max(this.bounds.messageCount, Math.max(0, Number(incoming.messageCount) || 0)),
1496 // When two payloads claim the exact same ordering key but disagree,
1497 // remain closed. A strictly newer state timestamp may deliberately open.
1498 readOnly: sameSnapshot
1499 ? Boolean(this.bounds.readOnly || incoming.readOnly)
1500 : Boolean(incoming.readOnly),
1501 updatedAt: incomingUpdatedAt || currentUpdatedAt || Date.now(),
1502 };
1503 // The world is centred on the first comb, so growth expands symmetrically
1504 // around the camera. Nothing under the viewer shifts and no scroll
1505 // compensation is needed the way it was when the plane drove page scroll.
1506 this.updateWorldSize();
1507 this.updateSummary();
1508 return true;
1509 }
1510
1511 viewerProjectionAdvanced(incoming) {
1512 const next = Number(incoming?.viewerRevision) || 0;
1513 const current = Number(this.bounds.viewerRevision) || 0;
1514 return Number.isSafeInteger(next) && next > current;
1515 }
1516
1517 updateSummary() {
1518 if (!this.summary) return;
1519 const messages = this.bounds.messageCount === 1 ? "1 comb" : `${this.bounds.messageCount.toLocaleString()} combs`;
1520 setTextIfChanged(this.summary, `${messages} · wall revision ${this.bounds.revision.toLocaleString()}${this.bounds.readOnly ? " · reading open while Hive Watch is verified" : ""}`);
1521 this.wall?.toggleAttribute("data-read-only", this.bounds.readOnly);
1522 const add = this.root.querySelector('[data-wall-action="add"]');
1523 if (add) {
1524 add.disabled = this.bounds.readOnly;
1525 add.title = this.bounds.readOnly ? "Messages open after Hive Watch verification" : "Add a message to an open comb";
1526 }
1527 const edgeNote = this.root.querySelector("[data-wall-edge-note]");
1528 if (edgeNote) setTextIfChanged(edgeNote, this.bounds.readOnly
1529 ? "The Wall is open to read while Hive Watch is verified. New combs will open soon."
1530 : "Click any open place in the honeycomb to leave a message.");
1531 const composeSubmit = this.root.querySelector("[data-wall-compose-submit]");
1532 if (composeSubmit) {
1533 composeSubmit.disabled = this.bounds.readOnly
1534 || this.composeBusy
1535 || Boolean(this.composeState && !this.composeState.editing
1536 && (!this.composeState.choiceMade || !PLACEMENT_INTENTS.has(this.composeState.intent)));
1537 }
1538 this.updatePersistentStatus();
1539 if (this.readerCell) this.paintReaderCell(this.readerCell, { preserveForms: true });
1540 }
1541
1542 captureAccessibleListView(preserveScroll = false) {
1543 const activeElement = globalThis.document?.activeElement || null;
1544 const focusedControl = activeElement && this.list?.contains(activeElement)
1545 ? activeElement.dataset?.wallListFocus || null
1546 : null;
1547 return {
1548 focusKey: focusedControl,
1549 focusTop: focusedControl && typeof activeElement.getBoundingClientRect === "function"
1550 ? activeElement.getBoundingClientRect().top
1551 : null,
1552 preserveScroll: Boolean(preserveScroll),
1553 scrollY: preserveScroll ? Number(globalThis.window?.scrollY) || 0 : null,
1554 };
1555 }
1556
1557 restoreAccessibleListView(viewState, requestGeneration, conversationId) {
1558 if (!viewState) return;
1559 const restore = () => {
1560 if (requestGeneration !== this.listRequestGeneration
1561 || conversationId !== this.listConversationId || this.mode !== "list") return;
1562 const candidate = viewState.focusKey
1563 ? this.list?.querySelector(`[data-wall-list-focus="${escapeSelectorValue(viewState.focusKey)}"]`)
1564 : null;
1565 const control = candidate && !candidate.hidden && !candidate.disabled && !candidate.closest?.("[hidden]")
1566 ? candidate
1567 : null;
1568 if (control) {
1569 control.focus({ preventScroll: true });
1570 if (viewState.focusTop != null && typeof globalThis.window?.scrollBy === "function") {
1571 const topDelta = control.getBoundingClientRect().top - viewState.focusTop;
1572 if (topDelta) globalThis.window.scrollBy({ top: topDelta, behavior: "auto" });
1573 }
1574 } else {
1575 if (viewState.focusKey) {
1576 const fallback = this.list?.querySelector("[data-wall-list-items] button:not([hidden]):not(:disabled), button:not([hidden]):not(:disabled)") || this.list;
1577 fallback?.focus?.({ preventScroll: true });
1578 if (fallback && viewState.focusTop != null
1579 && typeof fallback.getBoundingClientRect === "function"
1580 && typeof globalThis.window?.scrollBy === "function") {
1581 const topDelta = fallback.getBoundingClientRect().top - viewState.focusTop;
1582 if (topDelta) globalThis.window.scrollBy({ top: topDelta, behavior: "auto" });
1583 } else fallback?.scrollIntoView?.({ block: "nearest", behavior: "auto" });
1584 } else if (viewState.preserveScroll && typeof globalThis.window?.scrollTo === "function") {
1585 globalThis.window.scrollTo({ top: viewState.scrollY, behavior: "auto" });
1586 }
1587 }
1588 };
1589 if (typeof globalThis.requestAnimationFrame === "function") requestAnimationFrame(restore);
1590 else restore();
1591 }
1592
1593 invalidatePublicProjectionCache(options = {}) {
1594 this.publicCacheGeneration += 1;
1595 this.focusGeneration += 1;
1596 this.wallWindowRevision = 0;
1597 this.selectedCellKey = null;
1598 this.stage?.removeAttribute?.("aria-activedescendant");
1599 for (const node of this.nodes ? this.nodes.values() : []) {
1600 node.disabled = true;
1601 node.dataset.placeholder = "true";
1602 node.classList.add("is-refreshing");
1603 node.classList.remove("is-selected", "is-unseen", "is-mine", "is-viewer-hidden");
1604 node.removeAttribute("aria-current");
1605 node.setAttribute("aria-label", "Refreshing this comb's position");
1606 for (const part of node.querySelectorAll?.(".honey-comb-author,.honey-comb-body,.honey-comb-foot") || []) part.textContent = "";
1607 }
1608 for (const line of this.connectionNodes ? this.connectionNodes.values() : []) {
1609 line.classList.add("is-refreshing");
1610 line.removeAttribute("data-relation");
1611 }
1612 this.wall?.setAttribute?.("aria-busy", "true");
1613 this.cells?.clear?.();
1614 this.cellsById?.clear?.();
1615 this.cellChunks?.clear?.();
1616 this.loadedChunks?.clear?.();
1617 this.chunkAccess?.clear?.();
1618 this.dirtyChunks?.clear?.();
1619 this.inflightChunks?.clear?.();
1620 this.visibleChunkKeys?.clear?.();
1621 this.conversations?.clear?.();
1622 if (this.composeState && options.preserveComposer === false) {
1623 if (this.composeState.editing) this.saveEditDraft();
1624 else this.saveDraft();
1625 this.composeGeneration += 1;
1626 this.composeBusy = false;
1627 this.composeState = null;
1628 this.closeDialogImmediately(this.compose);
1629 this.updateResumeDraftAction();
1630 } else if (this.composeState && !this.composeState.editing) {
1631 // Public projections may be discarded while someone is writing. Keep
1632 // every draft byte and the exact coordinate open, but force submit to
1633 // re-hydrate the comb and its neighboring conversations.
1634 this.markComposerProjectionPending();
1635 this.draft = { ...this.composeState, body: this.composeBody?.value || this.composeState.body || "" };
1636 this.saveDraft();
1637 }
1638 if (this.readerCell || this.reader?.open || this.reader?.hasAttribute?.("open")) {
1639 this.closeReaderForProjectionRefresh();
1640 }
1641 this.discardAccessibleListWindow(options.resetConversation !== false);
1642 }
1643
1644 publicProjectionAccountedRevision(mode = this.mode) {
1645 if (mode !== "list") return Number(this.wallWindowRevision) || 0;
1646 const retainedIds = new Set(this.listCells.map((cell) => cell?.id).filter(Boolean));
1647 return [...this.listReconcileEvents.values()].reduce((revision, event) => (
1648 retainedIds.has(event?.cellId)
1649 ? Math.max(revision, Number(event?.revision) || 0)
1650 : revision
1651 ), Number(this.listWindowRevision) || 0);
1652 }
1653
1654 hasPublicProjection(mode = this.mode) {
1655 if (mode === "list") {
1656 return Boolean(this.listCells.length
1657 || this.listItems?.querySelector?.("[data-wall-list-row]")
1658 || this.cells?.size
1659 || this.cellsById?.size
1660 || this.conversations?.size
1661 || this.readerCell);
1662 }
1663 return Boolean(this.cells?.size || this.cellsById?.size || this.conversations?.size
1664 || this.loadedChunks?.size || this.nodes?.size || this.readerCell);
1665 }
1666
1667 hasUnaccountedPublicRevision(revision, mode = this.mode) {
1668 const nextRevision = Number(revision);
1669 return Number.isSafeInteger(nextRevision)
1670 && this.hasPublicProjection(mode)
1671 && nextRevision > this.publicProjectionAccountedRevision(mode);
1672 }
1673
1674 captureProjectionRebuild() {
1675 return {
1676 mode: this.mode,
1677 conversationId: this.listConversationId,
1678 listView: this.mode === "list" ? this.captureAccessibleListView(true) : null,
1679 };
1680 }
1681
1682 async rebuildPublicProjection(rebuild) {
1683 if (!rebuild || rebuild.mode !== this.mode || !this.active || !this.mounted) return false;
1684 if (rebuild.mode === "list") {
1685 if (rebuild.conversationId !== this.listConversationId) return false;
1686 await this.refreshList(true, rebuild.listView);
1687 return this.mode === "list" && rebuild.conversationId === this.listConversationId;
1688 }
1689 return this.refreshVisible(true, 0);
1690 }
1691
1692 refreshCurrentPublicProjection() {
1693 if (!this.active || !this.mounted) return;
1694 if (this.mode === "list") void this.refreshList(true);
1695 else void this.refreshVisible(true);
1696 }
1697
1698 async rebuildAfterConfirmedWrite(rebuild = this.captureProjectionRebuild()) {
1699 this.invalidatePublicProjectionCache({ resetConversation: false });
1700 return this.rebuildPublicProjection(rebuild);
1701 }
1702
1703 evictWallChunkProjection(chunkKey, options = {}) {
1704 const preserveGeometry = options.preserveGeometry === true;
1705 this.loadedChunks.delete(chunkKey);
1706 this.chunkAccess.delete(chunkKey);
1707 this.dirtyChunks.delete(chunkKey);
1708 let readerEvicted = false;
1709 const evictedIds = new Set();
1710 for (const [cellId, cellChunk] of [...this.cellChunks]) {
1711 if (cellChunk !== chunkKey) continue;
1712 evictedIds.add(cellId);
1713 const cell = this.cellsById.get(cellId);
1714 if (this.readerCell?.id === cellId) readerEvicted = true;
1715 if (cell && this.cells.get(cellKey(cell.q, cell.r))?.id === cellId) {
1716 this.cells.delete(cellKey(cell.q, cell.r));
1717 const node = this.nodes.get(cellKey(cell.q, cell.r));
1718 if (preserveGeometry && node) {
1719 node.disabled = true;
1720 node.dataset.placeholder = "true";
1721 node.classList.add("is-refreshing");
1722 node.classList.remove("is-selected", "is-unseen", "is-mine", "is-viewer-hidden");
1723 node.removeAttribute("aria-current");
1724 node.setAttribute("aria-label", "Refreshing this comb's position");
1725 for (const part of node.querySelectorAll(".honey-comb-author,.honey-comb-body,.honey-comb-foot")) part.textContent = "";
1726 } else {
1727 node?.remove();
1728 this.nodes.delete(cellKey(cell.q, cell.r));
1729 }
1730 }
1731 this.cellsById.delete(cellId);
1732 this.cellChunks.delete(cellId);
1733 }
1734 if (preserveGeometry) {
1735 for (const [key, line] of this.connectionNodes) {
1736 if (![...evictedIds].some((cellId) => key.includes(`:${cellId}`))) continue;
1737 line.classList.add("is-refreshing");
1738 line.removeAttribute("data-relation");
1739 }
1740 this.wall?.setAttribute?.("aria-busy", "true");
1741 }
1742 if (readerEvicted) this.closeReaderForProjectionRefresh();
1743 }
1744
1745 evictPublicCellProjection(cellId) {
1746 const cell = this.cellsById.get(cellId) || this.listCells.find((item) => item?.id === cellId) || null;
1747 if (cell && this.cells.get(cellKey(cell.q, cell.r))?.id === cellId) {
1748 this.cells.delete(cellKey(cell.q, cell.r));
1749 const node = this.nodes.get(cellKey(cell.q, cell.r));
1750 node?.remove();
1751 this.nodes.delete(cellKey(cell.q, cell.r));
1752 }
1753 this.cellsById.delete(cellId);
1754 this.cellChunks.delete(cellId);
1755 this.listCells = this.listCells.filter((item) => item?.id !== cellId);
1756 if (this.readerCell?.id === cellId) this.closeReaderForProjectionRefresh();
1757 }
1758
1759 closeReaderForProjectionRefresh() {
1760 if (!this.readerCell && !this.reader?.open && !this.reader?.hasAttribute?.("open")) return;
1761 const opener = this.dialogOpeners.get(this.reader) || null;
1762 const focusAnchor = this.dialogFocusAnchors.get(this.reader) || null;
1763 const body = this.root?.querySelector?.("[data-wall-reader-body]");
1764 setTextIfChanged(body, "Refreshing this comb from the shared Wall…");
1765 this.readerGeneration += 1;
1766 this.readerBusy = false;
1767 this.readerCell = null;
1768 this.reportRequest = null;
1769 this.operatorCaseRequest = null;
1770 this.closeDialogImmediately(this.reader);
1771 this.restoreWallFocus(opener, focusAnchor);
1772 }
1773
1774 markComposerProjectionPending() {
1775 if (!this.composeState || this.composeState.editing) return;
1776 const hadConversationContext = Boolean(
1777 this.composeState.conversationId
1778 || this.composeState.replyToId
1779 || this.composeState.requiresConversationChoice
1780 || this.composeState.choices?.length
1781 );
1782 this.composeState.placementVerified = false;
1783 this.composeState.choices = [];
1784 // An uncertain/in-flight command must retain both its durable request ID
1785 // and exact payload. An explicit human choice is frozen too: live activity
1786 // may require its anchors to be revalidated, but may never silently erase
1787 // or reinterpret the selected relationship. Only an unchosen draft drops
1788 // stale adjacency so the next hydration asks again.
1789 const preservesFrozenChoice = Boolean(this.composeState.requestId || this.composeState.choiceExplicit);
1790 if (!preservesFrozenChoice) {
1791 this.composeState.conversationId = null;
1792 this.composeState.replyToId = null;
1793 this.composeState.choiceMade = false;
1794 this.composeState.choiceExplicit = false;
1795 }
1796 this.composeState.requiresConversationChoice = hadConversationContext && !preservesFrozenChoice;
1797 const choiceField = this.root?.querySelector?.("[data-wall-conversation-choices]");
1798 const choiceList = this.root?.querySelector?.("[data-wall-conversation-options]");
1799 if (!choiceField || !choiceList) return;
1800 const choiceHadFocus = Boolean(globalThis.document?.activeElement
1801 && choiceList.contains?.(globalThis.document.activeElement));
1802 choiceList.replaceChildren();
1803 choiceField.hidden = !hadConversationContext;
1804 if (hadConversationContext) {
1805 const pending = document.createElement("p");
1806 pending.className = "honey-choice-pending";
1807 pending.textContent = "Nearby conversations must reload before you choose where this comb belongs.";
1808 choiceList.append(pending);
1809 if (choiceHadFocus) {
1810 this.announce(pending.textContent);
1811 const restore = () => this.composeBody?.focus?.({ preventScroll: true });
1812 if (typeof globalThis.requestAnimationFrame === "function") requestAnimationFrame(restore);
1813 else restore();
1814 }
1815 }
1816 }
1817
1818 updateWorldSize() {
1819 if (!this.plane || !this.stage) return;
1820 const radius = Math.max(0, Number(this.bounds?.radius) || 0);
1821 // Half-extents of the occupied hex field. |q|,|r|,|q+r| <= radius puts the
1822 // widest cell at (radius, 0) and the lowest at (0, radius).
1823 const halfWidth = axialToPixel(radius, 0, this.hexRadius).x + this.hexRadius;
1824 const halfHeight = radius * this.hexRadius * 1.5 + this.hexRadius;
1825 const width = halfWidth * 2 + WORLD_MARGIN * 2;
1826 const height = halfHeight * 2 + WORLD_MARGIN * 2;
1827 const originX = width / 2;
1828 const originY = height / 2;
1829 // Bounds are re-applied on every poll, usually with an unchanged radius.
1830 // Returning early keeps an idle wall completely still: no transform write,
1831 // no camera settle, and no refit scheduled behind an open growth picker.
1832 if (this.world.halfWidth === halfWidth && this.world.halfHeight === halfHeight) return;
1833 this.world = { halfWidth, halfHeight, width, height, originX, originY };
1834 this.plane.style.width = `${Math.ceil(width)}px`;
1835 this.plane.style.height = `${Math.ceil(height)}px`;
1836 this.plane.style.marginLeft = `${Math.ceil(width / -2)}px`;
1837 this.plane.style.setProperty("--honey-origin-x", `${Math.ceil(originX)}px`);
1838 this.plane.style.setProperty("--honey-origin-y", `${Math.ceil(originY)}px`);
1839 if (this.growthIntent) {
1840 // A growth picker owns the camera and is deliberately unclamped so an
1841 // edge cluster stays reachable. A bounds poll landing mid-choice must
1842 // refit it, never clamp it back and slide the open directions away.
1843 this.updatePlaneTransform();
1844 this.scheduleGrowthFit();
1845 return;
1846 }
1847 this.clampCamera();
1848 this.updatePlaneTransform();
1849 }
1850
1851 stageSize() {
1852 if (!this.stage) return { width: Math.max(1, window.innerWidth), height: Math.max(1, window.innerHeight) };
1853 return {
1854 width: Math.max(1, this.stage.clientWidth || window.innerWidth),
1855 height: Math.max(1, this.stage.clientHeight || window.innerHeight),
1856 };
1857 }
1858
1859 // The part of the stage the viewer can actually see, in stage coordinates.
1860 // Browser page-scale zoom makes the visual viewport a sub-rectangle of the
1861 // layout viewport, so aiming at the stage's own centre would point at pixels
1862 // that are off screen. Falls back to the whole stage when they coincide.
1863 visibleStageRect() {
1864 const size = this.stageSize();
1865 const whole = { left: 0, top: 0, right: size.width, bottom: size.height, width: size.width, height: size.height };
1866 const rect = this.stage?.getBoundingClientRect?.();
1867 const viewport = globalThis.window?.visualViewport;
1868 if (!rect || !viewport) return whole;
1869 const offsetLeft = Number(viewport.offsetLeft) || 0;
1870 const offsetTop = Number(viewport.offsetTop) || 0;
1871 const left = Math.max(0, offsetLeft - rect.left);
1872 const top = Math.max(0, offsetTop - rect.top);
1873 const right = Math.min(size.width, offsetLeft + (Number(viewport.width) || size.width) - rect.left);
1874 const bottom = Math.min(size.height, offsetTop + (Number(viewport.height) || size.height) - rect.top);
1875 if (right - left < 1 || bottom - top < 1) return whole;
1876 return { left, top, right, bottom, width: right - left, height: bottom - top };
1877 }
1878
1879 // World coordinates are the same space axialToPixel() returns, with (0,0) at
1880 // the first comb. Stage coordinates are pixels inside the stage box, which
1881 // is also the visible viewport now that the plane no longer drives page
1882 // scroll. Every hit test, reveal, and clamp goes through this one pair.
1883 worldToStage(x, y) {
1884 const size = this.stageSize();
1885 return {
1886 x: size.width / 2 + Number(x) * this.zoom + this.cameraX,
1887 y: (this.world.originY + Number(y)) * this.zoom + this.cameraY,
1888 };
1889 }
1890
1891 stageToWorld(x, y) {
1892 const size = this.stageSize();
1893 return {
1894 x: (Number(x) - size.width / 2 - this.cameraX) / this.zoom,
1895 y: (Number(y) - this.cameraY) / this.zoom - this.world.originY,
1896 };
1897 }
1898
1899 // The box the combs actually occupy, in world pixels. A wall of eighteen
1900 // combs sits in a small patch of a radius-512 field, so framing and camera
1901 // travel follow the conversations rather than the empty coordinate space.
1902 contentExtent() {
1903 let minX = Infinity;
1904 let maxX = -Infinity;
1905 let minY = Infinity;
1906 let maxY = -Infinity;
1907 for (const cell of this.cells.values()) {
1908 const point = axialToPixel(cell.q, cell.r, this.hexRadius);
1909 if (point.x < minX) minX = point.x;
1910 if (point.x > maxX) maxX = point.x;
1911 if (point.y < minY) minY = point.y;
1912 if (point.y > maxY) maxY = point.y;
1913 }
1914 if (!Number.isFinite(minX)) {
1915 minX = -this.hexRadius;
1916 maxX = this.hexRadius;
1917 minY = -this.hexRadius;
1918 maxY = this.hexRadius;
1919 }
1920 // Always keep the first comb inside the frame; it is the wall's anchor and
1921 // the target of Center and Home.
1922 const halfCellX = this.hexRadius * SQRT_3 * 0.5;
1923 return {
1924 minX: Math.min(minX, 0) - halfCellX,
1925 maxX: Math.max(maxX, 0) + halfCellX,
1926 minY: Math.min(minY, 0) - this.hexRadius,
1927 maxY: Math.max(maxY, 0) + this.hexRadius,
1928 };
1929 }
1930
1931 // A phone should open on a readable patch, not one empty coordinate or an
1932 // unreadably tiny map of the entire Hive. Frame the first comb and its
1933 // immediate neighbours; See it all remains available for the global view.
1934 initialPhoneExtent() {
1935 let minX = 0;
1936 let maxX = 0;
1937 let minY = 0;
1938 let maxY = 0;
1939 for (const cell of this.cells.values()) {
1940 if (hexDistance(cell.q, cell.r) > 1) continue;
1941 const point = axialToPixel(cell.q, cell.r, this.hexRadius);
1942 minX = Math.min(minX, point.x);
1943 maxX = Math.max(maxX, point.x);
1944 minY = Math.min(minY, point.y);
1945 maxY = Math.max(maxY, point.y);
1946 }
1947 const halfCellX = this.hexRadius * SQRT_3 * 0.5;
1948 return {
1949 minX: minX - halfCellX,
1950 maxX: maxX + halfCellX,
1951 minY: minY - this.hexRadius,
1952 maxY: maxY + this.hexRadius,
1953 };
1954 }
1955
1956 // Where the camera may roam: the whole authoritative wall, not just the part
1957 // that happens to be loaded. Restricting travel to loaded combs would make
1958 // distant clusters permanently undiscoverable.
1959 cameraBounds() {
1960 return {
1961 minX: -this.world.halfWidth,
1962 maxX: this.world.halfWidth,
1963 minY: -this.world.halfHeight,
1964 maxY: this.world.halfHeight,
1965 };
1966 }
1967
1968 zoomToFit(extent) {
1969 const size = this.stageSize();
1970 // A collapsed or not-yet-laid-out stage would compute a nonsense zoom and
1971 // strand the viewer at it once the real size arrives. Keep what we have.
1972 if (size.width < 2 || size.height < 2) return this.zoom;
1973 const pad = 28;
1974 const spanX = Math.max(1, extent.maxX - extent.minX + pad * 2);
1975 const spanY = Math.max(1, extent.maxY - extent.minY + pad * 2);
1976 return clamp(Math.min(size.width / spanX, size.height / spanY), WALL_LIMITS.minZoom, WALL_LIMITS.maxZoom);
1977 }
1978
1979 // "See it all" frames the combs that exist, which is what a viewer means by
1980 // seeing everything. Pulling back further is still allowed, and that is what
1981 // reveals clusters sitting outside the loaded window.
1982 fitZoom() {
1983 return this.zoomToFit(this.contentExtent());
1984 }
1985
1986 zoomFloor() {
1987 // The floor is the whole growable field, not the loaded combs, so zooming
1988 // out can always reach wall the viewer has not visited yet. A small wall
1989 // still never forces the viewer further out than 100%.
1990 const world = this.zoomToFit({
1991 minX: -this.world.halfWidth,
1992 maxX: this.world.halfWidth,
1993 minY: -this.world.halfHeight,
1994 maxY: this.world.halfHeight,
1995 });
1996 return clamp(Math.min(world, 1), WALL_LIMITS.minZoom, WALL_LIMITS.maxZoom);
1997 }
1998
1999 clampZoom(value) {
2000 const next = Number(value);
2001 if (!Number.isFinite(next)) return this.zoom;
2002 return clamp(next, this.zoomFloor(), WALL_LIMITS.maxZoom);
2003 }
2004
2005 // Convert the world point the viewer is looking at into camera offsets.
2006 cameraForFocus(x, y, zoom = this.zoom) {
2007 const size = this.stageSize();
2008 return {
2009 x: -Number(x) * zoom,
2010 y: size.height / 2 - (this.world.originY + Number(y)) * zoom,
2011 };
2012 }
2013
2014 cameraFocus(zoom = this.zoom) {
2015 const size = this.stageSize();
2016 return {
2017 x: -this.cameraX / zoom,
2018 y: (size.height / 2 - this.cameraY) / zoom - this.world.originY,
2019 };
2020 }
2021
2022 // Clamp the world point at the middle of the stage. An axis whose reachable
2023 // box is smaller than the stage locks to that box's centre, which is what
2024 // makes the fully zoomed-out view sit still instead of sliding around.
2025 clampCamera(zoom = this.zoom) {
2026 const size = this.stageSize();
2027 const box = this.cameraBounds();
2028 const content = this.contentExtent();
2029 const focus = this.cameraFocus(zoom);
2030 const overX = this.hexRadius * SQRT_3 * 0.75;
2031 const overY = this.hexRadius * 1.5 * 0.75;
2032 const halfViewX = size.width / 2 / zoom;
2033 const halfViewY = size.height / 2 / zoom;
2034 // An axis whose reachable box already fits on screen has nothing to pan
2035 // to, so it settles on the middle of the combs rather than the middle of
2036 // the coordinate space; a wall growing downward should not sit low in an
2037 // otherwise empty frame.
2038 const axis = (value, min, max, halfView, over, contentMid) => {
2039 if (max - min <= halfView * 2) return clamp(contentMid, min, max);
2040 return clamp(value, min + halfView - over, max - halfView + over);
2041 };
2042 const nextX = axis(Number.isFinite(focus.x) ? focus.x : 0, box.minX, box.maxX, halfViewX, overX, (content.minX + content.maxX) / 2);
2043 const nextY = axis(Number.isFinite(focus.y) ? focus.y : 0, box.minY, box.maxY, halfViewY, overY, (content.minY + content.maxY) / 2);
2044 const camera = this.cameraForFocus(nextX, nextY, zoom);
2045 this.cameraX = camera.x;
2046 this.cameraY = camera.y;
2047 return { x: this.cameraX, y: this.cameraY };
2048 }
2049
2050 // Retained so existing callers that only settle the horizontal axis keep
2051 // working; both axes are clamped together because a zoom change moves both.
2052 clampCameraX() {
2053 return this.clampCamera().x;
2054 }
2055
2056 detailTierFor(zoom = this.zoom) {
2057 return (DETAIL_TIERS.find((tier) => zoom >= tier.minZoom) || DETAIL_TIERS[DETAIL_TIERS.length - 1]).id;
2058 }
2059
2060 updatePlaneTransform() {
2061 if (!this.plane) return;
2062 this.plane.style.transform = `translate3d(${this.cameraX}px, ${this.cameraY}px, 0) scale(${this.zoom})`;
2063 if (this.zoomOutput) this.zoomOutput.textContent = `${Math.round(this.zoom * 100)}%`;
2064 const tier = this.detailTierFor();
2065 if (tier !== this.detailTier) {
2066 this.detailTier = tier;
2067 this.wall?.setAttribute?.("data-wall-detail", tier);
2068 }
2069 }
2070
2071 visibleCoordinates() {
2072 if (!this.stage || !this.plane) return { qMin: -4, qMax: 4, rMin: -4, rMax: 4, originX: 0 };
2073 const size = this.stageSize();
2074 const topLeft = this.stageToWorld(0, 0);
2075 const bottomRight = this.stageToWorld(size.width, size.height);
2076 const corners = [
2077 pixelToAxial(topLeft.x, topLeft.y, this.hexRadius),
2078 pixelToAxial(bottomRight.x, topLeft.y, this.hexRadius),
2079 pixelToAxial(topLeft.x, bottomRight.y, this.hexRadius),
2080 pixelToAxial(bottomRight.x, bottomRight.y, this.hexRadius),
2081 ];
2082 // Three rings of slack at 100%, as before, and proportionally more when
2083 // zoomed out, where a fixed ring count would be a sliver of the screen.
2084 // Never fewer than three: combs just outside the camera must stay mounted
2085 // so focus, links, and realtime updates can reach them.
2086 const overscan = clamp(Math.round(3 / Math.max(this.zoom, 0.05)), 3, 16);
2087 return {
2088 qMin: clamp(Math.min(...corners.map((item) => item.q)) - overscan, -this.bounds.radius, this.bounds.radius),
2089 qMax: clamp(Math.max(...corners.map((item) => item.q)) + overscan, -this.bounds.radius, this.bounds.radius),
2090 rMin: clamp(Math.min(...corners.map((item) => item.r)) - overscan, -this.bounds.radius, this.bounds.radius),
2091 rMax: clamp(Math.max(...corners.map((item) => item.r)) + overscan, -this.bounds.radius, this.bounds.radius),
2092 originX: this.world.originX,
2093 };
2094 }
2095
2096 chunksForVisibleRegion() {
2097 const bounds = this.visibleCoordinates();
2098 const centre = this.stageToWorld(this.stageSize().width / 2, this.stageSize().height / 2);
2099 const centreAxial = pixelToAxial(centre.x, centre.y, this.hexRadius);
2100 const chunks = new Map();
2101 const ordered = [];
2102 for (let q = Math.floor(bounds.qMin / WALL_LIMITS.chunkSize) * WALL_LIMITS.chunkSize; q <= bounds.qMax; q += WALL_LIMITS.chunkSize) {
2103 for (let r = Math.floor(bounds.rMin / WALL_LIMITS.chunkSize) * WALL_LIMITS.chunkSize; r <= bounds.rMax; r += WALL_LIMITS.chunkSize) {
2104 const chunk = chunkFor(q, r);
2105 if (chunks.has(chunk.key)) continue;
2106 chunks.set(chunk.key, chunk);
2107 ordered.push(chunk);
2108 }
2109 }
2110 if (ordered.length <= MAX_VISIBLE_CHUNKS) return chunks;
2111 // Pulled far enough out that the viewport covers more wall than one pass
2112 // should fetch. Keep the chunks nearest the camera so the middle of the
2113 // view is coherent; the rest load as the viewer moves toward them.
2114 const distance = (chunk) => hexDistance(
2115 (chunk.qMin + chunk.qMax) / 2,
2116 (chunk.rMin + chunk.rMax) / 2,
2117 centreAxial.q,
2118 centreAxial.r,
2119 );
2120 ordered.sort((left, right) => distance(left) - distance(right));
2121 return new Map(ordered.slice(0, MAX_VISIBLE_CHUNKS).map((chunk) => [chunk.key, chunk]));
2122 }
2123
2124 // Every unit of transient scheduled work, in one place. "Settled" has to mean
2125 // the camera glide and the realtime debounces too, not just the frames and
2126 // promises: a glide that is still armed will schedule a viewport refresh when
2127 // it lands, so treating the wall as idle while one is pending reads a legal
2128 // mid-settle moment as an idle loop. The two long-lived intervals (pollTimer,
2129 // watchPollTimer) are deliberately excluded — they are meant to outlive idle.
2130 pendingWork() {
2131 const pending = [];
2132 if (this.growthFitFrame) pending.push("growthFitFrame");
2133 if (this.renderFrame) pending.push("renderFrame");
2134 if (this.momentumFrame) pending.push("momentumFrame");
2135 if (this.focusFrame) pending.push("focusFrame");
2136 if (this.announceFrame) pending.push("announceFrame");
2137 if (this.glideTimer) pending.push("glideTimer");
2138 if (this.eventTimer) pending.push("eventTimer");
2139 if (this.eventRetryTimer) pending.push("eventRetryTimer");
2140 if (this.listReconcileTimer) pending.push("listReconcileTimer");
2141 if (this.viewportRefreshDirty) pending.push("viewportRefreshDirty");
2142 if (this.viewportRefreshPromise) pending.push("viewportRefreshPromise");
2143 if (this.realtimeDrainPromise) pending.push("realtimeDrainPromise");
2144 return pending;
2145 }
2146
2147 async refreshVisible(force = false) {
2148 if (!this.active || this.mode !== "wall") return false;
2149 this.viewportRefreshDirty = true;
2150 this.viewportRefreshForce = this.viewportRefreshForce || Boolean(force);
2151 if (this.viewportRefreshPromise) return this.viewportRefreshPromise;
2152 const run = async () => {
2153 let result = false;
2154 let pass = 0;
2155 while (this.viewportRefreshDirty && pass < 2 && this.active && this.mode === "wall") {
2156 const passForce = this.viewportRefreshForce;
2157 this.viewportRefreshDirty = false;
2158 this.viewportRefreshForce = false;
2159 const refresh = typeof this.performVisibleRefresh === "function"
2160 ? this.performVisibleRefresh
2161 : HiveWallController.prototype.performVisibleRefresh;
2162 result = await refresh.call(this, passForce, 0);
2163 pass += 1;
2164 }
2165 return result;
2166 };
2167 const request = run().finally(() => {
2168 if (this.viewportRefreshPromise === request) this.viewportRefreshPromise = null;
2169 if (this.viewportRefreshDirty && this.active && this.mode === "wall") this.scheduleViewport();
2170 });
2171 this.viewportRefreshPromise = request;
2172 return request;
2173 }
2174
2175 async performVisibleRefresh(force = false, retry = 0) {
2176 if (!this.active || this.mode !== "wall") return false;
2177 const identityGeneration = this.identityGeneration;
2178 await this.refreshBounds();
2179 if (!this.active || this.mode !== "wall" || identityGeneration !== this.identityGeneration) return false;
2180 const targetRevision = Number(this.bounds.revision) || 0;
2181 if (this.hasUnaccountedPublicRevision(targetRevision, "wall")) {
2182 // Polling observed a public mutation for which no complete broadcast
2183 // chain was reconciled. Remove every shared projection synchronously;
2184 // a failed reload may leave an empty Wall, never stale public words.
2185 this.invalidatePublicProjectionCache({ resetConversation: false });
2186 }
2187 const cacheGeneration = this.publicCacheGeneration;
2188 const chunks = this.chunksForVisibleRegion();
2189 this.visibleChunkKeys = new Set(chunks.keys());
2190 const results = await Promise.all([...chunks.values()]
2191 .map((chunk) => this.loadChunk(chunk, force, targetRevision)));
2192 if (!this.active || this.mode !== "wall" || identityGeneration !== this.identityGeneration) return false;
2193 if (cacheGeneration !== this.publicCacheGeneration) {
2194 if (retry < 1) return this.performVisibleRefresh(true, retry + 1);
2195 return false;
2196 }
2197 const complete = results.every((result) => result?.ok && Number(result.revision) === targetRevision);
2198 if (!complete) return false;
2199 this.wallWindowRevision = Math.max(Number(this.wallWindowRevision) || 0, targetRevision);
2200 this.wall?.setAttribute?.("aria-busy", "false");
2201 this.render();
2202 return true;
2203 }
2204
2205 loadChunk(chunk, force = false, accountedRevision = null) {
2206 const expectedRevision = Number.isSafeInteger(Number(accountedRevision))
2207 ? Number(accountedRevision)
2208 : Number(this.bounds.revision) || 0;
2209 if (!force && this.loadedChunks.has(chunk.key)) {
2210 return Promise.resolve({ ok: true, revision: expectedRevision, cached: true });
2211 }
2212 if (this.inflightChunks.has(chunk.key)) {
2213 if (force) this.dirtyChunks.add(chunk.key);
2214 return this.inflightChunks.get(chunk.key);
2215 }
2216 let request;
2217 const identityGeneration = this.identityGeneration;
2218 const cacheGeneration = this.publicCacheGeneration;
2219 const initial = this.backend.wallRegion({ ...chunk, limit: 500 })
2220 .then((payload) => {
2221 if (!this.mounted || identityGeneration !== this.identityGeneration
2222 || cacheGeneration !== this.publicCacheGeneration) return { ok: false, stale: true };
2223 if (!payload || !Array.isArray(payload.cells) || !payload.bounds
2224 || !Number.isSafeInteger(Number(payload.bounds.revision))) throw new Error("The wall region was incomplete.");
2225 const payloadRevision = Number(payload.bounds.revision);
2226 const viewerAdvanced = this.viewerProjectionAdvanced(payload.bounds);
2227 if (!this.applyAuthoritativeBounds(payload.bounds)) throw new Error("This wall region returned an older snapshot.");
2228 if (viewerAdvanced && this.hasPublicProjection()) {
2229 this.invalidatePublicProjectionCache({ resetConversation: false });
2230 return { ok: false, advanced: true, viewerAdvanced: true, revision: payloadRevision };
2231 }
2232 if (payloadRevision < expectedRevision) throw new Error("This wall region was behind the requested snapshot.");
2233 if (payloadRevision > expectedRevision) {
2234 // A newer snapshot means another mutation landed after the viewport
2235 // target was chosen. Do not mix snapshots; invalidate the generation
2236 // so all sibling region promises become harmless and retry once.
2237 this.invalidatePublicProjectionCache({ resetConversation: false });
2238 return { ok: false, advanced: true, revision: payloadRevision };
2239 }
2240 for (const cell of payload.cells) this.mergeCell(cell);
2241 if (Array.isArray(payload.conversations)) {
2242 for (const conversation of payload.conversations) {
2243 if (conversation && conversation.id) this.conversations.set(conversation.id, conversation);
2244 }
2245 }
2246 this.loadedChunks.add(chunk.key);
2247 this.chunkAccess.set(chunk.key, Date.now());
2248 this.lastGoodAt = Date.now();
2249 this.pruneChunkCache();
2250 return { ok: true, revision: payloadRevision };
2251 })
2252 .catch((error) => {
2253 if (!this.mounted || identityGeneration !== this.identityGeneration
2254 || cacheGeneration !== this.publicCacheGeneration) return { ok: false, stale: true };
2255 this.dataStale = true;
2256 this.setConnectionState(navigator.onLine ? "stale" : "offline");
2257 if (!this.loadedChunks.has(chunk.key)) this.announce(`Could not load this part of the wall: ${error.message}`);
2258 return { ok: false, error };
2259 })
2260 .finally(() => {
2261 if (this.inflightChunks.get(chunk.key) === request) this.inflightChunks.delete(chunk.key);
2262 });
2263 request = initial.then((result) => {
2264 if (identityGeneration === this.identityGeneration
2265 && cacheGeneration === this.publicCacheGeneration
2266 && this.dirtyChunks.delete(chunk.key) && this.mounted) return this.loadChunk(chunk, true, expectedRevision);
2267 return result;
2268 });
2269 this.inflightChunks.set(chunk.key, request);
2270 return request;
2271 }
2272
2273 async hydratePlacement(q, r) {
2274 const targetQ = Number(q);
2275 const targetR = Number(r);
2276 if (!validCoordinate(targetQ, targetR)) return { ok: false, code: "out_of_bounds", choices: [] };
2277 const identityGeneration = this.identityGeneration;
2278 const cacheGeneration = this.publicCacheGeneration;
2279 try {
2280 const payload = await this.backend.wallRegion({
2281 qMin: clamp(targetQ - 1, -WALL_LIMITS.maxRadius, WALL_LIMITS.maxRadius),
2282 qMax: clamp(targetQ + 1, -WALL_LIMITS.maxRadius, WALL_LIMITS.maxRadius),
2283 rMin: clamp(targetR - 1, -WALL_LIMITS.maxRadius, WALL_LIMITS.maxRadius),
2284 rMax: clamp(targetR + 1, -WALL_LIMITS.maxRadius, WALL_LIMITS.maxRadius),
2285 limit: 16,
2286 });
2287 if (identityGeneration !== this.identityGeneration) return { ok: false, code: "identity_changed", choices: [] };
2288 if (cacheGeneration !== this.publicCacheGeneration) return { ok: false, code: "wall_changed", choices: [] };
2289 if (!payload || !Array.isArray(payload.cells) || !payload.bounds
2290 || !Number.isSafeInteger(Number(payload.bounds.revision))) {
2291 throw new Error("The wall did not return a complete placement check.");
2292 }
2293 const payloadRevision = Number(payload.bounds.revision);
2294 const viewerAdvanced = this.viewerProjectionAdvanced(payload.bounds);
2295 if (!this.applyAuthoritativeBounds(payload.bounds)) return { ok: false, code: "wall_changed", choices: [] };
2296 if (viewerAdvanced && this.hasPublicProjection()) {
2297 const rebuild = this.captureProjectionRebuild();
2298 this.invalidatePublicProjectionCache({ resetConversation: false });
2299 void this.rebuildPublicProjection(rebuild);
2300 return { ok: false, code: "wall_changed", choices: [] };
2301 }
2302 if (this.hasUnaccountedPublicRevision(payloadRevision)) {
2303 const rebuild = this.captureProjectionRebuild();
2304 this.invalidatePublicProjectionCache({ resetConversation: false });
2305 void this.rebuildPublicProjection(rebuild);
2306 return { ok: false, code: "wall_changed", choices: [] };
2307 }
2308 for (const cell of payload.cells) this.mergeCell(cell);
2309 if (Array.isArray(payload.conversations)) {
2310 for (const conversation of payload.conversations) {
2311 if (conversation && conversation.id) this.conversations.set(conversation.id, conversation);
2312 }
2313 }
2314 this.lastGoodAt = Date.now();
2315 this.dataStale = false;
2316 this.render();
2317 if (!validCoordinate(targetQ, targetR, this.bounds.radius)) {
2318 return { ok: false, code: "out_of_bounds", choices: [] };
2319 }
2320 return {
2321 ok: true,
2322 occupied: this.cells.get(cellKey(targetQ, targetR)) || null,
2323 choices: conversationChoices(this.cells, targetQ, targetR, this.conversations),
2324 groups: adjacentConversationGroups(this.cells, targetQ, targetR, this.conversations),
2325 };
2326 } catch (error) {
2327 this.dataStale = true;
2328 this.setConnectionState(navigator.onLine ? "stale" : "offline");
2329 return { ok: false, code: "unavailable", choices: [], error };
2330 }
2331 }
2332
2333 mergeCell(cell, options = {}) {
2334 const q = Number(cell && cell.q);
2335 const r = Number(cell && cell.r);
2336 if (!cell || typeof cell.id !== "string" || !validCoordinate(q, r)) return null;
2337 const normalized = {
2338 ...cell,
2339 q,
2340 r,
2341 seq: Number(cell.seq) || 0,
2342 version: Number(cell.version) || 1,
2343 contentVersion: Number(cell.contentVersion) || 1,
2344 };
2345 const previous = this.cellsById.get(normalized.id);
2346 if (previous
2347 && normalized.version === previous.version
2348 && normalized.contentVersion === previous.contentVersion) {
2349 normalized.viewerReported = Boolean(previous.viewerReported || normalized.viewerReported);
2350 normalized.viewerHidden = Boolean(previous.viewerHidden || normalized.viewerHidden);
2351 if (normalized.viewerHidden) normalized.body = null;
2352 }
2353 if (previous && (normalized.version < previous.version
2354 || (normalized.version === previous.version && normalized.contentVersion < previous.contentVersion))) return previous;
2355 const projectionFields = ["version", "contentVersion", "status", "body", "author", "membership", "replyToId", "conversationId", "viewerReported", "viewerHidden", "isMine"];
2356 const projectionChanged = !previous || projectionFields.some((field) => previous[field] !== normalized[field]);
2357 const contentVersionChanged = Boolean(previous && previous.contentVersion !== normalized.contentVersion);
2358 const canonical = previous || normalized;
2359 if (previous) Object.assign(canonical, normalized);
2360 this.cells.set(cellKey(q, r), canonical);
2361 this.cellsById.set(canonical.id, canonical);
2362 this.cellChunks.set(canonical.id, chunkFor(q, r).key);
2363 const listIndex = this.listCells.findIndex((item) => item.id === canonical.id);
2364 if (listIndex >= 0) this.listCells[listIndex] = canonical;
2365 if (this.readerCell?.id === canonical.id) {
2366 const reportForm = this.root.querySelector("[data-wall-report-form]");
2367 const operatorForm = this.root.querySelector("[data-wall-operator-form]");
2368 const reportWasOpen = Boolean(reportForm && !reportForm.hidden);
2369 const operatorWasOpen = Boolean(operatorForm && !operatorForm.hidden);
2370 const reportStillValid = reportWasOpen && !contentVersionChanged && canonical.status === "visible"
2371 && !canonical.isMine && !canonical.viewerReported;
2372 const operatorStillValid = operatorWasOpen && !contentVersionChanged && canonical.status === "visible" && this.operator;
2373 const preserveForms = this.readerBusy || reportStillValid || operatorStillValid;
2374 const formInvalidated = (reportWasOpen || operatorWasOpen) && !preserveForms;
2375 if (contentVersionChanged) this.reportRequest = null;
2376 this.readerCell = canonical;
2377 if (projectionChanged && (this.reader?.open || this.reader?.hasAttribute("open"))) {
2378 this.paintReaderCell(canonical, { preserveForms });
2379 if (formInvalidated) this.toast("That comb changed, so the open review form was closed. Review the current version before acting.");
2380 }
2381 }
2382 if (options.renderList !== false
2383 && projectionChanged && listIndex >= 0 && this.mode === "list" && this.mounted) this.renderList();
2384 return canonical;
2385 }
2386
2387 pruneChunkCache() {
2388 const protectedIds = new Set([
2389 this.readerCell?.id,
2390 this.composeState?.cellId,
2391 this.composeState?.replyToId,
2392 ...this.listCells.map((cell) => cell.id),
2393 ].filter(Boolean));
2394 const candidates = [...this.loadedChunks]
2395 .filter((key) => !this.visibleChunkKeys.has(key) && !this.inflightChunks.has(key))
2396 .sort((left, right) => (this.chunkAccess.get(left) || 0) - (this.chunkAccess.get(right) || 0));
2397 while ((this.loadedChunks.size > MAX_CACHED_CHUNKS || this.cellsById.size > MAX_CACHED_CELLS) && candidates.length) {
2398 const key = candidates.shift();
2399 this.loadedChunks.delete(key);
2400 this.chunkAccess.delete(key);
2401 for (const [cellId, cellChunk] of this.cellChunks) {
2402 if (cellChunk !== key || protectedIds.has(cellId)) continue;
2403 const cell = this.cellsById.get(cellId);
2404 if (cell && this.cells.get(cellKey(cell.q, cell.r))?.id === cellId) this.cells.delete(cellKey(cell.q, cell.r));
2405 this.cellsById.delete(cellId);
2406 this.cellChunks.delete(cellId);
2407 }
2408 }
2409 if (this.conversations.size > 600) {
2410 const active = new Set([...this.cellsById.values()].map((cell) => cell.conversationId));
2411 for (const id of this.conversations.keys()) {
2412 if (this.conversations.size <= 600) break;
2413 if (!active.has(id) && id !== this.listConversationId) this.conversations.delete(id);
2414 }
2415 }
2416 }
2417
2418 scheduleViewport() {
2419 if (!this.active || this.renderFrame) return;
2420 this.renderFrame = requestAnimationFrame(() => {
2421 this.renderFrame = null;
2422 void this.refreshVisible(false);
2423 });
2424 }
2425
2426 queueRealtimeEvent(event) {
2427 const revision = Number(event?.revision);
2428 const q = Number(event?.q);
2429 const r = Number(event?.r);
2430 const cellId = typeof event?.cellId === "string" ? event.cellId : "";
2431 if (!Number.isSafeInteger(revision) || revision < 1 || !cellId || !validCoordinate(q, r)) return;
2432 const eventKey = `${cellId}:${revision}`;
2433 if (this.seenRealtimeEvents.has(eventKey)) return;
2434 this.seenRealtimeEvents.add(eventKey);
2435 if (this.seenRealtimeEvents.size > 512) this.seenRealtimeEvents.delete(this.seenRealtimeEvents.values().next().value);
2436 const sanitized = { ...event, cellId, revision, q, r, eventKey };
2437 if (this.pendingEvents.size >= 128 && !this.pendingEvents.has(event.cellId)) {
2438 const oldest = this.pendingEvents.keys().next().value;
2439 if (oldest) {
2440 const dropped = this.pendingEvents.get(oldest);
2441 this.pendingEvents.delete(oldest);
2442 if (dropped?.eventKey) this.seenRealtimeEvents.delete(dropped.eventKey);
2443 if (validCoordinate(Number(dropped?.q), Number(dropped?.r))) {
2444 const droppedChunk = chunkFor(Number(dropped.q), Number(dropped.r));
2445 this.loadedChunks.delete(droppedChunk.key);
2446 if (this.inflightChunks.has(droppedChunk.key)) this.dirtyChunks.add(droppedChunk.key);
2447 }
2448 }
2449 }
2450 const prior = this.pendingEvents.get(cellId);
2451 if (!prior || revision >= prior.revision) this.pendingEvents.set(cellId, sanitized);
2452 if (this.eventTimer) return;
2453 this.eventTimer = window.setTimeout(() => {
2454 this.eventTimer = null;
2455 const events = [...this.pendingEvents.values()];
2456 this.pendingEvents.clear();
2457 const drain = typeof this.queueRealtimeDrain === "function"
2458 ? this.queueRealtimeDrain
2459 : HiveWallController.prototype.queueRealtimeDrain;
2460 void drain.call(this, events);
2461 }, 140);
2462 }
2463
2464 queueRealtimeDrain(events) {
2465 if (!this.realtimeDrainQueue) this.realtimeDrainQueue = new Map();
2466 for (const event of Array.isArray(events) ? events : []) {
2467 if (!event?.eventKey || !event?.cellId) continue;
2468 const prior = this.realtimeDrainQueue.get(event.cellId);
2469 if (!prior || Number(event.revision) >= Number(prior.revision)) {
2470 this.realtimeDrainQueue.set(event.cellId, event);
2471 }
2472 }
2473 if (this.realtimeDrainPromise || !this.realtimeDrainQueue.size) return this.realtimeDrainPromise;
2474 const activationGeneration = this.activationGeneration;
2475 const identityGeneration = this.identityGeneration;
2476 const run = async () => {
2477 while (this.realtimeDrainQueue.size
2478 && this.isContextCurrent(activationGeneration, identityGeneration)) {
2479 const batch = [...this.realtimeDrainQueue.values()];
2480 this.realtimeDrainQueue.clear();
2481 for (const event of batch) this.consumingEvents.set(event.eventKey, event);
2482 await this.consumeRealtimeEvents(batch);
2483 }
2484 };
2485 let request;
2486 request = run().finally(() => {
2487 if (this.realtimeDrainPromise === request) this.realtimeDrainPromise = null;
2488 if (this.realtimeDrainQueue.size && this.active) this.queueRealtimeDrain([]);
2489 });
2490 this.realtimeDrainPromise = request;
2491 return request;
2492 }
2493
2494 scheduleRealtimeRetries(activationGeneration, identityGeneration) {
2495 if (!this.retryEvents.size || this.eventRetryTimer) return;
2496 this.eventRetryTimer = window.setTimeout(() => {
2497 this.eventRetryTimer = null;
2498 if (this.isContextCurrent(activationGeneration, identityGeneration)) {
2499 const retryEvents = [...this.retryEvents.values()];
2500 this.retryEvents.clear();
2501 for (const event of retryEvents) this.queueRealtimeEvent(event);
2502 }
2503 }, 600);
2504 }
2505
2506 scheduleListReconciliation(activationGeneration, identityGeneration, immediate = false) {
2507 if (this.listReconcileTimer || this.mode !== "list" || !this.listReconcileEvents.size
2508 || !this.isContextCurrent(activationGeneration, identityGeneration)) return;
2509 const loadedIds = new Set(this.listCells.map((cell) => cell?.id).filter(Boolean));
2510 const queued = [...this.listReconcileEvents.values()]
2511 .filter((event) => event.evicted || loadedIds.has(event.cellId))
2512 .slice(0, 64);
2513 if (!queued.length) return;
2514 const attempt = Math.max(...queued.map((event) => Number(event.reconcileAttempts) || 1));
2515 const delay = immediate ? 0 : Math.min(30_000, 600 * (2 ** Math.min(6, Math.max(0, attempt - 1))));
2516 this.listReconcileTimer = window.setTimeout(() => {
2517 this.listReconcileTimer = null;
2518 if (!this.isContextCurrent(activationGeneration, identityGeneration) || this.mode !== "list") return;
2519 for (const event of queued) {
2520 const current = this.listReconcileEvents.get(event.cellId);
2521 if (!current || current.revision !== event.revision) continue;
2522 this.seenRealtimeEvents.delete(event.eventKey);
2523 this.queueRealtimeEvent(event);
2524 }
2525 }, delay);
2526 }
2527
2528 wakeListReconciliation() {
2529 if (!this.active || !this.mounted || this.mode !== "list" || !this.listReconcileEvents.size) return;
2530 if (this.listReconcileTimer) window.clearTimeout(this.listReconcileTimer);
2531 this.listReconcileTimer = null;
2532 this.scheduleListReconciliation(this.activationGeneration, this.identityGeneration, true);
2533 }
2534
2535 async consumeRealtimeEvents(events) {
2536 const activationGeneration = this.activationGeneration;
2537 const identityGeneration = this.identityGeneration;
2538 const cacheGeneration = this.publicCacheGeneration;
2539 const realtimeMode = this.mode;
2540 const listRequestGeneration = this.listRequestGeneration;
2541 const listConversationId = this.listConversationId;
2542 const retainedListRevision = Number(this.listWindowRevision) || 0;
2543 const realtimeContextCurrent = () => (
2544 this.isContextCurrent(activationGeneration, identityGeneration)
2545 && cacheGeneration === this.publicCacheGeneration
2546 && realtimeMode === this.mode
2547 && (realtimeMode !== "list" || (
2548 listRequestGeneration === this.listRequestGeneration
2549 && listConversationId === this.listConversationId
2550 ))
2551 );
2552 const requeueForCurrentContext = () => {
2553 if (!this.isContextCurrent(activationGeneration, identityGeneration)) return;
2554 for (const event of events) {
2555 this.seenRealtimeEvents.delete(event.eventKey);
2556 this.queueRealtimeEvent(event);
2557 }
2558 };
2559 try {
2560 await this.refreshBounds();
2561 if (!this.isContextCurrent(activationGeneration, identityGeneration)) return;
2562 if (!realtimeContextCurrent()) {
2563 requeueForCurrentContext();
2564 return;
2565 }
2566 const authoritativeRevision = this.bounds.revision;
2567 const verified = events.filter((event) => (
2568 event.revision > 0 && event.revision <= authoritativeRevision
2569 ));
2570 for (const event of events) {
2571 if (event.revision > authoritativeRevision) {
2572 this.seenRealtimeEvents.delete(event.eventKey);
2573 if ((Number(event.retries) || 0) < 3) {
2574 const retried = { ...event, retries: (Number(event.retries) || 0) + 1 };
2575 const prior = this.retryEvents.get(event.cellId);
2576 if (!prior || retried.revision >= prior.revision) this.retryEvents.set(event.cellId, retried);
2577 }
2578 }
2579 }
2580 this.scheduleRealtimeRetries(activationGeneration, identityGeneration);
2581 if (!verified.length) return;
2582 const previouslyLoadedChunks = new Set();
2583 const previouslyInflightChunks = new Set();
2584 for (const event of verified) {
2585 const changedChunk = chunkFor(event.q, event.r);
2586 if (this.loadedChunks.has(changedChunk.key)) previouslyLoadedChunks.add(changedChunk.key);
2587 if (this.inflightChunks.has(changedChunk.key)) previouslyInflightChunks.add(changedChunk.key);
2588 this.loadedChunks.delete(changedChunk.key);
2589 if (this.inflightChunks.has(changedChunk.key)) this.dirtyChunks.add(changedChunk.key);
2590 }
2591 if (realtimeMode === "list") {
2592 const expectedRevisionCount = authoritativeRevision - retainedListRevision;
2593 const receivedRevisions = new Set(verified
2594 .map((event) => event.revision)
2595 .filter((revision) => revision > retainedListRevision && revision <= authoritativeRevision));
2596 const completeRevisionChain = expectedRevisionCount >= 0
2597 && receivedRevisions.size === expectedRevisionCount;
2598 if ((this.listCells.length || this.cells?.size || this.conversations?.size || this.readerCell)
2599 && !completeRevisionChain) {
2600 // A later event arrived after at least one missed invalidation. The
2601 // missing revision could belong to any older retained row, so clear
2602 // the rendered window before attempting a clean page-one rebuild.
2603 const rebuildView = this.captureAccessibleListView(true);
2604 this.invalidatePublicProjectionCache({ resetConversation: false });
2605 await this.refreshList(true, rebuildView);
2606 if (!this.isContextCurrent(activationGeneration, identityGeneration)
2607 || this.mode !== "list" || this.listConversationId !== listConversationId) return;
2608 this.announce("The Wall list was rebuilt after catching up with missed changes.");
2609 return;
2610 }
2611 // A newest-page refresh cannot authoritatively update a comb that the
2612 // reader loaded several pages ago. Re-read every changed comb already
2613 // present in the retained list window, merge those rows without
2614 // rendering, then let the single bounded list refresh reconcile and
2615 // paint the complete window while preserving focus and scroll.
2616 const loadedIds = new Set(this.listCells.map((cell) => cell?.id).filter(Boolean));
2617 const loadedEvents = verified.filter((event) => (
2618 loadedIds.has(event.cellId) || this.listReconcileEvents.get(event.cellId)?.evicted
2619 ));
2620 const reconcileView = this.captureAccessibleListView(true);
2621 // Cell and conversation caches also feed reply labels and participant
2622 // names. Evict every verified support projection, even when the
2623 // changed comb itself is outside the retained list window.
2624 for (const event of verified) {
2625 if (event.conversationId) this.conversations.delete(event.conversationId);
2626 this.evictPublicCellProjection(event.cellId);
2627 }
2628 this.renderList();
2629 this.restoreAccessibleListView(reconcileView, this.listRequestGeneration, this.listConversationId);
2630 if (loadedEvents.length) {
2631 for (const event of loadedEvents) {
2632 const prior = this.listReconcileEvents.get(event.cellId);
2633 if (!prior && this.listReconcileEvents.size >= MAX_LIST_RECONCILE_EVENTS) {
2634 // A long outage plus a very large retained history must not grow
2635 // an unbounded retry map. Drop the hidden/list DOM window; the
2636 // immediate page read below and later Load more calls rebuild it
2637 // authoritatively instead of ever showing a stale cached row.
2638 const rebuildView = this.captureAccessibleListView(true);
2639 this.invalidatePublicProjectionCache({ resetConversation: false });
2640 await this.refreshList(true, rebuildView);
2641 if (this.isContextCurrent(activationGeneration, identityGeneration)
2642 && this.mode === "list" && this.listConversationId === listConversationId) {
2643 this.announce("The Wall list was rebuilt after a large batch of changes.");
2644 }
2645 return;
2646 }
2647 if (!prior || event.revision >= prior.revision) {
2648 this.listReconcileEvents.set(event.cellId, {
2649 ...event,
2650 reconcileAttempts: Math.max(1, Number(prior?.reconcileAttempts) || Number(event.reconcileAttempts) || 1),
2651 });
2652 }
2653 }
2654 if (!realtimeContextCurrent()) {
2655 requeueForCurrentContext();
2656 return;
2657 }
2658 for (const event of loadedEvents) {
2659 const obligation = this.listReconcileEvents.get(event.cellId);
2660 if (obligation) this.listReconcileEvents.set(event.cellId, { ...obligation, evicted: true });
2661 }
2662 const authoritative = await Promise.allSettled(
2663 loadedEvents.map((event) => this.backend.wallCell(event.cellId)),
2664 );
2665 if (!realtimeContextCurrent()) {
2666 requeueForCurrentContext();
2667 return;
2668 }
2669 const advancedExact = authoritative.some((outcome) => (
2670 outcome.status === "fulfilled"
2671 && Number.isSafeInteger(Number(outcome.value?.bounds?.revision))
2672 && (
2673 Number(outcome.value.bounds.revision) > authoritativeRevision
2674 || this.viewerProjectionAdvanced(outcome.value.bounds)
2675 )
2676 ));
2677 if (advancedExact) {
2678 this.invalidatePublicProjectionCache({ resetConversation: false });
2679 await this.refreshList(true, reconcileView);
2680 if (this.isContextCurrent(activationGeneration, identityGeneration)
2681 && this.mode === "list" && this.listConversationId === listConversationId) {
2682 this.announce("The Wall list was rebuilt after a newer change arrived mid-refresh.");
2683 }
2684 return;
2685 }
2686 const changedCells = [];
2687 for (let index = 0; index < authoritative.length; index += 1) {
2688 const outcome = authoritative[index];
2689 const event = loadedEvents[index];
2690 const result = outcome.status === "fulfilled" ? outcome.value : null;
2691 if (!result?.cell || !result?.bounds
2692 || Number(result.bounds.revision) !== authoritativeRevision
2693 || !this.applyAuthoritativeBounds(result.bounds)) {
2694 this.seenRealtimeEvents.delete(event.eventKey);
2695 const prior = this.listReconcileEvents.get(event.cellId) || event;
2696 this.listReconcileEvents.set(event.cellId, {
2697 ...prior,
2698 reconcileAttempts: Math.min(20, (Number(prior.reconcileAttempts) || 1) + 1),
2699 });
2700 continue;
2701 }
2702 if (result?.conversation?.id) this.conversations.set(result.conversation.id, result.conversation);
2703 const canonical = this.mergeCell(result.cell, { renderList: false });
2704 if (canonical) changedCells.push(canonical);
2705 const obligation = this.listReconcileEvents.get(event.cellId);
2706 if (!obligation || obligation.revision <= event.revision) this.listReconcileEvents.delete(event.cellId);
2707 }
2708 this.listCells = reconcileAccessibleListWindow(this.listCells, changedCells, this.listConversationId);
2709 this.scheduleListReconciliation(activationGeneration, identityGeneration);
2710 if (completeRevisionChain) {
2711 // Failed exact reads are safe to account only because their public
2712 // rows were synchronously evicted above; the retained obligation
2713 // keeps retrying until the authoritative comb can be reinserted.
2714 this.listWindowRevision = Math.max(this.listWindowRevision, authoritativeRevision);
2715 }
2716 } else if (completeRevisionChain) {
2717 this.listWindowRevision = Math.max(this.listWindowRevision, authoritativeRevision);
2718 }
2719 await this.refreshList(true, reconcileView);
2720 if (!this.isContextCurrent(activationGeneration, identityGeneration)
2721 || this.mode !== "list" || this.listConversationId !== listConversationId) return;
2722 this.scheduleListReconciliation(activationGeneration, identityGeneration);
2723 this.announce(`${verified.length} wall ${verified.length === 1 ? "comb has" : "combs have"} changed.`);
2724 return;
2725 }
2726 const retainedWallRevision = Number(this.wallWindowRevision) || 0;
2727 const expectedRevisionCount = authoritativeRevision - retainedWallRevision;
2728 const receivedRevisions = new Set(verified
2729 .map((event) => event.revision)
2730 .filter((revision) => revision > retainedWallRevision && revision <= authoritativeRevision));
2731 const completeRevisionChain = expectedRevisionCount >= 0
2732 && receivedRevisions.size === expectedRevisionCount;
2733 if (this.hasPublicProjection("wall") && !completeRevisionChain) {
2734 this.invalidatePublicProjectionCache({ resetConversation: false });
2735 await this.refreshVisible(true);
2736 if (this.isContextCurrent(activationGeneration, identityGeneration) && this.mode === "wall") {
2737 this.announce("The Wall was rebuilt after catching up with missed changes.");
2738 }
2739 return;
2740 }
2741 const newEvents = verified.filter((event) => event.revision > retainedWallRevision);
2742 if (!newEvents.length) return;
2743 if (!this.hasPublicProjection("wall")) {
2744 await this.refreshVisible(true);
2745 return;
2746 }
2747 const affectedChunks = new Map();
2748 const visibleChunks = this.chunksForVisibleRegion();
2749 let readerAffected = false;
2750 for (const event of newEvents) {
2751 const changedChunk = chunkFor(event.q, event.r);
2752 affectedChunks.set(changedChunk.key, changedChunk);
2753 if (event.conversationId) {
2754 this.conversations.delete(event.conversationId);
2755 if (this.readerCell?.conversationId === event.conversationId) readerAffected = true;
2756 }
2757 }
2758 if (readerAffected) this.closeReaderForProjectionRefresh();
2759 if ([...affectedChunks.keys()].some((key) => previouslyInflightChunks.has(key))) {
2760 this.invalidatePublicProjectionCache({ resetConversation: false });
2761 await this.refreshVisible(true);
2762 return;
2763 }
2764 const reloadChunks = [];
2765 for (const [key, chunk] of affectedChunks) {
2766 const hadCachedCells = [...this.cellChunks.values()].some((cellChunk) => cellChunk === key);
2767 this.evictWallChunkProjection(key, { preserveGeometry: true });
2768 if (previouslyLoadedChunks.has(key) || hadCachedCells || visibleChunks.has(key)) reloadChunks.push(chunk);
2769 }
2770 // Blank only the changed words while retaining inert comb geometry until
2771 // the authoritative region arrives. This avoids a board-wide or chunk-wide
2772 // flash without ever displaying changed text from the prior revision.
2773 const reconciled = await Promise.all(reloadChunks
2774 .map((chunk) => this.loadChunk(chunk, true, authoritativeRevision)));
2775 if (!realtimeContextCurrent()) {
2776 if (this.isContextCurrent(activationGeneration, identityGeneration)) await this.refreshVisible(true);
2777 return;
2778 }
2779 if (!reconciled.every((result) => result?.ok && Number(result.revision) === authoritativeRevision)) {
2780 this.invalidatePublicProjectionCache({ resetConversation: false });
2781 await this.refreshVisible(true);
2782 return;
2783 }
2784 this.wallWindowRevision = Math.max(retainedWallRevision, authoritativeRevision);
2785 this.wall?.setAttribute?.("aria-busy", "false");
2786 this.render();
2787 this.announce(`${verified.length} wall ${verified.length === 1 ? "comb has" : "combs have"} changed.`);
2788 } finally {
2789 for (const event of events) this.consumingEvents.delete(event.eventKey);
2790 }
2791 }
2792
2793 render() {
2794 if (!this.mounted || this.mode !== "wall") return;
2795 const visible = this.visibleCoordinates();
2796 const keep = new Set();
2797 for (const [key, cell] of this.cells) {
2798 if (cell.q < visible.qMin || cell.q > visible.qMax || cell.r < visible.rMin || cell.r > visible.rMax) continue;
2799 if (hexDistance(cell.q, cell.r) > this.bounds.radius) continue;
2800 keep.add(key);
2801 let node = this.nodes.get(key);
2802 if (!node) {
2803 node = document.createElement("button");
2804 node.type = "button";
2805 node.className = "honey-comb";
2806 node.dataset.cellKey = key;
2807 node.innerHTML = '';
2808 this.cellLayer.append(node);
2809 this.nodes.set(key, node);
2810 }
2811 this.paintCellNode(node, cell);
2812 }
2813 for (const [key, node] of this.nodes) {
2814 if (!keep.has(key)) {
2815 node.remove();
2816 this.nodes.delete(key);
2817 }
2818 }
2819 this.renderConnections(keep);
2820 if (this.growthIntent) this.renderGrowthSlots();
2821 this.updateTarget();
2822 this.updateNewCount();
2823 }
2824
2825 paintCellNode(node, cell) {
2826 const point = axialToPixel(cell.q, cell.r, this.hexRadius);
2827 node.style.left = `calc(var(--honey-origin-x) + ${point.x}px)`;
2828 node.style.top = `calc(var(--honey-origin-y) + ${point.y}px)`;
2829 node.style.setProperty("--thread-hue", String(hueFor(cell.conversationId)));
2830 node.dataset.threadPattern = String(patternFor(cell.conversationId));
2831 node.dataset.status = cell.status;
2832 node.dataset.conversationId = cell.conversationId;
2833 node.id = `honey-cell-${cell.id}`;
2834 node.tabIndex = -1;
2835 node.disabled = false;
2836 delete node.dataset.placeholder;
2837 node.classList.remove("is-refreshing");
2838 node.classList.toggle("is-branch-origin", cell.origin?.kind === "branch");
2839 node.classList.toggle("is-meet-origin", cell.origin?.kind === "meet");
2840 node.classList.toggle("is-unseen", !this.seen.has(cell.id));
2841 node.classList.toggle("is-mine", Boolean(cell.isMine));
2842 node.classList.toggle("is-viewer-hidden", Boolean(cell.viewerHidden));
2843 const author = node.querySelector(".honey-comb-author");
2844 const body = node.querySelector(".honey-comb-body");
2845 const foot = node.querySelector(".honey-comb-foot");
2846 setTextIfChanged(author, cell.author || (cell.status === "quarantined" ? "Under review" : "Open space kept"));
2847 setTextIfChanged(body, statusText(cell));
2848 setTextIfChanged(foot, `${timeLabel(cell.createdAt)} · ${cell.membership === "alumni" ? "DHG" : cell.membership === "guest" ? "Guest" : "Hive"}`);
2849 const ariaLabel = `${author.textContent}: ${statusText(cell)}`;
2850 if (node.getAttribute("aria-label") !== ariaLabel) node.setAttribute("aria-label", ariaLabel);
2851 }
2852
2853 renderConnections(visibleKeys) {
2854 const keep = new Set();
2855 const paintLine = (key, fromCell, toCell, relation = "growth") => {
2856 const from = axialToPixel(fromCell.q, fromCell.r, this.hexRadius);
2857 const to = axialToPixel(toCell.q, toCell.r, this.hexRadius);
2858 const dx = to.x - from.x;
2859 const dy = to.y - from.y;
2860 let line = this.connectionNodes.get(key);
2861 if (!line) {
2862 line = document.createElement("span");
2863 line.className = "honey-link";
2864 this.connectionLayer.append(line);
2865 this.connectionNodes.set(key, line);
2866 }
2867 keep.add(key);
2868 line.classList.remove("is-refreshing");
2869 line.dataset.relation = relation;
2870 line.style.left = `calc(var(--honey-origin-x) + ${from.x}px)`;
2871 line.style.top = `calc(var(--honey-origin-y) + ${from.y}px)`;
2872 line.style.width = `${Math.hypot(dx, dy)}px`;
2873 line.style.transform = `rotate(${Math.atan2(dy, dx)}rad)`;
2874 line.style.setProperty("--thread-hue", String(hueFor(toCell.conversationId)));
2875 line.style.setProperty("--source-hue", String(hueFor(fromCell.conversationId)));
2876 };
2877 for (const key of visibleKeys) {
2878 const cell = this.cells.get(key);
2879 if (!cell) continue;
2880 if (cell.growthParentId) {
2881 const parent = this.cellsById.get(cell.growthParentId);
2882 if (parent && visibleKeys.has(cellKey(parent.q, parent.r))) {
2883 paintLine(`growth:${cell.id}:${parent.id}`, parent, cell, "growth");
2884 }
2885 }
2886 for (const anchorLink of cell.origin?.anchors || []) {
2887 const anchor = this.cellsById.get(anchorLink.cellId);
2888 if (!anchor || !visibleKeys.has(cellKey(anchor.q, anchor.r))) continue;
2889 paintLine(`origin:${cell.id}:${anchor.id}`, anchor, cell, cell.origin.kind);
2890 }
2891 }
2892 for (const [key, line] of this.connectionNodes) {
2893 if (keep.has(key)) continue;
2894 line.remove();
2895 this.connectionNodes.delete(key);
2896 }
2897 }
2898
2899 updateTarget() {
2900 if (!this.target) return;
2901 if (this.selectedCellKey) {
2902 const previous = this.nodes.get(this.selectedCellKey);
2903 previous?.classList.remove("is-selected");
2904 previous?.removeAttribute("aria-current");
2905 }
2906 const point = axialToPixel(this.selected.q, this.selected.r, this.hexRadius);
2907 this.target.style.left = `calc(var(--honey-origin-x) + ${point.x}px)`;
2908 this.target.style.top = `calc(var(--honey-origin-y) + ${point.y}px)`;
2909 const occupied = this.cells.get(cellKey(this.selected.q, this.selected.r));
2910 this.target.classList.toggle("is-occupied", Boolean(occupied));
2911 this.target.querySelector("span").textContent = occupied ? "•" : "+";
2912 if (occupied) {
2913 this.selectedCellKey = cellKey(occupied.q, occupied.r);
2914 const selectedNode = this.nodes.get(this.selectedCellKey);
2915 if (selectedNode) {
2916 selectedNode.classList.add("is-selected");
2917 selectedNode.setAttribute("aria-current", "true");
2918 this.stage?.setAttribute("aria-activedescendant", selectedNode.id || `honey-cell-${occupied.id}`);
2919 } else {
2920 this.stage?.removeAttribute("aria-activedescendant");
2921 }
2922 } else {
2923 this.selectedCellKey = null;
2924 this.stage?.removeAttribute("aria-activedescendant");
2925 }
2926 }
2927
2928 handleClick(event) {
2929 const action = event.target.closest("[data-wall-action]");
2930 if (action) {
2931 this.runToolbarAction(action.dataset.wallAction);
2932 return;
2933 }
2934 const closer = event.target.closest("[data-wall-close]");
2935 if (closer) {
2936 const dialog = closer.dataset.wallClose === "compose" ? this.compose
2937 : closer.dataset.wallClose === "reader" ? this.reader
2938 : this.watch;
2939 this.closeDialog(dialog);
2940 return;
2941 }
2942 const watchCase = event.target.closest("[data-wall-watch-case]");
2943 if (watchCase) {
2944 if (this.watchBusy) return;
2945 void this.openWatchCase(watchCase.dataset.wallWatchCase, Number(watchCase.dataset.wallWatchVersion));
2946 return;
2947 }
2948 if (event.target.closest("[data-wall-watch-more]")) {
2949 if (!this.watchBusy) void this.loadWatchQueue(false, this.watchGeneration);
2950 return;
2951 }
2952 const watchAction = event.target.closest("[data-wall-watch-action]");
2953 if (watchAction) {
2954 void this.moderateWatchCase(watchAction.dataset.wallWatchAction);
2955 return;
2956 }
2957 const readerAction = event.target.closest("[data-wall-reader-action]");
2958 if (readerAction) {
2959 if (this.readerBusy) return;
2960 void this.runReaderAction(readerAction.dataset.wallReaderAction);
2961 return;
2962 }
2963 const listCell = event.target.closest("[data-wall-list-cell]");
2964 if (listCell) {
2965 void this.openListCell(listCell.dataset.wallListCell, listCell);
2966 return;
2967 }
2968 const listConversation = event.target.closest("[data-wall-list-conversation]");
2969 if (listConversation) {
2970 void this.openListConversation(listConversation.dataset.wallListConversation);
2971 return;
2972 }
2973 const growthSlot = event.target.closest("[data-wall-growth-key]");
2974 if (growthSlot) {
2975 const [q, r] = String(growthSlot.dataset.wallGrowthKey || "").split(":").map(Number);
2976 if (validCoordinate(q, r, this.bounds.radius)) this.chooseGrowthCoordinate({ q, r }, growthSlot);
2977 return;
2978 }
2979 const cellNode = event.target.closest("[data-cell-key]");
2980 if (cellNode) {
2981 if (Date.now() <= this.suppressCellClickUntil) {
2982 event.preventDefault();
2983 event.stopPropagation();
2984 this.suppressCellClickUntil = 0;
2985 return;
2986 }
2987 const cell = this.cells.get(cellNode.dataset.cellKey);
2988 if (cell) {
2989 this.selected = { q: cell.q, r: cell.r };
2990 this.updateTarget();
2991 this.openReader(cell);
2992 }
2993 }
2994 }
2995
2996 runToolbarAction(action) {
2997 if (action === "add") {
2998 if (this.bounds.readOnly) {
2999 this.toast("The Wall is open to read while Hive Watch is verified. New combs will open soon.");
3000 return;
3001 }
3002 const coordinate = this.cells.has(cellKey(this.selected.q, this.selected.r))
3003 ? this.findNearestOpen(this.selected)
3004 : this.selected;
3005 if (!coordinate) {
3006 this.toast("No open comb is loaded yet. Center the Wall or try again after it grows.");
3007 return;
3008 }
3009 this.selected = coordinate;
3010 this.updateTarget();
3011 this.ensureCoordinateVisible(coordinate.q, coordinate.r);
3012 void this.preparePlacement(coordinate);
3013 }
3014 else if (action === "new") this.findNew();
3015 else if (action === "mine") this.findMine();
3016 else if (action === "center") this.centerWall(true);
3017 else if (action === "fit") this.fitWall(true);
3018 else if (action === "zoom-in") {
3019 this.applyCameraMotion("smooth");
3020 this.setZoom(this.zoom * ZOOM_STEP, null, { announce: true });
3021 }
3022 else if (action === "zoom-out") {
3023 this.applyCameraMotion("smooth");
3024 this.setZoom(this.zoom / ZOOM_STEP, null, { announce: true });
3025 }
3026 else if (action === "mode") this.setMode(this.mode === "wall" ? "list" : "wall");
3027 else if (action === "resume") void this.resumeCurrentDraft();
3028 else if (action === "load-more") void this.refreshList(false);
3029 else if (action === "list-all") void this.showAllListMessages();
3030 else if (action === "watch") void this.openWatch();
3031 else if (action === "cancel-growth") this.cancelGrowthIntent();
3032 else if (action === "nearest-growth") this.moveGrowthToNearestFrontier();
3033 }
3034
3035 handleStageKey(event) {
3036 if (isEditableField(event.target)) return;
3037 // Shift with an arrow glides the camera without moving the viewer's place
3038 // in the wall, so looking around never loses the selected comb.
3039 if (event.shiftKey && ["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].includes(event.key)) {
3040 event.preventDefault();
3041 const step = PAN_KEY_STEP;
3042 const dx = event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0;
3043 const dy = event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0;
3044 this.stopMomentum();
3045 this.panBy(dx, dy);
3046 return;
3047 }
3048 if (event.key === "+" || event.key === "=") {
3049 event.preventDefault();
3050 this.applyCameraMotion("smooth");
3051 this.setZoom(this.zoom * ZOOM_STEP, null, { announce: true });
3052 return;
3053 }
3054 if (event.key === "-" || event.key === "_") {
3055 event.preventDefault();
3056 this.applyCameraMotion("smooth");
3057 this.setZoom(this.zoom / ZOOM_STEP, null, { announce: true });
3058 return;
3059 }
3060 if (event.key === "0") {
3061 event.preventDefault();
3062 this.applyCameraMotion("smooth");
3063 this.fitWall(true);
3064 return;
3065 }
3066 let direction = null;
3067 if (event.key === "ArrowRight") direction = 0;
3068 else if (event.key === "ArrowUp") direction = 2;
3069 else if (event.key === "ArrowLeft") direction = 3;
3070 else if (event.key === "ArrowDown") direction = 5;
3071 else if (["e", "9"].includes(event.key.toLowerCase())) direction = 1;
3072 else if (["q", "7"].includes(event.key.toLowerCase())) direction = 2;
3073 else if (["a", "4"].includes(event.key.toLowerCase())) direction = 3;
3074 else if (["z", "1"].includes(event.key.toLowerCase())) direction = 4;
3075 else if (["c", "3"].includes(event.key.toLowerCase())) direction = 5;
3076 else if (["d", "6"].includes(event.key.toLowerCase())) direction = 0;
3077 if (event.key === "Escape" && this.growthIntent) {
3078 event.preventDefault();
3079 this.cancelGrowthIntent();
3080 return;
3081 }
3082 if (direction != null) {
3083 event.preventDefault();
3084 const [dq, dr] = HEX_DIRECTIONS[direction];
3085 const origin = this.growthIntent?.origin || this.selected;
3086 const next = { q: origin.q + dq, r: origin.r + dr };
3087 if (validCoordinate(next.q, next.r, this.bounds.radius)) {
3088 this.selected = next;
3089 this.updateTarget();
3090 this.ensureCoordinateVisible(next.q, next.r);
3091 const growthSlot = this.growthSlots?.querySelector?.(`[data-wall-growth-key="${cellKey(next.q, next.r)}"]`);
3092 if (this.growthIntent && growthSlot && !growthSlot.disabled) growthSlot.focus({ preventScroll: true });
3093 this.announce(`${HEX_DIRECTION_LABELS[direction]} comb${this.cells.has(cellKey(next.q, next.r)) ? ", occupied" : ", open"}.`);
3094 }
3095 } else if (event.key === "Home") {
3096 event.preventDefault();
3097 this.selected = { q: 0, r: 0 };
3098 this.updateTarget();
3099 this.ensureCoordinateVisible(0, 0);
3100 this.announce("Centered on comb 0, 0.");
3101 } else if (event.key === "Enter" || event.key === " ") {
3102 event.preventDefault();
3103 if (this.growthIntent && this.isGrowthCoordinate(this.selected)) {
3104 this.chooseGrowthCoordinate(this.selected, event.target);
3105 return;
3106 }
3107 const cell = this.cells.get(cellKey(this.selected.q, this.selected.r));
3108 if (cell) this.openReader(cell);
3109 else void this.preparePlacement(this.selected);
3110 }
3111 }
3112
3113 handlePointerDown(event) {
3114 if (event.button !== 0 || event.target.closest("[data-wall-growth-key]")) return;
3115 this.stopMomentum();
3116 this.plane?.classList.remove("is-gliding");
3117 this.activePointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
3118 if (this.activePointers.size === 2) {
3119 this.beginPinch();
3120 this.pointer = null;
3121 return;
3122 }
3123 if (this.activePointers.size > 2) return;
3124 const cellNode = event.target.closest("[data-cell-key]");
3125 this.pointer = {
3126 id: event.pointerId,
3127 startX: event.clientX,
3128 startY: event.clientY,
3129 lastX: event.clientX,
3130 lastY: event.clientY,
3131 lastAt: Date.now(),
3132 velocityX: 0,
3133 velocityY: 0,
3134 cameraX: this.cameraX,
3135 cameraY: this.cameraY,
3136 moved: false,
3137 startedOnCell: Boolean(cellNode),
3138 startedCellKey: cellNode?.dataset?.cellKey || null,
3139 };
3140 this.stage.setPointerCapture?.(event.pointerId);
3141 }
3142
3143 beginPinch() {
3144 const points = [...this.activePointers.values()];
3145 if (points.length < 2) return;
3146 const rect = this.stage.getBoundingClientRect();
3147 const midX = (points[0].x + points[1].x) / 2 - rect.left;
3148 const midY = (points[0].y + points[1].y) / 2 - rect.top;
3149 this.plane?.classList.add("is-panning");
3150 this.pinch = {
3151 distance: Math.max(1, Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y)),
3152 zoom: this.zoom,
3153 midX,
3154 midY,
3155 // Anchor the world point under the fingers so a pinch that also drifts
3156 // across the screen pans as well as zooms, the way a map does.
3157 world: this.stageToWorld(midX, midY),
3158 moved: false,
3159 };
3160 }
3161
3162 updatePinch() {
3163 const points = [...this.activePointers.values()];
3164 if (!this.pinch || points.length < 2) return;
3165 const rect = this.stage.getBoundingClientRect();
3166 const midX = (points[0].x + points[1].x) / 2 - rect.left;
3167 const midY = (points[0].y + points[1].y) / 2 - rect.top;
3168 const distance = Math.max(1, Math.hypot(points[0].x - points[1].x, points[0].y - points[1].y));
3169 const ratio = distance / this.pinch.distance;
3170 if (Math.abs(ratio - 1) > 0.01 || Math.hypot(midX - this.pinch.midX, midY - this.pinch.midY) > 4) {
3171 this.pinch.moved = true;
3172 }
3173 const size = this.stageSize();
3174 this.zoom = this.clampZoom(this.pinch.zoom * ratio);
3175 this.cameraX = midX - size.width / 2 - this.pinch.world.x * this.zoom;
3176 this.cameraY = midY - (this.world.originY + this.pinch.world.y) * this.zoom;
3177 this.clampCamera();
3178 this.updatePlaneTransform();
3179 this.scheduleViewport();
3180 }
3181
3182 handlePointerMove(event) {
3183 if (this.activePointers.has(event.pointerId)) {
3184 this.activePointers.set(event.pointerId, { x: event.clientX, y: event.clientY });
3185 }
3186 if (this.pinch) {
3187 event.preventDefault();
3188 this.updatePinch();
3189 return;
3190 }
3191 if (!this.pointer || this.pointer.id !== event.pointerId) {
3192 if (event.pointerType === "mouse") this.selectFromPoint(event.clientX, event.clientY, false);
3193 return;
3194 }
3195 const dx = event.clientX - this.pointer.startX;
3196 const dy = event.clientY - this.pointer.startY;
3197 if (!this.pointer.moved && Math.hypot(dx, dy) > 8) this.pointer.moved = true;
3198 if (!this.pointer.moved) return;
3199 event.preventDefault();
3200 const now = Date.now();
3201 const elapsed = Math.max(1, now - this.pointer.lastAt);
3202 this.pointer.velocityX = (event.clientX - this.pointer.lastX) / elapsed;
3203 this.pointer.velocityY = (event.clientY - this.pointer.lastY) / elapsed;
3204 this.pointer.lastX = event.clientX;
3205 this.pointer.lastY = event.clientY;
3206 this.pointer.lastAt = now;
3207 // Drag moves the wall in both axes now. The old build only honoured
3208 // horizontal drags because vertical belonged to the document scroller.
3209 this.plane.classList.add("is-panning");
3210 this.cameraX = this.pointer.cameraX + dx;
3211 this.cameraY = this.pointer.cameraY + dy;
3212 this.clampCamera();
3213 this.updatePlaneTransform();
3214 this.updateTarget();
3215 this.scheduleViewport();
3216 }
3217
3218 handlePointerUp(event) {
3219 this.activePointers.delete(event.pointerId);
3220 if (this.pinch) {
3221 if (this.activePointers.size < 2) {
3222 const moved = this.pinch.moved;
3223 this.pinch = null;
3224 this.plane?.classList.remove("is-panning");
3225 if (moved) this.suppressCellClickUntil = Date.now() + 420;
3226 // A finger lifted mid-pinch must not become a fresh one-finger drag
3227 // anchored to a stale origin, so re-seat whatever is still down.
3228 const [remaining] = [...this.activePointers.keys()];
3229 if (remaining != null) {
3230 const point = this.activePointers.get(remaining);
3231 this.pointer = {
3232 id: remaining,
3233 startX: point.x,
3234 startY: point.y,
3235 lastX: point.x,
3236 lastY: point.y,
3237 lastAt: Date.now(),
3238 velocityX: 0,
3239 velocityY: 0,
3240 cameraX: this.cameraX,
3241 cameraY: this.cameraY,
3242 moved: true,
3243 startedOnCell: false,
3244 startedCellKey: null,
3245 };
3246 }
3247 }
3248 return;
3249 }
3250 if (!this.pointer || this.pointer.id !== event.pointerId) return;
3251 const moved = this.pointer.moved;
3252 const startedOnCell = this.pointer.startedOnCell;
3253 const startedCellKey = this.pointer.startedCellKey;
3254 const velocityX = this.pointer.velocityX;
3255 const velocityY = this.pointer.velocityY;
3256 this.pointer = null;
3257 this.plane.classList.remove("is-panning");
3258 if (moved) {
3259 if (startedOnCell) this.suppressCellClickUntil = Date.now() + 420;
3260 this.startMomentum(velocityX, velocityY);
3261 return;
3262 }
3263 if (startedOnCell && startedCellKey) {
3264 const cell = this.cells.get(startedCellKey);
3265 if (cell) {
3266 this.selected = { q: cell.q, r: cell.r };
3267 this.updateTarget();
3268 // Pointer capture retargets the synthetic click to the stage in some
3269 // browsers. Open the original comb here, then suppress a duplicate
3270 // cell click in browsers that preserve the original target.
3271 this.suppressCellClickUntil = Date.now() + 420;
3272 // Touch browsers can retarget their compatibility click to the modal
3273 // backdrop because the reader opens during pointerup. Ignore only that
3274 // immediate backdrop click; subsequent taps still dismiss normally.
3275 if (event.pointerType !== "mouse") {
3276 this.suppressBackdropClick = { dialog: this.reader, until: Date.now() + 420 };
3277 }
3278 this.openReader(cell, this.nodes.get(startedCellKey));
3279 }
3280 return;
3281 }
3282 if (!startedOnCell) {
3283 const coordinate = this.selectFromPoint(event.clientX, event.clientY, true);
3284 if (!coordinate) return;
3285 const cell = this.cells.get(cellKey(coordinate.q, coordinate.r));
3286 if (cell) this.openReader(cell);
3287 else void this.preparePlacement(coordinate);
3288 }
3289 }
3290
3291 cancelPointerGesture(event = null) {
3292 if (event?.pointerId != null) this.activePointers.delete(event.pointerId);
3293 else this.activePointers.clear();
3294 if (this.pointer?.moved && this.pointer.startedOnCell) this.suppressCellClickUntil = Date.now() + 420;
3295 this.pointer = null;
3296 this.pinch = null;
3297 this.plane?.classList.remove("is-panning");
3298 }
3299
3300 // A flick keeps travelling briefly so crossing a wide wall does not need a
3301 // dozen drags. Reduced motion gets the exact drag distance and nothing more.
3302 startMomentum(velocityX, velocityY) {
3303 this.stopMomentum();
3304 if (this.motionBehavior("smooth") !== "smooth") return;
3305 let vx = Number(velocityX) || 0;
3306 let vy = Number(velocityY) || 0;
3307 if (Math.hypot(vx, vy) < 0.35) return;
3308 const step = () => {
3309 this.momentumFrame = null;
3310 vx *= 0.92;
3311 vy *= 0.92;
3312 if (Math.hypot(vx, vy) < 0.02) {
3313 this.scheduleViewport();
3314 return;
3315 }
3316 const beforeX = this.cameraX;
3317 const beforeY = this.cameraY;
3318 this.cameraX += vx * 16;
3319 this.cameraY += vy * 16;
3320 this.clampCamera();
3321 this.updatePlaneTransform();
3322 if (this.cameraX === beforeX && this.cameraY === beforeY) {
3323 this.scheduleViewport();
3324 return;
3325 }
3326 this.scheduleViewport();
3327 this.momentumFrame = requestAnimationFrame(step);
3328 };
3329 this.momentumFrame = requestAnimationFrame(step);
3330 }
3331
3332 stopMomentum() {
3333 if (this.momentumFrame) cancelAnimationFrame(this.momentumFrame);
3334 this.momentumFrame = null;
3335 }
3336
3337 // Plain wheel and two-finger trackpad scroll pan the wall. Ctrl or Command
3338 // wheel zooms at the cursor, which is also what a trackpad pinch sends.
3339 handleWheel(event) {
3340 if (this.mode !== "wall" || this.stage?.hidden) return;
3341 event.preventDefault();
3342 this.stopMomentum();
3343 const rect = this.stage.getBoundingClientRect();
3344 if (event.ctrlKey || event.metaKey) {
3345 const factor = Math.exp(-event.deltaY * 0.0022);
3346 this.setZoom(this.zoom * factor, { x: event.clientX - rect.left, y: event.clientY - rect.top });
3347 return;
3348 }
3349 const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? rect.height : 1;
3350 this.panBy(event.deltaX * scale, event.deltaY * scale);
3351 }
3352
3353 // The stage clips, so a comb outside the camera can still hold DOM focus
3354 // while being invisible. Every focus target inside the plane pulls the
3355 // camera to itself, which keeps keyboard and screen-reader focus on screen
3356 // now that the browser can no longer scroll the wall for us.
3357 handleStageFocus(event) {
3358 if (this.mode !== "wall" || !this.plane) return;
3359 const node = event.target?.closest?.("[data-cell-key], [data-wall-growth-key]");
3360 if (!node) return;
3361 const key = node.dataset?.cellKey || node.dataset?.wallGrowthKey;
3362 const [q, r] = String(key || "").split(":").map(Number);
3363 if (!Number.isFinite(q) || !Number.isFinite(r)) return;
3364 this.ensureCoordinateVisible(q, r, "auto");
3365 }
3366
3367 handleDoubleClick(event) {
3368 if (this.mode !== "wall" || event.target.closest("[data-wall-growth-key]")) return;
3369 event.preventDefault();
3370 const rect = this.stage.getBoundingClientRect();
3371 const anchor = { x: event.clientX - rect.left, y: event.clientY - rect.top };
3372 // Double-click toggles between a readable close-up and the whole wall.
3373 const target = this.zoom > this.zoomFloor() * 1.05 ? this.fitZoom() : 1;
3374 this.applyCameraMotion("smooth");
3375 this.setZoom(target, anchor, { announce: true });
3376 }
3377
3378 selectFromPoint(clientX, clientY, commit) {
3379 const stageRect = this.stage.getBoundingClientRect();
3380 const point = this.stageToWorld(clientX - stageRect.left, clientY - stageRect.top);
3381 const coordinate = pixelToAxial(point.x, point.y, this.hexRadius);
3382 if (!validCoordinate(coordinate.q, coordinate.r, this.bounds.radius)) return null;
3383 this.selected = coordinate;
3384 this.updateTarget();
3385 if (commit) this.stage.focus({ preventScroll: true });
3386 return coordinate;
3387 }
3388
3389 growthCoordinates(origin = this.growthIntent?.origin) {
3390 if (!origin) return [];
3391 return neighbors(origin.q, origin.r).map((coordinate, direction) => ({
3392 ...coordinate,
3393 direction,
3394 directionLabel: HEX_DIRECTION_LABELS[direction],
3395 available: validCoordinate(coordinate.q, coordinate.r, this.bounds.radius)
3396 && !this.cells.has(cellKey(coordinate.q, coordinate.r)),
3397 }));
3398 }
3399
3400 isGrowthCoordinate(coordinate) {
3401 return this.growthCoordinates().some((slot) => (
3402 slot.available && slot.q === Number(coordinate?.q) && slot.r === Number(coordinate?.r)
3403 ));
3404 }
3405
3406 renderGrowthSlots() {
3407 if (!this.growthSlots || !this.growthTray) return;
3408 const state = this.growthIntent;
3409 if (!state) {
3410 if (this.growthFitFrame) cancelAnimationFrame(this.growthFitFrame);
3411 this.growthFitFrame = null;
3412 this.growthSlots.replaceChildren();
3413 this.growthTray.hidden = true;
3414 return;
3415 }
3416 const slots = this.growthCoordinates(state.origin);
3417 const available = slots.filter((slot) => slot.available);
3418 const retained = new Set();
3419 for (const slot of slots) {
3420 const key = cellKey(slot.q, slot.r);
3421 retained.add(key);
3422 let button = this.growthSlots.querySelector(`[data-wall-growth-key="${key}"]`);
3423 if (!button) {
3424 button = document.createElement("button");
3425 button.type = "button";
3426 button.className = "honey-growth-slot";
3427 button.dataset.wallGrowthKey = key;
3428 this.growthSlots.append(button);
3429 }
3430 button.dataset.direction = String(slot.direction);
3431 button.disabled = !slot.available;
3432 const point = axialToPixel(slot.q, slot.r, this.hexRadius);
3433 button.style.left = `calc(var(--honey-origin-x) + ${point.x}px)`;
3434 button.style.top = `calc(var(--honey-origin-y) + ${point.y}px)`;
3435 button.textContent = slot.available ? "+" : "×";
3436 button.setAttribute("aria-label", slot.available
3437 ? `${state.kind === "branch" ? "Start a branch" : "Reply"} ${slot.directionLabel}`
3438 : `${slot.directionLabel} is unavailable`);
3439 }
3440 for (const button of this.growthSlots.querySelectorAll("[data-wall-growth-key]")) {
3441 if (!retained.has(button.dataset.wallGrowthKey)) button.remove();
3442 }
3443 const originName = state.origin.author || "this comb";
3444 const copy = available.length
3445 ? `${available.length} open ${available.length === 1 ? "place" : "places"} around ${originName}. Choose a glowing comb; Escape cancels.`
3446 : `${originName} is surrounded. You can continue from the conversation's nearest open edge, or cancel.`;
3447 setTextIfChanged(this.root.querySelector("[data-wall-growth-copy]"), copy);
3448 const nearest = this.root.querySelector('[data-wall-action="nearest-growth"]');
3449 nearest.hidden = available.length > 0;
3450 nearest.textContent = state.kind === "branch" ? "Branch at nearest edge" : "Continue at nearest edge";
3451 this.growthTray.hidden = false;
3452 if (this.growthFitFrame) cancelAnimationFrame(this.growthFitFrame);
3453 this.growthFitFrame = requestAnimationFrame(() => {
3454 this.growthFitFrame = null;
3455 this.fitGrowthIntent();
3456 });
3457 const active = globalThis.document?.activeElement;
3458 if (active && this.growthSlots.contains(active) && active.disabled) {
3459 const fallback = this.growthSlots.querySelector("[data-wall-growth-key]:not(:disabled)")
3460 || (!nearest.hidden ? nearest : this.root.querySelector('[data-wall-action="cancel-growth"]'));
3461 fallback?.focus?.({ preventScroll: true });
3462 this.announce(available.length
3463 ? "That comb was just filled. Focus moved to another open direction."
3464 : "That comb was just filled. This patch is now surrounded; choose its nearest open edge or cancel.");
3465 }
3466 }
3467
3468 beginGrowthIntent(cell, kind, opener = null, focusAnchor = null) {
3469 if (!cell?.id || !["reply", "branch"].includes(kind)) return false;
3470 if (this.bounds.readOnly) {
3471 this.toast("The Wall is open to read while Hive Watch is verified. New combs will open soon.");
3472 return false;
3473 }
3474 this.growthIntent = {
3475 kind,
3476 origin: cell,
3477 originalOrigin: cell,
3478 opener: opener || this.nodes.get(cellKey(cell.q, cell.r)) || this.stage,
3479 focusAnchor: focusAnchor || null,
3480 priorView: {
3481 zoom: this.zoom,
3482 cameraX: this.cameraX,
3483 cameraY: this.cameraY,
3484 viewportWidth: Number(window.visualViewport?.width) || window.innerWidth,
3485 viewportHeight: Number(window.visualViewport?.height) || window.innerHeight,
3486 },
3487 };
3488 // Deliberately does not scroll the page. A picker is always opened from a
3489 // comb the viewer just acted on, so the stage is already on screen, and a
3490 // scroll here would land its event after the fit and trigger a second one.
3491 this.renderGrowthSlots();
3492 this.fitGrowthIntent();
3493 const first = this.growthSlots.querySelector("[data-wall-growth-key]:not(:disabled)");
3494 if (first) {
3495 const [q, r] = first.dataset.wallGrowthKey.split(":").map(Number);
3496 this.selected = { q, r };
3497 this.updateTarget();
3498 first.focus({ preventScroll: true });
3499 } else {
3500 this.root.querySelector('[data-wall-action="nearest-growth"]')?.focus?.({ preventScroll: true });
3501 }
3502 this.announce(this.root.querySelector("[data-wall-growth-copy]")?.textContent || "Choose the next comb.");
3503 return true;
3504 }
3505
3506 cancelGrowthIntent(options = {}) {
3507 const state = this.growthIntent;
3508 if (!state) return;
3509 this.growthIntent = null;
3510 this.renderGrowthSlots();
3511 this.restoreGrowthView(state, null, { restoreScroll: options.restoreView !== false });
3512 if (options.announce !== false) this.announce("Branch selection canceled.");
3513 if (options.restoreFocus !== false) this.restoreWallFocus(state.opener, state.focusAnchor);
3514 }
3515
3516 chooseGrowthCoordinate(coordinate, opener = null) {
3517 const state = this.growthIntent;
3518 if (!state || !this.isGrowthCoordinate(coordinate)) {
3519 this.announce("That place is no longer open. Choose another glowing comb.");
3520 this.renderGrowthSlots();
3521 return false;
3522 }
3523 const origin = this.cellsById.get(state.origin.id) || state.origin;
3524 const options = state.kind === "branch" ? {
3525 intent: "branch",
3526 anchorCellIds: [origin.id],
3527 mode: "branch",
3528 choiceExplicit: true,
3529 } : {
3530 intent: "join",
3531 conversationId: origin.conversationId,
3532 replyToId: state.kind === "reply" ? origin.id : null,
3533 anchorCellIds: [origin.id],
3534 mode: state.kind === "reply" ? "reply" : "join",
3535 choiceExplicit: true,
3536 };
3537 const restoreOpener = state.opener || opener || this.stage;
3538 this.growthIntent = null;
3539 this.renderGrowthSlots();
3540 this.restoreGrowthView(state, coordinate);
3541 this.selected = { q: coordinate.q, r: coordinate.r };
3542 this.updateTarget();
3543 void this.preparePlacement(coordinate, { ...options, opener: restoreOpener });
3544 return true;
3545 }
3546
3547 findConversationFrontierChoice(conversationId, near = { q: 0, r: 0 }) {
3548 if (!conversationId) return null;
3549 const cells = [...this.cells.values()]
3550 .filter((cell) => cell.conversationId === conversationId && cell.status === "visible")
3551 .sort((a, b) => hexDistance(a.q, a.r, near.q, near.r) - hexDistance(b.q, b.r, near.q, near.r));
3552 for (const anchor of cells) {
3553 const coordinate = neighbors(anchor.q, anchor.r)
3554 .find((candidate) => validCoordinate(candidate.q, candidate.r, this.bounds.radius)
3555 && !this.cells.has(cellKey(candidate.q, candidate.r)));
3556 if (coordinate) return { anchor, coordinate };
3557 }
3558 return null;
3559 }
3560
3561 moveGrowthToNearestFrontier() {
3562 const state = this.growthIntent;
3563 if (!state) return;
3564 const found = this.findConversationFrontierChoice(state.origin.conversationId, state.origin);
3565 if (!found) {
3566 this.toast("Load more of this conversation to find an open edge.");
3567 return;
3568 }
3569 state.origin = found.anchor;
3570 if (state.kind === "reply") state.kind = "continue";
3571 this.renderGrowthSlots();
3572 this.fitGrowthIntent();
3573 const target = this.growthSlots.querySelector(`[data-wall-growth-key="${cellKey(found.coordinate.q, found.coordinate.r)}"]`)
3574 || this.growthSlots.querySelector("[data-wall-growth-key]:not(:disabled)");
3575 target?.focus?.({ preventScroll: true });
3576 this.announce(`The nearest open edge is beside ${found.anchor.author || "this conversation"}. Choose its glowing comb.`);
3577 }
3578
3579 fitGrowthIntent() {
3580 const state = this.growthIntent;
3581 if (!state || !this.stage || !this.plane || !this.growthTray) return;
3582 // Disabled slots still communicate the occupied shape around the origin;
3583 // fit the whole local neighborhood, not only the remaining open exit.
3584 const buttons = [...this.growthSlots.querySelectorAll("[data-wall-growth-key]")];
3585 if (!buttons.length) return;
3586 // Deliberately never scrolls the page: this runs from the scroll listener,
3587 // and scrolling from inside it would refit, scroll, and refit again.
3588 // beginGrowthIntent puts the stage on screen once, before the first fit.
3589
3590 // Everything below is measured in stage coordinates: the stage is the
3591 // visible viewport now, so the growth cluster only has to clear the
3592 // toolbar above it and the action tray below it. Re-measured on every
3593 // attempt because the tray can gain a line as its copy changes.
3594 const size = this.stageSize();
3595 const margin = 10;
3596 const usable = (box) => box.right - box.left > 24 && box.bottom - box.top > 24;
3597 const measure = () => {
3598 const stageRect = this.stage.getBoundingClientRect();
3599 const tray = this.growthTray.getBoundingClientRect();
3600 const toolbar = this.root.querySelector(".honey-toolbar")?.getBoundingClientRect();
3601 // Browser page-scale zoom shows only part of the layout viewport, so the
3602 // usable area is the stage intersected with the visual viewport. Fitting
3603 // to the stage alone would place slots a pinched-in viewer cannot see.
3604 const viewport = globalThis.window?.visualViewport;
3605 const viewLeft = Number(viewport?.offsetLeft) || 0;
3606 const viewTop = Number(viewport?.offsetTop) || 0;
3607 const viewRight = viewLeft + (Number(viewport?.width) || window.innerWidth);
3608 const viewBottom = viewTop + (Number(viewport?.height) || window.innerHeight);
3609 const toolbarOccludes = toolbar && toolbar.bottom > viewTop && toolbar.top < viewBottom;
3610 const trayOccludes = tray.height > 0 && tray.top < viewBottom;
3611 const box = {
3612 left: Math.max(margin, viewLeft - stageRect.left + margin),
3613 right: Math.min(size.width - margin, viewRight - stageRect.left - margin),
3614 top: Math.max(
3615 margin,
3616 viewTop - stageRect.top + margin,
3617 toolbarOccludes ? toolbar.bottom - stageRect.top + margin : 0,
3618 ),
3619 bottom: Math.min(
3620 size.height - margin,
3621 viewBottom - stageRect.top - margin,
3622 trayOccludes ? tray.top - stageRect.top - margin : Infinity,
3623 ),
3624 };
3625 // Mid-gesture the visual viewport can report a band that barely overlaps
3626 // the stage. Falling back to the stage keeps the picker fitted; bailing
3627 // out would leave it at the pre-gesture zoom, overflowing the screen.
3628 return { stageRect, box: usable(box) ? box : { left: margin, right: size.width - margin, top: margin, bottom: size.height - margin } };
3629 };
3630
3631 const { stageRect, box: available } = measure();
3632 if (!usable(available)) return;
3633 this.lastGrowthTrayHeight = this.growthTray.getBoundingClientRect().height;
3634
3635 const originPoint = axialToPixel(state.origin.q, state.origin.r, this.hexRadius);
3636 let minX = Infinity;
3637 let maxX = -Infinity;
3638 let minY = Infinity;
3639 let maxY = -Infinity;
3640 for (const button of buttons) {
3641 const [q, r] = button.dataset.wallGrowthKey.split(":").map(Number);
3642 const point = axialToPixel(q, r, this.hexRadius);
3643 const halfWidth = button.offsetWidth / 2 + 7;
3644 const halfHeight = button.offsetHeight / 2 + 7;
3645 minX = Math.min(minX, point.x - originPoint.x - halfWidth);
3646 maxX = Math.max(maxX, point.x - originPoint.x + halfWidth);
3647 minY = Math.min(minY, point.y - originPoint.y - halfHeight);
3648 maxY = Math.max(maxY, point.y - originPoint.y + halfHeight);
3649 }
3650 const clusterWidth = Math.max(1, maxX - minX);
3651 const clusterHeight = Math.max(1, maxY - minY);
3652 const clusterCenterX = (minX + maxX) / 2;
3653 const clusterCenterY = (minY + maxY) / 2;
3654 const fitZoom = Math.min(
3655 state.priorView?.zoom || this.zoom,
3656 (available.right - available.left) / clusterWidth,
3657 (available.bottom - available.top) / clusterHeight,
3658 );
3659 // The full-size comb buttons keep more than a 44px touch target well below
3660 // the ordinary Wall zoom floor, so a temporary lower floor lets all six
3661 // directions fit above the action tray in a short landscape viewport.
3662 this.zoom = clamp(fitZoom, 0.3, WALL_LIMITS.maxZoom);
3663 // Deliberately not clamped to the ordinary camera limits: the growth
3664 // cluster must stay reachable even when it sits on the wall's edge.
3665 this.cameraX = (available.left + available.right) / 2 - size.width / 2
3666 - (originPoint.x + clusterCenterX) * this.zoom;
3667 this.cameraY = (available.top + available.bottom) / 2
3668 - (this.world.originY + originPoint.y + clusterCenterY) * this.zoom;
3669 this.updatePlaneTransform();
3670 this.updateTarget();
3671 }
3672
3673 // The tray gains and loses a line of wrapped copy as its message changes,
3674 // which moves the ceiling the cluster has to clear. Watching it is the only
3675 // way to refit after a change the fit itself could not have predicted.
3676 scheduleGrowthFit() {
3677 if (!this.growthIntent) return;
3678 if (this.growthFitFrame) cancelAnimationFrame(this.growthFitFrame);
3679 this.growthFitFrame = requestAnimationFrame(() => {
3680 this.growthFitFrame = null;
3681 this.fitGrowthIntent();
3682 });
3683 }
3684
3685 restoreGrowthView(state, coordinate = null, options = {}) {
3686 const view = state?.priorView;
3687 if (!view) return;
3688 if (this.growthFitFrame) cancelAnimationFrame(this.growthFitFrame);
3689 this.growthFitFrame = null;
3690 this.zoom = this.clampZoom(view.zoom);
3691 this.cameraX = view.cameraX;
3692 this.cameraY = view.cameraY;
3693 this.clampCamera();
3694 this.updatePlaneTransform();
3695 const currentViewportWidth = Number(window.visualViewport?.width) || window.innerWidth;
3696 const currentViewportHeight = Number(window.visualViewport?.height) || window.innerHeight;
3697 const viewportChanged = Math.abs(currentViewportWidth - view.viewportWidth) > 1
3698 || Math.abs(currentViewportHeight - view.viewportHeight) > 1;
3699 if (coordinate) {
3700 this.revealCoordinate(coordinate.q, coordinate.r, "auto");
3701 } else if (options.restoreScroll !== false && viewportChanged && state.originalOrigin) {
3702 this.revealCoordinate(state.originalOrigin.q, state.originalOrigin.r, "auto");
3703 } else {
3704 this.updateTarget();
3705 this.scheduleViewport();
3706 }
3707 }
3708
3709 async preparePlacement(coordinate, options = {}) {
3710 let intentGeneration = ++this.placementIntentGeneration;
3711 const activationGeneration = this.activationGeneration;
3712 let identityGeneration = this.identityGeneration;
3713 const q = Number(coordinate.q);
3714 const r = Number(coordinate.r);
3715 if (!validCoordinate(q, r)) {
3716 this.toast("That spot is beyond the Hive's growing edge.");
3717 return;
3718 }
3719 if (this.bounds.readOnly) {
3720 this.toast("The Wall is open to read while Hive Watch is verified. New combs will open soon.");
3721 return;
3722 }
3723 const existingDraft = normalizedPlacementDraft(this.draft, true);
3724 if (existingDraft
3725 && (existingDraft.q !== q || existingDraft.r !== r)
3726 && String(existingDraft.body || "").trim()
3727 && options.preserveExistingDraft !== false) {
3728 const move = window.confirm(`You already have an unfinished draft at comb ${existingDraft.q}, ${existingDraft.r}. Move that draft to comb ${q}, ${r}? Choose Cancel to keep its original address.`);
3729 if (!move) return;
3730 options = { ...options, body: existingDraft.body, requestId: null, preserveExistingDraft: false };
3731 }
3732 const context = await this.hydratePlacement(q, r);
3733 if (intentGeneration !== this.placementIntentGeneration
3734 || !this.isContextCurrent(activationGeneration, identityGeneration)) return;
3735 if (!context.ok) {
3736 this.toast(context.code === "out_of_bounds"
3737 ? "That spot is beyond the Hive's growing edge."
3738 : "The Hive could not verify that comb yet. Your current wall stays visible; try the spot again when it reconnects.");
3739 return;
3740 }
3741 const occupied = context.occupied;
3742 if (occupied) {
3743 this.openReader(occupied);
3744 return;
3745 }
3746 if (!this.storageScope) {
3747 const expectedScopeRequest = this.scopeRequestGeneration + 1;
3748 const resolvedScope = await this.syncStorageScope(true);
3749 if (this.scopeRequestGeneration !== expectedScopeRequest
3750 || !this.isActivationCurrent(activationGeneration)
3751 || !resolvedScope
3752 || resolvedScope !== this.storageScope) {
3753 this.toast("The Hive could not establish a safe identity for this comb. Nothing was posted; try again when the connection recovers.");
3754 return;
3755 }
3756 intentGeneration = ++this.placementIntentGeneration;
3757 identityGeneration = this.identityGeneration;
3758 }
3759 if (intentGeneration !== this.placementIntentGeneration
3760 || !this.isContextCurrent(activationGeneration, identityGeneration)) return;
3761 const groups = context.groups || adjacentConversationGroups(this.cells, q, r, this.conversations);
3762 const choices = context.choices;
3763 const requestedIntent = PLACEMENT_INTENTS.has(options.intent) ? options.intent : null;
3764 const isolatedIndependent = !requestedIntent && groups.length === 0;
3765 const desiredIntent = requestedIntent || (isolatedIndependent ? "independent" : null);
3766 const desiredConversation = options.conversationId || null;
3767 const choiceExplicit = options.choiceExplicit === true || isolatedIndependent;
3768 const choiceMade = Boolean(desiredIntent) && (choiceExplicit || isolatedIndependent);
3769 const state = {
3770 q,
3771 r,
3772 body: options.body || (this.draft && this.draft.q === q && this.draft.r === r ? this.draft.body || "" : ""),
3773 requestId: options.requestId || null,
3774 conversationId: desiredConversation,
3775 replyToId: options.replyToId || null,
3776 intent: desiredIntent,
3777 anchorCellIds: canonicalAnchorIds(options.anchorCellIds),
3778 choices,
3779 groups,
3780 mode: options.mode || (desiredConversation ? "join" : "root"),
3781 choiceMade,
3782 choiceExplicit,
3783 requiresConversationChoice: groups.length > 0 && !choiceMade,
3784 placementVerified: true,
3785 };
3786 if (!this.getUser()) {
3787 this.draft = state;
3788 if (this.saveDraft() === false) {
3789 this.toast("Create a profile first, then choose this comb again. This browser cannot safely carry the spot through identity setup.");
3790 return;
3791 }
3792 this.announce("Create a profile, then this exact comb and draft will reopen.");
3793 this.requestIdentity({ reason: "wall", coordinate: { q, r } });
3794 return;
3795 }
3796 this.openComposer(state, options.opener);
3797 }
3798
3799 openComposer(state, opener = null) {
3800 this.placementIntentGeneration += 1;
3801 const generation = ++this.composeGeneration;
3802 this.composeBusy = false;
3803 this.composeBody.readOnly = false;
3804 const groups = Array.isArray(state.groups)
3805 ? state.groups
3806 : adjacentConversationGroups(this.cells, Number(state.q), Number(state.r), this.conversations);
3807 this.composeState = {
3808 generation,
3809 q: Number(state.q),
3810 r: Number(state.r),
3811 body: state.body || "",
3812 requestId: state.requestId || null,
3813 conversationId: state.conversationId || null,
3814 replyToId: state.replyToId || null,
3815 intent: PLACEMENT_INTENTS.has(state.intent) ? state.intent : null,
3816 anchorCellIds: canonicalAnchorIds(state.anchorCellIds),
3817 choices: Array.isArray(state.choices) ? state.choices : conversationChoices(this.cells, Number(state.q), Number(state.r), this.conversations),
3818 groups,
3819 mode: state.mode || (state.conversationId ? "join" : "root"),
3820 choiceMade: state.choiceMade !== false,
3821 choiceExplicit: state.choiceExplicit === true,
3822 requiresConversationChoice: state.requiresConversationChoice === true,
3823 choiceLocked: state.choiceLocked === true || (state.choiceExplicit === true && ["reply", "branch"].includes(state.mode)),
3824 placementVerified: state.placementVerified !== false,
3825 };
3826 const submit = this.root.querySelector("[data-wall-compose-submit]");
3827 submit.disabled = this.bounds.readOnly || !this.composeState.choiceMade || !this.composeState.intent;
3828 submit.textContent = this.placementSubmitLabel();
3829 this.root.querySelector("[data-wall-compose-cancel]").textContent = "Keep as draft";
3830 this.composeBody.value = this.composeState.body;
3831 this.root.querySelector("[data-wall-compose-count]").textContent = `${[...this.composeBody.value].length} / 600`;
3832 this.root.querySelector("[data-wall-compose-place]").textContent = "This comb keeps its place while every nearby conversation stays free to grow.";
3833 const choiceField = this.root.querySelector("[data-wall-conversation-choices]");
3834 choiceField.disabled = false;
3835 const choiceList = this.root.querySelector("[data-wall-conversation-options]");
3836 choiceList.replaceChildren();
3837 const relationChoices = this.placementChoicesForGroups(groups);
3838 if (relationChoices.length && !this.composeState.choiceLocked) {
3839 choiceField.hidden = false;
3840 setTextIfChanged(this.root.querySelector("[data-wall-conversation-legend]"), groups.length > 1
3841 ? "Conversations meet at this comb. What should happen here?"
3842 : "How should this comb connect?");
3843 for (const choice of relationChoices) choiceList.append(this.conversationRadio(choice));
3844 } else if (this.composeState.requiresConversationChoice) {
3845 choiceField.hidden = false;
3846 const pending = document.createElement("p");
3847 pending.className = "honey-choice-pending";
3848 pending.textContent = "Nearby conversations must reload before you choose where this comb belongs.";
3849 choiceList.append(pending);
3850 } else {
3851 choiceField.hidden = true;
3852 }
3853 this.paintComposerIntentCopy();
3854 this.hideComposeError();
3855 this.draft = { ...this.composeState };
3856 this.saveDraft();
3857 const firstChoice = !choiceField.hidden && !this.composeState.choiceMade
3858 ? choiceList.querySelector("input[type=radio]")
3859 : null;
3860 this.showDialog(this.compose, firstChoice || this.composeBody, opener);
3861 }
3862
3863 placementChoicesForGroups(groups) {
3864 const choices = [];
3865 for (const group of groups) {
3866 const anchor = group.anchors[0]?.cell;
3867 if (!anchor) continue;
3868 choices.push({
3869 intent: "join",
3870 conversationId: group.conversationId,
3871 replyToId: null,
3872 anchorCellIds: [anchor.id],
3873 group,
3874 });
3875 choices.push({
3876 intent: "branch",
3877 conversationId: null,
3878 replyToId: null,
3879 anchorCellIds: [anchor.id],
3880 group,
3881 });
3882 }
3883 if (groups.length > 1) {
3884 choices.push({
3885 intent: "meet",
3886 conversationId: null,
3887 replyToId: null,
3888 anchorCellIds: groups.map((group) => group.anchors[0]?.cell?.id).filter(Boolean),
3889 groups,
3890 });
3891 }
3892 choices.push({ intent: "independent", conversationId: null, replyToId: null, anchorCellIds: [] });
3893 return choices;
3894 }
3895
3896 placementChoiceSelected(choice) {
3897 return this.composeState.choiceMade
3898 && this.composeState.intent === choice.intent
3899 && (this.composeState.conversationId || null) === (choice.conversationId || null)
3900 && canonicalAnchorIds(this.composeState.anchorCellIds).join(",") === canonicalAnchorIds(choice.anchorCellIds).join(",");
3901 }
3902
3903 conversationRadio(choice) {
3904 const label = document.createElement("label");
3905 label.className = "honey-conversation-option";
3906 const input = document.createElement("input");
3907 input.type = "radio";
3908 input.name = "honeyConversation";
3909 input.value = choice.intent;
3910 input.checked = this.placementChoiceSelected(choice);
3911 input.required = this.composeState.requiresConversationChoice && !this.composeState.choiceMade;
3912 input.addEventListener("change", () => {
3913 this.composeState.intent = choice.intent;
3914 this.composeState.conversationId = choice.conversationId || null;
3915 this.composeState.replyToId = choice.replyToId || null;
3916 this.composeState.anchorCellIds = canonicalAnchorIds(choice.anchorCellIds);
3917 this.composeState.mode = choice.intent;
3918 this.composeState.choiceMade = true;
3919 this.composeState.choiceExplicit = true;
3920 this.composeState.requiresConversationChoice = false;
3921 this.composeState.requestId = null;
3922 const submit = this.root.querySelector("[data-wall-compose-submit]");
3923 submit.disabled = this.bounds.readOnly || this.composeBusy;
3924 submit.textContent = this.placementSubmitLabel();
3925 this.paintComposerIntentCopy();
3926 this.saveDraft();
3927 });
3928 const copy = document.createElement("span");
3929 copy.className = "honey-conversation-copy";
3930 const title = document.createElement("strong");
3931 const detail = document.createElement("small");
3932 if (choice.intent === "independent") {
3933 title.textContent = "Start on its own";
3934 detail.textContent = "Nearby in space, but not linked to another conversation.";
3935 } else if (choice.intent === "branch") {
3936 const anchor = choice.group.anchors[0];
3937 title.textContent = "Start a new branch";
3938 detail.textContent = `Bud from ${anchor.cell.author || "this conversation"}'s ${anchor.directionLabel} comb; both paths can keep growing.`;
3939 } else if (choice.intent === "meet") {
3940 title.textContent = "Meet them here";
3941 detail.textContent = `Start a new conversation linked to ${choice.groups.length} nearby groups. Nothing is merged or moved.`;
3942 } else {
3943 const anchor = choice.group.anchors[0];
3944 const conversation = this.conversations.get(choice.conversationId);
3945 const names = conversation && Array.isArray(conversation.participants)
3946 ? conversation.participants.map((participant) => participant.name).filter(Boolean).slice(0, 3)
3947 : [];
3948 title.textContent = names.length ? `Continue with ${names.join(", ")}` : `Continue with ${anchor.cell.author || "the nearby conversation"}`;
3949 const excerpt = String(anchor.cell.body || "").replace(/\s+/g, " ").trim().slice(0, 72);
3950 detail.textContent = `${anchor.directionLabel}${choice.group.anchors.length > 1 ? ` · touches on ${choice.group.anchors.length} sides` : ""}${excerpt ? ` · “${excerpt}${String(anchor.cell.body || "").length > 72 ? "…" : ""}”` : ""}`;
3951 }
3952 copy.append(title, detail);
3953 label.append(input, copy);
3954 return label;
3955 }
3956
3957 placementSubmitLabel() {
3958 if (this.composeState?.mode === "reply") return "Place this reply";
3959 return {
3960 join: "Continue conversation",
3961 branch: "Start this branch",
3962 meet: "Meet here",
3963 independent: "Start conversation",
3964 }[this.composeState?.intent] || "Choose a connection";
3965 }
3966
3967 paintComposerIntentCopy() {
3968 const intent = this.composeState?.intent;
3969 const copy = {
3970 join: [this.composeState?.mode === "reply" ? "Replying beside a comb" : "Continuing nearby", this.composeState?.mode === "reply" ? "Reply from this comb" : "Continue this conversation"],
3971 branch: ["Budding a new path", "Start a new branch"],
3972 meet: ["Nearby groups crossing paths", "Let these conversations meet"],
3973 independent: ["New patch", "Start something here"],
3974 }[intent] || ["Open comb", "Choose how this comb connects"];
3975 setTextIfChanged(this.root.querySelector("[data-wall-compose-kicker]"), copy[0]);
3976 setTextIfChanged(this.root.querySelector("[data-wall-compose-title]"), copy[1]);
3977 }
3978
3979 async submitCompose() {
3980 const state = this.composeState;
3981 if (!state) return;
3982 const generation = state.generation;
3983 const identityGeneration = this.identityGeneration;
3984 const body = this.composeBody.value.trim();
3985 if (!body || [...body].length > WALL_LIMITS.bodyCharacters) {
3986 this.showComposeError("Write between 1 and 600 characters. Nothing will be silently cut off.");
3987 return;
3988 }
3989 if (state.editing) {
3990 await this.commitEdit(body);
3991 return;
3992 }
3993 if (!this.getUser()) {
3994 state.body = body;
3995 this.draft = { ...state };
3996 if (this.saveDraft() === false) return;
3997 this.closeDialog(this.compose);
3998 this.requestIdentity({ reason: "wall", coordinate: { q: state.q, r: state.r } });
3999 return;
4000 }
4001 const submit = this.root.querySelector("[data-wall-compose-submit]");
4002 submit.disabled = true;
4003 submit.textContent = "Checking this comb…";
4004 this.composeBody.readOnly = true;
4005 this.composeBusy = true;
4006 const choiceField = this.root.querySelector("[data-wall-conversation-choices]");
4007 choiceField.disabled = true;
4008 this.hideComposeError();
4009 try {
4010 const replayFrozenCommand = Boolean(
4011 state.requestId && String(state.body || "").trim() === body
4012 );
4013 if (!replayFrozenCommand) {
4014 // Editing the command payload intentionally abandons any older
4015 // idempotency key; ordinary input/radio handlers do this first too.
4016 state.requestId = null;
4017 const context = await this.hydratePlacement(state.q, state.r);
4018 if (identityGeneration !== this.identityGeneration
4019 || this.composeState !== state || generation !== this.composeGeneration) return;
4020 if (!context.ok) {
4021 state.placementVerified = false;
4022 this.showComposeError("The Hive could not verify this comb and its neighbors. Your draft remains open here; reconnect before placing it.");
4023 return;
4024 }
4025 if (context.occupied) {
4026 this.draft = { ...state, body };
4027 this.saveDraft();
4028 const next = this.findOpenNeighbor({ q: state.q, r: state.r }, state.conversationId);
4029 if (next) {
4030 this.selected = next;
4031 this.updateTarget();
4032 this.showComposeError("Someone filled that comb first. Your whole draft remains here. Move it only if the highlighted open comb works for you.", next);
4033 } else {
4034 this.showComposeError("Someone filled that comb first. Your whole draft remains here, but no open neighboring comb is loaded yet.");
4035 }
4036 return;
4037 }
4038 state.placementVerified = true;
4039 state.choices = context.choices;
4040 state.groups = context.groups || adjacentConversationGroups(this.cells, state.q, state.r, this.conversations);
4041 if (!state.choiceMade || !PLACEMENT_INTENTS.has(state.intent)) {
4042 const opener = this.dialogOpeners.get(this.compose);
4043 this.openComposer({
4044 ...state,
4045 body,
4046 choices: context.choices,
4047 groups: state.groups,
4048 choiceMade: false,
4049 requiresConversationChoice: true,
4050 placementVerified: true,
4051 }, opener);
4052 this.showComposeError("Choose how this comb connects before placing it.");
4053 this.root.querySelector("[data-wall-conversation-options] input[type=radio]")?.focus?.({ preventScroll: true });
4054 return;
4055 }
4056 const adjacentIds = new Set(state.groups.flatMap((group) => group.anchors.map((anchor) => anchor.cell.id)));
4057 const missingAnchor = canonicalAnchorIds(state.anchorCellIds).some((cellId) => !adjacentIds.has(cellId));
4058 if (state.intent !== "independent" && missingAnchor) {
4059 const opener = this.dialogOpeners.get(this.compose);
4060 this.openComposer({
4061 ...state,
4062 body,
4063 choices: context.choices,
4064 groups: state.groups,
4065 intent: null,
4066 conversationId: null,
4067 replyToId: null,
4068 anchorCellIds: [],
4069 choiceMade: false,
4070 choiceExplicit: false,
4071 choiceLocked: false,
4072 requiresConversationChoice: true,
4073 placementVerified: true,
4074 }, opener);
4075 this.showComposeError("A linked comb changed while you were writing. Your message is untouched; choose the current connection again.");
4076 this.root.querySelector("[data-wall-conversation-options] input[type=radio]")?.focus?.({ preventScroll: true });
4077 return;
4078 }
4079 }
4080 const requestId = state.requestId || randomRequestId();
4081 state.requestId = requestId;
4082 state.body = body;
4083 this.draft = { ...state };
4084 this.saveDraft();
4085 submit.textContent = "Placing…";
4086 const result = await this.backend.wallPlaceCell({
4087 requestId,
4088 q: state.q,
4089 r: state.r,
4090 body,
4091 intent: state.intent,
4092 conversationId: state.conversationId,
4093 replyToId: state.replyToId,
4094 anchorCellIds: canonicalAnchorIds(state.anchorCellIds),
4095 });
4096 if (identityGeneration !== this.identityGeneration) return;
4097 if (this.composeState !== state || generation !== this.composeGeneration) {
4098 if (result?.ok && result.cell) {
4099 if (this.draft?.requestId === state.requestId) this.clearDraft();
4100 this.markSeen(result.cell.id);
4101 const rebuild = this.captureProjectionRebuild();
4102 await this.rebuildAfterConfirmedWrite(rebuild);
4103 this.toast("Your earlier comb was placed while you moved on.");
4104 if (this.onPlaced) this.onPlaced(result.cell);
4105 }
4106 return;
4107 }
4108 if (result && result.ok && result.cell) {
4109 // A confirmed response may jump across unseen global revisions. Never
4110 // splice just this cell into an older projection: clear first, then
4111 // authoritatively rebuild the current wall/list window.
4112 const rebuild = this.captureProjectionRebuild();
4113 this.composeBusy = false;
4114 this.clearDraft();
4115 this.closeDialog(this.compose);
4116 this.markSeen(result.cell.id);
4117 await this.rebuildAfterConfirmedWrite(rebuild);
4118 if (this.active && this.mode === "wall") await this.focusCell(result.cell.id);
4119 const placedCopy = {
4120 join: state.mode === "reply" ? "Your reply grew this conversation." : "Your comb continued this conversation.",
4121 branch: "Your new branch can now grow in any direction.",
4122 meet: "These nearby conversations now meet at a new patch.",
4123 independent: "Your new conversation is growing in the Hive.",
4124 }[state.intent] || "Your comb is part of the shared Hive.";
4125 this.toast(placedCopy);
4126 if (this.onPlaced) this.onPlaced(result.cell);
4127 } else if (result && result.code === "occupied") {
4128 state.requestId = null;
4129 this.draft = { ...state };
4130 this.saveDraft();
4131 const next = this.findOpenNeighbor({ q: state.q, r: state.r }, state.conversationId);
4132 if (next) {
4133 this.selected = next;
4134 this.updateTarget();
4135 this.showComposeError("Someone filled that comb first. Your whole draft remains here. Move it only if the highlighted open comb works for you.", next);
4136 } else {
4137 this.showComposeError("Someone filled that comb first. Your whole draft remains here, but no open neighboring comb is loaded yet.");
4138 }
4139 } else if (result && (result.code === "not_adjacent" || result.code === "invalid_reply")) {
4140 state.requestId = null;
4141 this.draft = { ...state };
4142 this.saveDraft();
4143 const next = this.findConversationFrontier(state.conversationId, state);
4144 if (next) {
4145 this.selected = next;
4146 this.updateTarget();
4147 this.showComposeError("That conversation grew away from this spot. Your draft remains here. Move it only if the highlighted edge comb works for you.", next);
4148 } else {
4149 this.showComposeError("That conversation grew away from this spot. Your draft remains here, but its open edge is not loaded yet.");
4150 }
4151 } else if (result && result.code === "stale_anchors") {
4152 state.requestId = null;
4153 this.draft = { ...state, body };
4154 this.saveDraft();
4155 const context = await this.hydratePlacement(state.q, state.r);
4156 if (identityGeneration !== this.identityGeneration
4157 || this.composeState !== state || generation !== this.composeGeneration) return;
4158 if (context.ok && !context.occupied) {
4159 const opener = this.dialogOpeners.get(this.compose);
4160 this.openComposer({
4161 ...state,
4162 body,
4163 requestId: null,
4164 choices: context.choices,
4165 groups: context.groups || [],
4166 intent: null,
4167 conversationId: null,
4168 replyToId: null,
4169 anchorCellIds: [],
4170 choiceMade: false,
4171 choiceExplicit: false,
4172 choiceLocked: false,
4173 requiresConversationChoice: true,
4174 placementVerified: true,
4175 }, opener);
4176 this.showComposeError("A nearby conversation changed while this comb was being placed. Your message is untouched; choose the current connection again.");
4177 this.root.querySelector("[data-wall-conversation-options] input[type=radio]")?.focus?.({ preventScroll: true });
4178 } else {
4179 this.showComposeError(`${result.message || "A nearby conversation changed."} Your draft is still here; reconnect and choose again.`);
4180 }
4181 } else if (result && result.ok === false) {
4182 state.requestId = null;
4183 this.draft = { ...state };
4184 this.saveDraft();
4185 if (result.code === "read_only" || result.code === "out_of_bounds") void this.refreshBounds();
4186 this.showComposeError(`${result.message || "The wall could not place that comb."} Your draft is still here.`);
4187 } else {
4188 this.showComposeError("The wall did not confirm that placement. Your draft is still here.");
4189 }
4190 } catch (error) {
4191 if (this.composeState === state && generation === this.composeGeneration) {
4192 this.showComposeError(`${error.message} Your draft is still open here; retrying will use the same idempotent request.`);
4193 }
4194 this.dataStale = true;
4195 this.setConnectionState(navigator.onLine ? "stale" : "offline");
4196 } finally {
4197 if (this.composeState === state && generation === this.composeGeneration) {
4198 this.composeBusy = false;
4199 submit.disabled = this.bounds.readOnly;
4200 submit.textContent = typeof this.placementSubmitLabel === "function"
4201 ? this.placementSubmitLabel()
4202 : "Place this comb";
4203 this.composeBody.readOnly = false;
4204 choiceField.disabled = false;
4205 }
4206 }
4207 }
4208
4209 acceptComposeSuggestion() {
4210 const state = this.composeState;
4211 if (!state) return;
4212 if (state.editing && state.editConflictCell) {
4213 const fresh = state.editConflictCell;
4214 const opener = this.dialogOpeners.get(this.compose);
4215 this.saveEditDraft();
4216 this.closeDialog(this.compose, { restoreFocus: false });
4217 this.openReader(fresh, opener);
4218 return;
4219 }
4220 const coordinate = state.suggestedCoordinate;
4221 if (!coordinate || this.cells.has(cellKey(coordinate.q, coordinate.r))) {
4222 this.showComposeError("That suggested comb is no longer open. Your draft has not moved.");
4223 return;
4224 }
4225 const choices = conversationChoices(this.cells, coordinate.q, coordinate.r, this.conversations);
4226 const groups = adjacentConversationGroups(this.cells, coordinate.q, coordinate.r, this.conversations);
4227 const adjacentIds = new Set(groups.flatMap((group) => group.anchors.map((anchor) => anchor.cell.id)));
4228 const anchorsRemainAdjacent = state.intent === "independent"
4229 || canonicalAnchorIds(state.anchorCellIds).every((cellId) => adjacentIds.has(cellId));
4230 const body = this.composeBody.value;
4231 this.selected = { q: coordinate.q, r: coordinate.r };
4232 this.updateTarget();
4233 this.openComposer({
4234 ...state,
4235 q: coordinate.q,
4236 r: coordinate.r,
4237 body,
4238 requestId: null,
4239 choices,
4240 groups,
4241 intent: anchorsRemainAdjacent ? state.intent : null,
4242 conversationId: anchorsRemainAdjacent ? state.conversationId : null,
4243 replyToId: anchorsRemainAdjacent ? state.replyToId : null,
4244 anchorCellIds: anchorsRemainAdjacent ? state.anchorCellIds : [],
4245 mode: anchorsRemainAdjacent ? state.mode : "root",
4246 choiceMade: anchorsRemainAdjacent && state.choiceMade,
4247 choiceExplicit: anchorsRemainAdjacent && state.choiceExplicit,
4248 choiceLocked: anchorsRemainAdjacent && state.choiceLocked,
4249 requiresConversationChoice: !anchorsRemainAdjacent || (groups.length > 0 && !state.choiceMade),
4250 placementVerified: true,
4251 suggestedCoordinate: null,
4252 });
4253 this.announce(anchorsRemainAdjacent
4254 ? "Draft moved to the highlighted open comb with its chosen connection intact."
4255 : "Draft moved, but its old connection no longer reaches this comb. Choose the current relationship before placing it.");
4256 }
4257
4258 findOpenNeighbor(origin, conversationId = null) {
4259 const direct = neighbors(origin.q, origin.r);
4260 const candidates = conversationId
4261 ? direct.filter((coordinate) => {
4262 return neighbors(coordinate.q, coordinate.r).some((neighbor) => this.cells.get(cellKey(neighbor.q, neighbor.r))?.conversationId === conversationId);
4263 })
4264 : direct;
4265 return candidates.find((coordinate) => validCoordinate(coordinate.q, coordinate.r, this.bounds.radius) && !this.cells.has(cellKey(coordinate.q, coordinate.r))) || null;
4266 }
4267
4268 findNearestOpen(origin = { q: 0, r: 0 }) {
4269 const start = validCoordinate(origin.q, origin.r, this.bounds.radius) ? origin : { q: 0, r: 0 };
4270 const queue = [{ q: start.q, r: start.r }];
4271 const seen = new Set([cellKey(start.q, start.r)]);
4272 while (queue.length) {
4273 const current = queue.shift();
4274 if (!this.cells.has(cellKey(current.q, current.r))) return current;
4275 for (const candidate of neighbors(current.q, current.r)) {
4276 const key = cellKey(candidate.q, candidate.r);
4277 if (seen.has(key) || !validCoordinate(candidate.q, candidate.r, this.bounds.radius)) continue;
4278 seen.add(key);
4279 queue.push(candidate);
4280 }
4281 }
4282 return null;
4283 }
4284
4285 findConversationFrontier(conversationId, near = { q: 0, r: 0 }) {
4286 if (!conversationId) return this.findOpenNeighbor(near);
4287 const cells = [...this.cells.values()]
4288 .filter((cell) => cell.conversationId === conversationId)
4289 .sort((a, b) => hexDistance(a.q, a.r, near.q, near.r) - hexDistance(b.q, b.r, near.q, near.r));
4290 for (const cell of cells) {
4291 const open = this.findOpenNeighbor(cell, conversationId);
4292 if (open) return open;
4293 }
4294 return null;
4295 }
4296
4297 openReader(cell, opener = null) {
4298 cell = this.cellsById.get(cell?.id) || this.mergeCell(cell) || cell;
4299 if (!cell?.id) return;
4300 this.placementIntentGeneration += 1;
4301 this.readerGeneration += 1;
4302 this.setReaderBusy(false);
4303 if (this.readerCell?.id !== cell.id || this.readerCell?.contentVersion !== cell.contentVersion) {
4304 this.reportRequest = null;
4305 this.operatorCaseRequest = null;
4306 }
4307 this.readerCell = cell;
4308 this.paintReaderCell(cell);
4309 this.markSeen(cell.id);
4310 this.showDialog(this.reader, this.reader.querySelector("[data-wall-reader-action]:not([hidden])"), opener);
4311 }
4312
4313 paintReaderCell(cell, options = {}) {
4314 if (!cell) return;
4315 const conversation = this.conversations.get(cell.conversationId);
4316 setTextIfChanged(this.root.querySelector("[data-wall-reader-author]"), cell.author || (cell.status === "visible" ? "Hive member" : "Open space kept"));
4317 const relationKind = cell.replyToId ? "Reply comb"
4318 : cell.origin?.kind === "branch" ? "Branch root"
4319 : cell.origin?.kind === "meet" ? "Meeting comb"
4320 : conversation?.rootCellId === cell.id ? "Conversation root" : "Conversation continuation";
4321 setTextIfChanged(this.root.querySelector("[data-wall-reader-kicker]"), relationKind);
4322 setTextIfChanged(this.root.querySelector("[data-wall-reader-meta]"), `${cell.membership === "alumni" ? "DHG alumni" : cell.membership === "guest" ? "Guest" : "Hive"} · ${timeLabel(cell.createdAt)} · comb ${cell.q}, ${cell.r}`);
4323 setTextIfChanged(this.root.querySelector("[data-wall-reader-body]"), statusText(cell));
4324 const participants = this.root.querySelector("[data-wall-reader-participants]");
4325 const participantNames = conversation && Array.isArray(conversation.participants)
4326 ? conversation.participants.map((participant) => participant.name).filter(Boolean).join(", ")
4327 : "";
4328 if (participants.dataset.wallParticipantNames !== participantNames) {
4329 participants.dataset.wallParticipantNames = participantNames;
4330 participants.replaceChildren();
4331 if (participantNames) {
4332 const label = document.createElement("span");
4333 label.textContent = "In this conversation: ";
4334 const names = document.createElement("strong");
4335 names.textContent = participantNames;
4336 participants.append(label, names);
4337 }
4338 }
4339 const relations = this.root.querySelector("[data-wall-reader-relations]");
4340 const relationFingerprint = JSON.stringify(cell.origin || null);
4341 if (relations.dataset.wallRelations !== relationFingerprint) {
4342 relations.dataset.wallRelations = relationFingerprint;
4343 relations.replaceChildren();
4344 if (cell.origin?.anchors?.length) {
4345 const heading = document.createElement("strong");
4346 heading.textContent = cell.origin.kind === "meet" ? "Connected nearby:" : "Branched from:";
4347 relations.append(heading);
4348 for (const link of cell.origin.anchors) {
4349 const anchor = this.cellsById.get(link.cellId);
4350 if (anchor) {
4351 const button = document.createElement("button");
4352 button.type = "button";
4353 button.className = "honey-relation-link";
4354 button.dataset.cellKey = cellKey(anchor.q, anchor.r);
4355 button.textContent = `${anchor.author || "Nearby comb"} · ${HEX_DIRECTION_LABELS[Number(link.direction)] || "beside this patch"}`;
4356 relations.append(button);
4357 } else {
4358 const text = document.createElement("span");
4359 text.textContent = "A nearby conversation";
4360 relations.append(text);
4361 }
4362 }
4363 }
4364 }
4365 const canInteract = cell.status === "visible";
4366 const canWrite = canInteract && !this.bounds.readOnly;
4367 const reply = this.root.querySelector('[data-wall-reader-action="reply"]');
4368 const branch = this.root.querySelector('[data-wall-reader-action="branch"]');
4369 const edit = this.root.querySelector('[data-wall-reader-action="edit"]');
4370 const remove = this.root.querySelector('[data-wall-reader-action="remove"]');
4371 const report = this.root.querySelector('[data-wall-reader-action="report"]');
4372 const watchOpen = this.root.querySelector('[data-wall-reader-action="watch-open"]');
4373 reply.hidden = !canWrite;
4374 branch.hidden = !canWrite;
4375 edit.hidden = !canWrite || !cell.isMine;
4376 remove.hidden = this.bounds.readOnly || !cell.isMine || cell.status === "author_removed";
4377 report.hidden = !canWrite || cell.isMine || cell.viewerReported;
4378 watchOpen.hidden = !canInteract || !this.operator;
4379 const reportForm = this.root.querySelector("[data-wall-report-form]");
4380 const operatorForm = this.root.querySelector("[data-wall-operator-form]");
4381 const reportFormAllowed = canWrite && !cell.isMine && !cell.viewerReported;
4382 const operatorFormAllowed = canInteract && Boolean(this.operator);
4383 const activeBefore = globalThis.document?.activeElement;
4384 if (!options.preserveForms || !reportFormAllowed) reportForm.hidden = true;
4385 if (!options.preserveForms || !operatorFormAllowed) operatorForm.hidden = true;
4386 if (!options.preserveForms) {
4387 this.root.querySelector("[data-wall-report-reason]").value = "";
4388 this.root.querySelector("[data-wall-operator-reason]").value = "";
4389 }
4390 if (activeBefore && this.reader?.contains(activeBefore)
4391 && (activeBefore.hidden || activeBefore.closest?.("[hidden]"))) {
4392 this.focusReaderFallback(report);
4393 }
4394 this.setReaderLocked(this.readerBusy);
4395 }
4396
4397 focusReaderFallback(preferred = null) {
4398 const available = (control) => Boolean(control
4399 && !control.disabled
4400 && !control.hidden
4401 && !control.closest?.("[hidden]"));
4402 const fallback = available(preferred) ? preferred
4403 : [...(this.reader?.querySelectorAll?.("[data-wall-reader-action], [data-wall-close=\"reader\"]") || [])]
4404 .find(available) || this.reader;
4405 fallback?.focus?.({ preventScroll: true });
4406 return fallback || null;
4407 }
4408
4409 setReaderLocked(locked) {
4410 if (!this.reader) return;
4411 for (const control of this.reader.querySelectorAll("button, select, textarea")) {
4412 control.disabled = Boolean(locked) && !control.matches('[data-wall-close="reader"]');
4413 }
4414 }
4415
4416 setReaderBusy(locked) {
4417 this.readerBusy = Boolean(locked);
4418 this.setReaderLocked(this.readerBusy);
4419 }
4420
4421 async runReaderAction(action) {
4422 if (this.readerBusy) return;
4423 const cell = this.readerCell;
4424 if (!cell) return;
4425 if (this.bounds.readOnly && ["reply", "branch", "edit", "remove", "report"].includes(action)) {
4426 this.toast("The Wall is open to read while Hive Watch is verified. New combs will open soon.");
4427 return;
4428 }
4429 const opener = this.dialogOpeners.get(this.reader);
4430 const openerAnchor = this.dialogFocusAnchors.get(this.reader);
4431 if (action === "reply" || action === "branch") {
4432 this.closeDialog(this.reader, { restoreFocus: false });
4433 if (this.mode === "list") {
4434 this.setMode("wall");
4435 this.stage?.focus?.({ preventScroll: true });
4436 this.announce("Opening the spatial Wall so you can choose one of six directions.");
4437 const refreshed = await this.refreshVisible(true);
4438 const current = this.cellsById.get(cell.id);
4439 if (!refreshed || !current || current.status !== "visible") {
4440 this.toast("That comb changed while the spatial Wall opened. Nothing was posted; choose its current comb again.");
4441 this.stage?.focus?.({ preventScroll: true });
4442 return;
4443 }
4444 this.revealCoordinate(current.q, current.r, "auto");
4445 this.beginGrowthIntent(current, action === "branch" ? "branch" : "reply", this.stage, null);
4446 } else {
4447 this.beginGrowthIntent(cell, action === "branch" ? "branch" : "reply", opener, openerAnchor);
4448 }
4449 } else if (action === "show") {
4450 this.closeDialog(this.reader, { restoreFocus: false });
4451 this.setMode("wall");
4452 this.revealCoordinate(cell.q, cell.r);
4453 this.restoreWallFocus(this.stage);
4454 } else if (action === "edit") {
4455 this.closeDialog(this.reader, { restoreFocus: false });
4456 this.openEditComposer(cell, opener);
4457 } else if (action === "remove") {
4458 await this.removeCell(cell);
4459 } else if (action === "report") {
4460 this.root.querySelector("[data-wall-report-form]").hidden = false;
4461 this.root.querySelector("[data-wall-report-reason]").focus();
4462 } else if (action === "cancel-report") {
4463 this.root.querySelector("[data-wall-report-form]").hidden = true;
4464 this.focusReaderFallback(this.root.querySelector('[data-wall-reader-action="report"]'));
4465 } else if (action === "watch-open") {
4466 this.root.querySelector("[data-wall-operator-form]").hidden = false;
4467 this.root.querySelector("[data-wall-operator-reason]").focus();
4468 } else if (action === "cancel-watch-open") {
4469 this.root.querySelector("[data-wall-operator-form]").hidden = true;
4470 this.focusReaderFallback(this.root.querySelector('[data-wall-reader-action="watch-open"]'));
4471 }
4472 }
4473
4474 openEditComposer(cell, opener = null) {
4475 if (this.editDraft
4476 && this.editDraft.cellId !== cell.id
4477 && String(this.editDraft.body || "").trim()
4478 && !window.confirm("You already have an unfinished edit for another comb. Replace that edit draft with this one?")) {
4479 this.restoreWallFocus(opener);
4480 return false;
4481 }
4482 this.placementIntentGeneration += 1;
4483 const generation = ++this.composeGeneration;
4484 this.composeBusy = false;
4485 this.composeBody.readOnly = false;
4486 this.root.querySelector("[data-wall-conversation-choices]").disabled = false;
4487 this.root.querySelector("[data-wall-compose-submit]").disabled = false;
4488 const saved = this.editDraft && this.editDraft.cellId === cell.id ? this.editDraft : null;
4489 const body = saved ? saved.body || "" : cell.body || "";
4490 this.composeState = {
4491 editing: true,
4492 generation,
4493 cellId: cell.id,
4494 expectedVersion: cell.version,
4495 q: cell.q,
4496 r: cell.r,
4497 body,
4498 requestId: saved && saved.expectedVersion === cell.version ? saved.requestId || null : null,
4499 recoveredFromVersion: saved && saved.expectedVersion !== cell.version ? saved.expectedVersion : null,
4500 };
4501 this.composeBody.value = body;
4502 this.root.querySelector("[data-wall-compose-kicker]").textContent = "Editing your comb";
4503 this.root.querySelector("[data-wall-compose-title]").textContent = "Update this message";
4504 this.root.querySelector("[data-wall-compose-place]").textContent = `Comb ${cell.q}, ${cell.r} stays in place.`;
4505 this.root.querySelector("[data-wall-conversation-choices]").hidden = true;
4506 this.root.querySelector("[data-wall-compose-submit]").textContent = "Save this comb";
4507 this.root.querySelector("[data-wall-compose-cancel]").textContent = "Keep edit draft";
4508 this.root.querySelector("[data-wall-compose-count]").textContent = `${[...this.composeBody.value].length} / 600`;
4509 this.hideComposeError();
4510 this.saveEditDraft();
4511 this.showDialog(this.compose, this.composeBody, opener);
4512 if (this.composeState.recoveredFromVersion) {
4513 this.showComposeError("This saved edit began from an older version. You reviewed the latest comb; check your draft carefully before saving over it.");
4514 }
4515 return true;
4516 }
4517
4518 async submitEdit() {
4519 // Retained as a named operation for integration tests and future toolbar use.
4520 const state = this.composeState;
4521 if (!state || !state.editing) return null;
4522 const body = this.composeBody.value.trim();
4523 const requestId = state.requestId || randomRequestId();
4524 state.requestId = requestId;
4525 this.saveEditDraft();
4526 return this.backend.wallEditCell({
4527 requestId,
4528 cellId: state.cellId,
4529 expectedVersion: state.expectedVersion,
4530 body,
4531 });
4532 }
4533
4534 async commitEdit(body) {
4535 const state = this.composeState;
4536 if (!state || !state.editing) return;
4537 const generation = state.generation;
4538 const identityGeneration = this.identityGeneration;
4539 const submit = this.root.querySelector("[data-wall-compose-submit]");
4540 submit.disabled = true;
4541 submit.textContent = "Saving…";
4542 this.composeBody.readOnly = true;
4543 this.composeBusy = true;
4544 try {
4545 const result = await this.submitEdit();
4546 if (identityGeneration !== this.identityGeneration) return;
4547 if (this.composeState !== state || generation !== this.composeGeneration) {
4548 if (result?.ok && result.cell) {
4549 const rebuild = this.captureProjectionRebuild();
4550 await this.rebuildAfterConfirmedWrite(rebuild);
4551 this.toast("Your earlier edit finished while you moved on.");
4552 }
4553 return;
4554 }
4555 if (result && result.ok && result.cell) {
4556 const rebuild = this.captureProjectionRebuild();
4557 this.clearEditDraft();
4558 this.composeBusy = false;
4559 this.composeState = null;
4560 this.closeDialog(this.compose);
4561 await this.rebuildAfterConfirmedWrite(rebuild);
4562 this.toast("Your comb was updated in place. The Wall reloaded its authoritative position.");
4563 } else if (result && result.code === "version_conflict") {
4564 state.requestId = null;
4565 this.saveEditDraft();
4566 let fresh = null;
4567 try {
4568 const exactCacheGeneration = this.publicCacheGeneration;
4569 const contextCurrent = () => (
4570 identityGeneration === this.identityGeneration
4571 && this.composeState === state
4572 && generation === this.composeGeneration
4573 && exactCacheGeneration === this.publicCacheGeneration
4574 );
4575 const latest = await this.readAuthoritativeCell(state.cellId, contextCurrent);
4576 if (latest?.rebuildRequired) {
4577 await this.rebuildPublicProjection(latest.rebuild);
4578 } else if (latest?.cell && contextCurrent()) {
4579 this.mergeCell(latest.cell);
4580 fresh = latest.cell;
4581 }
4582 } catch {
4583 // The edit remains locally recoverable even if the fresh read fails.
4584 }
4585 if (fresh) {
4586 state.editConflictCell = fresh;
4587 this.showComposeError("This comb changed on another screen. Your edit draft remains here; review the latest version before deciding what to save.", { editConflict: true });
4588 } else {
4589 this.showComposeError("This comb changed on another screen. Your edit draft remains here; reopen it before saving so newer words are not overwritten.");
4590 }
4591 } else if (result && result.ok === false) {
4592 state.requestId = null;
4593 this.saveEditDraft();
4594 this.showComposeError(`${result.message || "The wall could not save that edit."} Your edit draft is still here.`);
4595 } else {
4596 this.showComposeError("The wall did not confirm that edit. Your edit draft is still here.");
4597 }
4598 } catch (error) {
4599 if (this.composeState === state && generation === this.composeGeneration) this.showComposeError(`${error.message} Your edit is still here.`);
4600 } finally {
4601 if (this.composeState === state && generation === this.composeGeneration) {
4602 this.composeBusy = false;
4603 submit.disabled = false;
4604 submit.textContent = "Save this comb";
4605 this.composeBody.readOnly = false;
4606 }
4607 }
4608 }
4609
4610 async removeCell(cell) {
4611 if (this.readerBusy) return;
4612 if (!window.confirm("Remove this message? Its comb will remain as a tombstone so the wall never collapses.")) return;
4613 const readerGeneration = this.readerGeneration;
4614 const identityGeneration = this.identityGeneration;
4615 this.setReaderBusy(true);
4616 try {
4617 const result = await this.backend.wallRemoveCell({
4618 requestId: randomRequestId(),
4619 cellId: cell.id,
4620 expectedVersion: cell.version,
4621 });
4622 if (identityGeneration !== this.identityGeneration
4623 || this.readerCell?.id !== cell.id || readerGeneration !== this.readerGeneration) return;
4624 if (result?.ok && result.cell) {
4625 const rebuild = this.captureProjectionRebuild();
4626 this.setReaderBusy(false);
4627 this.closeDialog(this.reader);
4628 this.readerCell = null;
4629 this.reportRequest = null;
4630 await this.rebuildAfterConfirmedWrite(rebuild);
4631 this.toast("Your message was removed; its place in the Hive remains. The Wall reloaded authoritatively.");
4632 } else if (result?.ok && result.code === "already_removed") {
4633 const rebuild = this.captureProjectionRebuild();
4634 this.setReaderBusy(false);
4635 this.closeDialog(this.reader);
4636 this.readerCell = null;
4637 this.reportRequest = null;
4638 await this.rebuildAfterConfirmedWrite(rebuild);
4639 this.toast("That message was already removed; its comb remains in place.");
4640 } else if (result?.code === "version_conflict") {
4641 const exactCacheGeneration = this.publicCacheGeneration;
4642 const contextCurrent = () => (
4643 identityGeneration === this.identityGeneration
4644 && this.readerCell?.id === cell.id
4645 && readerGeneration === this.readerGeneration
4646 && exactCacheGeneration === this.publicCacheGeneration
4647 );
4648 const latest = await this.readAuthoritativeCell(cell.id, contextCurrent);
4649 if (latest?.rebuildRequired) {
4650 await this.rebuildPublicProjection(latest.rebuild);
4651 } else if (latest?.cell && contextCurrent()) {
4652 this.mergeCell(latest.cell);
4653 this.openReader(latest.cell);
4654 }
4655 this.toast("That comb changed on another screen. It was not removed; review the latest version first.");
4656 } else {
4657 this.toast(result?.message || "The wall did not confirm that removal. Nothing was changed.");
4658 }
4659 } catch (error) {
4660 this.toast(`Could not remove that comb: ${error.message}`);
4661 } finally {
4662 if (identityGeneration === this.identityGeneration && readerGeneration === this.readerGeneration) this.setReaderBusy(false);
4663 }
4664 }
4665
4666 async submitReport() {
4667 if (this.readerBusy) return;
4668 const cell = this.readerCell;
4669 if (!cell) return;
4670 if (this.bounds.readOnly) {
4671 this.toast("The Wall is open to read while Hive Watch is verified. Your selected report reason is still here.");
4672 return;
4673 }
4674 const reason = this.root.querySelector("[data-wall-report-reason]").value;
4675 if (!["personal_attack", "illegal", "spam", "privacy"].includes(reason)) {
4676 this.toast("Choose why the Hive watch should review this comb.");
4677 this.root.querySelector("[data-wall-report-reason]").focus();
4678 return;
4679 }
4680 const readerGeneration = this.readerGeneration;
4681 const identityGeneration = this.identityGeneration;
4682 this.setReaderBusy(true);
4683 if (!this.reportRequest
4684 || this.reportRequest.cellId !== cell.id
4685 || this.reportRequest.contentVersion !== cell.contentVersion
4686 || this.reportRequest.reason !== reason) {
4687 this.reportRequest = {
4688 requestId: randomRequestId(),
4689 cellId: cell.id,
4690 contentVersion: cell.contentVersion,
4691 reason,
4692 };
4693 }
4694 const reportRequest = this.reportRequest;
4695 try {
4696 const result = await this.backend.wallReportCell({
4697 requestId: reportRequest.requestId,
4698 cellId: cell.id,
4699 expectedContentVersion: cell.contentVersion,
4700 reason,
4701 });
4702 if (identityGeneration !== this.identityGeneration
4703 || this.readerCell?.id !== cell.id || readerGeneration !== this.readerGeneration) return;
4704 if (this.reportRequest === reportRequest) this.reportRequest = null;
4705 if (!result?.ok) {
4706 if (result?.code === "content_conflict") {
4707 const exactCacheGeneration = this.publicCacheGeneration;
4708 const contextCurrent = () => (
4709 identityGeneration === this.identityGeneration
4710 && this.readerCell?.id === cell.id
4711 && readerGeneration === this.readerGeneration
4712 && exactCacheGeneration === this.publicCacheGeneration
4713 );
4714 const latest = await this.readAuthoritativeCell(cell.id, contextCurrent);
4715 if (latest?.rebuildRequired) {
4716 await this.rebuildPublicProjection(latest.rebuild);
4717 } else if (latest?.cell && contextCurrent()) {
4718 this.mergeCell(latest.cell);
4719 this.openReader(latest.cell);
4720 }
4721 }
4722 this.toast(result?.message || "The Hive watch did not confirm that report.");
4723 return;
4724 }
4725 const rebuild = this.captureProjectionRebuild();
4726 if (identityGeneration === this.identityGeneration && readerGeneration === this.readerGeneration) this.setReaderBusy(false);
4727 this.closeDialog(this.reader);
4728 this.readerCell = null;
4729 await this.rebuildAfterConfirmedWrite(rebuild);
4730 this.toast("Your report went privately to the Hive watch.");
4731 } catch (error) {
4732 this.toast(`Could not send that report: ${error.message}`);
4733 } finally {
4734 if (identityGeneration === this.identityGeneration && readerGeneration === this.readerGeneration) this.setReaderBusy(false);
4735 }
4736 }
4737
4738 async probeOperator() {
4739 const button = this.root.querySelector('[data-wall-action="watch"]');
4740 if (!button || typeof this.backend.wallOperatorStatus !== "function") return false;
4741 const probeGeneration = ++this.operatorProbeGeneration;
4742 const activationGeneration = this.activationGeneration;
4743 const identityGeneration = this.identityGeneration;
4744 try {
4745 const result = await this.backend.wallOperatorStatus();
4746 if (probeGeneration !== this.operatorProbeGeneration
4747 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
4748 this.operator = result?.operator || null;
4749 button.hidden = !this.operator;
4750 if (this.operator) button.textContent = result?.cases?.length ? "Hive watch · review" : "Hive watch";
4751 const readerWatch = this.root.querySelector('[data-wall-reader-action="watch-open"]');
4752 if (readerWatch) readerWatch.hidden = !this.operator || this.readerCell?.status !== "visible";
4753 return Boolean(this.operator);
4754 } catch {
4755 if (probeGeneration !== this.operatorProbeGeneration
4756 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
4757 this.operator = null;
4758 button.hidden = true;
4759 return false;
4760 }
4761 }
4762
4763 async submitOperatorCase() {
4764 if (this.readerBusy) return;
4765 const cell = this.readerCell;
4766 if (!cell || !this.operator || typeof this.backend.wallOpenCase !== "function") return;
4767 const reasonField = this.root.querySelector("[data-wall-operator-reason]");
4768 const reason = reasonField.value.trim();
4769 if (reason.length < 3) {
4770 this.toast("Write a short evidence-based reason for opening the case.");
4771 reasonField.focus();
4772 return;
4773 }
4774 if (!window.confirm(`Open an urgent private review case for comb ${cell.q}, ${cell.r} by ${cell.author || "this author"}?`)) return;
4775 const activationGeneration = this.activationGeneration;
4776 const identityGeneration = this.identityGeneration;
4777 const readerGeneration = this.readerGeneration;
4778 if (!this.operatorCaseRequest
4779 || this.operatorCaseRequest.cellId !== cell.id
4780 || this.operatorCaseRequest.expectedVersion !== cell.version
4781 || this.operatorCaseRequest.reason !== reason) {
4782 this.operatorCaseRequest = {
4783 requestId: randomRequestId(),
4784 cellId: cell.id,
4785 expectedVersion: cell.version,
4786 reason,
4787 };
4788 }
4789 const operatorRequest = this.operatorCaseRequest;
4790 this.setReaderBusy(true);
4791 try {
4792 const result = await this.backend.wallOpenCase({
4793 requestId: operatorRequest.requestId,
4794 cellId: cell.id,
4795 expectedVersion: cell.version,
4796 reason,
4797 priority: "urgent",
4798 });
4799 if (!this.isContextCurrent(activationGeneration, identityGeneration)
4800 || readerGeneration !== this.readerGeneration || this.readerCell?.id !== cell.id) return;
4801 if (!result?.ok) {
4802 this.toast("That comb changed before the case opened. Review the current version first.");
4803 return;
4804 }
4805 if (this.operatorCaseRequest === operatorRequest) this.operatorCaseRequest = null;
4806 this.setReaderBusy(false);
4807 this.closeDialog(this.reader, { restoreFocus: false });
4808 const watchOpened = await this.openWatch();
4809 if (!this.isContextCurrent(activationGeneration, identityGeneration)) return;
4810 if (!watchOpened) return;
4811 await this.openWatchCase(result.cellId, result.contentVersion);
4812 this.toast("Urgent review case opened for the Hive watch.");
4813 } catch (error) {
4814 if (this.isContextCurrent(activationGeneration, identityGeneration)) this.toast(`The private case was not confirmed: ${error.message}`);
4815 } finally {
4816 if (this.isContextCurrent(activationGeneration, identityGeneration)
4817 && readerGeneration === this.readerGeneration) this.setReaderBusy(false);
4818 }
4819 }
4820
4821 async openWatch() {
4822 const generation = ++this.watchGeneration;
4823 this.watchQueueRequestGeneration += 1;
4824 this.watchCaseRequestGeneration += 1;
4825 this.watchActionGeneration += 1;
4826 const activationGeneration = this.activationGeneration;
4827 const identityGeneration = this.identityGeneration;
4828 if (!this.operator && !(await this.probeOperator())) {
4829 if (generation !== this.watchGeneration
4830 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
4831 this.toast("This saved account is not on the Hive watch allowlist.");
4832 return false;
4833 }
4834 if (generation !== this.watchGeneration
4835 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
4836 this.clearWatchDom();
4837 this.watchCases = [];
4838 this.watchCursor = null;
4839 this.watchHasMore = false;
4840 this.showDialog(this.watch, this.watch.querySelector("[data-wall-close='watch']"));
4841 await this.loadWatchQueue(true, generation);
4842 if (generation !== this.watchGeneration
4843 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
4844 if (this.watchPollTimer) window.clearInterval(this.watchPollTimer);
4845 this.watchPollTimer = window.setInterval(() => {
4846 if (this.watch.open && !this.watchBusy && generation === this.watchGeneration) {
4847 void this.loadWatchQueue(true, generation, true);
4848 }
4849 }, 15_000);
4850 return true;
4851 }
4852
4853 async loadWatchQueue(reset = false, watchGeneration = this.watchGeneration, quiet = false) {
4854 if (watchGeneration !== this.watchGeneration || this.watchBusy) return false;
4855 const requestGeneration = ++this.watchQueueRequestGeneration;
4856 this.watchLoadingGeneration = requestGeneration;
4857 const activationGeneration = this.activationGeneration;
4858 const identityGeneration = this.identityGeneration;
4859 const cursor = reset ? null : this.watchCursor;
4860 const status = this.root.querySelector("[data-wall-watch-status]");
4861 const priorFingerprint = this.watchQueueFingerprint();
4862 if (!quiet) setTextIfChanged(status, reset ? "Loading attributable review cases…" : "Loading more review cases…");
4863 try {
4864 const result = await this.backend.wallModerationQueue(cursor, 50);
4865 if (watchGeneration !== this.watchGeneration
4866 || requestGeneration !== this.watchQueueRequestGeneration
4867 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
4868 this.operator = result?.operator || this.operator;
4869 const cases = Array.isArray(result?.cases) ? result.cases : [];
4870 if (reset) this.watchCases = [];
4871 const known = new Set(this.watchCases.map((item) => `${item.cellId}:${item.contentVersion}`));
4872 for (const item of cases) {
4873 const key = `${item.cellId}:${item.contentVersion}`;
4874 if (!known.has(key)) {
4875 this.watchCases.push(item);
4876 known.add(key);
4877 }
4878 }
4879 this.watchCursor = result?.nextCursor || null;
4880 this.watchHasMore = Boolean(result?.hasMore && this.watchCursor);
4881 const changed = priorFingerprint !== this.watchQueueFingerprint();
4882 if (!quiet || changed) {
4883 this.renderWatchQueue();
4884 setTextIfChanged(status, `${this.operator?.name || "Hive watch"} · ${this.operator?.role || "reviewer"} · ${this.watchCases.length}${this.watchHasMore ? "+" : ""} active cases`);
4885 }
4886 return true;
4887 } catch (error) {
4888 if (watchGeneration === this.watchGeneration
4889 && requestGeneration === this.watchQueueRequestGeneration
4890 && this.isContextCurrent(activationGeneration, identityGeneration) && !quiet) {
4891 setTextIfChanged(status, `The private review queue could not load: ${error.message}`);
4892 }
4893 return false;
4894 } finally {
4895 if (this.watchLoadingGeneration === requestGeneration) this.watchLoadingGeneration = 0;
4896 }
4897 }
4898
4899 watchQueueFingerprint() {
4900 return JSON.stringify({
4901 operator: [this.operator?.name || "", this.operator?.role || ""],
4902 cursor: this.watchCursor || null,
4903 hasMore: Boolean(this.watchHasMore),
4904 cases: this.watchCases.map((item) => [
4905 item.cellId,
4906 Number(item.contentVersion) || 0,
4907 item.priority || "",
4908 Number(item.reportCount) || 0,
4909 Number(item.q) || 0,
4910 Number(item.r) || 0,
4911 item.caseStatus || "",
4912 item.currentStatus || "",
4913 ]),
4914 });
4915 }
4916
4917 renderWatchQueue() {
4918 const activeElement = globalThis.document?.activeElement || null;
4919 const focusedKey = activeElement && this.watch.contains(activeElement)
4920 ? activeElement.dataset?.wallWatchKey || activeElement.dataset?.wallWatchFocus || null
4921 : null;
4922 const focusedTop = focusedKey && typeof activeElement.getBoundingClientRect === "function"
4923 ? activeElement.getBoundingClientRect().top
4924 : null;
4925 const existing = new Map([...this.watchQueue.querySelectorAll("[data-wall-watch-key]")]
4926 .map((button) => [button.dataset.wallWatchKey, button]));
4927 const desiredKeys = new Set();
4928 let cursor = this.watchQueue.firstElementChild;
4929 for (const item of this.watchCases) {
4930 const key = `${item.cellId}:${item.contentVersion}`;
4931 desiredKeys.add(key);
4932 let button = existing.get(key);
4933 if (!button) {
4934 button = document.createElement("button");
4935 button.type = "button";
4936 button.className = "honey-watch-case";
4937 button.dataset.wallWatchKey = key;
4938 const title = document.createElement("strong");
4939 title.dataset.wallWatchPart = "title";
4940 const detail = document.createElement("span");
4941 detail.dataset.wallWatchPart = "detail";
4942 button.append(title, detail);
4943 }
4944 button.dataset.wallWatchCase = item.cellId;
4945 button.dataset.wallWatchVersion = String(item.contentVersion);
4946 const selected = this.watchCase?.case?.cellId === item.cellId
4947 && Number(this.watchCase?.case?.contentVersion) === Number(item.contentVersion);
4948 button.setAttribute("aria-controls", "honeyWatchDetail");
4949 button.setAttribute("aria-expanded", String(selected));
4950 if (selected) button.setAttribute("aria-current", "true");
4951 else button.removeAttribute("aria-current");
4952 setTextIfChanged(button.querySelector('[data-wall-watch-part="title"]'), `${item.priority === "urgent" ? "Urgent" : "Normal"} · ${item.reportCount} ${item.reportCount === 1 ? "report" : "reports"}`);
4953 setTextIfChanged(button.querySelector('[data-wall-watch-part="detail"]'), `Comb ${item.q}, ${item.r} · ${item.caseStatus} · ${item.currentStatus}`);
4954 if (button !== cursor) this.watchQueue.insertBefore(button, cursor);
4955 cursor = button.nextElementSibling;
4956 }
4957 for (const [key, button] of existing) {
4958 if (!desiredKeys.has(key)) button.remove();
4959 }
4960 let empty = this.watchQueue.querySelector("[data-wall-watch-empty]");
4961 if (!this.watchCases.length) {
4962 if (!empty) {
4963 empty = document.createElement("p");
4964 empty.className = "honey-list-empty";
4965 empty.dataset.wallWatchEmpty = "true";
4966 this.watchQueue.append(empty);
4967 }
4968 setTextIfChanged(empty, "No Wall cases need a human decision.");
4969 } else empty?.remove();
4970 const more = this.root.querySelector("[data-wall-watch-more]");
4971 more.hidden = !this.watchHasMore;
4972 more.disabled = this.watchBusy;
4973 if (focusedKey) {
4974 const focusTarget = (focusedKey === "more" && !more.hidden && !more.disabled ? more : null)
4975 || this.watchQueue.querySelector(`[data-wall-watch-key="${escapeSelectorValue(focusedKey)}"]`)
4976 || this.watchQueue.querySelector("[data-wall-watch-key]")
4977 || (!more.hidden && !more.disabled ? more : this.watch.querySelector("[data-wall-close='watch']"));
4978 const restore = () => {
4979 focusTarget?.focus?.({ preventScroll: true });
4980 if (focusTarget && focusedTop != null && typeof globalThis.window?.scrollBy === "function") {
4981 const topDelta = focusTarget.getBoundingClientRect().top - focusedTop;
4982 if (topDelta) globalThis.window.scrollBy({ top: topDelta, behavior: "auto" });
4983 }
4984 };
4985 if (typeof globalThis.requestAnimationFrame === "function") requestAnimationFrame(restore);
4986 else restore();
4987 }
4988 }
4989
4990 async openWatchCase(cellId, contentVersion) {
4991 if (this.watchBusy) return false;
4992 const watchGeneration = this.watchGeneration;
4993 const requestGeneration = ++this.watchCaseRequestGeneration;
4994 const activationGeneration = this.activationGeneration;
4995 const identityGeneration = this.identityGeneration;
4996 const status = this.root.querySelector("[data-wall-watch-status]");
4997 this.watchCase = null;
4998 this.watchDetail.hidden = true;
4999 this.watchReason.value = "";
5000 status.textContent = "Loading preserved evidence…";
5001 try {
5002 const detail = await this.backend.wallModerationDetail(cellId, contentVersion);
5003 if (watchGeneration !== this.watchGeneration
5004 || requestGeneration !== this.watchCaseRequestGeneration
5005 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
5006 if (!detail?.case || !detail?.current) throw new Error("That review case is no longer available.");
5007 this.watchCase = detail;
5008 this.watchActionRequest = null;
5009 this.renderWatchCase();
5010 this.watchDetail.hidden = false;
5011 this.renderWatchQueue();
5012 this.watchDetail.scrollIntoView({ block: "nearest", behavior: this.motionBehavior("smooth") });
5013 this.root.querySelector("#honeyWatchCaseTitle")?.focus?.({ preventScroll: true });
5014 status.textContent = `${detail.operator?.name || "Hive watch"} · evidence is private to allowlisted reviewers`;
5015 return true;
5016 } catch (error) {
5017 if (watchGeneration === this.watchGeneration
5018 && requestGeneration === this.watchCaseRequestGeneration
5019 && this.isContextCurrent(activationGeneration, identityGeneration)) status.textContent = `That case could not load: ${error.message}`;
5020 return false;
5021 }
5022 }
5023
5024 renderWatchCase() {
5025 const detail = this.watchCase;
5026 if (!detail?.case || !detail?.current) return;
5027 const moderationCase = detail.case;
5028 const current = detail.current;
5029 this.root.querySelector("[data-wall-watch-meta]").textContent = `${moderationCase.priority} priority · ${moderationCase.status} · comb ${current.q}, ${current.r} · content v${moderationCase.contentVersion} · current v${current.version}`;
5030 this.root.querySelector("[data-wall-watch-evidence]").textContent = `${moderationCase.evidenceAuthor || "Hive member"}: ${moderationCase.evidenceBody}`;
5031 this.root.querySelector("[data-wall-watch-current]").textContent = current.contentVersion === moderationCase.contentVersion
5032 ? `Current public version: ${current.body || "No public body is visible."}`
5033 : `Current public content is now version ${current.contentVersion}: ${current.body || "No public body is visible."}`;
5034 const reportSummary = this.root.querySelector("[data-wall-watch-reports]");
5035 reportSummary.replaceChildren();
5036 const reports = Array.isArray(detail.reports) ? detail.reports : [];
5037 const summary = document.createElement("p");
5038 summary.textContent = reports.length
5039 ? `Private reports: ${reports.map((report) => `${report.reporter || "verified reporter"} (${String(report.reason).replaceAll("_", " ")})`).join(", ")}`
5040 : "Operator-opened case; no visitor report is attached.";
5041 reportSummary.append(summary);
5042 const eventSummary = this.root.querySelector("[data-wall-watch-events]");
5043 eventSummary.replaceChildren();
5044 const events = Array.isArray(detail.events) ? detail.events : [];
5045 const history = document.createElement("p");
5046 history.textContent = events.length
5047 ? `Case history: ${events.map((event) => `${event.operator || "Hive watch"} ${String(event.action).replaceAll("_", " ")}`).join("; ")}`
5048 : "No prior operator action is recorded for this case.";
5049 eventSummary.append(history);
5050 const actions = this.root.querySelector("[data-wall-watch-actions]");
5051 actions.replaceChildren();
5052 const addAction = (action, label, primary = false) => {
5053 const button = document.createElement("button");
5054 button.type = "button";
5055 button.className = `honey-tool${primary ? " honey-tool-primary" : ""}`;
5056 button.dataset.wallWatchAction = action;
5057 button.textContent = label;
5058 actions.append(button);
5059 };
5060 if (moderationCase.status === "contained") addAction("restore", "Restore publicly");
5061 else {
5062 addAction("dismiss", "Dismiss report");
5063 if (current.status === "visible" && current.contentVersion === moderationCase.contentVersion) addAction("quarantine", "Contain for review", true);
5064 }
5065 if (this.operator?.role === "admin" && ["visible", "quarantined"].includes(current.status)) addAction("remove", "Remove globally");
5066 }
5067
5068 async moderateWatchCase(action) {
5069 if (this.watchBusy) return;
5070 const detail = this.watchCase;
5071 if (!detail?.case || !detail?.current) return;
5072 const reason = this.root.querySelector("[data-wall-watch-reason]").value.trim();
5073 if (reason.length < 3) {
5074 this.root.querySelector("[data-wall-watch-status]").textContent = "Write a short evidence-based decision note first.";
5075 return;
5076 }
5077 const actionLabel = { quarantine: "Contain for review", dismiss: "Dismiss this case", restore: "Restore publicly", remove: "Remove globally" }[action] || action;
5078 const current = detail.current;
5079 if (!window.confirm(`${actionLabel} for comb ${current.q}, ${current.r} by ${current.author || "this author"}? This exact action and your note will be audited.`)) return;
5080 const watchGeneration = this.watchGeneration;
5081 const caseRequestGeneration = this.watchCaseRequestGeneration;
5082 const actionGeneration = ++this.watchActionGeneration;
5083 const activationGeneration = this.activationGeneration;
5084 const identityGeneration = this.identityGeneration;
5085 const fingerprint = [
5086 detail.case.cellId,
5087 detail.case.contentVersion,
5088 detail.case.generation,
5089 detail.current.version,
5090 action,
5091 reason,
5092 ].join(":");
5093 if (!this.watchActionRequest || this.watchActionRequest.fingerprint !== fingerprint) {
5094 this.watchActionRequest = { requestId: randomRequestId(), fingerprint };
5095 }
5096 const watchRequest = this.watchActionRequest;
5097 this.watchBusy = true;
5098 this.setWatchLocked(true);
5099 try {
5100 const result = await this.backend.wallModerateCase({
5101 requestId: watchRequest.requestId,
5102 cellId: detail.case.cellId,
5103 contentVersion: detail.case.contentVersion,
5104 caseGeneration: detail.case.generation,
5105 expectedVersion: detail.current.version,
5106 action,
5107 reason,
5108 });
5109 if (watchGeneration !== this.watchGeneration
5110 || caseRequestGeneration !== this.watchCaseRequestGeneration
5111 || actionGeneration !== this.watchActionGeneration
5112 || !this.isContextCurrent(activationGeneration, identityGeneration)) return;
5113 if (!result?.ok) {
5114 this.root.querySelector("[data-wall-watch-status]").textContent = "That case changed on another screen. Reloading current evidence…";
5115 this.watchBusy = false;
5116 this.setWatchLocked(false);
5117 await this.openWatchCase(detail.case.cellId, detail.case.contentVersion);
5118 return;
5119 }
5120 if (this.watchActionRequest === watchRequest) this.watchActionRequest = null;
5121 const rebuild = this.captureProjectionRebuild();
5122 this.watchCase = null;
5123 this.watchDetail.hidden = true;
5124 this.watchReason.value = "";
5125 this.watchBusy = false;
5126 this.setWatchLocked(false);
5127 await this.rebuildAfterConfirmedWrite(rebuild);
5128 await this.loadWatchQueue(true, watchGeneration);
5129 const focusTarget = this.watchQueue.querySelector("[data-wall-watch-key]")
5130 || (!this.root.querySelector("[data-wall-watch-more]")?.hidden ? this.root.querySelector("[data-wall-watch-more]") : null)
5131 || this.watch.querySelector('[data-wall-close="watch"]');
5132 focusTarget?.focus?.({ preventScroll: true });
5133 this.toast(`Hive watch recorded: ${action}.`);
5134 } catch (error) {
5135 if (watchGeneration === this.watchGeneration
5136 && actionGeneration === this.watchActionGeneration
5137 && this.isContextCurrent(activationGeneration, identityGeneration)) {
5138 this.root.querySelector("[data-wall-watch-status]").textContent = `The action was not confirmed: ${error.message}`;
5139 }
5140 } finally {
5141 if (watchGeneration === this.watchGeneration && actionGeneration === this.watchActionGeneration) {
5142 this.watchBusy = false;
5143 this.setWatchLocked(false);
5144 }
5145 }
5146 }
5147
5148 setWatchLocked(locked) {
5149 for (const control of this.watch.querySelectorAll("button, textarea")) {
5150 control.disabled = Boolean(locked) && !control.matches('[data-wall-close="watch"]');
5151 }
5152 if (!locked) this.renderWatchQueue();
5153 }
5154
5155 showDialog(dialog, focusTarget, openerOverride = null) {
5156 const wasOpen = Boolean(dialog.open || dialog.hasAttribute("open"));
5157 if (!wasOpen) {
5158 const active = document.activeElement;
5159 const opener = openerOverride || (active instanceof HTMLElement ? active : null);
5160 this.dialogOpeners.set(dialog, opener);
5161 const focusKey = opener?.dataset?.wallListFocus || null;
5162 this.dialogFocusAnchors.set(dialog, focusKey ? {
5163 focusKey,
5164 focusTop: typeof opener.getBoundingClientRect === "function" ? opener.getBoundingClientRect().top : null,
5165 } : null);
5166 }
5167 if (typeof dialog.showModal === "function") {
5168 if (!dialog.open) dialog.showModal();
5169 } else {
5170 dialog.setAttribute("open", "");
5171 }
5172 if (this.focusFrame) cancelAnimationFrame(this.focusFrame);
5173 this.focusFrame = requestAnimationFrame(() => {
5174 this.focusFrame = null;
5175 focusTarget?.focus();
5176 });
5177 }
5178
5179 closeDialog(dialog, options = {}) {
5180 if (!dialog) return null;
5181 if (dialog === this.compose && this.composeState) {
5182 const persisted = this.composeState.editing ? this.saveEditDraft() : this.saveDraft();
5183 if (persisted === false) {
5184 const closeAnyway = (dialog === this.compose && this.composeBusy)
5185 || window.confirm("This browser cannot save the draft outside this tab. Close the composer anyway? Your words remain here until this page reloads.");
5186 if (!closeAnyway) return null;
5187 this.toast("The draft remains only in this tab. Copy it before reloading or switching accounts.");
5188 }
5189 }
5190 if (dialog === this.compose) {
5191 this.composeGeneration += 1;
5192 this.composeBusy = false;
5193 this.composeBody.readOnly = false;
5194 this.composeState = null;
5195 this.updateResumeDraftAction();
5196 }
5197 if (dialog === this.reader) {
5198 this.readerGeneration += 1;
5199 this.readerBusy = false;
5200 this.readerCell = null;
5201 this.reportRequest = null;
5202 this.operatorCaseRequest = null;
5203 }
5204 if (dialog === this.watch) {
5205 this.watchGeneration += 1;
5206 this.watchQueueRequestGeneration += 1;
5207 this.watchCaseRequestGeneration += 1;
5208 this.watchActionGeneration += 1;
5209 if (this.watchPollTimer) window.clearInterval(this.watchPollTimer);
5210 this.watchPollTimer = null;
5211 this.watchCase = null;
5212 this.watchBusy = false;
5213 this.clearWatchDom();
5214 }
5215 const restoreFocus = options.restoreFocus !== false;
5216 const opener = this.dialogOpeners.get(dialog);
5217 const focusAnchor = this.dialogFocusAnchors.get(dialog);
5218 if (typeof dialog.close === "function" && dialog.open) dialog.close();
5219 else dialog.removeAttribute("open");
5220 this.dialogOpeners.delete(dialog);
5221 this.dialogFocusAnchors.delete(dialog);
5222 if (!restoreFocus) return opener;
5223 this.restoreWallFocus(opener, focusAnchor);
5224 return opener;
5225 }
5226
5227 restoreWallFocus(opener = null, focusAnchor = null) {
5228 if (this.focusFrame) cancelAnimationFrame(this.focusFrame);
5229 this.focusFrame = requestAnimationFrame(() => {
5230 this.focusFrame = null;
5231 if (opener?.isConnected && !opener.disabled && opener.getAttribute?.("aria-disabled") !== "true"
5232 && !opener.closest("[hidden]") && !opener.closest("dialog:not([open])")) {
5233 opener.focus({ preventScroll: true });
5234 if (!globalThis.document || globalThis.document.activeElement === opener) return;
5235 }
5236 if (this.mode === "list") {
5237 const keyedCandidate = focusAnchor?.focusKey
5238 ? this.list?.querySelector(`[data-wall-list-focus="${escapeSelectorValue(focusAnchor.focusKey)}"]`)
5239 : null;
5240 const keyedTarget = keyedCandidate && !keyedCandidate.hidden && !keyedCandidate.disabled
5241 && !keyedCandidate.closest?.("[hidden]") ? keyedCandidate : null;
5242 const listTarget = keyedTarget || this.list?.querySelector("button:not([hidden])") || this.list;
5243 listTarget?.focus({ preventScroll: true });
5244 if (listTarget && focusAnchor?.focusTop != null && typeof window.scrollBy === "function") {
5245 const topDelta = listTarget.getBoundingClientRect().top - focusAnchor.focusTop;
5246 if (topDelta) window.scrollBy({ top: topDelta, behavior: "auto" });
5247 }
5248 } else {
5249 this.stage?.focus({ preventScroll: true });
5250 }
5251 });
5252 }
5253
5254 showComposeError(message, suggestion = null) {
5255 this.composeError.hidden = false;
5256 this.composeError.textContent = message;
5257 this.composeBody?.setAttribute?.("aria-invalid", "true");
5258 const button = this.root.querySelector("[data-wall-compose-suggestion]");
5259 if (suggestion?.editConflict) {
5260 button.textContent = "Review latest comb";
5261 button.hidden = false;
5262 } else if (suggestion && Number.isInteger(suggestion.q) && Number.isInteger(suggestion.r)) {
5263 if (this.composeState) this.composeState.suggestedCoordinate = { q: suggestion.q, r: suggestion.r };
5264 button.textContent = `Move draft to ${suggestion.q}, ${suggestion.r}`;
5265 button.hidden = false;
5266 } else {
5267 if (this.composeState) this.composeState.suggestedCoordinate = null;
5268 button.hidden = true;
5269 }
5270 }
5271
5272 hideComposeError() {
5273 this.composeError.hidden = true;
5274 this.composeError.textContent = "";
5275 this.composeBody?.removeAttribute?.("aria-invalid");
5276 const button = this.root.querySelector("[data-wall-compose-suggestion]");
5277 button.hidden = true;
5278 button.textContent = "Use highlighted comb";
5279 if (this.composeState) this.composeState.suggestedCoordinate = null;
5280 }
5281
5282 saveDraft() {
5283 if (this.composeState?.editing) return;
5284 if (!this.composeState && !this.draft) return;
5285 const source = this.composeState && !this.composeState.editing ? this.composeState : this.draft;
5286 if (!source) return;
5287 const draft = {
5288 q: Number(source.q),
5289 r: Number(source.r),
5290 body: this.composeBody && this.compose.open ? this.composeBody.value : source.body || "",
5291 requestId: source.requestId || null,
5292 conversationId: source.conversationId || null,
5293 replyToId: source.replyToId || null,
5294 intent: PLACEMENT_INTENTS.has(source.intent) ? source.intent : null,
5295 anchorCellIds: canonicalAnchorIds(source.anchorCellIds),
5296 choiceMade: source.choiceMade !== false,
5297 choiceExplicit: source.choiceExplicit === true,
5298 requiresConversationChoice: source.requiresConversationChoice === true,
5299 mode: source.mode || null,
5300 updatedAt: Date.now(),
5301 };
5302 this.draft = draft;
5303 const key = this.scopedStorageKey(DRAFT_KEY);
5304 if (!key || !safeSet(this.storage, key, draft)) {
5305 this.draftPersistenceFailed = true;
5306 this.showComposeError("This browser cannot persist the draft. It is still open on this page, but reloading or switching accounts could lose it.");
5307 this.updateResumeDraftAction();
5308 return false;
5309 }
5310 this.draftPersistenceFailed = false;
5311 this.updateResumeDraftAction();
5312 return true;
5313 }
5314
5315 clearDraft() {
5316 const key = this.scopedStorageKey(DRAFT_KEY);
5317 this.draft = null;
5318 this.composeState = null;
5319 if (this.draftFromHandoff) {
5320 try { this.handoffStorage.removeItem(DRAFT_HANDOFF_KEY); } catch { /* no-op */ }
5321 }
5322 this.draftFromHandoff = false;
5323 if (key) {
5324 try { this.storage.removeItem(key); } catch { /* no-op */ }
5325 }
5326 this.updateResumeDraftAction();
5327 }
5328
5329 saveEditDraft() {
5330 const state = this.composeState?.editing ? this.composeState : this.editDraft;
5331 if (!state?.cellId) return;
5332 const draft = {
5333 cellId: state.cellId,
5334 expectedVersion: Number(state.expectedVersion) || 1,
5335 q: Number(state.q),
5336 r: Number(state.r),
5337 body: this.composeState?.editing && this.composeBody && this.compose.open ? this.composeBody.value : state.body || "",
5338 requestId: state.requestId || null,
5339 updatedAt: Date.now(),
5340 };
5341 this.editDraft = draft;
5342 const key = this.scopedStorageKey(EDIT_DRAFT_KEY);
5343 if (!key || !safeSet(this.storage, key, draft)) {
5344 this.editDraftPersistenceFailed = true;
5345 this.showComposeError("This browser cannot persist the edit draft. It is still open on this page, but reloading or switching accounts could lose it.");
5346 return false;
5347 }
5348 this.editDraftPersistenceFailed = false;
5349 return true;
5350 }
5351
5352 clearEditDraft() {
5353 const key = this.scopedStorageKey(EDIT_DRAFT_KEY);
5354 this.editDraft = null;
5355 this.editDraftPersistenceFailed = false;
5356 if (key) {
5357 try { this.storage.removeItem(key); } catch { /* no-op */ }
5358 }
5359 }
5360
5361 markSeen(cellId) {
5362 if (!cellId) return;
5363 this.seen.add(cellId);
5364 if (this.seen.size > 800) this.seen = new Set([...this.seen].slice(-600));
5365 const key = this.scopedStorageKey(SEEN_KEY);
5366 if (key) safeSet(this.storage, key, [...this.seen]);
5367 this.updateNewCount();
5368 const node = this.root.querySelector(`#honey-cell-${CSS.escape(cellId)}`);
5369 node?.classList.remove("is-unseen");
5370 }
5371
5372 updateNewCount() {
5373 if (!this.newCount) return;
5374 const ids = new Set([...this.cellsById.keys(), ...this.pendingEvents.keys()]);
5375 const count = [...ids].filter((id) => !this.seen.has(id)).length;
5376 this.newCount.hidden = count === 0;
5377 this.newCount.textContent = count ? String(Math.min(count, 99)) : "";
5378 }
5379
5380 findNew() {
5381 const unseen = [...this.cells.values()].filter((cell) => !this.seen.has(cell.id)).sort((a, b) => b.seq - a.seq)[0];
5382 if (!unseen) {
5383 this.toast("No unread combs in the loaded wall yet.");
5384 return;
5385 }
5386 this.openReader(unseen);
5387 }
5388
5389 findMine() {
5390 const mine = [...this.cells.values()].filter((cell) => cell.isMine).sort((a, b) => b.seq - a.seq)[0];
5391 if (!mine) {
5392 this.toast(this.getUser() ? "No combs from you are loaded here yet." : "Create a profile to find your combs.");
5393 if (!this.getUser()) this.requestIdentity({ reason: "wall-mine" });
5394 return;
5395 }
5396 this.openReader(mine);
5397 }
5398
5399 // Zoom about a fixed stage point so the thing under the cursor, the pinch
5400 // midpoint, or the selected comb stays put. Without an anchor the wall
5401 // slides out from under the viewer on every step.
5402 setZoom(value, anchor = null, options = {}) {
5403 const previousZoom = this.zoom;
5404 const nextZoom = this.clampZoom(value);
5405 const size = this.stageSize();
5406 const point = anchor && Number.isFinite(anchor.x) && Number.isFinite(anchor.y)
5407 ? anchor
5408 : { x: size.width / 2, y: size.height / 2 };
5409 const before = this.stageToWorld(point.x, point.y);
5410 this.zoom = nextZoom;
5411 this.cameraX = point.x - size.width / 2 - before.x * nextZoom;
5412 this.cameraY = point.y - (this.world.originY + before.y) * nextZoom;
5413 this.clampCamera();
5414 this.updatePlaneTransform();
5415 this.updateTarget();
5416 this.scheduleViewport();
5417 if (options.announce && nextZoom !== previousZoom) {
5418 this.announce(`Wall zoom ${Math.round(nextZoom * 100)} percent.`);
5419 }
5420 return this.zoom;
5421 }
5422
5423 // "See it all": pull back until the whole occupied wall is inside the stage.
5424 fitWall(announce = false) {
5425 this.cancelGrowthIntent({ restoreFocus: false, announce: false });
5426 this.ensureStageOnScreen();
5427 const content = this.contentExtent();
5428 this.zoom = this.clampZoom(this.fitZoom());
5429 const camera = this.cameraForFocus(
5430 (content.minX + content.maxX) / 2,
5431 (content.minY + content.maxY) / 2,
5432 );
5433 this.cameraX = camera.x;
5434 this.cameraY = camera.y;
5435 this.clampCamera();
5436 this.updatePlaneTransform();
5437 this.updateTarget();
5438 this.scheduleViewport();
5439 if (announce) {
5440 this.announce(`The whole Hive is in view at ${Math.round(this.zoom * 100)} percent zoom. ${this.bounds.messageCount} combs.`);
5441 }
5442 }
5443
5444 frameInitialPhoneView() {
5445 if (!this.stage || this.stage.hidden) return;
5446 const extent = this.initialPhoneExtent();
5447 this.zoom = this.clampZoom(Math.min(1, this.zoomToFit(extent)));
5448 const camera = this.cameraForFocus(
5449 (extent.minX + extent.maxX) / 2,
5450 (extent.minY + extent.maxY) / 2,
5451 this.zoom,
5452 );
5453 this.cameraX = camera.x;
5454 this.cameraY = camera.y;
5455 this.clampCamera();
5456 this.updatePlaneTransform();
5457 this.updateTarget();
5458 this.scheduleViewport();
5459 }
5460
5461 // The stage is a fixed box inside a page that still scrolls past a header,
5462 // so a deliberate wall move must first make sure the map is actually on
5463 // screen. Only fires when most of the stage is out of view, which keeps it
5464 // from fighting the scroll listener that re-runs the growth fit.
5465 ensureStageOnScreen() {
5466 const view = globalThis.window;
5467 if (!this.stage || this.stage.hidden || typeof view?.scrollTo !== "function") return;
5468 const rect = this.stage.getBoundingClientRect?.();
5469 const viewportHeight = Number(view.visualViewport?.height) || view.innerHeight || 0;
5470 if (!rect?.height || !viewportHeight) return;
5471 const visible = Math.min(rect.bottom, viewportHeight) - Math.max(rect.top, 0);
5472 if (visible >= Math.min(rect.height, viewportHeight) * 0.9) return;
5473 const slack = Math.max(0, (viewportHeight - rect.height) / 2);
5474 view.scrollTo({ top: Math.max(0, rect.top + (Number(view.scrollY) || 0) - slack), behavior: "auto" });
5475 }
5476
5477 panBy(dx, dy) {
5478 this.cameraX -= Number(dx) || 0;
5479 this.cameraY -= Number(dy) || 0;
5480 this.clampCamera();
5481 this.updatePlaneTransform();
5482 this.updateTarget();
5483 this.scheduleViewport();
5484 }
5485
5486 centerWall(announce = false) {
5487 this.cancelGrowthIntent({ restoreFocus: false, announce: false });
5488 this.selected = { q: 0, r: 0 };
5489 this.revealCoordinate(0, 0);
5490 if (announce) this.announce("Centered on the first comb.");
5491 }
5492
5493 motionBehavior(preferred = "smooth") {
5494 if (preferred !== "smooth") return preferred;
5495 return globalThis.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches ? "auto" : "smooth";
5496 }
5497
5498 // Glide the camera so a coordinate lands in the middle of the stage. Reduced
5499 // motion drops the transition rather than the movement.
5500 revealCoordinate(q, r, behavior = "smooth") {
5501 this.selected = { q: Number(q), r: Number(r) };
5502 // Unconditional, including the "auto" reveal on activation: the scroll
5503 // model this replaced always brought the wall itself into the viewport,
5504 // and skipping it left phones looking at an empty stage below the fold.
5505 this.ensureStageOnScreen();
5506 const point = axialToPixel(q, r, this.hexRadius);
5507 const view = this.visibleStageRect();
5508 this.setCameraForWorldPoint(point, (view.left + view.right) / 2, (view.top + view.bottom) / 2, behavior);
5509 this.updateTarget();
5510 this.scheduleViewport();
5511 }
5512
5513 setCameraForWorldPoint(point, stageX, stageY, behavior = "auto") {
5514 const size = this.stageSize();
5515 this.cameraX = stageX - size.width / 2 - point.x * this.zoom;
5516 this.cameraY = stageY - (this.world.originY + point.y) * this.zoom;
5517 this.clampCamera();
5518 this.applyCameraMotion(behavior);
5519 this.updatePlaneTransform();
5520 }
5521
5522 // The plane animates its own transform instead of asking the document to
5523 // scroll. The class is removed on the next frame so drags stay immediate.
5524 applyCameraMotion(behavior = "auto") {
5525 if (!this.plane) return;
5526 if (this.motionBehavior(behavior) !== "smooth") {
5527 this.plane.classList.remove("is-gliding");
5528 return;
5529 }
5530 this.plane.classList.add("is-gliding");
5531 if (this.glideTimer) window.clearTimeout(this.glideTimer);
5532 this.glideTimer = window.setTimeout(() => {
5533 this.glideTimer = null;
5534 this.plane?.classList.remove("is-gliding");
5535 this.scheduleViewport();
5536 }, 340);
5537 }
5538
5539 ensureCoordinateVisible(q, r, behavior = "smooth") {
5540 // While a growth picker is open its fit owns the camera and has already
5541 // placed all six directions on screen together. Nudging toward whichever
5542 // slot just took focus would push the opposite ones out of the viewport.
5543 if (this.growthIntent) {
5544 this.scheduleViewport();
5545 return;
5546 }
5547 this.ensureStageOnScreen();
5548 const point = axialToPixel(q, r, this.hexRadius);
5549 const view = this.visibleStageRect();
5550 const screen = this.worldToStage(point.x, point.y);
5551 const marginX = Math.min(180, view.width * 0.24);
5552 const marginY = Math.min(180, view.height * 0.24);
5553 const outsideX = screen.x < view.left + marginX || screen.x > view.right - marginX;
5554 const outsideY = screen.y < view.top + marginY || screen.y > view.bottom - marginY;
5555 if (!outsideX && !outsideY) {
5556 this.scheduleViewport();
5557 return;
5558 }
5559 // Only recentre the axis that actually ran off the edge; nudging both
5560 // makes single-step arrow navigation feel like the wall jumps.
5561 this.setCameraForWorldPoint(
5562 point,
5563 outsideX ? (view.left + view.right) / 2 : screen.x,
5564 outsideY ? (view.top + view.bottom) / 2 : screen.y,
5565 behavior,
5566 );
5567 this.updateTarget();
5568 this.scheduleViewport();
5569 }
5570
5571 setMode(mode) {
5572 this.placementIntentGeneration += 1;
5573 this.focusGeneration += 1;
5574 const previousMode = this.mode;
5575 this.mode = mode === "list" ? "list" : "wall";
5576 try { this.storage.setItem(MODE_KEY, this.mode); } catch { /* no-op */ }
5577 if (this.mode === "list") {
5578 if (previousMode !== "list") this.invalidatePublicProjectionCache();
5579 this.applyMode();
5580 void this.refreshList(this.listCells.length === 0).finally(() => this.wakeListReconciliation());
5581 } else {
5582 if (previousMode === "list") this.invalidatePublicProjectionCache();
5583 else this.discardAccessibleListWindow();
5584 this.applyMode();
5585 this.scheduleViewport();
5586 }
5587 }
5588
5589 discardAccessibleListWindow(resetConversation = true) {
5590 if (this.listReconcileTimer) window.clearTimeout(this.listReconcileTimer);
5591 this.listReconcileTimer = null;
5592 this.listReconcileEvents.clear();
5593 if (this.listItems) this.listItems.textContent = "Refreshing the authoritative Wall list…";
5594 this.listCells = [];
5595 this.listBeforeSeq = null;
5596 this.listHasMore = true;
5597 this.listWindowRevision = 0;
5598 if (resetConversation) this.listConversationId = null;
5599 this.listRequestGeneration += 1;
5600 }
5601
5602 applyMode() {
5603 if (!this.wall) return;
5604 const listMode = this.mode === "list";
5605 this.stage.hidden = listMode;
5606 this.list.hidden = !listMode;
5607 this.root.querySelector("[data-wall-edge-note]").hidden = listMode;
5608 this.wall.dataset.wallMode = listMode ? "list" : "wall";
5609 for (const modeButton of this.root.querySelectorAll('[data-wall-action="mode"]')) {
5610 modeButton.textContent = listMode ? "Return to wall" : "Read as list";
5611 modeButton.setAttribute("aria-pressed", String(listMode));
5612 }
5613 }
5614
5615 async refreshList(reset = false, preservedViewState = null) {
5616 const identityGeneration = this.identityGeneration;
5617 const cacheGeneration = this.publicCacheGeneration;
5618 const requestGeneration = ++this.listRequestGeneration;
5619 const conversationId = this.listConversationId;
5620 const viewState = preservedViewState || this.captureAccessibleListView(false);
5621 const priorCells = this.listCells.slice();
5622 const priorBeforeSeq = this.listBeforeSeq;
5623 const priorHasMore = this.listHasMore;
5624 let beforeSeq = reset ? null : priorBeforeSeq;
5625 let hasMore = reset ? true : priorHasMore;
5626 const incomingCells = [];
5627 let authoritativeListRevision = Number(this.listWindowRevision) || 0;
5628 const pageSize = conversationId ? 60 : 40;
5629 const pageBudget = 1;
5630 if (!hasMore) return;
5631 try {
5632 for (let page = 0; page < pageBudget && hasMore; page += 1) {
5633 const result = conversationId
5634 ? await this.backend.wallConversation(conversationId, beforeSeq, pageSize)
5635 : await this.backend.wallList(beforeSeq, pageSize);
5636 if (identityGeneration !== this.identityGeneration
5637 || cacheGeneration !== this.publicCacheGeneration
5638 || requestGeneration !== this.listRequestGeneration
5639 || conversationId !== this.listConversationId) return;
5640 if (!result && conversationId) throw new Error("That conversation is no longer available.");
5641 if (!result?.bounds || !Number.isSafeInteger(Number(result.bounds.revision))) {
5642 throw new Error("The wall list did not include an authoritative revision.");
5643 }
5644 const resultRevision = Number(result.bounds.revision);
5645 if (resultRevision < Math.max(this.bounds.revision, this.listWindowRevision)) {
5646 throw new Error("The wall list returned an older snapshot.");
5647 }
5648 const viewerAdvanced = this.viewerProjectionAdvanced(result.bounds);
5649 if (!this.applyAuthoritativeBounds(result.bounds)) throw new Error("The wall list returned an older snapshot.");
5650 if (viewerAdvanced && this.hasPublicProjection("list")) {
5651 const rebuildView = this.captureAccessibleListView(true);
5652 if (!rebuildView.focusKey && viewState.focusKey) Object.assign(rebuildView, viewState, { preserveScroll: true });
5653 this.invalidatePublicProjectionCache({ resetConversation: false });
5654 await this.refreshList(true, rebuildView);
5655 return;
5656 }
5657 const priorIds = new Set(priorCells.map((cell) => cell?.id).filter(Boolean));
5658 const accountedRevision = [...this.listReconcileEvents.values()].reduce((revision, event) => (
5659 priorIds.has(event?.cellId)
5660 ? Math.max(revision, Number(event?.revision) || 0)
5661 : revision
5662 ), Number(this.listWindowRevision) || 0);
5663 if (resultRevision > accountedRevision && (
5664 priorCells.length || this.cells?.size || this.conversations?.size || this.readerCell
5665 )) {
5666 // The list observed a revision that no known realtime invalidation
5667 // advanced. Some retained older row may have changed, so remove the
5668 // whole visible cache synchronously and rebuild from page one. A
5669 // failed rebuild leaves only the refresh status, never stale text.
5670 const rebuildView = this.captureAccessibleListView(true);
5671 if (!rebuildView.focusKey && viewState.focusKey) Object.assign(rebuildView, viewState, { preserveScroll: true });
5672 this.invalidatePublicProjectionCache({ resetConversation: false });
5673 await this.refreshList(true, rebuildView);
5674 return;
5675 }
5676 authoritativeListRevision = resultRevision;
5677 if (result?.conversation?.id) this.conversations.set(result.conversation.id, result.conversation);
5678 const incoming = Array.isArray(result?.cells) ? result.cells : [];
5679 for (const cell of incoming) {
5680 const canonical = this.mergeCell(cell, { renderList: false });
5681 if (canonical) {
5682 incomingCells.push(canonical);
5683 this.listReconcileEvents.delete(canonical.id);
5684 }
5685 }
5686 const nextBeforeSeq = result?.nextBeforeSeq || null;
5687 hasMore = Boolean(result?.hasMore);
5688 if (!incoming.length || nextBeforeSeq === beforeSeq) {
5689 beforeSeq = nextBeforeSeq;
5690 break;
5691 }
5692 beforeSeq = nextBeforeSeq;
5693 }
5694 if (identityGeneration !== this.identityGeneration
5695 || cacheGeneration !== this.publicCacheGeneration
5696 || requestGeneration !== this.listRequestGeneration
5697 || conversationId !== this.listConversationId) return;
5698 this.listCells = reconcileAccessibleListWindow(priorCells, incomingCells, conversationId);
5699 const frontier = accessibleListRefreshFrontier({
5700 reset,
5701 priorCells,
5702 incomingCells,
5703 priorBeforeSeq,
5704 priorHasMore,
5705 nextBeforeSeq: beforeSeq,
5706 nextHasMore: hasMore,
5707 });
5708 this.listBeforeSeq = frontier.beforeSeq;
5709 this.listHasMore = frontier.hasMore;
5710 this.listWindowRevision = authoritativeListRevision;
5711 this.root.querySelector('[data-wall-action="load-more"]').hidden = !this.listHasMore;
5712 this.renderList();
5713 this.scheduleListReconciliation(this.activationGeneration, this.identityGeneration);
5714 this.restoreAccessibleListView(viewState, requestGeneration, conversationId);
5715 } catch (error) {
5716 this.announce(`The wall list could not refresh: ${error.message}`);
5717 this.restoreAccessibleListView(viewState, requestGeneration, conversationId);
5718 }
5719 }
5720
5721 renderList() {
5722 const title = this.root.querySelector("#honeyListTitle");
5723 const allButton = this.root.querySelector('[data-wall-action="list-all"]');
5724 const conversation = this.listConversationId ? this.conversations.get(this.listConversationId) : null;
5725 const participantNames = conversation?.participants?.map((participant) => participant.name).filter(Boolean) || [];
5726 setTextIfChanged(title, this.listConversationId
5727 ? (participantNames.length ? `Conversation with ${participantNames.join(", ")}` : "One Hive conversation")
5728 : "Every comb with its connections");
5729 allButton.hidden = !this.listConversationId;
5730 for (const node of [...this.listItems.childNodes]) {
5731 if (node.nodeType !== 1) node.remove();
5732 }
5733 const existing = new Map([...this.listItems.querySelectorAll("[data-wall-list-row]")]
5734 .map((article) => [article.dataset.wallListRow, article]));
5735 const desiredIds = new Set();
5736 let cursor = this.listItems.firstElementChild;
5737 for (const cell of this.listCells) {
5738 desiredIds.add(cell.id);
5739 let article = existing.get(cell.id);
5740 if (!article) {
5741 article = document.createElement("article");
5742 article.className = "honey-list-item";
5743 article.dataset.wallListRow = cell.id;
5744 const heading = document.createElement("h3");
5745 heading.dataset.wallListPart = "heading";
5746 const meta = document.createElement("p");
5747 meta.className = "honey-list-meta";
5748 meta.dataset.wallListPart = "meta";
5749 const relation = document.createElement("p");
5750 relation.className = "honey-list-relation";
5751 relation.dataset.wallListPart = "relation";
5752 const body = document.createElement("p");
5753 body.dataset.wallListPart = "body";
5754 const open = document.createElement("button");
5755 open.type = "button";
5756 open.className = "honey-tool";
5757 open.dataset.wallListPart = "open";
5758 open.textContent = "Open this comb";
5759 const openConversation = document.createElement("button");
5760 openConversation.type = "button";
5761 openConversation.className = "honey-tool";
5762 openConversation.dataset.wallListPart = "conversation";
5763 openConversation.textContent = "Open conversation";
5764 article.append(heading, meta, relation, body, open, openConversation);
5765 }
5766 article.style.setProperty("--thread-hue", String(hueFor(cell.conversationId)));
5767 article.dataset.threadPattern = String(patternFor(cell.conversationId));
5768 const heading = article.querySelector('[data-wall-list-part="heading"]');
5769 setTextIfChanged(heading, cell.author || "Open space kept");
5770 const meta = article.querySelector('[data-wall-list-part="meta"]');
5771 setTextIfChanged(meta, `${cell.membership === "alumni" ? "DHG alumni" : cell.membership === "guest" ? "Guest" : "Hive"} · ${timeLabel(cell.createdAt)} · comb ${cell.q}, ${cell.r}`);
5772 const body = article.querySelector('[data-wall-list-part="body"]');
5773 setTextIfChanged(body, statusText(cell));
5774 const relation = article.querySelector('[data-wall-list-part="relation"]');
5775 const parent = cell.replyToId ? this.cellsById.get(cell.replyToId) : null;
5776 const growthParent = cell.growthParentId ? this.cellsById.get(cell.growthParentId) : null;
5777 const conversation = this.conversations.get(cell.conversationId);
5778 const anchorNames = (cell.origin?.anchors || []).map((anchor) => (
5779 this.cellsById.get(anchor.cellId)?.author || "a nearby conversation"
5780 ));
5781 const relationText = cell.replyToId
5782 ? `Reply to ${parent?.author || "another comb"}`
5783 : cell.origin?.kind === "branch"
5784 ? `New branch from ${anchorNames[0] || "a nearby conversation"}`
5785 : cell.origin?.kind === "meet"
5786 ? `Meeting point for ${anchorNames.length || 2} nearby conversations${anchorNames.length ? `: ${anchorNames.join(", ")}` : ""}`
5787 : conversation?.rootCellId === cell.id
5788 ? "Conversation root"
5789 : `Continuation from ${growthParent?.author || "a nearby comb"}`;
5790 const people = this.conversations.get(cell.conversationId)?.participants
5791 ?.map((participant) => participant.name).filter(Boolean).slice(0, 6) || [];
5792 setTextIfChanged(relation, people.length ? `${relationText} · Conversation: ${people.join(", ")}` : relationText);
5793 const open = article.querySelector('[data-wall-list-part="open"]');
5794 open.dataset.wallListCell = cell.id;
5795 open.dataset.wallListFocus = `cell:${cell.id}`;
5796 open.setAttribute("aria-label", `Open comb by ${cell.author || "a Hive member"} at ${cell.q}, ${cell.r}. ${relationText}.`);
5797 const openConversation = article.querySelector('[data-wall-list-part="conversation"]');
5798 openConversation.dataset.wallListConversation = cell.conversationId;
5799 openConversation.dataset.wallListFocus = `conversation:${cell.id}`;
5800 openConversation.setAttribute("aria-label", `Open the conversation around ${cell.author || `comb ${cell.q}, ${cell.r}`}${people.length ? ` with ${people.join(", ")}` : ""}.`);
5801 if (article !== cursor) this.listItems.insertBefore(article, cursor);
5802 cursor = article.nextElementSibling;
5803 }
5804 for (const [cellId, article] of existing) {
5805 if (!desiredIds.has(cellId)) article.remove();
5806 }
5807 let empty = this.listItems.querySelector(".honey-list-empty");
5808 if (!this.listCells.length) {
5809 if (!empty) {
5810 empty = document.createElement("p");
5811 empty.className = "honey-list-empty";
5812 this.listItems.append(empty);
5813 }
5814 setTextIfChanged(empty, "The wall is ready for its first comb.");
5815 } else empty?.remove();
5816 }
5817
5818 async openListConversation(conversationId) {
5819 if (!conversationId) return;
5820 this.discardAccessibleListWindow();
5821 this.listConversationId = conversationId;
5822 const identityGeneration = this.identityGeneration;
5823 await this.refreshList(false);
5824 if (identityGeneration !== this.identityGeneration || this.listConversationId !== conversationId || this.mode !== "list") return;
5825 this.list?.focus({ preventScroll: true });
5826 }
5827
5828 async showAllListMessages() {
5829 this.discardAccessibleListWindow();
5830 const identityGeneration = this.identityGeneration;
5831 await this.refreshList(false);
5832 if (identityGeneration !== this.identityGeneration || this.listConversationId !== null || this.mode !== "list") return;
5833 this.list?.focus({ preventScroll: true });
5834 }
5835
5836 async readAuthoritativeCell(cellId, contextCurrent) {
5837 for (let attempt = 0; attempt < 2; attempt += 1) {
5838 const result = await this.backend.wallCell(cellId);
5839 if (!contextCurrent()) return null;
5840 if (!result?.cell || !result?.bounds || !Number.isSafeInteger(Number(result.bounds.revision))) continue;
5841 const viewerAdvanced = this.viewerProjectionAdvanced(result.bounds);
5842 if (!this.applyAuthoritativeBounds(result.bounds)) continue;
5843 if (viewerAdvanced && this.hasPublicProjection()) {
5844 const rebuild = this.captureProjectionRebuild();
5845 this.invalidatePublicProjectionCache({ resetConversation: false });
5846 return { rebuildRequired: true, rebuild };
5847 }
5848 if (this.hasUnaccountedPublicRevision(Number(result.bounds.revision))) {
5849 const rebuild = this.captureProjectionRebuild();
5850 this.invalidatePublicProjectionCache({ resetConversation: false });
5851 return { rebuildRequired: true, rebuild };
5852 }
5853 return result;
5854 }
5855 return null;
5856 }
5857
5858 async openListCell(cellId, opener = null, rebuildAttempt = 0) {
5859 if (!cellId || this.mode !== "list") return false;
5860 const generation = ++this.focusGeneration;
5861 const activationGeneration = this.activationGeneration;
5862 const identityGeneration = this.identityGeneration;
5863 const cacheGeneration = this.publicCacheGeneration;
5864 const conversationId = this.listConversationId;
5865 const contextCurrent = () => (
5866 generation === this.focusGeneration
5867 && this.isContextCurrent(activationGeneration, identityGeneration)
5868 && cacheGeneration === this.publicCacheGeneration
5869 && this.mode === "list"
5870 && conversationId === this.listConversationId
5871 );
5872 try {
5873 const result = await this.readAuthoritativeCell(cellId, contextCurrent);
5874 if (result?.rebuildRequired) {
5875 await this.rebuildPublicProjection(result.rebuild);
5876 if (rebuildAttempt >= 1 || this.mode !== "list" || conversationId !== this.listConversationId) return false;
5877 const focusKey = opener?.dataset?.wallListFocus;
5878 const rebuiltOpener = focusKey
5879 ? this.list?.querySelector(`[data-wall-list-focus="${escapeSelectorValue(focusKey)}"]`)
5880 : this.list;
5881 return this.openListCell(cellId, rebuiltOpener || this.list, rebuildAttempt + 1);
5882 }
5883 if (!result || !contextCurrent()) return false;
5884 if (result.conversation?.id) this.conversations.set(result.conversation.id, result.conversation);
5885 const cell = this.mergeCell(result.cell, { renderList: false });
5886 if (!cell) return false;
5887 this.renderList();
5888 this.openReader(cell, opener);
5889 return true;
5890 } catch {
5891 return false;
5892 }
5893 }
5894
5895 async focusCell(cellId, options = {}, rebuildAttempt = 0) {
5896 const generation = ++this.focusGeneration;
5897 const activationGeneration = this.activationGeneration;
5898 const identityGeneration = this.identityGeneration;
5899 const cacheGeneration = this.publicCacheGeneration;
5900 if (!this.isContextCurrent(activationGeneration, identityGeneration)) return false;
5901 const contextCurrent = () => (
5902 generation === this.focusGeneration
5903 && this.isContextCurrent(activationGeneration, identityGeneration)
5904 && cacheGeneration === this.publicCacheGeneration
5905 );
5906 let result;
5907 try {
5908 result = await this.readAuthoritativeCell(cellId, contextCurrent);
5909 } catch {
5910 return false;
5911 }
5912 if (result?.rebuildRequired) {
5913 await this.rebuildPublicProjection(result.rebuild);
5914 if (rebuildAttempt >= 1 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
5915 return this.focusCell(cellId, options, rebuildAttempt + 1);
5916 }
5917 if (!result || !contextCurrent()) return false;
5918 let cell = this.mergeCell(result.cell);
5919 if (!cell) return false;
5920 if (result.conversation?.id) this.conversations.set(result.conversation.id, result.conversation);
5921 if (generation !== this.focusGeneration
5922 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
5923 this.setMode("wall");
5924 const modeGeneration = this.focusGeneration;
5925 this.revealCoordinate(cell.q, cell.r);
5926 const loaded = await this.loadChunk(chunkFor(cell.q, cell.r), true, Number(this.bounds.revision) || 0);
5927 if (modeGeneration !== this.focusGeneration
5928 || !this.isContextCurrent(activationGeneration, identityGeneration)) return false;
5929 if (!loaded?.ok) return false;
5930 this.wallWindowRevision = Math.max(Number(this.wallWindowRevision) || 0, Number(loaded.revision) || 0);
5931 this.render();
5932 if (options.open !== false) this.openReader(this.cellsById.get(cell.id) || cell);
5933 if (this.onCellLink) this.onCellLink(cell.id);
5934 return true;
5935 }
5936
5937 nudgeAround(placedCell) {
5938 if (globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
5939 for (const cell of this.cells.values()) {
5940 const distance = hexDistance(cell.q, cell.r, placedCell.q, placedCell.r);
5941 if (distance < 1 || distance > 3) continue;
5942 const node = this.nodes.get(cellKey(cell.q, cell.r));
5943 if (!node) continue;
5944 const amount = distance === 1 ? 9 : distance === 2 ? 6 : 3;
5945 const from = axialToPixel(placedCell.q, placedCell.r, 1);
5946 const to = axialToPixel(cell.q, cell.r, 1);
5947 const length = Math.hypot(to.x - from.x, to.y - from.y) || 1;
5948 node.style.setProperty("--nudge-x", `${((to.x - from.x) / length) * amount}px`);
5949 node.style.setProperty("--nudge-y", `${((to.y - from.y) / length) * amount}px`);
5950 node.classList.remove("is-nudged");
5951 void node.offsetWidth;
5952 node.classList.add("is-nudged");
5953 }
5954 }
5955
5956 announce(message) {
5957 if (!this.live) return;
5958 this.live.textContent = "";
5959 if (this.announceFrame) cancelAnimationFrame(this.announceFrame);
5960 this.announceFrame = requestAnimationFrame(() => {
5961 this.announceFrame = null;
5962 if (this.live) this.live.textContent = message;
5963 });
5964 }
5965 }
5966
5967 export function createHiveWall(options) {
5968 return new HiveWallController(options);
5969 }