aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / spark-cockpit-rs / static / hive-wall.js
| 1 | var HiveWall=(()=>{var ce=Object.defineProperty;var Ae=Object.getOwnPropertyDescriptor;var Ee=Object.getOwnPropertyNames;var Pe=Object.prototype.hasOwnProperty;var Me=(d,e)=>{for(var t in e)ce(d,t,{get:e[t],enumerable:!0})},Fe=(d,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ee(e))!Pe.call(d,s)&&s!==t&&ce(d,s,{get:()=>e[s],enumerable:!(i=Ae(e,s))||i.enumerable});return d};var Ne=d=>Fe(ce({},"__esModule",{value:!0}),d);var He={};Me(He,{DETAIL_TIERS:()=>re,HEX_DIRECTIONS:()=>me,HEX_DIRECTION_LABELS:()=>ee,HiveWallController:()=>le,WALL_LIMITS:()=>C,accessibleListRefreshFrontier:()=>ke,adjacentConversationGroups:()=>Y,axialToPixel:()=>N,canonicalAnchorIds:()=>L,cellKey:()=>v,chunkFor:()=>O,conversationChoices:()=>ae,createHiveWall:()=>Ye,hexDistance:()=>W,neighbors:()=>_,pixelToAxial:()=>j,reconcileAccessibleListWindow:()=>fe,roundAxial:()=>Te});var me=Object.freeze([Object.freeze([1,0]),Object.freeze([1,-1]),Object.freeze([0,-1]),Object.freeze([-1,0]),Object.freeze([-1,1]),Object.freeze([0,1])]),ee=Object.freeze(["east","northeast","northwest","west","southwest","southeast"]),Z=new Set(["independent","join","branch","meet"]),ge=Object.freeze([34,52,76,105,137,168,196,218,244,271,298,326,8]),C=Object.freeze({maxRadius:512,bodyCharacters:600,chunkSize:16,minZoom:.08,maxZoom:1.8}),re=Object.freeze([Object.freeze({id:"full",minZoom:.62}),Object.freeze({id:"compact",minZoom:.34}),Object.freeze({id:"dot",minZoom:0})]),te=Math.sqrt(3),pe=88,Ce=170,Se=24,ie=1.28,De=140,X="hive_wall_draft_v1",de="hive_wall_edit_draft_v1",K="hive_wall_draft_handoff_v1",qe=1200*1e3,Re="hive_wall_seen_v1",xe="hive_wall_mode_v1",Le=32,Be=5e3,We=256;function v(d,e){return`${Number(d)}:${Number(e)}`}function W(d,e,t=0,i=0){let s=Number(d)-Number(t),o=Number(e)-Number(i);return Math.max(Math.abs(s),Math.abs(o),Math.abs(s+o))}function N(d,e,t=pe){return{x:t*te*(Number(d)+Number(e)/2),y:t*1.5*Number(e)}}function Te(d,e){let t=Number(d),i=Number(e),s=-t-i,o=Math.round(t),n=Math.round(s),r=Math.round(i),h=Math.abs(o-t),a=Math.abs(n-s),l=Math.abs(r-i);return h>a&&h>l?o=-n-r:a>l?n=-o-r:r=-o-n,{q:o,r}}function j(d,e,t=pe){let i=(te/3*Number(d)-Number(e)/3)/t,s=2/3*Number(e)/t;return Te(i,s)}function _(d,e){return me.map(([t,i])=>({q:Number(d)+t,r:Number(e)+i}))}function O(d,e,t=C.chunkSize){let i=Math.floor(Number(d)/t)*t,s=Math.floor(Number(e)/t)*t;return Object.freeze({key:`${i}:${s}`,qMin:i,qMax:i+t-1,rMin:s,rMax:s+t-1})}function ae(d,e,t,i=null){return Y(d,e,t,i).map(s=>s.anchors[0]?.cell).filter(Boolean)}function Y(d,e,t,i=null){let s=new Map;return _(e,t).forEach((o,n)=>{let r=d instanceof Map?d.get(v(o.q,o.r)):null;if(!r?.conversationId||r.status&&r.status!=="visible")return;if(i instanceof Map){let a=i.get(r.conversationId);if(!a||a.status!=="open")return}let h=s.get(r.conversationId);h||(h={conversationId:r.conversationId,anchors:[]},s.set(r.conversationId,h)),h.anchors.push({cell:r,direction:n,directionLabel:ee[n]})}),[...s.values()]}function L(d){return[...new Set((d||[]).filter(e=>typeof e=="string"&&e))].sort()}function fe(d,e,t=null){let i=new Map;for(let s of[...d||[],...e||[]])s&&s.id&&i.set(s.id,s);return[...i.values()].sort(t?(s,o)=>s.seq-o.seq:(s,o)=>o.seq-s.seq)}function ke({reset:d,priorCells:e,incomingCells:t,priorBeforeSeq:i,priorHasMore:s,nextBeforeSeq:o,nextHasMore:n}){let r=new Set((e||[]).map(a=>a?.id).filter(Boolean));return!!(d&&r.size&&(t||[]).some(a=>r.has(a?.id)))?{beforeSeq:i,hasMore:s}:{beforeSeq:o,hasMore:n}}function F(d,e,t){return Math.min(t,Math.max(e,d))}function se(d){return globalThis.CSS&&typeof globalThis.CSS.escape=="function"?globalThis.CSS.escape(String(d)):String(d).replace(/["\\]/g,"\\$&")}function g(d,e){if(!d)return;let t=String(e??"");d.textContent!==t&&(d.textContent=t)}function M(d,e,t=C.maxRadius){return Number.isInteger(d)&&Number.isInteger(e)&&W(d,e)<=t}function J(d,e,t){try{let i=JSON.parse(d.getItem(e));return i??t}catch{return t}}function Q(d,e,t){try{let i=JSON.stringify(t);return d.setItem(e,i),d.getItem(e)===i&&d.__hivePersistent!==!1}catch{return!1}}function Ge(){let d=new Map;return{__hivePersistent:!1,getItem(e){return d.has(e)?d.get(e):null},setItem(e,t){d.set(e,String(t))},removeItem(e){d.delete(e)}}}function Ve(d){if(d)return d;try{let e=globalThis.localStorage,t="__hive_wall_storage_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return Ge()}}function $e(d){if(d)return d;try{let e=globalThis.sessionStorage,t="__hive_wall_session_probe__";return e.setItem(t,"1"),e.removeItem(t),e}catch{return Ge()}}function H(d,e=!1){if(!d||!M(Number(d.q),Number(d.r)))return null;let t=typeof d.body=="string"?[...d.body].slice(0,C.bodyCharacters).join(""):"",i=d.intent&&Z.has(d.intent)?d.intent:d.conversationId?"join":"independent";return{q:Number(d.q),r:Number(d.r),body:t,requestId:e?null:typeof d.requestId=="string"?d.requestId:null,conversationId:typeof d.conversationId=="string"?d.conversationId:null,replyToId:typeof d.replyToId=="string"?d.replyToId:null,intent:i,anchorCellIds:L(d.anchorCellIds),choiceMade:d.choiceMade!==!1,choiceExplicit:d.choiceExplicit===!0,requiresConversationChoice:d.requiresConversationChoice===!0,mode:typeof d.mode=="string"?d.mode:null,updatedAt:Number(d.updatedAt)||Date.now()}}function U(){if(globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto.randomUUID();let d=new Uint8Array(16);if(globalThis.crypto&&typeof globalThis.crypto.getRandomValues=="function")globalThis.crypto.getRandomValues(d);else for(let t=0;t<d.length;t+=1)d[t]=Math.floor(Math.random()*256);d[6]=d[6]&15|64,d[8]=d[8]&63|128;let e=[...d].map(t=>t.toString(16).padStart(2,"0"));return`${e.slice(0,4).join("")}-${e.slice(4,6).join("")}-${e.slice(6,8).join("")}-${e.slice(8,10).join("")}-${e.slice(10).join("")}`}function oe(d){let e=2166136261;for(let t of String(d||"hive"))e^=t.charCodeAt(0),e=Math.imul(e,16777619);return ge[Math.abs(e)%ge.length]}function Ie(d){let e=0;for(let t of String(d||"hive"))e=Math.imul(e^t.charCodeAt(0),16777619);return Math.abs(e)%4}function ue(d){let e=Number(d);if(!Number.isFinite(e))return"";let t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.max(1,Math.floor(t/6e4))}m`:t<864e5?`${Math.floor(t/36e5)}h`:new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function ne(d){return d.viewerHidden?"Hidden after your private report":d.status==="author_removed"?"Message removed by its author":d.status==="quarantined"?"Message under review":d.status==="moderator_removed"?"Message removed by the Hive watch":d.body||""}function ze(d){return d instanceof Element&&!!d.closest("input, textarea, select, [contenteditable='true']")}function Oe(){return` |
| 2 | <section class="honey-wall" aria-labelledby="honeyWallTitle"> |
| 3 | <h1 id="honeyWallTitle" class="sr-only">The Hive conversation wall</h1> |
| 4 | <div class="honey-toolbar" aria-label="Hive wall controls"> |
| 5 | <div class="honey-toolbar-group honey-toolbar-main"> |
| 6 | <button type="button" class="honey-tool honey-tool-primary" data-wall-action="add">Add a comb</button> |
| 7 | <button type="button" class="honey-tool honey-tool-mode" data-wall-action="mode" aria-pressed="false">Read as list</button> |
| 8 | <button type="button" class="honey-tool honey-resume-tool" data-wall-action="resume" hidden>Resume draft</button> |
| 9 | <button type="button" class="honey-tool" data-wall-action="new">Find new <span data-wall-new-count hidden></span></button> |
| 10 | <button type="button" class="honey-tool" data-wall-action="mine">My combs</button> |
| 11 | <button type="button" class="honey-tool honey-watch-tool" data-wall-action="watch" hidden>Hive watch</button> |
| 12 | </div> |
| 13 | <div class="honey-toolbar-group honey-toolbar-view" aria-label="Move and zoom the wall"> |
| 14 | <button type="button" class="honey-tool" data-wall-action="center">Center</button> |
| 15 | <button type="button" class="honey-tool" data-wall-action="fit">See it all</button> |
| 16 | <button type="button" class="honey-tool" data-wall-action="zoom-out" aria-label="Zoom out">\u2212</button> |
| 17 | <output class="honey-zoom" data-wall-zoom aria-label="Wall zoom">100%</output> |
| 18 | <button type="button" class="honey-tool" data-wall-action="zoom-in" aria-label="Zoom in">+</button> |
| 19 | </div> |
| 20 | </div> |
| 21 | <header class="honey-welcome"> |
| 22 | <p class="honey-eyebrow">One wall \xB7 countless conversations</p> |
| 23 | <h2>The page is the Hive.</h2> |
| 24 | <p>Conversations grow beside each other instead of being sorted into a feed.</p> |
| 25 | <details class="honey-start-guide" data-wall-onboarding open> |
| 26 | <summary>Start here \xB7 three simple steps</summary> |
| 27 | <ol> |
| 28 | <li><strong>Pick a comb.</strong><span>Tap a message to read it, or choose Add a comb to begin.</span></li> |
| 29 | <li><strong>Choose a direction.</strong><span>Continue nearby, start a branch, or let conversations meet.</span></li> |
| 30 | <li><strong>Write and place it.</strong><span>Your message stays attached to the path you chose.</span></li> |
| 31 | </ol> |
| 32 | <p>Drag to move around. Pinch or use the zoom controls to change the view. Prefer a straight reading order? Choose <strong>Read as list</strong>.</p> |
| 33 | </details> |
| 34 | </header> |
| 35 | <div class="honey-summary" aria-hidden="true"> |
| 36 | <span class="honey-summary-mark">THE HIVE</span> |
| 37 | <span data-wall-summary>Loading the wall\u2026</span> |
| 38 | </div> |
| 39 | <p class="sr-only" data-wall-state-status role="status" aria-live="polite">Loading the shared Wall.</p> |
| 40 | <p id="honeyWallKeyboardHelp" class="sr-only">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.</p> |
| 41 | <div class="honey-stage" data-wall-stage tabindex="0" role="application" aria-label="Honeycomb message wall" aria-describedby="honeyWallKeyboardHelp"> |
| 42 | <div class="honey-plane" data-wall-plane> |
| 43 | <div class="honey-connections" data-wall-connections aria-hidden="true"></div> |
| 44 | <div class="honey-cells" data-wall-cells></div> |
| 45 | <div class="honey-growth-slots" data-wall-growth-slots aria-label="Open places around this comb"></div> |
| 46 | <div class="honey-target" data-wall-target aria-hidden="true"><span>+</span></div> |
| 47 | </div> |
| 48 | </div> |
| 49 | <div class="honey-growth-tray" data-wall-growth-tray role="status" hidden> |
| 50 | <span data-wall-growth-copy></span> |
| 51 | <button type="button" class="honey-tool" data-wall-action="nearest-growth" hidden>Find nearest open edge</button> |
| 52 | <button type="button" class="honey-tool" data-wall-action="cancel-growth">Cancel</button> |
| 53 | </div> |
| 54 | <section class="honey-list" data-wall-list hidden tabindex="-1" aria-labelledby="honeyListTitle"> |
| 55 | <div class="honey-list-head"> |
| 56 | <div><p class="honey-eyebrow">Accessible wall view</p><h2 id="honeyListTitle">Every comb with its connections</h2></div> |
| 57 | <div class="honey-list-actions"> |
| 58 | <button type="button" class="honey-tool" data-wall-action="list-all" data-wall-list-focus="list-all" hidden>All messages</button> |
| 59 | <button type="button" class="honey-tool" data-wall-action="load-more" data-wall-list-focus="load-more">Load more</button> |
| 60 | </div> |
| 61 | </div> |
| 62 | <div data-wall-list-items></div> |
| 63 | </section> |
| 64 | <div class="honey-edge-note" data-wall-edge-note>Click any open place in the honeycomb to leave a message.</div> |
| 65 | <div class="honey-live sr-only" data-wall-live aria-live="polite" aria-atomic="true"></div> |
| 66 | |
| 67 | <dialog class="honey-sheet honey-compose" data-wall-compose aria-labelledby="honeyComposeTitle"> |
| 68 | <form method="dialog" data-wall-compose-form> |
| 69 | <div class="honey-sheet-grip" aria-hidden="true"></div> |
| 70 | <div class="honey-sheet-head"> |
| 71 | <div><p class="honey-eyebrow" data-wall-compose-kicker>Open comb</p><h2 id="honeyComposeTitle" data-wall-compose-title>Leave a message</h2></div> |
| 72 | <button type="button" class="honey-sheet-close" data-wall-close="compose" aria-label="Close composer">\xD7</button> |
| 73 | </div> |
| 74 | <p class="honey-compose-place" data-wall-compose-place></p> |
| 75 | <fieldset class="honey-conversation-choices" data-wall-conversation-choices hidden> |
| 76 | <legend data-wall-conversation-legend>How should this comb connect?</legend> |
| 77 | <div data-wall-conversation-options></div> |
| 78 | </fieldset> |
| 79 | <label class="honey-compose-label" for="honeyComposeBody">Your message</label> |
| 80 | <textarea id="honeyComposeBody" data-wall-compose-body rows="5" maxlength="600" required aria-describedby="honeyComposePrivacy honeyComposeCount" aria-errormessage="honeyComposeError" placeholder="Leave something worth finding here\u2026"></textarea> |
| 81 | <div class="honey-compose-meta" id="honeyComposePrivacy"> |
| 82 | <span>Public to everyone who visits the Hive.</span> |
| 83 | <output id="honeyComposeCount" data-wall-compose-count>0 / 600</output> |
| 84 | </div> |
| 85 | <p class="honey-compose-error" id="honeyComposeError" data-wall-compose-error role="alert" hidden></p> |
| 86 | <div class="honey-sheet-actions"> |
| 87 | <button type="button" class="honey-tool" data-wall-close="compose" data-wall-compose-cancel>Keep as draft</button> |
| 88 | <button type="button" class="honey-tool" data-wall-compose-suggestion hidden>Use highlighted comb</button> |
| 89 | <button type="submit" class="honey-tool honey-tool-primary" data-wall-compose-submit>Place this comb</button> |
| 90 | </div> |
| 91 | </form> |
| 92 | </dialog> |
| 93 | |
| 94 | <dialog class="honey-sheet honey-reader" data-wall-reader aria-labelledby="honeyReaderTitle"> |
| 95 | <div class="honey-sheet-grip" aria-hidden="true"></div> |
| 96 | <div class="honey-sheet-head"> |
| 97 | <div><p class="honey-eyebrow" data-wall-reader-kicker>Conversation comb</p><h2 id="honeyReaderTitle" data-wall-reader-author></h2></div> |
| 98 | <button type="button" class="honey-sheet-close" data-wall-close="reader" aria-label="Close message">\xD7</button> |
| 99 | </div> |
| 100 | <p class="honey-reader-meta" data-wall-reader-meta></p> |
| 101 | <div class="honey-reader-body" data-wall-reader-body></div> |
| 102 | <div class="honey-participants" data-wall-reader-participants></div> |
| 103 | <div class="honey-relations" data-wall-reader-relations></div> |
| 104 | <div class="honey-sheet-actions honey-reader-actions"> |
| 105 | <button type="button" class="honey-tool honey-tool-primary" data-wall-reader-action="reply">Reply from this comb</button> |
| 106 | <button type="button" class="honey-tool" data-wall-reader-action="branch">Start a new branch</button> |
| 107 | <button type="button" class="honey-tool" data-wall-reader-action="show">Show on wall</button> |
| 108 | <button type="button" class="honey-tool" data-wall-reader-action="edit" hidden>Edit</button> |
| 109 | <button type="button" class="honey-tool" data-wall-reader-action="remove" hidden>Remove</button> |
| 110 | <button type="button" class="honey-tool honey-report" data-wall-reader-action="report">Report</button> |
| 111 | <button type="button" class="honey-tool honey-watch-open" data-wall-reader-action="watch-open" hidden>Open urgent review</button> |
| 112 | </div> |
| 113 | <form class="honey-report-form" data-wall-report-form hidden> |
| 114 | <label for="honeyReportReason">Why should the Hive watch look at this?</label> |
| 115 | <select id="honeyReportReason" data-wall-report-reason required> |
| 116 | <option value="" selected disabled>Choose a reason</option> |
| 117 | <option value="personal_attack">Attack aimed at a person</option> |
| 118 | <option value="illegal">Illegal content</option> |
| 119 | <option value="spam">Spam or flooding</option> |
| 120 | <option value="privacy">Private information</option> |
| 121 | </select> |
| 122 | <div class="honey-sheet-actions"> |
| 123 | <button type="button" class="honey-tool" data-wall-reader-action="cancel-report">Cancel</button> |
| 124 | <button type="submit" class="honey-tool honey-tool-primary">Send private report</button> |
| 125 | </div> |
| 126 | </form> |
| 127 | <form class="honey-operator-form" data-wall-operator-form hidden> |
| 128 | <label for="honeyOperatorReason">Why does this comb need urgent human review?</label> |
| 129 | <textarea id="honeyOperatorReason" data-wall-operator-reason maxlength="500" rows="3" required placeholder="Record the evidence-based reason for opening this case."></textarea> |
| 130 | <div class="honey-sheet-actions"> |
| 131 | <button type="button" class="honey-tool" data-wall-reader-action="cancel-watch-open">Cancel</button> |
| 132 | <button type="submit" class="honey-tool honey-tool-primary">Open private case</button> |
| 133 | </div> |
| 134 | </form> |
| 135 | </dialog> |
| 136 | |
| 137 | <dialog class="honey-sheet honey-watch" data-wall-watch aria-labelledby="honeyWatchTitle"> |
| 138 | <div class="honey-sheet-grip" aria-hidden="true"></div> |
| 139 | <div class="honey-watch-inner"> |
| 140 | <div class="honey-sheet-head"> |
| 141 | <div><p class="honey-eyebrow">Allowlisted human review</p><h2 id="honeyWatchTitle">Hive watch</h2></div> |
| 142 | <button type="button" class="honey-sheet-close" data-wall-close="watch" aria-label="Close Hive watch">\xD7</button> |
| 143 | </div> |
| 144 | <p class="honey-watch-status" data-wall-watch-status role="status" aria-live="polite"></p> |
| 145 | <div class="honey-watch-queue" data-wall-watch-queue></div> |
| 146 | <button type="button" class="honey-tool honey-watch-more" data-wall-watch-more data-wall-watch-focus="more" hidden>Load more cases</button> |
| 147 | <section class="honey-watch-detail" id="honeyWatchDetail" data-wall-watch-detail hidden aria-labelledby="honeyWatchCaseTitle"> |
| 148 | <h3 id="honeyWatchCaseTitle" tabindex="-1">Review case</h3> |
| 149 | <p data-wall-watch-meta></p> |
| 150 | <blockquote data-wall-watch-evidence></blockquote> |
| 151 | <p data-wall-watch-current></p> |
| 152 | <div data-wall-watch-reports></div> |
| 153 | <div data-wall-watch-events></div> |
| 154 | <label for="honeyWatchReason">Decision note</label> |
| 155 | <textarea id="honeyWatchReason" data-wall-watch-reason maxlength="500" rows="3" placeholder="State the evidence-based reason for this action."></textarea> |
| 156 | <div class="honey-sheet-actions" data-wall-watch-actions></div> |
| 157 | </section> |
| 158 | </div> |
| 159 | </dialog> |
| 160 | </section>`}var le=class d{constructor(e={}){if(!e.root)throw new Error("HiveWall needs a root element.");if(!e.backend)throw new Error("HiveWall needs the shared backend.");this.root=e.root,this.backend=e.backend,this.getUser=typeof e.getUser=="function"?e.getUser:()=>null,this.requestIdentity=typeof e.requestIdentity=="function"?e.requestIdentity:()=>{},this.toast=typeof e.toast=="function"?e.toast:()=>{},this.onCellLink=typeof e.onCellLink=="function"?e.onCellLink:null,this.onPlaced=typeof e.onPlaced=="function"?e.onPlaced:null,this.storage=Ve(e.storage),this.handoffStorage=$e(e.handoffStorage),this.hexRadius=Number(e.hexRadius)||pe,this.cells=new Map,this.cellsById=new Map,this.conversations=new Map,this.nodes=new Map,this.connectionNodes=new Map,this.loadedChunks=new Set,this.chunkAccess=new Map,this.cellChunks=new Map,this.dirtyChunks=new Set,this.inflightChunks=new Map,this.visibleChunkKeys=new Set,this.pendingEvents=new Map,this.retryEvents=new Map,this.listReconcileEvents=new Map,this.consumingEvents=new Map,this.realtimeDrainQueue=new Map,this.realtimeDrainPromise=null,this.realtimeDrainDirty=!1,this.seenRealtimeEvents=new Set,this.forceRefreshOnActivate=!1,this.publicCacheGeneration=0,this.wallWindowRevision=0,this.bounds={revision:0,viewerRevision:0,radius:5,messageCount:0,readOnly:!0,updatedAt:0},this.mode=this.storage&&this.storage.getItem(xe)==="list"?"list":"wall",this.zoom=1,this.cameraX=0,this.cameraY=0,this.world={halfWidth:0,halfHeight:0,width:0,height:0,originX:0,originY:0},this.detailTier=null,this.pinch=null,this.selected={q:0,r:0},this.selectedCellKey=null,this.readerCell=null,this.reportRequest=null,this.operatorCaseRequest=null,this.watchActionRequest=null,this.composeState=null,this.growthIntent=null,this.placementIntentGeneration=0,this.focusGeneration=0,this.composeGeneration=0,this.readerGeneration=0,this.watchGeneration=0,this.watchQueueRequestGeneration=0,this.watchCaseRequestGeneration=0,this.watchActionGeneration=0,this.operatorProbeGeneration=0,this.scopeRequestGeneration=0,this.composeBusy=!1,this.readerBusy=!1,this.operator=null,this.watchCase=null,this.watchLoadingGeneration=0,this.watchBusy=!1,this.watchCases=[],this.watchCursor=null,this.watchHasMore=!1,this.watchPollTimer=null,this.active=!1,this.mounted=!1,this.unsubscribe=null,this.realtimeTeardown=Promise.resolve(),this.pollTimer=null,this.eventTimer=null,this.eventRetryTimer=null,this.listReconcileTimer=null,this.renderFrame=null,this.glideTimer=null,this.momentumFrame=null,this.viewportRefreshPromise=null,this.viewportRefreshDirty=!1,this.viewportRefreshForce=!1,this.focusFrame=null,this.growthFitFrame=null,this.announceFrame=null,this.eventAbort=null,this.dialogOpeners=new Map,this.dialogFocusAnchors=new Map,this.pointer=null,this.activePointers=new Map,this.suppressCellClickUntil=0,this.suppressBackdropClick=null,this.listCells=[],this.listBeforeSeq=null,this.listHasMore=!0,this.listConversationId=null,this.listWindowRevision=0,this.listRequestGeneration=0,this.boundsRequestGeneration=0,this.boundsSuccessGeneration=0,this.lastGoodAt=0,this.hasActivated=!1,this.activationGeneration=0,this.realtimeGeneration=0,this.transportState="polling",this.dataStale=!1,this.storageScope=null,this.identityGeneration=0,this.seen=new Set,this.draft=null,this.editDraft=null,this.draftPersistenceFailed=!1,this.editDraftPersistenceFailed=!1,this.draftFromHandoff=!1,this.quarantinedDrafts=new Map,this.orphanedPrivateDraft=null,this.viewportWidth=window.innerWidth,this.boundViewport=t=>{this.updateVisualViewport();let i=window.innerWidth;if(this.growthIntent){this.viewportWidth=i,this.growthFitFrame&&cancelAnimationFrame(this.growthFitFrame),this.growthFitFrame=requestAnimationFrame(()=>{this.growthFitFrame=null,this.fitGrowthIntent()}),this.scheduleViewport();return}t?.type!=="scroll"&&(this.viewportWidth=i,this.setZoom(this.zoom,null,{announce:!1}))},this.boundVisualViewport=()=>this.boundViewport({type:"visualviewport"}),this.boundVisibility=()=>{document.visibilityState==="visible"&&this.active&&(this.mode==="list"?this.refreshList(!0):this.refreshVisible(!0),this.wakeListReconciliation())},this.boundOnline=()=>{this.setConnectionState(navigator.onLine?this.dataStale?"stale":this.transportState:"offline"),navigator.onLine&&this.wakeListReconciliation()}}mount(){this.mounted||(this.eventAbort=new AbortController,this.root.innerHTML=Oe(),this.wall=this.root.querySelector(".honey-wall"),this.stage=this.root.querySelector("[data-wall-stage]"),this.plane=this.root.querySelector("[data-wall-plane]"),this.cellLayer=this.root.querySelector("[data-wall-cells]"),this.connectionLayer=this.root.querySelector("[data-wall-connections]"),this.growthSlots=this.root.querySelector("[data-wall-growth-slots]"),this.growthTray=this.root.querySelector("[data-wall-growth-tray]"),this.target=this.root.querySelector("[data-wall-target]"),this.live=this.root.querySelector("[data-wall-live]"),this.summary=this.root.querySelector("[data-wall-summary]"),this.newCount=this.root.querySelector("[data-wall-new-count]"),this.zoomOutput=this.root.querySelector("[data-wall-zoom]"),this.list=this.root.querySelector("[data-wall-list]"),this.listItems=this.root.querySelector("[data-wall-list-items]"),this.compose=this.root.querySelector("[data-wall-compose]"),this.composeBody=this.root.querySelector("[data-wall-compose-body]"),this.composeError=this.root.querySelector("[data-wall-compose-error]"),this.reader=this.root.querySelector("[data-wall-reader]"),this.watch=this.root.querySelector("[data-wall-watch]"),this.watchQueue=this.root.querySelector("[data-wall-watch-queue]"),this.watchDetail=this.root.querySelector("[data-wall-watch-detail]"),this.watchReason=this.root.querySelector("[data-wall-watch-reason]"),this.bindEvents(),this.applyMode(),this.updateWorldSize(),this.updateTarget(),this.mounted=!0)}bindEvents(){let e={signal:this.eventAbort.signal};this.root.addEventListener("click",t=>this.handleClick(t),e),this.root.addEventListener("keydown",t=>{t.key==="Escape"&&this.growthIntent&&!t.defaultPrevented&&(t.preventDefault(),this.cancelGrowthIntent())},e),this.stage.addEventListener("keydown",t=>this.handleStageKey(t),e),this.stage.addEventListener("pointerdown",t=>this.handlePointerDown(t),e),this.stage.addEventListener("pointermove",t=>this.handlePointerMove(t),e),this.stage.addEventListener("pointerup",t=>this.handlePointerUp(t),e),this.stage.addEventListener("pointercancel",t=>this.cancelPointerGesture(t),e),this.stage.addEventListener("wheel",t=>this.handleWheel(t),{...e,passive:!1}),this.stage.addEventListener("dblclick",t=>this.handleDoubleClick(t),e),this.stage.addEventListener("focusin",t=>this.handleStageFocus(t),e),typeof globalThis.ResizeObserver=="function"&&(this.trayObserver=new globalThis.ResizeObserver(()=>{let t=this.growthTray?.getBoundingClientRect?.().height||0;!this.growthIntent||Math.abs(t-(this.lastGrowthTrayHeight||0))<1||(this.lastGrowthTrayHeight=t,this.scheduleGrowthFit())}),this.trayObserver.observe(this.growthTray)),this.root.querySelector("[data-wall-compose-form]").addEventListener("submit",t=>{t.preventDefault(),this.submitCompose()},e),this.composeBody.addEventListener("input",()=>{this.root.querySelector("[data-wall-compose-count]").textContent=`${[...this.composeBody.value].length} / 600`,this.composeState&&(this.composeState.requestId=null),(this.composeState?.editing?this.saveEditDraft():this.saveDraft())!==!1&&this.hideComposeError()},e),this.composeBody.addEventListener("focus",()=>this.updateVisualViewport(),e),this.root.querySelector("[data-wall-report-form]").addEventListener("submit",t=>{t.preventDefault(),this.submitReport()},e),this.root.querySelector("[data-wall-report-reason]").addEventListener("change",()=>{this.reportRequest=null},e),this.root.querySelector("[data-wall-operator-reason]").addEventListener("input",()=>{this.operatorCaseRequest=null},e),this.root.querySelector("[data-wall-watch-reason]").addEventListener("input",()=>{this.watchActionRequest=null},e),this.root.querySelector("[data-wall-operator-form]").addEventListener("submit",t=>{t.preventDefault(),this.submitOperatorCase()},e),this.root.querySelector("[data-wall-compose-suggestion]").addEventListener("click",()=>this.acceptComposeSuggestion(),e);for(let t of[this.compose,this.reader,this.watch])t.addEventListener("cancel",i=>{i.preventDefault(),this.closeDialog(t)},e),t.addEventListener("click",i=>{if(i.target!==t)return;let s=this.suppressBackdropClick;if(s?.dialog===t&&Date.now()<=s.until){this.suppressBackdropClick=null,i.preventDefault(),i.stopPropagation();return}s?.dialog===t&&(this.suppressBackdropClick=null),this.closeDialog(t)},e)}async activate(e={}){if(this.mount(),this.active){e.cellId&&await this.focusCell(e.cellId);return}let t=++this.activationGeneration;if(this.active=!0,this.wall.classList.add("is-active"),await this.syncStorageScope(!1),!this.isActivationCurrent(t))return;window.addEventListener("resize",this.boundViewport,{passive:!0}),window.addEventListener("scroll",this.boundViewport,{passive:!0}),window.visualViewport?.addEventListener?.("resize",this.boundVisualViewport,{passive:!0}),window.visualViewport?.addEventListener?.("scroll",this.boundVisualViewport,{passive:!0}),window.addEventListener("online",this.boundOnline),window.addEventListener("offline",this.boundOnline),document.addEventListener("visibilitychange",this.boundVisibility),this.updateVisualViewport();try{await this.startRealtime()}catch{this.unsubscribe=null,this.transportState="polling",this.setConnectionState(navigator.onLine?"polling":"offline")}if(!this.isActivationCurrent(t)||(await this.refreshBounds(),!this.isActivationCurrent(t)))return;let i=!this.hasActivated&&!e.cellId;i&&this.revealCoordinate(0,0,"auto"),this.hasActivated=!0;let s=this.forceRefreshOnActivate;if(this.forceRefreshOnActivate=!1,await this.refreshVisible(s),!!this.isActivationCurrent(t)){if(i&&this.mode==="wall"&&this.viewportWidth<=760&&this.frameInitialPhoneView(),this.probeOperator(),this.mode==="list"){if(await this.refreshList(!0),!this.isActivationCurrent(t))return;this.wakeListReconciliation()}this.pollTimer&&window.clearInterval(this.pollTimer),this.pollTimer=window.setInterval(()=>{this.active&&document.visibilityState==="visible"&&(this.mode==="list"?this.refreshList(!0):this.refreshVisible(!0),this.operator&&this.probeOperator())},45e3),!(e.cellId&&(await this.focusCell(e.cellId),!this.isActivationCurrent(t)))&&(this.draft&&M(this.draft.q,this.draft.r,C.maxRadius)&&this.announce("Your unfinished wall message is still here."),this.updateResumeDraftAction())}}deactivate(){if(this.activationGeneration+=1,this.realtimeGeneration+=1,this.scopeRequestGeneration+=1,this.invalidatePrivateOperations({saveDraft:!0,closeDialogs:!0}),!!this.active){this.active=!1,this.wall.classList.remove("is-active"),window.removeEventListener("resize",this.boundViewport),window.removeEventListener("scroll",this.boundViewport),window.visualViewport?.removeEventListener?.("resize",this.boundVisualViewport),window.visualViewport?.removeEventListener?.("scroll",this.boundVisualViewport),window.removeEventListener("online",this.boundOnline),window.removeEventListener("offline",this.boundOnline),document.removeEventListener("visibilitychange",this.boundVisibility),this.cancelGrowthIntent({restoreFocus:!1,announce:!1,restoreView:!1}),this.stopRealtime(),this.pollTimer&&window.clearInterval(this.pollTimer),this.eventTimer&&window.clearTimeout(this.eventTimer),this.eventRetryTimer&&window.clearTimeout(this.eventRetryTimer),this.listReconcileTimer&&window.clearTimeout(this.listReconcileTimer),this.renderFrame&&cancelAnimationFrame(this.renderFrame),this.focusFrame&&cancelAnimationFrame(this.focusFrame),this.growthFitFrame&&cancelAnimationFrame(this.growthFitFrame),this.growthFitFrame=null;for(let e of[...this.pendingEvents.values(),...this.retryEvents.values(),...this.realtimeDrainQueue.values(),...this.consumingEvents.values()])if(e?.eventKey&&this.seenRealtimeEvents.delete(e.eventKey),M(Number(e?.q),Number(e?.r))){let t=O(Number(e.q),Number(e.r));this.loadedChunks.delete(t.key),this.inflightChunks.has(t.key)&&this.dirtyChunks.add(t.key)}this.forceRefreshOnActivate=!0,this.pollTimer=null,this.eventTimer=null,this.eventRetryTimer=null,this.listReconcileTimer=null,this.renderFrame=null,this.stopMomentum(),this.viewportRefreshPromise=null,this.viewportRefreshDirty=!1,this.viewportRefreshForce=!1,this.realtimeDrainPromise=null,this.realtimeDrainDirty=!1,this.focusFrame=null,this.pendingEvents.clear(),this.retryEvents.clear(),this.realtimeDrainQueue?.clear?.(),this.consumingEvents.clear(),this.discardAccessibleListWindow()}}isActivationCurrent(e){return this.active&&this.mounted&&e===this.activationGeneration}isContextCurrent(e,t){return this.isActivationCurrent(e)&&t===this.identityGeneration}closeDialogImmediately(e){e&&(typeof e.close=="function"&&e.open?e.close():e.removeAttribute("open"),this.dialogOpeners.delete(e),this.dialogFocusAnchors.delete(e))}invalidatePrivateOperations(e={}){e.saveDraft&&this.composeState&&(this.composeState.editing?this.saveEditDraft():this.saveDraft()),this.placementIntentGeneration+=1,this.focusGeneration+=1,this.composeGeneration+=1,this.readerGeneration+=1,this.watchGeneration+=1,this.watchQueueRequestGeneration+=1,this.watchCaseRequestGeneration+=1,this.watchActionGeneration+=1,this.operatorProbeGeneration+=1,this.listRequestGeneration+=1,this.composeBusy=!1,this.readerBusy=!1,this.watchBusy=!1,this.watchLoadingGeneration=0,this.composeState=null,this.readerCell=null,this.reportRequest=null,this.operatorCaseRequest=null,this.watchActionRequest=null,this.watchCase=null,this.operator=null;let t=this.root.querySelector?.('[data-wall-action="watch"]');t&&(t.hidden=!0),this.watchPollTimer&&window.clearInterval(this.watchPollTimer),this.watchPollTimer=null,this.watchCases=[],this.watchCursor=null,this.watchHasMore=!1,this.clearWatchDom(),e.closeDialogs&&(this.closeDialogImmediately(this.compose),this.closeDialogImmediately(this.reader),this.closeDialogImmediately(this.watch))}preserveUnpersistedDrafts(e=this.storageScope){let t=!!(this.draft||this.composeState&&!this.composeState.editing),i=!!(this.editDraft||this.composeState?.editing),s=!t||this.saveDraft()!==!1,o=!i||this.saveEditDraft()!==!1;if(s&&o)return!0;let n={draft:s?null:H(this.draft,!0),editDraft:!o&&this.editDraft?{...this.editDraft}:null};if(e){let r=this.quarantinedDrafts.get(e)||{};this.quarantinedDrafts.set(e,{draft:n.draft||r.draft||null,editDraft:n.editDraft||r.editDraft||null})}else this.orphanedPrivateDraft=n;return!1}resetIdentityState(){if(!this.mounted)return;this.publicCacheGeneration+=1,this.preserveUnpersistedDrafts(this.storageScope),this.invalidatePrivateOperations({saveDraft:!1,closeDialogs:!0}),this.cancelGrowthIntent({restoreFocus:!1,announce:!1,restoreView:!1}),this.identityGeneration+=1,this.scopeRequestGeneration+=1,this.storageScope=null,this.cells.clear(),this.cellsById.clear(),this.conversations.clear();for(let i of this.nodes.values())i.remove();this.nodes.clear();for(let i of this.connectionNodes?.values?.()||[])i.remove();this.connectionNodes?.clear?.(),this.loadedChunks.clear(),this.chunkAccess.clear(),this.cellChunks.clear(),this.dirtyChunks.clear(),this.inflightChunks.clear(),this.pendingEvents.clear(),this.retryEvents.clear(),this.listReconcileEvents.clear(),this.realtimeDrainQueue?.clear?.(),this.consumingEvents.clear(),this.realtimeDrainPromise=null,this.realtimeDrainDirty=!1,this.eventTimer&&window.clearTimeout(this.eventTimer),this.eventRetryTimer&&window.clearTimeout(this.eventRetryTimer),this.listReconcileTimer&&window.clearTimeout(this.listReconcileTimer),this.eventTimer=null,this.eventRetryTimer=null,this.listReconcileTimer=null,this.seenRealtimeEvents.clear(),this.listCells=[],this.listBeforeSeq=null,this.listHasMore=!0,this.listConversationId=null,this.listWindowRevision=0,this.wallWindowRevision=0,this.bounds={...this.bounds,viewerRevision:0},this.listRequestGeneration+=1,this.seen.clear(),this.draft=null,this.editDraft=null,this.draftPersistenceFailed=!1,this.editDraftPersistenceFailed=!1,this.draftFromHandoff=!1,this.selected={q:0,r:0},this.cameraX=0,this.hasActivated=!1,this.composeBody&&(this.composeBody.value=""),this.hideComposeError();let e=this.root.querySelector?.("[data-wall-report-reason]"),t=this.root.querySelector?.("[data-wall-operator-reason]");e&&(e.value=""),t&&(t.value=""),this.watchReason&&(this.watchReason.value=""),this.listItems?.replaceChildren(),this.render(),this.updateNewCount(),this.updateTarget(),this.updatePlaneTransform(),this.updateResumeDraftAction()}clearWatchDom(){this.watchActionRequest=null,this.watchQueue&&this.watchQueue.replaceChildren(),this.watchDetail&&(this.watchDetail.hidden=!0);let e=n=>{let r=this.root.querySelector?.(n);r&&(r.textContent="")};e("[data-wall-watch-status]"),e("[data-wall-watch-meta]"),e("[data-wall-watch-evidence]"),e("[data-wall-watch-current]");let t=this.root.querySelector?.("[data-wall-watch-reports]"),i=this.root.querySelector?.("[data-wall-watch-events]"),s=this.root.querySelector?.("[data-wall-watch-actions]"),o=this.root.querySelector?.("[data-wall-watch-more]");t?.replaceChildren(),i?.replaceChildren(),s?.replaceChildren(),o&&(o.hidden=!0),this.watchReason&&(this.watchReason.value="")}destroy(){this.deactivate(),this.eventAbort?.abort(),this.eventAbort=null,this.renderFrame&&cancelAnimationFrame(this.renderFrame),this.focusFrame&&cancelAnimationFrame(this.focusFrame),this.announceFrame&&cancelAnimationFrame(this.announceFrame),this.eventTimer&&window.clearTimeout(this.eventTimer),this.eventRetryTimer&&window.clearTimeout(this.eventRetryTimer),this.listReconcileTimer&&window.clearTimeout(this.listReconcileTimer),this.glideTimer&&window.clearTimeout(this.glideTimer),this.trayObserver?.disconnect?.(),this.trayObserver=null,this.stopMomentum(),this.renderFrame=null,this.glideTimer=null,this.focusFrame=null,this.announceFrame=null,this.eventTimer=null,this.eventRetryTimer=null,this.listReconcileTimer=null,this.pendingEvents.clear(),this.retryEvents.clear(),this.listReconcileEvents.clear(),this.realtimeDrainQueue?.clear?.(),this.consumingEvents.clear(),this.inflightChunks.clear(),this.connectionNodes?.clear?.(),this.nodes.clear(),this.root.replaceChildren(),this.mounted=!1}prepareIdentityHandoff(){if(this.composeState?.editing||this.editDraft){if(this.saveEditDraft()===!1)return this.toast("Account switching stopped because this edit draft cannot be persisted safely."),!1;if(!this.draft&&(!this.composeState||this.composeState.editing))return this.cancelIdentityHandoff(),null}let e=this.composeState&&!this.composeState.editing?this.saveDraft():this.draft?this.saveDraft():!0,t=H(this.draft,!0);if(!t)return this.cancelIdentityHandoff(),null;if(!this.storageScope)return this.toast("This draft is not attached to a verified Hive identity yet. Finish or copy it before switching accounts."),!1;if(!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."))return this.cancelIdentityHandoff(),e===!1?(this.toast("Account switching stopped because the draft cannot stay safely with this identity in this browser."),!1):(this.toast("The draft stays private to the Hive identity that started it."),null);let s=Q(this.handoffStorage,K,{fromScope:this.storageScope,createdAt:Date.now(),sourceApproved:!0,draft:t});return s||this.toast("This browser could not safely hand the draft to another account. It remains with the current identity."),s}prepareIdentityExit(){return this.cancelIdentityHandoff(),!this.draft&&!this.editDraft&&!this.composeState?!0:!this.storageScope||!this.preserveUnpersistedDrafts(this.storageScope)?(this.toast("Starting fresh stopped because this browser cannot keep the unfinished Wall draft private to this identity."),!1):!0}cancelIdentityHandoff(){try{this.handoffStorage.removeItem(K)}catch{}}hasDraftHandoff(){let e=J(this.handoffStorage,K,null),t=Date.now()-Number(e?.createdAt||0),i=!!(e?.sourceApproved===!0&&typeof e.fromScope=="string"&&H(e.draft,!0)&&t>=0&&t<=qe);return!i&&e&&this.cancelIdentityHandoff(),i}async restoreDraftHandoff(e){let t=this.storageScope,i=this.identityGeneration,s=J(this.handoffStorage,K,null);if(!s)return!1;let o=()=>{try{this.handoffStorage.removeItem(K)}catch{}},n=Date.now()-Number(s.createdAt||0),r=H(s.draft,!0);if(s.sourceApproved!==!0||!r||n<0||n>qe)return o(),!1;let h=typeof s.fromScope=="string"?s.fromScope:"";if(!h)return o(),!1;if(h&&h===this.storageScope){if(this.draft)return o(),!0;let l=this.scopedStorageKey(X);return l&&Q(this.storage,l,r)?(this.draft=r,this.draftFromHandoff=!1,o(),this.toast("Your unfinished Wall draft was recovered with a new safe request."),this.updateResumeDraftAction(),!0):(this.draft=r,this.draftFromHandoff=!1,o(),this.toast("Your handoff draft is open in this tab. This browser cannot store it locally, so copy it before reloading."),this.updateResumeDraftAction(),!0)}if(this.draft)return o(),this.toast("This saved account already has an unfinished wall draft. The other draft remains with the browser identity that started it."),!1;if(t!==this.storageScope||i!==this.identityGeneration||!this.storageScope)return!1;let a=this.scopedStorageKey(X);if(!a||!Q(this.storage,a,r))return this.draft=r,this.draftFromHandoff=!1,o(),this.toast("The approved draft is open in this tab. This browser cannot store it locally, so copy it before reloading."),this.updateResumeDraftAction(),!0;if(this.draft=r,this.draftFromHandoff=!1,h){try{this.storage.removeItem(`${X}:${h}`)}catch{}this.quarantinedDrafts.delete(h)}return o(),this.toast("Draft restored for this saved account with a new safe request."),this.updateResumeDraftAction(),!0}async resumeAfterIdentity(e={}){let t=this.activationGeneration;if(!this.isActivationCurrent(t))return!1;let i=this.storageScope;if(await this.syncStorageScope(!1),!this.isActivationCurrent(t))return!1;let s=this.identityGeneration;if(await this.restoreDraftHandoff(i),!this.isContextCurrent(t,s))return!1;try{await this.startRealtime()}catch{this.unsubscribe=null,this.transportState="polling",this.setConnectionState(navigator.onLine?"polling":"offline")}return!this.isContextCurrent(t,s)||(this.probeOperator(),!this.active||!this.draft||!M(this.draft.q,this.draft.r))?!1:this.resumeCurrentDraft()}async resumeCurrentDraft(){let e=this.activationGeneration,t=this.identityGeneration;if(!this.isContextCurrent(e,t))return!1;let i=H(this.draft);if(!i)return!1;this.selected={q:i.q,r:i.r},this.updateTarget(),this.revealCoordinate(i.q,i.r,"auto");let s=await this.hydratePlacement(i.q,i.r);if(!this.isContextCurrent(e,t))return!1;let o=s.ok?s.groups||Y(this.cells,i.q,i.r,this.conversations):[],n=s.ok&&o.length===0&&!i.choiceExplicit;return this.openComposer({...i,choices:s.ok?s.choices:[],groups:o,intent:n?"independent":i.intent,choiceExplicit:i.choiceExplicit||n,placementVerified:s.ok,requiresConversationChoice:i.requiresConversationChoice||!i.choiceExplicit&&s.ok&&o.length>0,choiceMade:!!(n||i.choiceMade&&i.intent)}),s.ok||this.showComposeError("The exact comb and draft are open, but the Hive must reconnect and verify the nearby conversations before it can be placed."),!0}updateResumeDraftAction(){let e=this.root.querySelector?.('[data-wall-action="resume"]');if(!e)return;let t=H(this.draft,!0);e.hidden=!t,t&&(e.textContent=`Resume draft at ${t.q}, ${t.r}`)}setConnectionState(e){if(!this.wall)return;let t=this.wall.dataset.connection;this.wall.dataset.connection=e,this.updatePersistentStatus?.(),t!==e&&e==="offline"&&this.announce("Offline. The last loaded wall stays visible and drafts remain on this device.")}updatePersistentStatus(){let e=this.root.querySelector?.("[data-wall-state-status]");if(!e)return;let t=this.wall?.dataset?.connection||this.transportState||"polling",i={live:"Live updates connected.",polling:"Checking periodically for shared changes.",reconnecting:"Reconnecting; the last verified Wall remains visible.",stale:"Connection interrupted; the last verified Wall remains visible.",offline:"Offline; the last verified Wall remains visible and drafts stay on this device."}[t]||"Checking the shared Wall.",s=this.bounds?.readOnly?"Reading is open. New combs remain closed until Hive Watch is staffed and verified.":"Reading and new combs are open.";g(e,`${i} ${s}`)}async stopRealtime(){let e=this.unsubscribe;this.unsubscribe=null;let t=this.realtimeTeardown,i=Promise.resolve(t).catch(()=>{}).then(()=>typeof e=="function"?e():void 0);this.realtimeTeardown=Promise.resolve(i).catch(()=>{}),await this.realtimeTeardown}async startRealtime(){if(!this.active)return;let e=++this.realtimeGeneration;await this.stopRealtime(),!(!this.active||e!==this.realtimeGeneration)&&(this.unsubscribe=this.backend.subscribeWallChanges(t=>{this.active&&e===this.realtimeGeneration&&this.queueRealtimeEvent(t)},t=>{!this.active||e!==this.realtimeGeneration||(this.transportState=t==="SUBSCRIBED"?"live":t==="POLLING"?"polling":"reconnecting",this.setConnectionState(navigator.onLine?this.dataStale?"stale":this.transportState:"offline"))}))}scopedStorageKey(e){return this.storageScope?`${e}:${this.storageScope}`:null}async syncStorageScope(e){let t=++this.scopeRequestGeneration,i=null;try{typeof this.backend.wallIdentityKey=="function"&&(i=await this.backend.wallIdentityKey(!!e))}catch{return this.dataStale=!0,this.setConnectionState(navigator.onLine?"stale":"offline"),this.storageScope}if(t!==this.scopeRequestGeneration)return this.storageScope;if(i===this.storageScope)return i;let s=this.storageScope;this.preserveUnpersistedDrafts(s),this.invalidatePrivateOperations({saveDraft:!1,closeDialogs:!0}),this.identityGeneration+=1,this.publicCacheGeneration+=1,this.storageScope=i,this.cells.clear(),this.cellsById.clear(),this.conversations.clear();for(let l of this.nodes.values())l.remove();this.nodes.clear();for(let l of this.connectionNodes?.values?.()||[])l.remove();this.connectionNodes?.clear?.(),this.loadedChunks.clear(),this.chunkAccess.clear(),this.cellChunks.clear(),this.dirtyChunks.clear(),this.inflightChunks.clear(),this.eventTimer&&window.clearTimeout(this.eventTimer),this.eventRetryTimer&&window.clearTimeout(this.eventRetryTimer),this.listReconcileTimer&&window.clearTimeout(this.listReconcileTimer),this.eventTimer=null,this.eventRetryTimer=null,this.listReconcileTimer=null,this.pendingEvents.clear(),this.retryEvents.clear(),this.realtimeDrainQueue?.clear?.(),this.consumingEvents.clear(),this.realtimeDrainPromise=null,this.realtimeDrainDirty=!1,this.listReconcileEvents.clear(),this.seenRealtimeEvents.clear(),this.listCells=[],this.listBeforeSeq=null,this.listHasMore=!0,this.listConversationId=null,this.listWindowRevision=0,this.wallWindowRevision=0,this.bounds={...this.bounds,viewerRevision:0},this.listRequestGeneration+=1,this.readerCell=null,this.reportRequest=null;let o=this.scopedStorageKey(X),n=this.scopedStorageKey(de),r=this.scopedStorageKey(Re),h=i?this.quarantinedDrafts.get(i):null;this.draft=(o?J(this.storage,o,null):null)||h?.draft||null,this.editDraft=(n?J(this.storage,n,null):null)||h?.editDraft||null,i&&h&&this.quarantinedDrafts.delete(i);let a=r?J(this.storage,r,[]):[];return this.seen=new Set(Array.isArray(a)?a:[]),this.draftPersistenceFailed=!1,this.editDraftPersistenceFailed=!1,this.draftFromHandoff=!1,this.render(),this.updateResumeDraftAction(),i}updateVisualViewport(){if(!this.wall)return;let e=getComputedStyle(document.documentElement),t=e.getPropertyValue("--hive-vv-height").trim(),i=e.getPropertyValue("--hive-keyboard-inset").trim();if(t){this.wall.style.setProperty("--honey-visual-height","var(--hive-vv-height)"),this.wall.style.setProperty("--honey-keyboard-offset",i?"var(--hive-keyboard-inset)":"0px");return}let s=window.visualViewport,o=s?s.height:window.innerHeight,n=s?Math.max(0,window.innerHeight-s.height-s.offsetTop):0;this.wall.style.setProperty("--honey-visual-height",`${Math.max(1,o)}px`),this.wall.style.setProperty("--honey-keyboard-offset",`${n}px`)}async refreshBounds(){let e=this.identityGeneration,t=this.activationGeneration,i=++this.boundsRequestGeneration,s=()=>this.mounted&&e===this.identityGeneration&&t===this.activationGeneration;try{let o=await this.backend.wallBounds();if(!s())return this.bounds;if(!o||!Number.isSafeInteger(Number(o.revision)))throw new Error("The wall bounds were incomplete.");let n=this.viewerProjectionAdvanced(o);return this.applyAuthoritativeBounds(o)?(n&&this.hasPublicProjection()&&this.invalidatePublicProjectionCache({resetConversation:!1}),this.boundsSuccessGeneration=Math.max(this.boundsSuccessGeneration,i),this.lastGoodAt=Date.now(),this.dataStale=!1,this.setConnectionState(navigator.onLine?this.transportState:"offline"),this.bounds):this.bounds}catch(o){return!s()||i<this.boundsSuccessGeneration?this.bounds:(this.dataStale=!0,this.setConnectionState(navigator.onLine?"stale":"offline"),this.lastGoodAt||this.announce(`The shared wall is unavailable: ${o.message}`),this.bounds)}}applyAuthoritativeBounds(e){let t=Number(e?.revision);if(!Number.isSafeInteger(t)||t<0)return!1;let i=Number(e?.viewerRevision)||0;if(!Number.isSafeInteger(i)||i<0)return!1;let s=Number(this.bounds.revision)||0,o=Number(this.bounds.viewerRevision)||0,n=Number(e.updatedAt)||0,r=Number(this.bounds.updatedAt)||0;if(t<s||i<o||t===s&&n<r)return!1;let h=t===s&&n===r;return this.bounds={revision:t,viewerRevision:i,radius:Math.max(this.bounds.radius,F(Number(e.radius)||5,5,C.maxRadius)),messageCount:Math.max(this.bounds.messageCount,Math.max(0,Number(e.messageCount)||0)),readOnly:h?!!(this.bounds.readOnly||e.readOnly):!!e.readOnly,updatedAt:n||r||Date.now()},this.updateWorldSize(),this.updateSummary(),!0}viewerProjectionAdvanced(e){let t=Number(e?.viewerRevision)||0,i=Number(this.bounds.viewerRevision)||0;return Number.isSafeInteger(t)&&t>i}updateSummary(){if(!this.summary)return;let e=this.bounds.messageCount===1?"1 comb":`${this.bounds.messageCount.toLocaleString()} combs`;g(this.summary,`${e} \xB7 wall revision ${this.bounds.revision.toLocaleString()}${this.bounds.readOnly?" \xB7 reading open while Hive Watch is verified":""}`),this.wall?.toggleAttribute("data-read-only",this.bounds.readOnly);let t=this.root.querySelector('[data-wall-action="add"]');t&&(t.disabled=this.bounds.readOnly,t.title=this.bounds.readOnly?"Messages open after Hive Watch verification":"Add a message to an open comb");let i=this.root.querySelector("[data-wall-edge-note]");i&&g(i,this.bounds.readOnly?"The Wall is open to read while Hive Watch is verified. New combs will open soon.":"Click any open place in the honeycomb to leave a message.");let s=this.root.querySelector("[data-wall-compose-submit]");s&&(s.disabled=this.bounds.readOnly||this.composeBusy||!!(this.composeState&&!this.composeState.editing&&(!this.composeState.choiceMade||!Z.has(this.composeState.intent)))),this.updatePersistentStatus(),this.readerCell&&this.paintReaderCell(this.readerCell,{preserveForms:!0})}captureAccessibleListView(e=!1){let t=globalThis.document?.activeElement||null,i=t&&this.list?.contains(t)&&t.dataset?.wallListFocus||null;return{focusKey:i,focusTop:i&&typeof t.getBoundingClientRect=="function"?t.getBoundingClientRect().top:null,preserveScroll:!!e,scrollY:e?Number(globalThis.window?.scrollY)||0:null}}restoreAccessibleListView(e,t,i){if(!e)return;let s=()=>{if(t!==this.listRequestGeneration||i!==this.listConversationId||this.mode!=="list")return;let o=e.focusKey?this.list?.querySelector(`[data-wall-list-focus="${se(e.focusKey)}"]`):null,n=o&&!o.hidden&&!o.disabled&&!o.closest?.("[hidden]")?o:null;if(n){if(n.focus({preventScroll:!0}),e.focusTop!=null&&typeof globalThis.window?.scrollBy=="function"){let r=n.getBoundingClientRect().top-e.focusTop;r&&globalThis.window.scrollBy({top:r,behavior:"auto"})}}else if(e.focusKey){let r=this.list?.querySelector("[data-wall-list-items] button:not([hidden]):not(:disabled), button:not([hidden]):not(:disabled)")||this.list;if(r?.focus?.({preventScroll:!0}),r&&e.focusTop!=null&&typeof r.getBoundingClientRect=="function"&&typeof globalThis.window?.scrollBy=="function"){let h=r.getBoundingClientRect().top-e.focusTop;h&&globalThis.window.scrollBy({top:h,behavior:"auto"})}else r?.scrollIntoView?.({block:"nearest",behavior:"auto"})}else e.preserveScroll&&typeof globalThis.window?.scrollTo=="function"&&globalThis.window.scrollTo({top:e.scrollY,behavior:"auto"})};typeof globalThis.requestAnimationFrame=="function"?requestAnimationFrame(s):s()}invalidatePublicProjectionCache(e={}){this.publicCacheGeneration+=1,this.focusGeneration+=1,this.wallWindowRevision=0,this.selectedCellKey=null,this.stage?.removeAttribute?.("aria-activedescendant");for(let t of this.nodes?this.nodes.values():[]){t.disabled=!0,t.dataset.placeholder="true",t.classList.add("is-refreshing"),t.classList.remove("is-selected","is-unseen","is-mine","is-viewer-hidden"),t.removeAttribute("aria-current"),t.setAttribute("aria-label","Refreshing this comb's position");for(let i of t.querySelectorAll?.(".honey-comb-author,.honey-comb-body,.honey-comb-foot")||[])i.textContent=""}for(let t of this.connectionNodes?this.connectionNodes.values():[])t.classList.add("is-refreshing"),t.removeAttribute("data-relation");this.wall?.setAttribute?.("aria-busy","true"),this.cells?.clear?.(),this.cellsById?.clear?.(),this.cellChunks?.clear?.(),this.loadedChunks?.clear?.(),this.chunkAccess?.clear?.(),this.dirtyChunks?.clear?.(),this.inflightChunks?.clear?.(),this.visibleChunkKeys?.clear?.(),this.conversations?.clear?.(),this.composeState&&e.preserveComposer===!1?(this.composeState.editing?this.saveEditDraft():this.saveDraft(),this.composeGeneration+=1,this.composeBusy=!1,this.composeState=null,this.closeDialogImmediately(this.compose),this.updateResumeDraftAction()):this.composeState&&!this.composeState.editing&&(this.markComposerProjectionPending(),this.draft={...this.composeState,body:this.composeBody?.value||this.composeState.body||""},this.saveDraft()),(this.readerCell||this.reader?.open||this.reader?.hasAttribute?.("open"))&&this.closeReaderForProjectionRefresh(),this.discardAccessibleListWindow(e.resetConversation!==!1)}publicProjectionAccountedRevision(e=this.mode){if(e!=="list")return Number(this.wallWindowRevision)||0;let t=new Set(this.listCells.map(i=>i?.id).filter(Boolean));return[...this.listReconcileEvents.values()].reduce((i,s)=>t.has(s?.cellId)?Math.max(i,Number(s?.revision)||0):i,Number(this.listWindowRevision)||0)}hasPublicProjection(e=this.mode){return e==="list"?!!(this.listCells.length||this.listItems?.querySelector?.("[data-wall-list-row]")||this.cells?.size||this.cellsById?.size||this.conversations?.size||this.readerCell):!!(this.cells?.size||this.cellsById?.size||this.conversations?.size||this.loadedChunks?.size||this.nodes?.size||this.readerCell)}hasUnaccountedPublicRevision(e,t=this.mode){let i=Number(e);return Number.isSafeInteger(i)&&this.hasPublicProjection(t)&&i>this.publicProjectionAccountedRevision(t)}captureProjectionRebuild(){return{mode:this.mode,conversationId:this.listConversationId,listView:this.mode==="list"?this.captureAccessibleListView(!0):null}}async rebuildPublicProjection(e){return!e||e.mode!==this.mode||!this.active||!this.mounted?!1:e.mode==="list"?e.conversationId!==this.listConversationId?!1:(await this.refreshList(!0,e.listView),this.mode==="list"&&e.conversationId===this.listConversationId):this.refreshVisible(!0,0)}refreshCurrentPublicProjection(){!this.active||!this.mounted||(this.mode==="list"?this.refreshList(!0):this.refreshVisible(!0))}async rebuildAfterConfirmedWrite(e=this.captureProjectionRebuild()){return this.invalidatePublicProjectionCache({resetConversation:!1}),this.rebuildPublicProjection(e)}evictWallChunkProjection(e,t={}){let i=t.preserveGeometry===!0;this.loadedChunks.delete(e),this.chunkAccess.delete(e),this.dirtyChunks.delete(e);let s=!1,o=new Set;for(let[n,r]of[...this.cellChunks]){if(r!==e)continue;o.add(n);let h=this.cellsById.get(n);if(this.readerCell?.id===n&&(s=!0),h&&this.cells.get(v(h.q,h.r))?.id===n){this.cells.delete(v(h.q,h.r));let a=this.nodes.get(v(h.q,h.r));if(i&&a){a.disabled=!0,a.dataset.placeholder="true",a.classList.add("is-refreshing"),a.classList.remove("is-selected","is-unseen","is-mine","is-viewer-hidden"),a.removeAttribute("aria-current"),a.setAttribute("aria-label","Refreshing this comb's position");for(let l of a.querySelectorAll(".honey-comb-author,.honey-comb-body,.honey-comb-foot"))l.textContent=""}else a?.remove(),this.nodes.delete(v(h.q,h.r))}this.cellsById.delete(n),this.cellChunks.delete(n)}if(i){for(let[n,r]of this.connectionNodes)[...o].some(h=>n.includes(`:${h}`))&&(r.classList.add("is-refreshing"),r.removeAttribute("data-relation"));this.wall?.setAttribute?.("aria-busy","true")}s&&this.closeReaderForProjectionRefresh()}evictPublicCellProjection(e){let t=this.cellsById.get(e)||this.listCells.find(i=>i?.id===e)||null;t&&this.cells.get(v(t.q,t.r))?.id===e&&(this.cells.delete(v(t.q,t.r)),this.nodes.get(v(t.q,t.r))?.remove(),this.nodes.delete(v(t.q,t.r))),this.cellsById.delete(e),this.cellChunks.delete(e),this.listCells=this.listCells.filter(i=>i?.id!==e),this.readerCell?.id===e&&this.closeReaderForProjectionRefresh()}closeReaderForProjectionRefresh(){if(!this.readerCell&&!this.reader?.open&&!this.reader?.hasAttribute?.("open"))return;let e=this.dialogOpeners.get(this.reader)||null,t=this.dialogFocusAnchors.get(this.reader)||null,i=this.root?.querySelector?.("[data-wall-reader-body]");g(i,"Refreshing this comb from the shared Wall\u2026"),this.readerGeneration+=1,this.readerBusy=!1,this.readerCell=null,this.reportRequest=null,this.operatorCaseRequest=null,this.closeDialogImmediately(this.reader),this.restoreWallFocus(e,t)}markComposerProjectionPending(){if(!this.composeState||this.composeState.editing)return;let e=!!(this.composeState.conversationId||this.composeState.replyToId||this.composeState.requiresConversationChoice||this.composeState.choices?.length);this.composeState.placementVerified=!1,this.composeState.choices=[];let t=!!(this.composeState.requestId||this.composeState.choiceExplicit);t||(this.composeState.conversationId=null,this.composeState.replyToId=null,this.composeState.choiceMade=!1,this.composeState.choiceExplicit=!1),this.composeState.requiresConversationChoice=e&&!t;let i=this.root?.querySelector?.("[data-wall-conversation-choices]"),s=this.root?.querySelector?.("[data-wall-conversation-options]");if(!i||!s)return;let o=!!(globalThis.document?.activeElement&&s.contains?.(globalThis.document.activeElement));if(s.replaceChildren(),i.hidden=!e,e){let n=document.createElement("p");if(n.className="honey-choice-pending",n.textContent="Nearby conversations must reload before you choose where this comb belongs.",s.append(n),o){this.announce(n.textContent);let r=()=>this.composeBody?.focus?.({preventScroll:!0});typeof globalThis.requestAnimationFrame=="function"?requestAnimationFrame(r):r()}}}updateWorldSize(){if(!this.plane||!this.stage)return;let e=Math.max(0,Number(this.bounds?.radius)||0),t=N(e,0,this.hexRadius).x+this.hexRadius,i=e*this.hexRadius*1.5+this.hexRadius,s=t*2+Ce*2,o=i*2+Ce*2,n=s/2,r=o/2;if(!(this.world.halfWidth===t&&this.world.halfHeight===i)){if(this.world={halfWidth:t,halfHeight:i,width:s,height:o,originX:n,originY:r},this.plane.style.width=`${Math.ceil(s)}px`,this.plane.style.height=`${Math.ceil(o)}px`,this.plane.style.marginLeft=`${Math.ceil(s/-2)}px`,this.plane.style.setProperty("--honey-origin-x",`${Math.ceil(n)}px`),this.plane.style.setProperty("--honey-origin-y",`${Math.ceil(r)}px`),this.growthIntent){this.updatePlaneTransform(),this.scheduleGrowthFit();return}this.clampCamera(),this.updatePlaneTransform()}}stageSize(){return this.stage?{width:Math.max(1,this.stage.clientWidth||window.innerWidth),height:Math.max(1,this.stage.clientHeight||window.innerHeight)}:{width:Math.max(1,window.innerWidth),height:Math.max(1,window.innerHeight)}}visibleStageRect(){let e=this.stageSize(),t={left:0,top:0,right:e.width,bottom:e.height,width:e.width,height:e.height},i=this.stage?.getBoundingClientRect?.(),s=globalThis.window?.visualViewport;if(!i||!s)return t;let o=Number(s.offsetLeft)||0,n=Number(s.offsetTop)||0,r=Math.max(0,o-i.left),h=Math.max(0,n-i.top),a=Math.min(e.width,o+(Number(s.width)||e.width)-i.left),l=Math.min(e.height,n+(Number(s.height)||e.height)-i.top);return a-r<1||l-h<1?t:{left:r,top:h,right:a,bottom:l,width:a-r,height:l-h}}worldToStage(e,t){return{x:this.stageSize().width/2+Number(e)*this.zoom+this.cameraX,y:(this.world.originY+Number(t))*this.zoom+this.cameraY}}stageToWorld(e,t){let i=this.stageSize();return{x:(Number(e)-i.width/2-this.cameraX)/this.zoom,y:(Number(t)-this.cameraY)/this.zoom-this.world.originY}}contentExtent(){let e=1/0,t=-1/0,i=1/0,s=-1/0;for(let n of this.cells.values()){let r=N(n.q,n.r,this.hexRadius);r.x<e&&(e=r.x),r.x>t&&(t=r.x),r.y<i&&(i=r.y),r.y>s&&(s=r.y)}Number.isFinite(e)||(e=-this.hexRadius,t=this.hexRadius,i=-this.hexRadius,s=this.hexRadius);let o=this.hexRadius*te*.5;return{minX:Math.min(e,0)-o,maxX:Math.max(t,0)+o,minY:Math.min(i,0)-this.hexRadius,maxY:Math.max(s,0)+this.hexRadius}}initialPhoneExtent(){let e=0,t=0,i=0,s=0;for(let n of this.cells.values()){if(W(n.q,n.r)>1)continue;let r=N(n.q,n.r,this.hexRadius);e=Math.min(e,r.x),t=Math.max(t,r.x),i=Math.min(i,r.y),s=Math.max(s,r.y)}let o=this.hexRadius*te*.5;return{minX:e-o,maxX:t+o,minY:i-this.hexRadius,maxY:s+this.hexRadius}}cameraBounds(){return{minX:-this.world.halfWidth,maxX:this.world.halfWidth,minY:-this.world.halfHeight,maxY:this.world.halfHeight}}zoomToFit(e){let t=this.stageSize();if(t.width<2||t.height<2)return this.zoom;let i=28,s=Math.max(1,e.maxX-e.minX+i*2),o=Math.max(1,e.maxY-e.minY+i*2);return F(Math.min(t.width/s,t.height/o),C.minZoom,C.maxZoom)}fitZoom(){return this.zoomToFit(this.contentExtent())}zoomFloor(){let e=this.zoomToFit({minX:-this.world.halfWidth,maxX:this.world.halfWidth,minY:-this.world.halfHeight,maxY:this.world.halfHeight});return F(Math.min(e,1),C.minZoom,C.maxZoom)}clampZoom(e){let t=Number(e);return Number.isFinite(t)?F(t,this.zoomFloor(),C.maxZoom):this.zoom}cameraForFocus(e,t,i=this.zoom){let s=this.stageSize();return{x:-Number(e)*i,y:s.height/2-(this.world.originY+Number(t))*i}}cameraFocus(e=this.zoom){let t=this.stageSize();return{x:-this.cameraX/e,y:(t.height/2-this.cameraY)/e-this.world.originY}}clampCamera(e=this.zoom){let t=this.stageSize(),i=this.cameraBounds(),s=this.contentExtent(),o=this.cameraFocus(e),n=this.hexRadius*te*.75,r=this.hexRadius*1.5*.75,h=t.width/2/e,a=t.height/2/e,l=(y,b,E,k,I,p)=>E-b<=k*2?F(p,b,E):F(y,b+k-I,E-k+I),c=l(Number.isFinite(o.x)?o.x:0,i.minX,i.maxX,h,n,(s.minX+s.maxX)/2),u=l(Number.isFinite(o.y)?o.y:0,i.minY,i.maxY,a,r,(s.minY+s.maxY)/2),m=this.cameraForFocus(c,u,e);return this.cameraX=m.x,this.cameraY=m.y,{x:this.cameraX,y:this.cameraY}}clampCameraX(){return this.clampCamera().x}detailTierFor(e=this.zoom){return(re.find(t=>e>=t.minZoom)||re[re.length-1]).id}updatePlaneTransform(){if(!this.plane)return;this.plane.style.transform=`translate3d(${this.cameraX}px, ${this.cameraY}px, 0) scale(${this.zoom})`,this.zoomOutput&&(this.zoomOutput.textContent=`${Math.round(this.zoom*100)}%`);let e=this.detailTierFor();e!==this.detailTier&&(this.detailTier=e,this.wall?.setAttribute?.("data-wall-detail",e))}visibleCoordinates(){if(!this.stage||!this.plane)return{qMin:-4,qMax:4,rMin:-4,rMax:4,originX:0};let e=this.stageSize(),t=this.stageToWorld(0,0),i=this.stageToWorld(e.width,e.height),s=[j(t.x,t.y,this.hexRadius),j(i.x,t.y,this.hexRadius),j(t.x,i.y,this.hexRadius),j(i.x,i.y,this.hexRadius)],o=F(Math.round(3/Math.max(this.zoom,.05)),3,16);return{qMin:F(Math.min(...s.map(n=>n.q))-o,-this.bounds.radius,this.bounds.radius),qMax:F(Math.max(...s.map(n=>n.q))+o,-this.bounds.radius,this.bounds.radius),rMin:F(Math.min(...s.map(n=>n.r))-o,-this.bounds.radius,this.bounds.radius),rMax:F(Math.max(...s.map(n=>n.r))+o,-this.bounds.radius,this.bounds.radius),originX:this.world.originX}}chunksForVisibleRegion(){let e=this.visibleCoordinates(),t=this.stageToWorld(this.stageSize().width/2,this.stageSize().height/2),i=j(t.x,t.y,this.hexRadius),s=new Map,o=[];for(let r=Math.floor(e.qMin/C.chunkSize)*C.chunkSize;r<=e.qMax;r+=C.chunkSize)for(let h=Math.floor(e.rMin/C.chunkSize)*C.chunkSize;h<=e.rMax;h+=C.chunkSize){let a=O(r,h);s.has(a.key)||(s.set(a.key,a),o.push(a))}if(o.length<=Se)return s;let n=r=>W((r.qMin+r.qMax)/2,(r.rMin+r.rMax)/2,i.q,i.r);return o.sort((r,h)=>n(r)-n(h)),new Map(o.slice(0,Se).map(r=>[r.key,r]))}pendingWork(){let e=[];return this.growthFitFrame&&e.push("growthFitFrame"),this.renderFrame&&e.push("renderFrame"),this.momentumFrame&&e.push("momentumFrame"),this.focusFrame&&e.push("focusFrame"),this.announceFrame&&e.push("announceFrame"),this.glideTimer&&e.push("glideTimer"),this.eventTimer&&e.push("eventTimer"),this.eventRetryTimer&&e.push("eventRetryTimer"),this.listReconcileTimer&&e.push("listReconcileTimer"),this.viewportRefreshDirty&&e.push("viewportRefreshDirty"),this.viewportRefreshPromise&&e.push("viewportRefreshPromise"),this.realtimeDrainPromise&&e.push("realtimeDrainPromise"),e}async refreshVisible(e=!1){if(!this.active||this.mode!=="wall")return!1;if(this.viewportRefreshDirty=!0,this.viewportRefreshForce=this.viewportRefreshForce||!!e,this.viewportRefreshPromise)return this.viewportRefreshPromise;let i=(async()=>{let s=!1,o=0;for(;this.viewportRefreshDirty&&o<2&&this.active&&this.mode==="wall";){let n=this.viewportRefreshForce;this.viewportRefreshDirty=!1,this.viewportRefreshForce=!1,s=await(typeof this.performVisibleRefresh=="function"?this.performVisibleRefresh:d.prototype.performVisibleRefresh).call(this,n,0),o+=1}return s})().finally(()=>{this.viewportRefreshPromise===i&&(this.viewportRefreshPromise=null),this.viewportRefreshDirty&&this.active&&this.mode==="wall"&&this.scheduleViewport()});return this.viewportRefreshPromise=i,i}async performVisibleRefresh(e=!1,t=0){if(!this.active||this.mode!=="wall")return!1;let i=this.identityGeneration;if(await this.refreshBounds(),!this.active||this.mode!=="wall"||i!==this.identityGeneration)return!1;let s=Number(this.bounds.revision)||0;this.hasUnaccountedPublicRevision(s,"wall")&&this.invalidatePublicProjectionCache({resetConversation:!1});let o=this.publicCacheGeneration,n=this.chunksForVisibleRegion();this.visibleChunkKeys=new Set(n.keys());let r=await Promise.all([...n.values()].map(a=>this.loadChunk(a,e,s)));return!this.active||this.mode!=="wall"||i!==this.identityGeneration?!1:o!==this.publicCacheGeneration?t<1?this.performVisibleRefresh(!0,t+1):!1:r.every(a=>a?.ok&&Number(a.revision)===s)?(this.wallWindowRevision=Math.max(Number(this.wallWindowRevision)||0,s),this.wall?.setAttribute?.("aria-busy","false"),this.render(),!0):!1}loadChunk(e,t=!1,i=null){let s=Number.isSafeInteger(Number(i))?Number(i):Number(this.bounds.revision)||0;if(!t&&this.loadedChunks.has(e.key))return Promise.resolve({ok:!0,revision:s,cached:!0});if(this.inflightChunks.has(e.key))return t&&this.dirtyChunks.add(e.key),this.inflightChunks.get(e.key);let o,n=this.identityGeneration,r=this.publicCacheGeneration;return o=this.backend.wallRegion({...e,limit:500}).then(a=>{if(!this.mounted||n!==this.identityGeneration||r!==this.publicCacheGeneration)return{ok:!1,stale:!0};if(!a||!Array.isArray(a.cells)||!a.bounds||!Number.isSafeInteger(Number(a.bounds.revision)))throw new Error("The wall region was incomplete.");let l=Number(a.bounds.revision),c=this.viewerProjectionAdvanced(a.bounds);if(!this.applyAuthoritativeBounds(a.bounds))throw new Error("This wall region returned an older snapshot.");if(c&&this.hasPublicProjection())return this.invalidatePublicProjectionCache({resetConversation:!1}),{ok:!1,advanced:!0,viewerAdvanced:!0,revision:l};if(l<s)throw new Error("This wall region was behind the requested snapshot.");if(l>s)return this.invalidatePublicProjectionCache({resetConversation:!1}),{ok:!1,advanced:!0,revision:l};for(let u of a.cells)this.mergeCell(u);if(Array.isArray(a.conversations))for(let u of a.conversations)u&&u.id&&this.conversations.set(u.id,u);return this.loadedChunks.add(e.key),this.chunkAccess.set(e.key,Date.now()),this.lastGoodAt=Date.now(),this.pruneChunkCache(),{ok:!0,revision:l}}).catch(a=>!this.mounted||n!==this.identityGeneration||r!==this.publicCacheGeneration?{ok:!1,stale:!0}:(this.dataStale=!0,this.setConnectionState(navigator.onLine?"stale":"offline"),this.loadedChunks.has(e.key)||this.announce(`Could not load this part of the wall: ${a.message}`),{ok:!1,error:a})).finally(()=>{this.inflightChunks.get(e.key)===o&&this.inflightChunks.delete(e.key)}).then(a=>n===this.identityGeneration&&r===this.publicCacheGeneration&&this.dirtyChunks.delete(e.key)&&this.mounted?this.loadChunk(e,!0,s):a),this.inflightChunks.set(e.key,o),o}async hydratePlacement(e,t){let i=Number(e),s=Number(t);if(!M(i,s))return{ok:!1,code:"out_of_bounds",choices:[]};let o=this.identityGeneration,n=this.publicCacheGeneration;try{let r=await this.backend.wallRegion({qMin:F(i-1,-C.maxRadius,C.maxRadius),qMax:F(i+1,-C.maxRadius,C.maxRadius),rMin:F(s-1,-C.maxRadius,C.maxRadius),rMax:F(s+1,-C.maxRadius,C.maxRadius),limit:16});if(o!==this.identityGeneration)return{ok:!1,code:"identity_changed",choices:[]};if(n!==this.publicCacheGeneration)return{ok:!1,code:"wall_changed",choices:[]};if(!r||!Array.isArray(r.cells)||!r.bounds||!Number.isSafeInteger(Number(r.bounds.revision)))throw new Error("The wall did not return a complete placement check.");let h=Number(r.bounds.revision),a=this.viewerProjectionAdvanced(r.bounds);if(!this.applyAuthoritativeBounds(r.bounds))return{ok:!1,code:"wall_changed",choices:[]};if(a&&this.hasPublicProjection()){let l=this.captureProjectionRebuild();return this.invalidatePublicProjectionCache({resetConversation:!1}),this.rebuildPublicProjection(l),{ok:!1,code:"wall_changed",choices:[]}}if(this.hasUnaccountedPublicRevision(h)){let l=this.captureProjectionRebuild();return this.invalidatePublicProjectionCache({resetConversation:!1}),this.rebuildPublicProjection(l),{ok:!1,code:"wall_changed",choices:[]}}for(let l of r.cells)this.mergeCell(l);if(Array.isArray(r.conversations))for(let l of r.conversations)l&&l.id&&this.conversations.set(l.id,l);return this.lastGoodAt=Date.now(),this.dataStale=!1,this.render(),M(i,s,this.bounds.radius)?{ok:!0,occupied:this.cells.get(v(i,s))||null,choices:ae(this.cells,i,s,this.conversations),groups:Y(this.cells,i,s,this.conversations)}:{ok:!1,code:"out_of_bounds",choices:[]}}catch(r){return this.dataStale=!0,this.setConnectionState(navigator.onLine?"stale":"offline"),{ok:!1,code:"unavailable",choices:[],error:r}}}mergeCell(e,t={}){let i=Number(e&&e.q),s=Number(e&&e.r);if(!e||typeof e.id!="string"||!M(i,s))return null;let o={...e,q:i,r:s,seq:Number(e.seq)||0,version:Number(e.version)||1,contentVersion:Number(e.contentVersion)||1},n=this.cellsById.get(o.id);if(n&&o.version===n.version&&o.contentVersion===n.contentVersion&&(o.viewerReported=!!(n.viewerReported||o.viewerReported),o.viewerHidden=!!(n.viewerHidden||o.viewerHidden),o.viewerHidden&&(o.body=null)),n&&(o.version<n.version||o.version===n.version&&o.contentVersion<n.contentVersion))return n;let h=!n||["version","contentVersion","status","body","author","membership","replyToId","conversationId","viewerReported","viewerHidden","isMine"].some(u=>n[u]!==o[u]),a=!!(n&&n.contentVersion!==o.contentVersion),l=n||o;n&&Object.assign(l,o),this.cells.set(v(i,s),l),this.cellsById.set(l.id,l),this.cellChunks.set(l.id,O(i,s).key);let c=this.listCells.findIndex(u=>u.id===l.id);if(c>=0&&(this.listCells[c]=l),this.readerCell?.id===l.id){let u=this.root.querySelector("[data-wall-report-form]"),m=this.root.querySelector("[data-wall-operator-form]"),y=!!(u&&!u.hidden),b=!!(m&&!m.hidden),E=y&&!a&&l.status==="visible"&&!l.isMine&&!l.viewerReported,k=b&&!a&&l.status==="visible"&&this.operator,I=this.readerBusy||E||k,p=(y||b)&&!I;a&&(this.reportRequest=null),this.readerCell=l,h&&(this.reader?.open||this.reader?.hasAttribute("open"))&&(this.paintReaderCell(l,{preserveForms:I}),p&&this.toast("That comb changed, so the open review form was closed. Review the current version before acting."))}return t.renderList!==!1&&h&&c>=0&&this.mode==="list"&&this.mounted&&this.renderList(),l}pruneChunkCache(){let e=new Set([this.readerCell?.id,this.composeState?.cellId,this.composeState?.replyToId,...this.listCells.map(i=>i.id)].filter(Boolean)),t=[...this.loadedChunks].filter(i=>!this.visibleChunkKeys.has(i)&&!this.inflightChunks.has(i)).sort((i,s)=>(this.chunkAccess.get(i)||0)-(this.chunkAccess.get(s)||0));for(;(this.loadedChunks.size>Le||this.cellsById.size>Be)&&t.length;){let i=t.shift();this.loadedChunks.delete(i),this.chunkAccess.delete(i);for(let[s,o]of this.cellChunks){if(o!==i||e.has(s))continue;let n=this.cellsById.get(s);n&&this.cells.get(v(n.q,n.r))?.id===s&&this.cells.delete(v(n.q,n.r)),this.cellsById.delete(s),this.cellChunks.delete(s)}}if(this.conversations.size>600){let i=new Set([...this.cellsById.values()].map(s=>s.conversationId));for(let s of this.conversations.keys()){if(this.conversations.size<=600)break;!i.has(s)&&s!==this.listConversationId&&this.conversations.delete(s)}}}scheduleViewport(){!this.active||this.renderFrame||(this.renderFrame=requestAnimationFrame(()=>{this.renderFrame=null,this.refreshVisible(!1)}))}queueRealtimeEvent(e){let t=Number(e?.revision),i=Number(e?.q),s=Number(e?.r),o=typeof e?.cellId=="string"?e.cellId:"";if(!Number.isSafeInteger(t)||t<1||!o||!M(i,s))return;let n=`${o}:${t}`;if(this.seenRealtimeEvents.has(n))return;this.seenRealtimeEvents.add(n),this.seenRealtimeEvents.size>512&&this.seenRealtimeEvents.delete(this.seenRealtimeEvents.values().next().value);let r={...e,cellId:o,revision:t,q:i,r:s,eventKey:n};if(this.pendingEvents.size>=128&&!this.pendingEvents.has(e.cellId)){let a=this.pendingEvents.keys().next().value;if(a){let l=this.pendingEvents.get(a);if(this.pendingEvents.delete(a),l?.eventKey&&this.seenRealtimeEvents.delete(l.eventKey),M(Number(l?.q),Number(l?.r))){let c=O(Number(l.q),Number(l.r));this.loadedChunks.delete(c.key),this.inflightChunks.has(c.key)&&this.dirtyChunks.add(c.key)}}}let h=this.pendingEvents.get(o);(!h||t>=h.revision)&&this.pendingEvents.set(o,r),!this.eventTimer&&(this.eventTimer=window.setTimeout(()=>{this.eventTimer=null;let a=[...this.pendingEvents.values()];this.pendingEvents.clear(),(typeof this.queueRealtimeDrain=="function"?this.queueRealtimeDrain:d.prototype.queueRealtimeDrain).call(this,a)},140))}queueRealtimeDrain(e){this.realtimeDrainQueue||(this.realtimeDrainQueue=new Map);for(let n of Array.isArray(e)?e:[]){if(!n?.eventKey||!n?.cellId)continue;let r=this.realtimeDrainQueue.get(n.cellId);(!r||Number(n.revision)>=Number(r.revision))&&this.realtimeDrainQueue.set(n.cellId,n)}if(this.realtimeDrainPromise||!this.realtimeDrainQueue.size)return this.realtimeDrainPromise;let t=this.activationGeneration,i=this.identityGeneration,s=async()=>{for(;this.realtimeDrainQueue.size&&this.isContextCurrent(t,i);){let n=[...this.realtimeDrainQueue.values()];this.realtimeDrainQueue.clear();for(let r of n)this.consumingEvents.set(r.eventKey,r);await this.consumeRealtimeEvents(n)}},o;return o=s().finally(()=>{this.realtimeDrainPromise===o&&(this.realtimeDrainPromise=null),this.realtimeDrainQueue.size&&this.active&&this.queueRealtimeDrain([])}),this.realtimeDrainPromise=o,o}scheduleRealtimeRetries(e,t){!this.retryEvents.size||this.eventRetryTimer||(this.eventRetryTimer=window.setTimeout(()=>{if(this.eventRetryTimer=null,this.isContextCurrent(e,t)){let i=[...this.retryEvents.values()];this.retryEvents.clear();for(let s of i)this.queueRealtimeEvent(s)}},600))}scheduleListReconciliation(e,t,i=!1){if(this.listReconcileTimer||this.mode!=="list"||!this.listReconcileEvents.size||!this.isContextCurrent(e,t))return;let s=new Set(this.listCells.map(h=>h?.id).filter(Boolean)),o=[...this.listReconcileEvents.values()].filter(h=>h.evicted||s.has(h.cellId)).slice(0,64);if(!o.length)return;let n=Math.max(...o.map(h=>Number(h.reconcileAttempts)||1)),r=i?0:Math.min(3e4,600*2**Math.min(6,Math.max(0,n-1)));this.listReconcileTimer=window.setTimeout(()=>{if(this.listReconcileTimer=null,!(!this.isContextCurrent(e,t)||this.mode!=="list"))for(let h of o){let a=this.listReconcileEvents.get(h.cellId);!a||a.revision!==h.revision||(this.seenRealtimeEvents.delete(h.eventKey),this.queueRealtimeEvent(h))}},r)}wakeListReconciliation(){!this.active||!this.mounted||this.mode!=="list"||!this.listReconcileEvents.size||(this.listReconcileTimer&&window.clearTimeout(this.listReconcileTimer),this.listReconcileTimer=null,this.scheduleListReconciliation(this.activationGeneration,this.identityGeneration,!0))}async consumeRealtimeEvents(e){let t=this.activationGeneration,i=this.identityGeneration,s=this.publicCacheGeneration,o=this.mode,n=this.listRequestGeneration,r=this.listConversationId,h=Number(this.listWindowRevision)||0,a=()=>this.isContextCurrent(t,i)&&s===this.publicCacheGeneration&&o===this.mode&&(o!=="list"||n===this.listRequestGeneration&&r===this.listConversationId),l=()=>{if(this.isContextCurrent(t,i))for(let c of e)this.seenRealtimeEvents.delete(c.eventKey),this.queueRealtimeEvent(c)};try{if(await this.refreshBounds(),!this.isContextCurrent(t,i))return;if(!a()){l();return}let c=this.bounds.revision,u=e.filter(f=>f.revision>0&&f.revision<=c);for(let f of e)if(f.revision>c&&(this.seenRealtimeEvents.delete(f.eventKey),(Number(f.retries)||0)<3)){let w={...f,retries:(Number(f.retries)||0)+1},x=this.retryEvents.get(f.cellId);(!x||w.revision>=x.revision)&&this.retryEvents.set(f.cellId,w)}if(this.scheduleRealtimeRetries(t,i),!u.length)return;let m=new Set,y=new Set;for(let f of u){let w=O(f.q,f.r);this.loadedChunks.has(w.key)&&m.add(w.key),this.inflightChunks.has(w.key)&&y.add(w.key),this.loadedChunks.delete(w.key),this.inflightChunks.has(w.key)&&this.dirtyChunks.add(w.key)}if(o==="list"){let f=c-h,w=new Set(u.map(P=>P.revision).filter(P=>P>h&&P<=c)),x=f>=0&&w.size===f;if((this.listCells.length||this.cells?.size||this.conversations?.size||this.readerCell)&&!x){let P=this.captureAccessibleListView(!0);if(this.invalidatePublicProjectionCache({resetConversation:!1}),await this.refreshList(!0,P),!this.isContextCurrent(t,i)||this.mode!=="list"||this.listConversationId!==r)return;this.announce("The Wall list was rebuilt after catching up with missed changes.");return}let D=new Set(this.listCells.map(P=>P?.id).filter(Boolean)),$=u.filter(P=>D.has(P.cellId)||this.listReconcileEvents.get(P.cellId)?.evicted),he=this.captureAccessibleListView(!0);for(let P of u)P.conversationId&&this.conversations.delete(P.conversationId),this.evictPublicCellProjection(P.cellId);if(this.renderList(),this.restoreAccessibleListView(he,this.listRequestGeneration,this.listConversationId),$.length){for(let A of $){let B=this.listReconcileEvents.get(A.cellId);if(!B&&this.listReconcileEvents.size>=We){let V=this.captureAccessibleListView(!0);this.invalidatePublicProjectionCache({resetConversation:!1}),await this.refreshList(!0,V),this.isContextCurrent(t,i)&&this.mode==="list"&&this.listConversationId===r&&this.announce("The Wall list was rebuilt after a large batch of changes.");return}(!B||A.revision>=B.revision)&&this.listReconcileEvents.set(A.cellId,{...A,reconcileAttempts:Math.max(1,Number(B?.reconcileAttempts)||Number(A.reconcileAttempts)||1)})}if(!a()){l();return}for(let A of $){let B=this.listReconcileEvents.get(A.cellId);B&&this.listReconcileEvents.set(A.cellId,{...B,evicted:!0})}let P=await Promise.allSettled($.map(A=>this.backend.wallCell(A.cellId)));if(!a()){l();return}if(P.some(A=>A.status==="fulfilled"&&Number.isSafeInteger(Number(A.value?.bounds?.revision))&&(Number(A.value.bounds.revision)>c||this.viewerProjectionAdvanced(A.value.bounds)))){this.invalidatePublicProjectionCache({resetConversation:!1}),await this.refreshList(!0,he),this.isContextCurrent(t,i)&&this.mode==="list"&&this.listConversationId===r&&this.announce("The Wall list was rebuilt after a newer change arrived mid-refresh.");return}let we=[];for(let A=0;A<P.length;A+=1){let B=P[A],V=$[A],z=B.status==="fulfilled"?B.value:null;if(!z?.cell||!z?.bounds||Number(z.bounds.revision)!==c||!this.applyAuthoritativeBounds(z.bounds)){this.seenRealtimeEvents.delete(V.eventKey);let be=this.listReconcileEvents.get(V.cellId)||V;this.listReconcileEvents.set(V.cellId,{...be,reconcileAttempts:Math.min(20,(Number(be.reconcileAttempts)||1)+1)});continue}z?.conversation?.id&&this.conversations.set(z.conversation.id,z.conversation);let ye=this.mergeCell(z.cell,{renderList:!1});ye&&we.push(ye);let ve=this.listReconcileEvents.get(V.cellId);(!ve||ve.revision<=V.revision)&&this.listReconcileEvents.delete(V.cellId)}this.listCells=fe(this.listCells,we,this.listConversationId),this.scheduleListReconciliation(t,i),x&&(this.listWindowRevision=Math.max(this.listWindowRevision,c))}else x&&(this.listWindowRevision=Math.max(this.listWindowRevision,c));if(await this.refreshList(!0,he),!this.isContextCurrent(t,i)||this.mode!=="list"||this.listConversationId!==r)return;this.scheduleListReconciliation(t,i),this.announce(`${u.length} wall ${u.length===1?"comb has":"combs have"} changed.`);return}let b=Number(this.wallWindowRevision)||0,E=c-b,k=new Set(u.map(f=>f.revision).filter(f=>f>b&&f<=c)),I=E>=0&&k.size===E;if(this.hasPublicProjection("wall")&&!I){this.invalidatePublicProjectionCache({resetConversation:!1}),await this.refreshVisible(!0),this.isContextCurrent(t,i)&&this.mode==="wall"&&this.announce("The Wall was rebuilt after catching up with missed changes.");return}let p=u.filter(f=>f.revision>b);if(!p.length)return;if(!this.hasPublicProjection("wall")){await this.refreshVisible(!0);return}let q=new Map,T=this.chunksForVisibleRegion(),S=!1;for(let f of p){let w=O(f.q,f.r);q.set(w.key,w),f.conversationId&&(this.conversations.delete(f.conversationId),this.readerCell?.conversationId===f.conversationId&&(S=!0))}if(S&&this.closeReaderForProjectionRefresh(),[...q.keys()].some(f=>y.has(f))){this.invalidatePublicProjectionCache({resetConversation:!1}),await this.refreshVisible(!0);return}let R=[];for(let[f,w]of q){let x=[...this.cellChunks.values()].some(D=>D===f);this.evictWallChunkProjection(f,{preserveGeometry:!0}),(m.has(f)||x||T.has(f))&&R.push(w)}let G=await Promise.all(R.map(f=>this.loadChunk(f,!0,c)));if(!a()){this.isContextCurrent(t,i)&&await this.refreshVisible(!0);return}if(!G.every(f=>f?.ok&&Number(f.revision)===c)){this.invalidatePublicProjectionCache({resetConversation:!1}),await this.refreshVisible(!0);return}this.wallWindowRevision=Math.max(b,c),this.wall?.setAttribute?.("aria-busy","false"),this.render(),this.announce(`${u.length} wall ${u.length===1?"comb has":"combs have"} changed.`)}finally{for(let c of e)this.consumingEvents.delete(c.eventKey)}}render(){if(!this.mounted||this.mode!=="wall")return;let e=this.visibleCoordinates(),t=new Set;for(let[i,s]of this.cells){if(s.q<e.qMin||s.q>e.qMax||s.r<e.rMin||s.r>e.rMax||W(s.q,s.r)>this.bounds.radius)continue;t.add(i);let o=this.nodes.get(i);o||(o=document.createElement("button"),o.type="button",o.className="honey-comb",o.dataset.cellKey=i,o.innerHTML='<span class="honey-comb-inner"><span class="honey-comb-author"></span><span class="honey-comb-body"></span><span class="honey-comb-foot"></span></span>',this.cellLayer.append(o),this.nodes.set(i,o)),this.paintCellNode(o,s)}for(let[i,s]of this.nodes)t.has(i)||(s.remove(),this.nodes.delete(i));this.renderConnections(t),this.growthIntent&&this.renderGrowthSlots(),this.updateTarget(),this.updateNewCount()}paintCellNode(e,t){let i=N(t.q,t.r,this.hexRadius);e.style.left=`calc(var(--honey-origin-x) + ${i.x}px)`,e.style.top=`calc(var(--honey-origin-y) + ${i.y}px)`,e.style.setProperty("--thread-hue",String(oe(t.conversationId))),e.dataset.threadPattern=String(Ie(t.conversationId)),e.dataset.status=t.status,e.dataset.conversationId=t.conversationId,e.id=`honey-cell-${t.id}`,e.tabIndex=-1,e.disabled=!1,delete e.dataset.placeholder,e.classList.remove("is-refreshing"),e.classList.toggle("is-branch-origin",t.origin?.kind==="branch"),e.classList.toggle("is-meet-origin",t.origin?.kind==="meet"),e.classList.toggle("is-unseen",!this.seen.has(t.id)),e.classList.toggle("is-mine",!!t.isMine),e.classList.toggle("is-viewer-hidden",!!t.viewerHidden);let s=e.querySelector(".honey-comb-author"),o=e.querySelector(".honey-comb-body"),n=e.querySelector(".honey-comb-foot");g(s,t.author||(t.status==="quarantined"?"Under review":"Open space kept")),g(o,ne(t)),g(n,`${ue(t.createdAt)} \xB7 ${t.membership==="alumni"?"DHG":t.membership==="guest"?"Guest":"Hive"}`);let r=`${s.textContent}: ${ne(t)}`;e.getAttribute("aria-label")!==r&&e.setAttribute("aria-label",r)}renderConnections(e){let t=new Set,i=(s,o,n,r="growth")=>{let h=N(o.q,o.r,this.hexRadius),a=N(n.q,n.r,this.hexRadius),l=a.x-h.x,c=a.y-h.y,u=this.connectionNodes.get(s);u||(u=document.createElement("span"),u.className="honey-link",this.connectionLayer.append(u),this.connectionNodes.set(s,u)),t.add(s),u.classList.remove("is-refreshing"),u.dataset.relation=r,u.style.left=`calc(var(--honey-origin-x) + ${h.x}px)`,u.style.top=`calc(var(--honey-origin-y) + ${h.y}px)`,u.style.width=`${Math.hypot(l,c)}px`,u.style.transform=`rotate(${Math.atan2(c,l)}rad)`,u.style.setProperty("--thread-hue",String(oe(n.conversationId))),u.style.setProperty("--source-hue",String(oe(o.conversationId)))};for(let s of e){let o=this.cells.get(s);if(o){if(o.growthParentId){let n=this.cellsById.get(o.growthParentId);n&&e.has(v(n.q,n.r))&&i(`growth:${o.id}:${n.id}`,n,o,"growth")}for(let n of o.origin?.anchors||[]){let r=this.cellsById.get(n.cellId);!r||!e.has(v(r.q,r.r))||i(`origin:${o.id}:${r.id}`,r,o,o.origin.kind)}}}for(let[s,o]of this.connectionNodes)t.has(s)||(o.remove(),this.connectionNodes.delete(s))}updateTarget(){if(!this.target)return;if(this.selectedCellKey){let i=this.nodes.get(this.selectedCellKey);i?.classList.remove("is-selected"),i?.removeAttribute("aria-current")}let e=N(this.selected.q,this.selected.r,this.hexRadius);this.target.style.left=`calc(var(--honey-origin-x) + ${e.x}px)`,this.target.style.top=`calc(var(--honey-origin-y) + ${e.y}px)`;let t=this.cells.get(v(this.selected.q,this.selected.r));if(this.target.classList.toggle("is-occupied",!!t),this.target.querySelector("span").textContent=t?"\u2022":"+",t){this.selectedCellKey=v(t.q,t.r);let i=this.nodes.get(this.selectedCellKey);i?(i.classList.add("is-selected"),i.setAttribute("aria-current","true"),this.stage?.setAttribute("aria-activedescendant",i.id||`honey-cell-${t.id}`)):this.stage?.removeAttribute("aria-activedescendant")}else this.selectedCellKey=null,this.stage?.removeAttribute("aria-activedescendant")}handleClick(e){let t=e.target.closest("[data-wall-action]");if(t){this.runToolbarAction(t.dataset.wallAction);return}let i=e.target.closest("[data-wall-close]");if(i){let c=i.dataset.wallClose==="compose"?this.compose:i.dataset.wallClose==="reader"?this.reader:this.watch;this.closeDialog(c);return}let s=e.target.closest("[data-wall-watch-case]");if(s){if(this.watchBusy)return;this.openWatchCase(s.dataset.wallWatchCase,Number(s.dataset.wallWatchVersion));return}if(e.target.closest("[data-wall-watch-more]")){this.watchBusy||this.loadWatchQueue(!1,this.watchGeneration);return}let o=e.target.closest("[data-wall-watch-action]");if(o){this.moderateWatchCase(o.dataset.wallWatchAction);return}let n=e.target.closest("[data-wall-reader-action]");if(n){if(this.readerBusy)return;this.runReaderAction(n.dataset.wallReaderAction);return}let r=e.target.closest("[data-wall-list-cell]");if(r){this.openListCell(r.dataset.wallListCell,r);return}let h=e.target.closest("[data-wall-list-conversation]");if(h){this.openListConversation(h.dataset.wallListConversation);return}let a=e.target.closest("[data-wall-growth-key]");if(a){let[c,u]=String(a.dataset.wallGrowthKey||"").split(":").map(Number);M(c,u,this.bounds.radius)&&this.chooseGrowthCoordinate({q:c,r:u},a);return}let l=e.target.closest("[data-cell-key]");if(l){if(Date.now()<=this.suppressCellClickUntil){e.preventDefault(),e.stopPropagation(),this.suppressCellClickUntil=0;return}let c=this.cells.get(l.dataset.cellKey);c&&(this.selected={q:c.q,r:c.r},this.updateTarget(),this.openReader(c))}}runToolbarAction(e){if(e==="add"){if(this.bounds.readOnly){this.toast("The Wall is open to read while Hive Watch is verified. New combs will open soon.");return}let t=this.cells.has(v(this.selected.q,this.selected.r))?this.findNearestOpen(this.selected):this.selected;if(!t){this.toast("No open comb is loaded yet. Center the Wall or try again after it grows.");return}this.selected=t,this.updateTarget(),this.ensureCoordinateVisible(t.q,t.r),this.preparePlacement(t)}else e==="new"?this.findNew():e==="mine"?this.findMine():e==="center"?this.centerWall(!0):e==="fit"?this.fitWall(!0):e==="zoom-in"?(this.applyCameraMotion("smooth"),this.setZoom(this.zoom*ie,null,{announce:!0})):e==="zoom-out"?(this.applyCameraMotion("smooth"),this.setZoom(this.zoom/ie,null,{announce:!0})):e==="mode"?this.setMode(this.mode==="wall"?"list":"wall"):e==="resume"?this.resumeCurrentDraft():e==="load-more"?this.refreshList(!1):e==="list-all"?this.showAllListMessages():e==="watch"?this.openWatch():e==="cancel-growth"?this.cancelGrowthIntent():e==="nearest-growth"&&this.moveGrowthToNearestFrontier()}handleStageKey(e){if(ze(e.target))return;if(e.shiftKey&&["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key)){e.preventDefault();let i=De,s=e.key==="ArrowRight"?i:e.key==="ArrowLeft"?-i:0,o=e.key==="ArrowDown"?i:e.key==="ArrowUp"?-i:0;this.stopMomentum(),this.panBy(s,o);return}if(e.key==="+"||e.key==="="){e.preventDefault(),this.applyCameraMotion("smooth"),this.setZoom(this.zoom*ie,null,{announce:!0});return}if(e.key==="-"||e.key==="_"){e.preventDefault(),this.applyCameraMotion("smooth"),this.setZoom(this.zoom/ie,null,{announce:!0});return}if(e.key==="0"){e.preventDefault(),this.applyCameraMotion("smooth"),this.fitWall(!0);return}let t=null;if(e.key==="ArrowRight"?t=0:e.key==="ArrowUp"?t=2:e.key==="ArrowLeft"?t=3:e.key==="ArrowDown"?t=5:["e","9"].includes(e.key.toLowerCase())?t=1:["q","7"].includes(e.key.toLowerCase())?t=2:["a","4"].includes(e.key.toLowerCase())?t=3:["z","1"].includes(e.key.toLowerCase())?t=4:["c","3"].includes(e.key.toLowerCase())?t=5:["d","6"].includes(e.key.toLowerCase())&&(t=0),e.key==="Escape"&&this.growthIntent){e.preventDefault(),this.cancelGrowthIntent();return}if(t!=null){e.preventDefault();let[i,s]=me[t],o=this.growthIntent?.origin||this.selected,n={q:o.q+i,r:o.r+s};if(M(n.q,n.r,this.bounds.radius)){this.selected=n,this.updateTarget(),this.ensureCoordinateVisible(n.q,n.r);let r=this.growthSlots?.querySelector?.(`[data-wall-growth-key="${v(n.q,n.r)}"]`);this.growthIntent&&r&&!r.disabled&&r.focus({preventScroll:!0}),this.announce(`${ee[t]} comb${this.cells.has(v(n.q,n.r))?", occupied":", open"}.`)}}else if(e.key==="Home")e.preventDefault(),this.selected={q:0,r:0},this.updateTarget(),this.ensureCoordinateVisible(0,0),this.announce("Centered on comb 0, 0.");else if(e.key==="Enter"||e.key===" "){if(e.preventDefault(),this.growthIntent&&this.isGrowthCoordinate(this.selected)){this.chooseGrowthCoordinate(this.selected,e.target);return}let i=this.cells.get(v(this.selected.q,this.selected.r));i?this.openReader(i):this.preparePlacement(this.selected)}}handlePointerDown(e){if(e.button!==0||e.target.closest("[data-wall-growth-key]"))return;if(this.stopMomentum(),this.plane?.classList.remove("is-gliding"),this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.activePointers.size===2){this.beginPinch(),this.pointer=null;return}if(this.activePointers.size>2)return;let t=e.target.closest("[data-cell-key]");this.pointer={id:e.pointerId,startX:e.clientX,startY:e.clientY,lastX:e.clientX,lastY:e.clientY,lastAt:Date.now(),velocityX:0,velocityY:0,cameraX:this.cameraX,cameraY:this.cameraY,moved:!1,startedOnCell:!!t,startedCellKey:t?.dataset?.cellKey||null},this.stage.setPointerCapture?.(e.pointerId)}beginPinch(){let e=[...this.activePointers.values()];if(e.length<2)return;let t=this.stage.getBoundingClientRect(),i=(e[0].x+e[1].x)/2-t.left,s=(e[0].y+e[1].y)/2-t.top;this.plane?.classList.add("is-panning"),this.pinch={distance:Math.max(1,Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y)),zoom:this.zoom,midX:i,midY:s,world:this.stageToWorld(i,s),moved:!1}}updatePinch(){let e=[...this.activePointers.values()];if(!this.pinch||e.length<2)return;let t=this.stage.getBoundingClientRect(),i=(e[0].x+e[1].x)/2-t.left,s=(e[0].y+e[1].y)/2-t.top,n=Math.max(1,Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y))/this.pinch.distance;(Math.abs(n-1)>.01||Math.hypot(i-this.pinch.midX,s-this.pinch.midY)>4)&&(this.pinch.moved=!0);let r=this.stageSize();this.zoom=this.clampZoom(this.pinch.zoom*n),this.cameraX=i-r.width/2-this.pinch.world.x*this.zoom,this.cameraY=s-(this.world.originY+this.pinch.world.y)*this.zoom,this.clampCamera(),this.updatePlaneTransform(),this.scheduleViewport()}handlePointerMove(e){if(this.activePointers.has(e.pointerId)&&this.activePointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this.pinch){e.preventDefault(),this.updatePinch();return}if(!this.pointer||this.pointer.id!==e.pointerId){e.pointerType==="mouse"&&this.selectFromPoint(e.clientX,e.clientY,!1);return}let t=e.clientX-this.pointer.startX,i=e.clientY-this.pointer.startY;if(!this.pointer.moved&&Math.hypot(t,i)>8&&(this.pointer.moved=!0),!this.pointer.moved)return;e.preventDefault();let s=Date.now(),o=Math.max(1,s-this.pointer.lastAt);this.pointer.velocityX=(e.clientX-this.pointer.lastX)/o,this.pointer.velocityY=(e.clientY-this.pointer.lastY)/o,this.pointer.lastX=e.clientX,this.pointer.lastY=e.clientY,this.pointer.lastAt=s,this.plane.classList.add("is-panning"),this.cameraX=this.pointer.cameraX+t,this.cameraY=this.pointer.cameraY+i,this.clampCamera(),this.updatePlaneTransform(),this.updateTarget(),this.scheduleViewport()}handlePointerUp(e){if(this.activePointers.delete(e.pointerId),this.pinch){if(this.activePointers.size<2){let r=this.pinch.moved;this.pinch=null,this.plane?.classList.remove("is-panning"),r&&(this.suppressCellClickUntil=Date.now()+420);let[h]=[...this.activePointers.keys()];if(h!=null){let a=this.activePointers.get(h);this.pointer={id:h,startX:a.x,startY:a.y,lastX:a.x,lastY:a.y,lastAt:Date.now(),velocityX:0,velocityY:0,cameraX:this.cameraX,cameraY:this.cameraY,moved:!0,startedOnCell:!1,startedCellKey:null}}}return}if(!this.pointer||this.pointer.id!==e.pointerId)return;let t=this.pointer.moved,i=this.pointer.startedOnCell,s=this.pointer.startedCellKey,o=this.pointer.velocityX,n=this.pointer.velocityY;if(this.pointer=null,this.plane.classList.remove("is-panning"),t){i&&(this.suppressCellClickUntil=Date.now()+420),this.startMomentum(o,n);return}if(i&&s){let r=this.cells.get(s);r&&(this.selected={q:r.q,r:r.r},this.updateTarget(),this.suppressCellClickUntil=Date.now()+420,e.pointerType!=="mouse"&&(this.suppressBackdropClick={dialog:this.reader,until:Date.now()+420}),this.openReader(r,this.nodes.get(s)));return}if(!i){let r=this.selectFromPoint(e.clientX,e.clientY,!0);if(!r)return;let h=this.cells.get(v(r.q,r.r));h?this.openReader(h):this.preparePlacement(r)}}cancelPointerGesture(e=null){e?.pointerId!=null?this.activePointers.delete(e.pointerId):this.activePointers.clear(),this.pointer?.moved&&this.pointer.startedOnCell&&(this.suppressCellClickUntil=Date.now()+420),this.pointer=null,this.pinch=null,this.plane?.classList.remove("is-panning")}startMomentum(e,t){if(this.stopMomentum(),this.motionBehavior("smooth")!=="smooth")return;let i=Number(e)||0,s=Number(t)||0;if(Math.hypot(i,s)<.35)return;let o=()=>{if(this.momentumFrame=null,i*=.92,s*=.92,Math.hypot(i,s)<.02){this.scheduleViewport();return}let n=this.cameraX,r=this.cameraY;if(this.cameraX+=i*16,this.cameraY+=s*16,this.clampCamera(),this.updatePlaneTransform(),this.cameraX===n&&this.cameraY===r){this.scheduleViewport();return}this.scheduleViewport(),this.momentumFrame=requestAnimationFrame(o)};this.momentumFrame=requestAnimationFrame(o)}stopMomentum(){this.momentumFrame&&cancelAnimationFrame(this.momentumFrame),this.momentumFrame=null}handleWheel(e){if(this.mode!=="wall"||this.stage?.hidden)return;e.preventDefault(),this.stopMomentum();let t=this.stage.getBoundingClientRect();if(e.ctrlKey||e.metaKey){let s=Math.exp(-e.deltaY*.0022);this.setZoom(this.zoom*s,{x:e.clientX-t.left,y:e.clientY-t.top});return}let i=e.deltaMode===1?16:e.deltaMode===2?t.height:1;this.panBy(e.deltaX*i,e.deltaY*i)}handleStageFocus(e){if(this.mode!=="wall"||!this.plane)return;let t=e.target?.closest?.("[data-cell-key], [data-wall-growth-key]");if(!t)return;let i=t.dataset?.cellKey||t.dataset?.wallGrowthKey,[s,o]=String(i||"").split(":").map(Number);!Number.isFinite(s)||!Number.isFinite(o)||this.ensureCoordinateVisible(s,o,"auto")}handleDoubleClick(e){if(this.mode!=="wall"||e.target.closest("[data-wall-growth-key]"))return;e.preventDefault();let t=this.stage.getBoundingClientRect(),i={x:e.clientX-t.left,y:e.clientY-t.top},s=this.zoom>this.zoomFloor()*1.05?this.fitZoom():1;this.applyCameraMotion("smooth"),this.setZoom(s,i,{announce:!0})}selectFromPoint(e,t,i){let s=this.stage.getBoundingClientRect(),o=this.stageToWorld(e-s.left,t-s.top),n=j(o.x,o.y,this.hexRadius);return M(n.q,n.r,this.bounds.radius)?(this.selected=n,this.updateTarget(),i&&this.stage.focus({preventScroll:!0}),n):null}growthCoordinates(e=this.growthIntent?.origin){return e?_(e.q,e.r).map((t,i)=>({...t,direction:i,directionLabel:ee[i],available:M(t.q,t.r,this.bounds.radius)&&!this.cells.has(v(t.q,t.r))})):[]}isGrowthCoordinate(e){return this.growthCoordinates().some(t=>t.available&&t.q===Number(e?.q)&&t.r===Number(e?.r))}renderGrowthSlots(){if(!this.growthSlots||!this.growthTray)return;let e=this.growthIntent;if(!e){this.growthFitFrame&&cancelAnimationFrame(this.growthFitFrame),this.growthFitFrame=null,this.growthSlots.replaceChildren(),this.growthTray.hidden=!0;return}let t=this.growthCoordinates(e.origin),i=t.filter(a=>a.available),s=new Set;for(let a of t){let l=v(a.q,a.r);s.add(l);let c=this.growthSlots.querySelector(`[data-wall-growth-key="${l}"]`);c||(c=document.createElement("button"),c.type="button",c.className="honey-growth-slot",c.dataset.wallGrowthKey=l,this.growthSlots.append(c)),c.dataset.direction=String(a.direction),c.disabled=!a.available;let u=N(a.q,a.r,this.hexRadius);c.style.left=`calc(var(--honey-origin-x) + ${u.x}px)`,c.style.top=`calc(var(--honey-origin-y) + ${u.y}px)`,c.textContent=a.available?"+":"\xD7",c.setAttribute("aria-label",a.available?`${e.kind==="branch"?"Start a branch":"Reply"} ${a.directionLabel}`:`${a.directionLabel} is unavailable`)}for(let a of this.growthSlots.querySelectorAll("[data-wall-growth-key]"))s.has(a.dataset.wallGrowthKey)||a.remove();let o=e.origin.author||"this comb",n=i.length?`${i.length} open ${i.length===1?"place":"places"} around ${o}. Choose a glowing comb; Escape cancels.`:`${o} is surrounded. You can continue from the conversation's nearest open edge, or cancel.`;g(this.root.querySelector("[data-wall-growth-copy]"),n);let r=this.root.querySelector('[data-wall-action="nearest-growth"]');r.hidden=i.length>0,r.textContent=e.kind==="branch"?"Branch at nearest edge":"Continue at nearest edge",this.growthTray.hidden=!1,this.growthFitFrame&&cancelAnimationFrame(this.growthFitFrame),this.growthFitFrame=requestAnimationFrame(()=>{this.growthFitFrame=null,this.fitGrowthIntent()});let h=globalThis.document?.activeElement;h&&this.growthSlots.contains(h)&&h.disabled&&((this.growthSlots.querySelector("[data-wall-growth-key]:not(:disabled)")||(r.hidden?this.root.querySelector('[data-wall-action="cancel-growth"]'):r))?.focus?.({preventScroll:!0}),this.announce(i.length?"That comb was just filled. Focus moved to another open direction.":"That comb was just filled. This patch is now surrounded; choose its nearest open edge or cancel."))}beginGrowthIntent(e,t,i=null,s=null){if(!e?.id||!["reply","branch"].includes(t))return!1;if(this.bounds.readOnly)return this.toast("The Wall is open to read while Hive Watch is verified. New combs will open soon."),!1;this.growthIntent={kind:t,origin:e,originalOrigin:e,opener:i||this.nodes.get(v(e.q,e.r))||this.stage,focusAnchor:s||null,priorView:{zoom:this.zoom,cameraX:this.cameraX,cameraY:this.cameraY,viewportWidth:Number(window.visualViewport?.width)||window.innerWidth,viewportHeight:Number(window.visualViewport?.height)||window.innerHeight}},this.renderGrowthSlots(),this.fitGrowthIntent();let o=this.growthSlots.querySelector("[data-wall-growth-key]:not(:disabled)");if(o){let[n,r]=o.dataset.wallGrowthKey.split(":").map(Number);this.selected={q:n,r},this.updateTarget(),o.focus({preventScroll:!0})}else this.root.querySelector('[data-wall-action="nearest-growth"]')?.focus?.({preventScroll:!0});return this.announce(this.root.querySelector("[data-wall-growth-copy]")?.textContent||"Choose the next comb."),!0}cancelGrowthIntent(e={}){let t=this.growthIntent;t&&(this.growthIntent=null,this.renderGrowthSlots(),this.restoreGrowthView(t,null,{restoreScroll:e.restoreView!==!1}),e.announce!==!1&&this.announce("Branch selection canceled."),e.restoreFocus!==!1&&this.restoreWallFocus(t.opener,t.focusAnchor))}chooseGrowthCoordinate(e,t=null){let i=this.growthIntent;if(!i||!this.isGrowthCoordinate(e))return this.announce("That place is no longer open. Choose another glowing comb."),this.renderGrowthSlots(),!1;let s=this.cellsById.get(i.origin.id)||i.origin,o=i.kind==="branch"?{intent:"branch",anchorCellIds:[s.id],mode:"branch",choiceExplicit:!0}:{intent:"join",conversationId:s.conversationId,replyToId:i.kind==="reply"?s.id:null,anchorCellIds:[s.id],mode:i.kind==="reply"?"reply":"join",choiceExplicit:!0},n=i.opener||t||this.stage;return this.growthIntent=null,this.renderGrowthSlots(),this.restoreGrowthView(i,e),this.selected={q:e.q,r:e.r},this.updateTarget(),this.preparePlacement(e,{...o,opener:n}),!0}findConversationFrontierChoice(e,t={q:0,r:0}){if(!e)return null;let i=[...this.cells.values()].filter(s=>s.conversationId===e&&s.status==="visible").sort((s,o)=>W(s.q,s.r,t.q,t.r)-W(o.q,o.r,t.q,t.r));for(let s of i){let o=_(s.q,s.r).find(n=>M(n.q,n.r,this.bounds.radius)&&!this.cells.has(v(n.q,n.r)));if(o)return{anchor:s,coordinate:o}}return null}moveGrowthToNearestFrontier(){let e=this.growthIntent;if(!e)return;let t=this.findConversationFrontierChoice(e.origin.conversationId,e.origin);if(!t){this.toast("Load more of this conversation to find an open edge.");return}e.origin=t.anchor,e.kind==="reply"&&(e.kind="continue"),this.renderGrowthSlots(),this.fitGrowthIntent(),(this.growthSlots.querySelector(`[data-wall-growth-key="${v(t.coordinate.q,t.coordinate.r)}"]`)||this.growthSlots.querySelector("[data-wall-growth-key]:not(:disabled)"))?.focus?.({preventScroll:!0}),this.announce(`The nearest open edge is beside ${t.anchor.author||"this conversation"}. Choose its glowing comb.`)}fitGrowthIntent(){let e=this.growthIntent;if(!e||!this.stage||!this.plane||!this.growthTray)return;let t=[...this.growthSlots.querySelectorAll("[data-wall-growth-key]")];if(!t.length)return;let i=this.stageSize(),s=10,o=p=>p.right-p.left>24&&p.bottom-p.top>24,n=()=>{let p=this.stage.getBoundingClientRect(),q=this.growthTray.getBoundingClientRect(),T=this.root.querySelector(".honey-toolbar")?.getBoundingClientRect(),S=globalThis.window?.visualViewport,R=Number(S?.offsetLeft)||0,G=Number(S?.offsetTop)||0,f=R+(Number(S?.width)||window.innerWidth),w=G+(Number(S?.height)||window.innerHeight),x=T&&T.bottom>G&&T.top<w,D=q.height>0&&q.top<w,$={left:Math.max(s,R-p.left+s),right:Math.min(i.width-s,f-p.left-s),top:Math.max(s,G-p.top+s,x?T.bottom-p.top+s:0),bottom:Math.min(i.height-s,w-p.top-s,D?q.top-p.top-s:1/0)};return{stageRect:p,box:o($)?$:{left:s,right:i.width-s,top:s,bottom:i.height-s}}},{stageRect:r,box:h}=n();if(!o(h))return;this.lastGrowthTrayHeight=this.growthTray.getBoundingClientRect().height;let a=N(e.origin.q,e.origin.r,this.hexRadius),l=1/0,c=-1/0,u=1/0,m=-1/0;for(let p of t){let[q,T]=p.dataset.wallGrowthKey.split(":").map(Number),S=N(q,T,this.hexRadius),R=p.offsetWidth/2+7,G=p.offsetHeight/2+7;l=Math.min(l,S.x-a.x-R),c=Math.max(c,S.x-a.x+R),u=Math.min(u,S.y-a.y-G),m=Math.max(m,S.y-a.y+G)}let y=Math.max(1,c-l),b=Math.max(1,m-u),E=(l+c)/2,k=(u+m)/2,I=Math.min(e.priorView?.zoom||this.zoom,(h.right-h.left)/y,(h.bottom-h.top)/b);this.zoom=F(I,.3,C.maxZoom),this.cameraX=(h.left+h.right)/2-i.width/2-(a.x+E)*this.zoom,this.cameraY=(h.top+h.bottom)/2-(this.world.originY+a.y+k)*this.zoom,this.updatePlaneTransform(),this.updateTarget()}scheduleGrowthFit(){this.growthIntent&&(this.growthFitFrame&&cancelAnimationFrame(this.growthFitFrame),this.growthFitFrame=requestAnimationFrame(()=>{this.growthFitFrame=null,this.fitGrowthIntent()}))}restoreGrowthView(e,t=null,i={}){let s=e?.priorView;if(!s)return;this.growthFitFrame&&cancelAnimationFrame(this.growthFitFrame),this.growthFitFrame=null,this.zoom=this.clampZoom(s.zoom),this.cameraX=s.cameraX,this.cameraY=s.cameraY,this.clampCamera(),this.updatePlaneTransform();let o=Number(window.visualViewport?.width)||window.innerWidth,n=Number(window.visualViewport?.height)||window.innerHeight,r=Math.abs(o-s.viewportWidth)>1||Math.abs(n-s.viewportHeight)>1;t?this.revealCoordinate(t.q,t.r,"auto"):i.restoreScroll!==!1&&r&&e.originalOrigin?this.revealCoordinate(e.originalOrigin.q,e.originalOrigin.r,"auto"):(this.updateTarget(),this.scheduleViewport())}async preparePlacement(e,t={}){let i=++this.placementIntentGeneration,s=this.activationGeneration,o=this.identityGeneration,n=Number(e.q),r=Number(e.r);if(!M(n,r)){this.toast("That spot is beyond the Hive's growing edge.");return}if(this.bounds.readOnly){this.toast("The Wall is open to read while Hive Watch is verified. New combs will open soon.");return}let h=H(this.draft,!0);if(h&&(h.q!==n||h.r!==r)&&String(h.body||"").trim()&&t.preserveExistingDraft!==!1){if(!window.confirm(`You already have an unfinished draft at comb ${h.q}, ${h.r}. Move that draft to comb ${n}, ${r}? Choose Cancel to keep its original address.`))return;t={...t,body:h.body,requestId:null,preserveExistingDraft:!1}}let a=await this.hydratePlacement(n,r);if(i!==this.placementIntentGeneration||!this.isContextCurrent(s,o))return;if(!a.ok){this.toast(a.code==="out_of_bounds"?"That spot is beyond the Hive's growing edge.":"The Hive could not verify that comb yet. Your current wall stays visible; try the spot again when it reconnects.");return}let l=a.occupied;if(l){this.openReader(l);return}if(!this.storageScope){let q=this.scopeRequestGeneration+1,T=await this.syncStorageScope(!0);if(this.scopeRequestGeneration!==q||!this.isActivationCurrent(s)||!T||T!==this.storageScope){this.toast("The Hive could not establish a safe identity for this comb. Nothing was posted; try again when the connection recovers.");return}i=++this.placementIntentGeneration,o=this.identityGeneration}if(i!==this.placementIntentGeneration||!this.isContextCurrent(s,o))return;let c=a.groups||Y(this.cells,n,r,this.conversations),u=a.choices,m=Z.has(t.intent)?t.intent:null,y=!m&&c.length===0,b=m||(y?"independent":null),E=t.conversationId||null,k=t.choiceExplicit===!0||y,I=!!b&&(k||y),p={q:n,r,body:t.body||this.draft&&this.draft.q===n&&this.draft.r===r&&this.draft.body||"",requestId:t.requestId||null,conversationId:E,replyToId:t.replyToId||null,intent:b,anchorCellIds:L(t.anchorCellIds),choices:u,groups:c,mode:t.mode||(E?"join":"root"),choiceMade:I,choiceExplicit:k,requiresConversationChoice:c.length>0&&!I,placementVerified:!0};if(!this.getUser()){if(this.draft=p,this.saveDraft()===!1){this.toast("Create a profile first, then choose this comb again. This browser cannot safely carry the spot through identity setup.");return}this.announce("Create a profile, then this exact comb and draft will reopen."),this.requestIdentity({reason:"wall",coordinate:{q:n,r}});return}this.openComposer(p,t.opener)}openComposer(e,t=null){this.placementIntentGeneration+=1;let i=++this.composeGeneration;this.composeBusy=!1,this.composeBody.readOnly=!1;let s=Array.isArray(e.groups)?e.groups:Y(this.cells,Number(e.q),Number(e.r),this.conversations);this.composeState={generation:i,q:Number(e.q),r:Number(e.r),body:e.body||"",requestId:e.requestId||null,conversationId:e.conversationId||null,replyToId:e.replyToId||null,intent:Z.has(e.intent)?e.intent:null,anchorCellIds:L(e.anchorCellIds),choices:Array.isArray(e.choices)?e.choices:ae(this.cells,Number(e.q),Number(e.r),this.conversations),groups:s,mode:e.mode||(e.conversationId?"join":"root"),choiceMade:e.choiceMade!==!1,choiceExplicit:e.choiceExplicit===!0,requiresConversationChoice:e.requiresConversationChoice===!0,choiceLocked:e.choiceLocked===!0||e.choiceExplicit===!0&&["reply","branch"].includes(e.mode),placementVerified:e.placementVerified!==!1};let o=this.root.querySelector("[data-wall-compose-submit]");o.disabled=this.bounds.readOnly||!this.composeState.choiceMade||!this.composeState.intent,o.textContent=this.placementSubmitLabel(),this.root.querySelector("[data-wall-compose-cancel]").textContent="Keep as draft",this.composeBody.value=this.composeState.body,this.root.querySelector("[data-wall-compose-count]").textContent=`${[...this.composeBody.value].length} / 600`,this.root.querySelector("[data-wall-compose-place]").textContent="This comb keeps its place while every nearby conversation stays free to grow.";let n=this.root.querySelector("[data-wall-conversation-choices]");n.disabled=!1;let r=this.root.querySelector("[data-wall-conversation-options]");r.replaceChildren();let h=this.placementChoicesForGroups(s);if(h.length&&!this.composeState.choiceLocked){n.hidden=!1,g(this.root.querySelector("[data-wall-conversation-legend]"),s.length>1?"Conversations meet at this comb. What should happen here?":"How should this comb connect?");for(let l of h)r.append(this.conversationRadio(l))}else if(this.composeState.requiresConversationChoice){n.hidden=!1;let l=document.createElement("p");l.className="honey-choice-pending",l.textContent="Nearby conversations must reload before you choose where this comb belongs.",r.append(l)}else n.hidden=!0;this.paintComposerIntentCopy(),this.hideComposeError(),this.draft={...this.composeState},this.saveDraft();let a=!n.hidden&&!this.composeState.choiceMade?r.querySelector("input[type=radio]"):null;this.showDialog(this.compose,a||this.composeBody,t)}placementChoicesForGroups(e){let t=[];for(let i of e){let s=i.anchors[0]?.cell;s&&(t.push({intent:"join",conversationId:i.conversationId,replyToId:null,anchorCellIds:[s.id],group:i}),t.push({intent:"branch",conversationId:null,replyToId:null,anchorCellIds:[s.id],group:i}))}return e.length>1&&t.push({intent:"meet",conversationId:null,replyToId:null,anchorCellIds:e.map(i=>i.anchors[0]?.cell?.id).filter(Boolean),groups:e}),t.push({intent:"independent",conversationId:null,replyToId:null,anchorCellIds:[]}),t}placementChoiceSelected(e){return this.composeState.choiceMade&&this.composeState.intent===e.intent&&(this.composeState.conversationId||null)===(e.conversationId||null)&&L(this.composeState.anchorCellIds).join(",")===L(e.anchorCellIds).join(",")}conversationRadio(e){let t=document.createElement("label");t.className="honey-conversation-option";let i=document.createElement("input");i.type="radio",i.name="honeyConversation",i.value=e.intent,i.checked=this.placementChoiceSelected(e),i.required=this.composeState.requiresConversationChoice&&!this.composeState.choiceMade,i.addEventListener("change",()=>{this.composeState.intent=e.intent,this.composeState.conversationId=e.conversationId||null,this.composeState.replyToId=e.replyToId||null,this.composeState.anchorCellIds=L(e.anchorCellIds),this.composeState.mode=e.intent,this.composeState.choiceMade=!0,this.composeState.choiceExplicit=!0,this.composeState.requiresConversationChoice=!1,this.composeState.requestId=null;let r=this.root.querySelector("[data-wall-compose-submit]");r.disabled=this.bounds.readOnly||this.composeBusy,r.textContent=this.placementSubmitLabel(),this.paintComposerIntentCopy(),this.saveDraft()});let s=document.createElement("span");s.className="honey-conversation-copy";let o=document.createElement("strong"),n=document.createElement("small");if(e.intent==="independent")o.textContent="Start on its own",n.textContent="Nearby in space, but not linked to another conversation.";else if(e.intent==="branch"){let r=e.group.anchors[0];o.textContent="Start a new branch",n.textContent=`Bud from ${r.cell.author||"this conversation"}'s ${r.directionLabel} comb; both paths can keep growing.`}else if(e.intent==="meet")o.textContent="Meet them here",n.textContent=`Start a new conversation linked to ${e.groups.length} nearby groups. Nothing is merged or moved.`;else{let r=e.group.anchors[0],h=this.conversations.get(e.conversationId),a=h&&Array.isArray(h.participants)?h.participants.map(c=>c.name).filter(Boolean).slice(0,3):[];o.textContent=a.length?`Continue with ${a.join(", ")}`:`Continue with ${r.cell.author||"the nearby conversation"}`;let l=String(r.cell.body||"").replace(/\s+/g," ").trim().slice(0,72);n.textContent=`${r.directionLabel}${e.group.anchors.length>1?` \xB7 touches on ${e.group.anchors.length} sides`:""}${l?` \xB7 \u201C${l}${String(r.cell.body||"").length>72?"\u2026":""}\u201D`:""}`}return s.append(o,n),t.append(i,s),t}placementSubmitLabel(){return this.composeState?.mode==="reply"?"Place this reply":{join:"Continue conversation",branch:"Start this branch",meet:"Meet here",independent:"Start conversation"}[this.composeState?.intent]||"Choose a connection"}paintComposerIntentCopy(){let e=this.composeState?.intent,t={join:[this.composeState?.mode==="reply"?"Replying beside a comb":"Continuing nearby",this.composeState?.mode==="reply"?"Reply from this comb":"Continue this conversation"],branch:["Budding a new path","Start a new branch"],meet:["Nearby groups crossing paths","Let these conversations meet"],independent:["New patch","Start something here"]}[e]||["Open comb","Choose how this comb connects"];g(this.root.querySelector("[data-wall-compose-kicker]"),t[0]),g(this.root.querySelector("[data-wall-compose-title]"),t[1])}async submitCompose(){let e=this.composeState;if(!e)return;let t=e.generation,i=this.identityGeneration,s=this.composeBody.value.trim();if(!s||[...s].length>C.bodyCharacters){this.showComposeError("Write between 1 and 600 characters. Nothing will be silently cut off.");return}if(e.editing){await this.commitEdit(s);return}if(!this.getUser()){if(e.body=s,this.draft={...e},this.saveDraft()===!1)return;this.closeDialog(this.compose),this.requestIdentity({reason:"wall",coordinate:{q:e.q,r:e.r}});return}let o=this.root.querySelector("[data-wall-compose-submit]");o.disabled=!0,o.textContent="Checking this comb\u2026",this.composeBody.readOnly=!0,this.composeBusy=!0;let n=this.root.querySelector("[data-wall-conversation-choices]");n.disabled=!0,this.hideComposeError();try{if(!!!(e.requestId&&String(e.body||"").trim()===s)){e.requestId=null;let l=await this.hydratePlacement(e.q,e.r);if(i!==this.identityGeneration||this.composeState!==e||t!==this.composeGeneration)return;if(!l.ok){e.placementVerified=!1,this.showComposeError("The Hive could not verify this comb and its neighbors. Your draft remains open here; reconnect before placing it.");return}if(l.occupied){this.draft={...e,body:s},this.saveDraft();let m=this.findOpenNeighbor({q:e.q,r:e.r},e.conversationId);m?(this.selected=m,this.updateTarget(),this.showComposeError("Someone filled that comb first. Your whole draft remains here. Move it only if the highlighted open comb works for you.",m)):this.showComposeError("Someone filled that comb first. Your whole draft remains here, but no open neighboring comb is loaded yet.");return}if(e.placementVerified=!0,e.choices=l.choices,e.groups=l.groups||Y(this.cells,e.q,e.r,this.conversations),!e.choiceMade||!Z.has(e.intent)){let m=this.dialogOpeners.get(this.compose);this.openComposer({...e,body:s,choices:l.choices,groups:e.groups,choiceMade:!1,requiresConversationChoice:!0,placementVerified:!0},m),this.showComposeError("Choose how this comb connects before placing it."),this.root.querySelector("[data-wall-conversation-options] input[type=radio]")?.focus?.({preventScroll:!0});return}let c=new Set(e.groups.flatMap(m=>m.anchors.map(y=>y.cell.id))),u=L(e.anchorCellIds).some(m=>!c.has(m));if(e.intent!=="independent"&&u){let m=this.dialogOpeners.get(this.compose);this.openComposer({...e,body:s,choices:l.choices,groups:e.groups,intent:null,conversationId:null,replyToId:null,anchorCellIds:[],choiceMade:!1,choiceExplicit:!1,choiceLocked:!1,requiresConversationChoice:!0,placementVerified:!0},m),this.showComposeError("A linked comb changed while you were writing. Your message is untouched; choose the current connection again."),this.root.querySelector("[data-wall-conversation-options] input[type=radio]")?.focus?.({preventScroll:!0});return}}let h=e.requestId||U();e.requestId=h,e.body=s,this.draft={...e},this.saveDraft(),o.textContent="Placing\u2026";let a=await this.backend.wallPlaceCell({requestId:h,q:e.q,r:e.r,body:s,intent:e.intent,conversationId:e.conversationId,replyToId:e.replyToId,anchorCellIds:L(e.anchorCellIds)});if(i!==this.identityGeneration)return;if(this.composeState!==e||t!==this.composeGeneration){if(a?.ok&&a.cell){this.draft?.requestId===e.requestId&&this.clearDraft(),this.markSeen(a.cell.id);let l=this.captureProjectionRebuild();await this.rebuildAfterConfirmedWrite(l),this.toast("Your earlier comb was placed while you moved on."),this.onPlaced&&this.onPlaced(a.cell)}return}if(a&&a.ok&&a.cell){let l=this.captureProjectionRebuild();this.composeBusy=!1,this.clearDraft(),this.closeDialog(this.compose),this.markSeen(a.cell.id),await this.rebuildAfterConfirmedWrite(l),this.active&&this.mode==="wall"&&await this.focusCell(a.cell.id);let c={join:e.mode==="reply"?"Your reply grew this conversation.":"Your comb continued this conversation.",branch:"Your new branch can now grow in any direction.",meet:"These nearby conversations now meet at a new patch.",independent:"Your new conversation is growing in the Hive."}[e.intent]||"Your comb is part of the shared Hive.";this.toast(c),this.onPlaced&&this.onPlaced(a.cell)}else if(a&&a.code==="occupied"){e.requestId=null,this.draft={...e},this.saveDraft();let l=this.findOpenNeighbor({q:e.q,r:e.r},e.conversationId);l?(this.selected=l,this.updateTarget(),this.showComposeError("Someone filled that comb first. Your whole draft remains here. Move it only if the highlighted open comb works for you.",l)):this.showComposeError("Someone filled that comb first. Your whole draft remains here, but no open neighboring comb is loaded yet.")}else if(a&&(a.code==="not_adjacent"||a.code==="invalid_reply")){e.requestId=null,this.draft={...e},this.saveDraft();let l=this.findConversationFrontier(e.conversationId,e);l?(this.selected=l,this.updateTarget(),this.showComposeError("That conversation grew away from this spot. Your draft remains here. Move it only if the highlighted edge comb works for you.",l)):this.showComposeError("That conversation grew away from this spot. Your draft remains here, but its open edge is not loaded yet.")}else if(a&&a.code==="stale_anchors"){e.requestId=null,this.draft={...e,body:s},this.saveDraft();let l=await this.hydratePlacement(e.q,e.r);if(i!==this.identityGeneration||this.composeState!==e||t!==this.composeGeneration)return;if(l.ok&&!l.occupied){let c=this.dialogOpeners.get(this.compose);this.openComposer({...e,body:s,requestId:null,choices:l.choices,groups:l.groups||[],intent:null,conversationId:null,replyToId:null,anchorCellIds:[],choiceMade:!1,choiceExplicit:!1,choiceLocked:!1,requiresConversationChoice:!0,placementVerified:!0},c),this.showComposeError("A nearby conversation changed while this comb was being placed. Your message is untouched; choose the current connection again."),this.root.querySelector("[data-wall-conversation-options] input[type=radio]")?.focus?.({preventScroll:!0})}else this.showComposeError(`${a.message||"A nearby conversation changed."} Your draft is still here; reconnect and choose again.`)}else a&&a.ok===!1?(e.requestId=null,this.draft={...e},this.saveDraft(),(a.code==="read_only"||a.code==="out_of_bounds")&&this.refreshBounds(),this.showComposeError(`${a.message||"The wall could not place that comb."} Your draft is still here.`)):this.showComposeError("The wall did not confirm that placement. Your draft is still here.")}catch(r){this.composeState===e&&t===this.composeGeneration&&this.showComposeError(`${r.message} Your draft is still open here; retrying will use the same idempotent request.`),this.dataStale=!0,this.setConnectionState(navigator.onLine?"stale":"offline")}finally{this.composeState===e&&t===this.composeGeneration&&(this.composeBusy=!1,o.disabled=this.bounds.readOnly,o.textContent=typeof this.placementSubmitLabel=="function"?this.placementSubmitLabel():"Place this comb",this.composeBody.readOnly=!1,n.disabled=!1)}}acceptComposeSuggestion(){let e=this.composeState;if(!e)return;if(e.editing&&e.editConflictCell){let h=e.editConflictCell,a=this.dialogOpeners.get(this.compose);this.saveEditDraft(),this.closeDialog(this.compose,{restoreFocus:!1}),this.openReader(h,a);return}let t=e.suggestedCoordinate;if(!t||this.cells.has(v(t.q,t.r))){this.showComposeError("That suggested comb is no longer open. Your draft has not moved.");return}let i=ae(this.cells,t.q,t.r,this.conversations),s=Y(this.cells,t.q,t.r,this.conversations),o=new Set(s.flatMap(h=>h.anchors.map(a=>a.cell.id))),n=e.intent==="independent"||L(e.anchorCellIds).every(h=>o.has(h)),r=this.composeBody.value;this.selected={q:t.q,r:t.r},this.updateTarget(),this.openComposer({...e,q:t.q,r:t.r,body:r,requestId:null,choices:i,groups:s,intent:n?e.intent:null,conversationId:n?e.conversationId:null,replyToId:n?e.replyToId:null,anchorCellIds:n?e.anchorCellIds:[],mode:n?e.mode:"root",choiceMade:n&&e.choiceMade,choiceExplicit:n&&e.choiceExplicit,choiceLocked:n&&e.choiceLocked,requiresConversationChoice:!n||s.length>0&&!e.choiceMade,placementVerified:!0,suggestedCoordinate:null}),this.announce(n?"Draft moved to the highlighted open comb with its chosen connection intact.":"Draft moved, but its old connection no longer reaches this comb. Choose the current relationship before placing it.")}findOpenNeighbor(e,t=null){let i=_(e.q,e.r);return(t?i.filter(o=>_(o.q,o.r).some(n=>this.cells.get(v(n.q,n.r))?.conversationId===t)):i).find(o=>M(o.q,o.r,this.bounds.radius)&&!this.cells.has(v(o.q,o.r)))||null}findNearestOpen(e={q:0,r:0}){let t=M(e.q,e.r,this.bounds.radius)?e:{q:0,r:0},i=[{q:t.q,r:t.r}],s=new Set([v(t.q,t.r)]);for(;i.length;){let o=i.shift();if(!this.cells.has(v(o.q,o.r)))return o;for(let n of _(o.q,o.r)){let r=v(n.q,n.r);s.has(r)||!M(n.q,n.r,this.bounds.radius)||(s.add(r),i.push(n))}}return null}findConversationFrontier(e,t={q:0,r:0}){if(!e)return this.findOpenNeighbor(t);let i=[...this.cells.values()].filter(s=>s.conversationId===e).sort((s,o)=>W(s.q,s.r,t.q,t.r)-W(o.q,o.r,t.q,t.r));for(let s of i){let o=this.findOpenNeighbor(s,e);if(o)return o}return null}openReader(e,t=null){e=this.cellsById.get(e?.id)||this.mergeCell(e)||e,e?.id&&(this.placementIntentGeneration+=1,this.readerGeneration+=1,this.setReaderBusy(!1),(this.readerCell?.id!==e.id||this.readerCell?.contentVersion!==e.contentVersion)&&(this.reportRequest=null,this.operatorCaseRequest=null),this.readerCell=e,this.paintReaderCell(e),this.markSeen(e.id),this.showDialog(this.reader,this.reader.querySelector("[data-wall-reader-action]:not([hidden])"),t))}paintReaderCell(e,t={}){if(!e)return;let i=this.conversations.get(e.conversationId);g(this.root.querySelector("[data-wall-reader-author]"),e.author||(e.status==="visible"?"Hive member":"Open space kept"));let s=e.replyToId?"Reply comb":e.origin?.kind==="branch"?"Branch root":e.origin?.kind==="meet"?"Meeting comb":i?.rootCellId===e.id?"Conversation root":"Conversation continuation";g(this.root.querySelector("[data-wall-reader-kicker]"),s),g(this.root.querySelector("[data-wall-reader-meta]"),`${e.membership==="alumni"?"DHG alumni":e.membership==="guest"?"Guest":"Hive"} \xB7 ${ue(e.createdAt)} \xB7 comb ${e.q}, ${e.r}`),g(this.root.querySelector("[data-wall-reader-body]"),ne(e));let o=this.root.querySelector("[data-wall-reader-participants]"),n=i&&Array.isArray(i.participants)?i.participants.map(S=>S.name).filter(Boolean).join(", "):"";if(o.dataset.wallParticipantNames!==n&&(o.dataset.wallParticipantNames=n,o.replaceChildren(),n)){let S=document.createElement("span");S.textContent="In this conversation: ";let R=document.createElement("strong");R.textContent=n,o.append(S,R)}let r=this.root.querySelector("[data-wall-reader-relations]"),h=JSON.stringify(e.origin||null);if(r.dataset.wallRelations!==h&&(r.dataset.wallRelations=h,r.replaceChildren(),e.origin?.anchors?.length)){let S=document.createElement("strong");S.textContent=e.origin.kind==="meet"?"Connected nearby:":"Branched from:",r.append(S);for(let R of e.origin.anchors){let G=this.cellsById.get(R.cellId);if(G){let f=document.createElement("button");f.type="button",f.className="honey-relation-link",f.dataset.cellKey=v(G.q,G.r),f.textContent=`${G.author||"Nearby comb"} \xB7 ${ee[Number(R.direction)]||"beside this patch"}`,r.append(f)}else{let f=document.createElement("span");f.textContent="A nearby conversation",r.append(f)}}}let a=e.status==="visible",l=a&&!this.bounds.readOnly,c=this.root.querySelector('[data-wall-reader-action="reply"]'),u=this.root.querySelector('[data-wall-reader-action="branch"]'),m=this.root.querySelector('[data-wall-reader-action="edit"]'),y=this.root.querySelector('[data-wall-reader-action="remove"]'),b=this.root.querySelector('[data-wall-reader-action="report"]'),E=this.root.querySelector('[data-wall-reader-action="watch-open"]');c.hidden=!l,u.hidden=!l,m.hidden=!l||!e.isMine,y.hidden=this.bounds.readOnly||!e.isMine||e.status==="author_removed",b.hidden=!l||e.isMine||e.viewerReported,E.hidden=!a||!this.operator;let k=this.root.querySelector("[data-wall-report-form]"),I=this.root.querySelector("[data-wall-operator-form]"),p=l&&!e.isMine&&!e.viewerReported,q=a&&!!this.operator,T=globalThis.document?.activeElement;(!t.preserveForms||!p)&&(k.hidden=!0),(!t.preserveForms||!q)&&(I.hidden=!0),t.preserveForms||(this.root.querySelector("[data-wall-report-reason]").value="",this.root.querySelector("[data-wall-operator-reason]").value=""),T&&this.reader?.contains(T)&&(T.hidden||T.closest?.("[hidden]"))&&this.focusReaderFallback(b),this.setReaderLocked(this.readerBusy)}focusReaderFallback(e=null){let t=s=>!!(s&&!s.disabled&&!s.hidden&&!s.closest?.("[hidden]")),i=t(e)?e:[...this.reader?.querySelectorAll?.('[data-wall-reader-action], [data-wall-close="reader"]')||[]].find(t)||this.reader;return i?.focus?.({preventScroll:!0}),i||null}setReaderLocked(e){if(this.reader)for(let t of this.reader.querySelectorAll("button, select, textarea"))t.disabled=!!e&&!t.matches('[data-wall-close="reader"]')}setReaderBusy(e){this.readerBusy=!!e,this.setReaderLocked(this.readerBusy)}async runReaderAction(e){if(this.readerBusy)return;let t=this.readerCell;if(!t)return;if(this.bounds.readOnly&&["reply","branch","edit","remove","report"].includes(e)){this.toast("The Wall is open to read while Hive Watch is verified. New combs will open soon.");return}let i=this.dialogOpeners.get(this.reader),s=this.dialogFocusAnchors.get(this.reader);if(e==="reply"||e==="branch")if(this.closeDialog(this.reader,{restoreFocus:!1}),this.mode==="list"){this.setMode("wall"),this.stage?.focus?.({preventScroll:!0}),this.announce("Opening the spatial Wall so you can choose one of six directions.");let o=await this.refreshVisible(!0),n=this.cellsById.get(t.id);if(!o||!n||n.status!=="visible"){this.toast("That comb changed while the spatial Wall opened. Nothing was posted; choose its current comb again."),this.stage?.focus?.({preventScroll:!0});return}this.revealCoordinate(n.q,n.r,"auto"),this.beginGrowthIntent(n,e==="branch"?"branch":"reply",this.stage,null)}else this.beginGrowthIntent(t,e==="branch"?"branch":"reply",i,s);else e==="show"?(this.closeDialog(this.reader,{restoreFocus:!1}),this.setMode("wall"),this.revealCoordinate(t.q,t.r),this.restoreWallFocus(this.stage)):e==="edit"?(this.closeDialog(this.reader,{restoreFocus:!1}),this.openEditComposer(t,i)):e==="remove"?await this.removeCell(t):e==="report"?(this.root.querySelector("[data-wall-report-form]").hidden=!1,this.root.querySelector("[data-wall-report-reason]").focus()):e==="cancel-report"?(this.root.querySelector("[data-wall-report-form]").hidden=!0,this.focusReaderFallback(this.root.querySelector('[data-wall-reader-action="report"]'))):e==="watch-open"?(this.root.querySelector("[data-wall-operator-form]").hidden=!1,this.root.querySelector("[data-wall-operator-reason]").focus()):e==="cancel-watch-open"&&(this.root.querySelector("[data-wall-operator-form]").hidden=!0,this.focusReaderFallback(this.root.querySelector('[data-wall-reader-action="watch-open"]')))}openEditComposer(e,t=null){if(this.editDraft&&this.editDraft.cellId!==e.id&&String(this.editDraft.body||"").trim()&&!window.confirm("You already have an unfinished edit for another comb. Replace that edit draft with this one?"))return this.restoreWallFocus(t),!1;this.placementIntentGeneration+=1;let i=++this.composeGeneration;this.composeBusy=!1,this.composeBody.readOnly=!1,this.root.querySelector("[data-wall-conversation-choices]").disabled=!1,this.root.querySelector("[data-wall-compose-submit]").disabled=!1;let s=this.editDraft&&this.editDraft.cellId===e.id?this.editDraft:null,o=s?s.body||"":e.body||"";return this.composeState={editing:!0,generation:i,cellId:e.id,expectedVersion:e.version,q:e.q,r:e.r,body:o,requestId:s&&s.expectedVersion===e.version&&s.requestId||null,recoveredFromVersion:s&&s.expectedVersion!==e.version?s.expectedVersion:null},this.composeBody.value=o,this.root.querySelector("[data-wall-compose-kicker]").textContent="Editing your comb",this.root.querySelector("[data-wall-compose-title]").textContent="Update this message",this.root.querySelector("[data-wall-compose-place]").textContent=`Comb ${e.q}, ${e.r} stays in place.`,this.root.querySelector("[data-wall-conversation-choices]").hidden=!0,this.root.querySelector("[data-wall-compose-submit]").textContent="Save this comb",this.root.querySelector("[data-wall-compose-cancel]").textContent="Keep edit draft",this.root.querySelector("[data-wall-compose-count]").textContent=`${[...this.composeBody.value].length} / 600`,this.hideComposeError(),this.saveEditDraft(),this.showDialog(this.compose,this.composeBody,t),this.composeState.recoveredFromVersion&&this.showComposeError("This saved edit began from an older version. You reviewed the latest comb; check your draft carefully before saving over it."),!0}async submitEdit(){let e=this.composeState;if(!e||!e.editing)return null;let t=this.composeBody.value.trim(),i=e.requestId||U();return e.requestId=i,this.saveEditDraft(),this.backend.wallEditCell({requestId:i,cellId:e.cellId,expectedVersion:e.expectedVersion,body:t})}async commitEdit(e){let t=this.composeState;if(!t||!t.editing)return;let i=t.generation,s=this.identityGeneration,o=this.root.querySelector("[data-wall-compose-submit]");o.disabled=!0,o.textContent="Saving\u2026",this.composeBody.readOnly=!0,this.composeBusy=!0;try{let n=await this.submitEdit();if(s!==this.identityGeneration)return;if(this.composeState!==t||i!==this.composeGeneration){if(n?.ok&&n.cell){let r=this.captureProjectionRebuild();await this.rebuildAfterConfirmedWrite(r),this.toast("Your earlier edit finished while you moved on.")}return}if(n&&n.ok&&n.cell){let r=this.captureProjectionRebuild();this.clearEditDraft(),this.composeBusy=!1,this.composeState=null,this.closeDialog(this.compose),await this.rebuildAfterConfirmedWrite(r),this.toast("Your comb was updated in place. The Wall reloaded its authoritative position.")}else if(n&&n.code==="version_conflict"){t.requestId=null,this.saveEditDraft();let r=null;try{let h=this.publicCacheGeneration,a=()=>s===this.identityGeneration&&this.composeState===t&&i===this.composeGeneration&&h===this.publicCacheGeneration,l=await this.readAuthoritativeCell(t.cellId,a);l?.rebuildRequired?await this.rebuildPublicProjection(l.rebuild):l?.cell&&a()&&(this.mergeCell(l.cell),r=l.cell)}catch{}r?(t.editConflictCell=r,this.showComposeError("This comb changed on another screen. Your edit draft remains here; review the latest version before deciding what to save.",{editConflict:!0})):this.showComposeError("This comb changed on another screen. Your edit draft remains here; reopen it before saving so newer words are not overwritten.")}else n&&n.ok===!1?(t.requestId=null,this.saveEditDraft(),this.showComposeError(`${n.message||"The wall could not save that edit."} Your edit draft is still here.`)):this.showComposeError("The wall did not confirm that edit. Your edit draft is still here.")}catch(n){this.composeState===t&&i===this.composeGeneration&&this.showComposeError(`${n.message} Your edit is still here.`)}finally{this.composeState===t&&i===this.composeGeneration&&(this.composeBusy=!1,o.disabled=!1,o.textContent="Save this comb",this.composeBody.readOnly=!1)}}async removeCell(e){if(this.readerBusy||!window.confirm("Remove this message? Its comb will remain as a tombstone so the wall never collapses."))return;let t=this.readerGeneration,i=this.identityGeneration;this.setReaderBusy(!0);try{let s=await this.backend.wallRemoveCell({requestId:U(),cellId:e.id,expectedVersion:e.version});if(i!==this.identityGeneration||this.readerCell?.id!==e.id||t!==this.readerGeneration)return;if(s?.ok&&s.cell){let o=this.captureProjectionRebuild();this.setReaderBusy(!1),this.closeDialog(this.reader),this.readerCell=null,this.reportRequest=null,await this.rebuildAfterConfirmedWrite(o),this.toast("Your message was removed; its place in the Hive remains. The Wall reloaded authoritatively.")}else if(s?.ok&&s.code==="already_removed"){let o=this.captureProjectionRebuild();this.setReaderBusy(!1),this.closeDialog(this.reader),this.readerCell=null,this.reportRequest=null,await this.rebuildAfterConfirmedWrite(o),this.toast("That message was already removed; its comb remains in place.")}else if(s?.code==="version_conflict"){let o=this.publicCacheGeneration,n=()=>i===this.identityGeneration&&this.readerCell?.id===e.id&&t===this.readerGeneration&&o===this.publicCacheGeneration,r=await this.readAuthoritativeCell(e.id,n);r?.rebuildRequired?await this.rebuildPublicProjection(r.rebuild):r?.cell&&n()&&(this.mergeCell(r.cell),this.openReader(r.cell)),this.toast("That comb changed on another screen. It was not removed; review the latest version first.")}else this.toast(s?.message||"The wall did not confirm that removal. Nothing was changed.")}catch(s){this.toast(`Could not remove that comb: ${s.message}`)}finally{i===this.identityGeneration&&t===this.readerGeneration&&this.setReaderBusy(!1)}}async submitReport(){if(this.readerBusy)return;let e=this.readerCell;if(!e)return;if(this.bounds.readOnly){this.toast("The Wall is open to read while Hive Watch is verified. Your selected report reason is still here.");return}let t=this.root.querySelector("[data-wall-report-reason]").value;if(!["personal_attack","illegal","spam","privacy"].includes(t)){this.toast("Choose why the Hive watch should review this comb."),this.root.querySelector("[data-wall-report-reason]").focus();return}let i=this.readerGeneration,s=this.identityGeneration;this.setReaderBusy(!0),(!this.reportRequest||this.reportRequest.cellId!==e.id||this.reportRequest.contentVersion!==e.contentVersion||this.reportRequest.reason!==t)&&(this.reportRequest={requestId:U(),cellId:e.id,contentVersion:e.contentVersion,reason:t});let o=this.reportRequest;try{let n=await this.backend.wallReportCell({requestId:o.requestId,cellId:e.id,expectedContentVersion:e.contentVersion,reason:t});if(s!==this.identityGeneration||this.readerCell?.id!==e.id||i!==this.readerGeneration)return;if(this.reportRequest===o&&(this.reportRequest=null),!n?.ok){if(n?.code==="content_conflict"){let h=this.publicCacheGeneration,a=()=>s===this.identityGeneration&&this.readerCell?.id===e.id&&i===this.readerGeneration&&h===this.publicCacheGeneration,l=await this.readAuthoritativeCell(e.id,a);l?.rebuildRequired?await this.rebuildPublicProjection(l.rebuild):l?.cell&&a()&&(this.mergeCell(l.cell),this.openReader(l.cell))}this.toast(n?.message||"The Hive watch did not confirm that report.");return}let r=this.captureProjectionRebuild();s===this.identityGeneration&&i===this.readerGeneration&&this.setReaderBusy(!1),this.closeDialog(this.reader),this.readerCell=null,await this.rebuildAfterConfirmedWrite(r),this.toast("Your report went privately to the Hive watch.")}catch(n){this.toast(`Could not send that report: ${n.message}`)}finally{s===this.identityGeneration&&i===this.readerGeneration&&this.setReaderBusy(!1)}}async probeOperator(){let e=this.root.querySelector('[data-wall-action="watch"]');if(!e||typeof this.backend.wallOperatorStatus!="function")return!1;let t=++this.operatorProbeGeneration,i=this.activationGeneration,s=this.identityGeneration;try{let o=await this.backend.wallOperatorStatus();if(t!==this.operatorProbeGeneration||!this.isContextCurrent(i,s))return!1;this.operator=o?.operator||null,e.hidden=!this.operator,this.operator&&(e.textContent=o?.cases?.length?"Hive watch \xB7 review":"Hive watch");let n=this.root.querySelector('[data-wall-reader-action="watch-open"]');return n&&(n.hidden=!this.operator||this.readerCell?.status!=="visible"),!!this.operator}catch{return t!==this.operatorProbeGeneration||!this.isContextCurrent(i,s)||(this.operator=null,e.hidden=!0),!1}}async submitOperatorCase(){if(this.readerBusy)return;let e=this.readerCell;if(!e||!this.operator||typeof this.backend.wallOpenCase!="function")return;let t=this.root.querySelector("[data-wall-operator-reason]"),i=t.value.trim();if(i.length<3){this.toast("Write a short evidence-based reason for opening the case."),t.focus();return}if(!window.confirm(`Open an urgent private review case for comb ${e.q}, ${e.r} by ${e.author||"this author"}?`))return;let s=this.activationGeneration,o=this.identityGeneration,n=this.readerGeneration;(!this.operatorCaseRequest||this.operatorCaseRequest.cellId!==e.id||this.operatorCaseRequest.expectedVersion!==e.version||this.operatorCaseRequest.reason!==i)&&(this.operatorCaseRequest={requestId:U(),cellId:e.id,expectedVersion:e.version,reason:i});let r=this.operatorCaseRequest;this.setReaderBusy(!0);try{let h=await this.backend.wallOpenCase({requestId:r.requestId,cellId:e.id,expectedVersion:e.version,reason:i,priority:"urgent"});if(!this.isContextCurrent(s,o)||n!==this.readerGeneration||this.readerCell?.id!==e.id)return;if(!h?.ok){this.toast("That comb changed before the case opened. Review the current version first.");return}this.operatorCaseRequest===r&&(this.operatorCaseRequest=null),this.setReaderBusy(!1),this.closeDialog(this.reader,{restoreFocus:!1});let a=await this.openWatch();if(!this.isContextCurrent(s,o)||!a)return;await this.openWatchCase(h.cellId,h.contentVersion),this.toast("Urgent review case opened for the Hive watch.")}catch(h){this.isContextCurrent(s,o)&&this.toast(`The private case was not confirmed: ${h.message}`)}finally{this.isContextCurrent(s,o)&&n===this.readerGeneration&&this.setReaderBusy(!1)}}async openWatch(){let e=++this.watchGeneration;this.watchQueueRequestGeneration+=1,this.watchCaseRequestGeneration+=1,this.watchActionGeneration+=1;let t=this.activationGeneration,i=this.identityGeneration;return!this.operator&&!await this.probeOperator()?(e!==this.watchGeneration||!this.isContextCurrent(t,i)||this.toast("This saved account is not on the Hive watch allowlist."),!1):e!==this.watchGeneration||!this.isContextCurrent(t,i)||(this.clearWatchDom(),this.watchCases=[],this.watchCursor=null,this.watchHasMore=!1,this.showDialog(this.watch,this.watch.querySelector("[data-wall-close='watch']")),await this.loadWatchQueue(!0,e),e!==this.watchGeneration||!this.isContextCurrent(t,i))?!1:(this.watchPollTimer&&window.clearInterval(this.watchPollTimer),this.watchPollTimer=window.setInterval(()=>{this.watch.open&&!this.watchBusy&&e===this.watchGeneration&&this.loadWatchQueue(!0,e,!0)},15e3),!0)}async loadWatchQueue(e=!1,t=this.watchGeneration,i=!1){if(t!==this.watchGeneration||this.watchBusy)return!1;let s=++this.watchQueueRequestGeneration;this.watchLoadingGeneration=s;let o=this.activationGeneration,n=this.identityGeneration,r=e?null:this.watchCursor,h=this.root.querySelector("[data-wall-watch-status]"),a=this.watchQueueFingerprint();i||g(h,e?"Loading attributable review cases\u2026":"Loading more review cases\u2026");try{let l=await this.backend.wallModerationQueue(r,50);if(t!==this.watchGeneration||s!==this.watchQueueRequestGeneration||!this.isContextCurrent(o,n))return!1;this.operator=l?.operator||this.operator;let c=Array.isArray(l?.cases)?l.cases:[];e&&(this.watchCases=[]);let u=new Set(this.watchCases.map(y=>`${y.cellId}:${y.contentVersion}`));for(let y of c){let b=`${y.cellId}:${y.contentVersion}`;u.has(b)||(this.watchCases.push(y),u.add(b))}this.watchCursor=l?.nextCursor||null,this.watchHasMore=!!(l?.hasMore&&this.watchCursor);let m=a!==this.watchQueueFingerprint();return(!i||m)&&(this.renderWatchQueue(),g(h,`${this.operator?.name||"Hive watch"} \xB7 ${this.operator?.role||"reviewer"} \xB7 ${this.watchCases.length}${this.watchHasMore?"+":""} active cases`)),!0}catch(l){return t===this.watchGeneration&&s===this.watchQueueRequestGeneration&&this.isContextCurrent(o,n)&&!i&&g(h,`The private review queue could not load: ${l.message}`),!1}finally{this.watchLoadingGeneration===s&&(this.watchLoadingGeneration=0)}}watchQueueFingerprint(){return JSON.stringify({operator:[this.operator?.name||"",this.operator?.role||""],cursor:this.watchCursor||null,hasMore:!!this.watchHasMore,cases:this.watchCases.map(e=>[e.cellId,Number(e.contentVersion)||0,e.priority||"",Number(e.reportCount)||0,Number(e.q)||0,Number(e.r)||0,e.caseStatus||"",e.currentStatus||""])})}renderWatchQueue(){let e=globalThis.document?.activeElement||null,t=e&&this.watch.contains(e)&&(e.dataset?.wallWatchKey||e.dataset?.wallWatchFocus)||null,i=t&&typeof e.getBoundingClientRect=="function"?e.getBoundingClientRect().top:null,s=new Map([...this.watchQueue.querySelectorAll("[data-wall-watch-key]")].map(a=>[a.dataset.wallWatchKey,a])),o=new Set,n=this.watchQueue.firstElementChild;for(let a of this.watchCases){let l=`${a.cellId}:${a.contentVersion}`;o.add(l);let c=s.get(l);if(!c){c=document.createElement("button"),c.type="button",c.className="honey-watch-case",c.dataset.wallWatchKey=l;let m=document.createElement("strong");m.dataset.wallWatchPart="title";let y=document.createElement("span");y.dataset.wallWatchPart="detail",c.append(m,y)}c.dataset.wallWatchCase=a.cellId,c.dataset.wallWatchVersion=String(a.contentVersion);let u=this.watchCase?.case?.cellId===a.cellId&&Number(this.watchCase?.case?.contentVersion)===Number(a.contentVersion);c.setAttribute("aria-controls","honeyWatchDetail"),c.setAttribute("aria-expanded",String(u)),u?c.setAttribute("aria-current","true"):c.removeAttribute("aria-current"),g(c.querySelector('[data-wall-watch-part="title"]'),`${a.priority==="urgent"?"Urgent":"Normal"} \xB7 ${a.reportCount} ${a.reportCount===1?"report":"reports"}`),g(c.querySelector('[data-wall-watch-part="detail"]'),`Comb ${a.q}, ${a.r} \xB7 ${a.caseStatus} \xB7 ${a.currentStatus}`),c!==n&&this.watchQueue.insertBefore(c,n),n=c.nextElementSibling}for(let[a,l]of s)o.has(a)||l.remove();let r=this.watchQueue.querySelector("[data-wall-watch-empty]");this.watchCases.length?r?.remove():(r||(r=document.createElement("p"),r.className="honey-list-empty",r.dataset.wallWatchEmpty="true",this.watchQueue.append(r)),g(r,"No Wall cases need a human decision."));let h=this.root.querySelector("[data-wall-watch-more]");if(h.hidden=!this.watchHasMore,h.disabled=this.watchBusy,t){let a=(t==="more"&&!h.hidden&&!h.disabled?h:null)||this.watchQueue.querySelector(`[data-wall-watch-key="${se(t)}"]`)||this.watchQueue.querySelector("[data-wall-watch-key]")||(!h.hidden&&!h.disabled?h:this.watch.querySelector("[data-wall-close='watch']")),l=()=>{if(a?.focus?.({preventScroll:!0}),a&&i!=null&&typeof globalThis.window?.scrollBy=="function"){let c=a.getBoundingClientRect().top-i;c&&globalThis.window.scrollBy({top:c,behavior:"auto"})}};typeof globalThis.requestAnimationFrame=="function"?requestAnimationFrame(l):l()}}async openWatchCase(e,t){if(this.watchBusy)return!1;let i=this.watchGeneration,s=++this.watchCaseRequestGeneration,o=this.activationGeneration,n=this.identityGeneration,r=this.root.querySelector("[data-wall-watch-status]");this.watchCase=null,this.watchDetail.hidden=!0,this.watchReason.value="",r.textContent="Loading preserved evidence\u2026";try{let h=await this.backend.wallModerationDetail(e,t);if(i!==this.watchGeneration||s!==this.watchCaseRequestGeneration||!this.isContextCurrent(o,n))return!1;if(!h?.case||!h?.current)throw new Error("That review case is no longer available.");return this.watchCase=h,this.watchActionRequest=null,this.renderWatchCase(),this.watchDetail.hidden=!1,this.renderWatchQueue(),this.watchDetail.scrollIntoView({block:"nearest",behavior:this.motionBehavior("smooth")}),this.root.querySelector("#honeyWatchCaseTitle")?.focus?.({preventScroll:!0}),r.textContent=`${h.operator?.name||"Hive watch"} \xB7 evidence is private to allowlisted reviewers`,!0}catch(h){return i===this.watchGeneration&&s===this.watchCaseRequestGeneration&&this.isContextCurrent(o,n)&&(r.textContent=`That case could not load: ${h.message}`),!1}}renderWatchCase(){let e=this.watchCase;if(!e?.case||!e?.current)return;let t=e.case,i=e.current;this.root.querySelector("[data-wall-watch-meta]").textContent=`${t.priority} priority \xB7 ${t.status} \xB7 comb ${i.q}, ${i.r} \xB7 content v${t.contentVersion} \xB7 current v${i.version}`,this.root.querySelector("[data-wall-watch-evidence]").textContent=`${t.evidenceAuthor||"Hive member"}: ${t.evidenceBody}`,this.root.querySelector("[data-wall-watch-current]").textContent=i.contentVersion===t.contentVersion?`Current public version: ${i.body||"No public body is visible."}`:`Current public content is now version ${i.contentVersion}: ${i.body||"No public body is visible."}`;let s=this.root.querySelector("[data-wall-watch-reports]");s.replaceChildren();let o=Array.isArray(e.reports)?e.reports:[],n=document.createElement("p");n.textContent=o.length?`Private reports: ${o.map(u=>`${u.reporter||"verified reporter"} (${String(u.reason).replaceAll("_"," ")})`).join(", ")}`:"Operator-opened case; no visitor report is attached.",s.append(n);let r=this.root.querySelector("[data-wall-watch-events]");r.replaceChildren();let h=Array.isArray(e.events)?e.events:[],a=document.createElement("p");a.textContent=h.length?`Case history: ${h.map(u=>`${u.operator||"Hive watch"} ${String(u.action).replaceAll("_"," ")}`).join("; ")}`:"No prior operator action is recorded for this case.",r.append(a);let l=this.root.querySelector("[data-wall-watch-actions]");l.replaceChildren();let c=(u,m,y=!1)=>{let b=document.createElement("button");b.type="button",b.className=`honey-tool${y?" honey-tool-primary":""}`,b.dataset.wallWatchAction=u,b.textContent=m,l.append(b)};t.status==="contained"?c("restore","Restore publicly"):(c("dismiss","Dismiss report"),i.status==="visible"&&i.contentVersion===t.contentVersion&&c("quarantine","Contain for review",!0)),this.operator?.role==="admin"&&["visible","quarantined"].includes(i.status)&&c("remove","Remove globally")}async moderateWatchCase(e){if(this.watchBusy)return;let t=this.watchCase;if(!t?.case||!t?.current)return;let i=this.root.querySelector("[data-wall-watch-reason]").value.trim();if(i.length<3){this.root.querySelector("[data-wall-watch-status]").textContent="Write a short evidence-based decision note first.";return}let s={quarantine:"Contain for review",dismiss:"Dismiss this case",restore:"Restore publicly",remove:"Remove globally"}[e]||e,o=t.current;if(!window.confirm(`${s} for comb ${o.q}, ${o.r} by ${o.author||"this author"}? This exact action and your note will be audited.`))return;let n=this.watchGeneration,r=this.watchCaseRequestGeneration,h=++this.watchActionGeneration,a=this.activationGeneration,l=this.identityGeneration,c=[t.case.cellId,t.case.contentVersion,t.case.generation,t.current.version,e,i].join(":");(!this.watchActionRequest||this.watchActionRequest.fingerprint!==c)&&(this.watchActionRequest={requestId:U(),fingerprint:c});let u=this.watchActionRequest;this.watchBusy=!0,this.setWatchLocked(!0);try{let m=await this.backend.wallModerateCase({requestId:u.requestId,cellId:t.case.cellId,contentVersion:t.case.contentVersion,caseGeneration:t.case.generation,expectedVersion:t.current.version,action:e,reason:i});if(n!==this.watchGeneration||r!==this.watchCaseRequestGeneration||h!==this.watchActionGeneration||!this.isContextCurrent(a,l))return;if(!m?.ok){this.root.querySelector("[data-wall-watch-status]").textContent="That case changed on another screen. Reloading current evidence\u2026",this.watchBusy=!1,this.setWatchLocked(!1),await this.openWatchCase(t.case.cellId,t.case.contentVersion);return}this.watchActionRequest===u&&(this.watchActionRequest=null);let y=this.captureProjectionRebuild();this.watchCase=null,this.watchDetail.hidden=!0,this.watchReason.value="",this.watchBusy=!1,this.setWatchLocked(!1),await this.rebuildAfterConfirmedWrite(y),await this.loadWatchQueue(!0,n),(this.watchQueue.querySelector("[data-wall-watch-key]")||(this.root.querySelector("[data-wall-watch-more]")?.hidden?null:this.root.querySelector("[data-wall-watch-more]"))||this.watch.querySelector('[data-wall-close="watch"]'))?.focus?.({preventScroll:!0}),this.toast(`Hive watch recorded: ${e}.`)}catch(m){n===this.watchGeneration&&h===this.watchActionGeneration&&this.isContextCurrent(a,l)&&(this.root.querySelector("[data-wall-watch-status]").textContent=`The action was not confirmed: ${m.message}`)}finally{n===this.watchGeneration&&h===this.watchActionGeneration&&(this.watchBusy=!1,this.setWatchLocked(!1))}}setWatchLocked(e){for(let t of this.watch.querySelectorAll("button, textarea"))t.disabled=!!e&&!t.matches('[data-wall-close="watch"]');e||this.renderWatchQueue()}showDialog(e,t,i=null){if(!!!(e.open||e.hasAttribute("open"))){let o=document.activeElement,n=i||(o instanceof HTMLElement?o:null);this.dialogOpeners.set(e,n);let r=n?.dataset?.wallListFocus||null;this.dialogFocusAnchors.set(e,r?{focusKey:r,focusTop:typeof n.getBoundingClientRect=="function"?n.getBoundingClientRect().top:null}:null)}typeof e.showModal=="function"?e.open||e.showModal():e.setAttribute("open",""),this.focusFrame&&cancelAnimationFrame(this.focusFrame),this.focusFrame=requestAnimationFrame(()=>{this.focusFrame=null,t?.focus()})}closeDialog(e,t={}){if(!e)return null;if(e===this.compose&&this.composeState&&(this.composeState.editing?this.saveEditDraft():this.saveDraft())===!1){if(!(e===this.compose&&this.composeBusy||window.confirm("This browser cannot save the draft outside this tab. Close the composer anyway? Your words remain here until this page reloads.")))return null;this.toast("The draft remains only in this tab. Copy it before reloading or switching accounts.")}e===this.compose&&(this.composeGeneration+=1,this.composeBusy=!1,this.composeBody.readOnly=!1,this.composeState=null,this.updateResumeDraftAction()),e===this.reader&&(this.readerGeneration+=1,this.readerBusy=!1,this.readerCell=null,this.reportRequest=null,this.operatorCaseRequest=null),e===this.watch&&(this.watchGeneration+=1,this.watchQueueRequestGeneration+=1,this.watchCaseRequestGeneration+=1,this.watchActionGeneration+=1,this.watchPollTimer&&window.clearInterval(this.watchPollTimer),this.watchPollTimer=null,this.watchCase=null,this.watchBusy=!1,this.clearWatchDom());let i=t.restoreFocus!==!1,s=this.dialogOpeners.get(e),o=this.dialogFocusAnchors.get(e);return typeof e.close=="function"&&e.open?e.close():e.removeAttribute("open"),this.dialogOpeners.delete(e),this.dialogFocusAnchors.delete(e),i&&this.restoreWallFocus(s,o),s}restoreWallFocus(e=null,t=null){this.focusFrame&&cancelAnimationFrame(this.focusFrame),this.focusFrame=requestAnimationFrame(()=>{if(this.focusFrame=null,!(e?.isConnected&&!e.disabled&&e.getAttribute?.("aria-disabled")!=="true"&&!e.closest("[hidden]")&&!e.closest("dialog:not([open])")&&(e.focus({preventScroll:!0}),!globalThis.document||globalThis.document.activeElement===e)))if(this.mode==="list"){let i=t?.focusKey?this.list?.querySelector(`[data-wall-list-focus="${se(t.focusKey)}"]`):null,o=(i&&!i.hidden&&!i.disabled&&!i.closest?.("[hidden]")?i:null)||this.list?.querySelector("button:not([hidden])")||this.list;if(o?.focus({preventScroll:!0}),o&&t?.focusTop!=null&&typeof window.scrollBy=="function"){let n=o.getBoundingClientRect().top-t.focusTop;n&&window.scrollBy({top:n,behavior:"auto"})}}else this.stage?.focus({preventScroll:!0})})}showComposeError(e,t=null){this.composeError.hidden=!1,this.composeError.textContent=e,this.composeBody?.setAttribute?.("aria-invalid","true");let i=this.root.querySelector("[data-wall-compose-suggestion]");t?.editConflict?(i.textContent="Review latest comb",i.hidden=!1):t&&Number.isInteger(t.q)&&Number.isInteger(t.r)?(this.composeState&&(this.composeState.suggestedCoordinate={q:t.q,r:t.r}),i.textContent=`Move draft to ${t.q}, ${t.r}`,i.hidden=!1):(this.composeState&&(this.composeState.suggestedCoordinate=null),i.hidden=!0)}hideComposeError(){this.composeError.hidden=!0,this.composeError.textContent="",this.composeBody?.removeAttribute?.("aria-invalid");let e=this.root.querySelector("[data-wall-compose-suggestion]");e.hidden=!0,e.textContent="Use highlighted comb",this.composeState&&(this.composeState.suggestedCoordinate=null)}saveDraft(){if(this.composeState?.editing||!this.composeState&&!this.draft)return;let e=this.composeState&&!this.composeState.editing?this.composeState:this.draft;if(!e)return;let t={q:Number(e.q),r:Number(e.r),body:this.composeBody&&this.compose.open?this.composeBody.value:e.body||"",requestId:e.requestId||null,conversationId:e.conversationId||null,replyToId:e.replyToId||null,intent:Z.has(e.intent)?e.intent:null,anchorCellIds:L(e.anchorCellIds),choiceMade:e.choiceMade!==!1,choiceExplicit:e.choiceExplicit===!0,requiresConversationChoice:e.requiresConversationChoice===!0,mode:e.mode||null,updatedAt:Date.now()};this.draft=t;let i=this.scopedStorageKey(X);return!i||!Q(this.storage,i,t)?(this.draftPersistenceFailed=!0,this.showComposeError("This browser cannot persist the draft. It is still open on this page, but reloading or switching accounts could lose it."),this.updateResumeDraftAction(),!1):(this.draftPersistenceFailed=!1,this.updateResumeDraftAction(),!0)}clearDraft(){let e=this.scopedStorageKey(X);if(this.draft=null,this.composeState=null,this.draftFromHandoff)try{this.handoffStorage.removeItem(K)}catch{}if(this.draftFromHandoff=!1,e)try{this.storage.removeItem(e)}catch{}this.updateResumeDraftAction()}saveEditDraft(){let e=this.composeState?.editing?this.composeState:this.editDraft;if(!e?.cellId)return;let t={cellId:e.cellId,expectedVersion:Number(e.expectedVersion)||1,q:Number(e.q),r:Number(e.r),body:this.composeState?.editing&&this.composeBody&&this.compose.open?this.composeBody.value:e.body||"",requestId:e.requestId||null,updatedAt:Date.now()};this.editDraft=t;let i=this.scopedStorageKey(de);return!i||!Q(this.storage,i,t)?(this.editDraftPersistenceFailed=!0,this.showComposeError("This browser cannot persist the edit draft. It is still open on this page, but reloading or switching accounts could lose it."),!1):(this.editDraftPersistenceFailed=!1,!0)}clearEditDraft(){let e=this.scopedStorageKey(de);if(this.editDraft=null,this.editDraftPersistenceFailed=!1,e)try{this.storage.removeItem(e)}catch{}}markSeen(e){if(!e)return;this.seen.add(e),this.seen.size>800&&(this.seen=new Set([...this.seen].slice(-600)));let t=this.scopedStorageKey(Re);t&&Q(this.storage,t,[...this.seen]),this.updateNewCount(),this.root.querySelector(`#honey-cell-${CSS.escape(e)}`)?.classList.remove("is-unseen")}updateNewCount(){if(!this.newCount)return;let t=[...new Set([...this.cellsById.keys(),...this.pendingEvents.keys()])].filter(i=>!this.seen.has(i)).length;this.newCount.hidden=t===0,this.newCount.textContent=t?String(Math.min(t,99)):""}findNew(){let e=[...this.cells.values()].filter(t=>!this.seen.has(t.id)).sort((t,i)=>i.seq-t.seq)[0];if(!e){this.toast("No unread combs in the loaded wall yet.");return}this.openReader(e)}findMine(){let e=[...this.cells.values()].filter(t=>t.isMine).sort((t,i)=>i.seq-t.seq)[0];if(!e){this.toast(this.getUser()?"No combs from you are loaded here yet.":"Create a profile to find your combs."),this.getUser()||this.requestIdentity({reason:"wall-mine"});return}this.openReader(e)}setZoom(e,t=null,i={}){let s=this.zoom,o=this.clampZoom(e),n=this.stageSize(),r=t&&Number.isFinite(t.x)&&Number.isFinite(t.y)?t:{x:n.width/2,y:n.height/2},h=this.stageToWorld(r.x,r.y);return this.zoom=o,this.cameraX=r.x-n.width/2-h.x*o,this.cameraY=r.y-(this.world.originY+h.y)*o,this.clampCamera(),this.updatePlaneTransform(),this.updateTarget(),this.scheduleViewport(),i.announce&&o!==s&&this.announce(`Wall zoom ${Math.round(o*100)} percent.`),this.zoom}fitWall(e=!1){this.cancelGrowthIntent({restoreFocus:!1,announce:!1}),this.ensureStageOnScreen();let t=this.contentExtent();this.zoom=this.clampZoom(this.fitZoom());let i=this.cameraForFocus((t.minX+t.maxX)/2,(t.minY+t.maxY)/2);this.cameraX=i.x,this.cameraY=i.y,this.clampCamera(),this.updatePlaneTransform(),this.updateTarget(),this.scheduleViewport(),e&&this.announce(`The whole Hive is in view at ${Math.round(this.zoom*100)} percent zoom. ${this.bounds.messageCount} combs.`)}frameInitialPhoneView(){if(!this.stage||this.stage.hidden)return;let e=this.initialPhoneExtent();this.zoom=this.clampZoom(Math.min(1,this.zoomToFit(e)));let t=this.cameraForFocus((e.minX+e.maxX)/2,(e.minY+e.maxY)/2,this.zoom);this.cameraX=t.x,this.cameraY=t.y,this.clampCamera(),this.updatePlaneTransform(),this.updateTarget(),this.scheduleViewport()}ensureStageOnScreen(){let e=globalThis.window;if(!this.stage||this.stage.hidden||typeof e?.scrollTo!="function")return;let t=this.stage.getBoundingClientRect?.(),i=Number(e.visualViewport?.height)||e.innerHeight||0;if(!t?.height||!i||Math.min(t.bottom,i)-Math.max(t.top,0)>=Math.min(t.height,i)*.9)return;let o=Math.max(0,(i-t.height)/2);e.scrollTo({top:Math.max(0,t.top+(Number(e.scrollY)||0)-o),behavior:"auto"})}panBy(e,t){this.cameraX-=Number(e)||0,this.cameraY-=Number(t)||0,this.clampCamera(),this.updatePlaneTransform(),this.updateTarget(),this.scheduleViewport()}centerWall(e=!1){this.cancelGrowthIntent({restoreFocus:!1,announce:!1}),this.selected={q:0,r:0},this.revealCoordinate(0,0),e&&this.announce("Centered on the first comb.")}motionBehavior(e="smooth"){return e!=="smooth"?e:globalThis.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches?"auto":"smooth"}revealCoordinate(e,t,i="smooth"){this.selected={q:Number(e),r:Number(t)},this.ensureStageOnScreen();let s=N(e,t,this.hexRadius),o=this.visibleStageRect();this.setCameraForWorldPoint(s,(o.left+o.right)/2,(o.top+o.bottom)/2,i),this.updateTarget(),this.scheduleViewport()}setCameraForWorldPoint(e,t,i,s="auto"){let o=this.stageSize();this.cameraX=t-o.width/2-e.x*this.zoom,this.cameraY=i-(this.world.originY+e.y)*this.zoom,this.clampCamera(),this.applyCameraMotion(s),this.updatePlaneTransform()}applyCameraMotion(e="auto"){if(this.plane){if(this.motionBehavior(e)!=="smooth"){this.plane.classList.remove("is-gliding");return}this.plane.classList.add("is-gliding"),this.glideTimer&&window.clearTimeout(this.glideTimer),this.glideTimer=window.setTimeout(()=>{this.glideTimer=null,this.plane?.classList.remove("is-gliding"),this.scheduleViewport()},340)}}ensureCoordinateVisible(e,t,i="smooth"){if(this.growthIntent){this.scheduleViewport();return}this.ensureStageOnScreen();let s=N(e,t,this.hexRadius),o=this.visibleStageRect(),n=this.worldToStage(s.x,s.y),r=Math.min(180,o.width*.24),h=Math.min(180,o.height*.24),a=n.x<o.left+r||n.x>o.right-r,l=n.y<o.top+h||n.y>o.bottom-h;if(!a&&!l){this.scheduleViewport();return}this.setCameraForWorldPoint(s,a?(o.left+o.right)/2:n.x,l?(o.top+o.bottom)/2:n.y,i),this.updateTarget(),this.scheduleViewport()}setMode(e){this.placementIntentGeneration+=1,this.focusGeneration+=1;let t=this.mode;this.mode=e==="list"?"list":"wall";try{this.storage.setItem(xe,this.mode)}catch{}this.mode==="list"?(t!=="list"&&this.invalidatePublicProjectionCache(),this.applyMode(),this.refreshList(this.listCells.length===0).finally(()=>this.wakeListReconciliation())):(t==="list"?this.invalidatePublicProjectionCache():this.discardAccessibleListWindow(),this.applyMode(),this.scheduleViewport())}discardAccessibleListWindow(e=!0){this.listReconcileTimer&&window.clearTimeout(this.listReconcileTimer),this.listReconcileTimer=null,this.listReconcileEvents.clear(),this.listItems&&(this.listItems.textContent="Refreshing the authoritative Wall list\u2026"),this.listCells=[],this.listBeforeSeq=null,this.listHasMore=!0,this.listWindowRevision=0,e&&(this.listConversationId=null),this.listRequestGeneration+=1}applyMode(){if(!this.wall)return;let e=this.mode==="list";this.stage.hidden=e,this.list.hidden=!e,this.root.querySelector("[data-wall-edge-note]").hidden=e,this.wall.dataset.wallMode=e?"list":"wall";for(let t of this.root.querySelectorAll('[data-wall-action="mode"]'))t.textContent=e?"Return to wall":"Read as list",t.setAttribute("aria-pressed",String(e))}async refreshList(e=!1,t=null){let i=this.identityGeneration,s=this.publicCacheGeneration,o=++this.listRequestGeneration,n=this.listConversationId,r=t||this.captureAccessibleListView(!1),h=this.listCells.slice(),a=this.listBeforeSeq,l=this.listHasMore,c=e?null:a,u=e?!0:l,m=[],y=Number(this.listWindowRevision)||0,b=n?60:40,E=1;if(u)try{for(let I=0;I<E&&u;I+=1){let p=n?await this.backend.wallConversation(n,c,b):await this.backend.wallList(c,b);if(i!==this.identityGeneration||s!==this.publicCacheGeneration||o!==this.listRequestGeneration||n!==this.listConversationId)return;if(!p&&n)throw new Error("That conversation is no longer available.");if(!p?.bounds||!Number.isSafeInteger(Number(p.bounds.revision)))throw new Error("The wall list did not include an authoritative revision.");let q=Number(p.bounds.revision);if(q<Math.max(this.bounds.revision,this.listWindowRevision))throw new Error("The wall list returned an older snapshot.");let T=this.viewerProjectionAdvanced(p.bounds);if(!this.applyAuthoritativeBounds(p.bounds))throw new Error("The wall list returned an older snapshot.");if(T&&this.hasPublicProjection("list")){let w=this.captureAccessibleListView(!0);!w.focusKey&&r.focusKey&&Object.assign(w,r,{preserveScroll:!0}),this.invalidatePublicProjectionCache({resetConversation:!1}),await this.refreshList(!0,w);return}let S=new Set(h.map(w=>w?.id).filter(Boolean)),R=[...this.listReconcileEvents.values()].reduce((w,x)=>S.has(x?.cellId)?Math.max(w,Number(x?.revision)||0):w,Number(this.listWindowRevision)||0);if(q>R&&(h.length||this.cells?.size||this.conversations?.size||this.readerCell)){let w=this.captureAccessibleListView(!0);!w.focusKey&&r.focusKey&&Object.assign(w,r,{preserveScroll:!0}),this.invalidatePublicProjectionCache({resetConversation:!1}),await this.refreshList(!0,w);return}y=q,p?.conversation?.id&&this.conversations.set(p.conversation.id,p.conversation);let G=Array.isArray(p?.cells)?p.cells:[];for(let w of G){let x=this.mergeCell(w,{renderList:!1});x&&(m.push(x),this.listReconcileEvents.delete(x.id))}let f=p?.nextBeforeSeq||null;if(u=!!p?.hasMore,!G.length||f===c){c=f;break}c=f}if(i!==this.identityGeneration||s!==this.publicCacheGeneration||o!==this.listRequestGeneration||n!==this.listConversationId)return;this.listCells=fe(h,m,n);let k=ke({reset:e,priorCells:h,incomingCells:m,priorBeforeSeq:a,priorHasMore:l,nextBeforeSeq:c,nextHasMore:u});this.listBeforeSeq=k.beforeSeq,this.listHasMore=k.hasMore,this.listWindowRevision=y,this.root.querySelector('[data-wall-action="load-more"]').hidden=!this.listHasMore,this.renderList(),this.scheduleListReconciliation(this.activationGeneration,this.identityGeneration),this.restoreAccessibleListView(r,o,n)}catch(k){this.announce(`The wall list could not refresh: ${k.message}`),this.restoreAccessibleListView(r,o,n)}}renderList(){let e=this.root.querySelector("#honeyListTitle"),t=this.root.querySelector('[data-wall-action="list-all"]'),s=(this.listConversationId?this.conversations.get(this.listConversationId):null)?.participants?.map(a=>a.name).filter(Boolean)||[];g(e,this.listConversationId?s.length?`Conversation with ${s.join(", ")}`:"One Hive conversation":"Every comb with its connections"),t.hidden=!this.listConversationId;for(let a of[...this.listItems.childNodes])a.nodeType!==1&&a.remove();let o=new Map([...this.listItems.querySelectorAll("[data-wall-list-row]")].map(a=>[a.dataset.wallListRow,a])),n=new Set,r=this.listItems.firstElementChild;for(let a of this.listCells){n.add(a.id);let l=o.get(a.id);if(!l){l=document.createElement("article"),l.className="honey-list-item",l.dataset.wallListRow=a.id;let R=document.createElement("h3");R.dataset.wallListPart="heading";let G=document.createElement("p");G.className="honey-list-meta",G.dataset.wallListPart="meta";let f=document.createElement("p");f.className="honey-list-relation",f.dataset.wallListPart="relation";let w=document.createElement("p");w.dataset.wallListPart="body";let x=document.createElement("button");x.type="button",x.className="honey-tool",x.dataset.wallListPart="open",x.textContent="Open this comb";let D=document.createElement("button");D.type="button",D.className="honey-tool",D.dataset.wallListPart="conversation",D.textContent="Open conversation",l.append(R,G,f,w,x,D)}l.style.setProperty("--thread-hue",String(oe(a.conversationId))),l.dataset.threadPattern=String(Ie(a.conversationId));let c=l.querySelector('[data-wall-list-part="heading"]');g(c,a.author||"Open space kept");let u=l.querySelector('[data-wall-list-part="meta"]');g(u,`${a.membership==="alumni"?"DHG alumni":a.membership==="guest"?"Guest":"Hive"} \xB7 ${ue(a.createdAt)} \xB7 comb ${a.q}, ${a.r}`);let m=l.querySelector('[data-wall-list-part="body"]');g(m,ne(a));let y=l.querySelector('[data-wall-list-part="relation"]'),b=a.replyToId?this.cellsById.get(a.replyToId):null,E=a.growthParentId?this.cellsById.get(a.growthParentId):null,k=this.conversations.get(a.conversationId),I=(a.origin?.anchors||[]).map(R=>this.cellsById.get(R.cellId)?.author||"a nearby conversation"),p=a.replyToId?`Reply to ${b?.author||"another comb"}`:a.origin?.kind==="branch"?`New branch from ${I[0]||"a nearby conversation"}`:a.origin?.kind==="meet"?`Meeting point for ${I.length||2} nearby conversations${I.length?`: ${I.join(", ")}`:""}`:k?.rootCellId===a.id?"Conversation root":`Continuation from ${E?.author||"a nearby comb"}`,q=this.conversations.get(a.conversationId)?.participants?.map(R=>R.name).filter(Boolean).slice(0,6)||[];g(y,q.length?`${p} \xB7 Conversation: ${q.join(", ")}`:p);let T=l.querySelector('[data-wall-list-part="open"]');T.dataset.wallListCell=a.id,T.dataset.wallListFocus=`cell:${a.id}`,T.setAttribute("aria-label",`Open comb by ${a.author||"a Hive member"} at ${a.q}, ${a.r}. ${p}.`);let S=l.querySelector('[data-wall-list-part="conversation"]');S.dataset.wallListConversation=a.conversationId,S.dataset.wallListFocus=`conversation:${a.id}`,S.setAttribute("aria-label",`Open the conversation around ${a.author||`comb ${a.q}, ${a.r}`}${q.length?` with ${q.join(", ")}`:""}.`),l!==r&&this.listItems.insertBefore(l,r),r=l.nextElementSibling}for(let[a,l]of o)n.has(a)||l.remove();let h=this.listItems.querySelector(".honey-list-empty");this.listCells.length?h?.remove():(h||(h=document.createElement("p"),h.className="honey-list-empty",this.listItems.append(h)),g(h,"The wall is ready for its first comb."))}async openListConversation(e){if(!e)return;this.discardAccessibleListWindow(),this.listConversationId=e;let t=this.identityGeneration;await this.refreshList(!1),!(t!==this.identityGeneration||this.listConversationId!==e||this.mode!=="list")&&this.list?.focus({preventScroll:!0})}async showAllListMessages(){this.discardAccessibleListWindow();let e=this.identityGeneration;await this.refreshList(!1),!(e!==this.identityGeneration||this.listConversationId!==null||this.mode!=="list")&&this.list?.focus({preventScroll:!0})}async readAuthoritativeCell(e,t){for(let i=0;i<2;i+=1){let s=await this.backend.wallCell(e);if(!t())return null;if(!s?.cell||!s?.bounds||!Number.isSafeInteger(Number(s.bounds.revision)))continue;let o=this.viewerProjectionAdvanced(s.bounds);if(this.applyAuthoritativeBounds(s.bounds)){if(o&&this.hasPublicProjection()){let n=this.captureProjectionRebuild();return this.invalidatePublicProjectionCache({resetConversation:!1}),{rebuildRequired:!0,rebuild:n}}if(this.hasUnaccountedPublicRevision(Number(s.bounds.revision))){let n=this.captureProjectionRebuild();return this.invalidatePublicProjectionCache({resetConversation:!1}),{rebuildRequired:!0,rebuild:n}}return s}}return null}async openListCell(e,t=null,i=0){if(!e||this.mode!=="list")return!1;let s=++this.focusGeneration,o=this.activationGeneration,n=this.identityGeneration,r=this.publicCacheGeneration,h=this.listConversationId,a=()=>s===this.focusGeneration&&this.isContextCurrent(o,n)&&r===this.publicCacheGeneration&&this.mode==="list"&&h===this.listConversationId;try{let l=await this.readAuthoritativeCell(e,a);if(l?.rebuildRequired){if(await this.rebuildPublicProjection(l.rebuild),i>=1||this.mode!=="list"||h!==this.listConversationId)return!1;let u=t?.dataset?.wallListFocus,m=u?this.list?.querySelector(`[data-wall-list-focus="${se(u)}"]`):this.list;return this.openListCell(e,m||this.list,i+1)}if(!l||!a())return!1;l.conversation?.id&&this.conversations.set(l.conversation.id,l.conversation);let c=this.mergeCell(l.cell,{renderList:!1});return c?(this.renderList(),this.openReader(c,t),!0):!1}catch{return!1}}async focusCell(e,t={},i=0){let s=++this.focusGeneration,o=this.activationGeneration,n=this.identityGeneration,r=this.publicCacheGeneration;if(!this.isContextCurrent(o,n))return!1;let h=()=>s===this.focusGeneration&&this.isContextCurrent(o,n)&&r===this.publicCacheGeneration,a;try{a=await this.readAuthoritativeCell(e,h)}catch{return!1}if(a?.rebuildRequired)return await this.rebuildPublicProjection(a.rebuild),i>=1||!this.isContextCurrent(o,n)?!1:this.focusCell(e,t,i+1);if(!a||!h())return!1;let l=this.mergeCell(a.cell);if(!l||(a.conversation?.id&&this.conversations.set(a.conversation.id,a.conversation),s!==this.focusGeneration||!this.isContextCurrent(o,n)))return!1;this.setMode("wall");let c=this.focusGeneration;this.revealCoordinate(l.q,l.r);let u=await this.loadChunk(O(l.q,l.r),!0,Number(this.bounds.revision)||0);return c!==this.focusGeneration||!this.isContextCurrent(o,n)||!u?.ok?!1:(this.wallWindowRevision=Math.max(Number(this.wallWindowRevision)||0,Number(u.revision)||0),this.render(),t.open!==!1&&this.openReader(this.cellsById.get(l.id)||l),this.onCellLink&&this.onCellLink(l.id),!0)}nudgeAround(e){if(!globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches)for(let t of this.cells.values()){let i=W(t.q,t.r,e.q,e.r);if(i<1||i>3)continue;let s=this.nodes.get(v(t.q,t.r));if(!s)continue;let o=i===1?9:i===2?6:3,n=N(e.q,e.r,1),r=N(t.q,t.r,1),h=Math.hypot(r.x-n.x,r.y-n.y)||1;s.style.setProperty("--nudge-x",`${(r.x-n.x)/h*o}px`),s.style.setProperty("--nudge-y",`${(r.y-n.y)/h*o}px`),s.classList.remove("is-nudged"),s.offsetWidth,s.classList.add("is-nudged")}}announce(e){this.live&&(this.live.textContent="",this.announceFrame&&cancelAnimationFrame(this.announceFrame),this.announceFrame=requestAnimationFrame(()=>{this.announceFrame=null,this.live&&(this.live.textContent=e)}))}};function Ye(d){return new le(d)}return Ne(He);})(); |