| 1 | // "Ask Base anything": the chat docked beside Home (an <aside>), and the |
| 2 | // /ask page. Without this script the chat's forms post and come back (on |
| 3 | // Home, the X and the Base button post to /ask/dock); with it, the same |
| 4 | // forms go by fetch and replies stream in through /ask/events, which Base |
| 5 | // relays from Equipo. Text is only ever set with textContent. |
| 6 | |
| 7 | const root = document.querySelector("[data-ask]"); |
| 8 | if (root) start(root); |
| 9 | |
| 10 | function start(root) { |
| 11 | const dock = root.tagName === "ASIDE" ? root : null; |
| 12 | // The Base button and the Ask field under the greeting: whichever opened |
| 13 | // the chat on a phone gets focus back when it closes. |
| 14 | const openers = document.querySelectorAll("[data-ask-open]"); |
| 15 | let opener = openers[0]; |
| 16 | const thread = root.querySelector(".thread"); |
| 17 | const empty = root.querySelector("[data-empty]"); |
| 18 | const status = root.querySelector(".ask-status"); |
| 19 | const cancel = root.querySelector("form.cancel"); |
| 20 | const composer = root.querySelector("form.composer"); |
| 21 | const field = composer.querySelector("textarea"); |
| 22 | const send = composer.querySelector("button.send"); |
| 23 | const stop = composer.querySelector("button.stop"); |
| 24 | let source = null; |
| 25 | let turn = null; |
| 26 | let retry = 0; |
| 27 | |
| 28 | // Files (ask-attach.js, the module data-attach names): the paperclip, |
| 29 | // paste, drop and the chips, offered only while can_attach. files is |
| 30 | // null until the module is in; the chat works without it. A message of |
| 31 | // files alone has no words, so the field is never required here (it is |
| 32 | // without scripts, which can't attach). |
| 33 | let files = null; |
| 34 | let canAttach = composer.hasAttribute("data-can-attach"); |
| 35 | const attachMod = composer.dataset.attach ? import(composer.dataset.attach).then((m) => { |
| 36 | files = m.attach(root, { changed: () => paint(), lost: (state) => { quiet(); show(state); } }); |
| 37 | files.enable(canAttach); |
| 38 | paint(); |
| 39 | return m; |
| 40 | }, () => null) : Promise.resolve(null); |
| 41 | field.required = false; |
| 42 | |
| 43 | const json = { Accept: "application/json" }; |
| 44 | // A phone: Home's chat comes up full screen, and a job view is a sheet. |
| 45 | const phone = matchMedia("(max-width: 640px)"); |
| 46 | |
| 47 | // The states that show the conversation: ready, and ready without a |
| 48 | // runner that can answer (none, or one too old), which adds a note. |
| 49 | const runnerless = ["norunner", "oldrunner"]; |
| 50 | const chatting = (state) => state === "ready" || runnerless.includes(state); |
| 51 | |
| 52 | function show(state) { |
| 53 | root.dataset.state = state; |
| 54 | for (const el of root.querySelectorAll("[data-when]")) { |
| 55 | el.hidden = !el.dataset.when.split(" ").includes(state); |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | function key() { |
| 60 | const b = crypto.getRandomValues(new Uint8Array(16)); |
| 61 | return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join(""); |
| 62 | } |
| 63 | |
| 64 | // The log follows its newest line while the person is at (or within |
| 65 | // 80px of) its bottom. Anything that changes its height (a new line, a |
| 66 | // card, a streamed word, or the status row appearing below it) |
| 67 | // keeps it there; if they have scrolled up to read, it stays put and |
| 68 | // Jump to latest appears. Scrolling is always instant. |
| 69 | const jump = root.querySelector("button.jump"); |
| 70 | let pinned = true; |
| 71 | const atBottom = () => thread.scrollHeight - thread.scrollTop - thread.clientHeight < 80; |
| 72 | function toBottom() { |
| 73 | thread.scrollTop = thread.scrollHeight; |
| 74 | pinned = true; |
| 75 | if (jump) jump.hidden = true; |
| 76 | } |
| 77 | function scroll() { |
| 78 | empty.hidden = thread.children.length > 0; |
| 79 | if (pinned) toBottom(); |
| 80 | else if (jump) jump.hidden = false; |
| 81 | } |
| 82 | thread.addEventListener("scroll", () => { |
| 83 | pinned = atBottom(); |
| 84 | if (pinned && jump) jump.hidden = true; |
| 85 | }); |
| 86 | if (jump) jump.addEventListener("click", toBottom); |
| 87 | // The log's own box shrinks when the status row or a taller composer |
| 88 | // takes room below it, and its content grows with every word: either |
| 89 | // way, a pinned log goes back to its bottom. |
| 90 | if (window.ResizeObserver) { |
| 91 | const keep = () => { if (pinned) toBottom(); }; |
| 92 | const ro = new ResizeObserver(keep); |
| 93 | ro.observe(thread); |
| 94 | new MutationObserver(keep).observe(thread, { childList: true, subtree: true, characterData: true }); |
| 95 | } |
| 96 | |
| 97 | function item(attr, id) { |
| 98 | return id ? thread.querySelector(`[${attr}="${CSS.escape(id)}"]`) : null; |
| 99 | } |
| 100 | |
| 101 | // The note Home drew for this visit (how connecting Oficina went) stays |
| 102 | // where it was said, after the line it followed (data-after): a fresh |
| 103 | // read puts it back there, and what comes later goes below it. Once its |
| 104 | // line is gone from the conversation, so is the note. |
| 105 | const notice = thread.querySelector(":scope > .ask-notice"); |
| 106 | function placeNotice() { |
| 107 | if (!notice) return; |
| 108 | const after = notice.dataset.after; |
| 109 | const at = after ? item("data-id", after) : [...thread.querySelectorAll(":scope > li.msg[data-id]")].pop(); |
| 110 | if (at) { |
| 111 | at.after(notice); |
| 112 | notice.dataset.after = at.dataset.id; |
| 113 | } else if (after) notice.remove(); |
| 114 | else thread.prepend(notice); |
| 115 | } |
| 116 | |
| 117 | // A message, once: the Assistant's reply takes its streamed draft's |
| 118 | // place, or becomes its thinking bubble, where it is (once a glance has |
| 119 | // had its time, see held). |
| 120 | function addMessage(m) { |
| 121 | if (!m || !m.id || item("data-id", m.id)) return; |
| 122 | if (m.role !== "person" && held(m.turn_id, () => addMessage(m))) return; |
| 123 | const li = document.createElement("li"); |
| 124 | li.className = "msg " + (m.role === "person" ? "person" : "coordinator"); |
| 125 | li.dataset.id = m.id; |
| 126 | if (m.role !== "person" && m.turn_id) li.dataset.turn = m.turn_id; |
| 127 | // The person's own words take the same little Markdown as the |
| 128 | // Assistant's (rich), with emphasis only at word boundaries |
| 129 | // (strictEmphasis). |
| 130 | rich(li, m.text, m.role === "person"); |
| 131 | // What the Assistant looked up for its reply, after its words. |
| 132 | if (m.role !== "person") for (const l of m.lookups || []) li.append(lookupBox(l)); |
| 133 | // A person's files sit above their words, drawn as chat.html draws them. |
| 134 | if (m.role === "person" && m.attachments && m.attachments.length) { |
| 135 | attachMod.then((mod) => { if (mod) li.prepend(mod.filesRow(m.attachments, mod.wordsOf(composer))); }); |
| 136 | } |
| 137 | const draft = m.role !== "person" && (item("data-draft", m.turn_id) || bubbles.get(m.turn_id)); |
| 138 | if (draft && draft.querySelector(":scope > .think-line")) become(draft, li); |
| 139 | else if (draft) draft.replaceWith(li); |
| 140 | else thread.append(li); |
| 141 | if (m.role !== "person") reoffer(); |
| 142 | scroll(); |
| 143 | } |
| 144 | |
| 145 | // A streamed word: the turn's thinking bubble, if it shows, holds the |
| 146 | // draft. Equipo's offsets count UTF-8 bytes, so each draft keeps its |
| 147 | // length in bytes (drafted) to place the next word. A glance in the |
| 148 | // bubble has its time first (held), then crossfades into the first |
| 149 | // words; the words that come meanwhile wait for it. |
| 150 | const utf8 = new TextEncoder(); |
| 151 | const drafted = new WeakMap(); |
| 152 | function delta(d) { |
| 153 | if (held(d.turn_id, () => delta(d))) return; |
| 154 | let li = item("data-draft", d.turn_id); |
| 155 | const bubble = !li && bubbles.get(d.turn_id); |
| 156 | if (bubble && bubble.isConnected) { |
| 157 | li = bubble; |
| 158 | bubbles.delete(d.turn_id); |
| 159 | const glanced = glances.delete(d.turn_id); |
| 160 | const line = li.querySelector(":scope > .think-line"); |
| 161 | li.classList.replace("thinking", "draft"); |
| 162 | li.classList.add("answered"); |
| 163 | delete li.dataset.thinking; |
| 164 | li.dataset.draft = d.turn_id; |
| 165 | li.setAttribute("aria-busy", "true"); |
| 166 | spark.stop(li); |
| 167 | if (glanced) { |
| 168 | const id = d.turn_id; |
| 169 | waits.set(id, []); |
| 170 | const go = () => release(id); |
| 171 | setTimeout(go, 1000); // should the crossfade be cut short |
| 172 | swap(line, () => { unwiden(li); line.textContent = ""; write(li, line, d); }, go); |
| 173 | return; |
| 174 | } |
| 175 | for (const n of [line, li]) for (const a of n.getAnimations()) a.cancel(); |
| 176 | unwiden(li); |
| 177 | line.style.display = ""; |
| 178 | line.textContent = ""; |
| 179 | } else if (!li) { |
| 180 | li = document.createElement("li"); |
| 181 | li.className = "msg coordinator draft"; |
| 182 | li.dataset.draft = d.turn_id; |
| 183 | li.setAttribute("aria-busy", "true"); |
| 184 | // Above the turn's connect button, should it already show. |
| 185 | thread.insertBefore(li, thread.querySelector(`:scope > li.connect-offer[data-turn="${CSS.escape(d.turn_id)}"]`)); |
| 186 | } |
| 187 | write(li, li.querySelector(":scope > .think-line") || li, d); |
| 188 | } |
| 189 | function write(li, box, d) { |
| 190 | const at = drafted.get(li) || 0; |
| 191 | if (d.offset === at && typeof d.text === "string") { |
| 192 | const text = (drafting.get(li) || "") + d.text; |
| 193 | drafting.set(li, text); |
| 194 | drafted.set(li, at + utf8.encode(d.text).length); |
| 195 | draw(box, text); |
| 196 | } |
| 197 | scroll(); |
| 198 | } |
| 199 | // The draft is drawn as the reply will be: all the text so far through |
| 200 | // rich, in one go (no frame between clearing and filling), so a list is |
| 201 | // a list and bold is bold as it arrives. What the next words could still |
| 202 | // change stays out until they come (steady), as Equipo's drafts do. |
| 203 | const drafting = new WeakMap(); |
| 204 | function draw(box, text) { |
| 205 | const next = document.createElement("div"); |
| 206 | rich(next, steady(text)); |
| 207 | box.replaceChildren(...next.childNodes); |
| 208 | } |
| 209 | // A link on its way at the end of a line: its "[", words, and "]" or |
| 210 | // "](" with as much of the address as has come. |
| 211 | const openLink = /\[([^\[\]\n]*)(?:\](?:\([^()\s]*)?)?$/; |
| 212 | // A last line that is only a list marker so far. |
| 213 | const markerOnly = /^(?:[-*]|\d{1,3}[.)]?)?[ \t]*$/; |
| 214 | // steady is text without what its end leaves open: a last line that is |
| 215 | // only the start of a list item; a link on its way, down to its words; |
| 216 | // and an emphasis opener (**, * or _) with no closer yet, which shows as |
| 217 | // plain words until it closes. Only the last line can be open: no |
| 218 | // emphasis or link crosses a line. |
| 219 | function steady(text) { |
| 220 | text = text.replace(/\r\n?/g, "\n").replaceAll("\0", ""); |
| 221 | const at = text.lastIndexOf("\n") + 1; |
| 222 | let line = text.slice(at); |
| 223 | if (markerOnly.test(line)) return text.slice(0, at); |
| 224 | line = line.replace(openLink, "$1"); |
| 225 | // Between links, as emphasis reads it. |
| 226 | let out = "", last = 0; |
| 227 | for (const m of line.matchAll(linkRE)) { |
| 228 | out += unopened(line.slice(last, m.index)) + m[0]; |
| 229 | last = m.index + m[0].length; |
| 230 | } |
| 231 | return text.slice(0, at) + out + unopened(line.slice(last)); |
| 232 | } |
| 233 | // unopened is text without the emphasis openers emphasis would leave |
| 234 | // as they are for want of a closer: a marker followed by a non-space |
| 235 | // (or by the end), the way emphasis opens one. |
| 236 | function unopened(text) { |
| 237 | let out = "", last = 0; |
| 238 | for (let i = 0; i < text.length; ) { |
| 239 | const c = text[i]; |
| 240 | const run = c === "*" && text[i + 1] === "*" ? 2 : 1; |
| 241 | if (run === 2) { |
| 242 | const j = text.indexOf("**", i + 2); |
| 243 | if (j >= 0 && emphasized(text.slice(i + 2, j))) { i = j + 2; continue; } |
| 244 | } |
| 245 | if (c === "*" || (c === "_" && (i === 0 || !wordUnit(text.charCodeAt(i - 1))))) { |
| 246 | if (run === 1) { |
| 247 | const j = text.indexOf(c, i + 1); |
| 248 | if (j >= 0 && emphasized(text.slice(i + 1, j)) && (c === "*" || j + 1 === text.length || !wordUnit(text.charCodeAt(j + 1)))) { i = j + 1; continue; } |
| 249 | } |
| 250 | if (i + run === text.length || !space(text[i + run])) { |
| 251 | out += text.slice(last, i); |
| 252 | last = i + run; |
| 253 | } |
| 254 | } |
| 255 | i += run; |
| 256 | } |
| 257 | return out + text.slice(last); |
| 258 | } |
| 259 | |
| 260 | // An Assistant's line, in the little Markdown it may write (plan |
| 261 | // decision D16): runs of "- " or "* " lines are a bulleted list, runs of |
| 262 | // "1. " or "1) " lines (1 to 3 digits) a numbered one, and every other |
| 263 | // line is text with its newlines (the one next to a list goes). In text |
| 264 | // and list items, only http(s) addresses become links (opening in a new |
| 265 | // tab), and between links **x** is bold, *x* and _x_ italic. The rest, |
| 266 | // raw HTML and relative paths included, is text. Base's server does the |
| 267 | // same (richText in ask_cards.go). |
| 268 | const linkRE = /\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?:\/\/[^\s<>()\[\]"']+/g; |
| 269 | // webURL is target if it is an absolute http(s) URL with a host and no |
| 270 | // user info, else "" (equipo.WebURL on the server). |
| 271 | function webURL(target) { |
| 272 | try { |
| 273 | const u = new URL(target); |
| 274 | return (u.protocol === "http:" || u.protocol === "https:") && u.host && !u.username && !u.password ? u.href : ""; |
| 275 | } catch { |
| 276 | return ""; |
| 277 | } |
| 278 | } |
| 279 | // sameTab is whether href is Base's own connect-Oficina page. |
| 280 | function sameTab(href) { |
| 281 | try { |
| 282 | const u = new URL(href); |
| 283 | return u.origin === location.origin && u.pathname === "/ask/oficina/connect" && !u.search && !u.hash; |
| 284 | } catch { |
| 285 | return false; |
| 286 | } |
| 287 | } |
| 288 | function link(href, text) { |
| 289 | const a = document.createElement("a"); |
| 290 | a.href = href; |
| 291 | a.target = "_blank"; |
| 292 | a.rel = "noopener"; |
| 293 | a.textContent = text; |
| 294 | return a; |
| 295 | } |
| 296 | // listLine is line's list ({kind: "ul" or "ol", n, item}), or null. |
| 297 | function listLine(line) { |
| 298 | if (line.length > 2 && (line[0] === "-" || line[0] === "*") && line[1] === " ") return { kind: "ul", n: 0, item: line.slice(2) }; |
| 299 | const m = /^(\d{1,3})[.)] /.exec(line); |
| 300 | if (m && line.length > m[0].length) return { kind: "ol", n: Number(m[1]), item: line.slice(m[0].length) }; |
| 301 | return null; |
| 302 | } |
| 303 | // Line breaks are read as a page reads them (\r\n and \r are \n, and a |
| 304 | // NUL goes), so the server's HTML and this draw the same. |
| 305 | function rich(el, text, strict = false, links = true) { |
| 306 | el.replaceChildren(); |
| 307 | const lines = text.replace(/\r\n?/g, "\n").replaceAll("\0", "").split("\n"); |
| 308 | for (let i = 0; i < lines.length; ) { |
| 309 | const first = listLine(lines[i]); |
| 310 | if (!first) { |
| 311 | let j = i + 1; |
| 312 | while (j < lines.length && !listLine(lines[j])) j++; |
| 313 | inline(el, lines.slice(i, j).join("\n"), strict, links); |
| 314 | i = j; |
| 315 | continue; |
| 316 | } |
| 317 | const list = document.createElement(first.kind); |
| 318 | if (first.kind === "ol" && first.n !== 1) list.start = first.n; |
| 319 | for (let l; i < lines.length && (l = listLine(lines[i])) && l.kind === first.kind; i++) { |
| 320 | const li = document.createElement("li"); |
| 321 | inline(li, l.item, strict, links); |
| 322 | list.append(li); |
| 323 | } |
| 324 | el.append(list); |
| 325 | } |
| 326 | } |
| 327 | // inline appends text with its safe links, and bold and italics between |
| 328 | // them. Without links, each address is text, untouched by emphasis. |
| 329 | function inline(el, text, strict, links = true) { |
| 330 | const emphasis = strict ? strictEmphasis : looseEmphasis; |
| 331 | let last = 0; |
| 332 | for (const m of text.matchAll(links ? linkRE : plainLinkRE)) { |
| 333 | let end = m.index + m[0].length, label = m[1], target = m[2]; |
| 334 | if (label === undefined) { |
| 335 | target = m[0].replace(/[.,;:!?]+$/, ""); |
| 336 | end = m.index + target.length; |
| 337 | label = target; |
| 338 | } |
| 339 | if (!links) { |
| 340 | // An address is text, whatever it is: no URL check decides how |
| 341 | // it is drawn. |
| 342 | emphasis(el, text.slice(last, m.index)); |
| 343 | el.append(text.slice(m.index, end)); |
| 344 | last = end; |
| 345 | continue; |
| 346 | } |
| 347 | const href = webURL(target); |
| 348 | if (!href) continue; |
| 349 | emphasis(el, text.slice(last, m.index)); |
| 350 | el.append(link(href, label)); |
| 351 | last = end; |
| 352 | } |
| 353 | emphasis(el, text.slice(last)); |
| 354 | } |
| 355 | // emphasis appends text with **x** as <strong> and *x* or _x_ as <em>: |
| 356 | // x is the text up to the next same marker, not empty, on one line, and |
| 357 | // neither starting nor ending with a space; an _ also needs no word |
| 358 | // character just outside it. Nothing nests (emphasis in ask_cards.go). |
| 359 | function looseEmphasis(el, text) { |
| 360 | let last = 0; |
| 361 | const put = (tag, at, x, next) => { |
| 362 | if (at > last) el.append(text.slice(last, at)); |
| 363 | const e = document.createElement(tag); |
| 364 | e.textContent = x; |
| 365 | el.append(e); |
| 366 | last = next; |
| 367 | return next; |
| 368 | }; |
| 369 | for (let i = 0; i < text.length; ) { |
| 370 | const c = text[i]; |
| 371 | if (c === "*" && text[i + 1] === "*") { |
| 372 | const j = text.indexOf("**", i + 2); |
| 373 | if (j >= 0 && emphasized(text.slice(i + 2, j))) { |
| 374 | i = put("strong", i, text.slice(i + 2, j), j + 2); |
| 375 | continue; |
| 376 | } |
| 377 | } |
| 378 | if (c === "*" || (c === "_" && (i === 0 || !wordUnit(text.charCodeAt(i - 1))))) { |
| 379 | const j = text.indexOf(c, i + 1); |
| 380 | if (j >= 0 && emphasized(text.slice(i + 1, j)) && (c === "*" || j + 1 === text.length || !wordUnit(text.charCodeAt(j + 1)))) { |
| 381 | i = put("em", i, text.slice(i + 1, j), j + 1); |
| 382 | continue; |
| 383 | } |
| 384 | } |
| 385 | i++; |
| 386 | } |
| 387 | if (text.length > last) el.append(text.slice(last)); |
| 388 | } |
| 389 | // strictEmphasis is emphasis for the person's words: a run of markers |
| 390 | // opens only at the start or after a character that is no word's, closes |
| 391 | // only at the end or before one, and is exactly one * or _, or two *, so |
| 392 | // 2*3*4, x**2 + y**2 and __init__.py stay as written (strictEmphasis in |
| 393 | // ask_cards.go). Linear: each run looks only to the next of its marker. |
| 394 | function strictEmphasis(el, text) { |
| 395 | let last = 0; |
| 396 | const run = (at) => { let n = 1; while (text[at + n] === text[at]) n++; return n; }; |
| 397 | for (let i = 0; i < text.length; ) { |
| 398 | const c = text[i]; |
| 399 | if (c !== "*" && c !== "_") { i++; continue; } |
| 400 | const n = run(i); |
| 401 | if ((i === 0 || !wordUnit(text.charCodeAt(i - 1))) && (n === 1 || (n === 2 && c === "*"))) { |
| 402 | const j = text.indexOf(c, i + n); |
| 403 | if (j >= 0) { |
| 404 | const end = j + run(j), x = text.slice(i + n, j); |
| 405 | if (end - j === n && emphasized(x) && (end === text.length || !wordUnit(text.charCodeAt(end)))) { |
| 406 | if (i > last) el.append(text.slice(last, i)); |
| 407 | const e = document.createElement(n === 2 ? "strong" : "em"); |
| 408 | e.textContent = x; |
| 409 | el.append(e); |
| 410 | i = last = end; |
| 411 | continue; |
| 412 | } |
| 413 | } |
| 414 | } |
| 415 | i += n; |
| 416 | } |
| 417 | if (text.length > last) el.append(text.slice(last)); |
| 418 | } |
| 419 | // A lookup's answer: the person's Markdown (lists, and bold and italics |
| 420 | // at word boundaries) with no links at all; a Markdown link shows as its |
| 421 | // words, a bare URL or an autolink as text (lookupMarkdown in |
| 422 | // ask_cards.go, and the app's LookupMarkdown). |
| 423 | // Whitespace is spelled out (lookupSpace in ask_cards.go), and the u |
| 424 | // flag counts characters, not UTF-16 units, as Go and the app do. |
| 425 | const lookupSpace = "\\t\\n\\f\\r \\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000"; |
| 426 | const mdLinkRE = new RegExp(`\\[([^\\[\\]\\n]{1,300})\\]\\(([^()${lookupSpace}]{1,1000})\\)`, "gu"); |
| 427 | const plainLinkRE = new RegExp(`\\[([^\\[\\]\\n]{1,300})\\]\\(([^()${lookupSpace}]{1,1000})\\)|https?:\\/\\/[^${lookupSpace}<>()\\[\\]"']+`, "gu"); |
| 428 | function lookupMarkdown(el, text) { |
| 429 | rich(el, text.replace(/\r\n?/g, "\n").replaceAll("\0", "").replace(mdLinkRE, "$1"), true, false); |
| 430 | } |
| 431 | // sourceHost is a source's host as its line shows it, without "www." |
| 432 | // (sourceHost in ask_cards.go). |
| 433 | function sourceHost(u) { |
| 434 | try { |
| 435 | return new URL(u).hostname.toLowerCase().replace(/^www\./, ""); |
| 436 | } catch { |
| 437 | return ""; |
| 438 | } |
| 439 | } |
| 440 | // A lookup under the Assistant's reply, as the ask-lookup template draws |
| 441 | // it: the answer, then the quiet Sources line (ask.sources, copy review |
| 442 | // 14), each source's title a link opening in a new tab and its host |
| 443 | // after it. |
| 444 | function lookupBox(l) { |
| 445 | const box = document.createElement("div"); |
| 446 | box.className = "lookup"; |
| 447 | const answer = document.createElement("div"); |
| 448 | answer.className = "lookup-answer"; |
| 449 | lookupMarkdown(answer, String(l.answer || "")); |
| 450 | const line = document.createElement("p"); |
| 451 | line.className = "lookup-sources"; |
| 452 | const label = document.createElement("span"); |
| 453 | label.className = "lookup-label"; |
| 454 | label.textContent = "Sources"; |
| 455 | line.append(label); |
| 456 | for (const s of l.sources || []) { |
| 457 | const href = webURL(s.url); |
| 458 | if (!href || !href.startsWith("https:")) continue; |
| 459 | const host = sourceHost(s.url); |
| 460 | const one = document.createElement("span"); |
| 461 | one.className = "source"; |
| 462 | const a = document.createElement("a"); |
| 463 | a.href = s.url; |
| 464 | a.target = "_blank"; |
| 465 | a.rel = "noopener noreferrer nofollow"; |
| 466 | a.textContent = s.title || host; |
| 467 | const h = document.createElement("span"); |
| 468 | h.className = "source-host"; |
| 469 | h.textContent = host; |
| 470 | one.append(a, h); |
| 471 | line.append(one); |
| 472 | } |
| 473 | box.append(answer, line); |
| 474 | return box; |
| 475 | } |
| 476 | const space = (c) => c === " " || c === "\t"; |
| 477 | const emphasized = (x) => x !== "" && !x.includes("\n") && !space(x[0]) && !space(x[x.length - 1]); |
| 478 | // A word's code unit: an ASCII letter, digit or _, or anything beyond |
| 479 | // ASCII (wordByte on the server sees the same in UTF-8). |
| 480 | const wordUnit = (u) => u >= 0x80 || u === 95 || (u >= 48 && u <= 57) || (u >= 97 && u <= 122) || (u >= 65 && u <= 90); |
| 481 | |
| 482 | // A card, drawn from its fields alone as the server draws it (the |
| 483 | // ask-card template): the question, a link per link, a button per option |
| 484 | // (its label, posting its value) while it is open, and the line saying |
| 485 | // how it ended. A newer revision redraws it; a card that has ended with |
| 486 | // nothing to say goes, and so does one of a kind Base does not draw. |
| 487 | // A card that belongs to a job (c.job: a go-ahead or Publish) hangs under |
| 488 | // the job's pill once the job is drawn while it waits on the person, and |
| 489 | // once ended is listed in the job view (endedCard); it is loose until its |
| 490 | // job is drawn. |
| 491 | const kinds = ["question", "confirm", "outcome", "connect"]; |
| 492 | // The newest of each job's card, for its job to place when it is drawn. |
| 493 | const jobCards = new Map(); |
| 494 | function addCard(c) { |
| 495 | if (!c || !c.id) return; |
| 496 | if (c.kind === "connect" && (offerHref(c) || offers.has(c.id) || item("data-card", c.id)?.matches(".connect-offer"))) { |
| 497 | offer(c); |
| 498 | return; |
| 499 | } |
| 500 | const old = item("data-card", c.id); |
| 501 | if (!kinds.includes(c.kind) || (c.state !== "open" && !c.result)) { |
| 502 | if (old) old.remove(); |
| 503 | jobCards.delete(c.id); |
| 504 | scroll(); |
| 505 | return; |
| 506 | } |
| 507 | if (old && Number(old.dataset.revision) > c.revision) return; |
| 508 | if (c.job) jobCards.set(c.id, c); |
| 509 | const view = c.state !== "open" && c.job && item("data-job", c.job)?.querySelector(".jobview ol.jv-cards"); |
| 510 | if (view) { |
| 511 | const li = endedCard(c); |
| 512 | if (old && old.parentElement === view) old.replaceWith(li); |
| 513 | else { |
| 514 | if (old) old.remove(); |
| 515 | view.append(li); |
| 516 | } |
| 517 | scroll(); |
| 518 | return; |
| 519 | } |
| 520 | const li = document.createElement("li"); |
| 521 | li.className = "msg card card-" + c.kind; |
| 522 | li.dataset.card = c.id; |
| 523 | li.dataset.revision = String(c.revision); |
| 524 | if (c.job) li.dataset.for = c.job; |
| 525 | const q = document.createElement("p"); |
| 526 | q.textContent = c.question || ""; |
| 527 | li.append(q); |
| 528 | for (const l of c.links || []) { |
| 529 | const safe = l && typeof l.url === "string" && webURL(l.url); |
| 530 | if (!safe) continue; |
| 531 | const p = document.createElement("p"); |
| 532 | const a = link(safe, l.label || safe); |
| 533 | a.className = "card-link"; |
| 534 | // Connecting Oficina is a page of Base's own: same tab. |
| 535 | if (l.rel === "oficina_connect" && sameTab(safe)) { |
| 536 | a.removeAttribute("target"); |
| 537 | a.removeAttribute("rel"); |
| 538 | } |
| 539 | p.append(a); |
| 540 | li.append(p); |
| 541 | } |
| 542 | const options = (c.options || []).filter((o) => o && typeof o.value === "string" && o.value); |
| 543 | if (c.state === "open" && options.length) { |
| 544 | const form = document.createElement("form"); |
| 545 | form.className = "choices"; |
| 546 | form.method = "post"; |
| 547 | form.action = `/ask/cards/${encodeURIComponent(c.id)}/answer`; |
| 548 | const rev = document.createElement("input"); |
| 549 | rev.type = "hidden"; |
| 550 | rev.name = "revision"; |
| 551 | rev.value = String(c.revision); |
| 552 | form.append(rev); |
| 553 | for (const o of options) { |
| 554 | const b = document.createElement("button"); |
| 555 | b.className = "btn ghost"; |
| 556 | b.type = "submit"; |
| 557 | b.name = "choice"; |
| 558 | b.value = o.value; |
| 559 | b.textContent = o.label || o.value; |
| 560 | form.append(b); |
| 561 | } |
| 562 | li.append(form); |
| 563 | } |
| 564 | if (c.result) { |
| 565 | const p = document.createElement("p"); |
| 566 | p.className = "card-state"; |
| 567 | p.textContent = c.result; |
| 568 | li.append(p); |
| 569 | } |
| 570 | const list = c.job && item("data-job", c.job)?.querySelector("ol.job-cards"); |
| 571 | if (old && (!list || old.parentElement === list)) old.replaceWith(li); |
| 572 | else { |
| 573 | if (old) old.remove(); |
| 574 | (list || thread).append(li); |
| 575 | } |
| 576 | scroll(); |
| 577 | } |
| 578 | |
| 579 | // An open connect card is a button, as the server draws it (the |
| 580 | // ask-offer template): the Oficina mark and "Connect Oficina", going to |
| 581 | // Base's own connect page in this tab, and a line saying what connecting |
| 582 | // unlocks. It ends the Assistant's newest reply. One that comes while |
| 583 | // the reply of the turn that raised it is on its way waits for that |
| 584 | // reply to land (reoffer); if no words come for OFFER_WAIT, it shows on |
| 585 | // its own below the thinking bubble, and moves into the reply once it |
| 586 | // lands. Connected, it becomes a quiet line where it is; a fresh read no |
| 587 | // longer draws it. |
| 588 | const OFFER_WAIT = 3000; |
| 589 | const offers = new Map(); // card id: the open connect card, drawn or waiting |
| 590 | const waiting = new Map(); // card id: its timer, while it waits for its reply |
| 591 | function offerHref(c) { |
| 592 | for (const l of c.links || []) { |
| 593 | const safe = l && l.rel === "oficina_connect" && typeof l.url === "string" && webURL(l.url); |
| 594 | if (safe && sameTab(safe)) return safe; |
| 595 | } |
| 596 | return ""; |
| 597 | } |
| 598 | function offer(c) { |
| 599 | const old = item("data-card", c.id), known = offers.get(c.id); |
| 600 | if ((known && known.revision > c.revision) || (old && Number(old.dataset.revision) > c.revision)) return; |
| 601 | if (c.state !== "open") { |
| 602 | offers.delete(c.id); |
| 603 | clearTimeout(waiting.get(c.id)); |
| 604 | waiting.delete(c.id); |
| 605 | if (!old) return; |
| 606 | const done = document.createElement("p"); |
| 607 | done.className = "connect-done"; |
| 608 | const tick = icon(marks.done); |
| 609 | tick.setAttribute("aria-hidden", "true"); |
| 610 | done.append(tick, "Connected"); |
| 611 | old.classList.add("connected"); |
| 612 | old.dataset.revision = String(c.revision); |
| 613 | old.replaceChildren(done); |
| 614 | scroll(); |
| 615 | return; |
| 616 | } |
| 617 | if (!offerHref(c)) return; |
| 618 | const turnID = typeof c.turn_id === "string" && c.turn_id ? c.turn_id : known && known.turn_id; |
| 619 | c = { ...c, turn_id: turnID || "" }; |
| 620 | offers.set(c.id, c); |
| 621 | if (onItsWay(c)) { |
| 622 | if (!old) wait(c); |
| 623 | return; |
| 624 | } |
| 625 | put(c); |
| 626 | } |
| 627 | // onItsWay is whether the reply of the turn that raised c is still to |
| 628 | // land: the turn has not ended, or its words still stream. |
| 629 | function onItsWay(c) { |
| 630 | const id = c.turn_id; |
| 631 | if (!id || thread.querySelector(`:scope > li.msg.coordinator[data-id][data-turn="${CSS.escape(id)}"]`)) return false; |
| 632 | return !over.has(id) || bubbles.has(id) || !!item("data-draft", id); |
| 633 | } |
| 634 | function wait(c) { |
| 635 | if (waiting.has(c.id)) return; |
| 636 | waiting.set(c.id, setTimeout(() => { |
| 637 | waiting.delete(c.id); |
| 638 | const now = offers.get(c.id); |
| 639 | if (!now) return; |
| 640 | // Words are streaming: the reply is coming, wait for it. |
| 641 | if (item("data-draft", now.turn_id) && onItsWay(now)) wait(now); |
| 642 | else if (!item("data-card", now.id)) put(now); |
| 643 | }, OFFER_WAIT)); |
| 644 | } |
| 645 | // reoffer puts every open connect card whose reply is no longer on its |
| 646 | // way at the end of the newest reply (put). |
| 647 | function reoffer() { |
| 648 | for (const c of offers.values()) { |
| 649 | if (onItsWay(c)) continue; |
| 650 | clearTimeout(waiting.get(c.id)); |
| 651 | waiting.delete(c.id); |
| 652 | put(c); |
| 653 | } |
| 654 | } |
| 655 | // put draws open connect card c at the end of the Assistant's newest |
| 656 | // reply, or on its own at the end of the conversation (below the |
| 657 | // thinking bubble) when there is none, or its reply is still to land. |
| 658 | function put(c) { |
| 659 | const old = item("data-card", c.id); |
| 660 | const replies = thread.querySelectorAll(":scope > li.msg.coordinator[data-id]"); |
| 661 | const reply = onItsWay(c) ? null : replies[replies.length - 1]; |
| 662 | if (old && reply && old.tagName === "DIV") { |
| 663 | if (old.parentElement !== reply || reply.lastElementChild !== old) reply.append(old); |
| 664 | old.dataset.revision = String(c.revision); |
| 665 | scroll(); |
| 666 | return; |
| 667 | } |
| 668 | const focused = old && old.contains(document.activeElement); |
| 669 | const el = document.createElement(reply ? "div" : "li"); |
| 670 | el.className = reply ? "connect-offer" : "connect-offer loose"; |
| 671 | el.dataset.card = c.id; |
| 672 | el.dataset.revision = String(c.revision); |
| 673 | if (c.turn_id) el.dataset.turn = c.turn_id; |
| 674 | const a = document.createElement("a"); |
| 675 | a.className = "btn connect-btn"; |
| 676 | a.href = offerHref(c); |
| 677 | const mark = document.createElement("img"); |
| 678 | mark.className = "connect-mark"; |
| 679 | mark.src = thread.dataset.mark || ""; |
| 680 | mark.alt = ""; |
| 681 | a.append(mark, "Connect Oficina"); |
| 682 | el.append(a, para("connect-line", "Calendar, Docs, Sheets and more")); |
| 683 | if (old) old.remove(); |
| 684 | (reply || thread).append(el); |
| 685 | if (focused) a.focus({ preventScroll: true }); |
| 686 | scroll(); |
| 687 | } |
| 688 | |
| 689 | // A job's card that has ended, in its view, as the server draws it (the |
| 690 | // ask-jobcard template): the question and how it ended. |
| 691 | function endedCard(c) { |
| 692 | const li = document.createElement("li"); |
| 693 | li.className = "jv-card"; |
| 694 | li.dataset.card = c.id; |
| 695 | li.dataset.revision = String(c.revision); |
| 696 | li.dataset.for = c.job; |
| 697 | li.append(para("jv-q", c.question || ""), para("jv-result", c.result || "")); |
| 698 | return li; |
| 699 | } |
| 700 | |
| 701 | // A job, a pill, drawn as the server draws it (the ask-job template): its |
| 702 | // state's mark, the title and its status, and once there is something to |
| 703 | // see (ready, done) the link to it. A newer revision redraws it in place, |
| 704 | // never a second; the cards under it move to the new pill (ruling P6j), |
| 705 | // and so do loose cards of the job, drawn before it was (those that have |
| 706 | // ended to its view), and the ended cards in its view; an open job view |
| 707 | // stays open, and focus stays where it was. |
| 708 | const jobStates = ["working", "asking", "ready", "done", "paused", "stopped"]; |
| 709 | const marks = { |
| 710 | asking: "M9.2 9.2a2.9 2.9 0 0 1 5.6 1c0 2-2.8 2.4-2.8 4.3M12 18.2h.01", |
| 711 | ready: "M8 16L16 8M9.5 8H16v6.5", |
| 712 | done: "M6 12.5l4 4 8-9", |
| 713 | paused: "M19.2 12a7.2 7.2 0 1 1-14.4 0a7.2 7.2 0 1 1 14.4 0zM12 8.6V12l2.4 1.6", |
| 714 | stopped: "M9 7.5h6a1.5 1.5 0 0 1 1.5 1.5v6a1.5 1.5 0 0 1-1.5 1.5H9a1.5 1.5 0 0 1-1.5-1.5V9A1.5 1.5 0 0 1 9 7.5z", |
| 715 | }; |
| 716 | const svgNS = "http://www.w3.org/2000/svg"; |
| 717 | function span(cls, text) { |
| 718 | const el = document.createElement("span"); |
| 719 | el.className = cls; |
| 720 | if (text !== undefined) el.textContent = text; |
| 721 | return el; |
| 722 | } |
| 723 | function para(cls, text) { |
| 724 | const p = document.createElement("p"); |
| 725 | p.className = cls; |
| 726 | p.textContent = text; |
| 727 | return p; |
| 728 | } |
| 729 | // icon is a 24-unit SVG of one path. |
| 730 | function icon(d) { |
| 731 | const svg = document.createElementNS(svgNS, "svg"); |
| 732 | svg.setAttribute("viewBox", "0 0 24 24"); |
| 733 | const path = document.createElementNS(svgNS, "path"); |
| 734 | path.setAttribute("d", d); |
| 735 | svg.append(path); |
| 736 | return svg; |
| 737 | } |
| 738 | // A state's mark: working has none (it turns, in CSS). |
| 739 | function stateMark(state) { |
| 740 | const mark = span("state-mark"); |
| 741 | mark.setAttribute("aria-hidden", "true"); |
| 742 | if (marks[state]) mark.append(icon(marks[state])); |
| 743 | return mark; |
| 744 | } |
| 745 | // goOf is where to see job c's work once there is something to see |
| 746 | // (ready, done): its first link with no rel, as {href, label}, or null. |
| 747 | function goOf(c) { |
| 748 | if (c.state !== "ready" && c.state !== "done") return null; |
| 749 | const go = (c.links || []).find((l) => l && !l.rel); |
| 750 | const href = go && typeof go.url === "string" && webURL(go.url); |
| 751 | return href ? { href, label: go.label || href } : null; |
| 752 | } |
| 753 | // What in a pill can hold focus, each with its twin in the redrawn pill. |
| 754 | const twins = ["summary.pill-main", "a.pill-link", "a.jv-title", "a.jv-go", "[data-job-close]"]; |
| 755 | function addJob(c) { |
| 756 | if (!c || !c.id || !jobStates.includes(c.state)) return; |
| 757 | const old = item("data-job", c.id); |
| 758 | if (old && Number(old.dataset.revision) > c.revision) return; |
| 759 | // Where focus is, read before anything moves: a node that moves loses |
| 760 | // it, and a card that moves here is the same node. |
| 761 | const focus = document.activeElement; |
| 762 | const twin = old && old.contains(focus) ? twins.find((s) => old.querySelector(s) === focus) : undefined; |
| 763 | const inView = !!old && !!old.querySelector(".jobview")?.contains(focus); |
| 764 | const li = document.createElement("li"); |
| 765 | li.className = "job"; |
| 766 | li.dataset.job = c.id; |
| 767 | li.dataset.revision = String(c.revision); |
| 768 | li.dataset.state = c.state; |
| 769 | const title = c.question || "", stage = c.result || ""; |
| 770 | const pill = document.createElement("div"); |
| 771 | pill.className = "pill"; |
| 772 | const details = document.createElement("details"); |
| 773 | details.className = "job-toggle"; |
| 774 | const summary = document.createElement("summary"); |
| 775 | summary.className = "pill-main"; |
| 776 | summary.setAttribute("aria-label", title + ", " + stage); |
| 777 | summary.append(stateMark(c.state), span("pill-title", title), span("pill-stage", stage)); |
| 778 | details.append(summary, jobView(c)); |
| 779 | pill.append(details); |
| 780 | const go = goOf(c); |
| 781 | if (go) { |
| 782 | const a = link(go.href, go.label); |
| 783 | a.className = "pill-link"; |
| 784 | pill.append(a); |
| 785 | } |
| 786 | const list = document.createElement("ol"); |
| 787 | list.className = "job-cards"; |
| 788 | const ended = details.querySelector(".jobview ol.jv-cards"); |
| 789 | if (old) { |
| 790 | list.append(...old.querySelectorAll(":scope > ol.job-cards > li")); |
| 791 | ended.append(...old.querySelectorAll(".jobview ol.jv-cards > li")); |
| 792 | } |
| 793 | const loose = [...thread.querySelectorAll(`:scope > [data-for="${CSS.escape(c.id)}"]`)]; |
| 794 | for (const el of loose) { |
| 795 | const k = jobCards.get(el.dataset.card); |
| 796 | if (!k || k.state === "open") list.append(el); |
| 797 | else { |
| 798 | el.remove(); |
| 799 | ended.append(endedCard(k)); |
| 800 | } |
| 801 | } |
| 802 | li.append(pill, list); |
| 803 | if (popovers) { |
| 804 | summary.setAttribute("aria-expanded", "false"); |
| 805 | } else { |
| 806 | details.open = !!old && !!old.querySelector("details.job-toggle")?.open; |
| 807 | } |
| 808 | if (old) old.replaceWith(li); |
| 809 | else thread.append(li); |
| 810 | if (popovers && viewing === c.id) openView(li, false, true); |
| 811 | // Focus goes back: to the card that moved here, or to the twin of what |
| 812 | // had it; in the view, when its twin has gone, to Close; else the pill. |
| 813 | let to = null; |
| 814 | if (focus && li.contains(focus)) to = focus; |
| 815 | else if (twin || inView) { |
| 816 | to = [twin && li.querySelector(twin), inView && li.querySelector("[data-job-close]"), summary] |
| 817 | .find((el) => el && !el.hidden && el.checkVisibility({ visibilityProperty: true })); |
| 818 | } |
| 819 | if (to && document.activeElement !== to) to.focus({ preventScroll: true }); |
| 820 | scroll(); |
| 821 | } |
| 822 | // The job view, opened from the pill, drawn as the server draws it (the |
| 823 | // ask-jobview template): the title, linked to the job's own page (its |
| 824 | // link with rel equipo, the link's label as its tooltip): the only place |
| 825 | // that link is drawn. Then the status, one sentence more, for a paused |
| 826 | // job that offers it "Carry on now" (carryOn), when it started, and the |
| 827 | // link to the work once there is something to see. |
| 828 | function jobView(c) { |
| 829 | const view = document.createElement("section"); |
| 830 | view.className = "jobview"; |
| 831 | view.setAttribute("aria-label", c.question || ""); |
| 832 | const header = document.createElement("header"); |
| 833 | const h3 = document.createElement("h3"); |
| 834 | const page = (c.links || []).find((l) => l && l.rel === "equipo"); |
| 835 | const href = page && typeof page.url === "string" && webURL(page.url); |
| 836 | if (href) { |
| 837 | const a = link(href, c.question || ""); |
| 838 | a.className = "jv-title"; |
| 839 | if (page.label) a.title = page.label; |
| 840 | const arrow = icon("M9 6h9v9M18 6L7 17"); |
| 841 | arrow.setAttribute("aria-hidden", "true"); |
| 842 | a.append(arrow); |
| 843 | h3.append(a); |
| 844 | } else h3.textContent = c.question || ""; |
| 845 | const close = document.createElement("button"); |
| 846 | close.className = "round"; |
| 847 | close.type = "button"; |
| 848 | close.dataset.jobClose = ""; |
| 849 | close.setAttribute("aria-label", "Close"); |
| 850 | const x = icon("M6 6l12 12M18 6L6 18"); |
| 851 | x.setAttribute("aria-hidden", "true"); |
| 852 | close.append(x); |
| 853 | // Without the popover it opens in place, as without scripts: no Close. |
| 854 | close.hidden = !popovers; |
| 855 | header.append(stateMark(c.state), h3, close); |
| 856 | view.append(header, para("jv-stage", c.result || "")); |
| 857 | if (c.detail) view.append(para("jv-detail", c.detail)); |
| 858 | if ((c.state === "paused" || c.state === "stopped") && c.carry_on === true) view.append(carryOn(c)); |
| 859 | const ended = document.createElement("ol"); |
| 860 | ended.className = "jv-cards"; |
| 861 | view.append(ended); |
| 862 | const at = typeof c.started_at === "string" ? new Date(c.started_at) : null; |
| 863 | if (at && !isNaN(at)) { |
| 864 | const p = para("jv-started", startedText(at, Date.now())); |
| 865 | p.dataset.at = c.started_at; |
| 866 | view.append(p); |
| 867 | } |
| 868 | const go = goOf(c); |
| 869 | if (go) { |
| 870 | const a = link(go.href, go.label); |
| 871 | a.className = "jv-go"; |
| 872 | view.append(a); |
| 873 | } |
| 874 | return view; |
| 875 | } |
| 876 | |
| 877 | // "Carry on now", as the server draws it (the ask-jobview template): a |
| 878 | // form posting the card's revision, and the line under it saying what |
| 879 | // it uses, and an empty live region (jv-error, role="status") for a |
| 880 | // failure to say so inside the view, where a phone's sheet shows it. |
| 881 | // Its key is post's, kept until the outcome is known. |
| 882 | function carryOn(c) { |
| 883 | const form = document.createElement("form"); |
| 884 | form.className = "jv-act"; |
| 885 | form.method = "post"; |
| 886 | form.action = `/ask/cards/${encodeURIComponent(c.id)}/carry_on`; |
| 887 | const rev = document.createElement("input"); |
| 888 | rev.type = "hidden"; |
| 889 | rev.name = "revision"; |
| 890 | rev.value = String(c.revision); |
| 891 | const b = document.createElement("button"); |
| 892 | b.className = "btn ghost"; |
| 893 | b.type = "submit"; |
| 894 | b.textContent = "Carry on now"; |
| 895 | const error = para("jv-error", ""); |
| 896 | error.setAttribute("role", "status"); |
| 897 | form.append(rev, b); |
| 898 | // A held job (stopped) carries on on the same plan: no note. |
| 899 | if (c.state === "paused") { |
| 900 | const note = document.createElement("small"); |
| 901 | note.textContent = "Uses your other plan, at no extra cost."; |
| 902 | form.append(note); |
| 903 | } |
| 904 | form.append(error); |
| 905 | return form; |
| 906 | } |
| 907 | |
| 908 | // When a job started (plan decision D19), as the server says it |
| 909 | // (startedText in ask.go): how long ago in minutes or hours, then from a |
| 910 | // day on, the day in Base's time zone (the thread's data-zone; this |
| 911 | // device's if the browser does not know it). It moves on every minute. |
| 912 | const dayOf = (() => { |
| 913 | const day = { day: "numeric", month: "long" }; |
| 914 | try { |
| 915 | return new Intl.DateTimeFormat("en-GB", { ...day, timeZone: thread.dataset.zone || undefined }); |
| 916 | } catch { |
| 917 | return new Intl.DateTimeFormat("en-GB", day); |
| 918 | } |
| 919 | })(); |
| 920 | function startedText(at, now) { |
| 921 | const m = Math.floor((now - at) / 60000), h = Math.floor(m / 60); |
| 922 | if (!(m >= 1)) return "Started just now"; |
| 923 | if (m === 1) return "Started 1 minute ago"; |
| 924 | if (m < 60) return `Started ${m} minutes ago`; |
| 925 | if (h === 1) return "Started 1 hour ago"; |
| 926 | if (h < 24) return `Started ${h} hours ago`; |
| 927 | return "Started on " + dayOf.format(at); |
| 928 | } |
| 929 | setInterval(() => { |
| 930 | for (const p of thread.querySelectorAll(".jv-started[data-at]")) p.textContent = startedText(new Date(p.dataset.at), Date.now()); |
| 931 | }, 60000); |
| 932 | |
| 933 | // The job view opens from its pill (plan decision D13): on a wide screen |
| 934 | // a popover beside the pill inside the chat, above it when there is |
| 935 | // room, else below; on a phone a sheet from the foot of the screen, over |
| 936 | // the chat dimmed by a scrim. Focus goes to its Close; Close, Escape, a |
| 937 | // tap on the pill again, on the scrim or anywhere outside close it, and |
| 938 | // focus goes back to the pill (but for a tap outside, which puts focus |
| 939 | // where it lands). One view is open at a time; viewing is its job's id, |
| 940 | // kept while the job is redrawn. A browser with no popovers keeps the |
| 941 | // <details> as it is without scripts, opening in place. |
| 942 | const popovers = typeof HTMLElement.prototype.showPopover === "function"; |
| 943 | let viewing = ""; |
| 944 | const scrim = document.createElement("div"); |
| 945 | scrim.className = "scrim"; |
| 946 | scrim.hidden = true; |
| 947 | root.append(scrim); |
| 948 | const parts = (li) => { |
| 949 | const details = li.querySelector("details.job-toggle"); |
| 950 | return { details, summary: details.querySelector("summary"), view: details.querySelector(".jobview") }; |
| 951 | }; |
| 952 | // again: the job was redrawn with its view open, which stays put (no |
| 953 | // rise, no sheet sliding up). |
| 954 | function openView(li, focus, again) { |
| 955 | if (viewing && viewing !== li.dataset.job) closeView(false); |
| 956 | const { details, summary, view } = parts(li); |
| 957 | viewing = li.dataset.job; |
| 958 | if (again) view.style.animation = "none"; |
| 959 | details.open = true; |
| 960 | summary.setAttribute("aria-expanded", "true"); |
| 961 | view.popover = "manual"; |
| 962 | const close = view.querySelector("[data-job-close]"); |
| 963 | close.hidden = false; |
| 964 | if (!view.matches(":popover-open")) view.showPopover(); |
| 965 | scrim.hidden = !phone.matches; |
| 966 | place(); |
| 967 | if (focus) close.focus({ preventScroll: true }); |
| 968 | } |
| 969 | function closeView(focus) { |
| 970 | const li = viewing && item("data-job", viewing); |
| 971 | viewing = ""; |
| 972 | scrim.hidden = true; |
| 973 | if (!li) return; |
| 974 | const { details, summary, view } = parts(li); |
| 975 | if (view.matches(":popover-open")) view.hidePopover(); |
| 976 | details.open = false; |
| 977 | summary.setAttribute("aria-expanded", "false"); |
| 978 | if (focus) summary.focus({ preventScroll: true }); |
| 979 | } |
| 980 | // place anchors the open view to its pill, inside the chat and below |
| 981 | // its header (as the mockup's place()); a phone's sheet is the CSS's. |
| 982 | function place() { |
| 983 | const li = viewing && item("data-job", viewing); |
| 984 | if (!li) return; |
| 985 | const view = parts(li).view; |
| 986 | if (phone.matches) { |
| 987 | view.style.left = view.style.top = ""; |
| 988 | return; |
| 989 | } |
| 990 | const chat = root.getBoundingClientRect(), pill = li.querySelector(".pill").getBoundingClientRect(); |
| 991 | const head = root.querySelector(".ask-head")?.getBoundingClientRect().bottom ?? chat.top; |
| 992 | const w = view.offsetWidth, h = view.offsetHeight, above = pill.top - h - 8; |
| 993 | const top = above >= head + 8 ? above : pill.bottom + 8; |
| 994 | view.style.left = Math.max(chat.left + 16, Math.min(pill.left, chat.right - w - 16)) + "px"; |
| 995 | view.style.top = Math.max(head + 8, Math.min(top, chat.bottom - h - 8)) + "px"; |
| 996 | } |
| 997 | if (popovers) { |
| 998 | thread.addEventListener("click", (e) => { |
| 999 | const summary = e.target.closest("summary.pill-main"); |
| 1000 | if (summary) { |
| 1001 | e.preventDefault(); |
| 1002 | const li = summary.closest("li.job"); |
| 1003 | if (viewing === li.dataset.job) closeView(true); |
| 1004 | else openView(li, true); |
| 1005 | } else if (e.target.closest("[data-job-close]")) closeView(true); |
| 1006 | }); |
| 1007 | // A <details> opened some other way (find in page) opens its view. |
| 1008 | thread.addEventListener("toggle", (e) => { |
| 1009 | if (!e.target.matches || !e.target.matches("details.job-toggle")) return; |
| 1010 | const li = e.target.closest("li.job"); |
| 1011 | if (e.target.open && viewing !== li.dataset.job) openView(li, false); |
| 1012 | else if (!e.target.open && viewing === li.dataset.job) closeView(false); |
| 1013 | }, true); |
| 1014 | scrim.addEventListener("click", () => closeView(true)); |
| 1015 | // A tap outside closes the view. Focus goes back to the pill, unless |
| 1016 | // the tap put it on something else that takes it (once the tap's own |
| 1017 | // focusing is done). |
| 1018 | document.addEventListener("pointerdown", (e) => { |
| 1019 | if (!viewing || e.target === scrim) return; |
| 1020 | const li = item("data-job", viewing); |
| 1021 | if (!li) { |
| 1022 | closeView(false); |
| 1023 | return; |
| 1024 | } |
| 1025 | const { summary, view } = parts(li); |
| 1026 | if (view.contains(e.target) || summary.contains(e.target)) return; |
| 1027 | closeView(false); |
| 1028 | setTimeout(() => { |
| 1029 | const at = document.activeElement; |
| 1030 | if ((!at || at === document.body) && summary.isConnected && !summary.closest("[inert]")) summary.focus({ preventScroll: true }); |
| 1031 | }); |
| 1032 | }); |
| 1033 | // Escape closes an open view before anything else hears it (the docked |
| 1034 | // chat stays open). |
| 1035 | document.addEventListener("keydown", (e) => { |
| 1036 | if (e.key !== "Escape" || !viewing || e.defaultPrevented) return; |
| 1037 | const view = item("data-job", viewing)?.querySelector(".jobview"); |
| 1038 | if (!view || !view.matches(":popover-open")) { |
| 1039 | closeView(false); |
| 1040 | return; |
| 1041 | } |
| 1042 | e.preventDefault(); |
| 1043 | closeView(true); |
| 1044 | }, true); |
| 1045 | thread.addEventListener("scroll", place); |
| 1046 | addEventListener("resize", () => { |
| 1047 | if (!viewing) return; |
| 1048 | scrim.hidden = !phone.matches; |
| 1049 | place(); |
| 1050 | }); |
| 1051 | } |
| 1052 | |
| 1053 | // While the Assistant works on an answer, a small spark runs round its |
| 1054 | // thinking bubble's edge: a bright point with a short fading trail, its |
| 1055 | // colour drifting through Base's palette (teal, violet, rose, the |
| 1056 | // light's amber, mist), and now and then a faint crackle. It is drawn |
| 1057 | // with WebGL on a canvas over the edge, made only while a bubble thinks; |
| 1058 | // the loop ends once it has faded out, or the bubble has gone or is out |
| 1059 | // of sight. Without WebGL, or once its context is lost, the bubble gets |
| 1060 | // no-gl and the CSS sweep instead; with reduced motion, no spark at all |
| 1061 | // (the CSS glow alone). (The approved mockup's renderer, as it is.) |
| 1062 | const still = matchMedia("(prefers-reduced-motion: reduce)"); |
| 1063 | const lightDark = CSS.supports("color", "light-dark(white, black)"); |
| 1064 | function lightTheme() { |
| 1065 | const theme = document.documentElement.dataset.theme; |
| 1066 | return theme === "light" || (theme !== "dark" && lightDark && matchMedia("(prefers-color-scheme: light)").matches); |
| 1067 | } |
| 1068 | const spark = (() => { |
| 1069 | const cv = document.createElement("canvas"); |
| 1070 | cv.className = "spark"; |
| 1071 | cv.setAttribute("aria-hidden", "true"); |
| 1072 | const PAD = 8, LAP = 4000, CYCLE = 12000; |
| 1073 | const VS = "attribute vec2 p; void main() { gl_Position = vec4(p, 0.0, 1.0); }"; |
| 1074 | const FS = ` |
| 1075 | #ifdef GL_FRAGMENT_PRECISION_HIGH |
| 1076 | precision highp float; |
| 1077 | #else |
| 1078 | precision mediump float; |
| 1079 | #endif |
| 1080 | uniform vec2 u_size, u_half, u_hp; |
| 1081 | uniform vec4 u_rad; // corner radii: top-left, top-right, bottom-right, bottom-left |
| 1082 | uniform float u_head, u_len, u_dpr, u_time, u_alpha, u_flick, u_add, u_white, u_cyc; |
| 1083 | uniform vec3 u_pal[5]; |
| 1084 | uniform vec4 u_br[3]; |
| 1085 | const float PI = 3.14159265; |
| 1086 | float hash(float n) { return fract(sin(n) * 43758.5453); } |
| 1087 | float noise(float x) { float i = floor(x), f = fract(x); return mix(hash(i), hash(i + 1.0), f * f * (3.0 - 2.0 * f)); } |
| 1088 | float jag(float x) { float i = floor(x); return mix(hash(i), hash(i + 1.0), fract(x)); } |
| 1089 | vec3 pal(float x) { |
| 1090 | x = fract(x) * 5.0; float i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f); |
| 1091 | vec3 a = u_pal[0], b = u_pal[0]; |
| 1092 | for (int k = 0; k < 5; k++) { if (float(k) == i) a = u_pal[k]; if (float(k) == mod(i + 1.0, 5.0)) b = u_pal[k]; } |
| 1093 | return mix(a, b, f); |
| 1094 | } |
| 1095 | float qr(vec2 p) { return p.x > 0.0 ? (p.y < 0.0 ? u_rad.y : u_rad.z) : (p.y < 0.0 ? u_rad.x : u_rad.w); } |
| 1096 | float sdRR(vec2 p) { float r = qr(p); vec2 q = abs(p) - u_half + r; return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r; } |
| 1097 | // Distance along the edge, clockwise from the top edge's left end (y down), for the nearest edge point. |
| 1098 | float arcPos(vec2 p) { |
| 1099 | float tl = u_rad.x, tr = u_rad.y, br = u_rad.z, bl = u_rad.w, hx = u_half.x, hy = u_half.y; |
| 1100 | float T = 2.0 * hx - tl - tr, R = 2.0 * hy - tr - br, B = 2.0 * hx - br - bl, L = 2.0 * hy - bl - tl; |
| 1101 | float r = qr(p); vec2 q = abs(p) - (u_half - r); |
| 1102 | if (q.x > 0.0 && q.y > 0.0) { |
| 1103 | vec2 v = p - sign(p) * (u_half - r); float th = atan(v.y, v.x); |
| 1104 | if (p.x > 0.0 && p.y < 0.0) return T + r * (th + 0.5 * PI); |
| 1105 | if (p.x > 0.0) return T + 0.5 * PI * tr + R + r * th; |
| 1106 | if (p.y > 0.0) return T + 0.5 * PI * (tr + br) + R + B + r * (th - 0.5 * PI); |
| 1107 | return T + 0.5 * PI * (tr + br + bl) + R + B + L + r * (th + PI); |
| 1108 | } |
| 1109 | if (q.y > q.x) return p.y < 0.0 ? p.x + hx - tl : T + 0.5 * PI * (tr + br) + R + (hx - br - p.x); |
| 1110 | return p.x > 0.0 ? T + 0.5 * PI * tr + (p.y + hy - tr) : T + 0.5 * PI * (tr + br + bl) + R + B + (hy - bl - p.y); |
| 1111 | } |
| 1112 | void main() { |
| 1113 | vec2 p = gl_FragCoord.xy - 0.5 * u_size; p.y = -p.y; |
| 1114 | float sd = sdRR(p), d = abs(sd), s = arcPos(p); |
| 1115 | float inner = sd < 0.0 ? 0.5 : 1.0; // softer on the text side of the edge |
| 1116 | float delta = mod(u_head - s, u_len); |
| 1117 | float tl = min(u_len * 0.2, 110.0 * u_dpr); // trail length |
| 1118 | float k = clamp(delta / tl, 0.0, 1.0); |
| 1119 | float trail = pow(1.0 - k, 2.2) * smoothstep(0.0, 6.0 * u_dpr, delta) * (0.74 + 0.26 * noise(s / u_dpr * 0.4 - u_time * 26.0)); |
| 1120 | float w = 1.05 * u_dpr, gw = 3.6 * u_dpr; |
| 1121 | float line = trail * (exp(-d * d / (w * w)) + 0.42 * inner * exp(-d * d / (gw * gw))); |
| 1122 | float hd = length(p - u_hp); |
| 1123 | float hcore = exp(-hd * hd / (2.3 * 2.3 * u_dpr * u_dpr)); |
| 1124 | float head = hcore + 0.55 * inner * exp(-hd * hd / (4.6 * 4.6 * u_dpr * u_dpr)); |
| 1125 | float br = 0.0; |
| 1126 | for (int i = 0; i < 3; i++) { |
| 1127 | vec2 a = u_br[i].xy, e = u_br[i].zw, ab = e - a; |
| 1128 | float t = clamp(dot(p - a, ab) / max(dot(ab, ab), 1.0), 0.0, 1.0); |
| 1129 | vec2 n = normalize(vec2(-ab.y, ab.x) + 1e-5); |
| 1130 | vec2 c = a + ab * t + n * (jag(t * 4.0 + float(i) * 7.3 + floor(u_time * 24.0)) - 0.5) * 2.2 * u_dpr * t; |
| 1131 | float bd = length(p - c); |
| 1132 | br += (1.0 - t) * (exp(-bd * bd / (0.6 * 0.6 * u_dpr * u_dpr)) + 0.25 * exp(-bd / (2.4 * u_dpr))); |
| 1133 | } |
| 1134 | br *= u_flick; |
| 1135 | float I = clamp(line + head + br, 0.0, 1.0) * u_alpha; |
| 1136 | // The head carries the palette's current colour; the trail holds the colours it has just passed through. |
| 1137 | vec3 col = pal(u_cyc - 0.45 * (delta > 0.5 * u_len ? 0.0 : k)); |
| 1138 | col = mix(col, vec3(1.0), clamp(hcore * 1.2 + br * 0.5, 0.0, 1.0) * u_white); |
| 1139 | gl_FragColor = vec4(col * I, I * u_add); |
| 1140 | }`; |
| 1141 | // The WebGL context is made the first time the Assistant thinks, so a |
| 1142 | // page that never waits holds none. |
| 1143 | let gl = null, tried = false; |
| 1144 | const U = {}; |
| 1145 | function init() { |
| 1146 | tried = true; |
| 1147 | geo = null; |
| 1148 | gl = cv.getContext("webgl", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, powerPreference: "low-power" }); |
| 1149 | if (!gl) return; |
| 1150 | const sh = (type, src) => { |
| 1151 | const s = gl.createShader(type); |
| 1152 | gl.shaderSource(s, src); |
| 1153 | gl.compileShader(s); |
| 1154 | return gl.getShaderParameter(s, gl.COMPILE_STATUS) ? s : null; |
| 1155 | }; |
| 1156 | const vs = sh(gl.VERTEX_SHADER, VS), fs = sh(gl.FRAGMENT_SHADER, FS), prog = gl.createProgram(); |
| 1157 | if (vs && fs) { |
| 1158 | gl.attachShader(prog, vs); |
| 1159 | gl.attachShader(prog, fs); |
| 1160 | gl.linkProgram(prog); |
| 1161 | } |
| 1162 | if (!vs || !fs || !gl.getProgramParameter(prog, gl.LINK_STATUS)) { |
| 1163 | gl = null; |
| 1164 | return; |
| 1165 | } |
| 1166 | gl.useProgram(prog); |
| 1167 | gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer()); |
| 1168 | gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW); |
| 1169 | const loc = gl.getAttribLocation(prog, "p"); |
| 1170 | gl.enableVertexAttribArray(loc); |
| 1171 | gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0); |
| 1172 | for (const n of ["u_size", "u_half", "u_hp", "u_rad", "u_head", "u_len", "u_dpr", "u_time", "u_alpha", "u_flick", "u_add", "u_white", "u_cyc", "u_pal", "u_br"]) { |
| 1173 | U[n] = gl.getUniformLocation(prog, n); |
| 1174 | } |
| 1175 | } |
| 1176 | cv.addEventListener("webglcontextlost", (e) => { |
| 1177 | e.preventDefault(); |
| 1178 | gl = null; |
| 1179 | const was = host; |
| 1180 | end(); |
| 1181 | if (was && on) was.classList.add("no-gl"); |
| 1182 | }); |
| 1183 | |
| 1184 | // The edge's centre line, in device pixels from the canvas centre, and |
| 1185 | // a point on it by distance (clockwise, y down). |
| 1186 | let host = null, geo = null, raf = 0, on = false, alpha = 0, last = 0, t0 = 0, nextCrackle = 0, crackle = null; |
| 1187 | function measure() { |
| 1188 | const dpr = Math.min(devicePixelRatio || 1, 2), w = host.offsetWidth, h = host.offsetHeight; |
| 1189 | if (geo && geo.w === w && geo.h === h && geo.dpr === dpr) return geo; |
| 1190 | cv.width = Math.round((w + 2 * PAD) * dpr); |
| 1191 | cv.height = Math.round((h + 2 * PAD) * dpr); |
| 1192 | const cs = getComputedStyle(host), hx = (w / 2 - 0.5) * dpr, hy = (h / 2 - 0.5) * dpr; |
| 1193 | const rad = ["borderTopLeftRadius", "borderTopRightRadius", "borderBottomRightRadius", "borderBottomLeftRadius"] |
| 1194 | .map((k) => Math.max(0.5, Math.min((parseFloat(cs[k]) || 0) - 0.5, w / 2 - 0.5, h / 2 - 0.5)) * dpr); |
| 1195 | const [tl, tr, br, bl] = rad, T = 2 * hx - tl - tr, R = 2 * hy - tr - br, B = 2 * hx - br - bl, L = 2 * hy - bl - tl; |
| 1196 | const arc = (cx, cy, r, from) => [Math.PI * r / 2, (u) => { |
| 1197 | const t = from + u / r; |
| 1198 | return [cx + r * Math.cos(t), cy + r * Math.sin(t), Math.cos(t), Math.sin(t)]; |
| 1199 | }]; |
| 1200 | const segs = [ |
| 1201 | [T, (u) => [-hx + tl + u, -hy, 0, -1]], arc(hx - tr, -hy + tr, tr, -Math.PI / 2), |
| 1202 | [R, (u) => [hx, -hy + tr + u, 1, 0]], arc(hx - br, hy - br, br, 0), |
| 1203 | [B, (u) => [hx - br - u, hy, 0, 1]], arc(-hx + bl, hy - bl, bl, Math.PI / 2), |
| 1204 | [L, (u) => [-hx, hy - bl - u, -1, 0]], arc(-hx + tl, -hy + tl, tl, Math.PI), |
| 1205 | ]; |
| 1206 | geo = { w, h, dpr, hx, hy, rad, segs, len: segs.reduce((n, [l]) => n + l, 0) }; |
| 1207 | gl.viewport(0, 0, cv.width, cv.height); |
| 1208 | return geo; |
| 1209 | } |
| 1210 | function pointAt(s) { |
| 1211 | s = ((s % geo.len) + geo.len) % geo.len; |
| 1212 | for (const [l, f] of geo.segs) { |
| 1213 | if (s <= l) return f(s); |
| 1214 | s -= l; |
| 1215 | } |
| 1216 | return geo.segs[0][1](0); |
| 1217 | } |
| 1218 | const hex = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16) / 255); |
| 1219 | // Teal, violet, rose, the light beam's amber, pale mist: brighter on |
| 1220 | // dark glass, deeper on light so they read on white. |
| 1221 | const THEMES = { |
| 1222 | dark: { pal: ["#5EE3DA", "#A78BFA", "#F9A8D4", "#FFC48A", "#DCE4F5"].flatMap(hex), white: 0.75, add: 0.55 }, |
| 1223 | light: { pal: ["#0FA89C", "#7C4DE8", "#D23F8A", "#C9741F", "#5E6A96"].flatMap(hex), white: 0, add: 1 }, |
| 1224 | }; |
| 1225 | |
| 1226 | function end() { |
| 1227 | cancelAnimationFrame(raf); |
| 1228 | raf = 0; |
| 1229 | last = 0; |
| 1230 | alpha = 0; |
| 1231 | cv.remove(); |
| 1232 | } |
| 1233 | function frame(now) { |
| 1234 | raf = 0; |
| 1235 | if (!gl || still.matches || !host || !host.isConnected || !host.checkVisibility({ visibilityProperty: true })) { |
| 1236 | end(); |
| 1237 | return; |
| 1238 | } |
| 1239 | const dt = Math.min(now - (last || now), 100); |
| 1240 | last = now; |
| 1241 | alpha = on ? Math.min(1, alpha + dt / 260) : Math.max(0, alpha - dt / 360); |
| 1242 | if (!alpha && !on) { |
| 1243 | end(); // faded out: the loop ends here |
| 1244 | return; |
| 1245 | } |
| 1246 | const g = measure(); |
| 1247 | gl.clearColor(0, 0, 0, 0); |
| 1248 | gl.clear(gl.COLOR_BUFFER_BIT); |
| 1249 | const t = now - t0, head = ((t % LAP) / LAP) * g.len, [hx, hy] = pointAt(head); |
| 1250 | // Now and then, a crackle: two or three short jagged branches flick |
| 1251 | // out from the spark for a moment. |
| 1252 | if (now >= nextCrackle) { |
| 1253 | crackle = { at: now, b: Array.from({ length: 2 + (Math.random() < 0.5 ? 1 : 0) }, () => ({ ang: (Math.random() * 2 - 1) * 1.1, len: 3.5 + Math.random() * 3.5, back: Math.random() * 5 })) }; |
| 1254 | nextCrackle = now + 1200 + Math.random() * 1800; |
| 1255 | } |
| 1256 | const br = new Float32Array(12); |
| 1257 | let flick = 0; |
| 1258 | const ck = crackle ? now - crackle.at : Infinity; |
| 1259 | if (ck < 170) { |
| 1260 | flick = (1 - ck / 170) * (Math.floor(ck / 34) % 2 ? 0.35 : 1); |
| 1261 | crackle.b.forEach((b, i) => { |
| 1262 | const [sx, sy, snx, sny] = pointAt(head - b.back * g.dpr); |
| 1263 | const cs = Math.cos(b.ang), sn = Math.sin(b.ang), dx = snx * cs - sny * sn, dy = snx * sn + sny * cs, L = b.len * g.dpr; |
| 1264 | br.set([sx, sy, sx + dx * L, sy + dy * L], i * 4); |
| 1265 | }); |
| 1266 | } |
| 1267 | const th = THEMES[lightTheme() ? "light" : "dark"]; |
| 1268 | gl.uniform2f(U.u_size, cv.width, cv.height); |
| 1269 | gl.uniform2f(U.u_half, g.hx, g.hy); |
| 1270 | gl.uniform2f(U.u_hp, hx, hy); |
| 1271 | gl.uniform4fv(U.u_rad, g.rad); |
| 1272 | gl.uniform1f(U.u_head, head); |
| 1273 | gl.uniform1f(U.u_len, g.len); |
| 1274 | gl.uniform1f(U.u_dpr, g.dpr); |
| 1275 | gl.uniform1f(U.u_time, t / 1000); |
| 1276 | gl.uniform1f(U.u_alpha, alpha * alpha * (3 - 2 * alpha)); |
| 1277 | gl.uniform1f(U.u_flick, flick); |
| 1278 | gl.uniform1f(U.u_add, th.add); |
| 1279 | gl.uniform1f(U.u_white, th.white); |
| 1280 | gl.uniform1f(U.u_cyc, t / CYCLE); |
| 1281 | gl.uniform3fv(U.u_pal, th.pal); |
| 1282 | gl.uniform4fv(U.u_br, br); |
| 1283 | gl.drawArrays(gl.TRIANGLES, 0, 3); |
| 1284 | raf = requestAnimationFrame(frame); |
| 1285 | } |
| 1286 | function kick() { |
| 1287 | if (!on || still.matches || !host || !host.isConnected) return; |
| 1288 | // The shaders compile in the first frame, after the bubble has drawn. |
| 1289 | if (!tried) { |
| 1290 | if (!raf) raf = requestAnimationFrame(() => { |
| 1291 | raf = 0; |
| 1292 | init(); |
| 1293 | kick(); |
| 1294 | }); |
| 1295 | return; |
| 1296 | } |
| 1297 | if (!gl) { |
| 1298 | host.classList.add("no-gl"); |
| 1299 | return; |
| 1300 | } |
| 1301 | if (cv.parentNode !== host) { |
| 1302 | host.append(cv); |
| 1303 | geo = null; |
| 1304 | } |
| 1305 | if (!raf) raf = requestAnimationFrame(frame); |
| 1306 | } |
| 1307 | still.addEventListener("change", kick); |
| 1308 | return { |
| 1309 | // Start on a thinking bubble. |
| 1310 | start(el) { |
| 1311 | if (host !== el) { |
| 1312 | end(); |
| 1313 | host = el; |
| 1314 | } |
| 1315 | on = true; |
| 1316 | t0 = performance.now(); |
| 1317 | nextCrackle = t0 + 900 + Math.random() * 900; |
| 1318 | kick(); |
| 1319 | }, |
| 1320 | // Stop on el, if the spark is on it: it fades out, or ends at once |
| 1321 | // (now) when el is going away. |
| 1322 | stop(el, now) { |
| 1323 | if (host !== el) return; |
| 1324 | on = false; |
| 1325 | if (now) end(); |
| 1326 | }, |
| 1327 | }; |
| 1328 | })(); |
| 1329 | |
| 1330 | // The thinking bubble, one per turn being answered: on the Assistant's |
| 1331 | // side, at the end of the conversation, where its answer will appear. It |
| 1332 | // starts wordless, three soft dots (named "Thinking…" for assistive |
| 1333 | // tech), until Equipo says what the Assistant is doing: its glance, or |
| 1334 | // else its activity lines. The streamed words fill it and the reply |
| 1335 | // becomes it, in place; Stop or a failure takes it away. Its words are in |
| 1336 | // .think-line until the reply has landed. Without scripts the status line |
| 1337 | // says "Thinking…" instead. |
| 1338 | const bubbles = new Map(); |
| 1339 | function think(id) { |
| 1340 | const b = bubbles.get(id); |
| 1341 | // Its words are already streaming in (a late, stale revision). |
| 1342 | if ((b && b.isConnected) || item("data-draft", id)) return; |
| 1343 | const li = document.createElement("li"); |
| 1344 | li.className = "msg coordinator thinking"; |
| 1345 | li.dataset.thinking = id; |
| 1346 | const dots = threeDots(); |
| 1347 | dots.setAttribute("role", "img"); |
| 1348 | dots.setAttribute("aria-label", "Thinking…"); |
| 1349 | li.append(span("think-line")); |
| 1350 | li.firstChild.append(dots); |
| 1351 | thread.append(li); |
| 1352 | bubbles.set(id, li); |
| 1353 | spark.start(li); |
| 1354 | scroll(); |
| 1355 | } |
| 1356 | function threeDots() { |
| 1357 | const dots = span("dots"); |
| 1358 | dots.append(document.createElement("i"), document.createElement("i"), document.createElement("i")); |
| 1359 | return dots; |
| 1360 | } |
| 1361 | // say puts words in bubble b in place of what it says (its dots, or |
| 1362 | // other words), crossfading in place: both sit in the line's one grid |
| 1363 | // cell, the new fading in as the old fade out, so the bubble is never |
| 1364 | // blank, and it keeps its height (one line, an ellipsis if need be) and |
| 1365 | // only grows wider (widen). shown runs as the words come into view. |
| 1366 | // Instant with reduced motion, or out of sight. The words are a status, |
| 1367 | // not a reply: set apart in the CSS, and followed by the dots, still |
| 1368 | // shimmering (hidden from assistive tech, which reads the words). |
| 1369 | const FADE = 260; |
| 1370 | function say(b, words, shown) { |
| 1371 | const line = b.querySelector(":scope > .think-line"); |
| 1372 | const now = line && line.lastElementChild; |
| 1373 | if (!line || (now && now.matches(".say") && now.textContent === words)) return; |
| 1374 | for (const c of [...line.children]) if (c !== now) c.remove(); // already on their way out |
| 1375 | const w0 = b.getBoundingClientRect().width; |
| 1376 | const next = span("say"), dots = threeDots(); |
| 1377 | dots.setAttribute("aria-hidden", "true"); |
| 1378 | next.append(span("words", words), dots); |
| 1379 | line.append(next); |
| 1380 | const instant = still.matches || !line.getClientRects().length; |
| 1381 | widen(b, w0, instant); |
| 1382 | if (instant) { |
| 1383 | if (now) now.remove(); |
| 1384 | if (shown) shown(); |
| 1385 | return; |
| 1386 | } |
| 1387 | if (now) { |
| 1388 | // Fully in view as it starts to go, even if it was still fading in. |
| 1389 | for (const a of now.getAnimations()) a.cancel(); |
| 1390 | now.animate([{ opacity: 1 }, { opacity: 0 }], { duration: FADE, fill: "forwards" }).onfinish = () => now.remove(); |
| 1391 | } |
| 1392 | const fade = next.animate([{ opacity: 0 }, { opacity: 1 }], { duration: FADE }); |
| 1393 | if (shown) fade.ready.then(() => { if (fade.playState === "running") shown(); }, () => {}); |
| 1394 | } |
| 1395 | // widen keeps thinking bubble b at least as wide as it has been (w0 |
| 1396 | // before its line changed, and every width before), easing out to a |
| 1397 | // wider one; the reply lets it go (unwiden). |
| 1398 | const widths = new WeakMap(); |
| 1399 | function widen(b, w0, instant) { |
| 1400 | const keep = Math.max(widths.get(b) || 0, w0, b.getBoundingClientRect().width); |
| 1401 | widths.set(b, keep); |
| 1402 | for (const a of b.getAnimations()) if (a.id === "widen") a.cancel(); |
| 1403 | b.style.minWidth = `min(${w0}px, 100%)`; |
| 1404 | const done = () => { if (widths.get(b) === keep) b.style.minWidth = `min(${keep}px, 100%)`; }; |
| 1405 | if (instant || keep <= w0 + 0.5) return done(); |
| 1406 | const grow = b.animate([{ width: w0 + "px" }, { width: keep + "px" }], { duration: 200, easing: "cubic-bezier(.2,.8,.2,1)" }); |
| 1407 | grow.id = "widen"; |
| 1408 | grow.onfinish = done; |
| 1409 | } |
| 1410 | function unwiden(b) { |
| 1411 | widths.delete(b); |
| 1412 | for (const a of b.getAnimations()) if (a.id === "widen") a.cancel(); |
| 1413 | b.style.minWidth = ""; |
| 1414 | } |
| 1415 | |
| 1416 | // Equipo's glance: one line on the turn in flight, before its first |
| 1417 | // words (or never). It takes the bubble's dots or activity line, and |
| 1418 | // activity lines after it leave it be. It is never kept: a reload shows |
| 1419 | // the dots again. A reply that comes before the glance has been in view |
| 1420 | // for HOLD waits until it has (held), then takes its place. |
| 1421 | const HOLD = 1500; |
| 1422 | const glances = new Map(); // turn id: when its glance came into view (till then, when it came) |
| 1423 | const waits = new Map(); // turn id: what waits for its glance |
| 1424 | function glance(g) { |
| 1425 | const id = g && g.turn_id, text = g && typeof g.text === "string" ? g.text.trim() : ""; |
| 1426 | const b = bubbles.get(id); |
| 1427 | if (!text || isQuiet(id) || !turn || turn.id !== id || !b || !b.isConnected || !b.classList.contains("thinking") || glances.has(id) || waits.has(id)) return; |
| 1428 | glances.set(id, performance.now()); |
| 1429 | say(b, text, () => { if (glances.has(id)) glances.set(id, performance.now()); }); |
| 1430 | } |
| 1431 | // held keeps fn for turn id, to run once its glance has had its time, |
| 1432 | // and says whether it did. |
| 1433 | function held(id, fn) { |
| 1434 | if (!id) return false; |
| 1435 | const q = waits.get(id); |
| 1436 | if (q) { |
| 1437 | q.push(fn); |
| 1438 | return true; |
| 1439 | } |
| 1440 | const left = HOLD - (performance.now() - (glances.has(id) ? glances.get(id) : -Infinity)); |
| 1441 | if (!(left > 0)) return false; |
| 1442 | waits.set(id, [fn]); |
| 1443 | setTimeout(() => release(id), left); |
| 1444 | return true; |
| 1445 | } |
| 1446 | function release(id) { |
| 1447 | const q = waits.get(id); |
| 1448 | waits.delete(id); |
| 1449 | for (const fn of q || []) fn(); |
| 1450 | } |
| 1451 | // drop takes turn id's bubble away, and its spark with it. |
| 1452 | function drop(id) { |
| 1453 | const b = bubbles.get(id); |
| 1454 | bubbles.delete(id); |
| 1455 | glances.delete(id); |
| 1456 | waits.delete(id); |
| 1457 | if (!b) return; |
| 1458 | spark.stop(b, true); |
| 1459 | b.remove(); |
| 1460 | } |
| 1461 | // unthink settles turn t's bubble as the turn ends. Replied, the bubble |
| 1462 | // waits a little for the reply (it may come just after); otherwise, or |
| 1463 | // if it never comes, it goes. |
| 1464 | function unthink(t) { |
| 1465 | const b = bubbles.get(t.id); |
| 1466 | if (!b) return; |
| 1467 | if (t.state === "replied" && !(t.reply_id && item("data-id", t.reply_id))) { |
| 1468 | setTimeout(() => { if (bubbles.get(t.id) === b) drop(t.id); }, 5000); |
| 1469 | return; |
| 1470 | } |
| 1471 | drop(t.id); |
| 1472 | } |
| 1473 | // become makes bubble b the reply li, in place: its spark fades, and a |
| 1474 | // bubble that was still thinking crossfades its words into the reply's. |
| 1475 | function become(b, li) { |
| 1476 | const turnID = b.dataset.thinking || b.dataset.draft; |
| 1477 | bubbles.delete(turnID); |
| 1478 | glances.delete(turnID); |
| 1479 | spark.stop(b); |
| 1480 | const thinking = b.classList.contains("thinking"); |
| 1481 | b.classList.remove("thinking", "draft"); |
| 1482 | b.classList.add("answered"); |
| 1483 | delete b.dataset.thinking; |
| 1484 | delete b.dataset.draft; |
| 1485 | b.removeAttribute("aria-busy"); |
| 1486 | b.dataset.id = li.dataset.id; |
| 1487 | if (li.dataset.turn) b.dataset.turn = li.dataset.turn; |
| 1488 | const line = b.querySelector(":scope > .think-line"); |
| 1489 | const land = () => { unwiden(b); line.replaceChildren(...li.childNodes); }; |
| 1490 | const unwrap = () => { if (line.isConnected) line.replaceWith(...line.childNodes); }; |
| 1491 | if (thinking) swap(line, land, unwrap); |
| 1492 | else { |
| 1493 | for (const n of [line, b]) for (const a of n.getAnimations()) a.cancel(); |
| 1494 | land(); |
| 1495 | unwrap(); |
| 1496 | } |
| 1497 | } |
| 1498 | // swap changes the words in el, a bubble's line: the old ones fade out, |
| 1499 | // the bubble eases to its new size (the conversation following its foot |
| 1500 | // while it is pinned there), then the new ones fade in (shown runs as |
| 1501 | // they start to), and done runs. A straight swap with reduced motion, or |
| 1502 | // out of sight. |
| 1503 | function swap(el, apply, done, shown) { |
| 1504 | const box = el.parentElement; |
| 1505 | for (const n of [el, box]) for (const a of n.getAnimations()) a.cancel(); |
| 1506 | el.style.display = ""; |
| 1507 | const finish = () => { if (done) done(); }; |
| 1508 | if (still.matches || !el.getClientRects().length) { |
| 1509 | apply(); |
| 1510 | if (shown) shown(); |
| 1511 | finish(); |
| 1512 | return; |
| 1513 | } |
| 1514 | const out = el.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 150, easing: "ease-in", fill: "forwards" }); |
| 1515 | out.onfinish = () => { |
| 1516 | const w0 = box.offsetWidth, h0 = box.offsetHeight; |
| 1517 | apply(); |
| 1518 | const w1 = box.offsetWidth, h1 = box.offsetHeight; |
| 1519 | el.style.display = "none"; // out of layout while the box resizes, so it cannot overflow and nudge the scroll |
| 1520 | const grow = box.animate([{ width: w0 + "px", height: h0 + "px" }, { width: w1 + "px", height: h1 + "px" }], { duration: 220, easing: "cubic-bezier(.2,.8,.2,1)" }); |
| 1521 | const follow = () => { |
| 1522 | if (pinned) toBottom(); |
| 1523 | if (grow.playState === "running") requestAnimationFrame(follow); |
| 1524 | }; |
| 1525 | follow(); |
| 1526 | grow.onfinish = () => { |
| 1527 | el.style.display = ""; |
| 1528 | follow(); |
| 1529 | out.cancel(); |
| 1530 | const fade = el.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 260, easing: "ease-out" }); |
| 1531 | fade.onfinish = finish; |
| 1532 | if (shown) fade.ready.then(() => { if (fade.playState === "running") shown(); }, () => {}); |
| 1533 | }; |
| 1534 | grow.oncancel = () => { |
| 1535 | el.style.display = ""; |
| 1536 | out.cancel(); |
| 1537 | }; |
| 1538 | }; |
| 1539 | } |
| 1540 | |
| 1541 | const ended = (s) => s === "replied" || s === "failed" || s === "cancelled"; |
| 1542 | const failedFiles = { |
| 1543 | attachment_unavailable: "A file didn’t arrive whole. Attach it again.", |
| 1544 | runner_storage_full: "There’s no room left for these files. Try fewer or smaller ones.", |
| 1545 | runner_too_old: "Files can’t be read right now. Send it again without them.", |
| 1546 | }; |
| 1547 | |
| 1548 | // The field's end holds Stop while a turn runs, else Send once something |
| 1549 | // is typed, else nothing. A button that goes while it has focus hands it |
| 1550 | // to the field. |
| 1551 | function paint() { |
| 1552 | const had = document.activeElement; |
| 1553 | stop.hidden = !turn; |
| 1554 | send.hidden = !!turn || (!field.value.trim() && !(files && files.count())); |
| 1555 | if ((had === send && send.hidden) || (had === stop && stop.hidden)) field.focus(); |
| 1556 | } |
| 1557 | field.addEventListener("input", paint); |
| 1558 | paint(); |
| 1559 | |
| 1560 | // A team_update turn is the Assistant taking a job's news by itself, and |
| 1561 | // is quiet (plan decision D9): no status line, no activity, no Stop, and |
| 1562 | // never the turn in flight. Each turn's kind is kept for its activity. |
| 1563 | const quietTurns = new Set(); |
| 1564 | const isQuiet = (id) => quietTurns.has(id); |
| 1565 | // A turn that has ended stays ended: the send's own answer, carrying the |
| 1566 | // turn as it was queued, can come after the turn's events have ended it. |
| 1567 | const over = new Set(); |
| 1568 | function setTurn(t, line) { |
| 1569 | if (t && (!t.id || over.has(t.id))) return; |
| 1570 | if (t && ended(t.state)) over.add(t.id); |
| 1571 | if (t && t.kind === "team_update") { |
| 1572 | quietTurns.add(t.id); |
| 1573 | if (ended(t.state)) settle(t); |
| 1574 | return; |
| 1575 | } |
| 1576 | if (t && !ended(t.state)) { |
| 1577 | turn = t; |
| 1578 | cancel.action = `/ask/turns/${encodeURIComponent(t.id)}/cancel`; |
| 1579 | paint(); |
| 1580 | // Waiting is a notice, not an answer on its way: the status line |
| 1581 | // says it. Otherwise the thinking bubble does, and the line is empty. |
| 1582 | if (t.state === "waiting") { |
| 1583 | drop(t.id); |
| 1584 | status.textContent = line || "Ask Base can't answer right now. It will as soon as it can."; |
| 1585 | } else { |
| 1586 | status.textContent = ""; |
| 1587 | think(t.id); |
| 1588 | } |
| 1589 | return; |
| 1590 | } |
| 1591 | if (t) unthink(t); |
| 1592 | // A turn that ended without its reply lets its connect button show. |
| 1593 | if (t) reoffer(); |
| 1594 | if (t && turn && t.id !== turn.id) return; |
| 1595 | turn = null; |
| 1596 | paint(); |
| 1597 | // A turn that failed for its files says why (ask.go, failedFiles); read |
| 1598 | // afresh with nothing running, the server's line stands. |
| 1599 | status.textContent = t && t.state === "failed" ? failedFiles[t.reason] || "That didn't get an answer. Try again." : t ? "" : line || ""; |
| 1600 | settle(t); |
| 1601 | } |
| 1602 | // settle ends the drafts of turn t (every draft when there is none): a |
| 1603 | // cancelled or failed turn's goes, with any spark still on it and any |
| 1604 | // words still waiting for it (the failure is said in the status line); |
| 1605 | // the rest stay as written. |
| 1606 | function settle(t) { |
| 1607 | if (t && (t.state === "cancelled" || t.state === "failed")) waits.delete(t.id); |
| 1608 | for (const d of thread.querySelectorAll("[data-draft]")) { |
| 1609 | if (!t || d.dataset.draft === t.id) { |
| 1610 | if (t && (t.state === "cancelled" || t.state === "failed")) { |
| 1611 | spark.stop(d, true); |
| 1612 | d.remove(); |
| 1613 | } else d.removeAttribute("aria-busy"); |
| 1614 | } |
| 1615 | } |
| 1616 | } |
| 1617 | |
| 1618 | function listen(cursor) { |
| 1619 | quiet(); |
| 1620 | source = new EventSource(`/ask/events?after=${encodeURIComponent(cursor)}`); |
| 1621 | const on = (type, fn) => source.addEventListener(type, (e) => { |
| 1622 | retry = 0; |
| 1623 | fn(JSON.parse(e.data)); |
| 1624 | }); |
| 1625 | on("message", (e) => addMessage(e.data)); |
| 1626 | on("delta", (e) => delta(e.data)); |
| 1627 | on("card", (e) => (e.data && e.data.kind === "job" ? addJob(e.data) : addCard(e.data))); |
| 1628 | on("turn", (e) => setTurn(e.data)); |
| 1629 | on("glance", (e) => glance(e.data)); |
| 1630 | on("activity", (e) => { |
| 1631 | const id = e.data.turn_id, label = e.data.label; |
| 1632 | if (!label || isQuiet(id) || glances.has(id) || waits.has(id)) return; |
| 1633 | const b = bubbles.get(id); |
| 1634 | if (b && b.isConnected) say(b, label); |
| 1635 | else if (turn && id === turn.id) status.textContent = label; |
| 1636 | }); |
| 1637 | on("state", (e) => { |
| 1638 | quiet(); |
| 1639 | show(e.state); |
| 1640 | }); |
| 1641 | source.onerror = () => { |
| 1642 | if (source && source.readyState === EventSource.CLOSED) { |
| 1643 | quiet(); |
| 1644 | retry = Math.min(retry + 1, 6); |
| 1645 | setTimeout(() => { if (live()) load(); }, 2000 * retry); |
| 1646 | } |
| 1647 | }; |
| 1648 | } |
| 1649 | |
| 1650 | function quiet() { |
| 1651 | if (source) source.close(); |
| 1652 | source = null; |
| 1653 | } |
| 1654 | |
| 1655 | const live = () => !dock || isOpen(); |
| 1656 | |
| 1657 | async function load() { |
| 1658 | let s; |
| 1659 | try { |
| 1660 | const res = await fetch("/ask/state", { headers: json }); |
| 1661 | if (!res.ok) throw new Error(res.status); |
| 1662 | s = await res.json(); |
| 1663 | } catch { |
| 1664 | show("unavailable"); |
| 1665 | return; |
| 1666 | } |
| 1667 | show(s.state); |
| 1668 | canAttach = !!s.can_attach; |
| 1669 | if (files) files.enable(canAttach); |
| 1670 | if (!chatting(s.state) || !live()) return; |
| 1671 | // An open job view stays open, with focus in it if it was. |
| 1672 | const focused = viewing && item("data-job", viewing)?.querySelector(".jobview")?.contains(document.activeElement); |
| 1673 | thread.replaceChildren(); |
| 1674 | bubbles.clear(); |
| 1675 | jobCards.clear(); |
| 1676 | for (const timer of waiting.values()) clearTimeout(timer); |
| 1677 | waiting.clear(); |
| 1678 | offers.clear(); |
| 1679 | glances.clear(); |
| 1680 | waits.clear(); |
| 1681 | pinned = true; |
| 1682 | s.messages.forEach(addMessage); |
| 1683 | placeNotice(); |
| 1684 | for (const j of s.jobs || []) { |
| 1685 | addJob(j); |
| 1686 | (j.cards || []).forEach(addCard); |
| 1687 | } |
| 1688 | s.cards.forEach(addCard); |
| 1689 | // Home may have drawn the chat unread, saying nothing of it. |
| 1690 | empty.hidden = thread.children.length > 0; |
| 1691 | if (viewing && !item("data-job", viewing)) closeView(false); |
| 1692 | else if (focused) item("data-job", viewing).querySelector("[data-job-close]").focus({ preventScroll: true }); |
| 1693 | setTurn(s.turn, s.status); |
| 1694 | toBottom(); |
| 1695 | listen(s.cursor); |
| 1696 | } |
| 1697 | |
| 1698 | // Each form's request in flight or of unknown outcome: its key, and the |
| 1699 | // body it was made for. A form is sent once at a time; a retry of the |
| 1700 | // same body (after a lost answer, or Equipo not answering) reuses the |
| 1701 | // key, so Equipo does the work once. A known outcome forgets it. |
| 1702 | const sending = new WeakMap(); |
| 1703 | |
| 1704 | // post sends a form by fetch and returns its JSON, or null when it was |
| 1705 | // already on its way or failed (and the panel says so; quiet: the caller |
| 1706 | // says a failure to try again itself, not the status line). |
| 1707 | // lastStatus is the HTTP status of the latest post that got an answer, |
| 1708 | // lastState the state it answered with. |
| 1709 | // lastFiles is what it said of a send's files: "unavailable" or "stale" |
| 1710 | // (the chips say so), else "". A list in extra goes as one field per |
| 1711 | // item; a send with files is kept alive if the page goes, so the |
| 1712 | // beacon's leaving its files out (ask-attach.js) never loses it. |
| 1713 | let lastStatus = 0; |
| 1714 | let lastState = ""; |
| 1715 | let lastFiles = ""; |
| 1716 | async function post(form, extra, quiet) { |
| 1717 | lastStatus = 0; |
| 1718 | lastState = ""; |
| 1719 | lastFiles = ""; |
| 1720 | const body = new URLSearchParams(new FormData(form)); |
| 1721 | body.delete("key"); |
| 1722 | for (const [k, v] of Object.entries(extra || {})) { |
| 1723 | if (!Array.isArray(v)) { |
| 1724 | body.set(k, v); |
| 1725 | continue; |
| 1726 | } |
| 1727 | body.delete(k); |
| 1728 | for (const item of v) body.append(k, item); |
| 1729 | } |
| 1730 | const sig = body.toString(); |
| 1731 | let req = sending.get(form); |
| 1732 | if (req && req.busy) return null; |
| 1733 | if (!req || req.sig !== sig) req = { sig, key: key() }; |
| 1734 | req.busy = true; |
| 1735 | sending.set(form, req); |
| 1736 | body.set("key", req.key); |
| 1737 | let known = false; |
| 1738 | try { |
| 1739 | const res = await fetch(form.action, { method: "POST", headers: json, body, keepalive: body.has("attachments") }); |
| 1740 | const out = await res.json(); |
| 1741 | lastStatus = res.status; |
| 1742 | lastState = out.state || ""; |
| 1743 | lastFiles = out.files || ""; |
| 1744 | known = res.status !== 502; |
| 1745 | if (res.ok) { |
| 1746 | // It went through: a runner answers again, so its note goes. |
| 1747 | if (root.dataset.state !== "ready") show("ready"); |
| 1748 | return out; |
| 1749 | } |
| 1750 | // Lost the connection (a 409 saying so; Equipo refusing the key is |
| 1751 | // 409 reconnect, never 401): the panel says what to do. No runner that |
| 1752 | // can answer: the conversation stays, with a note saying so. |
| 1753 | // Otherwise the conversation stays, with a line to try again (a 409 |
| 1754 | // is stale: the next events show how things are). |
| 1755 | if (["connect", "pending", "reconnect", ...runnerless].includes(out.state)) show(out.state); |
| 1756 | else if (res.status !== 409 && !lastFiles && !quiet) status.textContent = "That didn't send. Try again."; |
| 1757 | } catch { |
| 1758 | if (!quiet) status.textContent = "That didn't send. Try again."; |
| 1759 | } finally { |
| 1760 | req.busy = false; |
| 1761 | if (known) sending.delete(form); |
| 1762 | } |
| 1763 | return null; |
| 1764 | } |
| 1765 | |
| 1766 | // Send waits for the chips' uploads, then sends once with their ids in |
| 1767 | // chip order; if one of them didn't take, nothing goes (its chip says |
| 1768 | // why). Files refused at send keep Ask ready: the chips say why |
| 1769 | // (unavailable: the paperclip goes; stale: attach it again), and the |
| 1770 | // words stay in the field. One submit at a time, from the wait to the |
| 1771 | // answer. |
| 1772 | let submitting = false; |
| 1773 | composer.addEventListener("submit", async (e) => { |
| 1774 | e.preventDefault(); |
| 1775 | const withFiles = !!(files && files.count()); |
| 1776 | if ((!field.value.trim() && !withFiles) || submitting) return; |
| 1777 | submitting = true; |
| 1778 | let ids = []; |
| 1779 | let sent = null; |
| 1780 | try { |
| 1781 | if (withFiles) { |
| 1782 | ids = await files.ready(); |
| 1783 | if (ids === null || (!field.value.trim() && !ids.length)) return; |
| 1784 | files.sending(ids, true); |
| 1785 | } |
| 1786 | sent = await post(composer, ids.length ? { attachments: ids } : null); |
| 1787 | } finally { |
| 1788 | // No answer at all (lastStatus 0), or Equipo not answering Base |
| 1789 | // (502): the send may have landed. |
| 1790 | if (ids && ids.length) files.sending(ids, false, sent ? "sent" : lastStatus && lastStatus !== 502 ? "refused" : "unknown"); |
| 1791 | submitting = false; |
| 1792 | } |
| 1793 | if (!sent) { |
| 1794 | if (ids.length && lastFiles) { |
| 1795 | files.refused(lastFiles, ids); |
| 1796 | if (lastFiles === "unavailable") canAttach = false; |
| 1797 | } |
| 1798 | return; |
| 1799 | } |
| 1800 | field.value = ""; |
| 1801 | if (ids.length) files.sent(ids); |
| 1802 | paint(); |
| 1803 | // Sending always goes to the bottom, wherever the person had scrolled. |
| 1804 | pinned = true; |
| 1805 | addMessage(sent.message); |
| 1806 | setTurn(sent.turn); |
| 1807 | toBottom(); |
| 1808 | }); |
| 1809 | // Enter sends; Shift Enter is the field's own new line, and so is Option |
| 1810 | // (Alt) Enter, as in the Mac app, though a browser leaves that one out. |
| 1811 | // An input method's Enter finishes its word: Safari ends the composition |
| 1812 | // before that keydown, so isComposing is already false there and only |
| 1813 | // keyCode 229 tells. |
| 1814 | field.addEventListener("keydown", (e) => { |
| 1815 | if (e.key !== "Enter" || e.isComposing || e.keyCode === 229 || e.shiftKey) return; |
| 1816 | e.preventDefault(); |
| 1817 | if (!e.altKey) composer.requestSubmit(); |
| 1818 | else typeIn("\n"); |
| 1819 | }); |
| 1820 | // A rich paste (a web page, Docs, Mail) comes in as the Markdown the |
| 1821 | // chat draws (pasteMarkdown); a plain one, or one whose HTML carries no |
| 1822 | // formatting, is left to the browser. |
| 1823 | field.addEventListener("paste", (e) => { |
| 1824 | // Files with no words of their own attach (ask-attach.js, paste). |
| 1825 | if (files && files.paste(e)) return; |
| 1826 | const html = e.clipboardData && e.clipboardData.getData("text/html"); |
| 1827 | const md = html ? pasteMarkdown(html) : null; |
| 1828 | if (md === null) return; |
| 1829 | e.preventDefault(); |
| 1830 | typeIn(md); |
| 1831 | }); |
| 1832 | // typeIn puts text in place of the field's selection as typing would, |
| 1833 | // so Undo takes it back. A text of many lines goes in at once instead |
| 1834 | // (insertText grows with the square of the lines: 4,000 take seconds), |
| 1835 | // without Undo, and so does any where insertText isn't offered; the |
| 1836 | // field's limit holds either way. |
| 1837 | function typeIn(text) { |
| 1838 | if (text.split("\n", 301).length <= 300 && document.execCommand("insertText", false, text)) return; |
| 1839 | const start = field.selectionStart, end = field.selectionEnd; |
| 1840 | const room = field.maxLength >= 0 ? field.maxLength - (field.value.length - (end - start)) : text.length; |
| 1841 | field.setRangeText(text.slice(0, Math.max(0, room)), start, end, "end"); |
| 1842 | field.dispatchEvent(new Event("input", { bubbles: true })); |
| 1843 | } |
| 1844 | |
| 1845 | // pasteMarkdown is a clipboard's HTML as the chat's Markdown: bold |
| 1846 | // (**x**), italics (*x*), links ([text](url), http(s) only, as webURL), |
| 1847 | // bullet and numbered lists (nested by indent), headings (# x), and line |
| 1848 | // breaks and paragraphs. Everything else is its text. It is null when the |
| 1849 | // HTML formats nothing, or is mostly code (a monospace font, or pre, |
| 1850 | // code, tt, samp, kbd), so a plain paste or code stays exactly as |
| 1851 | // copied. The HTML is parsed into an inert document (nothing runs or |
| 1852 | // loads) and walked once: elements deeper than 32 are flattened, the |
| 1853 | // walk stops once the Markdown passes the field's 16,000 characters, and |
| 1854 | // more than 2 MB of HTML is left plain. The app's PasteMarkdown does the |
| 1855 | // same (keep them in step: the samples in |
| 1856 | // internal/browsertest/testdata/paste.json check both). |
| 1857 | function pasteMarkdown(html) { |
| 1858 | if (html.length > 2000000) return null; |
| 1859 | const doc = new DOMParser().parseFromString(html, "text/html"); |
| 1860 | const maxDepth = 32, maxOut = 16000; |
| 1861 | const skip = new Set(["SCRIPT", "STYLE", "HEAD", "TITLE", "TEMPLATE", "NOSCRIPT", "IFRAME", "OBJECT", "EMBED", "SVG", "MATH", "CANVAS", "VIDEO", "AUDIO", "PICTURE", "IMG", "BUTTON", "SELECT", "INPUT", "TEXTAREA"]); |
| 1862 | const raw = new Set(["SCRIPT", "STYLE", "TEXTAREA", "TITLE", "TEMPLATE", "NOSCRIPT", "IFRAME"]); |
| 1863 | const lines = new Set(["DIV", "SECTION", "ARTICLE", "HEADER", "FOOTER", "MAIN", "NAV", "ASIDE", "BLOCKQUOTE", "FIGURE", "FIGCAPTION", "ADDRESS", "CENTER", "DETAILS", "SUMMARY", "FORM", "FIELDSET", "TABLE", "THEAD", "TBODY", "TFOOT", "TR", "CAPTION", "DL", "DT", "DD", "HR"]); |
| 1864 | const code = new Set(["CODE", "TT", "SAMP", "KBD"]); |
| 1865 | const blocks = new Set([...lines, "P", "LI", "UL", "OL", "H1", "H2", "H3", "H4", "H5", "H6", "PRE"]); |
| 1866 | const monoFont = /monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console/i; |
| 1867 | // The output, built once: its pieces, its length, and how many line |
| 1868 | // breaks it ends with. |
| 1869 | const out = []; |
| 1870 | // A <pre>'s text, kept out of the clean-up at the end: its spaces and |
| 1871 | // blank lines are the code's. Each stands in the output as NUL, its |
| 1872 | // number, NUL (the parser never leaves a NUL in text). |
| 1873 | const verbatim = []; |
| 1874 | let length = 0, breaks = 0; |
| 1875 | const put = (s) => { |
| 1876 | if (!s) return; |
| 1877 | out.push(s); |
| 1878 | length += s.length; |
| 1879 | const m = /\n*$/.exec(s)[0].length; |
| 1880 | breaks = m === s.length ? breaks + m : m; |
| 1881 | }; |
| 1882 | let runs = [], open = false, marker = null, indent = "", formatted = false, chars = 0, mono = 0; |
| 1883 | const lists = []; |
| 1884 | const flush = () => { |
| 1885 | const s = inline(runs).replace(/^ +/, ""); |
| 1886 | runs = []; |
| 1887 | if (!s) return; |
| 1888 | put(open ? s : (marker !== null ? marker : indent) + s); |
| 1889 | if (!open && marker !== null) formatted = true; |
| 1890 | marker = null; |
| 1891 | open = true; |
| 1892 | }; |
| 1893 | const ensure = (n) => { |
| 1894 | flush(); |
| 1895 | open = false; |
| 1896 | if (!length) return; |
| 1897 | for (let have = breaks; have < n; have++) put("\n"); |
| 1898 | }; |
| 1899 | const lineBreak = () => { |
| 1900 | flush(); |
| 1901 | if (length) { put("\n"); open = false; } |
| 1902 | }; |
| 1903 | // A declaration's value in a style attribute (never mso-bidi-font-weight |
| 1904 | // and the like). |
| 1905 | const declared = (style, name) => { |
| 1906 | const m = new RegExp("(?:^|;)\\s*" + name + "\\s*:\\s*([^;]*)", "i").exec(style); |
| 1907 | return m ? m[1].replace(/!\s*important\s*$/i, "").trim() : null; |
| 1908 | }; |
| 1909 | const walk = (node, st, depth) => { |
| 1910 | if (length > maxOut) return; |
| 1911 | if (node.nodeType === 3) { |
| 1912 | const counted = node.data.replace(/\s+/g, "").length; |
| 1913 | chars += counted; |
| 1914 | if (st.mono) mono += counted; |
| 1915 | let t = node.data.replace(/[ \t\n\r\f\u00a0]+/g, " "); |
| 1916 | // One space between words, whichever side of a tag it was. |
| 1917 | if (t[0] === " " && runs.length && runs[runs.length - 1].text.endsWith(" ")) t = t.slice(1); |
| 1918 | if (t) runs.push({ text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href }); |
| 1919 | return; |
| 1920 | } |
| 1921 | if (node.nodeType !== 1) return; |
| 1922 | const tag = node.tagName.toUpperCase(); |
| 1923 | if (tag === "BR") return lineBreak(); |
| 1924 | if (skip.has(tag)) return; |
| 1925 | // Too deep: its text, a block a line of its own and a cell a space, |
| 1926 | // as the app's tree has it. |
| 1927 | if (depth >= maxDepth) { |
| 1928 | const block = blocks.has(tag); |
| 1929 | if (block) ensure(1); |
| 1930 | for (const c of node.childNodes) walk(c, st, depth); |
| 1931 | if (block) ensure(1); |
| 1932 | if (tag === "TD" || tag === "TH") runs.push({ text: " ", bold: false, italic: false, href: "" }); |
| 1933 | return; |
| 1934 | } |
| 1935 | const next = { ...st }; |
| 1936 | if (tag === "B" || tag === "STRONG") next.bold = true; |
| 1937 | if (tag === "I" || tag === "EM") next.italic = true; |
| 1938 | if (code.has(tag)) next.mono = true; |
| 1939 | const style = node.getAttribute("style") || ""; |
| 1940 | const weight = declared(style, "font-weight"); |
| 1941 | if (weight !== null) next.bold = /^(bold|bolder|[6-9]00)$/i.test(weight); |
| 1942 | const slant = declared(style, "font-style"); |
| 1943 | if (slant !== null) next.italic = /^(italic|oblique)/i.test(slant); |
| 1944 | const family = declared(style, "font-family"); |
| 1945 | if (family !== null) next.mono = monoFont.test(family); |
| 1946 | if (tag === "A" && !st.href) next.href = webURL((node.getAttribute("href") || "").trim()); |
| 1947 | const children = () => { for (const c of node.childNodes) walk(c, next, depth + 1); }; |
| 1948 | const level = /^H([1-6])$/.exec(tag); |
| 1949 | if (level) { |
| 1950 | ensure(2); |
| 1951 | marker = "#".repeat(Number(level[1])) + " "; |
| 1952 | next.heading = true; |
| 1953 | const before = formatted; |
| 1954 | children(); |
| 1955 | flush(); |
| 1956 | if (marker !== null) { marker = null; formatted = before; } |
| 1957 | ensure(2); |
| 1958 | return; |
| 1959 | } |
| 1960 | if (tag === "UL" || tag === "OL") { |
| 1961 | const top = lists.length === 0; |
| 1962 | const parent = lists[lists.length - 1]; |
| 1963 | ensure(top ? 2 : 1); |
| 1964 | const start = parseInt(node.getAttribute("start"), 10); |
| 1965 | lists.push({ ordered: tag === "OL", n: Number.isNaN(start) ? 1 : Math.max(0, start), |
| 1966 | indent: parent ? parent.inner : indent, inner: parent ? parent.inner : indent }); |
| 1967 | const saved = indent; |
| 1968 | children(); |
| 1969 | lists.pop(); |
| 1970 | indent = saved; |
| 1971 | ensure(top ? 2 : 1); |
| 1972 | return; |
| 1973 | } |
| 1974 | if (tag === "LI") { |
| 1975 | ensure(1); |
| 1976 | const list = lists[lists.length - 1] || { ordered: false, n: 0, indent: "", inner: "" }; |
| 1977 | const m = list.ordered ? list.n++ + ". " : "- "; |
| 1978 | marker = list.indent + m; |
| 1979 | list.inner = list.indent + " ".repeat(m.length); |
| 1980 | const saved = indent; |
| 1981 | indent = list.inner; |
| 1982 | children(); |
| 1983 | flush(); |
| 1984 | marker = null; |
| 1985 | indent = saved; |
| 1986 | ensure(1); |
| 1987 | return; |
| 1988 | } |
| 1989 | if (tag === "P") { |
| 1990 | if (lists.length) { |
| 1991 | flush(); |
| 1992 | if (open) { put("\n"); open = false; } |
| 1993 | children(); |
| 1994 | return; |
| 1995 | } |
| 1996 | ensure(2); |
| 1997 | children(); |
| 1998 | ensure(2); |
| 1999 | return; |
| 2000 | } |
| 2001 | if (tag === "PRE") { |
| 2002 | // Verbatim, as a fenced code block longer than any run of |
| 2003 | // backticks in it. |
| 2004 | let code = ""; |
| 2005 | const read = (n) => { |
| 2006 | if (n.nodeType === 3) code += n.data; |
| 2007 | else if (n.nodeType === 1 && n.tagName.toUpperCase() === "BR") code += "\n"; |
| 2008 | else if (n.nodeType === 1 && !skip.has(n.tagName.toUpperCase())) for (const c of n.childNodes) read(c); |
| 2009 | }; |
| 2010 | read(node); |
| 2011 | code = code.replace(/\r\n?/g, "\n").replace(/\n$/, ""); |
| 2012 | const counted = code.replace(/\s+/g, "").length; |
| 2013 | chars += counted; |
| 2014 | mono += counted; |
| 2015 | if (!code.trim()) return; |
| 2016 | const fence = "`".repeat(Math.max(3, ...(code.match(/`+/g) || []).map((r) => r.length + 1))); |
| 2017 | ensure(2); |
| 2018 | put(fence + "\n\0" + verbatim.length + "\0\n" + fence); |
| 2019 | verbatim.push(code); |
| 2020 | formatted = true; |
| 2021 | ensure(2); |
| 2022 | return; |
| 2023 | } |
| 2024 | if (lines.has(tag)) { |
| 2025 | ensure(1); |
| 2026 | children(); |
| 2027 | ensure(1); |
| 2028 | return; |
| 2029 | } |
| 2030 | if (tag === "TD" || tag === "TH") { |
| 2031 | children(); |
| 2032 | runs.push({ text: " ", bold: false, italic: false, href: "" }); |
| 2033 | return; |
| 2034 | } |
| 2035 | children(); |
| 2036 | }; |
| 2037 | // inline is a line's runs as Markdown: neighbours alike are one run, |
| 2038 | // and a run's outer spaces stand outside its marks. A label the chat |
| 2039 | // can't draw as a link (over 300 characters) is text with its address. |
| 2040 | const inline = (rs) => { |
| 2041 | const merged = []; |
| 2042 | for (const r of rs) { |
| 2043 | const last = merged[merged.length - 1]; |
| 2044 | if (last && last.href === r.href && (r.href || (last.bold === r.bold && last.italic === r.italic))) last.text += r.text; |
| 2045 | else merged.push({ ...r }); |
| 2046 | } |
| 2047 | let s = ""; |
| 2048 | for (const r of merged) { |
| 2049 | const lead = /^ */.exec(r.text)[0], trail = / *$/.exec(r.text)[0]; |
| 2050 | const core = r.text.slice(lead.length, r.text.length - trail.length); |
| 2051 | if (!core) { s += r.text; continue; } |
| 2052 | if (r.href) { |
| 2053 | const label = core.replace(/[\[\]]/g, ""); |
| 2054 | const href = r.href.replace(/\(/g, "%28").replace(/\)/g, "%29"); |
| 2055 | s += lead + (label === r.href ? href : label.length > 300 ? label + " (" + href + ")" : "[" + label + "](" + href + ")") + trail; |
| 2056 | formatted = true; |
| 2057 | } else if (r.bold || r.italic) { |
| 2058 | const mark = r.bold ? "**" : "*"; |
| 2059 | s += lead + mark + core + mark + trail; |
| 2060 | formatted = true; |
| 2061 | } else { |
| 2062 | s += r.text; |
| 2063 | } |
| 2064 | } |
| 2065 | return s.replace(/ +$/, ""); |
| 2066 | }; |
| 2067 | // The body is depth -1: 32 levels under it are kept, as in the app. |
| 2068 | walk(doc.body, { bold: false, italic: false, href: "", heading: false, mono: false }, -1); |
| 2069 | flush(); |
| 2070 | if (!formatted || mono * 2 > chars) return null; |
| 2071 | return out.join("").split("\n").map((l) => l.replace(/[ \t]+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\n+$/g, "") |
| 2072 | .replace(/\0(\d+)\0/g, (_, n) => verbatim[Number(n)]); |
| 2073 | } |
| 2074 | |
| 2075 | cancel.addEventListener("submit", (e) => { |
| 2076 | e.preventDefault(); |
| 2077 | post(cancel); |
| 2078 | }); |
| 2079 | thread.addEventListener("submit", async (e) => { |
| 2080 | e.preventDefault(); |
| 2081 | const form = e.target; |
| 2082 | if (form.matches("form.jv-act")) { |
| 2083 | carryOnNow(form); |
| 2084 | return; |
| 2085 | } |
| 2086 | const choice = e.submitter && e.submitter.value; |
| 2087 | if (!choice) return; |
| 2088 | for (const b of form.querySelectorAll("button")) b.disabled = true; |
| 2089 | const out = await post(form, { choice }); |
| 2090 | if (!out && runnerless.includes(lastState)) { |
| 2091 | // Nothing was answered: the card stays open for when a runner can. |
| 2092 | for (const b of form.querySelectorAll("button")) b.disabled = false; |
| 2093 | return; |
| 2094 | } |
| 2095 | if (!out && lastStatus === 409 && lastState === "ready") { |
| 2096 | // The card moved on (a new revision, or answered elsewhere): read the |
| 2097 | // conversation afresh and let the person choose again. Never resend. |
| 2098 | await load(); |
| 2099 | return; |
| 2100 | } |
| 2101 | if (!out) { |
| 2102 | for (const b of form.querySelectorAll("button")) b.disabled = false; |
| 2103 | return; |
| 2104 | } |
| 2105 | addCard(out.card); |
| 2106 | // An outcome card's answer starts no turn: no message, nothing to wait |
| 2107 | // for (both are null). |
| 2108 | if (out.message) addMessage(out.message); |
| 2109 | if (out.turn) setTurn(out.turn); |
| 2110 | }); |
| 2111 | |
| 2112 | // Carry on now: once, with post's kept key (a retry after a lost answer |
| 2113 | // is the same request). The answer is the job card, redrawn in place; |
| 2114 | // a 409 (the card moved on, or no longer offers it, or is gone) or an |
| 2115 | // answer with no card reads the conversation afresh. Never resent by |
| 2116 | // itself. A failure to try again says so once, in the view's live |
| 2117 | // region (jv-error), never also on the status line, so a screen reader |
| 2118 | // hears it once. |
| 2119 | async function carryOnNow(form) { |
| 2120 | const b = form.querySelector("button"); |
| 2121 | const error = form.querySelector(".jv-error"); |
| 2122 | if (b.disabled) return; |
| 2123 | b.disabled = true; |
| 2124 | error.textContent = ""; |
| 2125 | const out = await post(form, {}, true); |
| 2126 | if ((!out && lastStatus === 409 && lastState === "ready") || (out && !out.card)) { |
| 2127 | await load(); |
| 2128 | return; |
| 2129 | } |
| 2130 | if (out) { |
| 2131 | addJob(out.card); |
| 2132 | return; |
| 2133 | } |
| 2134 | b.disabled = false; |
| 2135 | if (!runnerless.includes(lastState) && !["connect", "pending", "reconnect"].includes(lastState)) { |
| 2136 | error.textContent = "That didn't send. Try again."; |
| 2137 | } |
| 2138 | } |
| 2139 | |
| 2140 | // On a wide screen the field is ready when the page opens: only with the |
| 2141 | // chat open and ready, never on a phone (it would raise the keyboard), and |
| 2142 | // never over focus the person already has or a link's target (#...). |
| 2143 | const target = location.hash; |
| 2144 | function focusOnLoad() { |
| 2145 | if (phone.matches || (dock && !isOpen()) || !chatting(root.dataset.state) || field.disabled) return; |
| 2146 | if (target && target !== "#ask") return; |
| 2147 | const at = document.activeElement; |
| 2148 | if (at && at !== document.body && at !== document.documentElement) return; |
| 2149 | field.focus({ preventScroll: true }); |
| 2150 | } |
| 2151 | |
| 2152 | if (!dock) { |
| 2153 | load(); |
| 2154 | focusOnLoad(); |
| 2155 | return; |
| 2156 | } |
| 2157 | |
| 2158 | // Docked beside Home. A wide screen opens with the chat docked, unless the |
| 2159 | // member closed it there (<html class="desk-closed">, drawn by the server |
| 2160 | // and kept by /ask/dock); a phone opens on the springboard, and the chat |
| 2161 | // comes up full screen over it (phone-open), not remembered. Each keeps |
| 2162 | // its own state, so crossing 640px never strands the chat. |
| 2163 | const html = document.documentElement; |
| 2164 | const home = document.getElementById("home"); |
| 2165 | const bar = document.querySelector(".shell > .topbar"); |
| 2166 | const slot = document.querySelector(".ask-slot"); |
| 2167 | function isOpen() { |
| 2168 | return phone.matches ? html.classList.contains("phone-open") : !html.classList.contains("desk-closed"); |
| 2169 | } |
| 2170 | // What is out of sight is out of reach: the chat while closed, the |
| 2171 | // greeting's field while docked open, and Home behind the chat on a phone. |
| 2172 | // The conversation is read afresh and followed while the chat is open. |
| 2173 | let shown = false; |
| 2174 | function sync() { |
| 2175 | const open = isOpen(); |
| 2176 | // The job view goes with the chat, however it closes (its X, Escape, |
| 2177 | // a screen narrowed past a phone's width). |
| 2178 | if (!open && viewing) closeView(false); |
| 2179 | dock.inert = !open; |
| 2180 | if (slot) slot.inert = open && !phone.matches; |
| 2181 | if (home) home.inert = open && phone.matches; |
| 2182 | if (bar) bar.inert = open && phone.matches; |
| 2183 | for (const o of openers) o.setAttribute("aria-expanded", String(open)); |
| 2184 | if (open !== shown) { |
| 2185 | shown = open; |
| 2186 | if (open) { |
| 2187 | // The conversation Home drew shows its newest line at once; the |
| 2188 | // fresh read follows. |
| 2189 | toBottom(); |
| 2190 | load(); |
| 2191 | } else quiet(); |
| 2192 | } |
| 2193 | } |
| 2194 | // The first thing to reach in the chat: the composer, or the visible |
| 2195 | // note's button. |
| 2196 | function first() { |
| 2197 | return chatting(root.dataset.state) ? field : root.querySelector("[data-when]:not([hidden]) .btn"); |
| 2198 | } |
| 2199 | // A wide screen's choice is kept for the member's next visit; the screen |
| 2200 | // has already moved. One save at a time, and the last choice wins: what |
| 2201 | // is pressed while one is on its way waits, and only the latest is sent. |
| 2202 | // A save that fails leaves the screen as the person chose it, quietly; |
| 2203 | // nothing counts as kept, so a choice made meanwhile, or the next press, |
| 2204 | // is sent. |
| 2205 | let wanted = !html.classList.contains("desk-closed"); |
| 2206 | let kept = wanted; // what the server holds; null when a save failed |
| 2207 | let presses = 0; |
| 2208 | let saving = false; |
| 2209 | function remember(open) { |
| 2210 | wanted = open; |
| 2211 | presses++; |
| 2212 | save(); |
| 2213 | } |
| 2214 | async function save() { |
| 2215 | if (saving) return; |
| 2216 | saving = true; |
| 2217 | while (wanted !== kept) { |
| 2218 | const open = wanted, at = presses; |
| 2219 | let ok = false; |
| 2220 | try { |
| 2221 | const res = await fetch("/ask/dock", { method: "POST", headers: json, body: new URLSearchParams({ open: open ? "1" : "0" }) }); |
| 2222 | ok = res.ok; |
| 2223 | } catch {} |
| 2224 | kept = ok ? open : null; |
| 2225 | if (!ok && presses === at) break; |
| 2226 | } |
| 2227 | saving = false; |
| 2228 | } |
| 2229 | function setOpen(open) { |
| 2230 | if (phone.matches) { |
| 2231 | html.classList.toggle("phone-open", open); |
| 2232 | if (open) fit(); |
| 2233 | } else { |
| 2234 | html.classList.toggle("desk-closed", !open); |
| 2235 | remember(open); |
| 2236 | } |
| 2237 | sync(); |
| 2238 | if (open) { |
| 2239 | const f = first(); |
| 2240 | if (f) f.focus({ preventScroll: true }); |
| 2241 | return; |
| 2242 | } |
| 2243 | // Focus goes back to whichever opener shows: on a wide screen the Base |
| 2244 | // button, which appears as the chat leaves. |
| 2245 | const back = phone.matches && opener.checkVisibility() ? opener : [...openers].find((o) => o.checkVisibility({ visibilityProperty: true })) || openers[0]; |
| 2246 | if (back) back.focus({ preventScroll: true }); |
| 2247 | } |
| 2248 | // On a phone the openers are links to /ask, which works without scripts. |
| 2249 | for (const a of document.querySelectorAll("a[data-ask-open]")) { |
| 2250 | a.addEventListener("click", (e) => { |
| 2251 | e.preventDefault(); |
| 2252 | opener = a; |
| 2253 | setOpen(true); |
| 2254 | }); |
| 2255 | } |
| 2256 | for (const form of document.querySelectorAll('form[action="/ask/dock"]')) { |
| 2257 | form.addEventListener("submit", (e) => { |
| 2258 | e.preventDefault(); |
| 2259 | const open = form.elements.open.value === "1"; |
| 2260 | if (open) opener = e.submitter || form.querySelector("button"); |
| 2261 | setOpen(open); |
| 2262 | }); |
| 2263 | } |
| 2264 | document.addEventListener("keydown", (e) => { |
| 2265 | if (e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return; |
| 2266 | const el = document.activeElement; |
| 2267 | if (e.key === "Escape" && isOpen() && dock.contains(el)) { |
| 2268 | setOpen(false); |
| 2269 | return; |
| 2270 | } |
| 2271 | // "/" reaches the chat from anywhere but a field: it opens it, or |
| 2272 | // puts focus in the composer. |
| 2273 | const typing = el && (el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)); |
| 2274 | if (e.key !== "/" || typing) return; |
| 2275 | e.preventDefault(); |
| 2276 | if (!isOpen()) { |
| 2277 | opener = [...openers].find((o) => o.checkVisibility({ visibilityProperty: true })) || openers[0]; |
| 2278 | setOpen(true); |
| 2279 | return; |
| 2280 | } |
| 2281 | const f = first(); |
| 2282 | if (f) f.focus({ preventScroll: true }); |
| 2283 | }); |
| 2284 | phone.addEventListener("change", sync); |
| 2285 | |
| 2286 | // On a phone the chat follows the visual viewport, which shrinks when the |
| 2287 | // keyboard opens: the composer stays above it. |
| 2288 | const vv = window.visualViewport; |
| 2289 | function fit() { |
| 2290 | if (!vv) return; |
| 2291 | dock.style.setProperty("--vv-h", vv.height + "px"); |
| 2292 | dock.style.setProperty("--vv-top", vv.offsetTop + "px"); |
| 2293 | } |
| 2294 | if (vv) { |
| 2295 | vv.addEventListener("resize", () => { if (phone.matches && isOpen()) fit(); }); |
| 2296 | vv.addEventListener("scroll", () => { if (phone.matches && isOpen()) fit(); }); |
| 2297 | } |
| 2298 | |
| 2299 | // Back from setting up Ask Base on Home (/#ask): the chat open. |
| 2300 | if (location.hash === "#ask") { |
| 2301 | history.replaceState(null, "", location.pathname + location.search); |
| 2302 | if (!isOpen()) setOpen(true); |
| 2303 | } |
| 2304 | sync(); |
| 2305 | focusOnLoad(); |
| 2306 | } |
| 2307 | |