@leonidstern/labit 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3608 @@
1
+ (() => {
2
+ // src/widget/styles.css
3
+ var styles_default = `/* Theme: set --lab-accent, --lab-accent-fg, --lab-bg, --lab-fg, --lab-radius, --lab-font or --lab-font-features on the
4
+ [data-lab-comments] element (or on :root). Everything else is mixed from those. */
5
+ :host { all: initial;
6
+ --_bg: var(--lab-bg, #fff); --_fg: var(--lab-fg, #141414);
7
+ --_accent: var(--lab-accent, #141414); --_accent-fg: var(--lab-accent-fg, #fff);
8
+ --_radius: var(--lab-radius, 12px); --_r-s: 6px /* two corners in all: 6 px small (keys, rows, tabs, text buttons), 12 px boxes and buttons; circles only for dots */;
9
+ /* Washes of black (white in dark mode), four steps: soft, hover, line, muted, as lab.css. */
10
+ --_soft: var(--lab-soft, rgba(0,0,0,.05)); --_hover: var(--lab-hover, rgba(0,0,0,.10)); --_line: var(--lab-line, rgba(0,0,0,.15)); --_edge: var(--lab-edge, #c7c7cc); --_muted: var(--lab-muted, rgba(0,0,0,.50));
11
+ --_hair: .5px solid color-mix(in srgb, var(--_fg) 16%, transparent);
12
+ --_shadow: 0 0 0 .5px color-mix(in srgb, var(--_fg) 14%, transparent), 0 1px 2px rgba(0,0,0,.04), 0 8px 28px rgba(0,0,0,.08);
13
+ --_ease: cubic-bezier(.2, .8, .2, 1); }
14
+ @media (prefers-color-scheme: dark) {
15
+ :host { --_bg: var(--lab-bg, #1c1c1e); --_fg: var(--lab-fg, #f4f4f5);
16
+ --_accent: var(--lab-accent, #f4f4f5); --_accent-fg: var(--lab-accent-fg, #141414);
17
+ --_soft: var(--lab-soft, rgba(255,255,255,.05)); --_hover: var(--lab-hover, rgba(255,255,255,.10)); --_line: var(--lab-line, rgba(255,255,255,.15)); --_edge: var(--lab-edge, #48484a); --_muted: var(--lab-muted, rgba(255,255,255,.50));
18
+ --_shadow: 0 0 0 1px color-mix(in srgb, var(--_fg) 16%, transparent), 0 10px 32px rgba(0,0,0,.5); }
19
+ }
20
+ * { box-sizing: border-box; font-family: var(--lab-font, system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif);
21
+ font-size: 14px; line-height: 1.4; font-weight: 400; color: var(--_fg); letter-spacing: -.011em;
22
+ font-feature-settings: var(--lab-font-features, normal); font-synthesis: none; font-optical-sizing: auto;
23
+ -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-rendering: optimizeLegibility;
24
+ caret-color: var(--_accent); -webkit-tap-highlight-color: transparent; }
25
+ ::selection { background: color-mix(in srgb, var(--_accent) 38%, transparent); color: var(--_fg); }
26
+ button:focus-visible { outline: 2px solid var(--_accent); outline-offset: 2px; }
27
+ .layer { position: absolute; top: 0; left: 0; width: 0; height: 0; }
28
+ .pin { position: absolute; width: 28px; height: 28px; margin: -28px 0 0 0; border-radius: 14px 14px 14px 2px;
29
+ background: var(--_bg); border: 0; box-shadow: 0 0 0 1px var(--_edge), 0 2px 8px rgba(0,0,0,.16);
30
+ display: grid; place-items: center; cursor: pointer; padding: 0; color: var(--_fg); font-size: 12px; font-weight: 500;
31
+ font-variant-numeric: tabular-nums; letter-spacing: 0; transform-origin: 0 100%;
32
+ transition: transform .16s var(--_ease), box-shadow .16s var(--_ease), opacity .16s; }
33
+ /* A 1 px edge in the text colour (dark on light pins, light in dark mode) so a pin shows on white and black alike;
34
+ the one you point at or have open gets a green edge. */
35
+ button.pin:hover, button.pin.open { transform: scale(1.08); box-shadow: 0 0 0 1.5px rgb(36, 160, 70), 0 4px 14px rgba(0,0,0,.2); }
36
+ button.pin:active { transform: scale(.96); }
37
+ .pin.in { animation: lab-pin .26s var(--_ease); }
38
+ /* A new comment lands with one faint halo from its pin. */
39
+ button.pin.in::before { content: ''; position: absolute; inset: 0; border-radius: inherit; pointer-events: none;
40
+ animation: lab-halo .9s cubic-bezier(.2, .7, .3, 1) forwards; }
41
+ .pin.resolved { color: var(--_muted); }
42
+ /* Statuses. A go pin says "go": green in a green outline when placed, the turning stroke while the agent is on it,
43
+ white on green once done (a \u2713 is only ever a done comment). A comment pin: your initial, the stroke, then a green tick. */
44
+ button.pin.go { background: var(--_bg); color: rgb(36, 160, 70); font-size: 11px; font-weight: 600; letter-spacing: .006em;
45
+ box-shadow: inset 0 0 0 1.5px rgb(36, 160, 70), 0 2px 8px rgba(0,0,0,.16); }
46
+ button.pin.go.done { background: rgb(36, 160, 70); color: #fff; box-shadow: 0 0 0 .5px color-mix(in srgb, var(--_fg) 22%, transparent), 0 2px 8px rgba(0,0,0,.16); }
47
+ button.pin.done:not(.go) { color: rgb(36, 160, 70); }
48
+ .pin.moved { opacity: .5; scale: .8; }
49
+ button.pin.moved:hover, button.pin.moved.open { opacity: 1; }
50
+ .pin.grab { touch-action: none; }
51
+ button.pin.dragging { cursor: grabbing; transform: scale(1.1); opacity: 1; box-shadow: 0 0 0 .5px color-mix(in srgb, var(--_fg) 30%, transparent), 0 8px 20px rgba(0,0,0,.22); }
52
+ .zone { position: absolute; background: none;
53
+ border-radius: var(--_radius); pointer-events: none; }
54
+ .zone svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }
55
+ .zone rect { fill: none; stroke-linecap: round; stroke-dasharray: 0 4; rx: var(--lab-radius, 12px); ry: var(--lab-radius, 12px); }
56
+ /* Green dots, the same green as quoted words, with no dark ring under them. */
57
+ .zone rect.ring { display: none; }
58
+ .zone rect.dots { stroke: rgb(52, 199, 89); stroke-width: 1.5; } /* 1.5 px round dots, 4 px apart */
59
+ .zone.live { left: 0; top: 0; will-change: transform, width, height; animation: lab-fade .12s ease-out; }
60
+ /* The agent is on it: a green stroke runs round the pin's own teardrop outline. The ring (a still 2 px teardrop mask)
61
+ holds a conic gradient that turns by transform, so the screen turns it without redrawing: 30 such pins cost ~1 ms
62
+ a second, against ~125 ms when the gradient's angle itself was animated. */
63
+ .pin .ring { position: absolute; inset: -4px; border-radius: 18px 18px 18px 6px; padding: 2px; overflow: hidden; pointer-events: none;
64
+ -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); -webkit-mask-composite: xor;
65
+ mask: linear-gradient(#000 0 0) content-box exclude, linear-gradient(#000 0 0); }
66
+ .ring::before { content: ''; position: absolute; inset: -50%; will-change: transform;
67
+ background: conic-gradient(rgb(52, 199, 89) 0 28%, rgba(52, 199, 89, .22) 28% 100%); animation: lab-turn 1.2s linear infinite; }
68
+ @keyframes lab-turn { to { transform: rotate(360deg); } }
69
+ /* The drawn pointer: your pin, following the mouse (it moves without a transition; only its look eases). */
70
+ .ptr { position: fixed; left: 0; top: 0; width: 28px; height: 28px; border-radius: 14px 14px 14px 2px; corner-shape: round;
71
+ background: var(--_bg); box-shadow: 0 0 0 .5px color-mix(in srgb, var(--_fg) 30%, transparent), 0 2px 6px rgba(0,0,0,.18);
72
+ display: grid; place-items: center; pointer-events: none; z-index: 2147483647; opacity: 0; will-change: transform;
73
+ transition: opacity .12s ease-out, background-color .16s ease-out; }
74
+ .ptr.show { opacity: 1; }
75
+ .ptr span { grid-area: 1 / 1; font-size: 12px; letter-spacing: 0; font-weight: 600; line-height: 1; transition: opacity .16s ease-out, transform .16s ease-out; }
76
+ .ptr .tick { opacity: 0; transform: scale(.5); color: #fff; font-size: 11px; letter-spacing: .006em; }
77
+ .ptr.go { background: rgb(36, 160, 70); }
78
+ .ptr.go .ini { opacity: 0; transform: scale(.5); }
79
+ .ptr.go .tick { opacity: 1; transform: none; }
80
+ .pin.new::after { content: ''; position: absolute; top: -4px; right: -4px; width: 9px; height: 9px; border-radius: 50%;
81
+ background: var(--_fg); box-shadow: 0 0 0 2px var(--_bg); }
82
+ .dot { display: inline-block; width: 6px; height: 6px; border-radius: 50%; background: var(--_accent); margin: 0 6px 1px 0; }
83
+ .card { position: absolute; width: 320px; max-width: calc(100vw - 24px); background: var(--_bg); border-radius: var(--_radius);
84
+ box-shadow: var(--_shadow); padding: 12px 14px 14px; transform-origin: 14px 0; z-index: 1;
85
+ display: flex; flex-direction: column; max-height: min(460px, 62vh); }
86
+ /* A long thread scrolls inside the card, which keeps one size; the step buttons and the reply box stay put. */
87
+ .card > .body { flex: 0 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; margin-right: -8px; padding-right: 8px; }
88
+ .card > .foot { flex: none; }
89
+ .card.in, .float.in { animation: lab-in .18s var(--_ease); }
90
+ .card.out, .float.out { animation: lab-out .14s ease-in forwards; pointer-events: none; }
91
+ .item { display: grid; row-gap: 3px; }
92
+ .item + .item { margin-top: 14px; }
93
+ .msg.item { display: block; } .msg.item + .msg.item { margin-top: 0; }
94
+ .meta { display: flex; align-items: baseline; gap: .5em; font-size: 12px; color: var(--_muted); margin: 0;
95
+ white-space: nowrap; letter-spacing: 0; font-variant-numeric: tabular-nums; }
96
+ .meta b { font-weight: 500; font-size: 13px; letter-spacing: -.006em; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
97
+ .meta .dot { flex: none; align-self: center; margin: 0; }
98
+ .meta .ago { white-space: nowrap; }
99
+ .text { white-space: pre-wrap; overflow-wrap: anywhere; text-wrap: pretty; }
100
+ .row { display: flex; gap: 12px; justify-content: flex-start; align-items: center; margin-top: 8px; }
101
+ /* A thread's reopen / resolve / delete: small, on the right, out of the reading flow. */
102
+ .card .row:not(.nav) { justify-content: flex-end; gap: 10px; } .card .row:not(.nav) button.btn { font-size: 12px; letter-spacing: 0; }
103
+ button.btn { border: 0; padding: 2px 0; cursor: pointer; background: none; color: var(--_muted); font-size: 12px;
104
+ letter-spacing: 0; border-radius: var(--_r-s); transition: color .12s; }
105
+ button.btn:hover { color: var(--_fg); }
106
+ button.btn.danger, button.btn.danger:hover { color: #e5484d; }
107
+ .row .ask { white-space: nowrap; color: var(--_fg); font-size: 12px; letter-spacing: 0; padding: 2px 0; animation: lab-fade .12s ease-out; }
108
+ .float { position: absolute; width: 320px; max-width: calc(100vw - 24px); transform-origin: 0 20px; z-index: 1; }
109
+ .card .composer { margin-top: 6px; } /* close under resolve / delete */
110
+ .card > .body > .row:not(.nav) { margin-right: 7px; } /* resolve / delete end where the send button does */
111
+ .box { display: grid; grid-template-columns: 1fr auto; grid-template-areas: "text send"; align-items: center; column-gap: 8px;
112
+ border-radius: var(--_radius); padding: 7px 7px 7px 14px; margin: 0; transition: box-shadow .15s;
113
+ /* One box for the chat, threads and new comments: its look comes only from these two, which a place sets on
114
+ its container (never by restyling the box, idle or typing), so the three can't drift apart (Leo, 15 Nov). */
115
+ background: var(--_box-bg, var(--_soft)); box-shadow: var(--_box-edge, none); }
116
+ /* The new comment box on a computer floats over the page: the page's colour, the pins' 1 px edge in the text colour
117
+ (it shows on white and black pages alike) and a soft shadow. */
118
+ .float { --_box-bg: var(--_bg); --_box-edge: 0 0 0 1px var(--_edge), 0 1px 2px rgba(0,0,0,.06), 0 8px 26px rgba(0,0,0,.14); }
119
+ /* Same top and right padding open or closed: the text and the arrow's column stay put while the box grows. */
120
+ .box.open { grid-template-areas: "text text" "line line" "who send"; row-gap: 8px; padding: 7px 7px 8px 14px; }
121
+ /* One line of text is exactly as tall as the send button (20 + 2 + 2 = 24), so the text and the button share one middle. */
122
+ .box textarea { grid-area: text; width: 100%; border: 0; background: none; padding: 2px 0; line-height: 20px; margin: 0; resize: none;
123
+ min-height: 0; max-height: 200px; overflow-y: auto; outline: none; display: block; }
124
+ .box textarea::placeholder, .who input::placeholder { color: var(--_muted); opacity: 1; }
125
+ .line { grid-area: line; height: 0; border-top: var(--_hair); margin: 0 -7px 0 -14px; display: none; }
126
+ .who { grid-area: who; display: none; align-items: baseline; gap: 4px; min-width: 0; font-size: 13px; color: var(--_muted); letter-spacing: -.006em; }
127
+ .who * { font-size: 13px; letter-spacing: -.006em; }
128
+ .who span { color: var(--_muted); }
129
+ .who input { flex: 1; min-width: 0; border: 0; background: none; padding: 0; margin: 0; outline: none; color: var(--_muted); text-overflow: ellipsis; }
130
+ .who input:focus { color: var(--_fg); }
131
+ .box.open .line { display: block; animation: lab-fade .16s ease-out; }
132
+ .box.open .who { display: flex; animation: lab-fade .16s ease-out; }
133
+ /* One line once your name is known: text, a quiet "as <name>" (still editable) and the arrow, side by side.
134
+ The text grows upward; the name and arrow stay on its last line. Only a first comment, with no name yet, opens
135
+ the second row to ask for it. */
136
+ .box.one, .box.one.open { grid-template-columns: minmax(0, 1fr) auto auto; grid-template-areas: "text who send"; align-items: end; row-gap: 0; padding: 7px 7px 7px 14px; }
137
+ .box.one .line { display: none !important; }
138
+ .box.one .who { align-self: end; line-height: 20px; padding-bottom: 2px; max-width: 40%; } /* the text's last line box, so they share a line */
139
+ .box.one .who input { flex: none; field-sizing: content; min-width: 2ch; max-width: 9em; }
140
+ .send { grid-area: send; width: 24px; height: 24px; border-radius: 50%; border: 0; padding: 0; cursor: pointer;
141
+ background: var(--_hover); color: var(--_muted); display: grid; place-items: center; transition: background .15s, color .15s, transform .15s var(--_ease); }
142
+ .send.ready:hover { transform: scale(1.06); }
143
+ .send.ready:active { transform: scale(.94); }
144
+ .send.ready { background: var(--_accent); color: var(--_accent-fg); }
145
+ /* The send sign: a paper plane, one filled shape cut with clip-path (crisp at any size, no joins); it flies off on send. */
146
+ .send .arr { display: block; position: relative; left: -1px; width: 12px; height: 11px; background: currentColor; clip-path: polygon(0 42%, 100% 0, 66% 100%, 46% 60%); }
147
+ .send * { color: inherit; }
148
+ .error { color: #e5484d; font-size: 12px; padding: 6px 8px 0; letter-spacing: 0; }
149
+ .error:empty { display: none; }
150
+ .error.wait { color: var(--_muted); }
151
+ .bar { position: fixed; right: 16px; bottom: 16px; display: flex; gap: 8px; align-items: center; }
152
+ .bar button { border: 0; border-radius: var(--_radius); padding: 9px 14px; cursor: pointer; background: var(--_bg); color: var(--_fg);
153
+ box-shadow: var(--_shadow); font-size: 13px; font-weight: 500; display: inline-flex; gap: 8px; align-items: center;
154
+ letter-spacing: -.006em; font-variant-numeric: tabular-nums; white-space: nowrap; transition: color .15s, transform .15s var(--_ease); }
155
+ .bar button:active { transform: scale(.97); }
156
+ /* The list and the chat: a header, a part that scrolls, and (the chat) a box at the bottom that doesn't. */
157
+ .list { position: fixed; right: 16px; bottom: 66px; width: min(340px, calc(100vw - 32px)); max-height: min(60vh, 460px); overflow: hidden;
158
+ display: flex; flex-direction: column; background: var(--_bg); color: var(--_fg); border-radius: var(--_radius); box-shadow: var(--_shadow); font-size: 13px; letter-spacing: -.006em; }
159
+ .list .tabs { display: flex; flex-wrap: wrap; gap: 2px; flex: none; padding: 12px 8px 6px; }
160
+ .list .items, .msgs { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; }
161
+ .list .items { padding: 0 6px 6px; }
162
+ .list .tabs button { border: 0; border-radius: var(--_r-s); padding: 4px 8px; white-space: nowrap; background: none; color: var(--_muted); cursor: pointer; font: inherit; }
163
+ .list .tabs button.on { background: var(--_fg); color: var(--_bg); }
164
+ .list .tabs .hold { margin-left: auto; }
165
+ .list .it { display: block; width: 100%; text-align: left; border: 0; background: none; color: inherit; padding: 7px 8px; border-radius: var(--_r-s); cursor: pointer; font: inherit; }
166
+ .list .it:hover, .list .it.cur { background: var(--_hover); }
167
+ .list .it { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } /* one line per pin; the rest is in its thread */
168
+ .list .it span, .list .none { color: var(--_muted); }
169
+ .list .it .tag { display: inline-block; padding: 0 7px; border-radius: var(--_r-s); background: var(--_accent); color: var(--_accent-fg);
170
+ font-size: 12px; letter-spacing: 0; font-weight: 600; line-height: 18px; vertical-align: 1px; white-space: nowrap; }
171
+ .list .none { padding: 8px; }
172
+ /* Thin scrollbars inside the dialogs (chat, threads, the list), like macOS overlay ones, on a clear track. */
173
+ * { scrollbar-width: thin; scrollbar-color: color-mix(in srgb, var(--_fg) 24%, transparent) transparent; }
174
+ @supports not (scrollbar-width: thin) {
175
+ ::-webkit-scrollbar { width: 6px; height: 6px; }
176
+ ::-webkit-scrollbar-track { background: transparent; }
177
+ ::-webkit-scrollbar-thumb { background: color-mix(in srgb, var(--_fg) 24%, transparent); border-radius: 999px; }
178
+ }
179
+ .list .group { font-size: 11px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--_muted); padding: 10px 8px 2px; }
180
+ .pin.held { border: 1.5px dashed var(--_muted); opacity: .85; }
181
+ /* Close: a round, quiet button with a drawn cross (not the \u2715 character), darker on hover. */
182
+ .list .tabs .show-done { color: var(--_muted); }
183
+ .chatwin .tabs b { display: none; } /* no "chat" title: the window speaks for itself */
184
+ .list .tabs .x { margin-left: auto; flex: none; width: 26px; height: 26px; padding: 0; border-radius: 50%; display: grid; place-items: center;
185
+ font-size: 0; color: var(--_muted); background: transparent; }
186
+ /* The cross is drawn with CSS: two thin bars, no picture. */
187
+ .list .tabs .x::before, .list .tabs .x::after { content: ''; grid-area: 1 / 1; width: 12px; height: 1.6px; border-radius: 1px; background: currentColor; transform: rotate(45deg); }
188
+ .list .tabs .x::after { transform: rotate(-45deg); }
189
+ .list .tabs .x:hover { color: var(--_fg); } /* hover: the cross darkens, nothing drawn behind it */
190
+ .list .tabs .x:focus-visible { outline: 2px solid var(--_accent); outline-offset: 1px; }
191
+ .chatwin .chat { flex: none; background: var(--_bg); padding: 6px 6px 8px; }
192
+ .chatwin .replying { flex: none; }
193
+ .chatwin .tabs b { padding: 4px 8px; font-weight: 600; margin-right: auto; }
194
+ .msgs { display: flex; flex-direction: column; gap: 8px; padding: 4px 10px 8px; overflow-x: hidden; }
195
+ .msgs > :first-child { margin-top: auto; } /* a short conversation sits by the box, like a chat */
196
+ /* Something just sent eases in; the arrow flies off and comes back. */
197
+ .fresh { animation: lab-rise .2s var(--_ease); }
198
+ .send.sent .arr { animation: lab-fly .32s var(--_ease); }
199
+ @keyframes lab-rise { from { opacity: 0; transform: translateY(6px); } }
200
+ @keyframes lab-fly { 45% { transform: translate(9px, -9px) scale(.6); opacity: 0; } 46% { transform: translate(-7px, 7px) scale(.6); opacity: 0; } }
201
+ .msg { max-width: 85%; padding: 7px 10px; border-radius: var(--_radius); background: var(--_soft); align-self: flex-start; }
202
+ .msg.mine { align-self: flex-end; background: color-mix(in srgb, rgb(52, 199, 89) 15%, var(--_bg)); color: var(--_fg); } /* yours: soft green, dark text */
203
+ .msg b { display: block; font-size: 12px; letter-spacing: 0; font-weight: 600; opacity: .7; margin-bottom: 1px; }
204
+ /* Each agent's messages in its own brand colour: the name in it, the bubble a soft wash of it (Leo, 15 Nov). */
205
+ .msg[data-agent=claude] { --_brand: #d97757; } .msg[data-agent=codex] { --_brand: #10a37f; } .msg[data-agent=cursor] { --_brand: #8a8a8e; }
206
+ .msg[data-agent=gemini] { --_brand: #4285f4; } .msg[data-agent=copilot] { --_brand: #8957e5; } .msg[data-agent=amp] { --_brand: #f34e3f; }
207
+ .msg[data-agent=opencode] { --_brand: #8a8a8e; }
208
+ .msg[data-agent] { background: color-mix(in srgb, var(--_brand) 11%, var(--_bg)); }
209
+ .msg[data-agent] > b { color: var(--_brand); opacity: 1; }
210
+ .msg.mine b { display: none; }
211
+ .msg { position: relative; } .mark { font-weight: 400; font-size: 11px; letter-spacing: .006em; color: var(--_muted); margin-left: 6px; white-space: nowrap; } .mark.done { color: rgb(36, 160, 70); font-weight: 600; font-size: 12px; letter-spacing: 0; } /* a small green tick, as the ticks on messages */
212
+ .msg .quote { display: block; border-left: 2px solid rgb(52, 199, 89); padding: 1px 0 1px 8px; margin: 3px 0 5px; font-size: 12px; letter-spacing: 0; line-height: 1.35;
213
+ color: var(--_muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: pointer; }
214
+ .msg .quote b { display: block; font-size: 12px; letter-spacing: 0; font-weight: 600; color: rgb(36, 160, 70); opacity: 1; margin: 0; } .mine .mark { color: inherit; opacity: .7; } a.link { color: inherit; text-decoration: underline; text-underline-offset: 2px; overflow-wrap: anywhere; } .msg.to { box-shadow: 0 0 0 2px var(--_accent); }
215
+ .msg .p { display: block; white-space: pre-wrap; overflow-wrap: anywhere; text-wrap: pretty; } /* no lone last word */ .msg .p.gap { margin-top: 6px; }
216
+ .msg .p.li { padding-left: 14px; text-indent: -14px; } .msg .p.li .mk { display: inline-block; width: 14px; text-indent: 0; opacity: .6; }
217
+ .msg i { display: block; font-style: normal; font-size: 12px; letter-spacing: 0; opacity: .7; margin-bottom: 1px; }
218
+ .msg b, .msg i { color: inherit; }
219
+ .msg .stamp { text-indent: 0; color: inherit; position: absolute; right: 10px; bottom: 6px; font-size: 10px; letter-spacing: .012em; line-height: 1; opacity: .55; font-variant-numeric: tabular-nums; }
220
+ .msg .stamp-room { text-indent: 0; visibility: hidden; display: inline-block; margin-left: 10px; font-size: 10px; letter-spacing: .012em; line-height: 1; height: 10px; white-space: nowrap; }
221
+ .msg .stamp-room * { font-size: inherit; }
222
+ .msg .tick { color: inherit; margin-left: 4px; letter-spacing: -.34em; font-size: 10px; } /* \u2713 drawn as tall as the time's digits */
223
+ .msg .tick.got { font-weight: 600; }
224
+ /* Your message the agent is on: the pin's turning green ring, small, by its time; answered: a green \u2713. */
225
+ .msg .stamp:is(.busy, .ans) { opacity: 1; } .msg .stamp:is(.busy, .ans) .tm { opacity: .55; }
226
+ .msg .stamp .tm { font-size: inherit; line-height: inherit; color: inherit; } /* every element gets 14 px by default: the time keeps the stamp's 10 */
227
+ .msg :is(.stamp, .stamp-room) .ring { position: relative; display: inline-block; width: 9px; height: 9px; margin-left: 5px; vertical-align: -1px; border-radius: 50%; overflow: hidden;
228
+ -webkit-mask: radial-gradient(farthest-side, transparent calc(100% - 1.6px), #000 calc(100% - 1.5px));
229
+ mask: radial-gradient(farthest-side, transparent calc(100% - 1.6px), #000 calc(100% - 1.5px)); }
230
+ .msg .stamp.ans .tick { color: rgb(36, 160, 70); letter-spacing: 0; font-weight: 600; }
231
+ /* One slot for the mark, whatever it is (\u2713, \u2713\u2713, the turning ring, the green \u2713): 12 px wide after a 4 px gap, so the
232
+ time doesn't shift when one turns into another (Leo, 15 Nov: it flicked as \u2713 became the ring). */
233
+ .msg :is(.stamp, .stamp-room) .tick { display: inline-block; width: 12px; height: 10px; line-height: 10px; text-align: center; margin-left: 4px; vertical-align: top; }
234
+ .msg :is(.stamp, .stamp-room) .ring { margin: .5px 1.5px 0 5.5px; vertical-align: top; } /* the same 10 px tall as a \u2713, so the bubble keeps its height */
235
+ .msg .stamp { height: 10px; }
236
+ .replying { display: flex; gap: 6px; align-items: center; font-size: 12px; letter-spacing: 0; color: var(--_muted); padding: 2px 6px; }
237
+ .replying button { border: 0; background: none; color: inherit; cursor: pointer; margin-left: auto; font: inherit; }
238
+ .bar button * { color: inherit; font-weight: inherit; }
239
+ .bar .toggle:not(.secondary)::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--_accent); }
240
+ .bar button.secondary { color: var(--_muted); }
241
+ .bar button.secondary.has-new { color: var(--_fg); font-weight: 600; }
242
+ .bar button.go-btn.on { color: #fff; background: rgb(36, 160, 70); }
243
+ .bar .new-prev, .bar .new-next { padding: 9px 11px; font-size: 15px; letter-spacing: -.016em; line-height: 1; color: var(--_fg); }
244
+ .bar .list-btn, .bar .done-btn { font-variant-numeric: tabular-nums; min-width: 4.6em; justify-content: center; }
245
+ .bar button.quiet { opacity: .45; cursor: default; box-shadow: var(--_shadow); }
246
+ .bar button.go-btn.on kbd { color: #fff !important; }
247
+ .newline { display: flex; align-items: center; gap: 8px; font-size: 12px; letter-spacing: 0; font-weight: 500; color: var(--_muted); }
248
+ .newline::before, .newline::after { content: ''; flex: 1; height: 1px; background: currentColor; opacity: .35; }
249
+ /* The left side: who's listening, then copy link; the right side is the bar. */
250
+ .left { position: fixed; left: 16px; bottom: 16px; display: flex; gap: 8px; align-items: center; }
251
+ .left .copy-all { border: 0; border-radius: var(--_radius); padding: 9px 14px; cursor: pointer; background: var(--_bg); color: var(--_muted);
252
+ box-shadow: var(--_shadow); font: inherit; font-size: 13px; letter-spacing: -.006em; font-weight: 500; white-space: nowrap; }
253
+ .listener { display: inline-flex; gap: 6px; align-items: center; padding: 9px 14px; border-radius: var(--_radius);
254
+ background: var(--_bg); color: var(--_fg); box-shadow: var(--_shadow); font-size: 13px; letter-spacing: -.006em; text-decoration: none; white-space: nowrap; }
255
+ .listener::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--_accent); margin-right: 2px; }
256
+ .listener span { color: var(--_muted); }
257
+ .listener.idle::before { background: var(--_muted); opacity: .5; }
258
+ /* Working: the dot turns green and sends out a soft ring, like a "live" light. */
259
+ /* The ping is a copy of the dot that grows and fades (transform and opacity only), so only it is redrawn. A growing
260
+ shadow repainted the whole layer with every pin on it, each frame: ~170 ms a second on a page with 40 pins. */
261
+ .listener { position: relative; }
262
+ .listener.working::before { background: rgb(36, 160, 70); }
263
+ .listener.working::after { content: ''; position: absolute; left: 14px; top: 50%; width: 7px; height: 7px; margin-top: -3.5px;
264
+ border-radius: 50%; corner-shape: round; background: rgb(52, 199, 89); pointer-events: none; will-change: transform, opacity; animation: lab-ping 1.6s cubic-bezier(0, 0, .2, 1) infinite; }
265
+ @keyframes lab-ping { 0% { transform: scale(1); opacity: .55; } 80%, 100% { transform: scale(2.7); opacity: 0; } }
266
+ .listener { cursor: default; } /* a plain arrow, also where a tap copies the resume command */
267
+ /* Letter spacing follows the size, as Apple's SF text does: looser below 12 px, tighter above (11 +.006em,
268
+ 13 \u2212.006, 15 \u2212.016, 17 \u2212.025). Uppercase labels and the \u2713\u2713 overlap keep their own. */
269
+ /* Keys whisper: a small grey letter, no chip; a bit clearer while the pointer is on the bar. */
270
+ kbd { font-size: 10px; letter-spacing: .012em; line-height: 17px; min-width: 0; padding: 0 1px; text-align: center; background: none;
271
+ color: var(--_muted) !important; opacity: .45; transition: opacity .15s; }
272
+ .bar:hover kbd { opacity: .75; }
273
+ .bar button kbd { margin-left: -4px; } /* the hint sits close to its word: chat (c) */
274
+ .bar button.go-btn kbd { font-size: inherit; line-height: inherit; opacity: 1; margin-left: 0; } /* (1/2/3) reads like (c)hat and ne(w) */
275
+ /* One bar of segments, a hairline between them; the less used ones in the \u22EF menu above it (phones too: same bar, bigger to tap). */
276
+ @media all {
277
+ .bar { gap: 0; background: var(--_bg); border-radius: var(--_radius); box-shadow: var(--_shadow); overflow: hidden; }
278
+ .bar > button { box-shadow: inset .5px 0 0 var(--_line); border-radius: 0; background: none; padding: 8px 12px; gap: 6px; }
279
+ .bar > button.first { box-shadow: none; }
280
+ .bar > button:not(:disabled):hover { background: var(--_hover); }
281
+ .bar > button:active { transform: none; background: var(--_hover); }
282
+ .bar > button.quiet { opacity: 1; box-shadow: inset .5px 0 0 var(--_line); color: var(--_muted); }
283
+ .bar > button.quiet.first { box-shadow: none; }
284
+ .bar .list-btn, .bar .done-btn { min-width: 0; }
285
+ .bar .mn { color: var(--_muted); font-weight: 400; }
286
+ /* Words stay grey (as the bar's buttons were); the count is the one thing in the text colour: a plain number. */
287
+ .bar > button.secondary, .bar > button.secondary.has-new { color: var(--_muted); font-weight: 500; }
288
+ .bar .chat-btn, .bar .list-btn { align-items: baseline; } /* the number sits on the word's line */
289
+ .bar .cnt { font-size: 12px; letter-spacing: 0; font-weight: 400; line-height: 16px; text-align: center; background: none; color: var(--_fg); font-variant-numeric: tabular-nums; }
290
+ .bar .cnt.zero { color: var(--_muted); }
291
+ .bar button.go-btn.on { background: none; color: var(--_fg); }
292
+ .bar button.go-btn.on kbd { color: var(--_muted) !important; }
293
+ .gp { display: inline-grid; place-items: center; width: 22px; height: 22px; border-radius: 11px 11px 11px 2px; font-size: 10px; letter-spacing: .012em; font-weight: 600;
294
+ color: rgb(36, 160, 70); box-shadow: inset 0 0 0 1.25px rgb(36, 160, 70); transition: background-color .2s, color .2s; }
295
+ .go-btn.on .gp { background: rgb(36, 160, 70); color: #fff; }
296
+ /* 1, comment: your own pin, small: your initial in a white pin with the pins' edge. */
297
+ .go-btn:not(.on):not(.cursor) .gp { color: var(--_fg); background: var(--_bg); box-shadow: inset 0 0 0 1px var(--_edge); font-size: 10px; letter-spacing: .012em; }
298
+ /* 3, cursor: the switch is the same pin in grey, saying "off" (regular, a touch bigger than go's bold). */
299
+ .go-btn.cursor .gp { box-shadow: inset 0 0 0 1.25px var(--_muted); color: transparent; position: relative; }
300
+ .go-btn.cursor .gp::after { content: 'off'; position: absolute; inset: 0; display: grid; place-items: center; color: var(--_muted);
301
+ font-size: 10px; font-weight: 400; letter-spacing: .012em; }
302
+ .more { font-size: 15px !important; letter-spacing: .05em; }
303
+ .more-menu { position: fixed; right: 16px; bottom: 60px; display: grid; min-width: 180px; padding: 4px; background: var(--_bg);
304
+ border-radius: var(--_radius); box-shadow: var(--_shadow); animation: lab-fade .12s ease-out; }
305
+ .more-menu[hidden] { display: none; }
306
+ .more-menu button { border: 0; background: none; text-align: left; font: inherit; font-size: 13px; letter-spacing: -.006em; color: var(--_fg); padding: 7px 10px;
307
+ border-radius: var(--_r-s); cursor: pointer; display: flex; justify-content: space-between; align-items: center; gap: 12px; white-space: nowrap; }
308
+ .more-menu button:hover:not(:disabled) { background: var(--_hover); }
309
+ .more-menu button:disabled { color: var(--_muted); cursor: default; }
310
+ .more-menu button[hidden] { display: none; }
311
+ .more-menu kbd { margin: 0; }
312
+ }
313
+ kbd::before { content: '('; } kbd::after { content: ')'; } /* read as a hint: chat (c) */
314
+ .hint { position: fixed; left: 50%; bottom: 64px; transform: translateX(-50%); background: var(--_bg); color: var(--_muted);
315
+ box-shadow: var(--_shadow); padding: 8px 14px; border-radius: var(--_radius); font-size: 13px; pointer-events: none; white-space: nowrap;
316
+ letter-spacing: -.006em; animation: lab-fade .2s ease-out; }
317
+ /* 16px fields keep iOS from zooming the page when one is focused. */
318
+ @media (pointer: coarse) { .box textarea, .who input { font-size: 16px; letter-spacing: -.019em; } kbd { display: none; }
319
+ .box textarea { line-height: 22px; padding: 7px 0; } /* phones: 22 + 7 + 7 = 36, the send button's size */
320
+ .box.one .who { line-height: 22px; padding-bottom: 7px; } }
321
+ @keyframes lab-fade { from { opacity: 0; } }
322
+ /* Movement only: a page in the background can stall an animation, and a card stalled mid-fade showed the page through it. */
323
+ @keyframes lab-in { from { transform: translateY(4px) scale(.98); } }
324
+ @keyframes lab-sheet-in { from { transform: translateY(100%); } }
325
+ @keyframes lab-sheet-out { to { transform: translateY(100%); } }
326
+ @keyframes lab-out { to { opacity: 0; transform: translateY(2px) scale(.985); } }
327
+ /* Continuous (Apple-style) corners where the browser draws them; plain rounding elsewhere. */
328
+ /* Apple's continuous corners (squircle) where the browser draws them (Safari 26, Chrome): the same three sizes, a
329
+ smooth curve instead of a circle arc (a squircle needs about 1.8 times the radius to look the same size).
330
+ Circles and the pin's teardrop stay as they are. */
331
+ @supports (corner-shape: squircle) {
332
+ :host { --_radius: calc(var(--lab-radius, 12px) * 1.8); --_r-s: 11px; }
333
+ *, *::before, *::after { corner-shape: squircle; }
334
+ .pin, .pin .ring, .pin.new::after, .dot, .send, .list .tabs .x, .bar .toggle:not(.secondary)::before,
335
+ .listener::before, .list-btn[data-agent]::before, .chat-btn[data-agent]::before, .msg :is(.stamp, .stamp-room) .ring, .gp { corner-shape: round; } /* circles stay circles */
336
+ }
337
+ @keyframes lab-pin { from { transform: scale(1.1); } }
338
+ @keyframes lab-halo { from { box-shadow: 0 0 0 0 color-mix(in srgb, var(--_fg) 12%, transparent); }
339
+ to { box-shadow: 0 0 0 16px color-mix(in srgb, var(--_fg) 0%, transparent); } }
340
+ @media (prefers-reduced-motion: reduce) { *, *::before, *::after { animation: none !important; transition: none !important; } }
341
+ @media (max-width: 480px) { kbd { display: none; } }
342
+ .handle { display: none; }
343
+ /* Phones: a thread or a new comment opens as a sheet from the bottom, full width, instead of beside the pin. */
344
+ @media (pointer: coarse) and (max-width: 560px), (pointer: coarse) and (max-height: 500px) { /* phones, upright or on their side */
345
+ /* Sheets fit what the screen shows (--lab-vh, the visible height, and --lab-kb, the keyboard over the page's
346
+ bottom, are kept up to date from visualViewport); their bottom part is solid down past the screen's edge,
347
+ behind the home bar, the keyboard and Safari's toolbar, so nothing of the page shows below the box. */
348
+ :host { --_safe: env(safe-area-inset-bottom, 0px); --_kb: var(--lab-kb, 0px);
349
+ --_sheet-max: calc(min(72dvh, var(--lab-vh, 100dvh) - 24px) + var(--_kb)); --_pb: calc(12px + var(--_safe) + var(--_kb)); }
350
+ :host([data-kb]) { --_safe: 0px; --_kb: 0px; --_pb: 10px; }
351
+ /* Keyboard up: a thread, the list and the chat fill exactly what the screen shows, like a native composer, so iOS
352
+ panning the page can't push it up and nothing of the page shows above or below it. */
353
+ :host([data-kb]) :is(.card, .list:not([hidden])) { top: var(--lab-top, 0px) !important; bottom: auto !important;
354
+ height: var(--lab-vh, 100dvh) !important; max-height: none !important; border-radius: 0; }
355
+ /* A new comment stays small, just above the keyboard, with the page (dimmed) above it: you see what you comment on. */
356
+ :host([data-kb]) .float { top: auto !important; bottom: var(--lab-kb, 0px) !important; height: auto !important; border-radius: var(--_radius) var(--_radius) 0 0; }
357
+ .card, .float { position: fixed; left: 0 !important; right: 0; top: auto !important; bottom: 0; width: auto; max-width: none;
358
+ max-height: var(--_sheet-max); display: flex; flex-direction: column; border-radius: var(--_radius) var(--_radius) 0 0; padding: 8px 0 0; z-index: 3; }
359
+ .card::after, .float::after, .list::after { content: ''; position: absolute; left: 0; right: 0; top: 100%; height: 100vh; background: var(--_bg); }
360
+ /* The same 12 px sides as the chat's, so a thread's reply box sits exactly where the chat's message box does. */
361
+ .card > .body { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; padding: 0 12px 4px; margin-right: 0; }
362
+ /* A thread keeps one height, as the chat does (Leo, 15 Nov: it jumped while the chat stays put): the sheet's full
363
+ height whatever its length, a short thread sitting by the reply box, so new replies and the keyboard never
364
+ move its top. */
365
+ .card { height: var(--_sheet-max); }
366
+ .card > .foot, .float > .composer { flex: none; padding: 0 12px var(--_pb); }
367
+ .card > .foot { margin-top: 0; padding-top: 6px; }
368
+ .card .composer { margin-top: 0; }
369
+ .card > .nav { flex: none; margin: -6px 0 0; padding: 0 12px; gap: 20px; }
370
+ .card .nav .btn { font-size: 14px; letter-spacing: -.011em; padding: 0 2px; min-height: 44px; display: inline-flex; align-items: center; } /* 44 px tall to tap (iOS 44 pt) */
371
+ .card .nav { gap: 16px; }
372
+ .card .nav { flex-wrap: wrap; row-gap: 0; } /* too narrow for one row: reopen / delete drop under, on the right */
373
+ .card .nav .acts { margin: 0 0 0 auto; gap: 20px; }
374
+ .box.one .who span { font-size: 16px; letter-spacing: -.019em; } /* "as" the size of the name beside it */ /* reopen / delete share the prev / next row, on the right */
375
+ .card .nav .acts button.btn { font-size: 14px; letter-spacing: -.011em; }
376
+ .float { background: var(--_bg); box-shadow: var(--_shadow); }
377
+ /* The grab handle: the sheet's top strip, where a drag down moves it. The header of the list and the chat does the same. */
378
+ /* Reaching 60 px above the sheet's edge over the dimmed page (Leo, 15 Nov: "the whole top and a bit above", then
379
+ "do more"); the bar and the layout stay as they were. The chat's and the list's header reach up the same way. */
380
+ .handle { display: block; flex: none; height: 86px; margin-top: -68px; touch-action: none; position: relative;
381
+ background: linear-gradient(color-mix(in srgb, var(--_fg) 18%, transparent) 0 0) center 68px / 36px 4px no-repeat; }
382
+ .list .tabs { position: relative; }
383
+ .list .tabs::before { content: ''; position: absolute; left: 0; right: 0; top: -60px; height: 60px; }
384
+ .list .tabs { touch-action: pan-x; }
385
+ .chatwin .tabs { touch-action: none; }
386
+ .list .items, .msgs, .card > .body { touch-action: pan-y; }
387
+ .list .tabs .x { display: none; } /* the handle, a swipe down or a tap on the dimmed page closes it */
388
+
389
+ :host([data-sheet]) :is(.hint, .listener, .left) { visibility: hidden; }
390
+ /* The bar steps down under the screen's edge while a sheet is open and comes back as the sheet goes: --lab-p is
391
+ how far the sheet is on its way out (0 open, 1 gone), set while a finger drags it and while it slides away,
392
+ so the bar rises with it, in step, instead of after it (Leo, 15 Nov). */
393
+ .bar { transition: transform .34s cubic-bezier(.32, .72, 0, 1), opacity .2s; }
394
+ :host([data-sheet]) .bar { transform: translateY(calc((100% + 16px + env(safe-area-inset-bottom, 0px)) * (1 - var(--lab-p, 0))));
395
+ opacity: var(--lab-p, 0); pointer-events: none;
396
+ transition: transform .24s cubic-bezier(.4, 0, 1, 1), opacity .2s .04s; }
397
+ :host([data-sheet]) .bar button { pointer-events: none; }
398
+ /* A sheet stands apart from the page: the page dims behind it (a tap there closes it), and scrolling inside a
399
+ sheet never scrolls the page. */
400
+ :host([data-sheet]) .scrim { display: block; animation: lab-fade .22s ease-out; }
401
+ .card.in, .float.in, .list:not([hidden]) { animation: lab-sheet-in .28s cubic-bezier(.2, .8, .2, 1); }
402
+ .card.out, .float.out { animation: lab-sheet-out .22s cubic-bezier(.4, 0, 1, 1) forwards; }
403
+ .list { left: 0; right: 0; bottom: 0 !important; width: auto; max-height: var(--_sheet-max); overflow: visible; border-radius: var(--_radius) var(--_radius) 0 0;
404
+ font-size: 15px; letter-spacing: -.016em; z-index: 3; }
405
+ /* The chat keeps one height (new messages don't move its top) and opens at the newest. */
406
+ .chatwin { height: var(--_sheet-max); transition: height .38s cubic-bezier(.32, .72, 0, 1); }
407
+ /* Pulled up: the chat takes the whole screen, below the status bar (iOS large / Android expanded). */
408
+ .chatwin.full, .card.full { height: calc(var(--lab-vh, 100dvh) - env(safe-area-inset-top, 0px) - 10px + var(--_kb)); max-height: none; }
409
+ .card { transition: height .38s cubic-bezier(.32, .72, 0, 1); } /* a comment pulls up to full height as the chat does */
410
+ /* The header is the sheet's top edge, grab handle drawn on it; the list scrolls below it, never under or above it. */
411
+ .list .tabs { flex-wrap: nowrap; overflow-x: auto; padding: 18px 12px 8px; border-radius: var(--_radius) var(--_radius) 0 0;
412
+ background: linear-gradient(color-mix(in srgb, var(--_fg) 18%, transparent) 0 0) center 8px / 36px 4px no-repeat, var(--_bg); }
413
+ .list .items { padding: 0 12px calc(10px + var(--_safe)); }
414
+ .chatwin .msgs { padding: 4px 12px 8px; }
415
+ .chatwin .tabs { padding: 18px 12px 0; } /* just the grab strip, as tall as a thread's */
416
+ .chatwin .chat { padding: 6px 12px var(--_pb); }
417
+ /* Glass reply boxes (Leo, 15 Nov; iOS 26's look, Android too): the messages scroll on under the box and show
418
+ through it, blurred. Only the box's own strip overlaps; the new / resolve / delete row stays on the sheet. */
419
+ .chatwin .msgs { margin-bottom: calc(-56px - var(--_pb)); padding-bottom: calc(64px + var(--_pb)); }
420
+ .card > .body { margin-bottom: calc(-56px - var(--_pb)); padding-bottom: calc(64px + var(--_pb)); }
421
+ /* \u2026and fade out behind the box (iOS's scroll edge): from 4 px above its top to 12% at its bottom (Leo, 15 Nov:
422
+ "behind input bottom", "a bit more", "less, it's just black", then "more, darker there"). */
423
+ .chatwin .msgs { -webkit-mask-image: linear-gradient(#000 calc(100% - 60px - var(--_pb)), rgba(0,0,0,.12) calc(100% - var(--_pb)));
424
+ mask-image: linear-gradient(#000 calc(100% - 60px - var(--_pb)), rgba(0,0,0,.12) calc(100% - var(--_pb))); }
425
+ .card > .body { -webkit-mask-image: linear-gradient(#000 calc(100% - 60px - var(--_pb)), rgba(0,0,0,.12) calc(100% - var(--_pb)));
426
+ mask-image: linear-gradient(#000 calc(100% - 60px - var(--_pb)), rgba(0,0,0,.12) calc(100% - var(--_pb))); }
427
+ .chatwin .chat, .card > .foot { position: relative; z-index: 1; background: none; }
428
+ :host { --_box-bg: color-mix(in srgb, var(--_bg) 72%, transparent);
429
+ --_box-edge: inset 0 0 0 .5px color-mix(in srgb, var(--_fg) 16%, transparent), 0 4px 18px rgba(0, 0, 0, .08); }
430
+ .float { --_box-bg: inherit; --_box-edge: inherit; } /* phones: the new comment sheet's box is the same glass */
431
+ .box { -webkit-backdrop-filter: blur(18px) saturate(1.8); backdrop-filter: blur(18px) saturate(1.8); }
432
+ .list .it { padding: 11px 8px; }
433
+ /* Pins a size smaller (22 px), the tail still on the spot: 28 px covered words on a phone. Moved ones smaller still. */
434
+ .pin { scale: .8; }
435
+ /* Messages at 15 px (13 on computers): closer to the phone's own 17 px text, threads still short. */
436
+ .msg .p { font-size: 15px; letter-spacing: -.016em; line-height: 21px; }
437
+ .msg .quote { font-size: 14px; letter-spacing: -.011em; }
438
+ .msg b, .msg .quote b { font-size: 12px; letter-spacing: 0; }
439
+ .pin.moved { scale: .64; }
440
+ /* The same one bar as on computers, each segment 44 px tall to tap (iOS 44 pt); the menu opens above it. */
441
+ .bar > button { padding: 12px 14px; min-height: 44px; }
442
+ .more-menu { bottom: 72px; min-width: 200px; }
443
+ .more-menu button { padding: 11px 12px; font-size: 15px; letter-spacing: -.016em; }
444
+ }
445
+ /* Reaches past the screen's edges, under Safari's status bar and toolbar, so the page is dimmed everywhere. */
446
+ .scrim { cursor: pointer; display: none; position: fixed; inset: -50vh 0; background: rgba(0, 0, 0, .4); z-index: 2; touch-action: none; }
447
+ .sel-chip { position: fixed; transform: translateX(-50%); border: 0; border-radius: var(--_radius); padding: 8px 14px; background: var(--_fg);
448
+ color: var(--_bg); font: 500 14px/1 var(--_font, inherit); box-shadow: var(--_shadow); z-index: 4; }
449
+ /* Phones: the listening label is a light in the "list" button (steady: listening, blinking: working, grey:
450
+ nobody), the bar goes back to the bottom, and the send button is big enough for a thumb. */
451
+ @media (pointer: coarse) and (max-width: 560px), (pointer: coarse) and (max-height: 500px) { /* phones, upright or on their side */
452
+ .listener { display: none !important; }
453
+ .bar { bottom: 16px !important; }
454
+ .hint { bottom: 64px !important; }
455
+ .chat-btn[data-agent]::before { content: ''; display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; vertical-align: 1px; background: var(--_accent); }
456
+ .chat-btn[data-agent=away]::before { background: var(--_muted); opacity: .5; }
457
+ .chat-btn[data-agent=working]::before { background: rgb(36, 160, 70); }
458
+ .chat-btn[data-agent] { position: relative; }
459
+ .chat-btn[data-agent=working]::after { content: ''; position: absolute; left: 14px; top: 50%; width: 8px; height: 8px; margin-top: -4px;
460
+ border-radius: 50%; corner-shape: round; background: rgb(52, 199, 89); pointer-events: none; will-change: transform, opacity; animation: lab-ping 1.6s cubic-bezier(0, 0, .2, 1) infinite; }
461
+ .send { width: 36px; height: 36px; }
462
+ .send .arr { width: 17px; height: 15px; margin: auto; }
463
+ }
464
+ /* Narrow screens: the buttons sit a row above the listening label, so neither covers the other. */
465
+ @media (max-width: 560px) { .bar { bottom: 64px; } .hint { bottom: 112px; } .list { bottom: 114px; } }
466
+ [hidden] { display: none !important; }
467
+ `;
468
+
469
+ // src/widget/anchoring.ts
470
+ var host;
471
+ var layer;
472
+ var el;
473
+ var store;
474
+ function bindAnchoring(deps) {
475
+ ({ host, layer, el, store } = deps);
476
+ }
477
+ function selectorFor(node) {
478
+ const parts = [];
479
+ while (node && node.nodeType === 1 && node !== document.body && node !== document.documentElement) {
480
+ if (node.id && document.querySelectorAll(`#${CSS.escape(node.id)}`).length === 1) {
481
+ parts.unshift(`#${CSS.escape(node.id)}`);
482
+ break;
483
+ }
484
+ const tag = node.localName;
485
+ let index = 1;
486
+ for (let sib = node.previousElementSibling; sib; sib = sib.previousElementSibling) if (sib.localName === tag) index++;
487
+ parts.unshift(`${tag}:nth-of-type(${index})`);
488
+ node = node.parentElement;
489
+ }
490
+ return parts.length ? (parts[0].startsWith("#") ? "" : "body > ") + parts.join(" > ") : "body";
491
+ }
492
+ var docWidth = () => Math.max(document.documentElement.scrollWidth, 1);
493
+ var clamp01 = (v) => Math.min(Math.max(v, 0), 1);
494
+ var short = (v, n) => (v || "").replace(/\s+/g, " ").trim().slice(0, n);
495
+ function fileHint(url) {
496
+ if (!url || url.startsWith("data:")) return "";
497
+ try {
498
+ const u = new URL(url, location.href);
499
+ const inner = u.searchParams.get("href") || u.searchParams.get("url");
500
+ if (inner && /\/_(image|vercel\/image|next\/image)/.test(u.pathname)) return fileHint(inner);
501
+ const parts = u.pathname.split("/").filter(Boolean).map(decodeURIComponent);
502
+ let name = parts.pop() || "";
503
+ if (/^w?\d+(x\d+)?\.\w+$/i.test(name) && parts.length) name = parts.pop();
504
+ return name.replace(/\.(avif|webp|jpe?g|png|gif|svg|mp4|webm|mov)$/i, "").replace(/[._-][A-Za-z0-9_-]{8}$/, "");
505
+ } catch {
506
+ return "";
507
+ }
508
+ }
509
+ var mediaSrc = (m) => {
510
+ const src = m.currentSrc || m.getAttribute("src") || "";
511
+ if (src && !src.startsWith("data:")) return new URL(src, location.href).href;
512
+ const lazy = m.dataset?.src || (m.getAttribute("srcset") || m.dataset?.srcset || "").split(/\s+/)[0];
513
+ return lazy ? new URL(lazy, location.href).href : "";
514
+ };
515
+ function naturalSpot(m, rect, cx, cy, nw, nh) {
516
+ if (!nw || !nh || !rect.width || !rect.height) return null;
517
+ const cs = getComputedStyle(m);
518
+ const fit = cs.objectFit || "fill";
519
+ const pos = (cs.objectPosition || "50% 50%").split(/\s+/).map(
520
+ (v) => v.endsWith("%") ? parseFloat(v) / 100 : { left: 0, top: 0, right: 1, bottom: 1 }[v] ?? 0.5
521
+ );
522
+ const sx = rect.width / nw;
523
+ const sy = rect.height / nh;
524
+ const scale = { cover: Math.max(sx, sy), contain: Math.min(sx, sy), none: 1, "scale-down": Math.min(1, sx, sy) }[fit];
525
+ const dw = nw * (scale ?? sx);
526
+ const dh = nh * (scale ?? sy);
527
+ const ox = (rect.width - dw) * (pos[0] ?? 0.5);
528
+ const oy = (rect.height - dh) * (pos[1] ?? pos[0] ?? 0.5);
529
+ return { fit, nw, nh, imgX: clamp01((cx - rect.left - ox) / dw), imgY: clamp01((cy - rect.top - oy) / dh) };
530
+ }
531
+ function fileSize(img) {
532
+ let nw = img.naturalWidth;
533
+ let nh = img.naturalHeight;
534
+ const sets = [img.srcset, ...[...img.closest("picture")?.querySelectorAll("source") || []].map((s) => s.srcset)].filter(Boolean);
535
+ for (const set of sets) {
536
+ for (const part of set.split(/,\s+/)) {
537
+ const [url, d = "1x"] = part.trim().split(/\s+/);
538
+ let abs = "";
539
+ try {
540
+ abs = new URL(url, location.href).href;
541
+ } catch {
542
+ }
543
+ if (!url || abs !== img.currentSrc || !nw) continue;
544
+ const v = parseFloat(d);
545
+ if (d.endsWith("w") && v) return { nw: Math.round(v), nh: Math.round(v * nh / nw) };
546
+ if (d.endsWith("x") && v) return { nw: Math.round(nw * v), nh: Math.round(nh * v) };
547
+ }
548
+ }
549
+ return { nw, nh };
550
+ }
551
+ var PLAIN_NAME = /^[A-Z][A-Za-z0-9]{2,}$/;
552
+ var PLUMBING = /(Provider|Context|Consumer|Boundary|Slot|Portal|Fragment|Presence|Scope|Trap|Root)$/;
553
+ var variantOf = (p) => ["variant", "size", "tone", "intent", "kind"].flatMap((k) => (typeof p?.[k] === "string" || typeof p?.[k] === "number") && /^[\w.-]{1,20}$/.test(String(p[k])) ? [`${k}=${p[k]}`] : []).join(" ");
554
+ var repoPath = (url) => !/^[a-z-]+:\/\//i.test(url) ? url : decodeURIComponent(url.replace(/^[a-z-]+:\/\/\/?(\.\/)?/i, "/").replace(/^\/[^/]*:\d+/, "").split("?")[0]).replace(/^\/(@fs)?/, "").replace(/^\(app-pages-browser\)\/\.?\/?/, "");
555
+ function componentAt(el2) {
556
+ const name = (t, d = 0) => d > 3 ? "" : typeof t === "function" ? t.displayName || t.name || "" : t && typeof t === "object" ? t.displayName || name(t.render || t.type, d + 1) : "";
557
+ const plain = (n) => PLAIN_NAME.test(n) && !PLUMBING.test(n);
558
+ const srcOf = (f) => {
559
+ const d = f?._debugSource;
560
+ if (d?.fileName) return `${repoPath(String(d.fileName))}:${d.lineNumber || 0}`;
561
+ const st = f?._debugStack?.stack;
562
+ if (typeof st !== "string") return "";
563
+ for (const line of st.split("\n").slice(1)) {
564
+ const m = /((?:https?|webpack-internal|file):\/\/[^\s()]+?):(\d+):\d+\)?\s*$/.exec(line);
565
+ if (m && !/node_modules|react-dom|react-jsx|jsx-dev-runtime|react-server|scheduler/.test(m[1])) return `${repoPath(m[1])} (line ${m[2]} as served, may differ from the source)`;
566
+ }
567
+ return "";
568
+ };
569
+ const key = Object.keys(el2).find((k) => k.startsWith("__reactFiber$"));
570
+ if (key) {
571
+ const host2 = el2[key];
572
+ const parts = [];
573
+ let usedAt = "";
574
+ for (let f = host2?.return, i = 0; f && parts.length < 2 && i < 80; f = f.return, i++) {
575
+ if (typeof f.type === "string") continue;
576
+ const n = name(f.type);
577
+ if (!plain(n)) continue;
578
+ if (!parts.length) usedAt = srcOf(f);
579
+ const v = variantOf(f.memoizedProps);
580
+ parts.push(v ? `${n} ${v}` : n);
581
+ }
582
+ if (!parts.length) return srcOf(host2) ? { source: srcOf(host2) } : {};
583
+ return { component: parts.length > 1 ? `${parts[0]} (in ${parts[1]})` : parts[0], source: srcOf(host2) || void 0, usedAt: usedAt || void 0 };
584
+ }
585
+ const vue = el2.__vueParentComponent;
586
+ if (vue?.type) {
587
+ const n = vue.type.name || vue.type.__name || (vue.type.__file || "").replace(/^.*\//, "").replace(/\.vue$/, "");
588
+ const parent = vue.parent?.type;
589
+ const pn = parent && (parent.name || parent.__name);
590
+ const v = variantOf(vue.props);
591
+ return { component: `${n}${v ? " " + v : ""}${pn ? ` (in ${pn})` : ""}`, source: vue.type.__file ? repoPath(vue.type.__file) : void 0, usedAt: parent?.__file ? repoPath(parent.__file) : void 0 };
592
+ }
593
+ const loc = el2.__svelte_meta?.loc;
594
+ if (loc?.file) return { component: loc.file.replace(/^.*\//, "").replace(/\.svelte$/, ""), source: `${repoPath(loc.file)}:${loc.line ?? 0}` };
595
+ return {};
596
+ }
597
+ function looksOf(el2) {
598
+ const cs = getComputedStyle(el2);
599
+ const names = /* @__PURE__ */ new Map();
600
+ const NONE = "rgb(1, 2, 3)";
601
+ const wrap = document.createElement("i");
602
+ wrap.style.cssText = `display:none;color:${NONE}`;
603
+ const probe = wrap.appendChild(document.createElement("i"));
604
+ document.body.append(wrap);
605
+ for (const prop of [...getComputedStyle(document.documentElement)].filter((p) => p.startsWith("--")).slice(0, 400)) {
606
+ probe.style.color = "";
607
+ probe.style.color = `var(${prop})`;
608
+ const v = getComputedStyle(probe).color;
609
+ if (v && v !== NONE && !names.has(v)) names.set(v, prop);
610
+ }
611
+ wrap.remove();
612
+ const say = (v) => names.has(v) ? `${names.get(v)} ${v}` : v;
613
+ const out = [];
614
+ if (!/^(transparent|rgba\(0, 0, 0, 0\))$/.test(cs.backgroundColor)) out.push(`fill ${say(cs.backgroundColor)}`);
615
+ out.push(`text ${say(cs.color)} ${cs.fontSize}/${cs.fontWeight}`);
616
+ if (parseFloat(cs.borderTopLeftRadius)) out.push(`radius ${cs.borderTopLeftRadius}`);
617
+ return short(out.join(", "), 200);
618
+ }
619
+ function untransform(el2, cx, cy) {
620
+ const t = getComputedStyle(el2).transform;
621
+ if (!t || t === "none") return null;
622
+ const m = new DOMMatrix(t);
623
+ if (m.isIdentity) return null;
624
+ const w = el2.offsetWidth || el2.getBoundingClientRect().width;
625
+ const h = el2.offsetHeight || el2.getBoundingClientRect().height;
626
+ const [ox, oy] = getComputedStyle(el2).transformOrigin.split(" ").map(parseFloat);
627
+ const at = (x, y) => m.transformPoint(new DOMPoint(x - ox, y - oy));
628
+ const corners = [at(0, 0), at(w, 0), at(0, h), at(w, h)];
629
+ const r = el2.getBoundingClientRect();
630
+ const origin = { x: r.left - Math.min(...corners.map((p) => p.x)), y: r.top - Math.min(...corners.map((p) => p.y)) };
631
+ const q = m.inverse().transformPoint(new DOMPoint(cx - origin.x, cy - origin.y));
632
+ return { rect: { left: 0, top: 0, width: w, height: h }, x: q.x + ox, y: q.y + oy };
633
+ }
634
+ function svgImageSpot(el2, anchor, cx, cy) {
635
+ const r = el2.getBoundingClientRect();
636
+ const keep = (el2.getAttribute("preserveAspectRatio") || "xMidYMid meet").split(/\s+/);
637
+ const fill = (iw, ih) => {
638
+ if (!iw || !ih || !r.width || !r.height) return;
639
+ let [dw, dh] = [r.width, r.height];
640
+ if (keep[0] !== "none") {
641
+ const k = (keep[1] === "slice" ? Math.max : Math.min)(r.width / iw, r.height / ih);
642
+ [dw, dh] = [iw * k, ih * k];
643
+ }
644
+ const align = (v, room) => v === "Min" ? 0 : v === "Max" ? room : room / 2;
645
+ const ox = keep[0] === "none" ? 0 : align(keep[0].slice(1, 4), r.width - dw);
646
+ const oy = keep[0] === "none" ? 0 : align(keep[0].slice(5, 8), r.height - dh);
647
+ Object.assign(anchor, { nw: iw, nh: ih, imgX: clamp01((cx - r.left - ox) / dw), imgY: clamp01((cy - r.top - oy) / dh) });
648
+ };
649
+ const probe = new Image();
650
+ probe.onload = () => fill(probe.naturalWidth, probe.naturalHeight);
651
+ probe.src = anchor.src;
652
+ if (probe.complete) fill(probe.naturalWidth, probe.naturalHeight);
653
+ }
654
+ function backgroundSpot(n, url, anchor, cx, cy) {
655
+ const r = n.getBoundingClientRect();
656
+ const cs = getComputedStyle(n);
657
+ const layers = (v) => v.split(/,(?![^(]*\))/).map((x) => x.trim());
658
+ const at = Math.max(0, layers(cs.backgroundImage).findIndex((l) => l.includes(url)));
659
+ const pick = (v) => {
660
+ const l = layers(v);
661
+ return l[at % l.length];
662
+ };
663
+ const fill = (iw, ih) => {
664
+ if (!iw || !ih || !r.width || !r.height) return;
665
+ const size = pick(cs.backgroundSize);
666
+ let dw = iw;
667
+ let dh = ih;
668
+ if (size === "cover" || size === "contain") {
669
+ const k = (size === "cover" ? Math.max : Math.min)(r.width / iw, r.height / ih);
670
+ dw = iw * k;
671
+ dh = ih * k;
672
+ } else if (size !== "auto" && size !== "auto auto") {
673
+ const [w, h = "auto"] = size.split(/\s+/);
674
+ const len = (v, of) => v.endsWith("%") ? parseFloat(v) / 100 * of : parseFloat(v);
675
+ dw = w === "auto" ? NaN : len(w, r.width);
676
+ dh = h === "auto" ? NaN : len(h, r.height);
677
+ if (Number.isNaN(dw) && Number.isNaN(dh)) [dw, dh] = [iw, ih];
678
+ else if (Number.isNaN(dw)) dw = dh * iw / ih;
679
+ else if (Number.isNaN(dh)) dh = dw * ih / iw;
680
+ }
681
+ const [px = "50%", py = "50%"] = pick(cs.backgroundPosition).split(/\s+/);
682
+ const off = (v, room) => v.endsWith("%") ? parseFloat(v) / 100 * room : parseFloat(v) || 0;
683
+ const ox = off(px, r.width - dw);
684
+ const oy = off(py, r.height - dh);
685
+ Object.assign(anchor, { nw: iw, nh: ih, fit: `background ${size}`, imgX: clamp01((cx - r.left - ox) / dw), imgY: clamp01((cy - r.top - oy) / dh) });
686
+ };
687
+ const probe = new Image();
688
+ probe.onload = () => fill(probe.naturalWidth, probe.naturalHeight);
689
+ probe.src = url;
690
+ if (probe.complete) fill(probe.naturalWidth, probe.naturalHeight);
691
+ }
692
+ function between(target, cy) {
693
+ const kids = [...target.children].filter((k) => k !== host && k.getBoundingClientRect().height > 0);
694
+ let above = null;
695
+ let below = null;
696
+ for (const k of kids) {
697
+ const kr = k.getBoundingClientRect();
698
+ if (kr.bottom <= cy) above = k;
699
+ else if (kr.top >= cy && !below) below = k;
700
+ else if (kr.top < cy && kr.bottom > cy) return null;
701
+ }
702
+ const say = (k) => {
703
+ if (!k) return void 0;
704
+ const h = k.matches("h1, h2, h3, h4, h5, h6") ? k : k.querySelector("h1, h2, h3, h4, h5, h6");
705
+ return short(`${openingTag(k)} "${short((h || k).textContent, 60)}"`, 160);
706
+ };
707
+ return above || below ? { above: say(above), below: say(below) } : null;
708
+ }
709
+ function schemeAt(target) {
710
+ for (let n = target; n; n = n.parentElement) {
711
+ const m = getComputedStyle(n).backgroundColor.match(/rgba?\(([\d.]+),\s*([\d.]+),\s*([\d.]+)(?:,\s*([\d.]+))?/);
712
+ if (!m || m[4] !== void 0 && parseFloat(m[4]) < 0.5) continue;
713
+ const [r, g, b] = [m[1], m[2], m[3]].map(Number);
714
+ const hex = "#" + [r, g, b].map((v) => Math.round(v).toString(16).padStart(2, "0")).join("");
715
+ return { scheme: 0.2126 * r + 0.7152 * g + 0.0722 * b < 128 ? "dark" : "light", background: hex };
716
+ }
717
+ return { scheme: matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light" };
718
+ }
719
+ function quoteAt(cx, cy, shadowRoots = []) {
720
+ let node = null;
721
+ let offset = 0;
722
+ if (document.caretPositionFromPoint) {
723
+ const p = shadowRoots.length ? document.caretPositionFromPoint(cx, cy, { shadowRoots }) : document.caretPositionFromPoint(cx, cy);
724
+ if (p) {
725
+ node = p.offsetNode;
726
+ offset = p.offset;
727
+ }
728
+ } else if (document.caretRangeFromPoint) {
729
+ const r = document.caretRangeFromPoint(cx, cy);
730
+ if (r) {
731
+ node = r.startContainer;
732
+ offset = r.startOffset;
733
+ }
734
+ }
735
+ if (!node || node.nodeType !== 3 || !node.data.trim()) return null;
736
+ const range = document.createRange();
737
+ range.selectNodeContents(node);
738
+ const hit = [...range.getClientRects()].some((r) => cx >= r.left - 4 && cx <= r.right + 4 && cy >= r.top - 4 && cy <= r.bottom + 4);
739
+ if (!hit) return null;
740
+ const text = node.data;
741
+ let a = offset;
742
+ let b = offset;
743
+ const seg = /[\u0e00-\u0e7f\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af\uf900-\ufaff]/.test(text) && typeof Intl !== "undefined" && Intl.Segmenter ? new Intl.Segmenter(node.parentElement?.closest("[lang]")?.lang || void 0, { granularity: "word" }) : null;
744
+ if (seg) {
745
+ for (const w of seg.segment(text)) {
746
+ if (offset >= w.index && offset <= w.index + w.segment.length && w.segment.trim()) {
747
+ a = w.index;
748
+ b = w.index + w.segment.length;
749
+ if (offset < b) break;
750
+ }
751
+ }
752
+ } else {
753
+ while (a > 0 && /\S/.test(text[a - 1])) a--;
754
+ while (b < text.length && /\S/.test(text[b])) b++;
755
+ }
756
+ const block = node.parentElement?.closest("p, li, h1, h2, h3, h4, h5, h6, td, th, figcaption, blockquote, a, button, label, span, div") || node.parentElement;
757
+ const full = block?.textContent || text;
758
+ const before = full.slice(0, full.indexOf(text) + a);
759
+ const after = full.slice(full.indexOf(text) + b);
760
+ const squash = (v) => v.replace(/\s+/g, " ");
761
+ const quote = {
762
+ exact: short(text.slice(a, b), 80),
763
+ prefix: squash(before.slice(-80)).replace(/^\s+/, "").slice(-40),
764
+ suffix: squash(after.slice(0, 80)).replace(/\s+$/, "").slice(0, 40)
765
+ };
766
+ const pre = node.parentElement?.closest("pre, [data-file]") || (getComputedStyle(node.parentElement).whiteSpace.startsWith("pre") ? node.parentElement : null);
767
+ const codeTable = !pre && node.parentElement?.closest('table[data-file], table[class*="code" i]');
768
+ if (pre || codeTable) {
769
+ const box = pre || codeTable;
770
+ const r = document.createRange();
771
+ r.setStart(box, 0);
772
+ r.setEnd(node, offset);
773
+ let upto = r.toString();
774
+ let all = box.textContent;
775
+ const breaks = [...box.querySelectorAll("br, tr")];
776
+ if ((box.localName === "table" || !all.includes("\n")) && breaks.length) {
777
+ const ends = box.querySelectorAll("br").length ? [...box.querySelectorAll("br")] : [...box.querySelectorAll("tr")].slice(0, -1);
778
+ const before2 = ends.filter((e) => e.compareDocumentPosition(node) & Node.DOCUMENT_POSITION_FOLLOWING && !e.contains(node)).length;
779
+ const lineRange = document.createRange();
780
+ if (before2) lineRange.setStartAfter(ends[before2 - 1]);
781
+ else lineRange.setStart(box, 0);
782
+ if (ends[before2]) lineRange.setEndBefore(ends[before2]);
783
+ else lineRange.setEnd(box, box.childNodes.length);
784
+ const row2 = box.querySelectorAll("br").length ? null : node.parentElement?.closest("tr");
785
+ quote.line = short((row2 ? row2.textContent : lineRange.toString()).trim(), 200);
786
+ quote.lineNo = before2 + 1;
787
+ quote.lines = ends.length + (box.querySelectorAll("br").length ? 0 : 1);
788
+ } else {
789
+ const from = upto.lastIndexOf("\n") + 1;
790
+ const to = all.indexOf("\n", upto.length);
791
+ quote.line = short(all.slice(from, to < 0 ? void 0 : to).trim(), 200);
792
+ quote.lineNo = upto.split("\n").length;
793
+ quote.lines = all.replace(/\n$/, "").split("\n").length;
794
+ }
795
+ const row = node.parentElement?.closest("tr, [data-line], [data-line-number]");
796
+ if (row) {
797
+ const cell = row.matches("[data-line], [data-line-number]") ? row : row.querySelector("[data-line], [data-line-number]");
798
+ const n = cell?.getAttribute("data-line") || cell?.getAttribute("data-line-number") || [...row.children].map((c) => c.textContent.trim()).find((t) => /^\d+$/.test(t));
799
+ if (n && /^\d+$/.test(n)) quote.pageLineNo = Number(n);
800
+ }
801
+ let label = box.closest("[data-file]")?.getAttribute("data-file") || box.getAttribute("title") || box.getAttribute("aria-label") || "";
802
+ for (let el2 = box.parentElement, i = 0; !label.trim() && el2 && el2 !== document.body && i < 3; el2 = el2.parentElement, i++) {
803
+ label = el2.querySelector(':scope > figcaption, :scope > [class*="title" i]')?.textContent || "";
804
+ }
805
+ if (label.trim()) quote.label = short(label.trim(), 120);
806
+ }
807
+ return quote;
808
+ }
809
+ function openingTag(node) {
810
+ const attrs = [...node.attributes].filter((a) => /^(id|class|alt|role|aria-label|href|data-[\w-]+)$/.test(a.name)).map((a) => `${a.name}="${short(a.value, 60)}"`);
811
+ return `<${node.localName}${attrs.length ? ` ${attrs.join(" ")}` : ""}>`.slice(0, 200);
812
+ }
813
+ function sameKind(node, tag) {
814
+ if (!tag) return true;
815
+ const want = /^<([\w-]+)/.exec(tag)?.[1];
816
+ if (node.localName !== want) return false;
817
+ const id = / id="([^"]*)"/.exec(tag)?.[1];
818
+ if ((id || "") !== short(node.id || "", 60)) return false;
819
+ const classes = (/ class="([^"]*)"/.exec(tag)?.[1] || "").split(/\s+/).filter((c) => c && c !== "\u2026" && !c.endsWith("\u2026"));
820
+ return !classes.length || classes.some((c) => node.classList.contains(c));
821
+ }
822
+ function anchorAt(clientX, clientY) {
823
+ let stack = document.elementsFromPoint(clientX, clientY).filter((n) => n !== host && n !== document.documentElement);
824
+ const shadowRoots = [];
825
+ let shadowHost = null;
826
+ for (let top = stack[0]; top?.shadowRoot && !host.contains(top) && shadowRoots.length < 5; top = stack[0]) {
827
+ shadowHost ||= top;
828
+ shadowRoots.push(top.shadowRoot);
829
+ const inner = top.shadowRoot.elementsFromPoint(clientX, clientY).filter((n) => n !== top);
830
+ if (!inner.length) break;
831
+ stack = [...inner, ...stack];
832
+ }
833
+ const target = stack[0]?.closest("[data-comment-target]") || stack[0] || document.body;
834
+ const rect = target.getBoundingClientRect();
835
+ const anchor = {
836
+ selector: selectorFor(target),
837
+ x: rect.width ? (clientX - rect.left) / rect.width : 0,
838
+ y: rect.height ? (clientY - rect.top) / rect.height : 0,
839
+ docX: (clientX + scrollX) / docWidth(),
840
+ docY: clientY + scrollY,
841
+ width: innerWidth,
842
+ height: innerHeight,
843
+ dpr: Math.round((devicePixelRatio || 1) * 100) / 100,
844
+ element: openingTag(target),
845
+ eh: Math.round(rect.height)
846
+ // its height then: a pin on a big container can tell if the page grew under it
847
+ };
848
+ const own = short(target.textContent, 200);
849
+ if (own && target !== document.body && (target.textContent || "").length < 400) anchor.text = short(own, 80);
850
+ const inside = target.parentElement?.closest("[id], [data-lab]");
851
+ if (inside) anchor.inside = inside.dataset.lab ? `[data-lab="${inside.dataset.lab}"]` : `#${inside.id}`;
852
+ let heading = null;
853
+ for (const h of document.querySelectorAll("h1, h2, h3")) {
854
+ if (h.compareDocumentPosition(target) & Node.DOCUMENT_POSITION_FOLLOWING || h.contains(target)) heading = h;
855
+ }
856
+ if (heading) anchor.section = short(heading.textContent, 100);
857
+ if (shadowHost) anchor.shadow = openingTag(shadowHost);
858
+ for (const [k, v] of Object.entries(componentAt(target))) if (v) anchor[k] = short(v, 200);
859
+ if (target !== document.body) anchor.looks = looksOf(target);
860
+ const select = target.closest?.("select");
861
+ if (select && select.selectedIndex >= 0) {
862
+ anchor.chosen = short(`${select.selectedIndex + 1} of ${select.options.length}: "${select.options[select.selectedIndex].text}"`, 120);
863
+ }
864
+ for (const el2 of [target, target.parentElement]) {
865
+ if (!el2 || el2 === document.body) continue;
866
+ for (const which of ["::before", "::after"]) {
867
+ const c = getComputedStyle(el2, which).content;
868
+ const m = c && c.match(/^"(.+)"$/);
869
+ if (m && m[1].trim()) {
870
+ anchor.cssText = short(`"${m[1]}" from ${which} of ${openingTag(el2)}`, 160);
871
+ break;
872
+ }
873
+ }
874
+ if (anchor.cssText) break;
875
+ }
876
+ const build = document.querySelector('meta[name="lab-build"]')?.content;
877
+ if (build) anchor.build = short(build, 40);
878
+ const media = stack.slice(0, 5).find((n) => /^(img|video|canvas|svg|image)$/.test(n.localName) && !host.contains(n));
879
+ if (media?.localName === "image" && media.namespaceURI === "http://www.w3.org/2000/svg") {
880
+ anchor.kind = "image";
881
+ anchor.src = new URL(media.getAttribute("href") || media.getAttribute("xlink:href") || "", location.href).href;
882
+ anchor.file = fileHint(anchor.src);
883
+ svgImageSpot(media, anchor, clientX, clientY);
884
+ } else if (media) {
885
+ const r = media.getBoundingClientRect();
886
+ anchor.kind = media.localName === "img" ? "image" : media.localName;
887
+ if (media.localName === "img" || media.localName === "video") {
888
+ const img = media, video = media;
889
+ anchor.src = mediaSrc(media);
890
+ anchor.file = fileHint(anchor.src);
891
+ if (img.alt) anchor.alt = short(img.alt, 120);
892
+ const local = untransform(media, clientX, clientY);
893
+ const [box, px, py] = local ? [local.rect, local.x, local.y] : [r, clientX, clientY];
894
+ const spot = media.localName === "img" ? naturalSpot(media, box, px, py, fileSize(media).nw, fileSize(media).nh) : naturalSpot(media, box, px, py, video.videoWidth, video.videoHeight);
895
+ if (spot) Object.assign(anchor, spot);
896
+ if (local) anchor.transform = short(getComputedStyle(media).transform, 80);
897
+ if (media.localName === "img" && /\.(gif|webp|apng)(\?|#|$)/i.test(img.currentSrc || img.src)) {
898
+ const entry = performance.getEntriesByName(img.currentSrc || img.src)[0];
899
+ const since = entry ? (performance.now() - entry.responseEnd) / 1e3 : performance.now() / 1e3;
900
+ anchor.shownFor = Math.round(since * 10) / 10;
901
+ }
902
+ if (media.localName === "video") {
903
+ anchor.time = Math.round(video.currentTime * 10) / 10;
904
+ if (Number.isFinite(video.duration)) anchor.duration = Math.round(video.duration * 10) / 10;
905
+ if (!anchor.file && video.poster) anchor.file = fileHint(video.poster);
906
+ }
907
+ } else {
908
+ anchor.time = Math.round(performance.now() / 100) / 10;
909
+ anchor.imgX = clamp01((clientX - r.left) / (r.width || 1));
910
+ anchor.imgY = clamp01((clientY - r.top) / (r.height || 1));
911
+ anchor.nw = Math.round(r.width);
912
+ anchor.nh = Math.round(r.height);
913
+ }
914
+ } else {
915
+ const quote = quoteAt(clientX, clientY, shadowRoots);
916
+ if (quote) {
917
+ anchor.kind = "text";
918
+ anchor.quote = quote;
919
+ } else {
920
+ for (let n = target, i = 0; n && n !== document.documentElement && i < 4; n = n.parentElement, i++) {
921
+ const bg = getComputedStyle(n).backgroundImage.match(/url\(["']?(.+?)["']?\)/);
922
+ if (bg) {
923
+ anchor.kind = "background";
924
+ anchor.src = new URL(bg[1], location.href).href;
925
+ anchor.file = fileHint(anchor.src);
926
+ backgroundSpot(n, anchor.src, anchor, clientX, clientY);
927
+ break;
928
+ }
929
+ }
930
+ anchor.kind ||= "element";
931
+ if (anchor.kind === "element") {
932
+ const gap = between(target, clientY);
933
+ if (gap) Object.assign(anchor, { gapAbove: gap.above, gapBelow: gap.below });
934
+ }
935
+ }
936
+ }
937
+ Object.assign(anchor, schemeAt(target));
938
+ return anchor;
939
+ }
940
+ function findTarget(anchor) {
941
+ let node = null;
942
+ try {
943
+ node = anchor.selector ? document.querySelector(anchor.selector) : null;
944
+ } catch {
945
+ }
946
+ const matches = (n) => {
947
+ if (!n) return false;
948
+ if (anchor.file && /^(image|video)$/.test(anchor.kind)) {
949
+ const m = n.closest?.("img, video") || n;
950
+ return fileHint(mediaSrc(m)) === anchor.file;
951
+ }
952
+ if (anchor.element && !sameKind(n, anchor.element)) return false;
953
+ if (anchor.quote?.exact) {
954
+ const t = (n.textContent || "").replace(/\s+/g, "");
955
+ const q = anchor.quote.exact.replace(/\s+/g, "").slice(0, 24);
956
+ const before = (anchor.quote.prefix || "").replace(/\s+/g, "").slice(-10);
957
+ const after = (anchor.quote.suffix || "").replace(/\s+/g, "").slice(0, 10);
958
+ return t.includes(q) && (q.length >= 16 || !before && !after || t.includes(before + q) || t.includes(q + after));
959
+ }
960
+ return true;
961
+ };
962
+ const said = short(anchor.text, 400);
963
+ const sectionOf = (n) => {
964
+ let heading = null;
965
+ for (const h of document.querySelectorAll("h1, h2, h3")) if (h.compareDocumentPosition(n) & Node.DOCUMENT_POSITION_FOLLOWING || h.contains(n)) heading = h;
966
+ return heading ? short(heading.textContent, 100) : "";
967
+ };
968
+ const squash = (t) => String(t || "").replace(/\s+/g, "");
969
+ const areaWords = squash(anchor.zoneText).slice(0, 30);
970
+ const saysSame = (n) => anchor.quote?.exact ? true : said ? short(n.textContent, 400).startsWith(said.slice(0, 40)) : areaWords ? squash(n.textContent).includes(areaWords) : anchor.section ? sectionOf(n) === anchor.section : true;
971
+ const atPath = node && node !== document.body && matches(node) ? node : null;
972
+ if (atPath && saysSame(atPath)) return atPath;
973
+ if (anchor.file && /^(image|video)$/.test(anchor.kind)) {
974
+ return [...document.querySelectorAll("img, video")].find((m) => fileHint(mediaSrc(m)) === anchor.file) || null;
975
+ }
976
+ const tag = /^<([\w-]+)/.exec(anchor.element || "")?.[1];
977
+ if (!tag || tag === "body" || tag === "html") return atPath;
978
+ const flat = (t) => short(t, 400);
979
+ let found = null;
980
+ let best = -1;
981
+ let near = Infinity;
982
+ const twins = [...document.querySelectorAll(tag)].slice(0, 400).filter((n) => !host.contains(n) && sameKind(n, anchor.element));
983
+ for (const n of twins) {
984
+ const t = flat(n.textContent);
985
+ let score = 0;
986
+ if (anchor.quote?.exact && matches(n)) score += 4;
987
+ if (said && t === said) score += 4;
988
+ if (areaWords && squash(n.textContent).includes(areaWords)) score += 4;
989
+ else if (said && t.startsWith(said.slice(0, 40))) score += 2;
990
+ if (!score && twins.length > 1) continue;
991
+ if (score && anchor.section && sectionOf(n) === anchor.section) score += 2;
992
+ const d = Math.abs(n.getBoundingClientRect().top + scrollY - (anchor.docY || 0));
993
+ if (score > best || score === best && d < near) [found, best, near] = [n, score, d];
994
+ }
995
+ return best > 0 || !atPath ? found : atPath;
996
+ }
997
+ var wordCache = null;
998
+ function wordSpot(anchor) {
999
+ const m = /^(?:…)?(.*?)\[([^\]]+)\](.*?)(?:…)?$/s.exec(anchor.text || "");
1000
+ if (!m) return null;
1001
+ const before = m[1].replace(/\s+/g, " ").slice(-24);
1002
+ const word = m[2];
1003
+ if (!wordCache || performance.now() - wordCache.at > 400) {
1004
+ const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, { acceptNode: (t) => host.contains(t.parentNode) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT });
1005
+ let text2 = "";
1006
+ const at2 = [];
1007
+ for (let t = walker.nextNode(); t; t = walker.nextNode()) {
1008
+ const v = t.data.replace(/\s+/g, " ");
1009
+ for (let i2 = 0; i2 < v.length; i2++) at2.push([t, i2]);
1010
+ text2 += v;
1011
+ }
1012
+ wordCache = { at: performance.now(), text: text2, map: at2 };
1013
+ }
1014
+ const { text, map: at } = wordCache;
1015
+ let i = text.indexOf(before + word);
1016
+ if (i < 0) return { gone: true };
1017
+ i += before.length;
1018
+ const range = document.createRange();
1019
+ try {
1020
+ range.setStart(...at[i]);
1021
+ range.setEnd(at[i + word.length - 1][0], at[i + word.length - 1][1] + 1);
1022
+ } catch {
1023
+ return { gone: true };
1024
+ }
1025
+ const r = range.getBoundingClientRect();
1026
+ return r.width || r.height ? { left: r.left + scrollX + Math.min(6, r.width / 2), top: r.top + scrollY + r.height / 2 } : { gone: true };
1027
+ }
1028
+ var pageEnd = { at: -Infinity, y: 0 };
1029
+ var inPage = (y, h = 0) => {
1030
+ if (performance.now() - pageEnd.at > 300) {
1031
+ const bottoms = [...document.body.children].filter((c) => c !== host && !host.contains(c)).map((c) => c.getBoundingClientRect().bottom + scrollY);
1032
+ pageEnd = { at: performance.now(), y: Math.max(innerHeight, ...bottoms) };
1033
+ }
1034
+ return Math.max(0, Math.min(y, pageEnd.y - h - 40));
1035
+ };
1036
+ var pinOf = (zone, anchor) => ({ left: zone.left + (anchor.pinX ? zone.width : 0), top: zone.top + (anchor.pinY ? zone.height : 0) });
1037
+ var EDGE = 10;
1038
+ function position(anchor) {
1039
+ const at = spotOf(anchor);
1040
+ return at.moved ? { ...at, left: EDGE } : at;
1041
+ }
1042
+ function spotOf(anchor) {
1043
+ const node = findTarget(anchor);
1044
+ if (node && !anchor.zw && !anchor.docW && /^(html|body|main)$/.test(node.localName) && /\[[^\]]+\]/.test(anchor.text || "")) {
1045
+ const spot = wordSpot(anchor);
1046
+ if (spot && !spot.gone) return { left: spot.left, top: spot.top, zone: null };
1047
+ if (spot?.gone) return { left: anchor.docX * docWidth(), top: inPage(anchor.docY), zone: null, moved: true };
1048
+ }
1049
+ if (node && anchor.eh && !anchor.zw && !anchor.docW && /^(html|body|main)$/.test(node.localName) && !/\[[^\]]+\]/.test(anchor.text || "")) {
1050
+ if (Math.abs(node.getBoundingClientRect().height - anchor.eh) > 40) return { left: anchor.docX * docWidth(), top: inPage(anchor.docY), zone: null, moved: true };
1051
+ }
1052
+ if (node) {
1053
+ const rect = node.getBoundingClientRect();
1054
+ if (rect.width || rect.height) {
1055
+ const left2 = rect.left + scrollX + anchor.x * rect.width;
1056
+ const tall = anchor.zw && Number.isFinite(anchor.oy) && anchor.docH && rect.height > 2 * anchor.docH;
1057
+ const top2 = rect.top + scrollY + (tall ? anchor.oy : anchor.y * rect.height);
1058
+ const zone2 = anchor.zw ? { left: left2, top: top2, width: anchor.zw * rect.width, height: tall ? anchor.docH : anchor.zh * rect.height } : null;
1059
+ return zone2 ? { ...pinOf(zone2, anchor), zone: zone2 } : { left: left2, top: top2, zone: zone2 };
1060
+ }
1061
+ }
1062
+ const left = anchor.docX * docWidth();
1063
+ const top = inPage(anchor.docY, anchor.docH || 0);
1064
+ const zone = anchor.docW ? { left, top, width: anchor.docW, height: anchor.docH } : null;
1065
+ if (zone) return { ...pinOf(zone, anchor), zone, moved: Boolean(anchor.selector) && anchor.selector !== "body" };
1066
+ return { left, top, zone, moved: Boolean(anchor.selector) && anchor.selector !== "body" };
1067
+ }
1068
+ function quoteRange(anchor) {
1069
+ const q = anchor?.quote;
1070
+ let node = q?.exact ? findTarget(anchor) : null;
1071
+ if (!node) return null;
1072
+ const want = q.exact.replace(/\s+/g, "");
1073
+ const tail = (q.prefix || "").replace(/\s+/g, "").slice(-12);
1074
+ for (let up = 0; node && up < 4; node = node.parentElement, up++) {
1075
+ let text = "";
1076
+ const at = [];
1077
+ const walker = document.createTreeWalker(node, NodeFilter.SHOW_TEXT);
1078
+ for (let t = walker.nextNode(); t; t = walker.nextNode())
1079
+ for (let i = 0; i < t.data.length; i++) {
1080
+ if (/\s/.test(t.data[i])) continue;
1081
+ text += t.data[i];
1082
+ at.push([t, i]);
1083
+ }
1084
+ let first = null;
1085
+ for (let i = text.indexOf(want); i !== -1; i = text.indexOf(want, i + 1)) {
1086
+ const range = document.createRange();
1087
+ range.setStart(...at[i]);
1088
+ const [end, k] = at[i + want.length - 1];
1089
+ range.setEnd(end, k + 1);
1090
+ if (!tail || text.slice(0, i).endsWith(tail)) return range;
1091
+ first ||= range;
1092
+ }
1093
+ if (first) return first;
1094
+ }
1095
+ return null;
1096
+ }
1097
+ var nameLine = (name, done) => {
1098
+ const b = el("b", {}, String(name || "").replace(/\s*·\s*session\s+\S+$/i, ""));
1099
+ if (done) b.append(el("span", { class: "mark done", role: "img", "aria-label": "done" }, "\u2713"));
1100
+ return b;
1101
+ };
1102
+ var DRAFT_MODE = false;
1103
+ var drafting = () => DRAFT_MODE && store.get("lab-hold") === "1";
1104
+ var linked = (text) => {
1105
+ const out = [];
1106
+ let at = 0;
1107
+ for (const m of text.matchAll(/\bhttps?:\/\/[^\s<>"']*[^\s<>"'.,;:!?)\]]/g)) {
1108
+ if (m.index > at) out.push(document.createTextNode(text.slice(at, m.index)));
1109
+ const a = el("a", { href: m[0], target: "_blank", rel: "noopener noreferrer", class: "link" }, m[0]);
1110
+ a.addEventListener("click", (e) => e.stopPropagation());
1111
+ out.push(a);
1112
+ at = m.index + m[0].length;
1113
+ }
1114
+ if (at < text.length) out.push(document.createTextNode(text.slice(at)));
1115
+ return out;
1116
+ };
1117
+ var sentences = (t) => t.split(/(?<=[.!?])\s+(?=["'([]?[A-Z0-9])/);
1118
+ var readable = (text) => {
1119
+ const blocks = [];
1120
+ for (const [n, para] of String(text || "").trim().split(/\n\s*\n/).entries()) {
1121
+ const lines = para.split("\n");
1122
+ if (lines.length === 1 && para.length > 240) {
1123
+ const ss = sentences(para);
1124
+ for (let i = 0; i < ss.length; i += 2) blocks.push({ text: ss.slice(i, i + 2).join(" "), gap: n > 0 || i > 0 });
1125
+ continue;
1126
+ }
1127
+ lines.forEach((line, i) => {
1128
+ const item = /^\s*(?:[-•*]|\d+[.)])\s+/.exec(line);
1129
+ const prev = i > 0 ? blocks.at(-1) : null;
1130
+ if (item) blocks.push({ li: /\d/.test(item[0]) ? item[0].trim() : "\u2022", text: line.slice(item[0].length), gap: n > 0 && i === 0 });
1131
+ else if (prev && !prev.li) prev.text += `
1132
+ ${line}`;
1133
+ else blocks.push({ text: line, gap: n > 0 && i === 0 || Boolean(prev) });
1134
+ });
1135
+ }
1136
+ return blocks.map((b) => {
1137
+ const node = el("span", { class: `p${b.li ? " li" : ""}${b.gap ? " gap" : ""}` });
1138
+ if (b.li) node.append(el("span", { class: "mk" }, b.li));
1139
+ node.append(...linked(b.text));
1140
+ return node;
1141
+ });
1142
+ };
1143
+ var canMark = typeof Highlight === "function" && Boolean(CSS.highlights);
1144
+ var markQuote = (anchor) => {
1145
+ if (!canMark) return;
1146
+ const range = anchor && quoteRange(anchor);
1147
+ if (range) CSS.highlights.set("lab-quote", new Highlight(range));
1148
+ else CSS.highlights.delete("lab-quote");
1149
+ };
1150
+ var zoneEl = (cls) => {
1151
+ const z = el("div", { class: `zone ${cls}` });
1152
+ z.innerHTML = '<svg aria-hidden="true"><rect class="ring" width="100%" height="100%"/><rect class="dots" width="100%" height="100%"/></svg>';
1153
+ return z;
1154
+ };
1155
+ var drawZone = (box, cls) => {
1156
+ if (!box) return;
1157
+ const z = zoneEl(cls);
1158
+ Object.assign(z.style, { left: `${box.left}px`, top: `${box.top}px`, width: `${box.width}px`, height: `${box.height}px` });
1159
+ layer.append(z);
1160
+ return z;
1161
+ };
1162
+ function zoneAnchor({ x0, y0, x1, y1 }) {
1163
+ const left = Math.min(x0, x1);
1164
+ const top = Math.min(y0, y1);
1165
+ const right = Math.max(x0, x1);
1166
+ const bottom = Math.max(y0, y1);
1167
+ const anchor = anchorAt((left + right) / 2, (top + bottom) / 2);
1168
+ let box = document.elementsFromPoint((left + right) / 2, (top + bottom) / 2).find((n) => n !== host && !host.contains(n));
1169
+ const area = Math.max(1, (right - left) * (bottom - top));
1170
+ const contains = (r2) => Math.max(0, Math.min(r2.right, right) - Math.max(r2.left, left)) * Math.max(0, Math.min(r2.bottom, bottom) - Math.max(r2.top, top)) / area >= 0.8;
1171
+ while (box && box !== document.body && !contains(box.getBoundingClientRect())) box = box.parentElement;
1172
+ box ||= document.body;
1173
+ const r = box.getBoundingClientRect();
1174
+ Object.assign(anchor, {
1175
+ selector: box === document.body ? "body" : selectorFor(box),
1176
+ element: openingTag(box),
1177
+ x: r.width ? (left - r.left) / r.width : 0,
1178
+ y: r.height ? (top - r.top) / r.height : 0,
1179
+ zw: r.width ? (right - left) / r.width : 0,
1180
+ // may pass 1 a little: the area can reach past its element's edge
1181
+ zh: r.height ? (bottom - top) / r.height : 0,
1182
+ oy: Math.round(top - r.top),
1183
+ // px below the element's top: a share of a tall box drifts when it grows (pictures load)
1184
+ docX: (left + scrollX) / docWidth(),
1185
+ docY: top + scrollY,
1186
+ docW: Math.round(right - left),
1187
+ docH: Math.round(bottom - top),
1188
+ pinX: x1 >= x0 ? 1 : 0,
1189
+ // the drag ended on the right / at the bottom: the pin goes there
1190
+ pinY: y1 >= y0 ? 1 : 0
1191
+ });
1192
+ Object.assign(anchor, schemeAt(box));
1193
+ if (anchor.kind === "text") {
1194
+ delete anchor.quote;
1195
+ anchor.kind = "element";
1196
+ }
1197
+ const boxText = box === document.body ? "" : short(box.textContent, 200);
1198
+ if (boxText && (box.textContent || "").length < 400) anchor.text = short(boxText, 80);
1199
+ else delete anchor.text;
1200
+ if (box !== document.body) anchor.looks = looksOf(box);
1201
+ const words = [];
1202
+ const walker = document.createTreeWalker(box, NodeFilter.SHOW_TEXT);
1203
+ const range = document.createRange();
1204
+ for (let n = walker.nextNode(); n && words.length < 80; n = walker.nextNode()) {
1205
+ if (host.contains(n)) continue;
1206
+ const pr = n.parentElement?.getBoundingClientRect();
1207
+ if (!pr || pr.bottom < top || pr.top > bottom || pr.right < left || pr.left > right) continue;
1208
+ for (const m of n.data.matchAll(/\S+/g)) {
1209
+ range.setStart(n, m.index);
1210
+ range.setEnd(n, m.index + m[0].length);
1211
+ const w = range.getBoundingClientRect();
1212
+ const cx = (w.left + w.right) / 2;
1213
+ const cy = (w.top + w.bottom) / 2;
1214
+ if (w.width && cx >= left && cx <= right && cy >= top && cy <= bottom) words.push(m[0]);
1215
+ }
1216
+ }
1217
+ const text = short(words.join(" "), 300);
1218
+ if (text) anchor.zoneText = text;
1219
+ const inArea = [];
1220
+ const all = box.querySelectorAll("*");
1221
+ for (let i = 0; i < all.length && i < 3e3; i++) {
1222
+ const el2 = all[i];
1223
+ if (host.contains(el2) || inArea.some((x) => x.contains(el2))) continue;
1224
+ const er = el2.getBoundingClientRect();
1225
+ if (er.width < 8 || er.height < 8 || er.left < left - 4 || er.right > right + 4 || er.top < top - 4 || er.bottom > bottom + 4) continue;
1226
+ inArea.push(el2);
1227
+ }
1228
+ if (inArea.length) {
1229
+ anchor.zoneItems = inArea.slice(0, 5).map((el2) => {
1230
+ const c = componentAt(el2);
1231
+ const t = short(el2.textContent, 50);
1232
+ return short([openingTag(el2), t && `"${t}"`, c.component, c.source && `written at ${c.source}`, c.usedAt && `used at ${c.usedAt}`].filter(Boolean).join(" \xB7 "), 500);
1233
+ });
1234
+ if (inArea.length > 5) anchor.zoneItems.push(`and ${inArea.length - 5} more`);
1235
+ }
1236
+ if (/^(img|video)$/.test(box.localName)) {
1237
+ const nw = box.localName === "img" ? fileSize(box).nw : box.videoWidth;
1238
+ const nh = box.localName === "img" ? fileSize(box).nh : box.videoHeight;
1239
+ const a = naturalSpot(box, r, left, top, nw, nh);
1240
+ const b = naturalSpot(box, r, right, bottom, nw, nh);
1241
+ if (a && b) Object.assign(anchor, { imgX: a.imgX, imgY: a.imgY, imgX2: b.imgX, imgY2: b.imgY });
1242
+ } else if (anchor.kind === "image" || anchor.kind === "video") {
1243
+ delete anchor.imgX;
1244
+ delete anchor.imgY;
1245
+ anchor.kind = "element";
1246
+ }
1247
+ return anchor;
1248
+ }
1249
+
1250
+ // src/comments.js
1251
+ /*!
1252
+ * lab comments: anyone with the link clicks anywhere on a lab page to pin a comment. No login, just a name.
1253
+ * https://github.com/leonidstern/labit · MIT
1254
+ * Comments are off by default; the bar button or c turns them on (remembered per browser). When on, click anywhere that isn't a link or control to pin one (alt/option-click pins on those too). c (or the bar button) hides
1255
+ * and shows them; esc or a click outside closes an open comment. Dragging (mouse/pen) marks an area instead of a point.
1256
+ * Include on a page served through your lab domain:
1257
+ * <script src="https://lab.example.com/_lab/comments.js" defer><\/script>
1258
+ * The layer only turns on when the page is opened on the host the script is loaded from (or data-host),
1259
+ * so the deployment's own address and local dev stay clean. data-enable="always" turns it on everywhere.
1260
+ * Admin (resolve / delete / copy agent link): open any page once with ?lab-admin=<LAB_COMMENTS_ADMIN_TOKEN>; it is kept in this browser.
1261
+ */
1262
+ (() => {
1263
+ const script = (
1264
+ /** @type {HTMLScriptElement | null} */
1265
+ document.currentScript
1266
+ );
1267
+ const labHost = script?.dataset.host || (script?.src ? new URL(script.src, location.href).hostname : location.hostname);
1268
+ const enabled = location.hostname === labHost || script?.dataset.enable === "always";
1269
+ if (!enabled || /** @type {any} */
1270
+ window.__labComments) return;
1271
+ window.__labComments = true;
1272
+ const API = script?.dataset.api || "/_lab/api/comments";
1273
+ const pageNow = () => script?.dataset.page || location.pathname.replace(/\/+$/, "") || "/";
1274
+ let page = pageNow();
1275
+ const store2 = {
1276
+ get: (k) => {
1277
+ try {
1278
+ return localStorage.getItem(k) || "";
1279
+ } catch {
1280
+ return "";
1281
+ }
1282
+ },
1283
+ set: (k, v) => {
1284
+ try {
1285
+ localStorage.setItem(k, v);
1286
+ } catch {
1287
+ }
1288
+ }
1289
+ };
1290
+ const scopeOf = (key) => key.split(".").length === 3 ? key.split(".")[1] : "";
1291
+ const adminParam = new URLSearchParams(location.hash.slice(1)).get("lab-admin") || new URLSearchParams(location.search).get("lab-admin");
1292
+ if (adminParam) {
1293
+ const scope = scopeOf(adminParam);
1294
+ store2.set(scope ? `lab-admin:${scope}` : "lab-admin", adminParam);
1295
+ const url = new URL(location.href);
1296
+ url.searchParams.delete("lab-admin");
1297
+ if (/lab-admin=/.test(url.hash)) url.hash = "";
1298
+ history.replaceState(null, "", url);
1299
+ }
1300
+ const adminToken = script?.dataset.admin || store2.get(`lab-admin:${page.split("/")[1] || ""}`) || store2.get("lab-admin:*") || store2.get("lab-admin");
1301
+ let comments = [];
1302
+ let isAdmin = false;
1303
+ let on = store2.get("lab-on") ? store2.get("lab-on") === "1" : script?.dataset.on === "1";
1304
+ let openId = null;
1305
+ let closeFast = false;
1306
+ let cardFull = false;
1307
+ let draft = null;
1308
+ const host2 = document.createElement("div");
1309
+ host2.setAttribute("data-lab-comments", "");
1310
+ host2.style.cssText = "position:absolute;top:0;left:0;width:0;height:0;z-index:2147483000;";
1311
+ const root = host2.attachShadow({ mode: "open" });
1312
+ root.innerHTML = `
1313
+ <style>${styles_default}</style>
1314
+ <div class="scrim"></div>
1315
+ <div class="layer"></div>
1316
+ <button class="sel-chip" type="button" hidden>Comment</button>
1317
+ <div class="hint" role="status" hidden>click to comment \xB7 drag to mark an area \xB7 shift-drag to quote words \xB7 c chat \xB7 w new \xB7 1 comment \xB7 2 go \xB7 3 cursor \xB7 m hide</div>
1318
+ <div class="list" hidden><div class="tabs"><button type="button" data-f="new">new</button><button type="button" data-f="open">open</button><button type="button" data-f="work">work</button><button type="button" data-f="resolved">resolved</button><button type="button" data-f="mine">mine</button><button type="button" class="show-done" title="show or hide done pins on the page"></button><button type="button" class="hold" title="new pins wait here as drafts; send them together">draft mode</button><button type="button" class="x" aria-label="close">\u2715</button></div><div class="items"></div></div>
1319
+ <div class="list chatwin" hidden><div class="tabs"><b>chat</b></div><div class="msgs"></div><div class="replying" hidden></div><div class="chat"></div></div>
1320
+ <div class="left"><button class="secondary copy-all" type="button" hidden>copy link</button></div>
1321
+ <div class="bar">
1322
+ <button class="secondary send-all" type="button" hidden></button>
1323
+ <button class="secondary chat-btn" type="button" hidden title="chat (C)">chat</button>
1324
+ <button class="secondary new-prev" type="button" hidden aria-label="previous new comment">\u2039</button>
1325
+ <button class="secondary list-btn" type="button" hidden>list</button>
1326
+ <button class="secondary new-next" type="button" hidden aria-label="next new comment">\u203A</button>
1327
+ <button class="secondary done-btn" type="button" hidden title="show or hide done pins on the page"></button>
1328
+ <button class="secondary go-btn" type="button" hidden title="1 comment \xB7 2 go: every click approves what it's on \xB7 3 cursor: clicks are the page's own">go</button>
1329
+ <button class="toggle" type="button"></button>
1330
+ <button class="secondary more" type="button" hidden aria-label="more options" aria-expanded="false" aria-controls="lab-more">\u22EF</button>
1331
+ </div>
1332
+ <div class="more-menu" id="lab-more" hidden></div>`;
1333
+ const $ = (sel, box = root) => (
1334
+ /** @type {HTMLElement} */
1335
+ box.querySelector(sel)
1336
+ );
1337
+ const layer2 = $(".layer");
1338
+ const hint = $(".hint");
1339
+ if (matchMedia("(pointer: coarse)").matches) hint.textContent = "hold to comment";
1340
+ const toggleBtn = $(".toggle");
1341
+ const bar = (
1342
+ /** @type {HTMLElement} */
1343
+ root.querySelector(".bar")
1344
+ );
1345
+ const moreBtn = $(".more");
1346
+ const moreMenu = $(".more-menu");
1347
+ const copyBtn = $(".copy-all");
1348
+ const listBtn = (
1349
+ /** @type {HTMLButtonElement} */
1350
+ $(".list-btn")
1351
+ );
1352
+ const goBtn = $(".go-btn");
1353
+ const newPrev = $(".new-prev");
1354
+ const showDoneBtn = $(".show-done");
1355
+ const doneBtn = (
1356
+ /** @type {HTMLButtonElement} */
1357
+ $(".done-btn")
1358
+ );
1359
+ const LIST_WINDOW = false;
1360
+ const tabTitle = { base: "" };
1361
+ let showDone = store2.get("lab-show-done") === "1";
1362
+ const newNext = $(".new-next");
1363
+ const sendBtn = $(".send-all");
1364
+ const listEl = $(".list");
1365
+ const holdBtn = $(".hold", listEl);
1366
+ const chatEl = $(".chatwin");
1367
+ const chatBtn = (
1368
+ /** @type {HTMLElement} */
1369
+ root.querySelector(".chat-btn")
1370
+ );
1371
+ let listOpen = false;
1372
+ let filter = "open";
1373
+ let refit = () => {
1374
+ };
1375
+ let chatOpen = false;
1376
+ const el2 = (tag, attrs = {}, text) => {
1377
+ const node = document.createElement(tag);
1378
+ for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);
1379
+ if (text != null) node.textContent = text;
1380
+ return node;
1381
+ };
1382
+ bindAnchoring({ host: host2, layer: layer2, el: el2, store: store2 });
1383
+ function patchKids(box, next) {
1384
+ const keep = new Set(next);
1385
+ for (const n of Array.from(box.childNodes)) if (!keep.has(n)) n.remove();
1386
+ let at = box.firstChild;
1387
+ for (const n of next) {
1388
+ if (n === at) at = at.nextSibling;
1389
+ else box.insertBefore(n, at);
1390
+ }
1391
+ }
1392
+ const AGENT_KINDS = ["claude", "codex", "cursor", "gemini", "antigravity", "copilot", "amp", "opencode"];
1393
+ const agentOf = (m) => {
1394
+ if (!m?.session) return "";
1395
+ const k = String(m.session.kind || m.name || "").trim().split(/\W/)[0].toLowerCase();
1396
+ return AGENT_KINDS.includes(k) ? k === "antigravity" ? "gemini" : k : "";
1397
+ };
1398
+ const headers = () => ({ "content-type": "application/json", ...adminToken ? { "x-lab-admin": adminToken } : {} });
1399
+ let gone = false;
1400
+ let loaded = false;
1401
+ let retried = false;
1402
+ const typed = () => Boolean(root.activeElement) || [...root.querySelectorAll("textarea")].some((t) => t.value.trim());
1403
+ async function load() {
1404
+ try {
1405
+ const res = await fetch(`${API}?page=${encodeURIComponent(page)}`, { headers: headers(), cache: "no-store" });
1406
+ if (res.status === 404 && !loaded && script?.dataset.enable !== "always") {
1407
+ if (!retried) {
1408
+ retried = true;
1409
+ setTimeout(load, 1500);
1410
+ return;
1411
+ }
1412
+ gone = true;
1413
+ on = false;
1414
+ document.documentElement.classList.remove("lab-pinning");
1415
+ host2.remove();
1416
+ fonts.remove();
1417
+ return;
1418
+ }
1419
+ if (!res.ok) throw new Error(String(res.status));
1420
+ const data = await res.json();
1421
+ comments = data.comments || [];
1422
+ isAdmin = Boolean(data.admin);
1423
+ loaded = true;
1424
+ } catch {
1425
+ }
1426
+ shownAgain();
1427
+ }
1428
+ async function loadChanges(since) {
1429
+ try {
1430
+ const url = new URL("/_lab/api/changes", new URL(API, location.href));
1431
+ url.search = String(new URLSearchParams({ page, since: String(since) }));
1432
+ const res = await fetch(url, { cache: "no-store" });
1433
+ const data = res.ok ? await res.json() : { full: true };
1434
+ if (data.full || !loaded) return load();
1435
+ const gone2 = new Set(data.del);
1436
+ const fresh = new Map(data.set.map((c) => [c.id, c]));
1437
+ comments = comments.filter((c) => !gone2.has(c.id)).map((c) => fresh.get(c.id) || c);
1438
+ const had = new Set(comments.map((c) => c.id));
1439
+ for (const c of data.set) if (!had.has(c.id)) comments.push(c);
1440
+ comments.sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1441
+ } catch {
1442
+ return load();
1443
+ }
1444
+ shownAgain();
1445
+ }
1446
+ function shownAgain() {
1447
+ if (!typed() && !grabbing) render();
1448
+ else {
1449
+ if (openCard?.isConnected) openCard.sync();
1450
+ if (chatOpen) drawChat();
1451
+ drawList();
1452
+ }
1453
+ }
1454
+ let goMode = store2.get("lab-go") === "1";
1455
+ let cursorMode = store2.get("lab-cursor") === "1";
1456
+ const setCursor = (v) => {
1457
+ cursorMode = v;
1458
+ store2.set("lab-cursor", v ? "1" : "");
1459
+ goBtn.classList.toggle("cursor", v);
1460
+ goBtn.classList.toggle("on", goMode && !v);
1461
+ goFace();
1462
+ document.documentElement.classList.toggle("lab-pinning", on && !v);
1463
+ document.documentElement.classList.toggle("lab-go", on && goMode && !v);
1464
+ recheck();
1465
+ };
1466
+ const setGo = (v) => {
1467
+ if (cursorMode) setCursor(false);
1468
+ goMode = v;
1469
+ queueMicrotask(goFace);
1470
+ store2.set("lab-go", v ? "1" : "");
1471
+ goBtn.classList.toggle("on", v);
1472
+ goBtn.setAttribute("aria-pressed", String(v && !cursorMode));
1473
+ document.documentElement.classList.toggle("lab-go", on && v);
1474
+ ptr.classList.toggle("go", v);
1475
+ recheck();
1476
+ };
1477
+ function begin(anchor) {
1478
+ const name = store2.get("lab-name").trim();
1479
+ if (!goMode || !name) {
1480
+ draft = { anchor };
1481
+ return render();
1482
+ }
1483
+ if (drafting()) {
1484
+ store2.set(heldKey(), JSON.stringify([...held(), { name, text: "go", anchor }]));
1485
+ return render();
1486
+ }
1487
+ send({ name, text: "go", anchor }).then(({ comment, edit }) => {
1488
+ if (edit) store2.set(`lab-edit:${comment.id}`, edit);
1489
+ comments.push(comment);
1490
+ markSeen([comment]);
1491
+ posted = comment.id;
1492
+ render();
1493
+ }).catch(() => (draft = { anchor }, render()));
1494
+ }
1495
+ async function send(payload) {
1496
+ let res = null;
1497
+ if (!payload.action && !payload.nonce) payload = { ...payload, nonce: Math.random().toString(36).slice(2) + Date.now().toString(36) };
1498
+ for (let tries = 0; !res; tries++) {
1499
+ try {
1500
+ res = await fetch(API, { method: "POST", headers: headers(), body: JSON.stringify({ page, ...payload }) });
1501
+ } catch {
1502
+ if (tries >= 150) throw new Error("couldn't reach the lab; your text is still here");
1503
+ await new Promise((r) => setTimeout(r, 2e3));
1504
+ }
1505
+ }
1506
+ const data = await res.json().catch(() => ({}));
1507
+ if (!res.ok) throw new Error(data.error || `could not save (${res.status})`);
1508
+ if (data.comment && !payload.parent && !payload.action && payload.anchor?.kind !== "page") placed.push(data.comment.id);
1509
+ return data;
1510
+ }
1511
+ const placed = [];
1512
+ async function undoLast() {
1513
+ const id = placed.pop();
1514
+ const c = id && comments.find((x) => x.id === id);
1515
+ if (!c) return;
1516
+ const ownKey = store2.get(`lab-edit:${id}`);
1517
+ try {
1518
+ if (isAdmin) {
1519
+ await send({ action: "delete", id });
1520
+ comments = comments.filter((x) => x.id !== id && x.parent !== id);
1521
+ } else if (ownKey) {
1522
+ const { comment } = await send({ action: "resolve", id, edit: ownKey });
1523
+ Object.assign(c, comment);
1524
+ } else return void placed.push(id);
1525
+ } catch {
1526
+ return void placed.push(id);
1527
+ }
1528
+ if (openId === id) openId = null;
1529
+ render();
1530
+ say(`took back ${/^go$/i.test(c.text.trim()) ? "a go" : "a pin"} \xB7 ${placed.length ? "again for the one before" : "nothing more to take back"}`);
1531
+ }
1532
+ const said = { was: void 0, t: void 0 };
1533
+ function say(words) {
1534
+ said.was ??= hint.textContent;
1535
+ hint.textContent = words;
1536
+ hint.hidden = false;
1537
+ clearTimeout(said.t);
1538
+ said.t = setTimeout(() => {
1539
+ hint.hidden = true;
1540
+ hint.textContent = said.was;
1541
+ said.was = void 0;
1542
+ }, 1800);
1543
+ }
1544
+ const agentLink = () => new URL("/_lab/agent" + page, new URL(API, location.href)).href;
1545
+ async function copy(textPromise, button) {
1546
+ const textValue = await textPromise;
1547
+ try {
1548
+ await navigator.clipboard.writeText(textValue);
1549
+ } catch {
1550
+ const area = document.createElement("textarea");
1551
+ area.value = textValue;
1552
+ area.style.cssText = "position:fixed;opacity:0;";
1553
+ document.body.append(area);
1554
+ area.select();
1555
+ document.execCommand("copy");
1556
+ area.remove();
1557
+ }
1558
+ if (moreMenu.contains(button)) return say("link copied");
1559
+ const label = button.textContent;
1560
+ button.style.width = `${button.getBoundingClientRect().width}px`;
1561
+ button.style.justifyContent = "center";
1562
+ button.textContent = "copied";
1563
+ setTimeout(() => {
1564
+ button.textContent = label;
1565
+ button.style.width = button.style.justifyContent = "";
1566
+ }, 1400);
1567
+ }
1568
+ const threads = () => comments.filter((c) => !c.parent);
1569
+ const heldKey = () => `lab-held:${page}`;
1570
+ const held = () => {
1571
+ try {
1572
+ return JSON.parse(store2.get(heldKey()) || "[]");
1573
+ } catch {
1574
+ return [];
1575
+ }
1576
+ };
1577
+ const listed = () => threads().filter((c) => c.anchor?.kind !== "page").filter((c) => filter === "new" ? unread(c).length : filter === "open" ? !c.resolved : filter === "resolved" ? c.resolved : mine(c)).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
1578
+ const onWhat = (c) => {
1579
+ const a = c.anchor || {};
1580
+ let w = a.quote?.exact || "";
1581
+ let n = null;
1582
+ try {
1583
+ n = !w && a.selector ? document.querySelector(a.selector) : null;
1584
+ } catch {
1585
+ }
1586
+ for (let up = 0; n && n !== document.body && up < 5; n = n.parentElement, up++) {
1587
+ const t = n.innerText?.replace(/\s+/g, " ").trim() || "";
1588
+ if (t.length >= 12) {
1589
+ w = t;
1590
+ break;
1591
+ }
1592
+ }
1593
+ w = (w || a.text || a.section || "").replace(/\s+/g, " ").trim();
1594
+ return w ? `"${w.length > 40 ? `${w.slice(0, 39)}\u2026` : w}"` : "";
1595
+ };
1596
+ const isPage = (c) => c.anchor?.kind === "page";
1597
+ let stepping = false;
1598
+ let keepKeys = false;
1599
+ const goTo = (c, keys = false) => {
1600
+ stepping = Boolean(openId);
1601
+ keepKeys = stepping && (keys || root.activeElement?.localName === "textarea");
1602
+ openId = c.id;
1603
+ draft = null;
1604
+ if (coarse) listOpen = false;
1605
+ render();
1606
+ const pinTop = position(c.anchor || {}).top;
1607
+ let top = pinTop - Math.max(40, coarse && openCard?.isConnected ? (innerHeight - openCard.offsetHeight) / 2 : innerHeight / 3);
1608
+ if (!coarse && openCard?.isConnected) {
1609
+ const bottom = openCard.getBoundingClientRect().bottom + scrollY;
1610
+ const tall = bottom - pinTop + 28;
1611
+ top = tall <= innerHeight - 80 ? pinTop - 28 - (innerHeight - tall) / 2 : pinTop - 40;
1612
+ }
1613
+ if (coarse) {
1614
+ const de = document.documentElement;
1615
+ const had = parseFloat(de.style.getPropertyValue("--lab-room")) || 0;
1616
+ const room = Math.max(0, Math.ceil(top + innerHeight - (de.scrollHeight - had)));
1617
+ de.style.setProperty("--lab-room", `${room}px`);
1618
+ de.classList.toggle("lab-room", room > 0);
1619
+ }
1620
+ scrollTo({ top: Math.max(0, top), behavior: still.matches ? "auto" : "smooth" });
1621
+ };
1622
+ const isDone = (c) => c.resolved || workState(c)[0] === "done";
1623
+ const keyWord = (before, key, after) => {
1624
+ const w = el2("span", { class: "kw" });
1625
+ w.append(before, el2("span", { class: "mn", "aria-hidden": "true" }, `(${key})`), after);
1626
+ return w;
1627
+ };
1628
+ function placeBar() {
1629
+ const inMenu = on ? [doneBtn, copyBtn, toggleBtn] : [];
1630
+ for (const b of inMenu) if (b.parentNode !== moreMenu) moreMenu.append(b);
1631
+ if (!on && toggleBtn.parentNode !== bar) bar.insertBefore(toggleBtn, moreBtn);
1632
+ if (!on) root.querySelector(".left").append(copyBtn);
1633
+ moreBtn.hidden = !on;
1634
+ if (!on && !moreMenu.hidden) setMenu(false);
1635
+ let first = true;
1636
+ for (
1637
+ const b of
1638
+ /** @type {HTMLCollectionOf<HTMLElement>} */
1639
+ bar.children
1640
+ ) {
1641
+ b.classList.toggle("first", first && !b.hidden);
1642
+ if (!b.hidden) first = false;
1643
+ }
1644
+ }
1645
+ function goFace() {
1646
+ const gp = goBtn.querySelector(".gp");
1647
+ if (gp) gp.textContent = !goMode && !cursorMode ? initial(store2.get("lab-name")) || "+" : "go";
1648
+ goBtn.setAttribute("aria-label", `a click places: ${cursorMode ? "nothing (cursor)" : goMode ? "go" : "a comment"}`);
1649
+ goBtn.setAttribute("aria-keyshortcuts", "1 2 3");
1650
+ }
1651
+ function drawList() {
1652
+ const all = threads();
1653
+ listBtn.hidden = !on || !coarse && !all.length && !held().length;
1654
+ goBtn.hidden = !on;
1655
+ if (!goBtn.firstElementChild) goBtn.replaceChildren(el2("span", { class: "gp" }, "go"), el2("kbd", { "aria-hidden": "true" }, "1/2/3"));
1656
+ goFace();
1657
+ goBtn.classList.toggle("on", goMode && !cursorMode);
1658
+ goBtn.classList.toggle("cursor", cursorMode);
1659
+ goBtn.setAttribute("aria-pressed", String(goMode && !cursorMode));
1660
+ const freshAll = all.filter((c) => !isPage(c)).reduce((n, c) => n + unread(c).length, 0);
1661
+ listBtn.replaceChildren(document.createTextNode(freshAll ? `list \xB7 ${freshAll} new` : "list"), el2("kbd", { "aria-hidden": "true" }, "l"));
1662
+ newPrev.hidden = newNext.hidden = !on || !all.some((c) => !isPage(c) && unread(c).length);
1663
+ if (!LIST_WINDOW) {
1664
+ newPrev.hidden = newNext.hidden = true;
1665
+ listBtn.hidden = !on;
1666
+ {
1667
+ listBtn.replaceChildren(coarse ? "new" : keyWord("ne", "w", ""), el2("b", { class: `cnt${freshAll ? "" : " zero"}` }, String(freshAll)));
1668
+ listBtn.setAttribute("aria-label", `next new comment, ${freshAll} new`);
1669
+ listBtn.setAttribute("aria-keyshortcuts", "w");
1670
+ }
1671
+ listBtn.title = "next new comment: W, or Control-D while typing (Shift for the one before)";
1672
+ listBtn.disabled = !freshAll;
1673
+ listBtn.classList.toggle("quiet", !freshAll);
1674
+ const doneCount2 = all.filter((c) => !isPage(c) && (c.resolved || workState(c)[0] === "done") && !unread(c).length).length;
1675
+ doneBtn.hidden = !on;
1676
+ doneBtn.disabled = !doneCount2 && !showDone;
1677
+ doneBtn.classList.toggle("quiet", doneBtn.disabled);
1678
+ doneBtn.replaceChildren(showDone ? `hide done \xB7 ${doneCount2}` : `show done \xB7 ${doneCount2}`, el2("kbd", { "aria-hidden": "true" }, "d"));
1679
+ doneBtn.setAttribute("aria-keyshortcuts", "d");
1680
+ }
1681
+ placeBar();
1682
+ const tabNew = all.reduce((n, c) => n + unread(c).length, 0);
1683
+ if (!tabTitle.base || !document.title.startsWith("(")) tabTitle.base = document.title.replace(/^\(\d+\) /, "");
1684
+ const want = tabNew ? `(${tabNew}) ${tabTitle.base}` : tabTitle.base;
1685
+ if (document.title !== want) document.title = want;
1686
+ listBtn.classList.toggle("has-new", freshAll > 0);
1687
+ const h = held().length;
1688
+ sendBtn.hidden = !h;
1689
+ sendBtn.textContent = `send ${h} draft${h === 1 ? "" : "s"}`;
1690
+ listEl.hidden = !on || !listOpen;
1691
+ if (listEl.hidden) return;
1692
+ for (
1693
+ const b of
1694
+ /** @type {NodeListOf<HTMLElement>} */
1695
+ listEl.querySelectorAll("[data-f]")
1696
+ ) b.classList.toggle("on", b.dataset.f === filter);
1697
+ const fresh = all.filter((c) => !isPage(c) && unread(c).length).length;
1698
+ listEl.querySelector('[data-f="new"]').textContent = fresh ? `new \xB7 ${fresh}` : "new";
1699
+ for (const f of ["work", "resolved", "mine"]) $(`[data-f="${f}"]`, listEl).hidden = true;
1700
+ holdBtn.hidden = !DRAFT_MODE;
1701
+ const doneCount = all.filter((c) => !isPage(c) && (c.resolved || workState(c)[0] === "done") && !unread(c).length).length;
1702
+ showDoneBtn.hidden = !doneCount;
1703
+ showDoneBtn.textContent = showDone ? `hide done \xB7 ${doneCount}` : `show done \xB7 ${doneCount}`;
1704
+ holdBtn.classList.toggle("on", drafting());
1705
+ if (filter === "work") return listEl.querySelector(".items").replaceChildren(...workItems());
1706
+ const items = listed().map((c) => {
1707
+ const b = el2("button", { class: `it${openId === c.id ? " cur" : ""}`, type: "button" });
1708
+ b.append(document.createTextNode(`${c.resolved ? "\u2713" : numberOf(c)} ${c.text.replace(/\s+/g, " ").slice(0, 70)} `), ...onWhat(c) ? [el2("span", {}, `on ${onWhat(c)} `)] : [], el2("span", {}, `\xB7 ${c.name}${!c.resolved && isDone(c) ? " \xB7 \u2705 done" : ""}`), ...unread(c).length ? [" ", el2("span", { class: "tag" }, `${unread(c).length} new`)] : []);
1709
+ b.addEventListener("click", () => goTo(c));
1710
+ return b;
1711
+ });
1712
+ listEl.querySelector(".items").replaceChildren(...items.length ? items : [el2("div", { class: "none" }, "nothing here")]);
1713
+ }
1714
+ const ago = (iso) => {
1715
+ const m = Math.max(0, Math.round((Date.now() - new Date(iso).getTime()) / 6e4));
1716
+ return m < 1 ? "just now" : m < 60 ? `${m} min` : `${Math.floor(m / 60)} h ${m % 60} min`;
1717
+ };
1718
+ const workState = (c) => {
1719
+ const thread = [c, ...repliesOf(c.id)];
1720
+ const lastPerson = thread.filter((m) => !m.session).map((m) => m.createdAt).sort().at(-1) || "";
1721
+ const answer = thread.filter((m) => m.session).sort((a, b) => a.createdAt.localeCompare(b.createdAt)).at(-1);
1722
+ const answered = answer && answer.createdAt > lastPerson;
1723
+ if (c.resolved || answered && /^done\b/i.test(answer.text)) return ["done", answered ? answer.createdAt : c.createdAt];
1724
+ if (answered && /^on it\b/i.test(answer.text)) return ["now", answer.createdAt];
1725
+ if (!answered && c.handedAt && c.handedAt >= lastPerson) return ["now", c.handedAt];
1726
+ return answered ? [null, ""] : ["next", lastPerson];
1727
+ };
1728
+ function workItems() {
1729
+ const today = (/* @__PURE__ */ new Date()).toDateString();
1730
+ const now = [];
1731
+ const next = [];
1732
+ const done = [];
1733
+ for (const c of comments.filter((x) => !x.parent)) {
1734
+ const [state, at] = workState(c);
1735
+ if (state === "now") now.push([c, at]);
1736
+ else if (state === "next") next.push([c, at]);
1737
+ else if (state === "done" && new Date(at).toDateString() === today) done.push([c, at]);
1738
+ }
1739
+ const row = ([c, at], when) => {
1740
+ const b = el2("button", { class: `it${openId === c.id ? " cur" : ""}`, type: "button" });
1741
+ b.append(document.createTextNode(`${isPage(c) ? "chat" : c.resolved ? "\u2713" : numberOf(c)} ${c.text.replace(/\s+/g, " ").slice(0, 70)} `), el2("span", {}, `\xB7 ${when(at)}`));
1742
+ b.addEventListener("click", () => isPage(c) ? (chatOpen = true, listOpen = false, render()) : goTo(c));
1743
+ return b;
1744
+ };
1745
+ const part = (title, list, when, newest = false) => list.length ? [el2("div", { class: "group" }, `${title} \xB7 ${list.length}`), ...list.sort((a, b) => (newest ? -1 : 1) * a[1].localeCompare(b[1])).map((x) => row(x, when))] : [];
1746
+ const out = [
1747
+ ...part("Now", now, (at) => `on it ${ago(at)}`.replace("on it just now", "just started")),
1748
+ ...part("Next", next, (at) => `sent ${ago(at)} ago`.replace("just now ago", "just now")),
1749
+ ...part("Done today", done, (at) => new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), true)
1750
+ ];
1751
+ return out.length ? out : [el2("div", { class: "none" }, "nothing in progress on this page")];
1752
+ }
1753
+ const stamped = (bubble, stamp) => {
1754
+ const room = stamp.cloneNode(true);
1755
+ room.className = "stamp-room";
1756
+ room.setAttribute("aria-hidden", "true");
1757
+ for (const n of room.querySelectorAll("[role]")) n.removeAttribute("role");
1758
+ const last = [...bubble.children].reverse().find((n) => n.classList?.contains("p"));
1759
+ (last || bubble).append(room);
1760
+ bubble.append(stamp);
1761
+ };
1762
+ const stampOf = (m, root2, prefix = "") => {
1763
+ const at = new Date(m.createdAt);
1764
+ const time = at.toDateString() === (/* @__PURE__ */ new Date()).toDateString() ? at.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }) : at.toLocaleDateString([], { day: "numeric", month: "short" });
1765
+ const stamp = el2("span", { class: "stamp" });
1766
+ stamp.append(el2("span", { class: "tm" }, prefix + time));
1767
+ if (mine(m) && !m.session) {
1768
+ const thread = root2 ? [root2, ...repliesOf(root2.id)] : [m];
1769
+ const answered = thread.some((x) => x.session && x.createdAt > m.createdAt);
1770
+ const latest = !thread.some((x) => !x.session && x.createdAt > m.createdAt);
1771
+ if (!answered && latest && root2 && workState(root2)[0] === "now") {
1772
+ stamp.classList.add("busy");
1773
+ stamp.append(el2("span", { class: "ring", role: "img", "aria-label": "the agent is on it" }));
1774
+ } else if (answered) {
1775
+ stamp.classList.add("ans");
1776
+ stamp.append(el2("span", { class: "tick", role: "img", "aria-label": "answered" }, "\u2713"));
1777
+ } else {
1778
+ const got = root2?.handedAt && root2.handedAt >= m.createdAt;
1779
+ stamp.append(el2("span", { class: `tick${got ? " got" : ""}`, role: "img", "aria-label": got ? "delivered to the agent" : "sent" }, got ? "\u2713\u2713" : "\u2713"));
1780
+ }
1781
+ }
1782
+ return stamp;
1783
+ };
1784
+ let replyTo = null;
1785
+ let newFrom = null;
1786
+ function drawChat() {
1787
+ const byId = new Map(comments.map((c) => [c.id, c]));
1788
+ const msgs = comments.filter((c) => isPage(c) || c.parent && isPage(byId.get(c.parent) || {})).sort((a, b) => a.createdAt.localeCompare(b.createdAt)).slice(-150);
1789
+ if (on && chatOpen && chatEl.hidden) newFrom = msgs.find(isNew)?.id || null;
1790
+ if (!chatOpen) newFrom = null;
1791
+ if (on && chatOpen) markSeen(msgs.filter(isNew));
1792
+ const fresh = msgs.filter(isNew).length;
1793
+ chatBtn.hidden = !on;
1794
+ {
1795
+ chatBtn.replaceChildren(coarse ? "chat" : keyWord("", "c", "hat"), el2("b", { class: `cnt${fresh ? "" : " zero"}` }, String(fresh)));
1796
+ chatBtn.setAttribute("aria-label", `chat, ${fresh} new`);
1797
+ chatBtn.setAttribute("aria-keyshortcuts", "c");
1798
+ }
1799
+ chatBtn.classList.toggle("has-new", fresh > 0);
1800
+ placeBar();
1801
+ const opening = chatEl.hidden;
1802
+ chatEl.hidden = !on || !chatOpen;
1803
+ if (chatEl.hidden) chatEl.classList.remove("full");
1804
+ if (chatEl.hidden && chatEl.contains(root.activeElement)) root.activeElement.blur();
1805
+ if (chatEl.hidden) return;
1806
+ const box = $(".msgs", chatEl);
1807
+ const atEnd = opening || box.scrollHeight - box.scrollTop - box.clientHeight < 48;
1808
+ const before = new Set(opening ? [] : [.../** @type {HTMLCollectionOf<HTMLElement>} */
1809
+ box.children].map((n) => n.dataset.id));
1810
+ const kept = new Map([.../** @type {HTMLCollectionOf<HTMLElement>} */
1811
+ box.children].filter((n) => n.dataset.id).map((n) => [n.dataset.id, n]));
1812
+ const same = (n) => {
1813
+ const old = kept.get(n.dataset?.id);
1814
+ return old && old.outerHTML.replace(" fresh", "") === n.outerHTML ? old : n;
1815
+ };
1816
+ patchKids(box, msgs.flatMap((m) => {
1817
+ const root2 = m.parent ? byId.get(m.parent) : m;
1818
+ const b = el2("div", { class: `msg${mine(m) && !m.session ? " mine" : ""}${root2 && replyTo === root2.id ? " to" : ""}${before.size && !before.has(m.id) ? " fresh" : ""}`, "data-id": m.id, ...agentOf(m) ? { "data-agent": agentOf(m) } : {} });
1819
+ b.append(nameLine(m.name, false));
1820
+ if (m.parent && root2) {
1821
+ const q = el2("div", { class: "quote" });
1822
+ q.append(el2("b", {}, String(root2.name || "").replace(/\s*·\s*session\s+\S+$/i, "")), document.createTextNode(root2.text.replace(/\s+/g, " ").slice(0, 90)));
1823
+ q.addEventListener("click", (e) => {
1824
+ e.stopPropagation();
1825
+ const box2 = $(".msgs", chatEl);
1826
+ const to = $(`[data-id="${root2.id}"]`, box2);
1827
+ if (!to) return;
1828
+ box2.scrollTo({ top: to.offsetTop - box2.offsetTop - 12, behavior: still.matches ? "auto" : "smooth" });
1829
+ to.animate?.([{ boxShadow: "0 0 0 2px rgb(52,199,89)" }, { boxShadow: "0 0 0 0 transparent" }], { duration: 900 });
1830
+ });
1831
+ b.append(q);
1832
+ }
1833
+ b.append(...readable(m.text));
1834
+ stamped(b, stampOf(m, root2));
1835
+ return m.id === newFrom && m !== msgs[0] ? [el2("div", { class: "newline" }, "new"), b] : [b];
1836
+ }).map(same));
1837
+ const strip = $(".replying", chatEl);
1838
+ const target = replyTo && byId.get(replyTo);
1839
+ strip.hidden = !target;
1840
+ if (target) {
1841
+ const x = el2("button", { type: "button", title: "about the page instead" }, "\u2715");
1842
+ x.addEventListener("click", () => (replyTo = null, drawChat()));
1843
+ strip.replaceChildren(document.createTextNode(`\u21A9 ${target.name}: ${target.text.replace(/\s+/g, " ").slice(0, 40)}`), x);
1844
+ }
1845
+ if (!box.firstChild) box.append(el2("div", { class: "none" }, "say something about the page as a whole"));
1846
+ const chat = chatEl.querySelector(".chat");
1847
+ if (!chat.firstChild)
1848
+ chat.append(
1849
+ composer({
1850
+ placeholder: "message",
1851
+ onSubmit: async (name, text) => {
1852
+ const { comment } = await send(
1853
+ replyTo ? { name, text, parent: replyTo } : { name, text, anchor: { kind: "page", width: innerWidth, height: innerHeight, dpr: devicePixelRatio || 1 } }
1854
+ );
1855
+ const answered = replyTo && comments.find((x) => x.id === replyTo);
1856
+ if (answered?.resolved) answered.resolved = false;
1857
+ replyTo = null;
1858
+ comments.push(comment);
1859
+ markSeen([comment]);
1860
+ box.scrollTop = box.scrollHeight;
1861
+ render();
1862
+ return { keep: true };
1863
+ }
1864
+ })
1865
+ );
1866
+ chat.querySelector("textarea").placeholder = target ? "reply" : "message";
1867
+ if (atEnd) box.scrollTop = box.scrollHeight;
1868
+ }
1869
+ const numberOf = (c) => comments.filter((x) => !x.parent && !x.resolved).sort((a, b) => a.createdAt.localeCompare(b.createdAt)).indexOf(c) + 1;
1870
+ const seenKey = () => `lab-seen:${page}`;
1871
+ const readSeen = () => new Set(store2.get(seenKey()).split(",").filter(Boolean));
1872
+ let seen = readSeen();
1873
+ const plain = (n) => String(n || "").replace(/\s+/g, " ").trim().toLowerCase();
1874
+ const mine = (c) => plain(c.name) && plain(c.name) === plain(store2.get("lab-name")) || Boolean(store2.get(`lab-edit:${c.id}`));
1875
+ const isNew = (c) => !seen.has(c.id) && !mine(c);
1876
+ const unread = (c) => [c, ...repliesOf(c.id)].filter(isNew);
1877
+ const markSeen = (items) => {
1878
+ const fresh = items.filter((item) => !seen.has(item.id)).map((item) => item.id);
1879
+ for (const item of items) seen.add(item.id);
1880
+ store2.set(seenKey(), [...seen].join(","));
1881
+ if (fresh.length) shareReads(fresh);
1882
+ };
1883
+ const READS = script?.dataset.live ? script.dataset.live.replace(/live$/, "api/reads") : "";
1884
+ const shareReads = (ids) => {
1885
+ const who = store2.get("lab-name").trim();
1886
+ if (!READS || !who || !ids.length) return;
1887
+ fetch(READS, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: who, page, ids }) }).catch(() => {
1888
+ });
1889
+ };
1890
+ async function syncReads() {
1891
+ const who = store2.get("lab-name").trim();
1892
+ if (!READS || !who) return;
1893
+ const at = page;
1894
+ try {
1895
+ const { ids } = await (await fetch(`${READS}?name=${encodeURIComponent(who)}&page=${encodeURIComponent(at)}`, { cache: "no-store" })).json();
1896
+ if (at !== page) return;
1897
+ const theirs = new Set(ids);
1898
+ const mineOnly = [...seen].filter((id) => !theirs.has(id));
1899
+ const added = ids.filter((id) => !seen.has(id));
1900
+ if (mineOnly.length) shareReads(mineOnly);
1901
+ if (!added.length) return;
1902
+ for (const id of added) seen.add(id);
1903
+ store2.set(seenKey(), [...seen].join(","));
1904
+ shownAgain();
1905
+ } catch {
1906
+ }
1907
+ }
1908
+ const repliesOf = (id) => comments.filter((c) => c.parent === id);
1909
+ const initial = (name) => [...String(name || "").trim()][0]?.toUpperCase() || "";
1910
+ function placeCard(card, left, top) {
1911
+ layer2.append(card);
1912
+ const width = card.offsetWidth;
1913
+ const maxLeft = scrollX + document.documentElement.clientWidth - width - 12;
1914
+ card.style.left = `${Math.max(scrollX + 12, Math.min(left - 14, maxLeft))}px`;
1915
+ const h = card.offsetHeight;
1916
+ const below = top + 10 + h > contentEnd();
1917
+ card.style.top = `${below ? Math.max(scrollY + 8, top - 40 - h) : top + 10}px`;
1918
+ card.style.transformOrigin = below ? "14px 100%" : "";
1919
+ }
1920
+ const contentEnd = () => {
1921
+ inPage(0);
1922
+ return pageEnd.y;
1923
+ };
1924
+ const ARROW = '<i class="arr" aria-hidden="true"></i>';
1925
+ function composer({ placeholder, onSubmit, autofocus = false }) {
1926
+ const wrap = el2("div", { class: "composer" });
1927
+ const box = el2("div", { class: "box" });
1928
+ const text = el2("textarea", { placeholder, maxlength: "2000", rows: "1", "aria-label": placeholder, enterkeyhint: "send", autocomplete: "off", autocorrect: "off", spellcheck: "false", writingsuggestions: "false" });
1929
+ const who = el2("label", { class: "who" });
1930
+ const as = el2("span", {}, "as");
1931
+ const name = el2("input", { type: "text", placeholder: "your name", maxlength: "60", enterkeyhint: "send", autocomplete: "off", autocorrect: "off", autocapitalize: "words", spellcheck: "false", writingsuggestions: "false", "data-1p-ignore": "", "data-lpignore": "true" });
1932
+ name.value = store2.get("lab-name");
1933
+ who.append(as, name);
1934
+ const sendBtn2 = el2("button", { class: "send", type: "button", "aria-label": "send" });
1935
+ sendBtn2.addEventListener("pointerdown", (e) => e.preventDefault());
1936
+ sendBtn2.addEventListener("mousedown", (e) => e.preventDefault());
1937
+ sendBtn2.innerHTML = ARROW;
1938
+ const error = el2("div", { class: "error" });
1939
+ box.append(text, el2("div", { class: "line" }), who, sendBtn2);
1940
+ wrap.append(box, error);
1941
+ box.addEventListener("click", (e) => {
1942
+ if (e.target !== box && !e.target.classList?.contains("line")) return;
1943
+ text.focus({ preventScroll: true });
1944
+ text.setSelectionRange(text.value.length, text.value.length);
1945
+ });
1946
+ const sync = () => {
1947
+ const open = text.value.length > 0 || root.activeElement === name || !!error.textContent;
1948
+ const glide = open !== box.classList.contains("open") && !store2.get("lab-name") && box.isConnected && !matchMedia("(prefers-reduced-motion: reduce)").matches;
1949
+ const from = glide && { arrow: sendBtn2.getBoundingClientRect(), height: box.getBoundingClientRect().height };
1950
+ const one = Boolean(store2.get("lab-name"));
1951
+ box.classList.toggle("one", one);
1952
+ box.classList.toggle("open", open);
1953
+ as.hidden = !name.value.trim();
1954
+ if (one && !CSS.supports?.("field-sizing", "content")) name.style.width = `${Math.max(2, name.value.length + 1)}ch`;
1955
+ sendBtn2.classList.toggle("ready", Boolean(text.value.trim() && name.value.trim()));
1956
+ text.style.height = "auto";
1957
+ text.style.height = `${text.scrollHeight}px`;
1958
+ if (glide) {
1959
+ const to = sendBtn2.getBoundingClientRect();
1960
+ const timing = { duration: 220, easing: "cubic-bezier(.2, .7, .3, 1)" };
1961
+ sendBtn2.animate([{ transform: `translate(${from.arrow.left - to.left}px, ${from.arrow.top - to.top}px)` }, { transform: "none" }], timing);
1962
+ box.style.overflow = "hidden";
1963
+ box.animate([{ height: `${from.height}px` }, { height: `${box.getBoundingClientRect().height}px` }], timing).onfinish = () => box.style.overflow = "";
1964
+ }
1965
+ };
1966
+ let busy = false;
1967
+ const go = async () => {
1968
+ if (busy) return;
1969
+ if (!text.value.trim()) return text.focus();
1970
+ if (!name.value.trim()) {
1971
+ box.classList.add("open");
1972
+ return name.focus();
1973
+ }
1974
+ store2.set("lab-name", name.value.trim());
1975
+ refreshPinCursor();
1976
+ syncReads();
1977
+ sendBtn2.classList.remove("sent");
1978
+ void sendBtn2.offsetWidth;
1979
+ sendBtn2.classList.add("sent");
1980
+ busy = true;
1981
+ error.textContent = "";
1982
+ error.classList.remove("wait");
1983
+ const slow = setTimeout(() => {
1984
+ error.textContent = "sending\u2026 it goes as soon as the lab is back";
1985
+ error.classList.add("wait");
1986
+ }, 1500);
1987
+ try {
1988
+ const result = await onSubmit(name.value.trim(), text.value.trim());
1989
+ clearTimeout(slow);
1990
+ error.textContent = "";
1991
+ error.classList.remove("wait");
1992
+ if (result?.keep) {
1993
+ text.value = "";
1994
+ sync();
1995
+ }
1996
+ } catch (e) {
1997
+ clearTimeout(slow);
1998
+ error.classList.remove("wait");
1999
+ error.textContent = e.message;
2000
+ sync();
2001
+ }
2002
+ busy = false;
2003
+ };
2004
+ const onKey = (e) => {
2005
+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
2006
+ e.preventDefault();
2007
+ go();
2008
+ }
2009
+ };
2010
+ text.addEventListener("input", sync);
2011
+ name.addEventListener("input", sync);
2012
+ name.addEventListener("blur", () => setTimeout(sync, 0));
2013
+ text.addEventListener("keydown", onKey);
2014
+ name.addEventListener("keydown", onKey);
2015
+ sendBtn2.addEventListener("click", go);
2016
+ sendBtn2.addEventListener("mousedown", (e) => e.preventDefault());
2017
+ requestAnimationFrame(sync);
2018
+ const focus = () => text.focus({ preventScroll: true });
2019
+ if (autofocus) queueMicrotask(() => text.isConnected ? focus() : setTimeout(focus, 0));
2020
+ return wrap;
2021
+ }
2022
+ function placeBeside(node, left, top) {
2023
+ layer2.append(node);
2024
+ const width = node.offsetWidth;
2025
+ const right = scrollX + document.documentElement.clientWidth - 12;
2026
+ const h = node.offsetHeight;
2027
+ const end = contentEnd();
2028
+ if (left + 36 + width <= right) {
2029
+ node.style.left = `${left + 36}px`;
2030
+ node.style.top = `${Math.min(top - 37, end - h - 8)}px`;
2031
+ } else {
2032
+ node.style.left = `${Math.max(scrollX + 12, Math.min(left - 14, right - width))}px`;
2033
+ node.style.top = `${top + 10 + h > end ? Math.max(scrollY + 8, top - 40 - h) : top + 10}px`;
2034
+ }
2035
+ }
2036
+ let shown = null;
2037
+ let posted = null;
2038
+ const still = matchMedia("(prefers-reduced-motion: reduce)");
2039
+ const pinsById = /* @__PURE__ */ new Map();
2040
+ let dropDrag = null;
2041
+ function render() {
2042
+ grabbing = false;
2043
+ dropDrag?.();
2044
+ const prev = (
2045
+ /** @type {HTMLElement | null} */
2046
+ layer2.querySelector(".card:not(.out), .float:not(.out)")
2047
+ );
2048
+ const prevHeight = stepping && coarse && prev ? prev.offsetHeight : 0;
2049
+ const prevScroll = prev ? prev.querySelector(".body")?.scrollTop ?? null : null;
2050
+ const places = new Map(on ? threads().filter((c) => c.anchor?.kind !== "page").map((c) => [c.id, position(c.anchor || {})]) : []);
2051
+ layer2.replaceChildren();
2052
+ pinsById.clear();
2053
+ const now = on ? draft || openId : null;
2054
+ const appear = now !== shown;
2055
+ const anim = appear ? " in" : "";
2056
+ let quoted = null;
2057
+ const done = () => {
2058
+ if (closeFast && !now && prev) {
2059
+ closeFast = false;
2060
+ prev.inert = true;
2061
+ layer2.append(prev);
2062
+ const gone2 = () => prev.remove();
2063
+ if (still.matches || !prev.animate) gone2();
2064
+ else prev.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 120, easing: "ease-out", fill: "forwards" }).finished.then(gone2, gone2);
2065
+ } else if (coarse && !now && shown && prev && !still.matches && !prev.style.transform) {
2066
+ prev.classList.remove("in");
2067
+ prev.classList.add("out");
2068
+ prev.inert = true;
2069
+ layer2.append(prev);
2070
+ setTimeout(() => prev.remove(), coarse ? 230 : 150);
2071
+ }
2072
+ markQuote(quoted);
2073
+ shown = now;
2074
+ posted = null;
2075
+ };
2076
+ const list = threads();
2077
+ const open = list.filter((c) => !c.resolved && c.anchor?.kind !== "page").length;
2078
+ const fresh = list.filter((c) => !c.resolved && c.anchor?.kind !== "page").reduce((n, c) => n + unread(c).length, 0);
2079
+ toggleBtn.replaceChildren(
2080
+ document.createTextNode((on ? "hide comments" : open ? `comments \xB7 ${open}` : "comments") + (!on && fresh ? ` \xB7 ${fresh} new` : "")),
2081
+ el2("kbd", { "aria-hidden": "true" }, "m")
2082
+ );
2083
+ toggleBtn.classList.toggle("secondary", on);
2084
+ host2.toggleAttribute("data-sheet", Boolean(on && (draft || openId || listOpen || chatOpen)));
2085
+ document.documentElement.classList.toggle("lab-sheet", host2.hasAttribute("data-sheet"));
2086
+ backCloses();
2087
+ refit();
2088
+ document.documentElement.classList.toggle("lab-pinning", on && !cursorMode);
2089
+ document.documentElement.classList.toggle("lab-go", on && goMode && !cursorMode);
2090
+ copyBtn.hidden = !on || !isAdmin || list.every((c) => c.resolved);
2091
+ drawList();
2092
+ drawChat();
2093
+ if (!on) return done();
2094
+ for (const h of held()) {
2095
+ const { left, top } = position(h.anchor);
2096
+ const p = el2("div", { class: "pin held", title: `${h.name}: ${h.text} \xB7 draft, not sent yet` }, initial(h.name));
2097
+ p.style.left = `${left}px`;
2098
+ p.style.top = `${top}px`;
2099
+ layer2.append(p);
2100
+ }
2101
+ list.forEach((c) => {
2102
+ if (isPage(c)) return;
2103
+ if (!showDone && openId !== c.id && (c.resolved || workState(c)[0] === "done") && !unread(c).length) return;
2104
+ const { left, top, moved, zone } = places.get(c.id) || position(c.anchor || {});
2105
+ if (openId === c.id) drawZone(zone, `saved${anim}`);
2106
+ const news = unread(c);
2107
+ const movable = !zone && (isAdmin || store2.get(`lab-edit:${c.id}`));
2108
+ const [state] = workState(c);
2109
+ const pin = el2(
2110
+ "button",
2111
+ {
2112
+ class: `pin${/^go$/i.test(c.text.trim()) ? " go" : ""}${c.resolved ? " resolved" : ""}${state === "done" ? " done" : ""}${state === "now" ? " working" : ""}${news.length ? " new" : ""}${moved ? " moved" : ""}${posted === c.id ? " in" : ""}${movable ? " grab" : ""}${openId === c.id ? " open" : ""}`,
2113
+ type: "button",
2114
+ title: `${c.resolved ? "" : `${numberOf(c)} \xB7 `}${c.name}${moved ? " \xB7 the spot it was pinned to has changed" : ""}${movable ? " \xB7 drag to move" : ""}`,
2115
+ // Its state in words too (the ring, the tick and the new dot are only seen).
2116
+ "aria-label": `${/^go$/i.test(c.text.trim()) ? "go" : "comment"}${c.resolved ? "" : ` ${numberOf(c)}`} by ${c.name}${state === "now" ? ", agent working on it" : state === "done" || c.resolved ? ", done" : ""}${news.length ? `, ${news.length} new` : ""}${moved ? ", moved" : ""}`
2117
+ },
2118
+ /^go$/i.test(c.text.trim()) ? "go" : state === "done" || c.resolved ? "\u2713" : initial(c.name)
2119
+ );
2120
+ if (state === "now") pin.append(el2("i", { class: "ring", "aria-hidden": "true" }));
2121
+ pin.style.left = `${left}px`;
2122
+ pin.style.top = `${top}px`;
2123
+ if (movable) grab(pin, c);
2124
+ if (!coarse && zone && openId !== c.id) {
2125
+ let shown2 = null;
2126
+ pin.addEventListener("pointerenter", () => shown2 = drawZone(zone, "saved"));
2127
+ pin.addEventListener("pointerleave", () => (shown2?.remove(), shown2 = null));
2128
+ } else if (!coarse && c.anchor?.quote && !zone) {
2129
+ pin.addEventListener("pointerenter", () => markQuote(c.anchor));
2130
+ pin.addEventListener("pointerleave", () => markQuote(quoted));
2131
+ }
2132
+ pin.addEventListener("click", (e) => {
2133
+ e.stopPropagation();
2134
+ if (pin.dataset.dragged) return;
2135
+ if (coarse && openId !== c.id) return goTo(c);
2136
+ openId = openId === c.id ? null : c.id;
2137
+ draft = null;
2138
+ render();
2139
+ });
2140
+ layer2.append(pin);
2141
+ pinsById.set(c.id, pin);
2142
+ if (openId === c.id) {
2143
+ const card = threadCard(c, new Set(news.map((x) => x.id)), appear && (coarse ? keepKeys : !stepping || keepKeys));
2144
+ openCard = card;
2145
+ if (appear && !stepping) card.classList.add("in");
2146
+ if (prevHeight) card.style.minHeight = `min(${prevHeight}px, var(--_sheet-max))`;
2147
+ stepping = keepKeys = false;
2148
+ placeCard(card, zone ? left + 14 : left, zone ? zone.top + zone.height : top);
2149
+ if (!appear && prevScroll != null) card.querySelector(".body").scrollTop = prevScroll;
2150
+ else if (appear) {
2151
+ const body = card.querySelector(".body");
2152
+ const first = coarse ? null : body.querySelector(".fresh, .newline");
2153
+ body.scrollTop = first ? first.offsetTop - body.offsetTop - 8 : body.scrollHeight;
2154
+ }
2155
+ if (coarse && cardFull) card.classList.add("full");
2156
+ swipeDown(card, () => (openId = null, cardFull = false, render()), true);
2157
+ markSeen(news);
2158
+ if (news.length) drawList();
2159
+ quoted = zone ? null : c.anchor;
2160
+ }
2161
+ });
2162
+ if (draft) {
2163
+ const { anchor } = draft;
2164
+ const { left, top, zone } = position(anchor);
2165
+ drawZone(zone, "draft");
2166
+ quoted = zone ? null : anchor;
2167
+ const pin = el2("div", { class: `pin draft${anim}` }, initial(store2.get("lab-name")));
2168
+ pin.style.left = `${left}px`;
2169
+ pin.style.top = `${top}px`;
2170
+ layer2.append(pin);
2171
+ const float = el2("div", { class: `float${anim}` });
2172
+ float.append(
2173
+ el2("div", { class: "handle" }),
2174
+ composer({
2175
+ placeholder: "add a comment",
2176
+ autofocus: true,
2177
+ onSubmit: async (name, text) => {
2178
+ if (drafting()) {
2179
+ store2.set(heldKey(), JSON.stringify([...held(), { name, text, anchor }]));
2180
+ draft = null;
2181
+ return render();
2182
+ }
2183
+ const { comment, edit } = await send({ name, text, anchor });
2184
+ if (edit) store2.set(`lab-edit:${comment.id}`, edit);
2185
+ comments.push(comment);
2186
+ markSeen([comment]);
2187
+ draft = null;
2188
+ openId = null;
2189
+ posted = comment.id;
2190
+ render();
2191
+ }
2192
+ })
2193
+ );
2194
+ swipeDown(float, () => (draft = null, render()));
2195
+ if (zone) placeCard(float, left + 14, zone.top + zone.height);
2196
+ else placeBeside(float, left, top);
2197
+ }
2198
+ done();
2199
+ }
2200
+ let grabbing = false;
2201
+ function grab(pin, c) {
2202
+ pin.addEventListener("pointerdown", (e) => {
2203
+ if (e.button !== 0) return;
2204
+ const r = pin.getBoundingClientRect();
2205
+ const tip = { dx: e.clientX - r.left, dy: e.clientY - r.bottom };
2206
+ const start2 = { x: e.clientX, y: e.clientY, sx: scrollX, sy: scrollY, left: parseFloat(pin.style.left), top: parseFloat(pin.style.top) };
2207
+ let moving = false;
2208
+ let last = e;
2209
+ grabbing = true;
2210
+ pin.setPointerCapture(e.pointerId);
2211
+ const place2 = () => {
2212
+ pin.style.left = `${start2.left + last.clientX - start2.x + scrollX - start2.sx}px`;
2213
+ pin.style.top = `${start2.top + last.clientY - start2.y + scrollY - start2.sy}px`;
2214
+ };
2215
+ const move = (ev) => {
2216
+ last = ev;
2217
+ if (!moving && Math.hypot(ev.clientX - start2.x, ev.clientY - start2.y) < 5) return;
2218
+ moving = true;
2219
+ pin.classList.add("dragging");
2220
+ place2();
2221
+ };
2222
+ const scrolled = () => moving && place2();
2223
+ addEventListener("scroll", scrolled, true);
2224
+ dropDrag = () => {
2225
+ removeEventListener("scroll", scrolled, true);
2226
+ dropDrag = null;
2227
+ };
2228
+ const up = async (ev) => {
2229
+ pin.removeEventListener("pointermove", move);
2230
+ pin.removeEventListener("pointerup", up);
2231
+ pin.removeEventListener("pointercancel", up);
2232
+ pin.removeEventListener("lostpointercapture", up);
2233
+ dropDrag?.();
2234
+ if (!grabbing) return;
2235
+ grabbing = false;
2236
+ if (!moving) return;
2237
+ pin.dataset.dragged = "1";
2238
+ setTimeout(() => delete pin.dataset.dragged, 0);
2239
+ const x = ev.clientX - tip.dx;
2240
+ const y = ev.clientY - tip.dy;
2241
+ const under = document.elementsFromPoint(x, y).find((n) => n !== host2);
2242
+ if (ev.type === "pointercancel" || x < 0 || y < 0 || x > innerWidth || y > innerHeight || under?.closest(OFF)) return render();
2243
+ const before = c.anchor;
2244
+ c.anchor = anchorAt(x, y);
2245
+ render();
2246
+ try {
2247
+ const { comment } = await send({ action: "move", id: c.id, anchor: c.anchor, edit: store2.get(`lab-edit:${c.id}`) || void 0 });
2248
+ Object.assign(c, comment);
2249
+ } catch {
2250
+ c.anchor = before;
2251
+ render();
2252
+ }
2253
+ };
2254
+ pin.addEventListener("pointermove", move);
2255
+ pin.addEventListener("pointerup", up);
2256
+ pin.addEventListener("pointercancel", up);
2257
+ pin.addEventListener("lostpointercapture", up);
2258
+ });
2259
+ }
2260
+ let openCard = null;
2261
+ const coarse = matchMedia("(pointer: coarse)").matches;
2262
+ function threadCard(c, fresh = /* @__PURE__ */ new Set(), focus = false) {
2263
+ const card = el2("div", { class: "card" });
2264
+ const body = el2("div", { class: "body" });
2265
+ const foot = el2("div", { class: "foot" });
2266
+ card.append(el2("div", { class: "handle" }), body, foot);
2267
+ card.addEventListener("click", (e) => e.stopPropagation());
2268
+ body.classList.add("msgs");
2269
+ const itemEl = (item) => {
2270
+ const box = el2("div", { class: `item msg${mine(item) && !item.session ? " mine" : ""}`, "data-id": item.id, ...agentOf(item) ? { "data-agent": agentOf(item) } : {} });
2271
+ box.append(nameLine(item.name, false), ...readable(item.text));
2272
+ stamped(box, stampOf(item, c, item === c && !c.resolved ? `#${numberOf(c)} \xB7 ` : ""));
2273
+ return box;
2274
+ };
2275
+ const shown2 = /* @__PURE__ */ new Set();
2276
+ const all = [c, ...repliesOf(c.id)];
2277
+ const firstNew = all.find((x) => fresh.has(x.id));
2278
+ for (const item of all) {
2279
+ if (item === firstNew && item !== c) body.append(el2("div", { class: "newline" }, "new"));
2280
+ body.append(itemEl(item));
2281
+ shown2.add(item.id);
2282
+ }
2283
+ card.sync = () => {
2284
+ for (const r of repliesOf(c.id)) {
2285
+ if (shown2.has(r.id)) continue;
2286
+ const items = card.querySelectorAll(".item");
2287
+ const added = itemEl(r);
2288
+ added.classList.add("fresh");
2289
+ items[items.length - 1].after(added);
2290
+ shown2.add(r.id);
2291
+ markSeen([r]);
2292
+ }
2293
+ };
2294
+ const ownKey = store2.get(`lab-edit:${c.id}`);
2295
+ let actions = null;
2296
+ if (isAdmin || ownKey) {
2297
+ actions = el2("div", { class: "row acts" });
2298
+ const resolve = el2("button", { class: "btn", type: "button" }, c.resolved ? "reopen" : "resolve");
2299
+ const failed = (btn) => btn.textContent = "failed, try again";
2300
+ resolve.addEventListener("click", async () => {
2301
+ try {
2302
+ const closing = !c.resolved;
2303
+ const { comment } = await send({ action: c.resolved ? "reopen" : "resolve", id: c.id, ...ownKey ? { edit: ownKey } : {} });
2304
+ Object.assign(c, comment);
2305
+ if (closing && openId === c.id) return closeFast = true, openId = null, render();
2306
+ render();
2307
+ } catch {
2308
+ failed(resolve);
2309
+ }
2310
+ });
2311
+ const del = el2("button", { class: "btn", type: "button" }, "delete");
2312
+ const yes = el2("button", { class: "btn danger", type: "button" }, "delete");
2313
+ const no = el2("button", { class: "btn", type: "button" }, "cancel");
2314
+ const back = () => {
2315
+ actions.replaceChildren(resolve, del);
2316
+ del.focus();
2317
+ };
2318
+ del.addEventListener("click", () => {
2319
+ actions.replaceChildren(el2("span", { class: "ask" }, repliesOf(c.id).length ? "delete thread?" : "delete comment?"), yes, no);
2320
+ no.focus();
2321
+ });
2322
+ no.addEventListener("click", back);
2323
+ actions.addEventListener("keydown", (e) => {
2324
+ if (e.key === "Escape" && yes.isConnected) {
2325
+ e.stopPropagation();
2326
+ back();
2327
+ }
2328
+ });
2329
+ yes.addEventListener("click", async () => {
2330
+ try {
2331
+ await send({ action: "delete", id: c.id });
2332
+ } catch {
2333
+ return failed(yes);
2334
+ }
2335
+ comments = comments.filter((x) => x.id !== c.id && x.parent !== c.id);
2336
+ openId = null;
2337
+ render();
2338
+ });
2339
+ actions.append(...isAdmin ? [resolve, del] : [resolve]);
2340
+ body.append(actions);
2341
+ }
2342
+ if (coarse) {
2343
+ const topOf = (x) => position(x.anchor || {}).top;
2344
+ const here = topOf(c);
2345
+ const fresh2 = threads().filter((x) => !isPage(x) && x.id !== c.id && unread(x).length).map((x) => [x, topOf(x)]);
2346
+ fresh2.sort((p, q) => (p[1] > here ? 0 : 1) - (q[1] > here ? 0 : 1) || p[1] - q[1]);
2347
+ const nav = el2("div", { class: "row nav" });
2348
+ if (fresh2.length) {
2349
+ const b = el2("button", { class: "btn", type: "button" }, `new \xB7 ${fresh2.length} \u203A`);
2350
+ b.addEventListener("pointerdown", (e) => e.preventDefault());
2351
+ b.addEventListener("click", () => goTo(fresh2[0][0]));
2352
+ nav.append(b);
2353
+ }
2354
+ if (actions) nav.append(actions);
2355
+ if (nav.firstChild) card.insertBefore(nav, body);
2356
+ }
2357
+ foot.append(
2358
+ composer({
2359
+ placeholder: "reply",
2360
+ autofocus: focus,
2361
+ onSubmit: async (name, text) => {
2362
+ const { comment } = await send({ name, text, parent: c.id });
2363
+ comments.push(comment);
2364
+ markSeen([comment]);
2365
+ if (c.resolved) {
2366
+ c.resolved = false;
2367
+ render();
2368
+ const again = openCard?.querySelector(".body");
2369
+ if (again) again.scrollTop = again.scrollHeight;
2370
+ openCard?.querySelector("textarea")?.focus({ preventScroll: true });
2371
+ return { keep: true };
2372
+ }
2373
+ shown2.add(comment.id);
2374
+ const items = card.querySelectorAll(".item");
2375
+ const added = itemEl(comment);
2376
+ added.classList.add("fresh");
2377
+ items[items.length - 1].after(added);
2378
+ body.scrollTop = body.scrollHeight;
2379
+ return { keep: true };
2380
+ }
2381
+ })
2382
+ );
2383
+ return card;
2384
+ }
2385
+ const showHint = () => {
2386
+ if (store2.get("lab-hint-seen") === "1") return;
2387
+ hint.hidden = false;
2388
+ store2.set("lab-hint-seen", "1");
2389
+ setTimeout(() => hint.hidden = true, 5e3);
2390
+ };
2391
+ const setOn = (value) => {
2392
+ on = value;
2393
+ if (!on) ptr.classList.remove("show");
2394
+ else recheck();
2395
+ store2.set("lab-on", on ? "1" : "0");
2396
+ if (on) showHint();
2397
+ draft = null;
2398
+ openId = null;
2399
+ render();
2400
+ };
2401
+ toggleBtn.addEventListener("click", () => setOn(!on));
2402
+ function setMenu(open, refocus = false) {
2403
+ moreMenu.hidden = !open;
2404
+ moreBtn.setAttribute("aria-expanded", String(open));
2405
+ if (open) [...moreMenu.querySelectorAll("button")].find((b) => !b.hidden && !b.disabled)?.focus({ preventScroll: true });
2406
+ else if (refocus) moreBtn.focus({ preventScroll: true });
2407
+ }
2408
+ moreBtn.addEventListener("click", (e) => {
2409
+ e.stopPropagation();
2410
+ setMenu(moreMenu.hidden);
2411
+ });
2412
+ moreMenu.addEventListener("click", () => setTimeout(() => setMenu(false, true), 0));
2413
+ addEventListener("pointerdown", (e) => {
2414
+ if (!moreMenu.hidden && !e.composedPath().some((n) => n === moreMenu || n === moreBtn)) setMenu(false);
2415
+ }, true);
2416
+ addEventListener("keydown", (e) => {
2417
+ if (e.key === "Escape" && !moreMenu.hidden) {
2418
+ setMenu(false, true);
2419
+ e.stopPropagation();
2420
+ }
2421
+ }, true);
2422
+ goBtn.addEventListener("click", () => setGo(!goMode));
2423
+ const stepNew = (dir) => {
2424
+ const fresh = threads().filter((c) => !isPage(c) && unread(c).length);
2425
+ if (!fresh.length) return;
2426
+ const top = (c) => position(c.anchor || {}).top;
2427
+ fresh.sort((a, b) => top(a) - top(b));
2428
+ const open = openId && threads().find((c) => c.id === openId);
2429
+ const here = open ? top(open) : null;
2430
+ const after = here == null ? -1 : fresh.findIndex((c) => top(c) > here);
2431
+ const at = fresh.findIndex((c) => c.id === openId);
2432
+ const next = at >= 0 ? (at + dir + fresh.length) % fresh.length : here == null ? dir > 0 ? 0 : fresh.length - 1 : dir > 0 ? after < 0 ? 0 : after : ((after < 0 ? fresh.length : after) - 1 + fresh.length) % fresh.length;
2433
+ chatOpen = false;
2434
+ goTo(fresh[next], !coarse);
2435
+ };
2436
+ newPrev.addEventListener("click", () => stepNew(-1));
2437
+ doneBtn.addEventListener("click", () => showDoneBtn.click());
2438
+ showDoneBtn.addEventListener("click", () => {
2439
+ showDone = !showDone;
2440
+ store2.set("lab-show-done", showDone ? "1" : "");
2441
+ render();
2442
+ });
2443
+ newNext.addEventListener("click", () => stepNew(1));
2444
+ const showAgain = () => {
2445
+ if (on) return;
2446
+ on = true;
2447
+ store2.set("lab-on", "1");
2448
+ };
2449
+ copyBtn.addEventListener("click", () => copy(agentLink(), copyBtn));
2450
+ listBtn.addEventListener("click", () => LIST_WINDOW ? (listOpen = !listOpen, listOpen && (filter = "new"), chatOpen = false, hint.hidden = true, render()) : stepNew(1));
2451
+ listEl.querySelector(".x").addEventListener("click", () => slideAway(listEl, () => (listOpen = false, render())));
2452
+ chatBtn.addEventListener("click", () => {
2453
+ chatOpen = !chatOpen;
2454
+ listOpen = false;
2455
+ if (chatOpen && !coarse) {
2456
+ openId = null;
2457
+ if (draft && !/** @type {HTMLTextAreaElement | null} */
2458
+ root.querySelector(".float textarea")?.value.trim()) draft = null;
2459
+ }
2460
+ hint.hidden = true;
2461
+ render();
2462
+ if (chatOpen && !coarse) chatEl.querySelector(".chat textarea")?.focus({ preventScroll: true });
2463
+ });
2464
+ let closingClick = false;
2465
+ document.addEventListener("pointerdown", (e) => {
2466
+ closingClick = false;
2467
+ if (coarse || !chatOpen || e.button !== 0) return;
2468
+ const path = e.composedPath();
2469
+ if (path.includes(chatEl) || path.includes(chatBtn)) return;
2470
+ chatOpen = false;
2471
+ if (path.includes(host2)) return void addEventListener("click", () => render(), { once: true });
2472
+ closingClick = true;
2473
+ render();
2474
+ }, true);
2475
+ addEventListener("click", (e) => {
2476
+ if (!closingClick) return;
2477
+ closingClick = false;
2478
+ e.preventDefault();
2479
+ e.stopImmediatePropagation();
2480
+ }, true);
2481
+ for (
2482
+ const b of
2483
+ /** @type {NodeListOf<HTMLElement>} */
2484
+ listEl.querySelectorAll("[data-f]")
2485
+ ) b.addEventListener("click", () => (filter = b.dataset.f, drawList()));
2486
+ holdBtn.addEventListener("click", () => (store2.set("lab-hold", drafting() ? "" : "1"), drawList()));
2487
+ sendBtn.addEventListener("click", async () => {
2488
+ const list = held();
2489
+ for (let i = 0; i < list.length; i++) {
2490
+ try {
2491
+ const { comment, edit } = await send(list[i]);
2492
+ if (edit) store2.set(`lab-edit:${comment.id}`, edit);
2493
+ comments.push(comment);
2494
+ markSeen([comment]);
2495
+ store2.set(heldKey(), JSON.stringify(list.slice(i + 1)));
2496
+ } catch {
2497
+ sendBtn.textContent = "send failed, try again";
2498
+ return;
2499
+ }
2500
+ }
2501
+ render();
2502
+ });
2503
+ const typing = (e) => e.composedPath().some((n) => n instanceof HTMLElement && (n.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(n.tagName)));
2504
+ document.addEventListener("keydown", (e) => {
2505
+ if (gone) return;
2506
+ const inOtherWidget = document.activeElement?.localName.includes("-") && document.activeElement !== host2;
2507
+ if ((e.key === "m" || e.key === "M" || e.code === "KeyM") && !e.metaKey && !e.ctrlKey && !e.altKey && !e.repeat && !typing(e) && !inOtherWidget) {
2508
+ e.preventDefault();
2509
+ setOn(!on);
2510
+ return;
2511
+ }
2512
+ if (on && (e.metaKey || e.ctrlKey) && !e.shiftKey && !e.altKey && (/^z$/i.test(e.key || "") || !/^[a-z]$/i.test(e.key || "") && e.code === "KeyZ") && !typing(e) && !inOtherWidget && placed.length) {
2513
+ e.preventDefault();
2514
+ return void undoLast();
2515
+ }
2516
+ if (on && e.ctrlKey && !e.metaKey && !e.altKey && e.code === "KeyD" && !(typing(e) && !e.composedPath().includes(host2))) {
2517
+ e.preventDefault();
2518
+ const typed2 = (
2519
+ /** @type {HTMLTextAreaElement | null} */
2520
+ root.querySelector(".card textarea, .float textarea")
2521
+ );
2522
+ if (typed2?.value.trim()) return typed2.closest(".card, .float")?.animate([{ transform: "none" }, { transform: "translateX(-6px)" }, { transform: "translateX(6px)" }, { transform: "none" }], { duration: 260 });
2523
+ return stepNew(e.shiftKey ? -1 : 1);
2524
+ }
2525
+ if (on && /^(Digit|Numpad)[123]$/.test(e.code || "") && !e.metaKey && !e.ctrlKey && !e.altKey && !e.repeat && !typing(e) && !inOtherWidget) {
2526
+ e.preventDefault();
2527
+ if (e.code.endsWith("3")) setCursor(true);
2528
+ else setGo(e.code.endsWith("2"));
2529
+ return;
2530
+ }
2531
+ const letter = /^[a-z]$/i.test(e.key || "") ? e.key.toLowerCase() : /^Key[A-Z]$/.test(e.code || "") ? e.code.slice(3).toLowerCase() : "";
2532
+ if (on && !typing(e) && !inOtherWidget && !e.metaKey && !e.ctrlKey && !e.altKey && !e.repeat && /^[cwred]$/.test(letter)) {
2533
+ const k = letter;
2534
+ e.preventDefault();
2535
+ if (k === "c") return chatBtn.click();
2536
+ if (k === "w") return stepNew(e.shiftKey ? -1 : 1);
2537
+ if (k === "d") return showDoneBtn.click();
2538
+ if (k === "r" && openId) root.querySelector(".card textarea")?.focus({ preventScroll: true });
2539
+ else if (k === "e" && openId && isAdmin) [.../** @type {NodeListOf<HTMLElement>} */
2540
+ root.querySelectorAll(".card .btn")].find((b) => /^(resolve|reopen)$/.test(b.textContent))?.click();
2541
+ return;
2542
+ }
2543
+ if (e.key === "Escape" && (draft || openId)) {
2544
+ draft = null;
2545
+ openId = null;
2546
+ render();
2547
+ } else if (e.key === "Escape" && (chatOpen || listOpen)) {
2548
+ if (chatOpen) chatOpen = false;
2549
+ else listOpen = false;
2550
+ render();
2551
+ }
2552
+ });
2553
+ const INTERACTIVE = 'a, button, input, textarea, select, label, summary, video[controls], audio, iframe, [contenteditable], [role="button"], [role="link"], [role="tab"], [role="menuitem"], [role="option"], [role="checkbox"], [role="switch"], [tabindex]:not([tabindex="-1"]), [onclick]';
2554
+ const OFF = "[data-uncommentable]";
2555
+ let drag = null;
2556
+ let afterDrag = false;
2557
+ let liveZone = null;
2558
+ let zoneFrame = 0;
2559
+ const paintZone = () => {
2560
+ zoneFrame = 0;
2561
+ if (!drag?.active || !liveZone) return;
2562
+ const x = Math.min(drag.x0, drag.x1) + scrollX;
2563
+ const y = Math.min(drag.y0, drag.y1) + scrollY;
2564
+ liveZone.style.transform = `translate3d(${x}px, ${y}px, 0)`;
2565
+ liveZone.style.width = `${Math.abs(drag.x1 - drag.x0)}px`;
2566
+ liveZone.style.height = `${Math.abs(drag.y1 - drag.y0)}px`;
2567
+ };
2568
+ const draftHasText = () => Boolean(draft) && [.../** @type {NodeListOf<HTMLTextAreaElement>} */
2569
+ root.querySelectorAll(".float textarea")].some((t) => t.value.trim());
2570
+ function startDrag(e) {
2571
+ if (!on && !e.altKey || cursorMode && !e.altKey || draftHasText() || e.button !== 0 || e.pointerType === "touch" || e.metaKey || e.ctrlKey || e.shiftKey) return;
2572
+ if (e.composedPath().includes(host2)) return;
2573
+ if (!e.altKey && e.target instanceof Element && e.target.closest(INTERACTIVE)) return;
2574
+ if (e.target instanceof Element && e.target.closest(OFF)) return;
2575
+ drag = { x0: e.clientX, y0: e.clientY, x1: e.clientX, y1: e.clientY, active: false };
2576
+ }
2577
+ document.addEventListener(
2578
+ "pointerdown",
2579
+ (e) => {
2580
+ if (e.altKey) return;
2581
+ if (!on && !e.altKey || cursorMode && !e.altKey || draftHasText() || e.button !== 0 || e.pointerType === "touch" || e.metaKey || e.ctrlKey || e.shiftKey) return;
2582
+ if (e.composedPath().includes(host2)) return;
2583
+ if (!e.altKey && e.target instanceof Element && e.target.closest(INTERACTIVE)) return;
2584
+ if (e.target instanceof Element && e.target.closest(OFF)) return;
2585
+ drag = { x0: e.clientX, y0: e.clientY, x1: e.clientX, y1: e.clientY, active: false };
2586
+ },
2587
+ true
2588
+ );
2589
+ document.addEventListener(
2590
+ "pointermove",
2591
+ (e) => {
2592
+ if (!drag) return;
2593
+ drag.x1 = e.clientX;
2594
+ drag.y1 = e.clientY;
2595
+ if (!drag.active && Math.hypot(drag.x1 - drag.x0, drag.y1 - drag.y0) > 8) {
2596
+ drag.active = true;
2597
+ getSelection?.()?.removeAllRanges();
2598
+ document.documentElement.classList.add("lab-dragging");
2599
+ liveZone = zoneEl("draft live");
2600
+ layer2.append(liveZone);
2601
+ }
2602
+ if (!drag.active) return;
2603
+ e.preventDefault();
2604
+ zoneFrame ||= requestAnimationFrame(paintZone);
2605
+ },
2606
+ true
2607
+ );
2608
+ const endDrag = (e) => {
2609
+ if (!drag) return;
2610
+ const d = drag;
2611
+ drag = null;
2612
+ document.documentElement.classList.remove("lab-dragging");
2613
+ cancelAnimationFrame(zoneFrame);
2614
+ zoneFrame = 0;
2615
+ liveZone?.remove();
2616
+ liveZone = null;
2617
+ if (!d.active || e.type === "pointercancel") return;
2618
+ afterDrag = true;
2619
+ setTimeout(() => afterDrag = false, 0);
2620
+ getSelection?.()?.removeAllRanges();
2621
+ for (const [a, b] of [["x0", "x1"], ["y0", "y1"]]) {
2622
+ if (Math.abs(d[b] - d[a]) >= 12) continue;
2623
+ const mid = (d[a] + d[b]) / 2;
2624
+ d[a] = mid - 6;
2625
+ d[b] = mid + 6;
2626
+ }
2627
+ showAgain();
2628
+ openId = null;
2629
+ begin(zoneAnchor(d));
2630
+ };
2631
+ document.addEventListener("pointerup", endDrag, true);
2632
+ document.addEventListener("pointercancel", endDrag, true);
2633
+ document.addEventListener(
2634
+ "dragstart",
2635
+ (e) => {
2636
+ const media = on && e.target instanceof Element && e.target.closest("img, video") && !e.composedPath().includes(host2);
2637
+ if (drag || media) e.preventDefault();
2638
+ },
2639
+ true
2640
+ );
2641
+ document.addEventListener(
2642
+ "click",
2643
+ (e) => {
2644
+ if (!afterDrag) return;
2645
+ e.preventDefault();
2646
+ e.stopPropagation();
2647
+ },
2648
+ true
2649
+ );
2650
+ const optionPress = (e) => e.altKey && !e.metaKey && !e.ctrlKey && e.button === 0 && !e.composedPath().includes(host2) && !(e.target instanceof Element && e.target.closest(OFF));
2651
+ for (const type of ["pointerdown", "mousedown", "pointerup", "mouseup"]) {
2652
+ addEventListener(type, (e) => {
2653
+ if (!optionPress(e)) return;
2654
+ e.preventDefault();
2655
+ e.stopImmediatePropagation();
2656
+ if (type === "pointerdown") startDrag(e);
2657
+ if (type === "pointerup") endDrag(e);
2658
+ }, true);
2659
+ }
2660
+ addEventListener("click", (e) => {
2661
+ if (!optionPress(e)) return;
2662
+ e.preventDefault();
2663
+ e.stopImmediatePropagation();
2664
+ if (!afterDrag) onPageClick(e);
2665
+ }, true);
2666
+ document.addEventListener("click", (e) => onPageClick(e));
2667
+ let lastTouch = 0;
2668
+ let pinnedByHold = false;
2669
+ const selChip = (
2670
+ /** @type {HTMLElement} */
2671
+ root.querySelector(".sel-chip")
2672
+ );
2673
+ const scrim = (
2674
+ /** @type {HTMLElement} */
2675
+ root.querySelector(".scrim")
2676
+ );
2677
+ const openSheet = () => root.querySelector(".card:not(.out), .float:not(.out)") || (listOpen ? listEl : chatOpen ? chatEl : null);
2678
+ const closeAll = () => {
2679
+ draft = null;
2680
+ openId = null;
2681
+ listOpen = false;
2682
+ chatOpen = false;
2683
+ render();
2684
+ };
2685
+ const closeOrNudge = () => {
2686
+ const node = openSheet();
2687
+ if (![...root.querySelectorAll("textarea")].some((t) => t.value.trim() && !chatEl.contains(t))) return slideAway(node, closeAll);
2688
+ node?.animate?.([{ transform: "none" }, { transform: "translateY(12px)" }, { transform: "none" }], { duration: 260, easing: "ease-out" });
2689
+ };
2690
+ let sheetDraggedAt = -1e9;
2691
+ scrim.addEventListener("click", () => performance.now() - sheetDraggedAt > 300 && closeOrNudge());
2692
+ scrim.addEventListener("touchmove", (e) => e.preventDefault(), { passive: false });
2693
+ function slideAway(node, close, ms = 0) {
2694
+ if (!coarse || !node || still.matches) return close();
2695
+ if (!host2.hasAttribute("data-kb")) root.activeElement?.blur();
2696
+ node.style.pointerEvents = "none";
2697
+ node.style.transition = ms ? `transform ${ms}ms cubic-bezier(.2, .6, .4, 1)` : "transform .22s cubic-bezier(.4, 0, 1, 1)";
2698
+ scrim.style.transition = `opacity ${ms || 220}ms`;
2699
+ node.style.transform = "translateY(100%)";
2700
+ scrim.style.opacity = "0";
2701
+ bar.style.transition = `transform ${ms || 220}ms cubic-bezier(.2, .6, .4, 1), opacity ${ms || 220}ms`;
2702
+ host2.style.setProperty("--lab-p", "1");
2703
+ setTimeout(() => {
2704
+ root.activeElement?.blur();
2705
+ close();
2706
+ node.style.pointerEvents = "";
2707
+ node.style.transform = node.style.transition = scrim.style.opacity = scrim.style.transition = bar.style.transition = "";
2708
+ host2.style.removeProperty("--lab-p");
2709
+ }, ms || 220);
2710
+ }
2711
+ const grabArea = (t) => Boolean(t.closest?.(".handle, .tabs"));
2712
+ const scrollerIn = (e, node) => e.composedPath().find((n) => n instanceof HTMLElement && node.contains(n) && (n.localName === "textarea" || /auto|scroll/.test(getComputedStyle(n).overflowY)));
2713
+ const SPRING = "cubic-bezier(.32,.72,0,1)";
2714
+ let backWatcher = null;
2715
+ function backCloses() {
2716
+ const open = matchMedia("(pointer: coarse)").matches && host2.hasAttribute("data-sheet");
2717
+ if (!open && backWatcher) {
2718
+ const w = backWatcher;
2719
+ backWatcher = null;
2720
+ w.destroy();
2721
+ }
2722
+ if (open && !backWatcher && "CloseWatcher" in window) {
2723
+ try {
2724
+ const w = new /** @type {any} */
2725
+ window.CloseWatcher();
2726
+ w.onclose = () => {
2727
+ if (backWatcher === w) backWatcher = null;
2728
+ closeOrNudge();
2729
+ backCloses();
2730
+ };
2731
+ backWatcher = w;
2732
+ } catch {
2733
+ }
2734
+ }
2735
+ }
2736
+ let dbg = null;
2737
+ function swipeDown(node, close, grows = false) {
2738
+ if (!coarse) return;
2739
+ let raw = 0;
2740
+ let scrolledAt = -1e9;
2741
+ let releasedAt = -1e9;
2742
+ node.addEventListener("scroll", () => scrolledAt = performance.now(), { capture: true, passive: true });
2743
+ node.addEventListener("click", (e) => {
2744
+ if (performance.now() - releasedAt < 200) {
2745
+ e.preventDefault();
2746
+ e.stopPropagation();
2747
+ }
2748
+ }, true);
2749
+ node.addEventListener("focusin", (e) => {
2750
+ if (performance.now() - releasedAt < 200 && e.target.localName === "textarea") e.target.blur();
2751
+ });
2752
+ let x0 = 0;
2753
+ let y0 = 0;
2754
+ let dy = 0;
2755
+ let v = 0;
2756
+ let last = null;
2757
+ let mode = null;
2758
+ let box = null;
2759
+ let fromScrim = false;
2760
+ const onStart = (e) => {
2761
+ fromScrim = e.currentTarget === scrim;
2762
+ if (fromScrim && openSheet() !== node) return void (mode = "off");
2763
+ const t = e.touches[0];
2764
+ x0 = t.clientX;
2765
+ y0 = t.clientY;
2766
+ dy = v = raw = 0;
2767
+ last = { y: y0, at: e.timeStamp };
2768
+ box = fromScrim ? null : scrollerIn(e, node);
2769
+ mode = e.touches.length > 1 || box?.localName === "textarea" ? "off" : null;
2770
+ };
2771
+ node.addEventListener("touchstart", onStart, { passive: true });
2772
+ scrim.addEventListener("touchstart", onStart, { passive: true });
2773
+ const onMove = (e) => {
2774
+ if (fromScrim !== (e.currentTarget === scrim)) return;
2775
+ const t = e.touches[0];
2776
+ if (mode === "off" && box && box.localName !== "textarea" && e.touches.length === 1 && e.cancelable && box.scrollTop <= 0 && t.clientY > last.y + 1) {
2777
+ mode = "drag";
2778
+ y0 = t.clientY;
2779
+ v = 0;
2780
+ last = { y: t.clientY, at: e.timeStamp };
2781
+ }
2782
+ if (mode === "off") return void (last = { y: t.clientY, at: e.timeStamp });
2783
+ if (mode === "hold") return e.preventDefault();
2784
+ if (!mode) {
2785
+ const down = t.clientY - y0;
2786
+ const across = t.clientX - x0;
2787
+ if (!down && !across) return;
2788
+ const sideways = Math.abs(across) > Math.abs(down);
2789
+ const nearTop = !sideways && down > 0 && y0 - node.getBoundingClientRect().top < node.offsetHeight * 0.25;
2790
+ if (fromScrim) mode = sideways ? "hold" : "drag";
2791
+ else if (grabArea(e.target)) mode = sideways && e.target.closest(".tabs") ? "off" : "drag";
2792
+ else if (nearTop && box?.localName !== "textarea") mode = "drag";
2793
+ else if (box) mode = !sideways && down > 0 && box.scrollTop <= 0 && performance.now() - scrolledAt > 100 ? "drag" : "off";
2794
+ else mode = sideways ? "hold" : "drag";
2795
+ dbg?.(`touch ${String(e.target.className || e.target.localName).slice(0, 20)} at ${Math.round(y0 - node.getBoundingClientRect().top)}/${node.offsetHeight} down${Math.round(down)} \u2192 ${mode}${e.cancelable ? "" : " (not cancelable)"}${box ? ` box${Math.round(box.scrollTop)}` : ""}`);
2796
+ if (mode === "off") return;
2797
+ if (mode === "hold") return e.preventDefault();
2798
+ }
2799
+ e.preventDefault();
2800
+ raw = t.clientY - y0;
2801
+ const size = node.offsetHeight || 400;
2802
+ dy = raw >= 0 ? raw : -(1 - 1 / (-raw * 0.55 / size + 1)) * size;
2803
+ if (e.timeStamp > last.at) v = 0.8 * ((t.clientY - last.y) / (e.timeStamp - last.at)) + 0.2 * v;
2804
+ last = { y: t.clientY, at: e.timeStamp };
2805
+ node.style.transition = scrim.style.transition = "none";
2806
+ node.style.transform = `translateY(${dy}px)`;
2807
+ scrim.style.opacity = String(Math.min(1, Math.max(0, 1 - dy / 320)));
2808
+ bar.style.transition = "none";
2809
+ host2.style.setProperty("--lab-p", String(Math.min(1, Math.max(0, dy / (node.offsetHeight || 400)))));
2810
+ };
2811
+ node.addEventListener("touchmove", onMove, { passive: false });
2812
+ scrim.addEventListener("touchmove", onMove, { passive: false });
2813
+ const end = (e) => {
2814
+ if (fromScrim !== (e.currentTarget === scrim)) return;
2815
+ const was = mode;
2816
+ mode = null;
2817
+ if (was === "drag") sheetDraggedAt = performance.now();
2818
+ if (was !== "drag") return;
2819
+ releasedAt = performance.now();
2820
+ if (e.timeStamp - last.at > 80) v = 0;
2821
+ const h = node.offsetHeight || innerHeight;
2822
+ const settle = () => {
2823
+ node.style.transition = `transform 380ms ${SPRING}, height 380ms ${SPRING}`;
2824
+ scrim.style.transition = "opacity 300ms";
2825
+ node.style.transform = scrim.style.opacity = "";
2826
+ bar.style.transition = "";
2827
+ host2.style.removeProperty("--lab-p");
2828
+ setTimeout(() => node.style.transition = scrim.style.transition = "", 400);
2829
+ };
2830
+ if (grows && !node.classList.contains("full") && (raw < -40 || v < -0.4)) return node.classList.add("full"), node.classList.contains("card") && (cardFull = true), settle();
2831
+ if (grows && node.classList.contains("full") && v < 1.2 && (raw > 60 || v > 0.4)) return node.classList.remove("full"), node.classList.contains("card") && (cardFull = false), settle();
2832
+ const rest = dy + Math.max(0, v) * 499;
2833
+ dbg?.(`let go: moved ${Math.round(dy)} speed ${v.toFixed(2)} rest ${Math.round(rest)} of half ${Math.round(h / 2)} \u2192 ${v > -0.1 && rest > h / 2 ? "close" : "stay"}`);
2834
+ if (v > -0.1 && rest > h / 2) return slideAway(node, close, Math.min(320, Math.max(140, (h - dy) / Math.max(v, 1.2))));
2835
+ node.style.transition = `transform 380ms ${SPRING}`;
2836
+ scrim.style.transition = "opacity 300ms";
2837
+ node.style.transform = scrim.style.opacity = "";
2838
+ bar.style.transition = "";
2839
+ host2.style.removeProperty("--lab-p");
2840
+ setTimeout(() => node.style.transition = scrim.style.transition = "", 400);
2841
+ };
2842
+ node.addEventListener("touchend", end);
2843
+ scrim.addEventListener("touchend", end);
2844
+ scrim.addEventListener("touchcancel", end);
2845
+ node.addEventListener("touchcancel", end);
2846
+ }
2847
+ const vv = window.visualViewport;
2848
+ if (coarse && vv) {
2849
+ const probe = el2("i", { style: "position:fixed;top:0;bottom:0;left:0;width:0;visibility:hidden;pointer-events:none" });
2850
+ const strip = el2("i", { style: "position:absolute;left:0;width:100vw;display:none;background:var(--_bg);z-index:3;pointer-events:none" });
2851
+ root.append(probe, strip);
2852
+ let fitted = "";
2853
+ const fit = () => {
2854
+ const zoomed = Math.abs(vv.scale - 1) > 0.01;
2855
+ const r = probe.getBoundingClientRect();
2856
+ const field = (
2857
+ /** @type {HTMLElement | null} */
2858
+ root.activeElement || document.activeElement
2859
+ );
2860
+ const typing2 = /^(textarea|input|select)$/.test(field?.localName || "") || Boolean(field?.isContentEditable);
2861
+ const top = zoomed || !typing2 ? 0 : vv.offsetTop;
2862
+ const seen2 = top + vv.height;
2863
+ const kb = zoomed ? 0 : Math.max(0, Math.round(r.bottom - seen2));
2864
+ const gap = zoomed ? 0 : Math.max(0, Math.round(seen2 - r.bottom));
2865
+ const vh = zoomed ? 0 : Math.round(vv.height);
2866
+ const sheet = host2.hasAttribute("data-sheet");
2867
+ const key = `${kb} ${vh} ${gap} ${sheet} ${scrollY} ${Math.round(top)}`;
2868
+ if (key === fitted) {
2869
+ const open2 = sheet ? openSheet() : null;
2870
+ if (open2?.offsetHeight && !open2.style.transform) Object.assign(fit, { sheet: open2, top: open2.getBoundingClientRect().top });
2871
+ return;
2872
+ }
2873
+ fitted = key;
2874
+ host2.style.setProperty("--lab-kb", `${kb}px`);
2875
+ host2.style.setProperty("--lab-top", `${Math.round(top)}px`);
2876
+ if (vh) host2.style.setProperty("--lab-vh", `${vh}px`);
2877
+ else host2.style.removeProperty("--lab-vh");
2878
+ host2.toggleAttribute("data-kb", kb > 60);
2879
+ strip.style.display = sheet && gap ? "block" : "none";
2880
+ strip.style.top = `${Math.round(scrollY + r.bottom)}px`;
2881
+ strip.style.height = `${gap}px`;
2882
+ const open = sheet ? openSheet() : null;
2883
+ const slid = (n) => {
2884
+ try {
2885
+ return new DOMMatrixReadOnly(getComputedStyle(n).transform).m42 || 0;
2886
+ } catch {
2887
+ return 0;
2888
+ }
2889
+ };
2890
+ const keyboardMoved = Math.abs((fit.vh || vh) - vh) > 60 || fit.kbUp !== kb > 60;
2891
+ const sliding = open && open === fit.sheet && keyboardMoved && !open.style.transform && !still.matches;
2892
+ if (sliding) {
2893
+ open.style.transition = "none";
2894
+ void open.offsetHeight;
2895
+ }
2896
+ const at = open ? open.getBoundingClientRect().top - slid(open) : null;
2897
+ if (sliding && Math.abs(fit.top - at) <= 8) open.style.transition = "";
2898
+ if (sliding && Math.abs(fit.top - at) > 8) {
2899
+ open.style.transform = `translateY(${fit.top - at}px)`;
2900
+ void open.offsetHeight;
2901
+ open.style.transition = `transform 340ms ${SPRING}`;
2902
+ open.style.transform = "";
2903
+ clearTimeout(fit.done);
2904
+ fit.done = setTimeout(() => !open.style.transform && (open.style.transition = ""), 360);
2905
+ }
2906
+ Object.assign(fit, { vh, kbUp: kb > 60 }, open?.offsetHeight ? { sheet: open, top: at } : { sheet: null });
2907
+ };
2908
+ refit = fit;
2909
+ root.addEventListener("focusin", () => setTimeout(fit, 50));
2910
+ root.addEventListener("focusout", () => setTimeout(fit, 50));
2911
+ vv.addEventListener("resize", fit);
2912
+ vv.addEventListener("scroll", fit);
2913
+ fit();
2914
+ if (globalThis.__LAB_DEBUG__ !== false && /[?&]kbdebug\b/.test(location.search)) {
2915
+ let lines = [];
2916
+ let t0 = performance.now();
2917
+ let sendTimer = 0;
2918
+ const row = (what) => {
2919
+ const open = openSheet();
2920
+ const r = open?.getBoundingClientRect();
2921
+ lines.push(`${Math.round(performance.now() - t0)} ${what} h${Math.round(vv.height)} top${Math.round(vv.offsetTop)} in${innerHeight} kb${host2.hasAttribute("data-kb") ? 1 : 0}` + (r ? ` sheet${Math.round(r.top)}/${Math.round(r.height)}${open.getAnimations().length ? " anim" : ""}` : "") + // What is moving anywhere (the page, the pins, the dimming): for a flicker that isn't the keyboard.
2922
+ ` [${[...document.getAnimations(), ...root.getAnimations()].map((a) => (
2923
+ /** @type {any} */
2924
+ a.animationName || /** @type {any} */
2925
+ a.transitionProperty || "js"
2926
+ )).slice(0, 6).join(",")}] scrim${getComputedStyle(scrim).opacity.slice(0, 4)} scroll${Math.round(scrollY)}`);
2927
+ };
2928
+ const watch = (what) => {
2929
+ row(what);
2930
+ const end = performance.now() + 1500;
2931
+ let prev = "";
2932
+ const f = () => {
2933
+ const before = lines.length;
2934
+ row("f");
2935
+ const last = lines[lines.length - 1].replace(/^\d+ f /, "");
2936
+ if (last === prev) lines.length = before;
2937
+ prev = last;
2938
+ if (performance.now() < end) requestAnimationFrame(f);
2939
+ };
2940
+ requestAnimationFrame(f);
2941
+ };
2942
+ root.addEventListener("focusin", () => (t0 = performance.now(), watch("focus")));
2943
+ const sendSoon = () => {
2944
+ clearTimeout(sendTimer);
2945
+ sendTimer = setTimeout(async () => {
2946
+ const text = lines.join("\n");
2947
+ lines = [];
2948
+ for (let i = 0; i < text.length; i += 1900) {
2949
+ await send({ name: "kb-log", text: text.slice(i, i + 1900), anchor: { kind: "page", selector: "body", x: 0, y: 0, docX: 0, docY: 0, width: innerWidth } }).catch(() => {
2950
+ });
2951
+ }
2952
+ }, 2e3);
2953
+ };
2954
+ root.addEventListener("focusout", () => {
2955
+ lines.push("--- let go");
2956
+ t0 = performance.now();
2957
+ watch("blur");
2958
+ sendSoon();
2959
+ });
2960
+ dbg = (line) => {
2961
+ lines.push(`${Math.round(performance.now() - t0)} ${line}`);
2962
+ sendSoon();
2963
+ };
2964
+ vv.addEventListener("resize", () => {
2965
+ watch("resize");
2966
+ if (lines.length > 1) sendSoon();
2967
+ });
2968
+ }
2969
+ }
2970
+ const msgsEl = $(".msgs", chatEl);
2971
+ let stick = true;
2972
+ msgsEl.addEventListener("scroll", () => stick = msgsEl.scrollHeight - msgsEl.scrollTop - msgsEl.clientHeight < 48, { passive: true });
2973
+ if ("ResizeObserver" in window) new ResizeObserver(() => stick && (msgsEl.scrollTop = msgsEl.scrollHeight)).observe(msgsEl);
2974
+ swipeDown(listEl, () => (listOpen = false, render()));
2975
+ swipeDown(chatEl, () => (chatOpen = false, render()), true);
2976
+ let press = null;
2977
+ const stopPress = () => press && (clearTimeout(press.timer), press = null);
2978
+ document.addEventListener(
2979
+ "pointerdown",
2980
+ (e) => {
2981
+ stopPress();
2982
+ pinnedByHold = false;
2983
+ if (e.pointerType === "touch") lastTouch = Date.now();
2984
+ if (e.pointerType !== "touch" || draft || !(e.target instanceof Element) || e.composedPath().includes(host2) || e.target.closest(OFF)) return;
2985
+ const { clientX: x, clientY: y } = e;
2986
+ press = {
2987
+ x,
2988
+ y,
2989
+ timer: setTimeout(() => {
2990
+ press = null;
2991
+ pinnedByHold = true;
2992
+ navigator.vibrate?.(8);
2993
+ getSelection?.()?.removeAllRanges();
2994
+ afterDrag = true;
2995
+ setTimeout(() => afterDrag = false, 800);
2996
+ showAgain();
2997
+ openId = null;
2998
+ begin(anchorAt(x, y));
2999
+ }, 500)
3000
+ };
3001
+ },
3002
+ true
3003
+ );
3004
+ document.addEventListener("pointermove", (e) => press && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 10 && stopPress(), true);
3005
+ document.addEventListener("pointerup", (e) => {
3006
+ if (e.pointerType === "touch") lastTouch = Date.now();
3007
+ stopPress();
3008
+ if (pinnedByHold) root.querySelector(".float textarea")?.focus({ preventScroll: true });
3009
+ }, true);
3010
+ document.addEventListener("touchend", (e) => {
3011
+ if (!pinnedByHold) return;
3012
+ pinnedByHold = false;
3013
+ e.preventDefault();
3014
+ root.querySelector(".float textarea")?.focus({ preventScroll: true });
3015
+ }, { capture: true, passive: false });
3016
+ document.addEventListener("pointercancel", stopPress, true);
3017
+ addEventListener("scroll", stopPress, { passive: true, capture: true });
3018
+ document.addEventListener("contextmenu", (e) => (press || afterDrag) && e.preventDefault(), true);
3019
+ let selRect = null;
3020
+ document.addEventListener("selectionchange", () => {
3021
+ const sel = getSelection?.();
3022
+ const range = sel?.rangeCount && sel.getRangeAt(0);
3023
+ const text = String(sel || "").trim();
3024
+ const inside = range && host2.contains(range.commonAncestorContainer);
3025
+ selRect = coarse && on && !draft && text && range && !inside ? range.getClientRects()[0] || range.getBoundingClientRect() : null;
3026
+ selChip.hidden = !selRect;
3027
+ if (!selRect) return;
3028
+ const below = selRect.bottom + 52 < innerHeight;
3029
+ selChip.style.left = `${Math.min(Math.max(selRect.left + selRect.width / 2, 60), innerWidth - 60)}px`;
3030
+ selChip.style.top = `${below ? selRect.bottom + 10 : Math.max(selRect.top - 46, 8)}px`;
3031
+ });
3032
+ const commentOnSelection = () => {
3033
+ const sel = getSelection?.();
3034
+ const range = sel?.rangeCount && sel.getRangeAt(0);
3035
+ const exact = String(sel || "").replace(/\s+/g, " ").trim();
3036
+ if (!range || !exact || host2.contains(range.commonAncestorContainer)) return false;
3037
+ const rects = range.getClientRects();
3038
+ const first = rects[0] || range.getBoundingClientRect();
3039
+ const last = rects[rects.length - 1] || first;
3040
+ const startEl = range.startContainer.nodeType === 1 ? range.startContainer : range.startContainer.parentElement;
3041
+ const endEl = range.endContainer.nodeType === 1 ? range.endContainer : range.endContainer.parentElement;
3042
+ const anchor = startEl && (startEl === endEl || startEl.contains(endEl)) ? anchorAt(Math.max(last.left, last.right - 2), last.top + last.height / 2) : anchorAt(first.left + 2, first.top + first.height / 2);
3043
+ const at = range.commonAncestorContainer;
3044
+ const block = (
3045
+ /** @type {Element | null} */
3046
+ (at.nodeType === 1 ? at : at.parentElement)?.closest("p, li, h1, h2, h3, h4, h5, h6, td, th, figcaption, blockquote, pre, section, article, div") || document.body
3047
+ );
3048
+ const side = (a, b) => {
3049
+ const r = document.createRange();
3050
+ r.setStart(...a);
3051
+ r.setEnd(...b);
3052
+ return String(r).replace(/\s+/g, " ");
3053
+ };
3054
+ anchor.kind = "text";
3055
+ anchor.quote = {
3056
+ exact: short(exact, 300),
3057
+ prefix: side([block, 0], [range.startContainer, range.startOffset]).replace(/^\s+/, "").slice(-40),
3058
+ suffix: side([range.endContainer, range.endOffset], [block, block.childNodes.length]).replace(/\s+$/, "").slice(0, 40)
3059
+ };
3060
+ sel.removeAllRanges();
3061
+ selChip.hidden = true;
3062
+ showAgain();
3063
+ openId = null;
3064
+ begin(anchor);
3065
+ return true;
3066
+ };
3067
+ selChip.addEventListener("click", (e) => {
3068
+ e.stopPropagation();
3069
+ if (selRect) commentOnSelection();
3070
+ });
3071
+ document.addEventListener("mouseup", (e) => {
3072
+ if (on && !cursorMode && !draft && e.shiftKey && e.button === 0 && !e.composedPath().includes(host2)) setTimeout(commentOnSelection, 0);
3073
+ }, true);
3074
+ function onPageClick(e) {
3075
+ if (e.composedPath().includes(host2)) return;
3076
+ if (draft || openId) {
3077
+ if ([...root.querySelectorAll("textarea")].some((t) => t.value.trim())) return;
3078
+ draft = null;
3079
+ openId = null;
3080
+ render();
3081
+ return;
3082
+ }
3083
+ if (!on && !e.altKey || cursorMode && !e.altKey || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
3084
+ if (lastTouch && Date.now() - lastTouch < 800) return;
3085
+ if (e.altKey) e.preventDefault();
3086
+ else if (e.defaultPrevented || e.target instanceof Element && e.target.closest(INTERACTIVE)) return;
3087
+ if (e.target instanceof Element && e.target.closest(OFF)) return;
3088
+ if (String(getSelection?.() || "").trim()) return;
3089
+ showAgain();
3090
+ begin(anchorAt(e.clientX, e.clientY));
3091
+ }
3092
+ const movePins = () => {
3093
+ const list = threads().filter((c) => c.anchor?.kind !== "page");
3094
+ if (!on || openId || list.length !== pinsById.size) return render();
3095
+ const places = list.map((c) => [pinsById.get(c.id), position(c.anchor || {})]);
3096
+ if (places.some(([pin]) => !pin)) return render();
3097
+ for (const [pin, { left, top, moved }] of places) {
3098
+ pin.style.left = `${left}px`;
3099
+ pin.style.top = `${top}px`;
3100
+ pin.classList.toggle("moved", Boolean(moved));
3101
+ }
3102
+ };
3103
+ let frame = 0;
3104
+ const reflow = () => {
3105
+ cancelAnimationFrame(frame);
3106
+ frame = requestAnimationFrame(() => {
3107
+ if (draft || root.activeElement || grabbing) return;
3108
+ movePins();
3109
+ });
3110
+ };
3111
+ addEventListener("resize", reflow);
3112
+ addEventListener("scroll", (e) => e.target !== document && !host2.contains(
3113
+ /** @type {Node} */
3114
+ e.target
3115
+ ) && reflow(), { capture: true, passive: true });
3116
+ const navigated = () => {
3117
+ if (gone) return;
3118
+ if (!host2.isConnected && document.body) document.body.append(host2);
3119
+ if (!fonts.isConnected) document.head.append(fonts);
3120
+ if (!pinCursorStyle.isConnected) document.head.append(pinCursorStyle);
3121
+ if (pageNow() === page) return;
3122
+ page = pageNow();
3123
+ seen = readSeen();
3124
+ syncReads();
3125
+ comments = [];
3126
+ draft = null;
3127
+ openId = null;
3128
+ render();
3129
+ load();
3130
+ };
3131
+ for (const m of ["pushState", "replaceState"]) {
3132
+ const original = history[m];
3133
+ history[m] = function(...args) {
3134
+ const out = original.apply(this, args);
3135
+ queueMicrotask(navigated);
3136
+ return out;
3137
+ };
3138
+ }
3139
+ addEventListener("popstate", navigated);
3140
+ document.addEventListener("astro:after-swap", navigated);
3141
+ document.addEventListener("visibilitychange", () => {
3142
+ if (document.visibilityState === "visible" && !draft && !root.activeElement) load();
3143
+ });
3144
+ if ("ResizeObserver" in window) new ResizeObserver(reflow).observe(document.body);
3145
+ const fonts = document.createElement("style");
3146
+ if (script?.dataset.fontUrl)
3147
+ fonts.textContent = `@font-face{font-family:'lab comments';font-display:swap;src:url('${new URL(script.dataset.fontUrl, script.src || location.href)}') format('woff2');}`;
3148
+ const fontName = script?.dataset.fontUrl ? "lab comments" : script?.dataset.font;
3149
+ if (fontName) host2.style.setProperty("--lab-font", `'${fontName.replace(/'/g, "")}', system-ui, sans-serif`);
3150
+ const pinCursorStyle = document.createElement("style");
3151
+ const ptr = el2("div", { class: "ptr", "aria-hidden": "true" });
3152
+ ptr.append(el2("span", { class: "ini" }, "+"), el2("span", { class: "tick" }, "go"));
3153
+ root.append(ptr);
3154
+ let mouse = null;
3155
+ const place = (x, y, target) => {
3156
+ const show = Boolean(target) && target !== host2 && !host2.contains(target) && getComputedStyle(target).cursor === "none";
3157
+ ptr.classList.toggle("show", show);
3158
+ ptr.classList.toggle("go", goMode);
3159
+ ptr.style.transform = `translate(${x - 1}px, ${y - 27}px)`;
3160
+ };
3161
+ const recheck = () => mouse && requestAnimationFrame(() => mouse && place(mouse.x, mouse.y, document.elementFromPoint(mouse.x, mouse.y)));
3162
+ addEventListener("pointermove", (e) => {
3163
+ if (e.pointerType !== "mouse") return;
3164
+ document.documentElement.classList.add("lab-drawn");
3165
+ mouse = { x: e.clientX, y: e.clientY };
3166
+ const t = e.composedPath()[0];
3167
+ place(e.clientX, e.clientY, t instanceof Element ? t : null);
3168
+ }, { capture: true, passive: true });
3169
+ addEventListener("scroll", recheck, { capture: true, passive: true });
3170
+ addEventListener("keydown", (e) => (e.key === "Shift" || e.key === "Alt") && recheck(), true);
3171
+ addEventListener("keyup", (e) => (e.key === "Shift" || e.key === "Alt") && recheck(), true);
3172
+ document.documentElement.addEventListener("mouseleave", () => (mouse = null, ptr.classList.remove("show")));
3173
+ addEventListener("blur", () => (mouse = null, ptr.classList.remove("show")));
3174
+ let cursorKey = "";
3175
+ function refreshPinCursor() {
3176
+ const ch = (initial(store2.get("lab-name")) || "+").replace(/[<>&'"]/g, "");
3177
+ if (ch === cursorKey) return;
3178
+ cursorKey = ch;
3179
+ ptr.querySelector(".ini").textContent = ch;
3180
+ const plain2 = `:not(${INTERACTIVE}, a *, button *, label *, [role="button"] *, [contenteditable], [contenteditable] *, ${OFF}, ${OFF} *, [data-lab-comments])`;
3181
+ const top = `dialog, dialog *, [popover], [popover] *, :fullscreen, :fullscreen *`;
3182
+ pinCursorStyle.textContent = `@layer lab-pointer { html.lab-pinning:not(.lab-shift) body, html.lab-pinning:not(.lab-shift) body *${plain2} { cursor: crosshair; } html.lab-drawn.lab-pinning:not(.lab-shift):not(.lab-dragging) body, html.lab-drawn.lab-pinning:not(.lab-shift):not(.lab-dragging) body *${plain2}:not(${top}) { cursor: none; } html.lab-pinning body :is([contenteditable], [contenteditable] *) { cursor: text; } html.lab-pinning body :is(${OFF}, ${OFF} *) { cursor: auto; } }html.lab-alt body, html.lab-alt body *:not([data-lab-comments], [data-lab-comments] *, ${OFF}, ${OFF} *) { cursor: crosshair !important; }html.lab-drawn.lab-alt body, html.lab-drawn.lab-alt body *:not([data-lab-comments], [data-lab-comments] *, ${OFF}, ${OFF} *, ${top}) { cursor: none !important; }html.lab-go:not(.lab-drawn) body, html.lab-go:not(.lab-drawn) body * { cursor: copy !important; }`;
3183
+ }
3184
+ fonts.textContent += `@media (pointer: fine) { html.lab-pinning:not(.lab-shift) body > :not([data-lab-comments]), html.lab-pinning:not(.lab-shift) body > :not([data-lab-comments]) :not(input, textarea, select, [contenteditable], [contenteditable] *) { -webkit-user-select: none; user-select: none; } }`;
3185
+ let shiftOff = 0;
3186
+ const shiftKey = (e) => {
3187
+ clearTimeout(shiftOff);
3188
+ if (e.shiftKey) document.documentElement.classList.add("lab-shift");
3189
+ else shiftOff = setTimeout(() => (document.documentElement.classList.remove("lab-shift"), recheck()), 400);
3190
+ };
3191
+ addEventListener("keydown", shiftKey, true);
3192
+ addEventListener("keyup", shiftKey, true);
3193
+ addEventListener("pointerdown", (e) => {
3194
+ if (e.shiftKey) return shiftKey(e);
3195
+ clearTimeout(shiftOff);
3196
+ document.documentElement.classList.remove("lab-shift");
3197
+ }, true);
3198
+ addEventListener("blur", () => document.documentElement.classList.remove("lab-shift"));
3199
+ fonts.textContent += "html.lab-dragging, html.lab-dragging * { user-select: none !important; -webkit-user-select: none !important; cursor: crosshair !important; }";
3200
+ fonts.textContent += "html.lab-sheet, html.lab-sheet body { overscroll-behavior-y: none; }";
3201
+ fonts.textContent += "html.lab-room body::after { content: ''; display: block; height: var(--lab-room, 0px); }";
3202
+ addEventListener("scroll", () => {
3203
+ const de = document.documentElement;
3204
+ const had = parseFloat(de.style.getPropertyValue("--lab-room")) || 0;
3205
+ if (!had || host2.hasAttribute("data-sheet")) return;
3206
+ const room = Math.max(0, Math.ceil(scrollY + innerHeight - (de.scrollHeight - had)));
3207
+ if (room >= had) return;
3208
+ de.style.setProperty("--lab-room", `${room}px`);
3209
+ if (!room) de.classList.remove("lab-room");
3210
+ }, { passive: true });
3211
+ fonts.textContent += "@media (pointer: coarse) { html.lab-sheet, html.lab-sheet body { overflow: hidden; } }";
3212
+ fonts.textContent += `html.lab-pinning body, html.lab-pinning body * { -webkit-touch-callout: none; }`;
3213
+ fonts.textContent += `@media (pointer: coarse) { html.lab-pinning body > :not([data-lab-comments]) { -webkit-user-select: none; user-select: none; } html.lab-pinning body > :not([data-lab-comments]), html.lab-pinning body > :not([data-lab-comments]) * { -webkit-user-drag: none; } }`;
3214
+ const setAlt = (down) => document.documentElement.classList.toggle("lab-alt", Boolean(down));
3215
+ addEventListener("keydown", (e) => e.key === "Alt" && setAlt(true), true);
3216
+ addEventListener("keyup", (e) => e.key === "Alt" && setAlt(false), true);
3217
+ addEventListener("pointermove", (e) => setAlt(e.altKey), { capture: true, passive: true });
3218
+ addEventListener("blur", () => setAlt(false));
3219
+ const start = () => {
3220
+ document.head.append(fonts, pinCursorStyle);
3221
+ refreshPinCursor();
3222
+ if (on) showHint();
3223
+ document.body.append(host2);
3224
+ const paint = "background-color: rgba(52, 199, 89, .3); color: inherit;";
3225
+ fonts.textContent += `html.lab-pinning ::selection { ${paint} } ::highlight(lab-quote) { ${paint} }`;
3226
+ load();
3227
+ };
3228
+ if (document.body) start();
3229
+ else document.addEventListener("DOMContentLoaded", start);
3230
+ if (script?.dataset.live) {
3231
+ let onState = function(v) {
3232
+ {
3233
+ if (v.widget && script.dataset.widget && v.widget !== script.dataset.widget) return reload();
3234
+ if (v.lab && script.dataset.lab && v.lab !== script.dataset.lab) {
3235
+ script.dataset.lab = v.lab;
3236
+ script.dataset.version = String(v.files);
3237
+ hotAt = v.hot;
3238
+ commentsRev = v.comments;
3239
+ morphPage();
3240
+ load();
3241
+ }
3242
+ if (String(v.files) !== script.dataset.version) return reload();
3243
+ if (hotAt !== null && v.hot !== hotAt) {
3244
+ if (v.hot - hotAt > 1) hotUpdate([{ kind: "html" }, { kind: "css", path: "" }]);
3245
+ else hotUpdate(v.hotFiles || []);
3246
+ }
3247
+ hotAt = v.hot;
3248
+ if (commentsRev !== null && v.comments !== commentsRev) loadChanges(commentsRev);
3249
+ commentsRev = v.comments;
3250
+ if (v.reads !== readsAt) {
3251
+ readsAt = v.reads;
3252
+ syncReads();
3253
+ }
3254
+ const s = v.session;
3255
+ const mode = s ? v.mode || "listening" : "away";
3256
+ const span = (t) => Object.assign(document.createElement("span"), { textContent: t });
3257
+ const agent = s?.agent || "Claude";
3258
+ const tag = s && s.name !== agent ? [span(`(${s.name})`)] : [];
3259
+ if (mode === "listening") who.replaceChildren(span("talking to"), agent, ...tag);
3260
+ else if (mode === "working") who.replaceChildren(agent, span("is working"), ...tag);
3261
+ else who.replaceChildren(span("no agent listening"));
3262
+ who.classList.toggle("idle", mode === "away");
3263
+ who.classList.toggle("working", mode === "working");
3264
+ listBtn.dataset.agent = mode;
3265
+ chatBtn.dataset.agent = mode;
3266
+ if (coarse) chatBtn.title = who.textContent;
3267
+ who.setAttribute("aria-label", who.textContent);
3268
+ if (s?.url && mode !== "away") Object.assign(who, { href: s.url, target: "_blank" });
3269
+ else who.removeAttribute("href");
3270
+ who.dataset.copy = !s?.url && s?.resume && mode !== "away" ? s.resume : "";
3271
+ who.title = mode === "away" ? "Ask your agent to run: npx @leonidstern/labit wait" : s?.resume ? `${s.resume}${who.dataset.copy ? " (tap to copy)" : ""}` : "";
3272
+ who.hidden = false;
3273
+ }
3274
+ };
3275
+ const key = "lab-scroll:" + location.pathname;
3276
+ try {
3277
+ const kept = JSON.parse(sessionStorage.getItem(key) || "null");
3278
+ if (kept !== null) {
3279
+ sessionStorage.removeItem(key);
3280
+ if (kept.open) openId = kept.open;
3281
+ if (kept.list) {
3282
+ listOpen = true;
3283
+ filter = ["new", "open", "resolved", "mine"].includes(kept.filter) ? kept.filter : filter;
3284
+ }
3285
+ if (kept.chat) chatOpen = true;
3286
+ addEventListener("load", () => scrollTo(0, +(kept.y ?? kept)));
3287
+ }
3288
+ } catch {
3289
+ }
3290
+ let touchedAt = 0;
3291
+ for (const t of ["pointerdown", "keydown", "wheel", "touchstart"]) addEventListener(t, () => touchedAt = performance.now(), { capture: true, passive: true });
3292
+ const busy = () => draft || grabbing || openId || chatOpen || listOpen || coarse && /^(textarea|input)$/.test(root.activeElement?.localName || "") || [...root.querySelectorAll("textarea")].some((t) => t.value.trim()) || performance.now() - touchedAt < 1500;
3293
+ let reloadWhenShown = false;
3294
+ let reloadTimer = 0;
3295
+ const reload = () => {
3296
+ if (document.hidden) return void (reloadWhenShown = true);
3297
+ if (busy()) {
3298
+ if (!reloadTimer) reloadTimer = setTimeout(() => (reloadTimer = 0, reload()), 500);
3299
+ return;
3300
+ }
3301
+ try {
3302
+ sessionStorage.setItem(key, JSON.stringify({ y: scrollY, open: openId, list: listOpen, filter, chat: chatOpen }));
3303
+ } catch {
3304
+ }
3305
+ location.reload();
3306
+ };
3307
+ const who = document.createElement("a");
3308
+ who.className = "listener";
3309
+ who.addEventListener("click", async () => {
3310
+ const text = who.dataset.copy;
3311
+ if (!text) return;
3312
+ try {
3313
+ await navigator.clipboard.writeText(text);
3314
+ const was = [...who.childNodes];
3315
+ who.replaceChildren("copied");
3316
+ setTimeout(() => who.textContent === "copied" && who.replaceChildren(...was), 1200);
3317
+ } catch {
3318
+ }
3319
+ });
3320
+ who.hidden = true;
3321
+ root.querySelector(".left").prepend(who);
3322
+ let stream = null;
3323
+ let beat = 0;
3324
+ const showAway = (word) => {
3325
+ who.replaceChildren(Object.assign(document.createElement("span"), { textContent: word }));
3326
+ who.setAttribute("aria-label", word);
3327
+ who.classList.add("idle");
3328
+ who.classList.remove("working");
3329
+ who.hidden = false;
3330
+ };
3331
+ let commentsRev = null;
3332
+ let readsAt = null;
3333
+ let hotAt = null;
3334
+ const swapCss = (files) => {
3335
+ const links = [.../** @type {NodeListOf<HTMLLinkElement>} */
3336
+ document.querySelectorAll('link[rel~="stylesheet"][href]:not([data-lab-swap])')].filter((l) => new URL(l.href, location.href).origin === location.origin);
3337
+ const named = links.filter((l) => files.includes(decodeURIComponent(new URL(l.href, location.href).pathname)));
3338
+ for (const link of named.length ? named : links) {
3339
+ const url = new URL(link.href, location.href);
3340
+ url.searchParams.set("lab-v", Date.now().toString(36));
3341
+ const next = (
3342
+ /** @type {HTMLLinkElement} */
3343
+ link.cloneNode()
3344
+ );
3345
+ next.href = url.href;
3346
+ next.dataset.labSwap = "";
3347
+ const path = url.pathname;
3348
+ next.addEventListener("load", () => {
3349
+ for (
3350
+ const l of
3351
+ /** @type {NodeListOf<HTMLLinkElement>} */
3352
+ document.querySelectorAll('link[rel~="stylesheet"][href]')
3353
+ ) if (l !== next && new URL(l.href, location.href).pathname === path) l.remove();
3354
+ delete next.dataset.labSwap;
3355
+ }, { once: true });
3356
+ next.addEventListener("error", () => next.remove(), { once: true });
3357
+ link.after(next);
3358
+ }
3359
+ };
3360
+ const fresh = (u) => {
3361
+ const url = new URL(u, location.href);
3362
+ url.searchParams.set("lab-v", Date.now().toString(36));
3363
+ return url.href;
3364
+ };
3365
+ const samePath = (u, paths) => {
3366
+ try {
3367
+ const url = new URL(u, location.href);
3368
+ return url.origin === location.origin && paths.includes(decodeURIComponent(url.pathname));
3369
+ } catch {
3370
+ return false;
3371
+ }
3372
+ };
3373
+ const swapImages = (paths) => {
3374
+ let hit = 0;
3375
+ for (const n of document.querySelectorAll('img, source, video[poster], image, use, link[rel~="icon"]')) {
3376
+ if (host2.contains(n)) continue;
3377
+ for (const attr of ["src", "href", "poster", "xlink:href"]) {
3378
+ const v = n.getAttribute(attr);
3379
+ if (!v || !samePath(v.split("#")[0], paths)) continue;
3380
+ const next = fresh(v.split("#")[0]);
3381
+ const im = new Image();
3382
+ im.src = next;
3383
+ (im.decode ? im.decode() : Promise.resolve()).catch(() => {
3384
+ }).finally(() => n.setAttribute(attr, next + (v.includes("#") ? v.slice(v.indexOf("#")) : "")));
3385
+ hit++;
3386
+ }
3387
+ const set = n.getAttribute("srcset");
3388
+ if (set && set.split(",").some((c) => samePath(c.trim().split(/\s+/)[0], paths))) {
3389
+ n.setAttribute("srcset", set.split(",").map((c) => {
3390
+ const [u, ...rest] = c.trim().split(/\s+/);
3391
+ return [samePath(u, paths) ? fresh(u) : u, ...rest].join(" ");
3392
+ }).join(", "));
3393
+ hit++;
3394
+ }
3395
+ }
3396
+ if (!hit) swapCss([]);
3397
+ };
3398
+ const reloadFonts = (paths) => {
3399
+ for (const sheet of document.styleSheets) {
3400
+ let rules;
3401
+ try {
3402
+ rules = sheet.cssRules;
3403
+ } catch {
3404
+ continue;
3405
+ }
3406
+ for (const r of rules || []) {
3407
+ if (!(r instanceof CSSFontFaceRule)) continue;
3408
+ const src = r.style.getPropertyValue("src");
3409
+ const base = sheet.href || location.href;
3410
+ if (!/url\(/.test(src) || ![...src.matchAll(/url\(["']?([^"')]+)/g)].some((m) => samePath(new URL(m[1], base).href, paths))) continue;
3411
+ const again = src.replace(/url\(["']?([^"')]+)["']?\)/g, (all, u) => samePath(new URL(u, base).href, paths) ? `url("${fresh(new URL(u, base).href)}")` : all);
3412
+ const d = (k) => r.style.getPropertyValue(k) || void 0;
3413
+ try {
3414
+ const face = new FontFace(
3415
+ d("font-family").replace(/^["']|["']$/g, ""),
3416
+ again,
3417
+ /** @type {any} */
3418
+ { weight: d("font-weight"), style: d("font-style"), stretch: d("font-stretch"), unicodeRange: d("unicode-range"), display: d("font-display") }
3419
+ );
3420
+ face.load().then((f) => document.fonts.add(f)).catch(() => {
3421
+ });
3422
+ } catch {
3423
+ }
3424
+ }
3425
+ }
3426
+ };
3427
+ const ownStyles = () => /* @__PURE__ */ new Set([fonts, pinCursorStyle]);
3428
+ const scriptsOf = (doc) => [...doc.querySelectorAll("script")].filter((x) => !/\/_lab\/comments\.js/.test(x.getAttribute("src") || "")).map((x) => x.getAttribute("src") || x.textContent);
3429
+ const sheetsOf = (doc) => [...doc.querySelectorAll('link[rel~="stylesheet"]')].map((l) => {
3430
+ try {
3431
+ return new URL(l.getAttribute("href"), location.href).pathname;
3432
+ } catch {
3433
+ return "";
3434
+ }
3435
+ });
3436
+ const keepOut = (n) => n === host2 || n.nodeType === 1 && n.localName === "script";
3437
+ const same = (o, n) => o.nodeType === n.nodeType && o.nodeName === n.nodeName && (o.nodeType !== 1 || (o.id || "") === (n.id || ""));
3438
+ const alike = (o, n) => same(o, n) && (o.nodeType === 1 ? Boolean(o.id) || o.getAttribute("class") === n.getAttribute("class") : o.nodeType !== 3 || o.data === n.data);
3439
+ const morphKids = (a, b) => {
3440
+ const olds = [...a.childNodes].filter((n) => !keepOut(n));
3441
+ const news = [...b.childNodes].filter((n) => !(n.nodeType === 1 && n.localName === "script"));
3442
+ let j = 0;
3443
+ let prev = null;
3444
+ const put = (n) => {
3445
+ const c = document.importNode(n, true);
3446
+ a.insertBefore(c, prev ? prev.nextSibling : olds[j] || a.firstChild);
3447
+ return c;
3448
+ };
3449
+ news.forEach((n, i) => {
3450
+ const o = olds[j];
3451
+ if (!o) return void (prev = put(n));
3452
+ if (alike(o, n)) return void (prev = morphNode(o, n), j++);
3453
+ if (news.slice(i + 1, i + 8).some((m) => alike(o, m))) return void (prev = put(n));
3454
+ const k = olds.slice(j + 1, j + 8).findIndex((m) => alike(m, n));
3455
+ if (k >= 0) {
3456
+ for (const gone2 of olds.slice(j, j + 1 + k)) gone2.remove();
3457
+ j += k + 1;
3458
+ return void (prev = morphNode(olds[j], n), j++);
3459
+ }
3460
+ prev = morphNode(o, n);
3461
+ j++;
3462
+ });
3463
+ for (const o of olds.slice(j)) o.remove();
3464
+ };
3465
+ const morphNode = (o, n) => {
3466
+ if (o.nodeType !== n.nodeType || o.nodeName !== n.nodeName || o.nodeType === 1 && (o.id || "") !== (n.id || "")) {
3467
+ const c = document.importNode(n, true);
3468
+ o.replaceWith(c);
3469
+ return c;
3470
+ }
3471
+ if (o.nodeType === 3 || o.nodeType === 8) {
3472
+ if (o.data !== n.data) o.data = n.data;
3473
+ return o;
3474
+ }
3475
+ if (o.nodeType !== 1) return o;
3476
+ for (const { name } of Array.from(o.attributes)) if (!n.hasAttribute(name) && !(name === "open" && /^(details|dialog)$/.test(o.localName))) o.removeAttribute(name);
3477
+ for (const { name, value } of Array.from(n.attributes)) if (o.getAttribute(name) !== value) o.setAttribute(name, value);
3478
+ if (o === document.activeElement || o.shadowRoot || /^(iframe|canvas|video|audio|textarea|select|input)$/.test(o.localName)) return o;
3479
+ morphKids(o, n);
3480
+ return o;
3481
+ };
3482
+ const ownScripts = () => scriptsOf(document).length > 0;
3483
+ let morphRun = 0;
3484
+ const morphPage = async () => {
3485
+ if (ownScripts()) return reload();
3486
+ const run = ++morphRun;
3487
+ try {
3488
+ const res = await fetch(location.href, { cache: "no-store", headers: { accept: "text/html" } });
3489
+ if (!res.ok) return reload();
3490
+ const html = await res.text();
3491
+ if (run !== morphRun) return;
3492
+ const doc = new DOMParser().parseFromString(html, "text/html");
3493
+ if (scriptsOf(doc).join("\n") !== scriptsOf(document).join("\n") || sheetsOf(doc).join("\n") !== sheetsOf(document).join("\n")) return reload();
3494
+ let mark = null;
3495
+ for (const y of [Math.min(innerHeight / 3, 240), innerHeight / 2, 80]) {
3496
+ const e = document.elementFromPoint(innerWidth / 2, y);
3497
+ if (e && e !== document.body && e !== document.documentElement && !host2.contains(e) && e !== host2) {
3498
+ mark = e;
3499
+ break;
3500
+ }
3501
+ }
3502
+ const markTop = mark?.getBoundingClientRect().top;
3503
+ const apply = () => {
3504
+ if (doc.title !== tabTitle.base) {
3505
+ tabTitle.base = doc.title;
3506
+ document.title = doc.title;
3507
+ drawList();
3508
+ }
3509
+ const mine2 = ownStyles();
3510
+ const olds = [...document.head.querySelectorAll("style")].filter((x) => !mine2.has(x));
3511
+ const news = [...doc.head.querySelectorAll("style")];
3512
+ news.forEach((n, i) => olds[i] ? olds[i].textContent !== n.textContent && (olds[i].textContent = n.textContent) : document.head.append(document.importNode(n, true)));
3513
+ for (const o of olds.slice(news.length)) o.remove();
3514
+ morphKids(document.body, doc.body);
3515
+ if (mark?.isConnected) {
3516
+ const moved = mark.getBoundingClientRect().top - markTop;
3517
+ if (Math.abs(moved) > 1) scrollBy(0, moved);
3518
+ }
3519
+ reflow();
3520
+ };
3521
+ const safe = () => {
3522
+ try {
3523
+ apply();
3524
+ } catch {
3525
+ reload();
3526
+ }
3527
+ };
3528
+ if (document.startViewTransition && !still.matches) document.startViewTransition(safe);
3529
+ else safe();
3530
+ } catch {
3531
+ reload();
3532
+ }
3533
+ };
3534
+ const hotUpdate = (files) => {
3535
+ const of = (kind) => files.filter((f) => f.kind === kind).map((f) => f.path);
3536
+ const here = decodeURIComponent(location.pathname).replace(/\/$/, "/index").replace(/\.html?$/i, "");
3537
+ if (of("html").some((p) => !p || p.replace(/\.html?$/i, "") === here)) morphPage();
3538
+ if (of("css").length) swapCss(of("css"));
3539
+ if (of("img").length) swapImages(of("img"));
3540
+ if (of("font").length) reloadFonts(of("font"));
3541
+ };
3542
+ const tab = Math.random().toString(36).slice(2, 12);
3543
+ let pollTimer = 0;
3544
+ let dropTimer = 0;
3545
+ const poll = async () => {
3546
+ try {
3547
+ onState(await (await fetch(`${script.dataset.live.replace(/live$/, "state")}?tab=${tab}`, { cache: "no-store" })).json());
3548
+ } catch {
3549
+ }
3550
+ };
3551
+ const toBackground = () => {
3552
+ clearTimeout(dropTimer);
3553
+ dropTimer = setTimeout(() => {
3554
+ stream?.close();
3555
+ stream = null;
3556
+ clearInterval(pollTimer);
3557
+ pollTimer = setInterval(poll, 2e4);
3558
+ }, 3e4);
3559
+ };
3560
+ const toFront = () => {
3561
+ clearTimeout(dropTimer);
3562
+ clearInterval(pollTimer);
3563
+ pollTimer = 0;
3564
+ connect();
3565
+ };
3566
+ const connect = () => {
3567
+ if (stream) return;
3568
+ stream = new EventSource(`${script.dataset.live}?tab=${tab}`);
3569
+ beat = Date.now();
3570
+ stream.addEventListener("beat", () => beat = Date.now());
3571
+ stream.onerror = () => showAway("reconnecting");
3572
+ stream.onmessage = (e) => {
3573
+ beat = Date.now();
3574
+ onState(JSON.parse(e.data));
3575
+ };
3576
+ };
3577
+ document.addEventListener("visibilitychange", () => {
3578
+ if (document.hidden) return toBackground();
3579
+ if (reloadWhenShown) return reload();
3580
+ toFront();
3581
+ });
3582
+ addEventListener("pagehide", () => {
3583
+ stream?.close();
3584
+ stream = null;
3585
+ fetch(script.dataset.live.replace(/live$/, "bye"), { method: "POST", keepalive: true, headers: { "content-type": "application/json" }, body: JSON.stringify({ tab }) }).catch(() => {
3586
+ });
3587
+ });
3588
+ addEventListener("pageshow", (e) => e.persisted && connect());
3589
+ let tick = Date.now();
3590
+ const freshStream = () => {
3591
+ stream?.close();
3592
+ stream = null;
3593
+ showAway("reconnecting");
3594
+ connect();
3595
+ };
3596
+ setInterval(() => {
3597
+ const now = Date.now();
3598
+ const slept = now - tick > 2e4;
3599
+ tick = now;
3600
+ if (document.hidden) return;
3601
+ if (slept || stream && now - beat > 4e4) freshStream();
3602
+ }, 5e3);
3603
+ addEventListener("online", () => !document.hidden && freshStream());
3604
+ connect();
3605
+ if (document.hidden) toBackground();
3606
+ }
3607
+ })();
3608
+ })();