chirkle 0.3.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -47
- package/bin/release/darwin-amd64/chirkle-server +4 -0
- package/bin/release/darwin-arm64/chirkle-server +0 -0
- package/bin/release/linux-amd64/chirkle-server +0 -0
- package/bin/release/linux-arm64/chirkle-server +0 -0
- package/package.json +9 -6
- package/pb_hooks/federation/inbox.js +2 -69
- package/pb_hooks/federation/messages.js +5 -3
- package/pb_hooks/federation/net.js +1 -0
- package/pb_hooks/federation/people.js +1 -0
- package/pb_hooks/federation.pb.js +1 -8
- package/pb_hooks/lib/access.js +33 -10
- package/pb_hooks/lib/account.js +542 -6
- package/pb_hooks/lib/anonymous.js +2 -129
- package/pb_hooks/lib/bulk.js +1 -2
- package/pb_hooks/lib/collections.js +4 -4
- package/pb_hooks/lib/dms.js +1 -1
- package/pb_hooks/lib/files.js +82 -120
- package/pb_hooks/lib/handles.js +2 -2
- package/pb_hooks/lib/inbox.js +40 -54
- package/pb_hooks/lib/invites.js +266 -0
- package/pb_hooks/lib/media.js +5 -43
- package/pb_hooks/lib/messages.js +72 -117
- package/pb_hooks/lib/moderation.js +2 -16
- package/pb_hooks/lib/reactions.js +28 -4
- package/pb_hooks/lib/retention.js +88 -0
- package/pb_hooks/lib/site.js +13 -2
- package/pb_hooks/lib/stats.js +6 -34
- package/pb_hooks/lib/users.js +88 -7
- package/pb_hooks/lib/worker.js +22 -1
- package/pb_hooks/main.pb.js +85 -94
- package/pb_hooks/telegram/api.js +64 -12
- package/pb_hooks/telegram/inbound.js +158 -31
- package/pb_hooks/telegram/links.js +4 -3
- package/pb_hooks/telegram/outbound.js +86 -45
- package/pb_hooks/telegram/people.js +3 -3
- package/pb_hooks/telegram/worker.js +59 -15
- package/pb_migrations/1760000045_password_reset.js +38 -0
- package/pb_migrations/1760000047_telegram_supergroup_ids.js +51 -0
- package/pb_migrations/1760000048_inbox_reactions_merged.js +24 -0
- package/pb_migrations/1760000049_inbox_room_index.js +22 -0
- package/pb_migrations/1760000050_messages_unread_index.js +22 -0
- package/pb_migrations/1760000051_users_kind.js +31 -0
- package/pb_migrations/1760000052_deleted_accounts.js +19 -0
- package/pb_migrations/1760000053_account_jobs.js +45 -0
- package/pb_migrations/1760000054_room_invites.js +39 -0
- package/pb_migrations/1760000055_invite_barred.js +16 -0
- package/pb_migrations/1760000056_telegram_fetch.js +21 -0
- package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
- package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
- package/pb_public/assets/access-UK3L54NR.js +2 -0
- package/pb_public/assets/access-UK3L54NR.js.map +7 -0
- package/pb_public/assets/account-CT2BVMAX.css +2 -0
- package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
- package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
- package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
- package/pb_public/assets/app-HB3NZHQ2.js +3 -0
- package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
- package/pb_public/assets/app-XJ73EU5O.css +2 -0
- package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
- package/pb_public/assets/chunk-56ACD3V5.js +2 -0
- package/pb_public/assets/chunk-56ACD3V5.js.map +7 -0
- package/pb_public/assets/chunk-AG73QNUN.js +2 -0
- package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
- package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
- package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
- package/pb_public/assets/chunk-DZC4SY4M.js +2 -0
- package/pb_public/assets/chunk-DZC4SY4M.js.map +7 -0
- package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
- package/pb_public/assets/chunk-N2OFGBCZ.js.map +7 -0
- package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
- package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
- package/pb_public/assets/chunk-RPCBA7VF.js +2 -0
- package/pb_public/assets/chunk-RPCBA7VF.js.map +7 -0
- package/pb_public/assets/chunk-UZDXAORM.js +2 -0
- package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
- package/pb_public/assets/chunk-VTOUI25E.js +4 -0
- package/pb_public/assets/chunk-VTOUI25E.js.map +7 -0
- package/pb_public/assets/chunk-WR25F7FU.js +2 -0
- package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
- package/pb_public/assets/{emoji-VA2WCEAC.css → emoji-WWNPWCF3.css} +2 -2
- package/pb_public/assets/{emoji-VA2WCEAC.css.map → emoji-WWNPWCF3.css.map} +2 -2
- package/pb_public/assets/{emoji-picker-65VVVGYW.js → emoji-picker-K6JTK2GV.js} +4 -4
- package/pb_public/assets/emoji-picker-K6JTK2GV.js.map +7 -0
- package/pb_public/assets/forward-267HRNPY.js +2 -0
- package/pb_public/assets/forward-267HRNPY.js.map +7 -0
- package/pb_public/assets/inbox-CLMYESNI.js +2 -0
- package/pb_public/assets/inbox-CLMYESNI.js.map +7 -0
- package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
- package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
- package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
- package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
- package/pb_public/assets/lazy-H3KIJVB5.js +2 -0
- package/pb_public/assets/lazy-H3KIJVB5.js.map +7 -0
- package/pb_public/assets/login-TK6K4WGB.js +2 -0
- package/pb_public/assets/login-TK6K4WGB.js.map +7 -0
- package/pb_public/assets/media-WZ4653L5.js +2 -0
- package/pb_public/assets/media-WZ4653L5.js.map +7 -0
- package/pb_public/assets/mention-suggest-ODJD2IC5.js +2 -0
- package/pb_public/assets/mention-suggest-ODJD2IC5.js.map +7 -0
- package/pb_public/assets/notify-EPDM772N.js +2 -0
- package/pb_public/assets/notify-EPDM772N.js.map +7 -0
- package/pb_public/assets/profile-3R6S5QYS.js +2 -0
- package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
- package/pb_public/assets/search-WCHOGAJQ.js +2 -0
- package/pb_public/assets/search-WCHOGAJQ.js.map +7 -0
- package/pb_public/assets/stats-GTO2H6PG.js +2 -0
- package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
- package/pb_public/assets/switcher-TFSO45KV.js +2 -0
- package/pb_public/assets/switcher-TFSO45KV.js.map +7 -0
- package/pb_public/assets/user-search-3HQOCQWL.js +2 -0
- package/pb_public/assets/user-search-3HQOCQWL.js.map +7 -0
- package/pb_public/assets/viewer-2Y5FJBW4.js +2 -0
- package/pb_public/assets/viewer-2Y5FJBW4.js.map +7 -0
- package/pb_public/index.html +10 -2
- package/pb_public/stats.html +1 -1
- package/scripts/service.mjs +201 -0
- package/scripts/start.mjs +21 -17
- package/pb_hooks/lib/enrich.js +0 -75
- package/pb_hooks/lib/lists.js +0 -179
- package/pb_hooks/lib/live.js +0 -137
- package/pb_hooks/lib/reads.js +0 -183
- package/pb_public/assets/access-GUDTDXIP.js +0 -2
- package/pb_public/assets/access-GUDTDXIP.js.map +0 -7
- package/pb_public/assets/app-3WX5JYL2.js +0 -3
- package/pb_public/assets/app-3WX5JYL2.js.map +0 -7
- package/pb_public/assets/app-WAFKVN2H.css +0 -2
- package/pb_public/assets/app-WAFKVN2H.css.map +0 -7
- package/pb_public/assets/emoji-picker-65VVVGYW.js.map +0 -7
- package/pb_public/assets/forward-66PELNWT.js +0 -2
- package/pb_public/assets/forward-66PELNWT.js.map +0 -7
- package/pb_public/assets/inbox-TZJWPRTG.js +0 -2
- package/pb_public/assets/inbox-TZJWPRTG.js.map +0 -7
- package/pb_public/assets/lazy-4CXRBHHM.js +0 -2
- package/pb_public/assets/lazy-4CXRBHHM.js.map +0 -7
- package/pb_public/assets/login-G7Y44CJ7.js +0 -2
- package/pb_public/assets/login-G7Y44CJ7.js.map +0 -7
- package/pb_public/assets/media-FPRU2QH5.js +0 -2
- package/pb_public/assets/media-FPRU2QH5.js.map +0 -7
- package/pb_public/assets/mention-suggest-R7MXUH6R.js +0 -2
- package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +0 -7
- package/pb_public/assets/notify-RQ6ZLR46.js +0 -2
- package/pb_public/assets/notify-RQ6ZLR46.js.map +0 -7
- package/pb_public/assets/profile-2CNVT2KX.js +0 -2
- package/pb_public/assets/profile-2CNVT2KX.js.map +0 -7
- package/pb_public/assets/search-3UT4HMES.js +0 -2
- package/pb_public/assets/search-3UT4HMES.js.map +0 -7
- package/pb_public/assets/stats-JX52AQCO.js +0 -2
- package/pb_public/assets/stats-JX52AQCO.js.map +0 -7
- package/pb_public/assets/switcher-CEUKRLEY.js +0 -2
- package/pb_public/assets/switcher-CEUKRLEY.js.map +0 -7
- package/pb_public/assets/user-search-7GNEIXMN.js +0 -2
- package/pb_public/assets/user-search-7GNEIXMN.js.map +0 -7
- package/pb_public/assets/viewer-DXT7SKOU.js +0 -2
- package/pb_public/assets/viewer-DXT7SKOU.js.map +0 -7
- package/scripts/fetch-pocketbase.sh +0 -63
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../web/src/actions.ts", "../../web/src/cache.ts", "../../web/src/collections.ts", "../../web/src/drafts.ts", "../../web/src/favicon.ts", "../../web/src/lazy.ts", "../../web/src/lib/messages.ts", "../../web/src/prefetch.ts", "../../web/src/renewal.ts", "../../web/src/router.ts", "../../web/src/site.ts", "../../web/src/sync.ts", "../../web/src/unread.ts", "../../web/src/update.ts", "../../web/src/views/collection.ts", "../../web/src/views/home.ts", "../../web/src/lib/scroll.ts", "../../web/src/strings/room.ts", "../../web/src/ui/loadbar.ts", "../../web/src/views/room/badges.ts", "../../web/src/ui/icon.ts", "../../web/src/ui/menu.ts", "../../web/src/views/room/composer.ts", "../../web/src/lib/id.ts", "../../web/src/strings/lib-reactions.ts", "../../web/src/lib/reactions.ts", "../../web/src/views/room/writes.ts", "../../web/src/views/room/controller.ts", "../../web/src/views/room/footer.ts", "../../web/src/views/room/gallery.ts", "../../web/src/views/room/header.ts", "../../web/src/lib/links.ts", "../../web/src/lib/mentions.ts", "../../web/src/strings/room-messages.ts", "../../web/src/strings/room-attachments.ts", "../../web/src/views/room/attachments.ts", "../../web/src/views/room/reactions.ts", "../../web/src/views/room/messages.ts", "../../web/src/views/room/names.ts", "../../web/src/views/room/notice.ts", "../../web/src/views/room/parking.ts", "../../web/src/views/room/pickers.ts", "../../web/src/views/room/reading.ts", "../../web/src/views/room/reply.ts", "../../web/src/views/room/selection.ts", "../../web/src/views/room.ts", "../../web/src/strings/rooms.ts", "../../web/src/views/rooms.ts", "../../web/src/app.ts", "../../web/src/main.ts"],
|
|
4
|
+
"sourcesContent": ["// Room commands shared by the room list and the room header: call the server, then update the store.\n// They reject with ApiError; showing the failure is up to the caller.\n\nimport type { Api } from \"./api.ts\";\nimport type { Posting, Room, Visibility } from \"./lib/types.ts\";\nimport { type AppState, markHidden, type Store, unmarkHidden, unmarkHiddenRoom, upsertRoom } from \"./store.ts\";\n\nexport interface RoomActions {\n create(name: string, visibility?: Visibility): Promise<Room>;\n hide(roomId: string): Promise<void>;\n unhide(roomId: string): Promise<void>;\n setArchived(roomId: string, archived: boolean): Promise<void>;\n /** Change who can see the room (\u00A723.2), and with `posting` who can post in it (\u00A723.6); creator only. */\n setAccess(\n roomId: string,\n visibility: Visibility,\n members: readonly string[],\n posting?: Posting,\n writers?: readonly string[],\n ): Promise<void>;\n /** Open (or reopen) the DM with `userId` (\u00A716.2). Resolves to the room, now in the store. */\n openDm(userId: string): Promise<Room>;\n}\n\nexport function createRoomActions({ api, store }: { api: Api; store: Store<AppState> }): RoomActions {\n return {\n async create(name, visibility) {\n const room = await api.createRoom(name, visibility);\n store.set(upsertRoom(room));\n return room;\n },\n async hide(roomId) {\n const row = await api.hideRoom(roomId);\n store.set(markHidden(roomId, row.id));\n },\n async unhide(roomId) {\n const rowId = store.get().hidden.get(roomId);\n if (!rowId) return;\n await api.unhideRoom(rowId);\n store.set(unmarkHidden(rowId));\n },\n async setArchived(roomId, archived) {\n store.set(upsertRoom(await api.setArchived(roomId, archived)));\n },\n async setAccess(roomId, visibility, members, posting, writers) {\n store.set(upsertRoom(await api.setAccess(roomId, visibility, members, posting, writers)));\n },\n async openDm(userId) {\n // Already open: no request (the route is rate limited per IP, which a whole office may share; QA BUG-30).\n const { rooms, hidden, user } = store.get();\n for (const r of rooms.values()) {\n if (r.kind === \"dm\" && r.members?.includes(userId) && r.members.includes(user?.id ?? \"\") && !hidden.has(r.id)) return r;\n }\n const room = await api.openDm(userId);\n store.set(upsertRoom(room));\n store.set(unmarkHiddenRoom(room.id));\n return room;\n },\n };\n}\n", "// Each room's latest messages, kept in IndexedDB (\u00A77.5): a room opens at once with what it showed last time, while its\n// first page loads. One user's at a time: cleared when the session ends (a shared computer must not show the next person\n// someone else's rooms), and a room kept for another user is never shown. What was kept is also held in memory while\n// the page is open: switching back to a room shows it in the same task, without waiting for IndexedDB (or showing an\n// empty room for a frame). A convenience, never an error: without IndexedDB (a private window, a browser that\n// refuses it) nothing outlives the page.\n\nimport type { Message, Room } from \"./lib/types.ts\";\nimport type { AppState, Store } from \"./store.ts\";\n\nexport interface Kept {\n items: Message[];\n hasOlder: boolean;\n /** The room itself: after a reload, its header shows before the room list is in. */\n room?: Room | undefined;\n /** Prefetched (prefetch.ts): the room's unread count when the page was asked for. */\n unread?: number | undefined;\n /**\n * The ETag of the latest page these items are (PERF.md \u00A75): asked for with it, an unchanged page comes back without a\n * body. Only where `items` are that page, as the server still has it while the tag stands (the room at its live edge).\n */\n tag?: string | undefined;\n}\n\nexport interface Cache {\n /** The room as `user` (\"\" for a guest) last saw it, if kept. */\n get(user: string, roomId: string): Promise<Kept | undefined>;\n put(user: string, roomId: string, kept: Kept): void;\n /** The room as kept in memory, at once: undefined when it is only in IndexedDB (or not kept). */\n peek(user: string, roomId: string): Kept | undefined;\n /** Forget every room. */\n clear(): void;\n}\n\nconst STORE = \"rooms\";\n\n/** A request's result, once it succeeds. */\nconst done = <T>(req: IDBRequest<T> | IDBOpenDBRequest) =>\n new Promise<T>((resolve, reject) => {\n req.onsuccess = () => resolve(req.result as T);\n req.onerror = () => reject(req.error);\n });\n\nexport function createCache(name = \"chat\"): Cache {\n let db: Promise<IDBDatabase> | undefined;\n let opened: IDBDatabase | undefined;\n /** Opened on first use. Requests run in the order they were made (one connection): a clear is never overtaken. */\n const open = () => {\n if (!db) {\n db = new Promise<IDBDatabase>((resolve) => {\n const req = indexedDB.open(name, 1);\n req.onupgradeneeded = () => req.result.createObjectStore(STORE);\n resolve(done<IDBDatabase>(req));\n }).then((d) => (opened = d));\n }\n return db;\n };\n /** Kept since the page loaded, by room. (Not what was read: a read answered after a clear would bring it back.) */\n const mem = new Map<string, Kept & { user: string }>();\n /**\n * Kept as the page went: IndexedDB may not get to write it before the page is gone (Chromium under load, QA BUG-104),\n * so it is also written here, at once, and moved to IndexedDB by the next page.\n */\n const LEFT = `${name}.left`;\n let leaving = false;\n /** Write (or with nothing, remove) what was kept as the page went. */\n const left = (row?: unknown) => {\n try {\n if (row) localStorage.setItem(LEFT, JSON.stringify(row));\n else localStorage.removeItem(LEFT);\n } catch {}\n };\n // Before the room view's own listener (the cache is made first), which keeps the room.\n addEventListener(\"pagehide\", () => (leaving = true));\n // Back from the back/forward cache: the page lives on, and its writes with it.\n addEventListener(\"pageshow\", () => {\n leaving = false;\n left();\n });\n const go = <T>(d: IDBDatabase, mode: IDBTransactionMode, op: (s: IDBObjectStore) => IDBRequest) => {\n const tx = d.transaction(STORE, mode);\n const result = done<T>(op(tx.objectStore(STORE)));\n tx.commit?.();\n return result;\n };\n /**\n * Once the database is open, the request is made at once: one made as the page goes (`pagehide`) was often\n * lost when it waited for a promise, and is committed at once rather than when the page would next run (QA BUG-104).\n */\n const run = <T>(mode: IDBTransactionMode, op: (s: IDBObjectStore) => IDBRequest): Promise<T | undefined> => {\n try {\n return (opened ? go<T>(opened, mode, op) : open().then((d) => go<T>(d, mode, op))).catch(() => undefined);\n } catch {\n return Promise.resolve(undefined); // the connection was closed (the browser does that, e.g. when storage is cleared)\n }\n };\n try {\n // Nothing left (null) throws here.\n const [roomId, row] = JSON.parse(localStorage.getItem(LEFT) as string) as [string, Kept & { user: string }];\n mem.set(roomId, row);\n void run(\"readwrite\", (s) => s.put(row, roomId));\n } catch {}\n left();\n return {\n async get(user, roomId) {\n const kept = mem.get(roomId) ?? (await run<(Kept & { user: string }) | undefined>(\"readonly\", (s) => s.get(roomId)));\n return kept?.user === user ? kept : undefined;\n },\n peek(user, roomId) {\n const kept = mem.get(roomId);\n return kept?.user === user ? kept : undefined;\n },\n put(user, roomId, kept) {\n const row = { ...kept, user };\n mem.set(roomId, row);\n void run(\"readwrite\", (s) => s.put(row, roomId));\n if (leaving) left([roomId, row]);\n },\n clear() {\n mem.clear();\n left();\n void run(\"readwrite\", (s) => s.clear());\n },\n };\n}\n\n/**\n * Forget the rooms that leave the loaded room list (access lost, \u00A723.4; a room deleted), not only the open one: kept,\n * the next load would show them until the server said no (QA BUG-101). Returns the unsubscribe.\n */\nexport function forgetGone(cache: Cache, store: Store<AppState>): () => void {\n return store.subscribe((s, prev) => {\n if (s.roomsStatus !== \"ready\" || prev.roomsStatus !== \"ready\" || s.user?.id !== prev.user?.id) return;\n for (const id of prev.rooms.keys()) if (!s.rooms.has(id)) cache.put(s.user?.id ?? \"\", id, { items: [], hasOlder: false });\n });\n}\n", "// Media collections (\u00A731): keeps `collections` in the store (yours, and the public ones you follow with how many of\n// their items are new) for as long as someone is logged in, refetched whenever one of them or your subscriptions\n// change (live), and on every reconnect. Views read the store; what changes a collection (the lazy chunk) calls\n// refresh() after.\n\nimport type { Api, Unsubscribe } from \"./api.ts\";\nimport { createScope, type Scope } from \"./scope.ts\";\nimport type { AppState, Store } from \"./store.ts\";\n\nexport interface CollectionsService {\n start(): void;\n stop(): void;\n /** Refetch soon (several calls in a row make one request). */\n refresh(): void;\n /** You have seen the collection up to `at` (its newest item's `created`): its badge goes at once. */\n seen(id: string, at?: string): void;\n}\n\nconst REFRESH_MS = 250;\n\nexport function createCollections({ api, store }: { api: Api; store: Store<AppState> }): CollectionsService {\n let scope: Scope | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n /** The live subscription, for the collections followed when it was made. */\n let live: { key: string; off: Promise<Unsubscribe> } | null = null;\n let issued = 0;\n\n async function load(s: Scope) {\n const seq = ++issued;\n const res = await api.collections(s.signal).catch(() => null);\n if (!res || !s.active || seq !== issued) return;\n store.set({ collections: res });\n follow(s);\n }\n\n /** Listen to your collections and those you follow (again, when they changed). */\n function follow(s: Scope) {\n const ids = store.get().collections?.subs.map((c) => c.id) ?? [];\n const key = ids.join();\n if (live?.key === key) return;\n const old = live?.off;\n if (old) void old.then((off) => off()).catch(() => {});\n const off = api.subscribeCollections(ids, refresh);\n const mine = { key, off };\n live = mine;\n s.sub(off);\n void off.then(\n // A change after the list was read but before the server had the subscription reaches neither (a follow from\n // another device just then, QA BUG-170): read it once more. The same subscription isn't made again, so this ends.\n () => s.active && live === mine && refresh(),\n // Not subscribed: the next load tries again.\n () => {\n if (live === mine) live = null;\n },\n );\n }\n\n function refresh() {\n const s = scope;\n if (!s) return;\n clearTimeout(timer);\n timer = setTimeout(() => void load(s), REFRESH_MS);\n }\n\n return {\n start() {\n if (scope) return;\n const s = createScope();\n scope = s;\n s.defer(() => clearTimeout(timer));\n s.defer(\n api.onConnect((reconnect) => {\n if (reconnect && s.active) void load(s);\n }),\n );\n void load(s);\n },\n stop() {\n scope?.dispose();\n scope = null;\n live = null;\n },\n refresh,\n seen(id, at) {\n const c = store.get().collections;\n if (c?.subs.some((x) => x.id === id && x.new)) {\n store.set({ collections: { ...c, subs: c.subs.map((x) => (x.id === id ? { ...x, new: 0 } : x)) } });\n }\n void api.markSeen(id, at).catch(() => {});\n },\n };\n}\n", "// Unsent composer text (\u00A722.3): kept per user and room in localStorage, so it survives visiting other rooms\n// (QA BUG-50) and reloading the page. One key per room, so tabs writing in different rooms don't overwrite each other.\n// Cleared when the session ends: a shared computer must not show the next person what you were writing.\n\nexport interface Drafts {\n get(roomId: string): string;\n /** Blank text removes the draft. */\n set(roomId: string, text: string): void;\n /** Forget every draft of `userId`. */\n clear(userId: string): void;\n}\n\nconst PREFIX = \"chat.draft.\";\n\n/** `user`: whose drafts these are now (\"\" when nobody is logged in: nothing is kept). */\nexport function createDrafts(user: () => string, storage: Storage | null = safeLocalStorage()): Drafts {\n const key = (roomId: string) => `${PREFIX}${user()}.${roomId}`;\n // Storage can throw (quota, disabled in a private window): drafts are a convenience, never an error.\n const attempt = <T>(fn: (s: Storage) => T, fallback: T): T => {\n try {\n return storage ? fn(storage) : fallback;\n } catch {\n return fallback;\n }\n };\n return {\n get: (roomId) => (user() ? attempt((s) => s.getItem(key(roomId)) ?? \"\", \"\") : \"\"),\n set(roomId, text) {\n if (!user()) return;\n attempt((s) => (text.trim() ? s.setItem(key(roomId), text) : s.removeItem(key(roomId))), undefined);\n },\n clear(userId) {\n if (!userId) return;\n attempt((s) => {\n const mine = `${PREFIX}${userId}.`;\n const keys: string[] = [];\n for (let i = 0; i < s.length; i++) {\n const k = s.key(i);\n if (k?.startsWith(mine)) keys.push(k);\n }\n for (const k of keys) s.removeItem(k);\n }, undefined);\n },\n };\n}\n\nfunction safeLocalStorage(): Storage | null {\n try {\n return globalThis.localStorage ?? null;\n } catch {\n return null;\n }\n}\n", "// Unread badge on the tab (\u00A722.4): the favicon shows how many messages are unread across every room and DM that has\n// a badge in the room list (\u00A718.4), and the title starts with it, e.g. \"(3) #general \u2013 Chirkle\": the open room's name, then\n// the site's title (\u00A724).\n\nimport { roomTitle } from \"./lib/rooms.ts\";\nimport { type AppState, type Store, unreadCount } from \"./store.ts\";\n\n/** Unread messages over every room with a badge. */\nexport function totalUnread(s: AppState): number {\n let n = 0;\n for (const r of s.rooms.values()) n += unreadCount(s, r);\n return n;\n}\n\n/** What the badge says: nothing for 0, \"99+\" past 99. */\nexport const badgeLabel = (n: number): string => (n <= 0 ? \"\" : n > 99 ? \"99+\" : String(n));\n\n/** The app icon, a speech bubble (`web/public/icons/icon.svg`, which `index.html` names too): the favicon as it is. */\nexport const ICON = \"/icons/icon.svg\";\nlet icon: HTMLImageElement | undefined;\n\n/** The icon with a red badge holding `label`, drawn on a canvas: a PNG data: URL. */\nexport async function badgedIcon(label: string): Promise<string> {\n icon ??= Object.assign(new Image(), { src: ICON });\n await icon.decode();\n const c = document.createElement(\"canvas\");\n c.width = c.height = 64;\n const g = c.getContext(\"2d\") as CanvasRenderingContext2D;\n g.scale(2, 2);\n g.drawImage(icon, 0, 0, 32, 32);\n // Wider for more digits; the text is the largest that fits.\n const w = label.length === 1 ? 20 : label.length === 2 ? 26 : 32;\n g.beginPath();\n g.roundRect(32 - w, 0, w, 20, 10);\n g.fillStyle = \"#d1213b\";\n g.fill();\n g.lineWidth = 1.5;\n g.strokeStyle = g.fillStyle = \"#fff\";\n g.stroke();\n g.font = `700 ${label.length === 3 ? 13 : 16}px Arial,Helvetica,sans-serif`;\n g.textAlign = \"center\";\n g.fillText(label, 32 - w / 2, 15);\n return c.toDataURL();\n}\n\n/** The tab's title: the unread count, the open room and the site's title, e.g. \"(3) #general \u2013 Chirkle\". */\nexport function tabTitle(s: AppState, label: string): string {\n const room = s.activeRoomId ? s.rooms.get(s.activeRoomId) : undefined;\n const title = room ? `${roomTitle(room, s.user)} \u2013 ${s.site.title}` : s.site.title;\n return label ? `(${label}) ${title}` : title;\n}\n\n/** Keep the favicon and the title in step with the unread counts. Returns a function that stops it. */\nexport function startFavicon(store: Store<AppState>, doc: Document = document): () => void {\n const title = doc.title;\n let shown: string | null = null;\n // Firefox ignores a new href on the icon's <link>, so each change puts in a fresh one, once its icon is drawn and\n // only if no newer count came in meanwhile. The count is on it as `data-badge` too.\n const setIcon = async (label: string) => {\n const href = label ? await badgedIcon(label).catch(() => ICON) : ICON;\n if (label !== shown) return;\n const link = doc.createElement(\"link\");\n link.rel = \"icon\";\n link.href = href;\n link.dataset.badge = label;\n const old = doc.querySelector('link[rel=\"icon\"]');\n old ? old.replaceWith(link) : doc.head.append(link);\n };\n const render = (s: AppState) => {\n const label = badgeLabel(totalUnread(s));\n if (label !== shown) {\n shown = label;\n void setIcon(label);\n }\n const t = tabTitle(s, label);\n if (doc.title !== t) doc.title = t;\n };\n render(store.get());\n const off = store.subscribe((s, prev) => {\n if (\n s.unread !== prev.unread ||\n s.rooms !== prev.rooms ||\n s.hidden !== prev.hidden ||\n s.activeRoomId !== prev.activeRoomId ||\n s.away !== prev.away ||\n s.site !== prev.site ||\n s.user !== prev.user\n )\n render(s);\n });\n return () => {\n off();\n doc.title = title;\n shown = \"\";\n void setIcon(\"\");\n };\n}\n", "// A page from a lazy chunk (`lazyView`). Until 2026-11-12 this also held the \"kits\", what each lazy chunk got of app.js\n// as arguments while lazy chunks could share no code with it (REFACTOR item 52): they import what they use now.\n\nimport { h } from \"./dom.ts\";\nimport type { View } from \"./router.ts\";\nimport * as S from \"./strings/lazy.ts\";\n\n/**\n * A page from a lazy chunk: \"Loading\u2026\" until `load` gives its view, which is then mounted in its place (if it is still\n * wanted). `failed` is said when the chunk can't be loaded (offline, or a new version deployed).\n */\nexport function lazyView(load: () => Promise<View>, failed: string): View {\n let inner: View | null = null;\n let gone = false;\n return {\n mount(el, params) {\n gone = false;\n el.replaceChildren(h(\"p\", { class: \"empty\", role: \"status\" }, \"Loading\u2026\"));\n load().then(\n (v) => {\n if (gone) return;\n inner = v;\n v.mount(el, params);\n },\n () => {\n if (!gone) el.replaceChildren(h(\"p\", { class: \"empty\", role: \"alert\" }, failed));\n },\n );\n },\n update(params) {\n inner?.update?.(params);\n },\n unmount() {\n gone = true;\n inner?.unmount();\n inner = null;\n },\n };\n}\n", "// The message list as a sliding window over a room's history (\u00A77.5).\n// Pure functions: every operation returns a new window (or the same object when nothing changed).\n\nimport * as S from \"../strings/lib-messages.ts\";\nimport { PAGE_SIZE } from \"./cursor.ts\";\nimport { parsePb } from \"./time.ts\";\nimport type { Message, Quoted } from \"./types.ts\";\n\nexport const WINDOW_MAX = 300;\nconst GROUP_GAP_MS = 5 * 60 * 1000;\n\nexport interface MessageWindow {\n /** Sorted by (created, id); at most WINDOW_MAX after trimming. */\n items: Message[];\n /** false \u21D2 items[0] is the room's very first message. */\n hasOlder: boolean;\n /** false \u21D2 the window is at the live edge. */\n hasNewer: boolean;\n}\n\nexport type PageKind = \"latest\" | \"first\" | \"older\" | \"newer\";\nexport type Side = \"top\" | \"bottom\";\n\nexport const emptyWindow = (): MessageWindow => ({ items: [], hasOlder: false, hasNewer: false });\n\nexport function compare(a: Message, b: Message): number {\n if (a.created !== b.created) return a.created < b.created ? -1 : 1;\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n}\n\n/** Which of two copies of the same message to keep. */\nfunction newest(current: Message, incoming: Message): Message {\n if (current.status && !incoming.status) return incoming; // server ack replaces optimistic copy\n if (!current.status && incoming.status) return current; // never regress to an optimistic copy\n return incoming.updated >= current.updated ? incoming : current;\n}\n\n/** Merge messages into the window: dedupe by id, keep the newest copy, keep (created, id) order. */\nexport function merge(win: MessageWindow, incoming: readonly Message[]): MessageWindow {\n if (!incoming.length) return win;\n const byId = new Map(win.items.map((m) => [m.id, m]));\n for (const m of incoming) {\n const cur = byId.get(m.id);\n byId.set(m.id, cur ? newest(cur, m) : m);\n }\n return { ...win, items: [...byId.values()].sort(compare) };\n}\n\nexport function remove(win: MessageWindow, id: string): MessageWindow {\n const i = win.items.findIndex((m) => m.id === id);\n if (i < 0) return win;\n return { ...win, items: win.items.filter((_, j) => j !== i) };\n}\n\n/** Drop messages beyond `max` from one end. \"bottom\" drops the newest, \"top\" the oldest. */\nexport function trim(win: MessageWindow, side: Side, max = WINDOW_MAX): { win: MessageWindow; dropped: string[] } {\n const extra = win.items.length - max;\n if (extra <= 0) return { win, dropped: [] };\n if (side === \"bottom\") {\n return {\n win: { ...win, items: win.items.slice(0, max), hasNewer: true },\n dropped: win.items.slice(max).map((m) => m.id),\n };\n }\n return {\n win: { ...win, items: win.items.slice(extra), hasOlder: true },\n dropped: win.items.slice(0, extra).map((m) => m.id),\n };\n}\n\n/**\n * Apply a fetched page (in any order). \"latest\"/\"first\" reset the window; \"older\"/\"newer\" extend it and\n * trim the opposite end. A page shorter than PAGE_SIZE means that end of the history has been reached.\n */\nexport function applyPage(win: MessageWindow, page: readonly Message[], kind: PageKind): { win: MessageWindow; dropped: string[] } {\n const full = page.length >= PAGE_SIZE;\n switch (kind) {\n case \"latest\":\n return { win: merge({ items: [], hasOlder: full, hasNewer: false }, page), dropped: [] };\n case \"first\":\n return { win: merge({ items: [], hasOlder: false, hasNewer: full }, page), dropped: [] };\n case \"older\":\n return trim({ ...merge(win, page), hasOlder: full }, \"bottom\");\n case \"newer\":\n return trim({ ...merge(win, page), hasNewer: full }, \"top\");\n }\n}\n\n/** Does `cur` start a new author group after `prev`? (author change or a gap over 5 minutes) */\nexport function startsGroup(prev: Message | undefined, cur: Message): boolean {\n if (!prev || prev.author !== cur.author) return true;\n return parsePb(cur.created) - parsePb(prev.created) > GROUP_GAP_MS;\n}\n\nexport function group(items: readonly Message[]): Message[][] {\n const groups: Message[][] = [];\n items.forEach((m, i) => {\n if (startsGroup(items[i - 1], m)) groups.push([m]);\n else groups[groups.length - 1]!.push(m);\n });\n return groups;\n}\n\n/** The newest message the server has (not pending or failed): what read state and gap fill go by. */\nexport function lastSaved(win: MessageWindow): Message | undefined {\n for (let i = win.items.length - 1; i >= 0; i--) if (!win.items[i]!.status) return win.items[i];\n return undefined;\n}\n\n/** My newest message that can be edited (Up arrow in an empty composer). */\nexport function lastOwnEditable(win: MessageWindow, me: string): Message | undefined {\n for (let i = win.items.length - 1; i >= 0; i--) {\n const m = win.items[i]!;\n if (m.author === me && !m.deleted && !m.status && !m.forwarded_from) return m;\n }\n return undefined;\n}\n\n/** A forward whose original was deleted: it has nothing left to show, or to forward again (\u00A721.3). */\nexport const emptyForward = (m: Message): boolean => !!m.forwarded_from && !m.text && !m.files?.length;\n\n/** What a reply keeps of the message it answers (\u00A719), e.g. for an optimistic reply before the server expands it. */\nexport function quoteOf(m: Message): Quoted {\n return {\n id: m.id,\n author: m.author,\n text: m.text,\n deleted: m.deleted,\n ...(m.files?.length ? { files: m.files } : {}),\n ...(m.expand?.author ? { expand: { author: m.expand.author } } : {}),\n };\n}\n\n/** One line of a quoted message: its text on one line, or what it holds when it has none (\u00A719). */\nexport function quoteText(q: Pick<Quoted, \"text\" | \"deleted\" | \"files\">): string {\n if (q.deleted) return \"Message deleted\";\n const text = q.text.replace(/\\s+/g, \" \").trim();\n if (text) return text;\n const n = q.files?.length ?? 0;\n if (!n) return \"Message deleted\"; // a forward whose original was deleted (\u00A721.3)\n return n === 1 ? \"Attachment\" : `${n} attachments`;\n}\n", "// Keeps the room cache (cache.ts) up to date for rooms with unread messages (\u00A77.5): when a room's unread count goes up,\n// its latest page is fetched in the background, so opening it shows the new messages at once. Messages that come within\n// DELAY_MS of the first are one fetch, and rooms are fetched one at a time, GAP_MS apart. A room fetched less than\n// REFETCH_MS ago waits until then: a busy room that stays unread is fetched every REFETCH_MS, not every DELAY_MS, by\n// every user who has it unread (QA BUG-108); its first unread message is still fetched at once. A message deleted in a room\n// refetches it too, so the cache never shows its text again. Runs while someone is logged in (unread counts are theirs);\n// stopped before the cache is cleared, so nothing lands in it afterwards. Once the room list is in, the rooms that\n// aren't kept yet are fetched too (after the unread ones, up to WARM of them): a room not yet opened here opens at once.\n// A room's link pressed, or pointed at for HOVER_MS, asks for its latest page at once (`hint`): the room takes that\n// request as its first page when it opens (`take`), a click later (PERF.md \u00A75).\n\nimport type { Api } from \"./api.ts\";\nimport type { Cache } from \"./cache.ts\";\nimport { latest, PAGE_SIZE } from \"./lib/cursor.ts\";\nimport { compare } from \"./lib/messages.ts\";\nimport type { Message } from \"./lib/types.ts\";\nimport { createScope, type Scope } from \"./scope.ts\";\nimport { type AppState, roomSections, type Store } from \"./store.ts\";\n\nexport interface Prefetch {\n start(): void;\n stop(): void;\n /** The pointer went down on room `id`'s link, or rests on it: ask for its latest page now. Signed in only. */\n hint(id: string): void;\n /** The page `hint` asked for, if lately (EARLY_MS): the room's first page, and its tag. Taken once. */\n take(id: string): Promise<EarlyPage> | undefined;\n}\n\n/** A latest page asked for early, and its ETag (PERF.md \u00A75). */\nexport interface EarlyPage {\n items: Message[];\n tag: string;\n}\n\n/** A hinted page goes stale after this long: the room asks for its own. */\nconst EARLY_MS = 5000;\n/** How long the pointer rests on a room's link before its page is asked for. */\nexport const HOVER_MS = 120;\n\nconst DELAY_MS = 1000;\n/** Between two fetches: hundreds of rooms must not use up the server's per-IP request limit (QA BUG-94). */\nconst GAP_MS = 250;\n/** Rooms not kept yet that are fetched once the room list is in: the first ones it lists (DMs, then rooms). */\nconst WARM = 30;\n/** Between two fetches of a room, unless it had no unread messages (or one was deleted) since (QA BUG-108). */\nconst REFETCH_MS = 30_000;\n\nexport function createPrefetch({\n api,\n store,\n cache,\n delayMs = DELAY_MS,\n gapMs = GAP_MS,\n refetchMs = REFETCH_MS,\n}: {\n api: Api;\n store: Store<AppState>;\n cache: Cache;\n delayMs?: number;\n gapMs?: number;\n refetchMs?: number;\n}): Prefetch {\n let scope: Scope | null = null;\n /** Pages asked for by `hint`, by room, with when. */\n const early = new Map<string, { at: number; page: Promise<EarlyPage> }>();\n\n return {\n hint(id) {\n const user = store.get().user?.id ?? \"\";\n const s = scope;\n const was = early.get(id);\n if (!s || !user || id === store.get().activeRoomId || (was && was.at > Date.now() - EARLY_MS)) return;\n const kept = cache.peek(user, id);\n let tag = \"\";\n const items = kept ? [...kept.items].sort(compare).reverse() : [];\n const page = api.page(latest(id), s.signal, { tag: kept?.tag, items, got: (t) => (tag = t) }).then((p) => {\n // Kept too, as prefetching keeps a page: pointed at and not opened, it opens at once later.\n if (s.active && store.get().user?.id === user && store.get().activeRoomId !== id && tag !== kept?.tag)\n cache.put(user, id, { items: p, hasOlder: p.length >= PAGE_SIZE, room: store.get().rooms.get(id), tag });\n return { items: p, tag };\n });\n page.catch(() => early.delete(id));\n early.set(id, { at: Date.now(), page });\n },\n take(id) {\n const was = early.get(id);\n early.delete(id);\n return was && was.at > Date.now() - EARLY_MS ? was.page : undefined;\n },\n start() {\n const user = store.get().user?.id ?? \"\";\n if (scope || !user) return;\n const s = createScope();\n scope = s;\n /** Rooms to fetch, in the order they became due. */\n const due = new Set<string>();\n /** Rooms to fetch after those, unless they are kept already. */\n const cold = new Set<string>();\n /** Set from when rooms are due until a run has fetched them: a busy room never puts it off (QA BUG-92). */\n let timer: ReturnType<typeof setTimeout> | undefined;\n /** When each room's last fetch began. */\n const fetched = new Map<string, number>();\n /** Rooms fetched too recently to be due yet: due once REFETCH_MS has passed, if still unread. */\n const later = new Set<string>();\n const ready = (id: string) => (fetched.get(id) ?? 0) <= Date.now() - refetchMs;\n\n async function drain() {\n for (const id of later) if (ready(id) && later.delete(id) && store.get().unread.get(id)) due.add(id);\n // Rooms due again meanwhile wait for the next run (and REFETCH_MS).\n for (const id of new Set([...due, ...cold])) {\n if (due.delete(id)) cold.delete(id);\n else {\n // A room not kept yet gives way to one that became due meanwhile: the next run fetches that first.\n if (due.size) break;\n cold.delete(id);\n if (id === store.get().activeRoomId || (await cache.get(user, id))) continue;\n if (!s.active) return;\n }\n const unread = store.get().unread.get(id);\n // From when it is asked for: a message that comes while it is on its way waits too.\n fetched.set(id, Date.now());\n // With the kept copy's tag: unchanged, the page comes without a body, and nothing is parsed or written (PERF.md \u00A75).\n const kept = cache.peek(user, id);\n let tag = \"\";\n const same: Message[] = [];\n const page = await api.page(latest(id), s.signal, { tag: kept?.tag, items: same, got: (t) => (tag = t) }).catch(() => null);\n if (!s.active) return;\n // Refused (the rate limit, offline): the rest waits for their counts to go up again (or the next start).\n if (!page) {\n due.clear();\n cold.clear();\n break;\n }\n // The open room keeps its own page (and gets every message live).\n if (store.get().user?.id === user && store.get().activeRoomId !== id) {\n if (kept && kept.tag === tag && kept.items.length) {\n if (kept.unread !== unread) cache.put(user, id, { ...kept, unread }); // the same page: only the count to note\n } else cache.put(user, id, { items: page, hasOlder: page.length >= PAGE_SIZE, room: store.get().rooms.get(id), unread, tag });\n }\n await new Promise((r) => setTimeout(r, gapMs));\n }\n timer = undefined;\n if (due.size || cold.size || later.size) schedule();\n }\n const schedule = () => {\n timer ??= setTimeout(drain, delayMs);\n };\n /** `now`: the room had no unread messages before, or one was deleted: fetched even if it just was. */\n const add = (id: string, now = false) => {\n if (id === store.get().activeRoomId) return;\n if (now) fetched.delete(id);\n (ready(id) ? due : later).add(id);\n schedule();\n };\n\n let warmed = false;\n const warm = (st: AppState) => {\n if (warmed || st.roomsStatus !== \"ready\") return;\n warmed = true;\n const { dms, rooms } = roomSections(st);\n for (const r of [...dms, ...rooms].slice(0, WARM)) cold.add(r.id);\n schedule();\n };\n s.defer(\n store.subscribe((st, prev) => {\n if (st.unread !== prev.unread) for (const [id, n] of st.unread) if (n > (prev.unread.get(id) ?? 0)) add(id, !prev.unread.get(id));\n warm(st);\n }),\n );\n warm(store.get());\n s.sub(api.subscribeAllMessages((_, m) => m.deleted && add(m.room, true)));\n s.defer(() => clearTimeout(timer));\n },\n stop() {\n scope?.dispose();\n scope = null;\n early.clear();\n },\n };\n}\n", "// Keeping the session alive and checked (QA BUG-45, BUG-51, BUG-151): renewed halfway through its lifetime for as long\n// as the tab stays open, checked again when the tab comes back after a while and when the server refuses a change. A\n// session that ran out or was revoked calls `expire`; one that can't be checked for lack of network is tried later.\n\nimport { type Api, ApiError } from \"./api.ts\";\nimport type { AppState, Store } from \"./store.ts\";\n\n/** Statuses meaning \"the server rejected this session\" (vs. 0 = network trouble). */\nconst AUTH_REJECTED = new Set([401, 403, 404]);\n/** Longest wait between session renewals, and the wait before another try after one failed for lack of network. */\nconst RENEW_MAX_MS = 24 * 60 * 60 * 1000;\nconst RENEW_RETRY_MS = 60 * 1000;\n/**\n * A session can also be revoked before it expires: a password change signs out every other device. It is checked again\n * when the server refuses a change (at most this often), and when the tab comes back after this long (QA BUG-51).\n */\nconst CHECK_MIN_MS = 30 * 1000;\nconst CHECK_STALE_MS = 5 * 60 * 1000;\n/** At start, the check waits for the room list (it would take a connection and server time from it), at most this long. */\nconst START_WAIT_MS = 3000;\n\nexport interface Renewal {\n /** Check (and renew) the session now. */\n renew(): void;\n /**\n * A restored session, at start: checked (and renewed) once the room list is in, or START_WAIT_MS on, whichever is\n * first. One that ran out meanwhile is over at once. Until checked, a revoked one shows what a guest sees (PERF.md \u00A75).\n */\n renewSoon(): void;\n /** The tab became visible: timers were late or paused meanwhile. */\n visible(): void;\n stop(): void;\n}\n\nexport function createRenewal({ api, store, expire }: { api: Api; store: Store<AppState>; expire: () => void }): Renewal {\n let timer: ReturnType<typeof setTimeout> | undefined;\n /** When the session was last checked with the server (renewed, or found revoked). */\n let checkedAt = 0;\n /** Stops waiting for the room list to check a restored session (renewSoon). */\n let starting = () => {};\n\n function schedule(ms = Math.min(Math.max((api.sessionExpiry() - Date.now()) / 2, 0), RENEW_MAX_MS)) {\n clearTimeout(timer);\n if (store.get().user) timer = setTimeout(renew, ms);\n }\n\n function renew() {\n const user = store.get().user;\n if (!user) return;\n // Already over (e.g. the computer slept through it): it can't be renewed, so say so instead of failing quietly.\n if (api.sessionExpiry() <= Date.now()) return expire();\n checkedAt = Date.now();\n api.refreshAuth().then(\n (fresh) => {\n if (store.get().user?.id !== fresh.id) return;\n store.set({ user: fresh });\n schedule();\n },\n (err: unknown) => {\n if (store.get().user?.id !== user.id) return;\n if (err instanceof ApiError && AUTH_REJECTED.has(err.status)) expire();\n else schedule(RENEW_RETRY_MS); // offline \u2260 logged out: try again later\n },\n );\n }\n\n /** A refused change: was it the session? A revoked one logs out instead of failing every send (\"Not sent\"). */\n const offRejected = api.onRejected(() => {\n if (!store.get().user) return;\n const wait = checkedAt + CHECK_MIN_MS - Date.now();\n // Checked a moment ago: check again once allowed, not never (QA BUG-151).\n if (wait <= 0) renew();\n else schedule(wait);\n });\n\n const offStore = store.subscribe((s, prev) => {\n if (s.user === prev.user) return;\n if (s.user && !prev.user) schedule();\n if (!s.user) clearTimeout(timer);\n });\n\n return {\n renew,\n renewSoon() {\n if (!store.get().user) return;\n if (api.sessionExpiry() <= Date.now()) return expire();\n const listed = (s: AppState) => s.roomsStatus !== \"idle\" && s.roomsStatus !== \"loading\";\n if (listed(store.get())) return renew();\n const go = () => {\n starting();\n renew();\n };\n const wait = setTimeout(go, START_WAIT_MS);\n const off = store.subscribe((s) => listed(s) && go());\n starting = () => {\n clearTimeout(wait);\n off();\n };\n },\n visible() {\n // Also check a session not checked for a while: revoked meanwhile, this tab would get nothing live and send nothing.\n if (store.get().user && Date.now() - checkedAt > CHECK_STALE_MS) renew();\n else schedule();\n },\n stop() {\n starting();\n offRejected();\n offStore();\n clearTimeout(timer);\n },\n };\n}\n", "// Router (\u00A77.1, \u00A77.2): pages are paths (`/r/abc`), changed with the History API; PocketBase serves index.html for any\n// path that isn't a file. Old `#/r/abc` links still work. Idempotent: re-resolving to the mounted route does nothing.\n\nexport interface View {\n mount(root: HTMLElement, params: Record<string, string>): void;\n unmount(): void;\n /**\n * Optional: take new params in place. Used instead of a remount when the next route has the same view\n * factory, e.g. switching rooms keeps the sidebar mounted.\n */\n update?(params: Record<string, string>): void;\n /**\n * Optional: kept, hidden, after it was left (app.ts withSidebar keeps the last rooms, PERF.md \u00A75): still live, but not\n * what you are looking at. `resume` shows it again; false if it can't be (it is to be unmounted and made afresh).\n */\n park?(): void;\n resume?(): boolean;\n}\n\nexport interface Route {\n pattern: string;\n view: () => View;\n /** Reachable without auth (guests read the Open Air rooms, \u00A723.3). */\n public?: boolean;\n /** Only for guests (logging in, signing up): signed in, it goes home. */\n guestOnly?: boolean;\n}\n\nexport interface Router {\n start(): void;\n stop(): void;\n /** Go to `path` (a new history entry), or re-check it if it is where we are. */\n navigate(path: string): void;\n /** Re-check the current route, e.g. after auth changes. */\n refresh(): void;\n /** Unmount the current view and resolve the route again with a fresh one (e.g. after the user changed). */\n remount(): void;\n}\n\nconst HOME = \"/\";\nconst LOGIN = \"/login\";\n\n/**\n * The page we are on, as a path (what routes match). An old-style URL (`/#/r/abc`, from before paths) is its hash's.\n * A trailing slash (`/r/abc/`, typed or pasted) is dropped, and leading ones are one: `#//host` as a URL is another\n * site's, which replaceState refuses, and the app never started (QA BUG-146).\n */\nexport const here = (): string =>\n (location.hash.startsWith(\"#/\") ? location.hash.slice(1) : location.pathname).replace(/^[/\\\\]+/, \"/\").replace(/(.)\\/$/, \"$1\");\n\n/** An old-style URL: show it as its path (`/r/abc`) instead. True if it was one. */\nfunction fromLegacyHash(): boolean {\n if (!location.hash.startsWith(\"#/\")) return false;\n history.replaceState(history.state, \"\", here());\n return true;\n}\n\nexport function matchRoute<R extends { pattern: string }>(\n routes: readonly R[],\n path: string,\n): { route: R; params: Record<string, string> } | null {\n const parts = (path || HOME).split(\"/\");\n for (const route of routes) {\n const pp = route.pattern.split(\"/\");\n if (pp.length !== parts.length) continue;\n const params: Record<string, string> = {};\n const ok = pp.every((seg, i) => {\n const part = parts[i]!;\n if (!seg.startsWith(\":\")) return seg === part;\n if (!part) return false;\n try {\n params[seg.slice(1)] = decodeURIComponent(part);\n } catch {\n return false; // malformed escape (e.g. \"%E0%A4%A\"): no match, so it redirects home\n }\n return true;\n });\n if (ok) return { route, params };\n }\n return null;\n}\n\nexport function createRouter(opts: {\n root: HTMLElement;\n routes: Route[];\n isAuthed: () => boolean;\n /** The user went somewhere (a link, Back/Forward, `navigate()`), before any redirect. */\n onNavigate?: (path: string) => void;\n}): Router {\n const { root, routes, isAuthed } = opts;\n let current: { key: string; factory: () => View; view: View } | null = null;\n let running = false;\n /** Stops the listeners added by start(). */\n let listening: AbortController | null = null;\n\n function unmountCurrent() {\n current?.view.unmount();\n current = null;\n }\n\n /** Where `path` must go instead, or null if it may be shown. */\n function redirect(route: Route | undefined): string | null {\n if (!route) return HOME;\n if (!route.public && !isAuthed()) return LOGIN;\n if ((route.guestOnly || route.pattern === LOGIN) && isAuthed()) return HOME;\n return null;\n }\n\n function resolve() {\n if (!running) return;\n const path = here();\n const m = matchRoute(routes, path);\n const target = redirect(m?.route);\n if (target !== null && target !== path) {\n history.replaceState(null, \"\", target);\n return resolve();\n }\n if (!m) return; // unreachable: no match always redirects to HOME, which matches\n\n if (current?.key === path) return;\n if (current?.factory === m.route.view && current.view.update) {\n current.key = path;\n current.view.update(m.params);\n return;\n }\n unmountCurrent();\n const view = m.route.view();\n current = { key: path, factory: m.route.view, view };\n view.mount(root, m.params);\n }\n\n function go(path: string) {\n if (here() !== path) {\n history.pushState(null, \"\", path);\n opts.onNavigate?.(path);\n }\n resolve();\n }\n\n /**\n * An entry the image viewer (\u00A717.7) or the media grid (\u00A730) added with nothing open on it: Forward after Back closed\n * it, or a reload while it was open. It would take an extra Back that seems to do nothing, so it is passed over.\n * (While a viewer is open, a popstate only ever leaves its entry, so this never meets an open viewer; the grid's\n * entry is met with the grid open when Back closes a viewer over it, QA BUG-118.)\n */\n const skipViewerEntry = () => {\n const s = history.state as { viewer?: unknown; media?: unknown } | null;\n if (s?.viewer || (s?.media && !document.querySelector(\"dialog.media\"))) history.back();\n };\n /** Back/Forward. (Also the image viewer's own history entry, \u00A717.7: same path, so nothing to do.) */\n const onPopState = () => {\n skipViewerEntry();\n opts.onNavigate?.(here());\n resolve();\n };\n /** An old-style link (`#/r/abc`) opened in this tab. */\n const onHashChange = () => {\n if (!fromLegacyHash()) return;\n opts.onNavigate?.(here());\n resolve();\n };\n /** A click on a link to one of the app's pages shows it here, without loading the page again. */\n const onClick = (e: MouseEvent) => {\n if (e.defaultPrevented || e.button || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;\n const a = (e.target as Element | null)?.closest?.(\"a[href]\");\n if (!(a instanceof HTMLAnchorElement) || a.target || a.hasAttribute(\"download\") || a.origin !== location.origin) return;\n if (!matchRoute(routes, a.pathname)) return;\n e.preventDefault();\n go(a.pathname);\n };\n\n return {\n start() {\n running = true;\n fromLegacyHash();\n skipViewerEntry();\n listening = new AbortController();\n const { signal } = listening;\n window.addEventListener(\"popstate\", onPopState, { signal });\n window.addEventListener(\"hashchange\", onHashChange, { signal });\n document.addEventListener(\"click\", onClick, { signal });\n resolve();\n },\n stop() {\n running = false;\n listening?.abort();\n unmountCurrent();\n },\n navigate: go,\n refresh: resolve,\n remount() {\n unmountCurrent();\n resolve();\n },\n };\n}\n", "// The site's branding and signup policy (\u00A724): loaded once at startup into the store. The last one seen is kept in\n// localStorage, so a reload shows the site's own title and logo right away instead of the defaults first.\n\nimport type { Api } from \"./api.ts\";\nimport { DEFAULT_SITE, type Site } from \"./lib/types.ts\";\nimport type { AppState, Store } from \"./store.ts\";\n\nconst KEY = \"chat.site\";\n\n/** The cached site, if it looks like one. */\nexport function cachedSite(storage: Storage | null): Site | null {\n try {\n const v = JSON.parse(storage?.getItem(KEY) ?? \"null\") as Partial<Site> | null;\n if (!v || typeof v.title !== \"string\" || !v.title || typeof v.logo !== \"string\" || typeof v.inviteOnly !== \"boolean\") return null;\n return { title: v.title, logo: v.logo, inviteOnly: v.inviteOnly, passwordReset: v.passwordReset === true };\n } catch {\n return null;\n }\n}\n\n/** Show the cached site, then the server's. Failing to load keeps what is shown. Returns a function that stops it. */\nexport function startSite(api: Api, store: Store<AppState>, storage: Storage | null = safeLocalStorage()): () => void {\n const cached = cachedSite(storage);\n if (cached) store.set({ site: cached });\n const ac = new AbortController();\n api.site(ac.signal).then(\n (site) => {\n if (ac.signal.aborted) return;\n const cur = store.get().site;\n const changed =\n site.title !== cur.title ||\n site.logo !== cur.logo ||\n site.inviteOnly !== cur.inviteOnly ||\n site.passwordReset !== cur.passwordReset;\n if (changed) store.set({ site });\n try {\n // Storage can throw (quota, disabled in a private window): the cache is a convenience.\n if (site === DEFAULT_SITE) storage?.removeItem(KEY);\n else storage?.setItem(KEY, JSON.stringify(site));\n } catch {}\n },\n () => {},\n );\n return () => ac.abort();\n}\n\nfunction safeLocalStorage(): Storage | null {\n try {\n return globalThis.localStorage ?? null;\n } catch {\n return null;\n }\n}\n", "// Keeps the room list and the user's hidden rows in the store (\u00A77.4): one load, one set of realtime\n// subscriptions and a reload after every reconnect, for as long as the app runs: for a guest too, who only gets the\n// Open Air rooms and has nothing hidden (\u00A723.3). Restarted whenever someone logs in or out. Views only read.\n// Unread counts have their own service (unread.ts).\n\nimport type { Api } from \"./api.ts\";\nimport { createScope, type Scope } from \"./scope.ts\";\nimport { type AppState, listLoad, markHidden, removeRoom, type Store, unmarkHidden, upsertRoom } from \"./store.ts\";\n\ntype Update = ReturnType<typeof upsertRoom>;\n\nexport interface Sync {\n /** Load and subscribe, as whoever is logged in now (or as a guest). */\n start(): void;\n /** Unsubscribe and ignore anything still in flight. Leaves the store as it is. */\n stop(): void;\n /** Refetch both lists (also runs on every realtime reconnect, since events may have been missed). */\n reload(): Promise<void>;\n}\n\nexport function createSync({ api, store }: { api: Api; store: Store<AppState> }): Sync {\n /** The current run; callbacks hold on to theirs, so a restart can't revive them. */\n let scope: Scope | null = null;\n\n /** The current run is a guest's (\u00A723.3). */\n let guest = true;\n\n /** Loads are numbered; an answer older than the one in the store is dropped. */\n let issued = 0;\n let applied = 0;\n\n function apply(s: Scope, update: Update) {\n if (s.active) store.set(update);\n }\n\n /** Loads out now. */\n let inFlight = 0;\n /**\n * The rooms whose entry in `rooms`, and those whose entry in `hidden`, changed in the store while a load was out,\n * however: a live event, or this tab itself (a room created, a DM opened, a room hidden or shown), which may have no\n * event yet. A load's answer is older, so these are taken from the store as it is then, or left out if gone from it:\n * a room you were just taken out of isn't listed again (\u00A723.4), an archive isn't undone (QA BUG-69), a DM just\n * opened doesn't vanish (QA BUG-107).\n */\n let changed = { rooms: new Set<string>(), hidden: new Set<string>() };\n const track = (st: AppState, prev: AppState) => {\n if (inFlight)\n for (const k of [\"rooms\", \"hidden\"] as const)\n for (const id of new Set([...st[k].keys(), ...prev[k].keys()])) if (st[k].get(id) !== prev[k].get(id)) changed[k].add(id);\n };\n /** `answer` with the entries in `ids` as they are in `now`. */\n function settle<V>(answer: Map<string, V>, now: Map<string, V>, ids: Set<string>): Map<string, V> {\n for (const id of ids) now.has(id) ? answer.set(id, now.get(id)!) : answer.delete(id);\n return answer;\n }\n\n async function load(s: Scope) {\n const seq = ++issued;\n if (!inFlight++) changed = { rooms: new Set<string>(), hidden: new Set<string>() };\n if (store.get().roomsStatus !== \"ready\") store.set({ roomsStatus: \"loading\" });\n store.set(listLoad(1));\n try {\n const [rooms, hidden] = await Promise.all([api.listRooms(s.signal), guest ? [] : api.listHidden(s.signal)]);\n if (!s.active || seq < applied) return;\n applied = seq;\n // One store update: one by one, a room the answer lacks would vanish and come back, which views see as a room\n // returning (\u00A723.4).\n const now = store.get();\n store.set({\n rooms: settle(new Map(rooms.map((x) => [x.id, x])), now.rooms, changed.rooms),\n hidden: settle(new Map(hidden.map((x) => [x.room, x.id])), now.hidden, changed.hidden),\n roomsStatus: \"ready\",\n });\n } catch {\n if (s.active && seq >= applied) store.set({ roomsStatus: \"error\" });\n } finally {\n inFlight--;\n store.set(listLoad(-1));\n }\n }\n\n return {\n start() {\n if (scope) return;\n const s = createScope();\n scope = s;\n guest = !api.currentUser();\n s.defer(store.subscribe(track));\n s.sub(api.subscribeRooms((action, room) => apply(s, action === \"delete\" ? removeRoom(room.id) : upsertRoom(room))));\n if (!guest) {\n s.sub(api.subscribeHidden((action, row) => apply(s, action === \"delete\" ? unmarkHidden(row.id) : markHidden(row.room, row.id))));\n }\n s.defer(\n api.onConnect((reconnect) => {\n if (reconnect && s.active) void load(s);\n }),\n );\n void load(s);\n },\n stop() {\n scope?.dispose();\n scope = null;\n },\n async reload() {\n if (scope) await load(scope);\n },\n };\n}\n", "// Unread counts (\u00A718.3): keeps `unread` in the store and tells the server what has been read, for as long as someone\n// is logged in. The room view only reports what it shows (`open(roomId).seen(created, caughtUp)`); this module owns the\n// counting, the batching of reads, retries, and whose session a read belongs to.\n\nimport { type Api, ApiError } from \"./api.ts\";\nimport { createScope, type Scope } from \"./scope.ts\";\nimport { type AppState, bumpUnread, clearUnread, listLoad, type Store } from \"./store.ts\";\n\nexport interface Unread {\n /** Load the counts and follow them live. Call once a user is logged in. */\n start(): void;\n /** Unsubscribe and ignore anything still in flight. Pending reads are dropped: flush() first to keep them. */\n stop(): void;\n /** Refetch the counts soon (several calls in a row make one request). */\n refresh(): void;\n /** Send every pending read now (before the session ends, e.g. on logout). */\n flush(): void;\n /** Start reading a room (the room view, while mounted). */\n open(roomId: string): RoomReader;\n}\n\nexport interface RoomReader {\n /**\n * The messages up to `created` (a message's `created`) have been on screen: read. `caughtUp` is whether that was\n * the newest one (the room's count is then cleared). Cheap to call on every render and scroll.\n */\n seen(created: string, caughtUp: boolean): void;\n /**\n * Leaving the room: send a pending read now. `caughtUp` is whether the newest messages were on screen at the end;\n * if not, messages may have arrived unseen (they aren't counted live in the room you are in), so refetch.\n */\n close(caughtUp: boolean): void;\n}\n\nexport interface UnreadTiming {\n /** How long refresh() waits for more calls before it fetches. */\n refreshMs: number;\n /** How long reads are batched before the server is told. */\n readMs: number;\n /** The first wait before a failed read is sent again; it doubles each time, up to MAX_RETRY_MS. */\n retryMs: number;\n}\n\nconst TIMING: UnreadTiming = { refreshMs: 250, readMs: 1000, retryMs: 2000 };\nconst MAX_RETRY_MS = 60_000;\n\nexport function createUnread({ api, store, timing = TIMING }: { api: Api; store: Store<AppState>; timing?: UnreadTiming }): Unread {\n /** The current run; callbacks hold on to theirs, so a restart can't revive them. */\n let scope: Scope | null = null;\n /**\n * The live +1s received while a count request is in flight. Those its answer doesn't account for (`ids`) are added\n * back on top (never refetched: a busy room would starve the counts, QA).\n */\n let recent: { room: string; id: string }[] = [];\n /**\n * The recent messages the counts in the store account for: their live events, late, are already counted (QA BUG-106).\n * Not reset by start(): a new session's events are all of messages newer than any of these.\n */\n let accounted = new Set<string>();\n let inFlight = 0;\n /** `at` of the counts in the store: an older answer that arrives late is dropped. */\n let countedAt = \"\";\n let refreshTimer: ReturnType<typeof setTimeout> | undefined;\n /**\n * The open room while its newest messages are on screen (its reader last said `caughtUp`): its count is the room\n * view's to clear, and what arrives in it is read as it comes. Scrolled up, or opened at its first unread message, it\n * keeps the server's count, badge included: the rest is still unread (2026-11-02, user).\n */\n let following: string | null = null;\n /** Readers with a read not sent yet. */\n const pending = new Set<{ send(): void }>();\n\n async function load(s: Scope) {\n inFlight++;\n store.set(listLoad(1));\n try {\n const res = await api.unreadCounts(s.signal).catch(() => null);\n if (!res || !s.active || res.at < countedAt) return;\n countedAt = res.at;\n accounted = new Set(res.ids);\n const unread = new Map(Object.entries(res.rooms));\n for (const b of recent) if (!accounted.has(b.id)) unread.set(b.room, (unread.get(b.room) ?? 0) + 1);\n // The room you are caught up in is the room view's to clear; the server may not have its latest read yet. Not\n // while the tab is away: then the room view reads nothing, and the server's count is the one to show.\n const mentions = new Map(Object.entries(res.mentions ?? {}));\n if (following && !store.get().away) {\n unread.delete(following);\n mentions.delete(following);\n }\n store.set({ unread, mentions, inbox: res.inbox ?? 0 });\n } finally {\n store.set(listLoad(-1));\n if (--inFlight === 0) recent = [];\n }\n }\n\n function refresh() {\n const s = scope;\n if (!s) return;\n clearTimeout(refreshTimer);\n refreshTimer = setTimeout(() => void load(s), timing.refreshMs);\n }\n\n function open(roomId: string): RoomReader {\n /** The session this reader belongs to: reads are never sent from another one. */\n const s = scope;\n /** Whose reads these are: the session is shared with other tabs, which may switch it to someone else. */\n const reader = store.get().user?.id ?? \"\";\n /** Read up to here: sent, or about to be when `timer` fires. */\n let readAt = \"\";\n let timer: ReturnType<typeof setTimeout> | undefined;\n let closed = false;\n /** Failed sends in a row: the next retry waits longer. */\n let failures = 0;\n /** What the last seen() said: not caught up, the count is fetched again once a read is in. */\n let caughtUpNow = false;\n const live = () => !closed && !!s?.active && s === scope;\n\n const self = {\n send(): Promise<void> | undefined {\n clearTimeout(timer);\n timer = undefined;\n pending.delete(self);\n if (!s?.active || api.currentUser()?.id !== reader) return; // never as someone else\n const at = readAt;\n return api.markRead(roomId, at).then(\n () => {\n failures = 0;\n // What is still unread below the screen: the server counts it. So does the inbox's count: a mention or reply\n // read in its room is seen there too (\u00A741.4).\n if ((!caughtUpNow || store.get().inbox) && live()) refresh();\n },\n (e: unknown) => {\n // Offline, or the server in trouble: sent again a little later. Nothing else may ask (the room on screen\n // doesn't change), and the room would stay unread everywhere (QA BUG-162). A refusal is final.\n const status = e instanceof ApiError ? e.status : 0;\n if ((status >= 400 && status < 500 && status !== 429) || !live() || timer) return;\n pending.add(self);\n timer = setTimeout(self.send, Math.min(timing.retryMs * 2 ** Math.min(failures++, 5), MAX_RETRY_MS));\n },\n );\n },\n };\n\n return {\n seen(created, caughtUp) {\n if (!live()) return;\n caughtUpNow = caughtUp;\n if (caughtUp) following = roomId;\n else if (following === roomId) following = null;\n // Even with nothing new: a count fetched while the tab was away may include what was already read. Not before\n // the newest message: the rest is still unread (close() refetches the count).\n if (caughtUp) store.set(clearUnread(roomId));\n if (created <= readAt) return;\n readAt = created;\n if (timer) return;\n pending.add(self);\n timer = setTimeout(self.send, timing.readMs);\n },\n close(caughtUp) {\n if (closed) return;\n if (following === roomId) following = null;\n const sent = timer ? self.send() : undefined;\n if (live()) {\n if (caughtUp) store.set(clearUnread(roomId));\n // After the read is in: counted before it, the messages just read would show as unread again.\n else if (sent) void sent.then(refresh);\n else refresh();\n }\n closed = true;\n },\n };\n }\n\n return {\n start() {\n if (scope) return;\n const s = createScope();\n scope = s;\n countedAt = \"\";\n s.defer(() => clearTimeout(refreshTimer));\n s.sub(\n api.subscribeAllMessages((action, m) => {\n if (!s.active) return;\n const { user, away, unread } = store.get();\n // The room you are caught up in is read as it arrives (the room view reports it), unless the tab is away;\n // scrolled up, it stays unread. Your own messages never count.\n if (action === \"create\" && m.author !== user?.id && (m.room !== following || away) && !accounted.has(m.id)) {\n if (inFlight) recent.push({ room: m.room, id: m.id });\n store.set(bumpUnread(m.room));\n } else if (action === \"update\" && m.deleted && unread.has(m.room)) refresh(); // was it unread?\n }),\n );\n // A mention, reply or reaction for you, or one taken back (\u00A741): counted again.\n s.sub(api.subscribeInbox(() => s.active && refresh()));\n s.sub(\n api.subscribeReads((_action, row) => {\n // Read in another tab or on another device. The room you are caught up in is already at 0 here, unless the\n // tab is away.\n if (s.active && (row.room !== following || store.get().away)) refresh();\n }),\n );\n s.defer(\n api.onConnect((reconnect) => {\n if (reconnect && s.active) void load(s);\n }),\n );\n // A room you can now see (you were added to a private room, \u00A723.2) may already have messages for you.\n // Leaving the tab: the open room may have messages that arrived unseen (scrolled up), which only the server\n // counts. What was read is sent first.\n s.defer(\n store.subscribe((st, prev) => {\n if (!s.active) return;\n if (prev.roomsStatus === \"ready\" && st.rooms !== prev.rooms && [...st.rooms.keys()].some((id) => !prev.rooms.has(id))) refresh();\n if (st.away && !prev.away && st.activeRoomId) {\n for (const r of [...pending]) r.send();\n refresh();\n }\n }),\n );\n void load(s);\n },\n stop() {\n pending.clear();\n scope?.dispose();\n scope = null;\n },\n refresh,\n flush() {\n for (const r of [...pending]) r.send();\n },\n open,\n };\n}\n", "// A new version (\u00A727.4): when a deploy changed the app, a line above the app says so, with a link that reloads the page.\n// The page names its build's script (/assets/app-HASH.js); a newer index.html names another one. It is checked after\n// realtime reconnects (a deploy restarts the server), when the tab comes back into view, and every half hour.\n\nimport type { Api } from \"./api.ts\";\nimport { h } from \"./dom.ts\";\nimport * as S from \"./strings/update.ts\";\n\n/** At most one check this often from the tab coming into view (a reconnect checks anyway). */\nconst MIN_GAP = 60_000;\nconst EVERY = 30 * 60_000;\n/** After a reconnect, every open tab checks at once: spread over this long. */\nconst SPREAD = 10_000;\n\n/** The build's script in an index.html, e.g. \"/assets/app-AB12CD34.js\". */\nexport const appScript = (html: string) => /<script type=\"module\" src=\"(\\/assets\\/app[^\"]*\\.js)\"/.exec(html)?.[1];\n\n/**\n * Watch for a new version; the line goes at the top of `root` (#app). `current`: this page's script (none: nothing to\n * compare). Returns a function that stops it.\n */\nexport function startUpdates(\n api: Api,\n root: HTMLElement,\n current = document.querySelector('script[src^=\"/assets/app\"]')?.getAttribute(\"src\"),\n load = () => fetch(\"/\", { cache: \"no-store\" }).then((r) => r.text()),\n): () => void {\n let last = 0;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const shown = () => root.querySelector(\".update-bar\");\n const check = async (force?: boolean) => {\n if (!current || shown() || (!force && Date.now() - last < MIN_GAP)) return;\n last = Date.now();\n // Offline, a server mid-restart, a proxy's error page: no script named, nothing to say yet.\n const next = appScript(await load().catch(() => \"\"));\n if (next && next !== current && !shown()) {\n root.prepend(\n h(\"div\", { class: \"update-bar\", role: \"status\" }, [\n \"A new version of the app is out. \",\n // The page itself, loaded again: the router would show it in place (and middle-click opens it fresh anyway).\n h(\n \"a\",\n {\n href: location.href,\n on: {\n click: (e) => {\n e.preventDefault();\n location.reload();\n },\n },\n },\n \"Reload\",\n ),\n ]),\n );\n }\n };\n const onVisible = () => document.visibilityState === \"visible\" && void check();\n document.addEventListener(\"visibilitychange\", onVisible);\n const every = setInterval(check, EVERY);\n const offConnect = api.onConnect((reconnect) => {\n clearTimeout(timer);\n if (reconnect) timer = setTimeout(check, Math.random() * SPREAD, true);\n });\n return () => {\n document.removeEventListener(\"visibilitychange\", onVisible);\n clearInterval(every);\n clearTimeout(timer);\n offConnect();\n shown()?.remove();\n };\n}\n", "// A collection's page (\u00A731), /c/:id, next to the room list. Only this much is in app.js: the page itself, the save\n// menu and the picker are a lazy chunk (views/collection/lazy.ts), loaded when one is first wanted, with their own\n// stylesheet. What they need from app.js comes in their options.\n\nimport type { Ctx } from \"../context.ts\";\nimport { clear, h } from \"../dom.ts\";\nimport { formatFull, parsePb } from \"../lib/time.ts\";\nimport type { View } from \"../router.ts\";\nimport { createScope } from \"../scope.ts\";\nimport * as S from \"../strings/collection.ts\";\nimport type * as Lazy from \"./collection/lazy.ts\";\n\n/** The chunk, loaded once (a failed load is tried again next time). */\nlet chunk: Promise<typeof Lazy> | null = null;\nexport function collectionChunk(): Promise<typeof Lazy> {\n chunk ??= import(\"./collection/lazy.ts\").catch((e: unknown) => {\n chunk = null;\n throw e;\n });\n return chunk;\n}\n\n/** What the chunk's parts get from the app: the API, the DOM helper, the collections in the store and their service. */\nexport function chunkContext({ api, store, collections }: Pick<Ctx, \"api\" | \"store\" | \"collections\">) {\n return {\n api,\n h,\n service: collections,\n me: () => store.get().user,\n list: () => store.get().collections,\n watch: (fn: () => void) => store.subscribe((s, prev) => s.collections !== prev.collections && fn()),\n when: (created: string) => formatFull(parsePb(created)),\n };\n}\n\nexport function createCollectionView(ctx: Pick<Ctx, \"api\" | \"store\" | \"collections\" | \"navigate\">): View {\n const scope = createScope();\n let root: HTMLElement;\n return {\n mount(el, params) {\n root = el;\n const id = params.id ?? \"\";\n ctx.store.set({ activeCollectionId: id });\n const status = h(\"p\", { class: \"empty\", role: \"status\" }, \"Loading\u2026\");\n el.replaceChildren(status);\n collectionChunk().then(\n (m) => {\n if (scope.active) void m.mountCollection(el, { ...chunkContext(ctx), id, navigate: ctx.navigate, signal: scope.signal });\n },\n () => {\n if (scope.active) status.textContent = \"Couldn't open the collection. Check your connection.\";\n },\n );\n },\n unmount() {\n scope.dispose();\n ctx.store.set({ activeCollectionId: null });\n clear(root);\n },\n };\n}\n", "// Home (\u00A77.1): what the pane next to the room list shows when no room is open. A guest is told what they can read and\n// how to join in (\u00A723.3).\n\nimport type { Ctx } from \"../context.ts\";\nimport { clear, h } from \"../dom.ts\";\nimport type { View } from \"../router.ts\";\nimport { createScope } from \"../scope.ts\";\nimport * as S from \"../strings/home.ts\";\n\nconst firstName = (name: string) => name.trim().split(/\\s+/)[0] ?? \"\";\n\nexport function createHomeView({ store }: Pick<Ctx, \"store\">): View {\n const scope = createScope();\n let root: HTMLElement;\n const title = h(\"h1\", {});\n const text = h(\"p\", {});\n const render = () => {\n const user = store.get().user;\n const name = firstName(user?.name ?? \"\");\n title.textContent = name ? `Welcome, ${name}!` : \"Welcome!\";\n if (user) text.replaceChildren(\"Pick a room or a conversation from the list, or start a new one.\");\n else\n text.replaceChildren(\n \"Read any of the Open Air rooms in the list, no account needed. \",\n h(\"a\", { href: \"/login\" }, \"Log in\"),\n \" or \",\n h(\"a\", { href: \"/signup\" }, \"sign up\"),\n \" to join the conversation.\",\n );\n };\n\n return {\n mount(el) {\n root = el;\n render();\n clear(root);\n root.append(h(\"section\", { class: \"welcome\" }, [title, text]));\n scope.defer(\n store.subscribe((s, prev) => {\n if (s.user !== prev.user) render();\n }),\n );\n },\n unmount() {\n scope.dispose();\n clear(root);\n },\n };\n}\n", "// Scroll helpers for the message list (\u00A77.5).\n\nconst STICKY_PX = 80;\n\nexport interface ScrollBox {\n scrollTop: number;\n scrollHeight: number;\n clientHeight: number;\n}\n\n/** Within 80px of the bottom (or content shorter than the viewport). */\nexport function isNearBottom(el: ScrollBox): boolean {\n return el.scrollHeight - el.clientHeight - el.scrollTop <= STICKY_PX;\n}\n\nexport interface Anchor {\n el: HTMLElement;\n /** data-id of the element, to find it again if a re-render replaced it. */\n id: string | undefined;\n /** el.offsetTop \u2212 container.scrollTop when captured. */\n offset: number;\n}\n\n/** The first element matching `selector` at or below the current scroll position. */\nexport function captureAnchor(container: HTMLElement, selector: string): Anchor | null {\n const top = container.scrollTop;\n let candidate: HTMLElement | null = null;\n for (const el of container.querySelectorAll<HTMLElement>(selector)) {\n candidate = el;\n if (el.offsetTop >= top) break;\n }\n return candidate ? { el: candidate, id: candidate.dataset.id, offset: candidate.offsetTop - top } : null;\n}\n\n/** After the DOM changed above/below, scroll so the anchor sits where it was. */\nexport function restoreAnchor(container: HTMLElement, anchor: Anchor | null): void {\n if (!anchor) return;\n const el = container.contains(anchor.el)\n ? anchor.el\n : anchor.id\n ? container.querySelector<HTMLElement>(`[data-id=\"${CSS.escape(anchor.id)}\"]`)\n : null;\n if (el) container.scrollTop = el.offsetTop - anchor.offset;\n}\n", "// The user-facing text of views/room.ts (docs/REFACTOR.md item 56): one module per source file, so a lazy\n// screen's text stays in its own chunk. Copy changes here; a translation would replace these.\n\nexport const COULDNT_OPEN_ROOM_ACCESS_CHECK_YOUR = \"Couldn't open room access. Check your connection.\";\nexport const couldntSave = (why: string | number) => `Couldn't save. ${why}`;\nexport const BEGINNING_OF_THE_ROOM = \"Beginning of the room\";\nexport const beginningOf = (name: string | number) => `Beginning of #${name}`;\nexport const beginningOfYourConversationWith = (name: string | undefined) => `Beginning of your conversation with ${name ?? \"Unknown\"}`;\nexport const INSERT_EMOJI = \"Insert emoji\";\nexport const COULDNT_FORWARD_A_MESSAGE_WAS_DELETED = \"Couldn't forward. A message was deleted.\";\nexport const MESSAGE_FORWARDED = \"Message forwarded.\";\nexport const couldntForward = (why: string | number) => `Couldn't forward. ${why}`;\nexport const couldntDeleteThoseMessages = (why: string | number) => `Couldn't delete those messages. ${why}`;\nexport const COULDNT_OPEN_FORWARD_CHECK_YOUR_CONNECTION = \"Couldn't open Forward. Check your connection.\";\nexport const BACK_TO_REPLY = \"Back to reply\";\nexport const NEW_MESSAGES_JUMP_TO_LATEST = \"New messages \u00B7 Jump to latest\";\nexport const NEW_MESSAGES = \"New messages\";\nexport const JUMP_TO_LATEST = \"Jump to latest\";\nexport const couldntOpenThatConversation = (why: string | number) => `Couldn't open that conversation. ${why}`;\nexport const UNBANNED = \"Unbanned.\";\nexport const BANNED_THEY_CANT_SIGN_IN_UNTIL = \"Banned. They can't sign in until unbanned.\";\nexport const couldntBan = (banned: boolean, why: string | number) => `Couldn't ${banned ? \"ban\" : \"unban\"} them. ${why}`;\nexport const LOG_IN = \"Log in\";\nexport const BACK_TO_ROOMS = \"Back to rooms\";\nexport const THIS_ROOM_DOESNT_EXIST = \"This room doesn't exist.\";\nexport const YOU_CANT_SEE_THIS_ROOM_ANY = \"You can't see this room any more.\";\nexport const COULDNT_OPEN_SEARCH_CHECK_YOUR_CONNECTION = \"Couldn't open search. Check your connection.\";\nexport const COULDNT_SAVE_YOUR_EDIT = \"Couldn't save your edit.\";\nexport const COULDNT_DELETE_THIS_MESSAGE = \"Couldn't delete this message.\";\nexport const couldntRemoveYourReaction = (emoji: string | number) => `Couldn't remove your ${emoji} reaction.`;\nexport const couldntAddYourReaction = (emoji: string | number) => `Couldn't add your ${emoji} reaction.`;\nexport const ADD_REACTION = \"Add reaction\";\nexport const THIS_ROOM = \"this room\";\nexport const messagesForwarded = (n: string | number) => `${n} messages forwarded.`;\nexport const TO_SEE_MORE_ROOMS_OR = \" to see more rooms, or \";\nexport const GO_BACK_TO_THE_OPEN_AIR = \"go back to the Open Air rooms\";\n", "// A thin moving line over the room list or a room while it is being fetched (\u00A77.9): only once a fetch has taken\n// LOADBAR_MS, so a quick one shows nothing, and gone as soon as nothing is out.\n\nimport { h } from \"../dom.ts\";\n\nexport const LOADBAR_MS = 400;\n\nexport interface Loadbar {\n el: HTMLElement;\n /** Something is being fetched (true) or nothing is any more. */\n set(busy: boolean): void;\n}\n\nexport function createLoadbar(): Loadbar {\n const el = h(\"div\", { class: \"loadbar\", \"aria-hidden\": \"true\" });\n let timer: ReturnType<typeof setTimeout> | undefined;\n return {\n el,\n set(busy) {\n if (busy) timer ??= setTimeout(() => el.classList.add(\"on\"), LOADBAR_MS);\n else {\n clearTimeout(timer);\n timer = undefined;\n el.classList.remove(\"on\");\n }\n },\n };\n}\n", "// A room's collections (\u00A731): the badges on messages sent from a collection's items, and the save menu and the picker,\n// which are the collections' lazy chunk. Badges are asked for together after a render, and told live.\n// (In views/room.ts until REFACTOR item 53.)\n\nimport type { Ctx } from \"../../context.ts\";\nimport type { Badge, LocalFile, Message } from \"../../lib/types.ts\";\nimport type { Scope } from \"../../scope.ts\";\nimport * as S from \"../../strings/room-badges.ts\";\nimport { chunkContext, collectionChunk } from \"../collection.ts\";\n\n/** What the room's collections use of the room view. */\nexport interface RoomCollectionsHost extends Pick<Ctx, \"api\" | \"store\" | \"collections\"> {\n scope: Scope;\n /** Badges came in: draw the list again, keeping what is on screen where it is. */\n rerender: () => void;\n /** Items picked: they join the composer's tray. */\n addItems: (items: LocalFile[]) => void;\n /** Say something in the room's status line. */\n say: (text: string) => void;\n}\n\nexport interface RoomCollections {\n /** What collection `id`'s badge says: undefined while asked (a render asks), null for none. */\n badge(id: string): Badge | undefined;\n /** The save menu for a file of `m` (a forward's is its original's, \u00A721.3). */\n saveFile(m: Message, file: string, opener: HTMLElement): void;\n /** The picker: at most `max` items, which join the composer's tray. */\n pickItems(opener: HTMLElement, max: number): void;\n}\n\nexport function createRoomCollections({ api, store, collections, scope, rerender, addItems, say }: RoomCollectionsHost): RoomCollections {\n const { signal } = scope;\n /** What each collection's badge says, by id: undefined while asked. */\n const badges = new Map<string, Badge | undefined>();\n const asking = new Set<string>();\n let listening = false;\n\n function badge(id: string): Badge | undefined {\n if (!badges.has(id)) {\n badges.set(id, undefined);\n ask(id);\n // Told live when one is made public or private, renamed or deleted; asked again after a reconnect (missed).\n if (!listening) {\n listening = true;\n scope.sub(api.subscribeBadges(ask));\n scope.defer(api.onConnect((re) => re && [...badges.keys()].map(ask)));\n }\n }\n return badges.get(id);\n }\n /** Asked together, at the end of the task. A badge shown says what it said until the answer. */\n function ask(id: string) {\n if (!badges.has(id) || asking.has(id)) return;\n if (!asking.size) queueMicrotask(askBadges);\n asking.add(id);\n }\n function askBadges() {\n const ids = [...asking];\n asking.clear();\n for (let i = 0; i < ids.length; i += 50) {\n const some = ids.slice(i, i + 50);\n api.badges(some, signal).then(\n (got) => {\n for (const id of some) badges.set(id, got[id] ?? null);\n rerender();\n },\n () => {\n for (const id of some) badges.delete(id); // asked again by the next render\n },\n );\n }\n }\n\n const lazy = () => ({ ...chunkContext({ api, store, collections }), signal });\n const failed = () => scope.active && say(\"Couldn't open collections. Check your connection.\");\n\n return {\n badge,\n saveFile(m, file, opener) {\n collectionChunk().then(\n (c) => scope.active && void c.openSave({ ...lazy(), from: { message: m.forward_of || m.id, file }, opener }),\n failed,\n );\n },\n pickItems(opener, max) {\n collectionChunk().then(\n (c) =>\n scope.active &&\n void c.openPicker({\n ...lazy(),\n max,\n opener,\n onPick: (items) =>\n addItems(\n items.map((it) => ({\n file: new File([], it.name || it.file),\n url: it.video ? (it.poster ? api.itemPosterUrl(it) : \"\") : api.itemUrl(it, \"800x480f\"),\n item: { id: it.id, collection: it.collection },\n })),\n ),\n }),\n failed,\n );\n },\n };\n}\n", "// The collections icon (\u00A731), drawn by CSS (.ci in styles/app/collections.css): a picture with another behind it.\n\nimport { h } from \"../dom.ts\";\n\nexport const collectionIcon = (): HTMLElement => h(\"span\", { class: \"ci\", \"aria-hidden\": \"true\" });\n", "// \"\u22EF\" actions menu (\u00A77.1) used by room rows and the room header: a <details> disclosure with an optional\n// inline confirm step. It owns its open/confirm state and focus, so callers just hand it the current items.\n// Keyboard: Escape closes it and returns focus to the toggle; a confirm step focuses Cancel.\n\nimport { h } from \"../dom.ts\";\nimport * as S from \"../strings/ui-menu.ts\";\n\nexport interface MenuItem {\n label: string;\n run: () => void;\n /** Ask first: `text` is the question, `action` the label of the button that runs the item. */\n confirm?: { text: string; action: string };\n /** An icon (an .i-* class) before the label. */\n icon?: string;\n /** A setting turned on or off: shown as a switch. */\n checked?: boolean;\n /** Set apart from the items before it by a line. */\n sep?: boolean;\n /** A line under the label saying more. */\n hint?: string;\n /** What it is set to, on the right (a room's access: \"Private\"). */\n value?: string;\n}\n\nexport interface ActionMenu {\n readonly el: HTMLDetailsElement;\n /** Replace the items. Cheap when only their callbacks changed: the buttons are rebuilt only if labels did. */\n update(items: readonly MenuItem[]): void;\n close(): void;\n}\n\n/**\n * `label` names the menu for assistive tech. With `summary`, the toggle shows that text (which then is its name,\n * e.g. an author's name) instead of \"\u22EF\" (or `icon`, an .i-* class); `className` goes on the toggle.\n */\nexport function createActionMenu(opts: {\n label: string;\n summary?: string;\n className?: string;\n icon?: string;\n /** A line over the items, e.g. which instance an author is on (\u00A733.4). */\n note?: string | undefined;\n /**\n * The menu already drawn (a `details.menu` with its summary and `.menu-items`, as this would draw it), to make work:\n * the message list draws authors' menus as plain markup and makes one work when it is first opened (PERF.md \u00A75).\n */\n el?: HTMLDetailsElement;\n signal: AbortSignal;\n}): ActionMenu {\n const { signal } = opts;\n let items: readonly MenuItem[] = [];\n let shape = \"\";\n let confirming: string | null = null;\n\n const summary =\n (opts.el?.querySelector(\"summary\") as HTMLElement | null) ??\n (opts.summary\n ? h(\"summary\", { class: opts.className ?? \"\" }, opts.summary)\n : h(\"summary\", { \"aria-label\": opts.label, class: `ic ${opts.icon ?? \"i-dots\"} ${opts.className ?? \"\"}`.trim() }));\n const body = (opts.el?.querySelector(\".menu-items\") as HTMLElement | null) ?? h(\"div\", { class: \"menu-items\" });\n const el = opts.el ?? h(\"details\", { class: \"menu\" }, [summary, body]);\n el.addEventListener(\n \"toggle\",\n () => {\n if (el.open) {\n watchOutside();\n place();\n } else {\n outside?.abort();\n outside = null;\n if (confirming) setConfirming(null);\n }\n },\n { signal },\n );\n el.addEventListener(\n \"keydown\",\n (e) => {\n if (e.key !== \"Escape\" || !el.open) return;\n e.preventDefault();\n close();\n summary.focus();\n },\n { signal },\n );\n\n /** While open: listeners that close it when you click or tab anywhere else (QA BUG-46). */\n let outside: AbortController | null = null;\n function watchOutside() {\n if (outside || signal.aborted) return;\n outside = new AbortController();\n const opts = { capture: true, signal: outside.signal };\n const away = (e: Event) => {\n if (e.target instanceof Node && !el.contains(e.target)) close();\n };\n document.addEventListener(\"pointerdown\", away, opts);\n document.addEventListener(\"focusin\", away, opts);\n }\n signal.addEventListener(\"abort\", () => outside?.abort(), { once: true });\n if (el.open) watchOutside(); // made to work as it opens\n\n const button = (label: string, onClick: () => void, cls?: string, item?: MenuItem) =>\n h(\n \"button\",\n {\n type: \"button\",\n ...(cls ? { class: cls } : {}),\n // A switch, not a menuitemcheckbox: the items are buttons in a disclosure, not a role=menu (QA BUG-189).\n ...(item?.checked === undefined ? {} : { role: \"switch\", \"aria-checked\": String(item.checked) }),\n on: { click: onClick },\n signal,\n },\n item?.hint || item?.value\n ? [\n h(\"span\", { class: `tile ic ${item.icon}` }),\n h(\"span\", {}, [label, item.hint ? h(\"small\", {}, item.hint) : null]),\n item.value ? h(\"span\", { class: \"value\" }, item.value) : null,\n ]\n : label,\n );\n const find = (label: string | null) => items.find((i) => i.label === label);\n /**\n * Close, then run the item's *current* callback (items may have been updated since the button was built). Closing\n * redraws the items, so the focus they had goes back to the toggle, not to the page (QA BUG-190).\n */\n const runItem = (label: string) => {\n const item = find(label);\n const focused = el.contains(document.activeElement);\n close();\n if (focused) summary.focus();\n item?.run();\n };\n\n function render() {\n const item = find(confirming);\n if (item?.confirm) {\n const cancel = button(\n \"Cancel\",\n () => {\n setConfirming(null);\n summary.focus();\n },\n \"cancel\",\n );\n body.replaceChildren(\n h(\"p\", {}, item.confirm.text),\n button(item.confirm.action, () => runItem(item.label), \"danger\"),\n cancel,\n );\n return cancel;\n }\n body.replaceChildren(\n ...(opts.note ? [h(\"p\", {}, opts.note)] : []),\n ...items.map((i) =>\n button(\n i.label,\n () => {\n if (find(i.label)?.confirm) setConfirming(i.label)?.focus();\n else runItem(i.label);\n },\n [i.icon && !i.hint && !i.value ? `ic ${i.icon}` : \"\", i.sep ? \"sep\" : \"\"].join(\" \").trim(),\n i,\n ),\n ),\n );\n return null;\n }\n\n /**\n * Open upwards when the items would run past the bottom of what shows them (the message list ends at the composer:\n * an author's menu on the last message) and there is more room above (QA BUG-227). Again when the items change.\n */\n function place() {\n el.classList.remove(\"up\");\n if (!el.open) return;\n let clip = { top: 0, bottom: innerHeight };\n for (let p = el.parentElement; p; p = p.parentElement) {\n if (getComputedStyle(p).overflowY === \"visible\") continue;\n clip = p.getBoundingClientRect();\n break;\n }\n const at = summary.getBoundingClientRect();\n if (body.getBoundingClientRect().bottom > clip.bottom && at.top - clip.top > clip.bottom - at.bottom) el.classList.add(\"up\");\n }\n\n /** Enter or leave the confirm step; returns the Cancel button when entering one. */\n function setConfirming(label: string | null) {\n confirming = label;\n const cancel = render();\n place();\n return cancel;\n }\n\n function close() {\n el.open = false;\n outside?.abort();\n outside = null;\n confirming = null;\n render();\n }\n\n return {\n el,\n update(next) {\n items = next;\n const nextShape = JSON.stringify(next.map((i) => [i.label, i.confirm ?? null, i.icon, i.checked, i.sep, i.hint, i.value]));\n const stale = confirming !== null && !find(confirming)?.confirm;\n if (stale) confirming = null;\n if (nextShape === shape && !stale) return; // same buttons; they look their item up when clicked\n shape = nextShape;\n render();\n place();\n },\n close,\n };\n}\n", "// Message composer (\u00A77.6, \u00A717.4): auto-growing textarea, character counter, Enter to send, Shift+Enter for a\n// newline, Up arrow in an empty composer to edit your last message, Ctrl+Up/Down to pick the message replied to, attachments (picker, paste, drop) shown\n// in a tray above the textarea, the message being replied to (\u00A719) above that, and an emoji button (\u00A720.4). Typing\n// \":name\" asks for emoji suggestions (\u00A720.6). Ctrl+/ (\u2318/) anywhere in the room focuses it, which a key badge says while\n// it isn't focused (\u00A77.6).\n\nimport { h } from \"../../dom.ts\";\nimport { checkFiles, formatBytes, isVideo } from \"../../lib/files.ts\";\nimport { prepareImage } from \"../../lib/image.ts\";\nimport { LIMITS, textLength } from \"../../lib/limits.ts\";\nimport type { LocalFile } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-composer.ts\";\nimport { collectionIcon } from \"../../ui/icon.ts\";\nimport { createActionMenu } from \"../../ui/menu.ts\";\n\nconst MAX_LEN = LIMITS.messageText;\nconst COUNTER_FROM = 1800;\nconst MAX_ROWS = 6;\n\n/** Zero-width and bidi format characters: text made only of these is blank to the server (INVISIBLE in pb_hooks/lib/text.js). */\nconst INVISIBLE = /[\u00AD\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u2069\uFEFF]/g;\n\n/** Does trimmed `t` show anything? The server refuses text that doesn't (QA BUG-42). */\nconst isBlank = (t: string) => t.replace(INVISIBLE, \"\").trim() === \"\";\n\n/** Trimmed text that may be sent or saved, or null. Length in code points, as the server counts it. */\nexport function validText(raw: string): string | null {\n const t = raw.trim();\n return !isBlank(t) && textLength(t) <= MAX_LEN ? t : null;\n}\n\n/** Like validText, but next to attachments the text may be empty (\u00A717.1). */\nexport function validEdit(raw: string, hasFiles: boolean): string | null {\n if (!hasFiles) return validText(raw);\n const t = raw.trim();\n return textLength(t) <= MAX_LEN ? t : null;\n}\n\n/** Longest edge of an attached image after preparation (\u00A715.3). */\nconst IMAGE_EDGE = 2048;\n\n/** Images get a preview in the tray (never SVG: it is shown as a file), and so do videos (their first frame). */\nconst previewable = (f: File) => f.type.startsWith(\"image/\") && f.type !== \"image/svg+xml\";\n\n/**\n * Why an edit of `raw` can't be saved, as a sentence; \"\" when it can. A message with attachments may be left\n * without text (\u00A717.1).\n */\nexport function editProblem(raw: string, hasFiles = false): string {\n const len = textLength(raw.trim());\n if (isBlank(raw) && !hasFiles) return \"A message can't be empty. Use Delete to remove it.\";\n return len > MAX_LEN ? `Too long: ${len - MAX_LEN} characters over the ${MAX_LEN} limit.` : \"\";\n}\n\n/**\n * Is this key part of typing with an input method (IME)? Safari ends the composition before the keydown of the Enter\n * that confirms it, so only its keyCode (229) says so: without it, picking a Japanese or Chinese word would send.\n */\nexport const composing = (e: KeyboardEvent) => e.isComposing || e.keyCode === 229;\n\n/** Rows for a textarea showing `text` (grows with its lines, up to 6). */\nexport const rowsFor = (text: string) => Math.min(MAX_ROWS, text.split(\"\\n\").length);\n\n/**\n * Size a textarea to its content, up to 6 rows, counting lines that wrap as well as explicit newlines.\n * Without layout (scrollHeight 0, e.g. in tests) it falls back to counting newlines.\n */\nexport function fitRows(t: HTMLTextAreaElement): void {\n t.rows = 1;\n const style = getComputedStyle(t);\n const line = Number.parseFloat(style.lineHeight) || 1.2 * (Number.parseFloat(style.fontSize) || 16);\n const padding = (Number.parseFloat(style.paddingTop) || 0) + (Number.parseFloat(style.paddingBottom) || 0);\n const wrapped = t.scrollHeight > 0 ? Math.round((t.scrollHeight - padding) / line) : 0;\n t.rows = Math.min(MAX_ROWS, Math.max(rowsFor(t.value), wrapped, 1));\n}\n\nexport interface Composer {\n readonly el: HTMLFormElement;\n /** The text typed so far (a draft to keep), and replacing it. */\n text(): string;\n setText(text: string): void;\n setPlaceholder(text: string): void;\n focus(): void;\n /** Add attachments (e.g. dropped on the room). Images are prepared first (\u00A715.3). */\n addFiles(files: readonly File[]): Promise<void>;\n /** Add items from collections (\u00A731): they go after the uploads, as the server attaches them. */\n addItems(items: readonly LocalFile[]): void;\n /** Show who and what the next message replies to (\u00A719), or nothing. */\n setReply(reply: { name: string; text: string } | null): void;\n}\n\nexport function createComposer(opts: {\n id: string;\n /**\n * Called with trimmed text (valid, or \"\" when there are attachments) and the attachments. Return false to\n * refuse (everything stays in the composer). On true, the attachments' preview URLs belong to the caller.\n */\n onSend: (text: string, files: LocalFile[]) => boolean;\n /** Up arrow in an empty composer. Return true if it was handled (an edit started). */\n onEditLast: () => boolean;\n /** Ctrl+Up / Ctrl+Down: reply to an older (-1) or newer (1) message. Return true if it was handled. */\n onStepReply?: (dir: -1 | 1) => boolean;\n /** The reply bar's \u00D7 (or Escape in the textarea while replying). */\n onCancelReply: () => void;\n /** The emoji button: open the picker next to it; `insert` puts the chosen emoji at the caret. */\n onEmoji: (opener: HTMLElement, insert: (emoji: string) => void) => void;\n /** \":\" and two letters typed before the caret: offer emoji by name (\u00A720.6). Those follow the textarea from then on. */\n onEmojiName?: (textarea: HTMLTextAreaElement) => void;\n /** An \"@\" typed (\u00A741): offer people by handle. Those follow the textarea from then on. */\n onMention?: (textarea: HTMLTextAreaElement) => void;\n /** The text changed (typed, inserted, sent or replaced): e.g. to keep it as a draft. */\n onChange?: (text: string) => void;\n /** Attach from collections (\u00A731): offer at most `room` items next to `opener` (they come back through addItems). */\n onCollections?: (opener: HTMLElement, room: number) => void;\n signal: AbortSignal;\n}): Composer {\n const { signal } = opts;\n const mac = /Mac|iP/.test(navigator.platform);\n const textarea = h(\"textarea\", {\n name: \"text\",\n rows: 1,\n id: opts.id,\n autocomplete: \"off\",\n \"aria-keyshortcuts\": mac ? \"Meta+/\" : \"Control+/\",\n });\n // The placeholder as given, and cut to the box with \"\u2026\": browsers ignore text-overflow on a textarea's placeholder,\n // so a long room or person name was cut off mid-word.\n let placeholder = \"\";\n let measure: CanvasRenderingContext2D | null | undefined;\n function fitPlaceholder() {\n let text = placeholder;\n measure ??= document.createElement(\"canvas\").getContext?.(\"2d\");\n const width = textarea.clientWidth - 12;\n if (measure && width > 0) {\n // Not the `font` shorthand: it reads \"\" while font-feature-settings is set (BUG-191).\n const css = getComputedStyle(textarea);\n measure.font = `${css.fontStyle} ${css.fontWeight} ${css.fontSize} ${css.fontFamily}`;\n while (text.length > 1 && measure.measureText(text === placeholder ? text : `${text}\u2026`).width > width) text = text.slice(0, -1);\n if (text !== placeholder) text = `${text.trimEnd()}\u2026`;\n }\n if (textarea.placeholder !== text) textarea.placeholder = text;\n }\n if (typeof ResizeObserver === \"function\") {\n const resizes = new ResizeObserver(fitPlaceholder);\n resizes.observe(textarea);\n signal.addEventListener(\"abort\", () => resizes.disconnect());\n }\n const counter = h(\"span\", { class: \"counter\", \"aria-live\": \"polite\" });\n const sendBtn = h(\"button\", { type: \"submit\", class: \"send ic i-send\", \"aria-label\": \"Send\", title: \"Send\", disabled: true });\n const fileInput = h(\"input\", {\n id: `${opts.id}-files`,\n type: \"file\",\n multiple: true,\n class: \"visually-hidden\",\n tabindex: -1,\n \"aria-label\": \"Attach files\",\n });\n const { onCollections } = opts;\n // With collections (\u00A731) the paperclip offers both; without, it opens the file chooser.\n const attachMenu = onCollections && createActionMenu({ label: \"Attach\", icon: \"i-clip\", className: \"attach\", signal });\n attachMenu?.update([\n { label: \"Upload file\", hint: \"Photo, video or document\", icon: \"i-upload\", run: () => fileInput.click() },\n {\n label: \"From collection\",\n hint: \"Pick from your saved media\",\n icon: \"i-media\",\n run: () => onCollections!(attachMenu.el.firstElementChild as HTMLElement, Math.max(0, LIMITS.attachments - files.length)),\n },\n ]);\n const attach =\n attachMenu?.el ??\n h(\"button\", { type: \"button\", class: \"icon-button attach ic i-clip\", title: \"Attach files\", \"aria-label\": \"Attach files\" });\n const emojiBtn = h(\"button\", {\n type: \"button\",\n class: \"icon-button emoji-button ic i-smile\",\n title: \"Emoji\",\n \"aria-label\": \"Emoji\",\n \"aria-haspopup\": \"dialog\",\n \"aria-expanded\": \"false\",\n on: { click: () => opts.onEmoji(emojiBtn, insertEmoji) },\n signal,\n });\n const tray = h(\"ul\", { class: \"tray\", \"aria-label\": \"Attachments\" });\n const trayError = h(\"p\", { class: \"tray-error\", role: \"alert\" });\n const replyLabel = h(\"span\", { class: \"replying-label\" });\n const replyBar = h(\"div\", { class: \"replying ic i-reply\", hidden: true }, [\n replyLabel,\n h(\"button\", {\n type: \"button\",\n class: \"icon-button remove ic i-x\",\n \"aria-label\": \"Cancel reply\",\n title: \"Cancel reply\",\n on: { click: () => cancelReply() },\n signal,\n }),\n ]);\n\n /** Put `emoji` where the caret is (replacing any selection), and the caret after it. */\n function insertEmoji(emoji: string) {\n if (signal.aborted) return;\n textarea.focus();\n textarea.setRangeText(emoji, textarea.selectionStart, textarea.selectionEnd, \"end\");\n onInput();\n }\n\n function cancelReply() {\n opts.onCancelReply();\n textarea.focus();\n }\n\n let files: LocalFile[] = [];\n /** Attachments still being prepared: Send waits for them. */\n let preparing = 0;\n\n /** What Send would send: valid text, or attachments with text that isn't too long. */\n function sendable(): string | null {\n return validEdit(textarea.value, files.length > 0);\n }\n\n function onInput() {\n // Count what would be sent (trimmed, in code points), so the counter agrees with the Send button.\n const len = textLength(textarea.value.trim());\n counter.textContent = len <= COUNTER_FROM ? \"\" : len <= MAX_LEN ? `${MAX_LEN - len} left` : `${len - MAX_LEN} over`;\n fitRows(textarea);\n sendBtn.disabled = preparing > 0 || sendable() === null;\n opts.onChange?.(textarea.value);\n }\n\n function renderTray() {\n tray.replaceChildren(\n ...files.map((f) =>\n h(\"li\", { class: \"tray-item\" }, [\n f.item && !f.url\n ? collectionIcon()\n : !f.url\n ? h(\"span\", { class: \"tray-icon\", \"aria-hidden\": \"true\" }, \"\uD83D\uDCC4\")\n : h(isVideo(f.file.name) && !f.item ? \"video\" : \"img\", {\n class: \"tray-thumb\",\n src: isVideo(f.file.name) && !f.item ? `${f.url}#t=0.001` : f.url,\n width: 40,\n height: 40,\n alt: \"\",\n }),\n h(\"span\", { class: \"tray-name\" }, f.file.name),\n h(\"span\", { class: \"tray-size\" }, f.item ? \"From a collection\" : formatBytes(f.file.size)),\n h(\n \"button\",\n { type: \"button\", class: \"remove\", \"aria-label\": `Remove ${f.file.name}`, on: { click: () => removeFile(f) }, signal },\n \"\u00D7\",\n ),\n ]),\n ),\n );\n tray.hidden = files.length === 0;\n onInput();\n }\n\n function removeFile(f: LocalFile) {\n if (f.url && !f.item) URL.revokeObjectURL(f.url);\n files = files.filter((x) => x !== f);\n trayError.textContent = \"\";\n renderTray();\n textarea.focus();\n }\n\n async function addFiles(added: readonly File[]) {\n if (!added.length || signal.aborted) return;\n preparing++;\n onInput();\n const prepared = await Promise.all(added.map((f) => (previewable(f) ? prepareImage(f, IMAGE_EDGE) : Promise.resolve(f))));\n preparing--;\n if (signal.aborted) return;\n const { accepted, rejected } = checkFiles(\n files.map((f) => f.file),\n prepared,\n );\n files = [\n ...files.filter((f) => !f.item),\n ...accepted.map((file) => ({ file, url: previewable(file) || isVideo(file.name) ? URL.createObjectURL(file) : \"\" })),\n ...files.filter((f) => f.item),\n ];\n trayError.textContent = rejected.map((r) => `\u201C${r.name}\u201D: ${r.reason}.`).join(\" \");\n renderTray();\n }\n\n function addItems(items: readonly LocalFile[]) {\n if (signal.aborted) return;\n const fresh = items.filter((it) => !files.some((f) => f.item?.id === it.item?.id));\n const room = Math.max(0, LIMITS.attachments - files.length);\n files = [...files, ...fresh.slice(0, room)];\n trayError.textContent = fresh.length > room ? `At most ${LIMITS.attachments} files per message.` : \"\";\n renderTray();\n textarea.focus();\n }\n\n function submit() {\n const text = sendable();\n if (text === null || preparing > 0 || !opts.onSend(text, files)) return;\n textarea.value = \"\";\n files = []; // the sent message owns their preview URLs now\n trayError.textContent = \"\";\n renderTray();\n }\n\n if (!attachMenu) attach.addEventListener(\"click\", () => fileInput.click(), { signal });\n fileInput.addEventListener(\n \"change\",\n () => {\n const picked = [...(fileInput.files ?? [])];\n fileInput.value = \"\";\n void addFiles(picked);\n },\n { signal },\n );\n textarea.addEventListener(\n \"paste\",\n (e) => {\n const pasted = [...(e.clipboardData?.files ?? [])];\n if (!pasted.length) return;\n e.preventDefault();\n void addFiles(pasted);\n },\n { signal },\n );\n signal.addEventListener(\n \"abort\",\n () => {\n for (const f of files) if (f.url && !f.item) URL.revokeObjectURL(f.url);\n },\n { once: true },\n );\n\n textarea.addEventListener(\"input\", onInput, { signal });\n textarea.addEventListener(\n \"input\",\n () => {\n const before = textarea.value.slice(0, textarea.selectionStart);\n if (/(?<=^|[\\s(]):[\\w+-]{2,}$/.test(before)) opts.onEmojiName?.(textarea);\n if (/(^|[^\\w@./])@\\w*$/.test(before)) opts.onMention?.(textarea);\n },\n { signal },\n );\n textarea.addEventListener(\n \"keydown\",\n (e) => {\n if (e.key === \"Enter\" && !e.shiftKey && !composing(e)) {\n e.preventDefault();\n submit();\n } else if (\n (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") &&\n e.ctrlKey &&\n !(e.altKey || e.metaKey || e.shiftKey) &&\n opts.onStepReply?.(e.key === \"ArrowUp\" ? -1 : 1)\n ) {\n e.preventDefault();\n } else if (e.key === \"ArrowUp\" && !e.ctrlKey && textarea.value === \"\" && opts.onEditLast()) {\n e.preventDefault();\n } else if (e.key === \"Escape\" && !composing(e) && !replyBar.hidden) {\n // (While composing, Escape belongs to the input method: it cancels the composition.)\n e.preventDefault();\n cancelReply();\n }\n },\n { signal },\n );\n\n const el = h(\n \"form\",\n {\n class: \"composer\",\n on: {\n submit: (e) => {\n e.preventDefault();\n submit();\n },\n },\n signal,\n },\n [\n replyBar,\n h(\"div\", { class: \"tray-wrap\" }, [tray, trayError]),\n h(\"div\", { class: \"composer-row\" }, [\n fileInput,\n attach,\n h(\"label\", { for: opts.id, class: \"visually-hidden\" }, \"Message\"),\n textarea,\n h(\"kbd\", { class: \"focus-key\", \"aria-hidden\": \"true\", title: \"Focus the message box\" }, mac ? \"\u2318/\" : \"Ctrl /\"),\n counter,\n emojiBtn,\n sendBtn,\n ]),\n ],\n );\n tray.hidden = true;\n\n return {\n el,\n addFiles,\n addItems,\n text: () => textarea.value,\n setText(text) {\n textarea.value = text;\n onInput();\n },\n setPlaceholder(text) {\n placeholder = text;\n fitPlaceholder();\n },\n focus() {\n textarea.focus();\n },\n setReply(reply) {\n replyBar.hidden = !reply;\n replyLabel.replaceChildren(\n ...(reply ? [\"Replying to \", h(\"strong\", {}, reply.name), h(\"span\", { class: \"replying-text\" }, reply.text)] : []),\n );\n },\n };\n}\n", "// Client-generated record ids (\u00A77.5): PocketBase's default id format, 15 chars of [a-z0-9].\n\nconst ALPHABET = \"abcdefghijklmnopqrstuvwxyz0123456789\";\nconst LENGTH = 15;\n// Largest multiple of 36 below 256: bytes at or above it are rejected to avoid modulo bias.\nconst LIMIT = 256 - (256 % ALPHABET.length);\n\nexport function newId(): string {\n let id = \"\";\n const buf = new Uint8Array(LENGTH * 2);\n while (id.length < LENGTH) {\n crypto.getRandomValues(buf);\n for (const b of buf) {\n if (b < LIMIT) id += ALPHABET[b % ALPHABET.length];\n if (id.length === LENGTH) break;\n }\n }\n return id;\n}\n", "// The user-facing text of lib/reactions.ts (docs/REFACTOR.md item 56): one module per source file, so a lazy\n// screen's text stays in its own chunk. Copy changes here; a translation would replace these.\n\nexport const and = (first: string, last: string | undefined) => `${first} and ${last}`;\nexport const YOU = \"You\";\n/** The people reacted with no name known: after names, \"and 2 others\"; alone, \"3 people\". */\nexport const others = (n: number) => `${n} ${n === 1 ? \"other\" : \"others\"}`;\nexport const people = (n: number) => `${n} ${n === 1 ? \"person\" : \"people\"}`;\n", "// Emoji reactions (\u00A720): pure helpers for showing them and for changing them optimistically.\n\nimport * as S from \"../strings/lib-reactions.ts\";\nimport type { Reaction } from \"./types.ts\";\n\n/**\n * `list` with `user`'s `emoji` reaction added (`on`) or removed, the way the server does it\n * (pb_hooks/lib/reactions.js): a new emoji goes last, one nobody uses any more goes away. Same list when unchanged.\n */\nexport function setReaction(list: readonly Reaction[], emoji: string, user: string, on: boolean): readonly Reaction[] {\n const r = list.find((x) => x.emoji === emoji);\n if (r && r.users.includes(user) === on) return list;\n if (!on && !r) return list;\n if (on) return r ? list.map((x) => (x === r ? { emoji, users: [...x.users, user] } : x)) : [...list, { emoji, users: [user] }];\n return list.map((x) => (x === r ? { emoji, users: x.users.filter((u) => u !== user) } : x)).filter((x) => x.users.length > 0);\n}\n\n/** \"You\", \"You and Ada\", \"Ada, Bob and 3 others\": who reacted, with names where they are known. */\nexport function reactors(users: readonly string[], me: string, names: (id: string) => string | undefined): string {\n const known: string[] = [];\n let others = 0;\n for (const id of users) {\n const name = id === me ? \"You\" : names(id);\n if (name === undefined) others++;\n else if (id === me) known.unshift(name);\n else known.push(name);\n }\n // Long lists name the first few, then count the rest.\n const shown = known.slice(0, 5);\n others += known.length - shown.length;\n if (others) shown.push(shown.length ? S.others(others) : S.people(others));\n if (shown.length === 1) return shown[0]!;\n return `${shown.slice(0, -1).join(\", \")} and ${shown.at(-1)}`;\n}\n", "// What the room controller (controller.ts) writes: sending (\u00A77.5, \u00A717.4, \u00A719), edits and deletes, deleting several\n// messages at once (\u00A721) and reactions (\u00A720). Each is shown at once and then made good, or undone, by the server's\n// answer; writes go one at a time per message, in the order they were made.\n\nimport { type Api, ApiError, reasonOf } from \"../../api.ts\";\nimport { newId } from \"../../lib/id.ts\";\nimport { type MessageWindow, merge, quoteOf, remove, trim } from \"../../lib/messages.ts\";\nimport { setReaction } from \"../../lib/reactions.ts\";\nimport { parsePb, toPb } from \"../../lib/time.ts\";\nimport type { LocalFile, Message, Reaction, User } from \"../../lib/types.ts\";\nimport type { Scope } from \"../../scope.ts\";\nimport type { Change } from \"./controller.ts\";\n\n/**\n * Sends that failed, by room, kept for its next view when the view went: those that failed after it had gone (another\n * room was opened while they were on their way), and those it showed as not sent (QA BUG-119). The next view shows\n * them as not sent, with Retry: otherwise what was written would be lost without a word, as the composer and the draft\n * were cleared on sending.\n */\nconst strays = new Map<string, Message[]>();\n/** Keep a failed send for the room's next view. Its previews went with the view: its files show by name. */\nexport function stray(m: Message) {\n const files = m.localFiles?.map((f) => ({ ...f, url: \"\" }));\n strays.set(m.room, [...(strays.get(m.room) ?? []), { ...m, ...(files && { localFiles: files }) }]);\n}\n/** The failed sends kept for this room's view (taken: the next view won't get them again). */\nexport function takeStrays(roomId: string): Message[] {\n const out = strays.get(roomId) ?? [];\n strays.delete(roomId);\n return out;\n}\n\n/** Release a local message's preview URLs (sent, discarded, or the room is going away). */\nexport const revokeLocal = (m: Message | undefined) => {\n for (const f of m?.localFiles ?? []) if (f.url) URL.revokeObjectURL(f.url);\n};\n\n/** What the writes use of the controller. */\nexport interface WriteCtx {\n api: Api;\n roomId: string;\n scope: Scope;\n me: () => User | null;\n posting: () => boolean;\n editable: (m: Message) => boolean;\n deletable: (m: Message) => boolean;\n /** The window, and replacing it as it is (no unsent messages are set aside: these writes keep them). */\n win: () => MessageWindow;\n put: (next: MessageWindow) => void;\n find: (id: string) => Message | undefined;\n /** Local optimistic change that must win regardless of `updated` (edit/delete/revert). */\n patchLocal: (id: string, patch: Partial<Message>) => void;\n emit: (change?: Change) => void;\n /** The change for messages changed where they are. */\n inPlace: () => Change;\n /** Go back to the live edge, for a message sent from history. */\n toLatest: () => Promise<void>;\n /** A message sent: no pill. */\n clearPill: () => void;\n /** Unsent messages the window dropped (controller.ts), updated as their sends end. */\n unsent: Map<string, Message>;\n onUpload?: ((id: string, fraction: number) => void) | undefined;\n}\n\nexport function createWrites(ctx: WriteCtx) {\n const { api, roomId, scope, me, find, patchLocal, emit, inPlace, unsent } = ctx;\n /**\n * My reaction changes still on their way, by message id and emoji: whether it should be there, and which change said\n * so last. They show over every copy of the message until that change is answered (\u00A720.3).\n */\n const reacting = new Map<string, Map<string, { on: boolean; seq: number }>>();\n /**\n * Writes go one at a time, so the server applies them in the order they were made: sends (key \"\"), and each message's\n * edits, deletes and reactions (key: its id). Two at once can land the other way round: a message with an attachment\n * after the text sent just after it, or an older edit over a newer one.\n */\n const queues = new Map<string, Promise<unknown>>();\n const inTurn = <T>(key: string, write: () => Promise<T>): Promise<T> => {\n const run = (queues.get(key) ?? Promise.resolve()).then(write);\n const done = run.catch(() => {});\n queues.set(key, done);\n void done.then(() => queues.get(key) === done && queues.delete(key));\n return run;\n };\n let reactSeq = 0;\n\n // ---------------------------------------------------------------- sending\n\n function send(text: string, files: LocalFile[] = [], replyTo?: Message): boolean {\n const user = me();\n if (!user || !ctx.posting()) return false;\n const quoted = replyTo ? quoteOf(replyTo) : undefined;\n void (async () => {\n if (ctx.win().hasNewer) await ctx.toLatest();\n const last = ctx.win().items.at(-1);\n const created = toPb(Math.max(Date.now(), last ? parsePb(last.created) + 1 : 0));\n const msg: Message = {\n id: newId(),\n room: roomId,\n author: user.id,\n text,\n created,\n updated: created,\n edited_at: \"\",\n deleted: false,\n expand: { author: { id: user.id, name: user.name, avatar: user.avatar ?? \"\" }, ...(quoted ? { reply_to: quoted } : {}) },\n ...(quoted ? { reply_to: quoted.id } : {}),\n status: \"pending\",\n ...(files.length ? { localFiles: files } : {}),\n };\n ctx.put(trim(merge(ctx.win(), [msg]), \"top\").win);\n ctx.clearPill();\n emit({ render: {}, scroll: \"bottom\" });\n await inTurn(\"\", () => deliver(msg));\n })();\n return true;\n }\n\n async function deliver(msg: Message) {\n // A reply whose original has been deleted meanwhile can only go without its quote (\u00A719): Retry sends it so.\n const quoted = msg.expand?.reply_to;\n const replyTo = msg.reply_to && !(find(msg.reply_to) ?? quoted)?.deleted ? msg.reply_to : undefined;\n let saved: Message | null = null;\n let failed: Message | null = null;\n try {\n const files = msg.localFiles?.filter((f) => !f.item).map((f) => f.file);\n const items = msg.localFiles?.flatMap((f) => (f.item ? [f.item.id] : []));\n saved = await api.send(\n {\n id: msg.id,\n room: msg.room,\n text: msg.text,\n ...(files?.length ? { files } : {}),\n ...(items?.length ? { items } : {}),\n ...(replyTo ? { replyTo } : {}),\n },\n (fraction) => ctx.onUpload?.(msg.id, fraction),\n );\n } catch (e) {\n // A retry of a send that already reached the server fails with a duplicate id: it was sent after all.\n const recovered = e instanceof ApiError && e.status === 400 ? await api.getMessage(msg.id).catch(() => null) : null;\n if (recovered && recovered.author === me()?.id) saved = recovered;\n else {\n const replyGone = e instanceof ApiError && \"reply_to\" in e.fields && quoted;\n failed = {\n ...msg,\n status: \"failed\",\n ...(replyGone ? { expand: { ...msg.expand, reply_to: { ...quoted, text: \"\", deleted: true } } } : {}),\n };\n // The server says the original is deleted, though the window may not have heard yet.\n if (replyGone && find(quoted.id)) patchLocal(quoted.id, { text: \"\", deleted: true });\n }\n }\n // The server has the files now: the previews can go, even if the room was left meanwhile (its echo may already have\n // replaced the pending copy, whose previews nothing else would release; QA BUG-70).\n if (saved) revokeLocal(msg);\n if (!scope.active) {\n if (failed) stray(failed);\n return;\n }\n // The window may have moved back in history meanwhile (a quote, a jump): then the message isn't in it, and\n // must not be put after older messages. Sent, it shows once the window is back at the live edge.\n if (saved) {\n unsent.delete(msg.id);\n if (find(msg.id)) ctx.put(merge(ctx.win(), [saved]));\n } else if (failed && find(msg.id)?.status) ctx.put(merge(ctx.win(), [failed]));\n else if (failed && unsent.has(msg.id)) unsent.set(msg.id, failed);\n emit({ render: {} });\n }\n\n async function retrySend(id: string) {\n const m = find(id);\n if (m?.status !== \"failed\") return;\n patchLocal(id, { status: \"pending\" });\n emit({ render: {} });\n await inTurn(\"\", () => deliver({ ...m, status: \"pending\" }));\n }\n\n function discard(id: string) {\n revokeLocal(find(id));\n ctx.put(remove(ctx.win(), id));\n emit({ render: {} });\n }\n\n // ---------------------------------------------------------------- edit / delete\n\n /** Show `patch` right away; keep the server's copy, or put `before` back if the request fails. */\n async function optimistic(id: string, patch: Partial<Message>, before: Partial<Message>, request: () => Promise<Message>) {\n patchLocal(id, patch);\n emit(inPlace());\n let ok = true;\n try {\n const saved = await inTurn(id, request);\n if (scope.active) ctx.put(merge(ctx.win(), [saved]));\n } catch {\n if (!scope.active) return false;\n patchLocal(id, before);\n ok = false;\n }\n emit(inPlace());\n return ok;\n }\n\n function edit(id: string, text: string) {\n const m = find(id);\n // Deleted elsewhere or the room was archived while the edit box was open: nothing left to save.\n if (!m || !ctx.editable(m) || text === m.text) return null;\n return optimistic(id, { text, previews: [] }, { text: m.text, edited_at: m.edited_at, previews: m.previews ?? [] }, () =>\n api.edit(id, text),\n );\n }\n\n function removeMessage(id: string) {\n const m = find(id);\n if (!m) return null;\n // Someone else's, or a moderator's own where they can't post (\u00A736): only the delete route allows it.\n const own = m.author === me()?.id && ctx.posting();\n const remove = own ? () => api.softDelete(id) : async () => (await api.deleteMany([id]))[0]!;\n return optimistic(id, { text: \"\", deleted: true }, { text: m.text, deleted: false }, remove);\n }\n\n function removeMany(ids: readonly string[]) {\n const ms = ids.flatMap((id) => {\n const m = find(id);\n return m && ctx.deletable(m) ? [m] : [];\n });\n return ms.length ? deleteAll(ms) : null;\n }\n\n async function deleteAll(ms: Message[]): Promise<unknown> {\n for (const m of ms) patchLocal(m.id, { text: \"\", deleted: true });\n emit(inPlace());\n let failure: unknown = null;\n try {\n const saved = await api.deleteMany(ms.map((m) => m.id));\n if (scope.active)\n ctx.put(\n merge(\n ctx.win(),\n saved.filter((m) => find(m.id)),\n ),\n );\n } catch (e) {\n if (!scope.active) return e;\n for (const m of ms) patchLocal(m.id, { text: m.text, deleted: false });\n failure = e;\n }\n emit(inPlace());\n return failure;\n }\n\n // ---------------------------------------------------------------- reactions\n\n function reactions(m: Message): readonly Reaction[] {\n let list: readonly Reaction[] = m.reactions ?? [];\n const mine = reacting.get(m.id);\n const user = me()?.id;\n if (mine && user) for (const [emoji, p] of mine) list = setReaction(list, emoji, user, p.on);\n return list;\n }\n\n async function react(id: string, emoji: string, on: boolean): Promise<boolean | string> {\n const seq = ++reactSeq;\n const mine = reacting.get(id) ?? new Map();\n const latest = () => mine.get(emoji)?.seq === seq;\n const request = async () => {\n if (!latest()) return true; // changed again before it went out: the later change says what to send\n try {\n const saved = await api.react(id, emoji, on);\n // The whole message comes back: kept like any other copy (the newest wins).\n if (scope.active && find(id)) ctx.put(merge(ctx.win(), [saved]));\n return true;\n } catch (e) {\n // Refused (a 4xx but 429): why, and no retry.\n return e instanceof ApiError && e.status >= 400 && e.status < 500 && e.status !== 429 ? reasonOf(e) : false;\n }\n };\n const queue = inTurn(id, request);\n reacting.set(id, mine.set(emoji, { on, seq }));\n emit(inPlace());\n const ok = await queue;\n // Changed again meanwhile: the later change shows, and says whether it worked.\n if (!latest()) return true;\n if (!scope.active) return ok;\n mine.delete(emoji);\n if (!mine.size && reacting.get(id) === mine) reacting.delete(id);\n emit(inPlace());\n return ok;\n }\n\n return { send, retrySend, discard, edit, remove: removeMessage, removeMany, reactions, react };\n}\n", "// Room controller (\u00A77.5, \u00A77.6): one room's message window and everything that changes it: loading, realtime and\n// reconnects here, and the writes (sending, edits, deletes, reactions) in writes.ts. No DOM: every change is reported to\n// `onChange` with a hint (render, keep the anchor, scroll), and the room view (views/room.ts) applies it to the list.\n\nimport { type Action, type Api, ApiError } from \"../../api.ts\";\nimport type { Cache } from \"../../cache.ts\";\nimport { type Cursor, changedIn, first, latest, newer, older, PAGE_SIZE } from \"../../lib/cursor.ts\";\nimport {\n applyPage,\n compare,\n emptyWindow,\n lastOwnEditable,\n lastSaved,\n type MessageWindow,\n merge,\n type PageKind,\n remove,\n trim,\n} from \"../../lib/messages.ts\";\nimport { canPost, isDm } from \"../../lib/rooms.ts\";\nimport type { LocalFile, Message, Quoted, Reaction, Room } from \"../../lib/types.ts\";\nimport type { EarlyPage } from \"../../prefetch.ts\";\nimport type { Scope } from \"../../scope.ts\";\nimport { type AppState, type Store, UNCOUNTED, upsertRoom } from \"../../store.ts\";\nimport * as S from \"../../strings/room-controller.ts\";\nimport { createWrites, revokeLocal, stray, takeStrays } from \"./writes.ts\";\n\n/** How long a message gone to (a quote, a link) stays highlighted; styles/app/messages.css fades it out over this time. */\nexport const HIGHLIGHT_MS = 3000;\n/** How long the line over the first unread message shows; styles/app/messages.css fades it out before then. */\nexport const UNREAD_LINE_MS = 5000;\n/** How many replies \"Back to reply\" remembers (\u00A719.5); the oldest go first. */\nconst BACK_MAX = 50;\n\n/** \"loading\" until the first page is in; \"failed\" offers Retry; \"not-found\": no such room (or not yours). */\nexport type Phase = \"loading\" | \"ready\" | \"failed\" | \"not-found\";\n/** \"below\": new messages under the viewport. \"history\": new messages, but the window isn't at the live edge. */\nexport type Pill = \"below\" | \"history\" | null;\n\nexport interface RoomState {\n win: MessageWindow;\n phase: Phase;\n /** The message the route asked for, once it is in the window (highlighted). */\n targetId: string | null;\n /** The first message that was unread when the room was opened (\u00A718.5): a line over it, for UNREAD_LINE_MS. */\n unreadId: string | null;\n pill: Pill;\n /**\n * The reply to go back to after following quotes (\u00A719.5): the last of the replies whose quote was followed, each\n * step back taking the one before. null: none, and the pill offers \"Jump to latest\" as before.\n */\n back: string | null;\n /** Showing the room as it was last time (cache.ts) until its first page is in: there may be newer messages. */\n stale: boolean;\n /**\n * The stale window shows at the bottom before the server has said where the unread messages start: nothing counts as\n * read until it has, since they may begin further up (QA BUG-102).\n */\n unsure: boolean;\n}\n\n/** What a change asks of the view. Pill and phase are read from `state()`, and every change may have changed them. */\nexport interface Change {\n /** The window changed. `anchor`: keep what is on screen in place (content changed above it). */\n render?: { anchor?: boolean };\n /** \"target\": bring `targetId` (else `unreadId`) into view. */\n scroll?: \"bottom\" | \"top\" | \"target\";\n /** Replace the notice above the list (\"\" clears it). */\n notice?: string;\n}\n\nexport interface RoomController {\n /** The view is kept hidden (PERF.md \u00A75): the first message from someone else that comes meanwhile is the first unread. */\n park(): void;\n /**\n * Shown again: a line over the first message still unread (\u00A718.5), brought into view (true), as on opening it. The\n * count says which, as for a kept room; else the first from someone else that came while parked.\n */\n resume(): boolean;\n state(): RoomState;\n /** Subscribe and run the first load. Everything ends with the scope. */\n start(): void;\n /** Retry a failed first load. */\n retry(): void;\n /** Extend the window at one end (a sentinel came into view). One request per end at a time. */\n loadEdge(side: \"top\" | \"bottom\"): Promise<void>;\n /** Reset the window to the latest page or the first page. */\n jump(kind: \"latest\" | \"first\"): Promise<void>;\n /**\n * Highlight and centre message `id` (a reply's quote, \u00A719), loading the history around it when needed. `from`: the\n * reply whose quote was clicked, remembered to come back to (\u00A719.5) once the original is shown.\n */\n goTo(id: string, from?: string): Promise<void>;\n /** Back to the reply whose quote was followed last (`state().back`), and forget it (\u00A719.5). */\n goBack(): Promise<void>;\n /**\n * The user is at the bottom now: hide a \"new messages below\" pill, and, at the live edge, forget the replies to go\n * back to (\u00A719.5): nothing is needed to come back to the latest messages.\n */\n dismissPill(): void;\n find(id: string): Message | undefined;\n /** Can I edit this message right now? Not a forward: its words are someone else's (\u00A721.3). */\n editable(m: Message): boolean;\n /** Can I delete this message right now? */\n deletable(m: Message): boolean;\n /** Can I reply to this message right now? (\u00A719) */\n repliable(m: Message): boolean;\n /** My newest editable message (Up arrow in an empty composer). */\n lastEditable(): Message | undefined;\n /** Send optimistically, as a reply to `replyTo` if given (\u00A719). False when sending isn't possible (no user, archived room, not allowed to post: \u00A723.6). */\n send(text: string, files?: LocalFile[], replyTo?: Message): boolean;\n retrySend(id: string): Promise<void>;\n /** Drop a failed message (no request). */\n discard(id: string): void;\n /** Save validated text. null: nothing to save (unchanged, or no longer editable). Resolves false if the save failed. */\n edit(id: string, text: string): Promise<boolean> | null;\n /** Soft delete. null: not in the window. Resolves false if the delete failed. */\n remove(id: string): Promise<boolean> | null;\n /** Can this message be selected, to forward (or delete) it with others? Saved and not deleted (\u00A721). */\n selectable(m: Message): boolean;\n /**\n * Soft-delete several messages in one request, all or none (\u00A721.2). null: none of them deletable. Resolves to why it\n * failed (the error), or null once they are deleted.\n */\n removeMany(ids: readonly string[]): Promise<unknown> | null;\n /** Can I react to this message right now? (\u00A720) */\n reactable(m: Message): boolean;\n /** A message's reactions as they should show: the server's, with my changes still on their way applied. */\n reactions(m: Message): readonly Reaction[];\n /**\n * Add (`on`) or remove my `emoji` reaction, shown at once. null: not possible (not in the window, not reactable).\n * Resolves true once it is in; else (the reaction then shows as it was) the server's reason for a refusal (at most so\n * many reactions, QA BUG-258), or false (not reached: worth a retry).\n */\n react(id: string, emoji: string, on: boolean): Promise<boolean | string> | null;\n}\n\nexport function createRoomController(opts: {\n api: Api;\n store: Store<AppState>;\n roomId: string;\n /** /r/:id/m/:msgId */\n msgId?: string | undefined;\n scope: Scope;\n /** Is the list scrolled to (near) the bottom? New messages are followed only then. */\n nearBottom: () => boolean;\n onChange: (change: Change) => void;\n /** A sending message's attachments are this far uploaded, 0 to 1 (\u00A717.4). */\n onUpload?: (id: string, fraction: number) => void;\n /** The room is being fetched (true: a first load, history, a jump, catching up after a reconnect), or no longer. */\n onBusy?: (busy: boolean) => void;\n /** Where the room's latest messages are kept between visits (\u00A77.5). */\n cache?: Cache;\n /** The latest page, asked for as the room's link was pressed (prefetch.ts `take`): the first load uses it. */\n early?: Promise<EarlyPage> | undefined;\n /** Any of the room's messages changed or went (`gone`: deleted for good), in the window or not. */\n onEvent?: (m: Message, gone: boolean) => void;\n}): RoomController {\n const { api, store, roomId, msgId, scope, nearBottom } = opts;\n const { signal } = scope;\n /** New messages scroll into view only in a visible tab at the bottom: a background tab stays put, with the pill. */\n const follows = () => nearBottom() && !store.get().away;\n /**\n * Messages changed where they are (an edit, a reaction, link previews, a delete): what is on screen stays put, but\n * at the live bottom the list stays at the bottom, or a message growing would slide under the composer.\n */\n const inPlace = (): Change => (!win.hasNewer && nearBottom() ? { render: {}, scroll: \"bottom\" } : { render: { anchor: true } });\n\n let win: MessageWindow = emptyWindow();\n let phase: Phase = \"loading\";\n let targetId: string | null = null;\n let targetTimer: ReturnType<typeof setTimeout> | undefined;\n let unreadId: string | null = null;\n let pill: Pill = null;\n /** Replies whose quotes were followed, the last on top (\u00A719.5). */\n const back: string[] = [];\n /** The window is the one kept from last time (cache.ts), until the first page replaces it. */\n let stale = false;\n /**\n * The kept window was shown before the server said where the unread messages start, and they turned out not to be\n * in it: the first page goes to them (unless you scrolled away from the bottom, where it was shown).\n */\n let retarget = false;\n /** Waiting for the server's first unread message while a kept window shows at the bottom (`unsure`). */\n let asking = false;\n /** An end the list asked to extend while stale: extended once the first page is in. */\n let wanted: \"top\" | \"bottom\" | null = null;\n let keepTimer: ReturnType<typeof setTimeout> | undefined;\n /**\n * The ETag of the latest page as the first load got it (PERF.md \u00A75). Kept with the window: while the server's page\n * still has that tag nothing in it changed since, so the window's newest messages, which realtime kept up, are that page.\n */\n let pageTag: string | undefined;\n /** The page asked for as the room's link was pressed, until the first load takes it. */\n let early = opts.early;\n /** Parked (`park`), and the first message from someone else since. */\n let parked = false;\n let firstNew: string | null = null;\n /** Bumped whenever the window is replaced (a jump): pages requested before that are stale. */\n let gen = 0;\n /** Realtime events that arrive before the first page (even while a stale window shows); replayed once it is in. */\n let buffer: [Action, Message][] = [];\n /**\n * Unsent (pending or failed) messages the window dropped, e.g. when a reply's quote took it back in history (\u00A719).\n * They belong after the newest messages, so they come back once the window is at the live edge again.\n */\n const unsent = new Map<string, Message>();\n const loading = { top: false, bottom: false };\n /** The room's realtime subscription, set up by start(); \"ready\" once the server has it. */\n let live: Promise<unknown> = Promise.resolve();\n let liveReady = false;\n\n /** Fetches out now (`track`). */\n let fetching = 0;\n /** `p` is a fetch of the room's messages: `onBusy` while any is out (\u00A77.9). */\n const track = <T>(p: Promise<T>): Promise<T> => {\n if (!fetching++) opts.onBusy?.(true);\n return p.finally(() => {\n if (!--fetching) opts.onBusy?.(false);\n });\n };\n\n const ready = () => phase === \"ready\";\n const room = (): Room | undefined => store.get().rooms.get(roomId);\n const me = () => store.get().user;\n /** Whom the window was loaded for: after a logout or a user switch, nothing of it may be kept for the next one. */\n const owner = me()?.id ?? \"\";\n const find = (id: string) => win.items.find((m) => m.id === id);\n /** I may post here (\u00A723.6): signed in, the room isn't archived, and it lets me. */\n const posting = () => {\n const r = room();\n return !!r && !r.archived && canPost(r, me());\n };\n /**\n * Moderators delete anyone's messages outside DMs, even where they can't post (\u00A736); in a copy of another instance's\n * room, not that instance's people's: its home moderates them (\u00A733.5).\n */\n const moderates = (m: Message) => {\n const r = room();\n if (!r || r.archived || !me()?.moderator || isDm(r) || !m.author) return false;\n return !(r.shared?.home && m.expand?.author?.instance);\n };\n const deletable = (m: Message) => !m.deleted && !m.status && ((posting() && m.author === me()?.id) || moderates(m));\n const editable = (m: Message) => deletable(m) && posting() && m.author === me()?.id && !m.forwarded_from;\n /** Guests only read (\u00A723.3): no replies, reactions or selecting. Readers who can't post still react (\u00A723.6). */\n const reactable = (m: Message) => {\n const r = room();\n return !!me() && !!r && !r.archived && !m.deleted && !m.status;\n };\n const repliable = (m: Message) => reactable(m) && posting();\n const emit = (change: Change = {}) => {\n if (!scope.active) return;\n opts.onChange(change);\n clearTimeout(keepTimer);\n keepTimer = setTimeout(keep, 1000);\n };\n /**\n * Keep the latest page for next time: only a fresh window at the live edge, only for whom it was loaded for. A room\n * that isn't there (any more, \u00A723.4) is forgotten, so that it doesn't show again before the server says so.\n */\n const keep = () => {\n if ((me()?.id ?? \"\") !== owner) return;\n if (phase === \"not-found\" || (!room() && store.get().roomsStatus === \"ready\"))\n return opts.cache?.put(owner, roomId, { items: [], hasOlder: false });\n if (stale || !ready() || win.hasNewer) return;\n const saved = win.items.filter((m) => !m.status);\n const items = saved.slice(-PAGE_SIZE);\n opts.cache?.put(owner, roomId, { items, hasOlder: win.hasOlder || items.length < saved.length, room: room(), tag: pageTag });\n };\n /** Local optimistic change that must win regardless of `updated` (edit/delete/revert). */\n const patchLocal = (id: string, patch: Partial<Message>) => {\n win = { ...win, items: win.items.map((m) => (m.id === id ? { ...m, ...patch } : m)) };\n };\n /**\n * Replace the window by one that may have dropped messages (a jump, a page that trimmed the other end). Unsent\n * messages it dropped are kept aside, and put back once the window is at the live edge.\n */\n const setWin = (next: MessageWindow) => {\n const kept = new Set(next.items.map((m) => m.id));\n for (const m of win.items) if (m.status && !kept.has(m.id)) unsent.set(m.id, m);\n win = next;\n if (win.hasNewer || !unsent.size) return;\n win = merge(win, [...unsent.values()]);\n unsent.clear();\n };\n /** Highlight message `id` (or nothing) for HIGHLIGHT_MS: long enough to spot it, then it fades (styles/app/messages.css). */\n const setTarget = (id: string | null) => {\n targetId = id;\n clearTimeout(targetTimer);\n if (!id) return;\n targetTimer = setTimeout(() => {\n if (targetId !== id) return;\n targetId = null;\n emit({ render: { anchor: true } });\n }, HIGHLIGHT_MS);\n };\n /** Show the line over message `id` (\u00A718.5) until UNREAD_LINE_MS from now. */\n const setUnread = (id?: string) => {\n if (!id || id === unreadId) return;\n unreadId = id;\n setTimeout(() => {\n if (unreadId !== id) return;\n unreadId = null;\n emit({ render: { anchor: true } });\n }, UNREAD_LINE_MS);\n };\n // ---------------------------------------------------------------- loading\n\n /** Apply a page fetched under generation `g`, unless a jump (or the end of the scope) has made it stale. */\n function applyLoaded(kind: PageKind, page: Message[], g: number): boolean {\n if (g !== gen || !scope.active) return false;\n setWin(applyPage(win, page, kind).win);\n return true;\n }\n\n async function loadEdge(side: \"top\" | \"bottom\") {\n const more = side === \"top\" ? win.hasOlder : win.hasNewer;\n if (stale) wanted = side; // the window is about to be replaced: what it would load now could be out of date\n if (!ready() || stale || !more || loading[side] || !win.items.length) return;\n loading[side] = true;\n const g = gen;\n try {\n const page =\n side === \"top\" ? await api.page(older(roomId, win.items[0]!), signal) : await api.page(newer(roomId, win.items.at(-1)!), signal);\n if (applyLoaded(side === \"top\" ? \"older\" : \"newer\", page, g)) emit({ render: { anchor: true } });\n } catch {\n /* the sentinel will trigger again */\n } finally {\n if (g === gen) loading[side] = false;\n }\n }\n\n async function jump(kind: \"latest\" | \"first\") {\n const g = ++gen;\n loading.top = loading.bottom = false;\n pill = null;\n back.length = 0;\n emit();\n const page = await api.page(kind === \"latest\" ? latest(roomId) : first(roomId), signal).catch(() => null);\n if (!page || !applyLoaded(kind, page, g)) return;\n setTarget(null);\n emit({ render: {}, notice: \"\", scroll: kind === \"latest\" ? \"bottom\" : \"top\" });\n }\n\n async function goTo(id: string, from?: string) {\n const remember = () => {\n if (!from || back.at(-1) === from) return;\n back.push(from);\n if (back.length > BACK_MAX) back.shift();\n };\n const m = find(id);\n if (m && !m.status) {\n remember();\n setTarget(id);\n return emit({ render: {}, scroll: \"target\", notice: \"\" });\n }\n // The current window stays until the new one is in; a jump meanwhile wins.\n const g = gen;\n const around = await windowAround(id).catch(() => undefined);\n if (g !== gen || !scope.active) return;\n if (!around) {\n return emit({\n notice: around === null ? \"That message isn't available any more.\" : \"Couldn't load that message. Check your connection.\",\n });\n }\n gen++; // pages requested for the old window are stale now\n loading.top = loading.bottom = false;\n setWin(around.win);\n remember();\n setTarget(around.target);\n pill = null;\n emit({ render: {}, scroll: \"target\", notice: \"\" });\n }\n\n /** The window around message `id`, or null when it isn't in this room. Rejects if a page fails. */\n async function windowAround(id: string): Promise<{ win: MessageWindow; target: string } | null> {\n // A missing message falls back to the latest page; any other failure fails the load (and offers Retry).\n const target = await api.getMessage(id, signal).catch((e: unknown) => {\n if (e instanceof ApiError && e.status === 404) return null;\n throw e;\n });\n if (!target || target.room !== roomId) return null;\n return { win: await windowAt(target), target: target.id };\n }\n\n /** The page before message `c`, and `c` with the page after it. */\n async function windowAt(c: Cursor): Promise<MessageWindow> {\n const [before, after] = await Promise.all([api.page(older(roomId, c), signal), api.page(newer(roomId, { ...c, id: \"\" }), signal)]);\n return merge({ items: [], hasOlder: before.length >= PAGE_SIZE, hasNewer: after.length >= PAGE_SIZE }, [...before, ...after]);\n }\n\n async function open() {\n const g = ++gen;\n const roomP = api.getRoom(roomId, signal).then((r) => store.set(upsertRoom(r)));\n // With unread messages (the room list showed a badge), the room opens at the first of them (\u00A718.5). Before the\n // counts are in (a reload), only the server knows.\n const { unread } = store.get();\n const firstP =\n msgId || !me() || (unread !== UNCOUNTED && !unread.get(roomId)) ? null : api.firstUnread(roomId, signal).catch(() => null);\n // Loaders only return a window; it is committed below, and only if nothing (a jump) replaced it meanwhile.\n const pageP = (async (): Promise<{ win: MessageWindow; target: string | null; unread?: string | undefined }> => {\n const around = msgId ? await windowAround(msgId) : null;\n if (around) return around;\n // The latest page is asked for at once, beside the first unread message: with only a few unread, it has them.\n // With the tag of the copy kept in memory, an unchanged page comes back without a body, and that copy is it.\n const kept = opts.cache?.peek(owner, roomId);\n const asked = early;\n early = undefined; // a retry asks again\n const latestP = asked\n ? asked.then((p) => {\n pageTag = p.tag;\n return p.items;\n })\n : api.page(latest(roomId), signal, {\n tag: kept?.tag,\n items: kept ? [...kept.items].sort(compare).reverse() : [],\n got: (t) => (pageTag = t),\n });\n latestP.catch(() => {});\n const f = (firstP && (await firstP))?.id;\n const page = await (f ? latestP.catch(() => []) : latestP);\n if (f && !page.some((m) => m.id === f)) return { win: await windowAt((await firstP)!), target: null, unread: f };\n return { win: applyPage(emptyWindow(), page, \"latest\").win, target: null, unread: f };\n })();\n pageP.catch(() => {}); // handled below; but we may return early (room not found) without awaiting it\n if (!msgId) void showKept(g, roomP, firstP);\n try {\n await roomP;\n } catch (e) {\n if (!scope.active) return;\n phase = e instanceof ApiError && e.status === 404 ? \"not-found\" : \"failed\";\n stale = false;\n return emit({ render: {} });\n }\n const loaded = await pageP.catch(() => null);\n if (!scope.active) return;\n const current = g === gen;\n // Never show a failed load as an empty room (\"Beginning of #room\"): say so and offer Retry.\n if (current && !loaded) {\n phase = \"failed\";\n stale = false;\n return emit({ render: {} });\n }\n const change: Change = { render: {} };\n if (current && loaded) {\n // The page was asked for before what was sent, edited or reacted to while the kept window showed (QA BUG-100), and\n // realtime may not have told it: the newer copies stay. Of the same age, the page's (an author's new name or\n // avatar comes with it). Pending sends are kept by setWin.\n const [a, z] = [loaded.win.items[0], loaded.win.items.at(-1)];\n const meanwhile = win.items.filter((m) => !m.status && (!a || compare(m, a) >= 0) && (!loaded.win.hasNewer || compare(m, z!) <= 0));\n setWin(merge(merge(loaded.win, meanwhile), loaded.win.items));\n setTarget(loaded.target);\n setUnread(loaded.unread);\n change.notice = msgId && !loaded.target ? \"That message isn't in this room. Showing the latest messages instead.\" : \"\";\n // Otherwise the jump has positioned the list. A stale window was already shown at the first unread message, or\n // you scrolled it: stay there (QA BUG-96), unless it was at the bottom and there is nothing unread.\n if (targetId || !stale || retarget) change.scroll = targetId || loaded.unread ? \"target\" : \"bottom\";\n else if (nearBottom() && !loaded.unread) change.scroll = \"bottom\";\n else change.render = { anchor: true };\n }\n // Ready either way: a jump made during the load already owns the window, but still needs the view live.\n phase = \"ready\";\n stale = false;\n emit(change);\n if (wanted) void track(loadEdge(wanted));\n const pending = buffer;\n buffer = [];\n for (const [action, m] of pending) onMessage(action, m);\n // The page and the subscription are set up side by side. A message sent after the page was read but before the\n // server had the subscription reaches neither (QA BUG-61): once the subscription is there, fetch what is newer.\n if (!liveReady) void live.then(() => track(catchUp()));\n }\n\n /**\n * Show the room as it was last time while its first page loads, if that is still to come. Nothing is waited for:\n * just after a reload, the kept room stands in for the room list. A room the list lacks waits for the server to say\n * it is yours to see.\n */\n async function showKept(g: number, roomP: Promise<unknown>, firstP: Promise<Cursor | null> | null) {\n const kept = await opts.cache?.get(owner, roomId);\n if (!room() && kept?.room && store.get().roomsStatus !== \"ready\") store.set(upsertRoom(kept.room));\n if (!room()) await roomP.catch(() => {});\n if (!kept?.items.length || g !== gen || phase !== \"loading\" || !room() || !scope.active) return;\n const shown = merge({ items: [], hasOlder: kept.hasOlder, hasNewer: false }, kept.items);\n // Opening at the first unread message (\u00A718.5): the count says which one, by the server's rule (server/unread.go), if they\n // were all prefetched with that count; else the first page opens there. Before the counts are in (a reload), the\n // server says.\n const { unread } = store.get();\n const n = firstP && unread !== UNCOUNTED ? (unread.get(roomId) ?? 0) : 0;\n const theirs = shown.items.filter((m) => m.author !== owner && !m.deleted);\n const guess = n ? theirs[theirs.length - n] : undefined;\n if (n && (!guess || kept.unread !== n)) return;\n setWin(shown);\n setUnread(guess?.id);\n asking = !!firstP && !guess;\n stale = true;\n phase = \"ready\";\n emit({ render: {}, scroll: guess ? \"target\" : \"bottom\" });\n const f = (await firstP)?.id;\n const asked = asking;\n asking = false;\n if (g !== gen || !stale || !scope.active) return;\n if (!f || f === unreadId) return void (asked && emit({ render: { anchor: true } })); // read now\n // Shown at the bottom (or the count was out of step): go where the server says, unless you scrolled away.\n const follow = !!guess || nearBottom();\n if (!find(f)) retarget = follow;\n else {\n setUnread(f);\n emit(follow ? { render: {}, scroll: \"target\" } : { render: { anchor: true } });\n }\n }\n\n /** Messages newer than the window's that realtime may have missed while it was being set up (QA BUG-61). */\n async function catchUp() {\n if (!scope.active || !ready() || win.hasNewer) return;\n const g = gen;\n const last = lastSaved(win);\n const page = await api.page(last ? newer(roomId, last) : latest(roomId), signal).catch(() => null);\n if (!page || g !== gen || !scope.active || win.hasNewer) return;\n const missed = page.filter((m) => !find(m.id));\n if (!missed.length) return;\n const follow = follows();\n setWin(applyPage(win, page, last ? \"newer\" : \"latest\").win);\n if (!follow) pill = \"below\";\n emit(follow ? { render: {}, scroll: \"bottom\" } : { render: { anchor: true } });\n }\n\n function retry() {\n if (phase !== \"failed\" || !scope.active) return;\n phase = \"loading\";\n emit({ render: {} });\n void track(open());\n }\n\n /**\n * After a reconnect: re-fetch the messages in the window that changed while realtime was down, so edits and\n * deletes missed meanwhile apply (a deleted message must not keep showing its text). Newer messages are\n * gapFill's job.\n */\n async function refreshWindow() {\n const g = gen;\n const known = win.items.filter((m) => !m.status);\n const oldest = known[0];\n const newest = known.at(-1);\n if (!oldest || !newest) return;\n // Any change made after the newest `updated` we have was made by the server later: it is newer than that.\n const since = known.reduce((max, m) => (m.updated > max ? m.updated : max), \"\");\n const changed = await api.changes(changedIn(roomId, since, oldest, newest), signal).catch(() => null);\n if (!changed || g !== gen || !scope.active) return;\n const inWindow = changed.filter((m) => find(m.id));\n if (!inWindow.length) return;\n win = merge(win, inWindow);\n emit(inPlace());\n }\n\n /** At the live edge after a reconnect: fetch everything newer than what we have (\u00A77.5). */\n async function gapFill() {\n const g = gen;\n const wasNear = follows();\n for (;;) {\n const last = lastSaved(win);\n const page = await api.page(last ? newer(roomId, last) : latest(roomId), signal).catch(() => null);\n if (!page || g !== gen || !scope.active) return;\n setWin(applyPage(win, page, last ? \"newer\" : \"latest\").win);\n if (page.length < PAGE_SIZE) break;\n }\n setWin({ ...win, hasNewer: false });\n emit(wasNear ? { render: {}, scroll: \"bottom\" } : { render: { anchor: true } });\n }\n\n function onReconnect() {\n if (!scope.active) return;\n if (phase === \"failed\") return retry(); // back online: try the first load again\n if (!ready() || stale) return; // the first page is on its way\n void track(refreshWindow());\n if (!win.hasNewer) void track(gapFill());\n }\n\n // ---------------------------------------------------------------- realtime\n\n /** What a reply shows of `q` (\u00A719). */\n const quoteOf = ({ id, author, text, deleted, files = [], expand }: Quoted): Quoted => ({\n id,\n author,\n text,\n deleted,\n files,\n ...(expand?.author && { expand: { author: expand.author } }),\n });\n const withQuote = (m: Message, q: Quoted): Message => ({ ...m, expand: { ...m.expand, reply_to: quoteOf(q) } });\n\n /**\n * Live events come without the message a reply answers (api.ts LIVE_TOPIC): the quote is the copy in the window, or\n * the one the message had there; failing both (a reply to a message far back), it is fetched.\n */\n function quoted(m: Message): Message {\n const id = m.reply_to;\n if (!id || m.expand?.reply_to) return m;\n const q = find(id) ?? find(m.id)?.expand?.reply_to;\n if (q) return withQuote(m, q);\n api.getMessage(id).then(\n (q) => {\n if (!scope.active) return;\n win = { ...win, items: win.items.map((x) => (x.reply_to === id && !x.expand?.reply_to ? withQuote(x, q) : x)) };\n emit(inPlace());\n },\n () => {},\n );\n return m;\n }\n\n function onMessage(action: Action, event: Message) {\n if (!scope.active || event.room !== roomId) return;\n if (action !== \"create\") opts.onEvent?.(event, action === \"delete\");\n if (!ready() || stale) buffer.push([action, event]); // the first page may be older than this event\n if (!ready()) return;\n const m = action === \"delete\" ? event : quoted(event);\n if (action === \"delete\") {\n win = remove(win, m.id);\n return emit(inPlace());\n }\n if (action === \"update\") {\n if (!find(m.id)) return;\n win = merge(win, [m]);\n return emit(inPlace());\n }\n // create\n if (find(m.id)) {\n win = merge(win, [m]);\n return emit({ render: {} });\n }\n if (win.hasNewer) {\n pill = \"history\";\n return emit();\n }\n if (parked && !firstNew && m.author !== me()?.id) firstNew = m.id;\n const follow = !store.get().away && (nearBottom() || m.author === me()?.id);\n win = trim(merge(win, [m]), \"top\").win;\n if (!follow && pill !== \"history\") pill = \"below\";\n emit(follow ? { render: {}, scroll: \"bottom\" } : { render: { anchor: true } });\n }\n\n const writes = createWrites({\n api,\n roomId,\n scope,\n me,\n posting,\n editable,\n deletable,\n win: () => win,\n put: (next) => {\n win = next;\n },\n find,\n patchLocal,\n emit,\n inPlace,\n toLatest: () => track(jump(\"latest\")),\n clearPill: () => {\n pill = null;\n },\n unsent,\n onUpload: opts.onUpload,\n });\n\n // ---------------------------------------------------------------- lifecycle\n\n return {\n state: () => ({ win, phase, targetId, unreadId, pill, back: back.at(-1) ?? null, stale, unsure: stale && asking }),\n park() {\n parked = true;\n },\n resume() {\n parked = false;\n const { unread } = store.get();\n const n = unread === UNCOUNTED || win.hasNewer ? 0 : (unread.get(roomId) ?? 0);\n const theirs = n ? win.items.filter((m) => m.author !== me()?.id && !m.deleted && !m.status) : [];\n const id = (n && theirs[theirs.length - n]?.id) || firstNew;\n firstNew = null;\n if (!id || !find(id)) return false;\n setUnread(id);\n emit({ render: {}, scroll: \"target\" });\n return true;\n },\n start() {\n scope.defer(() => {\n clearTimeout(keepTimer);\n keep();\n for (const m of [...win.items, ...unsent.values()]) {\n if (m.status === \"failed\") stray(m);\n revokeLocal(m);\n }\n });\n // Leaving the page (a reload, the tab closed) before the timer: kept now.\n addEventListener(\"pagehide\", keep, { signal });\n // Back online: a first load that failed tries again, even if realtime never noticed (QA BUG-123).\n addEventListener(\"online\", retry, { signal });\n scope.defer(() => clearTimeout(targetTimer));\n for (const m of takeStrays(roomId)) if (m.author === me()?.id) unsent.set(m.id, m); // not from before a logout\n // Room record changes (archive etc.) arrive through the store, kept live by sync.ts.\n const sub = api.subscribeMessages(roomId, onMessage);\n scope.sub(sub);\n live = sub.then(\n () => (liveReady = true),\n () => {},\n );\n scope.defer(api.onConnect((reconnect) => reconnect && onReconnect()));\n void track(open());\n },\n retry,\n loadEdge: (side) => track(loadEdge(side)),\n jump: (kind) => track(jump(kind)),\n goTo: (id, from) => track(goTo(id, from)),\n goBack() {\n const id = back.pop();\n if (!id) return Promise.resolve();\n emit();\n return track(goTo(id));\n },\n dismissPill() {\n const forget = back.length > 0 && !win.hasNewer;\n if (pill !== \"below\" && !forget) return;\n if (pill === \"below\") pill = null;\n if (forget) back.length = 0;\n emit();\n },\n find,\n editable,\n deletable,\n repliable,\n lastEditable() {\n const mine = lastOwnEditable(win, me()?.id ?? \"\");\n return mine && editable(mine) ? mine : undefined;\n },\n send: writes.send,\n retrySend: writes.retrySend,\n discard: writes.discard,\n edit: writes.edit,\n remove: writes.remove,\n selectable: (m) => !!me() && !m.deleted && !m.status,\n removeMany: writes.removeMany,\n reactable,\n reactions: writes.reactions,\n react(id, emoji, on) {\n const m = find(id);\n return m && reactable(m) ? writes.react(id, emoji, on) : null;\n },\n };\n}\n", "// The bottom of a room: the composer, or, instead of it, the selection bar (\u00A721), or a banner saying why there is none\n// (archived, a guest \u00A723.3, a reader \u00A723.6, a DM that takes no messages \u00A716.7). And the ways to the composer: the\n// caret goes there on entering a room and on coming back to the window, Ctrl+/ anywhere (\u00A77.6), and files dropped on\n// the room are attached (\u00A717.4). (In views/room.ts until REFACTOR item 53.)\n\nimport { h } from \"../../dom.ts\";\nimport { canPost, dmClosed, roomTitle } from \"../../lib/rooms.ts\";\nimport type { Room, User } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-footer.ts\";\nimport type { Composer } from \"./composer.ts\";\nimport type { Selection } from \"./selection.ts\";\n\nexport interface Footer {\n readonly el: HTMLElement;\n /** The composer is shown (not a banner or the selection bar). */\n composing(): boolean;\n /** Show what fits the room now. `failed`: the room didn't load (no composer: you'd write into history you can't see). */\n render(failed: boolean): void;\n /** Put the caret in the composer when it is next shown: on entering the room (\u00A722.5). */\n focusNext(): void;\n /** The listeners on the window and the room (`shell`), from mount on. */\n bind(shell: HTMLElement): void;\n}\n\nconst noHover = () => matchMedia(\"(hover:none)\").matches;\n\nexport function createFooter({\n composer,\n selection,\n room,\n me,\n closePicker,\n parked,\n active,\n signal,\n}: {\n composer: Composer;\n selection: Selection;\n room: () => Room | undefined;\n me: () => User | null;\n /** Nothing left to insert into or react to. */\n closePicker: () => void;\n /** The room is kept out of the page (parking.ts): never focus it. */\n parked: () => boolean;\n active: () => boolean;\n signal: AbortSignal;\n}): Footer {\n const el = h(\"footer\", { class: \"room-footer\" });\n const banner = h(\"p\", { class: \"archived-banner ic i-archive\" }, \"This room is archived. History is read-only.\");\n const guestBanner = h(\n \"p\",\n { class: \"guest-banner ic i-globe\" },\n // One flex item: the links stay in the sentence, not spaced apart by the banner's gap.\n h(\"span\", {}, [\n \"You're reading as a guest. \",\n h(\"a\", { href: \"/login\" }, \"Log in\"),\n \" or \",\n h(\"a\", { href: \"/signup\" }, \"sign up\"),\n \" to join the conversation.\",\n ]),\n );\n const readerBanner = h(\"p\", { class: \"guest-banner reader-banner ic i-lock\" }, \"Only some people can post in this room. You can read along and react.\");\n const closedBanner = h(\"p\", { class: \"guest-banner reader-banner ic i-x\" });\n let focusComposer = true;\n const composing = () => el.contains(composer.el);\n const show = (child: HTMLElement) => el.firstChild !== child && el.replaceChildren(child);\n\n return {\n el,\n composing,\n render(failed) {\n const r = room();\n // (The composer element, and anything typed into it, is kept for when the load succeeds.)\n if (!r || failed) return el.replaceChildren();\n if (selection.ids) {\n // The composer (and anything typed into it) comes back when selecting ends.\n selection.refresh();\n show(selection.bar);\n closePicker();\n } else if (r.archived) {\n el.replaceChildren(banner);\n closePicker();\n } else if (!me()) {\n show(guestBanner);\n } else if (!canPost(r, me())) {\n // A reader. What they had typed stays in the composer, for if they may post again.\n show(readerBanner);\n } else if (dmClosed(r, me())) {\n // Readable, but the server refuses what is sent (QA BUG-178). What was typed stays, as for a reader.\n closedBanner.textContent = dmClosed(r, me());\n show(closedBanner);\n } else show(composer.el);\n composer.setPlaceholder(`Message ${roomTitle(r, me())}`);\n // Entering a room (or switching to another one), you can just type. Not on touch screens: it would pop up the\n // keyboard over the messages you came to read.\n if (focusComposer && composing()) {\n focusComposer = false;\n // In the next frame, whose layout it then uses: focus() lays the page out at once, and on entering a room that\n // came in the middle of drawing it (PERF.md \u00A75).\n if (!noHover()) requestAnimationFrame(() => active() && !parked() && composing() && composer.focus());\n }\n },\n focusNext() {\n focusComposer = true;\n },\n bind(shell) {\n // Coming back to the window: put the caret in the composer so you can just type. Only when nothing else has\n // focus (or a link does, e.g. an attachment opened in a new tab): never away from a field, menu or confirm you\n // were on. Not with text selected (you may be copying it), and not on touch screens (it pops up the keyboard).\n window.addEventListener(\n \"focus\",\n () =>\n !parked() &&\n composing() &&\n document.activeElement!.matches(\"body,a\") &&\n getSelection()!.isCollapsed &&\n !noHover() &&\n composer.focus(),\n { signal },\n );\n // Ctrl+/ (\u2318/ on a Mac) anywhere: to the composer, as its key badge says. By the key's place too, for layouts\n // where it types something else (Cyrillic: \".\"). Not for a room kept in the background, nor while there is no\n // composer (a banner instead); behind a modal dialog the composer is inert, so focus stays there.\n document.addEventListener(\n \"keydown\",\n (e) => {\n if (!(e.ctrlKey || e.metaKey) || e.altKey || (e.key !== \"/\" && e.code !== \"Slash\")) return;\n if (parked() || !composing()) return;\n e.preventDefault();\n composer.focus();\n },\n { signal },\n );\n // Files dropped anywhere on the room go to the composer.\n const hasFiles = (e: DragEvent) => !!e.dataTransfer?.types.includes(\"Files\");\n shell.addEventListener(\"dragover\", (e) => hasFiles(e) && composing() && e.preventDefault(), { signal });\n shell.addEventListener(\n \"drop\",\n (e) => {\n if (!hasFiles(e) || !composing()) return;\n e.preventDefault();\n void composer.addFiles([...(e.dataTransfer?.files ?? [])]);\n },\n { signal },\n );\n },\n };\n}\n", "// A room's images and videos: the viewer (\u00A717.7), opened from a thumbnail or from the media grid, and the grid (\u00A730).\n// Both are lazy chunks; both are told of the messages that change or go while they are open.\n// (In views/room.ts until REFACTOR item 53.)\n\nimport type { Api } from \"../../api.ts\";\nimport { newer, older, PAGE_SIZE, withFiles } from \"../../lib/cursor.ts\";\nimport { attachmentName, isMedia, isVideo } from \"../../lib/files.ts\";\nimport type { MessageWindow } from \"../../lib/messages.ts\";\nimport { formatFull, parsePb } from \"../../lib/time.ts\";\nimport type { Message, Room } from \"../../lib/types.ts\";\nimport type { Scope } from \"../../scope.ts\";\nimport * as S from \"../../strings/room-gallery.ts\";\nimport type { ViewerImage } from \"./viewer.ts\";\n\n/** What the viewer and the grid use of the room view. */\nexport interface GalleryHost {\n api: Api;\n roomId: () => string;\n room: () => Room | undefined;\n /** The message window: the viewer starts with its images. */\n win: () => MessageWindow;\n /** \"Show in chat\": go to the message, as the user's own action. */\n goTo: (id: string) => Promise<void>;\n /** The save menu for a file, which the viewer offers to whoever is signed in (`signedIn`). */\n saveFile: (m: Message, file: string, opener: HTMLElement) => void;\n signedIn: () => boolean;\n /** Ends when the room is left (parked or unmounted): the viewer and the grid close with it. */\n screen: () => AbortSignal;\n scope: Scope;\n say: (text: string) => void;\n}\n\nexport interface Gallery {\n /**\n * A thumbnail was clicked: show it in the viewer with the room's other images and videos, oldest first: the\n * window's to start with; the viewer fetches the others when it gets near them. The viewer is loaded on the first\n * click; if it can't be (offline, or a new version was deployed), the file opens in a new tab, as a thumbnail did\n * before the viewer. From the grid: its `images` and `more`, and `leave` closes it on \"Show in chat\".\n */\n view(m: Message, file: string, opener: HTMLElement, images?: ViewerImage[], more?: [boolean, boolean], leave?: () => void): Promise<void>;\n /** The room's images and videos as a grid; it opens the viewer with `view`. */\n openGrid(): void;\n /** A message changed or went (live): the open viewer and grid follow it. */\n changed(m: Message, gone: boolean): void;\n}\n\nconst media = (x: Message) => (x.files ?? []).filter(isMedia).map((f) => ({ message: x, file: f, video: isVideo(f) }));\n\nexport function createGallery({ api, roomId, room, win, goTo, saveFile, signedIn, screen, scope, say }: GalleryHost): Gallery {\n /** Tells the open viewer that a message changed or went. */\n let viewing: ((m: Message, gone: boolean) => void) | undefined;\n /** And the open grid. */\n let gridding: ((m: Message, gone: boolean) => void) | undefined;\n\n async function view(\n m: Message,\n file: string,\n opener: HTMLElement,\n images?: ViewerImage[],\n more?: [boolean, boolean],\n leave?: () => void,\n ) {\n const w = win();\n images ??= w.items.flatMap((x) => (x.deleted || x.localFiles?.length ? [] : media(x)));\n const id = roomId();\n const start = images.findIndex((i) => i.message.id === m.id && i.file === file);\n try {\n const { openViewer } = await import(\"./viewer.ts\");\n if (!scope.active) return;\n await openViewer({\n images,\n start,\n more: more ?? [w.hasOlder, w.hasNewer],\n page: async (back, edge) => {\n const messages = await api.page(withFiles(back ? older(id, edge) : newer(id, edge)), scope.signal);\n return { messages: back ? messages.reverse() : messages, done: messages.length < PAGE_SIZE };\n },\n media,\n name: attachmentName,\n when: (x) => formatFull(parsePb(x.created)),\n fileUrl: api.fileUrl,\n onJump: (x) => {\n leave?.();\n return goTo(x.id);\n },\n ...(signedIn() ? { onSave: saveFile } : {}),\n opener,\n follow: (fn) => (viewing = fn),\n signal: screen(),\n });\n } catch {\n if (scope.active) window.open(api.fileUrl(m, file), \"_blank\", \"noopener\");\n }\n }\n\n return {\n view,\n openGrid() {\n import(\"./media.ts\").then(\n (g) =>\n scope.active &&\n g.openMedia({\n room: roomId(),\n label: room()?.kind === \"dm\" ? \"\" : room()?.name,\n api,\n name: attachmentName,\n open: view,\n follow: (fn) => (gridding = fn),\n signal: screen(),\n }),\n () => scope.active && say(\"Couldn't open media. Check your connection.\"),\n );\n },\n changed(m, gone) {\n viewing?.(m, gone);\n gridding?.(m, gone);\n },\n };\n}\n", "// Room header (\u00A77.1, \u00A716.5): back link, room title, a private room's members (opening the access dialog), the search\n// (\u00A729) and media (\u00A730) buttons and the room actions menu (room access, hide, archive, notify of every message (\u00A734.5),\n// jump to beginning). A DM shows the other member's avatar and name, and can be closed but never archived. A private or Open\n// Air room says so next to its name (\u00A723.1); a guest only gets \"Jump to beginning\" (\u00A723.3). A room shared with other\n// instances says where else it is held, and when its home can't be reached (\u00A733.9, \u00A733.7).\n\nimport type { RoomActions } from \"../../actions.ts\";\nimport { errorMessage } from \"../../api.ts\";\nimport { h } from \"../../dom.ts\";\nimport { canManage, otherMember, roomTitle, sharedNote, VISIBILITY, visibilityOf } from \"../../lib/rooms.ts\";\nimport type { Room, User } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-header.ts\";\nimport { type AvatarUrl, avatar } from \"../../ui/avatar.ts\";\nimport { createActionMenu, type MenuItem } from \"../../ui/menu.ts\";\n\nexport interface RoomHeader {\n readonly el: HTMLElement;\n update(state: { room: Room | undefined; hidden: boolean; me: User | null }): void;\n}\n\nexport function createRoomHeader(opts: {\n titleId: string;\n actions: RoomActions;\n avatarUrl: AvatarUrl;\n onJumpToBeginning: () => void;\n /** Search the room's messages (\u00A729). */\n onSearch: () => void;\n /** Show the room's images and videos as a grid (\u00A730). */\n onMedia: () => void;\n /** \"Room access\u2026\" (the creator) or \"Members\" (the others, in a private room): open the access dialog (\u00A723.2). */\n onAccess: () => void;\n /** A DM was closed from this menu. */\n onClosed: () => void;\n /** The notification choices changed (\u00A734.5): app.ts follows them, if it doesn't yet. */\n onNotify: () => void;\n signal: AbortSignal;\n}): RoomHeader {\n const { actions, signal } = opts;\n const title = h(\"h1\", { id: opts.titleId });\n const error = h(\"p\", { class: \"room-error\", role: \"alert\" });\n const shared = h(\"p\", { class: \"room-shared\", hidden: true });\n const menu = createActionMenu({ label: \"Room actions\", signal });\n const search = h(\"button\", {\n type: \"button\",\n class: \"icon-button search-toggle ic i-search\",\n \"aria-label\": \"Search messages\",\n \"aria-expanded\": \"false\",\n title: \"Search messages\",\n on: { click: opts.onSearch },\n signal,\n });\n // Has the search button's class too, but comes after it: closing search focuses the first `.search-toggle`.\n const media = h(\"button\", {\n type: \"button\",\n class: \"icon-button search-toggle ic i-media\",\n \"aria-label\": \"Media\",\n title: \"Media\",\n on: { click: opts.onMedia },\n signal,\n });\n // A private room's members (\u00A723.2): a few faces and how many, opening the access dialog.\n const members = h(\"button\", { type: \"button\", class: \"room-members\", hidden: true, on: { click: opts.onAccess }, signal });\n const el = h(\"header\", { class: \"room-header\" }, [\n h(\"a\", { href: \"/\", class: \"back ic i-back\", \"aria-label\": \"Back to rooms\" }),\n title,\n members,\n search,\n media,\n menu.el,\n shared,\n error,\n ]);\n /** What the title shows, to rebuild it only when that changes (the avatar is an image). */\n let shown = \"\";\n let last: Parameters<RoomHeader[\"update\"]>[0] | undefined;\n\n /** Notify of every message here (\u00A734.5): flip it in notify.ts's choices (chat.notify), without loading notify.ts. */\n async function setNotifyAll(id: string, on: boolean) {\n const p = notifyPrefs();\n const rooms = (Array.isArray(p.rooms) ? p.rooms : []).filter((r) => r !== id);\n if (on) rooms.push(id);\n p.rooms = rooms;\n // Nothing chosen yet to alert with: a pop-up, as ticking DMs on the profile page does.\n if (on && !p.popup && !p.sound) p.popup = true;\n try {\n if (rooms.length || Object.values(p).some((v) => v === true)) localStorage.setItem(NOTIFY_KEY, JSON.stringify(p));\n else localStorage.removeItem(NOTIFY_KEY);\n } catch {}\n if (last) update(last);\n opts.onNotify();\n if (!on || !p.popup || p.sound) return;\n const perm = globalThis.Notification?.permission;\n if (perm === \"default\") await Notification.requestPermission().catch(() => {});\n if (!signal.aborted && globalThis.Notification?.permission !== \"granted\")\n error.textContent = \"This browser blocks notifications here: allow them, or choose the sound in your profile.\";\n }\n\n async function act(fn: () => Promise<unknown>) {\n try {\n await fn();\n error.textContent = \"\";\n return true;\n } catch (e) {\n // Say why: network trouble, rate limiting or the server's reason (QA BUG-39).\n if (!signal.aborted) error.textContent = `That didn't work. ${errorMessage(e)}`;\n return false;\n }\n }\n\n function dmItems(room: Room, hidden: boolean): MenuItem[] {\n return [\n hidden\n ? { label: \"Reopen conversation\", run: () => void act(() => actions.unhide(room.id)) }\n : {\n label: \"Close conversation\",\n run: () =>\n void act(() => actions.hide(room.id)).then((ok) => {\n if (ok) opts.onClosed();\n }),\n },\n { label: \"Jump to beginning\", run: opts.onJumpToBeginning, icon: \"i-top\", sep: true },\n ];\n }\n\n function items(room: Room | undefined, hidden: boolean, mine: boolean, guest: boolean): MenuItem[] {\n if (room?.kind === \"dm\") return dmItems(room, hidden);\n const out: MenuItem[] = [];\n if (guest) return [{ label: \"Jump to beginning\", run: opts.onJumpToBeginning, icon: \"i-top\" }];\n if (room && (mine || visibilityOf(room) === \"private\")) {\n out.push({\n label: mine ? \"Room access\u2026\" : `Members (${room.members?.length ?? 0})`,\n run: opts.onAccess,\n icon: \"i-users\",\n ...(mine ? { value: VISIBILITY[visibilityOf(room)].label } : {}),\n });\n }\n // Hiding an archived room is pointless (it is listed under Archived), but one hidden before it was\n // archived must still be unhidable, or it would silently come back hidden after an unarchive.\n if (room && (!room.archived || hidden)) {\n out.push(\n hidden\n ? { label: \"Unhide room\", run: () => void act(() => actions.unhide(room.id)), icon: \"i-eyeoff\" }\n : { label: \"Hide room\", run: () => void act(() => actions.hide(room.id)), icon: \"i-eyeoff\" },\n );\n }\n if (room && mine) {\n out.push(\n room.archived\n ? { label: \"Unarchive room\", run: () => void act(() => actions.setArchived(room.id, false)), icon: \"i-archive\" }\n : {\n label: \"Archive room\",\n confirm: { text: `Archive \u201C${room.name}\u201D? It becomes read-only for everyone.`, action: \"Archive\" },\n run: () => void act(() => actions.setArchived(room.id, true)),\n icon: \"i-archive\",\n },\n );\n }\n if (room && (!room.archived || notifyAll(room.id))) {\n const on = notifyAll(room.id);\n out.push({\n label: \"Notify of every message\",\n hint: on ? \"On \u2014 you hear about everything here\" : \"Off \u2014 only mentions and replies to you\",\n run: () => void setNotifyAll(room.id, !on),\n icon: \"i-bell\",\n checked: on,\n sep: true,\n });\n }\n out.push({ label: \"Jump to beginning\", run: opts.onJumpToBeginning, icon: \"i-top\", sep: out.length > 0 });\n return out;\n }\n\n function update(state: Parameters<RoomHeader[\"update\"]>[0]) {\n last = state;\n const { room, hidden, me } = state;\n const other = room ? otherMember(room, me) : undefined;\n const text = room ? roomTitle(room, me) : \"\";\n const vis = room && !other ? visibilityOf(room) : \"public\";\n const key = JSON.stringify([text, other?.avatar ?? null, vis]);\n if (key !== shown) {\n shown = key;\n const badge =\n vis === \"public\"\n ? null\n : h(\n \"span\",\n { class: `vis-badge ic ${vis === \"open\" ? \"i-globe\" : \"i-lock\"}`, title: VISIBILITY[vis].hint },\n VISIBILITY[vis].label,\n );\n title.replaceChildren(\n ...(other\n ? [avatar(other, 24, opts.avatarUrl), h(\"span\", {}, text)]\n : [h(\"span\", { class: \"name\" }, [h(\"span\", { class: \"hash\" }, \"#\"), text.slice(1)]), badge ?? \"\"]),\n );\n }\n title.classList.toggle(\"dm-title\", !!other);\n const people = room && !other && vis === \"private\" ? (room.expand?.members ?? []) : [];\n members.hidden = !people.length;\n const faces = people\n .slice(0, 3)\n .map((u) => u.id + (u.avatar ?? \"\"))\n .join();\n if (people.length && members.dataset.shown !== `${faces}|${people.length}`) {\n members.dataset.shown = `${faces}|${people.length}`;\n members.setAttribute(\"aria-label\", `Members, ${people.length}`);\n members.replaceChildren(\n h(\n \"span\",\n { class: \"faces\" },\n people.slice(0, 3).map((u) => avatar(u, 24, opts.avatarUrl)),\n ),\n String(people.length),\n );\n }\n const note = room ? sharedNote(room) : \"\";\n if (shared.textContent !== note) shared.textContent = note;\n shared.hidden = !note;\n menu.update(items(room, hidden, !!room && canManage(room, me), !me));\n }\n\n return { el, update };\n}\n\n/** notify.ts's NOTIFY_KEY. */\nconst NOTIFY_KEY = \"chat.notify\";\n\nfunction notifyPrefs(): { rooms?: unknown; popup?: unknown; sound?: unknown } {\n try {\n const p: unknown = JSON.parse(localStorage.getItem(NOTIFY_KEY) ?? \"null\");\n return p && typeof p === \"object\" ? p : {};\n } catch {\n return {};\n }\n}\n\n/** Is every message of this room notified on this device (\u00A734.5)? */\nfunction notifyAll(id: string): boolean {\n const { rooms } = notifyPrefs();\n return Array.isArray(rooms) && rooms.includes(id);\n}\n", "// Links in message text (\u00A77.6.3). Pure, so what becomes a link is unit-tested.\n\n/** A link found in text: what it shows, and where it goes. */\nexport interface Link {\n text: string;\n href: string;\n}\n\n/** Candidates: `http(s)://\u2026` or `www.\u2026`, up to whitespace or a character URLs don't contain unescaped. */\nconst CANDIDATE = /\\b(?:https?:\\/\\/|www\\.)[^\\s<>\"]+/gi;\n/**\n * Punctuation that ends a sentence rather than a URL (\"see https://x.com.\" \u2192 no \".\"), typographic quotes (\"\u201Ehttps://x.com\u201C\",\n * as phones type them) and CJK punctuation included.\n */\nconst TRAILING = /[.,:;!?'\"*_\u2026\u3002\\p{Pi}\\p{Pf}]$/u;\n/** A closing bracket, and the one that opens it. */\nconst OPENING: Record<string, string> = { \")\": \"(\", \"]\": \"[\" };\n\n/**\n * Split `text` into plain strings and links. Only http(s) URLs become links (`www.example.com` \u2192 https), so a\n * `javascript:` or `data:` URL never does. Trailing punctuation stays text, and so does a closing bracket the link\n * didn't open: \"(see https://en.wikipedia.org/wiki/Rust_(language))\" keeps the inner pair.\n */\nexport function linkify(text: string): (string | Link)[] {\n const out: (string | Link)[] = [];\n let at = 0;\n for (const match of text.matchAll(CANDIDATE)) {\n let url = match[0];\n for (;;) {\n const last = url.slice(-1);\n const open = OPENING[last];\n if (!TRAILING.test(last) && !(open && count(url, open) < count(url, last))) break;\n url = url.slice(0, -1);\n }\n const www = /^www\\./i.test(url);\n // Not the www. inside an email address or a longer host name (bob@www.example.com, my.www.example.com).\n if (www && /[@.-]/.test(text[match.index - 1] ?? \"\")) continue;\n // Always http(s), as that is all CANDIDATE matches.\n let href: string;\n try {\n href = new URL(www ? `https://${url}` : url).href;\n } catch {\n continue; // not a valid URL\n }\n if (match.index > at) out.push(text.slice(at, match.index));\n out.push({ text: url, href });\n at = match.index + url.length;\n }\n if (at < text.length) out.push(text.slice(at));\n return out;\n}\n\nconst count = (s: string, ch: string) => s.split(ch).length - 1;\n", "// \"@handle\" in message text (\u00A741). Pure, so what is a mention is unit-tested (shared/vectors/mentions.json). Keep in\n// sync with pb_hooks/lib/handles.js MENTION and the app's lib/Mentions.kt.\n\n/** \"@handle\": after the start or anything but a letter, digit, \"_\", \"@\", \".\" or \"/\", and not followed by one of those. */\nconst MENTION = /(^|[^A-Za-z0-9_@./])@([A-Za-z0-9_]{3,24})(?![A-Za-z0-9_@])/g;\n\n/** `text` as plain strings and its mentions: `handle` in lower case without the \"@\", `text` as written. */\nexport function splitMentions(text: string): (string | { handle: string; text: string })[] {\n const out: (string | { handle: string; text: string })[] = [];\n let at = 0;\n for (const m of text.matchAll(MENTION)) {\n const start = m.index + m[1]!.length;\n if (start > at) out.push(text.slice(at, start));\n out.push({ handle: m[2]!.toLowerCase(), text: `@${m[2]}` });\n at = start + m[2]!.length + 1;\n }\n if (at < text.length) out.push(text.slice(at));\n return out;\n}\n", "// The user-facing text of views/room/messages.ts (docs/REFACTOR.md item 56): one module per source file, so a lazy\n// screen's text stays in its own chunk. Copy changes here; a translation would replace these.\n\nexport const REPLY = \"Reply\";\nexport const FORWARD = \"Forward\";\nexport const SELECT = \"Select\";\nexport const EDIT = \"Edit\";\nexport const DELETE = \"Delete\";\nexport const MESSAGES = \"Messages\";\nexport const COULDNT_LOAD_THIS_ROOM_CHECK_YOUR = \"Couldn't load this room. Check your connection. \";\nexport const RETRY = \"Retry\";\nexport const MESSAGE = \"Message\";\nexport const UNBAN = \"Unban\";\nexport const BAN = \"Ban\u2026\";\nexport const banTheyAreSignedOutEverywhere = (name: string | number) =>\n `Ban ${name}? They are signed out everywhere and can't sign in until unbanned.`;\nexport const ENTER_TO_SAVE_ESC_TO_CANCEL = \"Enter to save \u00B7 Esc to cancel\";\nexport const EDIT_MESSAGE = \"Edit message\";\nexport const UNKNOWN = \"Unknown\";\nexport const selectMessageFrom = (name: string | number, when: string | number) => `Select message from ${name}, ${when}`;\nexport const forwardedFrom = (name: string | undefined) => `Forwarded from ${name ?? UNKNOWN}`;\nexport const THE_ORIGINAL_MESSAGE_WAS_DELETED = \"The original message was deleted\";\nexport const MESSAGE_DELETED = \"Message deleted\";\nexport const edited = (when: string | number) => `Edited ${when}`;\nexport const NOT_SENT = \"Not sent. \";\nexport const NOT_SENT_THE_MESSAGE_YOU_REPLIED = \"Not sent: the message you replied to was deleted. \";\nexport const SEND_WITHOUT_QUOTE = \"Send without quote\";\nexport const DISCARD = \"Discard\";\nexport const CONFIRM_DELETE = \"Confirm delete\";\nexport const DELETE_THIS_MESSAGE = \"Delete this message? \";\nexport const CANCEL = \"Cancel\";\nexport const DELETE_MESSAGE = \"Delete message\";\nexport const SHOW_THE_ORIGINAL_MESSAGE = \"Show the original message\";\nexport const quotingShowTheOriginalMessage = (name: string, spoken: string | number) =>\n `Quoting ${name || \"a message\"}: ${spoken}. Show the original message.`;\nexport const on = (instance: string | number) => `On ${instance}`;\nexport const BAN_ACTION = \"Ban\";\nexport const NEW = \"New\";\nexport const EDITED = \"(edited)\";\n", "// The user-facing text of views/room/attachments.ts (docs/REFACTOR.md item 56): one module per source file, so a lazy\n// screen's text stays in its own chunk. Copy changes here; a translation would replace these.\n\nexport const UPLOADING = \"Uploading\";\nexport const saveToCollection = (file: string | number) => `Save ${file} to collection`;\nexport const SAVE_TO_COLLECTION = \"Save to collection\";\nexport const PRIVATE_COLLECTION = \"Private collection\";\nexport const fromTheCollection = (name: string | number) => `From the collection \u201C${name}\u201D`;\nexport const PRIVATE = \"Private\";\nexport const couldntLoad = (video: boolean) => `Couldn't load ${video ? \"video\" : \"image\"} `;\nexport const RETRY = \"Retry\";\nexport const MORE = \" more\";\n", "// A message's attachments (\u00A717.5): image and video thumbnails that open the viewer (\u00A717.7), audio players, download\n// chips for other files, and a sending message's local previews. An image or video has a Save button (to a collection,\n// \u00A731), and one attached from a collection says which.\n\nimport { type Child, h } from \"../../dom.ts\";\nimport { attachmentName, isAudio, isGif, isMedia, isVideo } from \"../../lib/files.ts\";\nimport type { Badge, LocalFile, Message } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-attachments.ts\";\nimport { collectionIcon } from \"../../ui/icon.ts\";\n\n/** Most image and video tiles a message shows; the last one says how many more there are, which the viewer shows. */\nexport const MAX_TILES = 4;\n\n/** A message's attachments, or null without any. */\nexport type Attachments = ((m: Message) => HTMLElement | null) & {\n /** After the list is drawn: stop and forget the audio players no longer on the page (a deleted message's, say). */\n prune: () => void;\n};\n\nexport function createAttachments(opts: {\n /** URL of an attachment (\u00A737.3). */\n fileUrl: (m: Message, filename: string, thumb?: string) => string;\n /** URL of a video's poster frame (\u00A730.1): 404 until the server has made one. */\n posterUrl: (m: Message, filename: string) => string;\n /** A thumbnail was clicked: show the image or video in the viewer (\u00A717.7). */\n onOpenImage: (m: Message, file: string, opener: HTMLElement) => void;\n /** How much of a sending message's attachments has been uploaded, 0 to 1 (\u00A717.4). */\n uploadProgress: (id: string) => number;\n /** What the badge of a file from collection `id` says (\u00A731); undefined until known. */\n badge?: (id: string) => Badge | undefined;\n /** Save to collection on a tile (\u00A731): offer it next to `opener`. None for guests. */\n onSave?: (m: Message, file: string, opener: HTMLElement) => void;\n signal: AbortSignal;\n}): Attachments {\n const { signal } = opts;\n /**\n * Aspect ratios of a sending message's image and video previews, so its tiles take their width before loading. A\n * message from the server says its files' own (`file_dims`); these cover the ones it doesn't know yet (a new video).\n */\n const sentRatios = new Map<string, string[]>();\n /** Audio players by message id and file, kept across renders so a new reaction or edit doesn't stop one playing. */\n const players = new Map<string, HTMLAudioElement>();\n /** Stops and forgets the players no longer on the page, or (unmounting) all of them. */\n const prune = (all?: unknown) =>\n players.forEach((el, key) => {\n if (all || !el.isConnected) {\n el.pause();\n players.delete(key);\n }\n });\n signal.addEventListener(\"abort\", prune);\n const btn = (label: string, onClick: () => void) => h(\"button\", { type: \"button\", on: { click: onClick }, signal }, label);\n\n /**\n * A message's attachments (\u00A717.5): images and videos as uncropped thumbnails of a fixed height (1 large, or a row of\n * up to 4 small ones, the 4th saying \"+N\" when there are more), audio as a player under its download chip, other\n * files as download chips. A message not yet on\n * the server shows its local previews instead, and while it sends, how much of them has been uploaded.\n */\n function attachments(m: Message): HTMLElement | null {\n const local = m.localFiles ?? [];\n const names = m.files ?? [];\n if (!local.length && !names.length) return null;\n // Shown as an image or video only if the server will show it as one too, so nothing changes shape once it is sent.\n // A collection's video without a poster too, as a plain tile: as a file it grew into a tile once sent, and the room\n // didn't follow it down (QA BUG-249).\n const shown = (f: LocalFile) => (!!f.url || !!f.item) && isMedia(f.file.name);\n const imageCount = local.length ? local.filter(shown).length : names.filter(isMedia).length;\n /** The last tile shown, when more are left out: it says how many. */\n const more = (tile: HTMLElement) => {\n if (images.childElementCount === MAX_TILES && imageCount > MAX_TILES) {\n tile.append(h(\"span\", { class: \"att-more\" }, [`+${imageCount - MAX_TILES}`, h(\"span\", { class: \"visually-hidden\" }, \" more\")]));\n }\n };\n const thumb = imageCount === 1 ? \"800x480f\" : \"480x240f\";\n const images = h(\"div\", { class: `att-images ${imageCount === 1 ? \"one\" : \"row\"}` });\n const others = h(\"ul\", { class: \"att-files\" });\n\n if (local.length) {\n for (const f of local) {\n if (!shown(f)) {\n others.append(h(\"li\", {}, h(\"span\", { class: \"att-file i-file\" }, f.file.name)));\n continue;\n }\n if (images.childElementCount === MAX_TILES) continue;\n const i = images.childElementCount;\n // An item from a collection (\u00A731) shows its thumbnail (or a video's poster, or nothing yet), never as a video.\n const el = !f.item ? preview(f.file.name, f.url) : f.url ? h(\"img\", { src: f.url, alt: f.file.name, decoding: \"async\" }) : null;\n el?.addEventListener(\n el instanceof HTMLVideoElement ? \"loadedmetadata\" : \"load\",\n () => {\n const [w, ht] = el instanceof HTMLVideoElement ? [el.videoWidth, el.videoHeight] : [el.naturalWidth, el.naturalHeight];\n if (!w || !ht) return;\n const ratios = sentRatios.get(m.id) ?? [];\n ratios[i] = `${w} / ${ht}`;\n sentRatios.set(m.id, ratios);\n },\n { signal },\n );\n const tile = h(\"span\", { class: \"att-tile\" }, [el, playBadge(f.file.name)]);\n images.append(tile);\n more(tile);\n }\n } else {\n const ratios = sentRatios.get(m.id);\n for (const name of names) {\n if (isMedia(name)) {\n if (images.childElementCount === MAX_TILES) continue;\n const dims = m.file_dims?.[name];\n const ratio = ratios?.[images.childElementCount] ?? (dims ? `${dims[0]} / ${dims[1]}` : undefined);\n const tile = mediaTile(m, name, thumb, ratio);\n images.append(cell(m, name, tile));\n more(tile);\n } else {\n const chip = fileLink(m, name, \"att-file i-file\", [attachmentName(m, name)]);\n others.append(h(\"li\", {}, isAudio(name) ? [chip, \" \", player(m, name)] : chip));\n }\n }\n }\n const progress =\n local.length && m.status === \"pending\"\n ? h(\"progress\", { class: \"att-progress\", max: \"1\", value: String(opts.uploadProgress(m.id)), \"aria-label\": \"Uploading\" })\n : null;\n return h(\"div\", { class: \"attachments\" }, [\n images.childElementCount ? images : null,\n others.childElementCount ? others : null,\n progress,\n ]);\n }\n\n /**\n * A tile with what goes over it (\u00A731): Save, and for a file attached from a collection its badge, a link to the\n * collection if you may see it, else \"Private collection\". A forward's files are its original's (\u00A721.3).\n */\n function cell(m: Message, name: string, tile: HTMLElement): HTMLElement {\n const from = m.file_sources?.[name];\n const b = from ? opts.badge?.(from) : null;\n const { onSave } = opts;\n const save =\n onSave &&\n h(\n \"button\",\n {\n type: \"button\",\n class: \"att-save\",\n \"aria-label\": `Save ${attachmentName(m, name)} to collection`,\n title: \"Save to collection\",\n \"aria-haspopup\": \"dialog\",\n on: { click: () => onSave(m, name, save!) },\n signal,\n },\n collectionIcon(),\n );\n const badge =\n b &&\n (\"private\" in b\n ? h(\"span\", { class: \"att-src\" }, [collectionIcon(), \"Private collection\"])\n : h(\"a\", { class: \"att-src\", href: `/c/${from}`, title: `From the collection \u201C${b.name}\u201D` }, [\n collectionIcon(),\n h(\"span\", {}, b.name),\n b.public ? null : h(\"span\", { class: \"ic i-lock\", title: \"Private\" }, h(\"span\", { class: \"visually-hidden\" }, \" (private)\")),\n ]));\n return h(\"span\", { class: \"att-cell\" }, [tile, badge, save]);\n }\n\n /** A link to the full file. */\n function fileLink(m: Message, name: string, cls: string, children: Child[]): HTMLAnchorElement {\n return h(\n \"a\",\n { class: cls, href: opts.fileUrl(m, name), target: \"_blank\", rel: \"noopener\", download: attachmentName(m, name) },\n children,\n );\n }\n\n /** An audio file's player, kept across redraws (it keeps playing). A file it can't load shows the player's own error state. */\n function player(m: Message, name: string): HTMLAudioElement {\n const key = `${m.id}/${name}`;\n const kept = players.get(key);\n if (kept) return kept;\n const el = h(\"audio\", { src: opts.fileUrl(m, name), controls: true, preload: \"metadata\", \"aria-label\": attachmentName(m, name) });\n players.set(key, el);\n return el;\n }\n\n /**\n * What shows an image or video: an image as itself, a video as its first frame (the browser fetches just enough of\n * the file to draw it).\n */\n function preview(name: string, src: string): HTMLImageElement | HTMLVideoElement {\n return isVideo(name)\n ? h(\"video\", { src: `${src}#t=0.001`, preload: \"metadata\", muted: true, playsinline: true })\n : h(\"img\", { src, alt: name, decoding: \"async\" });\n }\n\n /** A video's tile shows a play badge over its first frame. */\n const playBadge = (name: string) => isVideo(name) && h(\"span\", { class: \"att-play\", \"aria-hidden\": \"true\" });\n\n /**\n * An image's thumbnail or a video's first frame: a click opens the viewer, a click that asks for a new tab or window\n * (or a middle click) gets the full file there. A video shows the poster the server made of it (\u00A730.1), so the\n * browser fetches nothing of the video; without one (not made yet, no ffmpeg there) it shows the video's own first\n * frame. A failed load offers Retry.\n */\n function mediaTile(m: Message, name: string, thumb: string, ratio?: string): HTMLElement {\n const video = isVideo(name);\n let poster = video;\n const src = () => (poster ? opts.posterUrl(m, name) : opts.fileUrl(m, name, video || isGif(name) ? undefined : thumb));\n let el = poster ? h(\"img\", { src: src(), alt: attachmentName(m, name), decoding: \"async\" }) : preview(attachmentName(m, name), src());\n if (el instanceof HTMLImageElement) el.loading = \"lazy\";\n if (ratio) el.style.aspectRatio = ratio;\n const tile = fileLink(m, name, \"att-tile\", [el, playBadge(name)]);\n tile.removeAttribute(\"download\"); // open images and videos in a tab rather than download them\n if (video) tile.setAttribute(\"aria-label\", `${attachmentName(m, name)}, video`);\n tile.addEventListener(\n \"click\",\n (e) => {\n if (e.button || e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return;\n e.preventDefault();\n opts.onOpenImage(m, name, tile);\n },\n { signal },\n );\n const load = () => (el.src = video && !poster ? `${src()}#t=0.001` : src());\n const failed = () => {\n // No poster: the video's first frame instead, as if there had never been one.\n if (poster) {\n poster = false;\n const was = el;\n el = preview(attachmentName(m, name), src());\n el.style.aspectRatio = was.style.aspectRatio;\n el.addEventListener(\"error\", failed, { signal });\n was.replaceWith(el);\n return;\n }\n const broken = h(\"span\", { class: \"att-tile att-broken\" }, [\n S.couldntLoad(video),\n btn(\"Retry\", () => {\n broken.replaceWith(tile);\n load();\n }),\n ]);\n tile.replaceWith(broken);\n };\n el.addEventListener(\"error\", failed, { signal });\n return tile;\n }\n\n return Object.assign(attachments, { prune: () => prune() });\n}\n", "// Reactions on a message (\u00A720.3): a chip per emoji with how many reacted and who, and the buttons that open the emoji\n// picker to add one. What reacting *does* is up to the room view; the buttons have no listeners of their own: the message\n// list handles their clicks by their `data-act` (messages.ts, PERF.md \u00A75).\n\nimport { h } from \"../../dom.ts\";\nimport type { Reaction } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-reactions.ts\";\n\n/** A reaction as shown: with who reacted, in words. */\nexport type ShownReaction = Reaction & { who: string };\n\n/** Where focus goes in a message after its reactions change: the reaction, else the buttons that add one. */\nexport const reactionFocus = (emoji: string): readonly string[] => [\n `.reactions [data-emoji=\"${CSS.escape(emoji)}\"]`,\n \".reactions .add-reaction\",\n \".actions .react\",\n];\n\n/**\n * \"Add reaction\", with class `cls` (also its `data-act`): opens the emoji picker for a reaction to its message. The\n * picker says whether it is open (`aria-expanded`).\n */\nexport function addReactionButton(cls: string): HTMLButtonElement {\n const label = \"Add reaction\";\n return h(\"button\", {\n type: \"button\",\n class: `${cls} ic i-react`,\n title: label,\n \"aria-label\": label,\n \"aria-haspopup\": \"dialog\",\n \"aria-expanded\": \"false\",\n dataset: { act: cls },\n });\n}\n\n/**\n * The emoji people reacted with, each with how many (\u00A720.3). Where I can react, each one is a toggle for mine\n * (`data-act=\"reaction\"`, `aria-pressed`), and a last button adds another; otherwise (an archived room) they only show.\n */\nexport function reactionRow(reactions: readonly ShownReaction[], reactable: boolean, me: string): HTMLElement {\n const chips = reactions.map((r) => {\n const mine = r.users.includes(me);\n const n = r.users.length;\n const content = [h(\"span\", { class: \"reaction-emoji\" }, r.emoji), h(\"span\", { class: \"reaction-count\" }, String(n))];\n const attrs = { class: `reaction${mine ? \" mine\" : \"\"}`, title: `${r.who} reacted with ${r.emoji}`, dataset: { emoji: r.emoji } };\n if (!reactable) return h(\"span\", attrs, content);\n return h(\n \"button\",\n {\n ...attrs,\n dataset: { emoji: r.emoji, act: \"reaction\" },\n type: \"button\",\n \"aria-pressed\": String(mine),\n \"aria-label\": `${r.emoji} ${n} ${n === 1 ? \"reaction\" : \"reactions\"}`,\n },\n content,\n );\n });\n return h(\"div\", { class: \"reactions\", role: \"group\", \"aria-label\": \"Reactions\" }, [\n ...chips,\n reactable ? addReactionButton(\"add-reaction\") : null,\n ]);\n}\n", "// The message list DOM (\u00A77.5, \u00A77.6.1, \u00A77.6.2): renders a MessageWindow with author groups and day dividers,\n// reusing each message's element until something it shows changes. Owns the per-message UI state (edit box,\n// delete confirm, inline errors), shows reactions (\u00A720.3, reactions.ts), attachments (\u00A717.5, attachments.ts) and which\n// messages are selected (\u00A721.1); what those buttons *do* is up to the room view. A message's buttons have no listeners of\n// their own: the list handles their clicks by their `data-act` (one listener, not one per button), and each toolbar is\n// a clone of one built once (PERF.md \u00A75).\n\nimport { h, reconcile } from \"../../dom.ts\";\nimport { linkify } from \"../../lib/links.ts\";\nimport { splitMentions } from \"../../lib/mentions.ts\";\nimport { emptyForward, type MessageWindow, quoteText, startsGroup } from \"../../lib/messages.ts\";\nimport { reactors } from \"../../lib/reactions.ts\";\nimport { captureAnchor, restoreAnchor } from \"../../lib/scroll.ts\";\nimport { dayLabel, formatFull, formatTime, parsePb } from \"../../lib/time.ts\";\nimport type { Badge, LinkPreview, Message, Quoted, Reaction, User } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-messages.ts\";\nimport { type AvatarUrl, avatar } from \"../../ui/avatar.ts\";\nimport { type ActionMenu, createActionMenu, type MenuItem } from \"../../ui/menu.ts\";\nimport { createAttachments } from \"./attachments.ts\";\nimport { composing, editProblem, fitRows, rowsFor } from \"./composer.ts\";\nimport { addReactionButton, reactionFocus, reactionRow } from \"./reactions.ts\";\n\nexport interface MsgError {\n text: string;\n /** None for a refusal that would only be refused again (QA BUG-258). */\n retry?: () => void;\n}\n\n/** What to render, read fresh on every render. */\nexport interface ListState {\n win: MessageWindow;\n /** The first load is done (until then, no \"beginning of the room\" marker). */\n ready: boolean;\n /** The first load failed: show an error with Retry instead of the (empty) window. */\n failed: boolean;\n /** Text of the \"beginning of the room\" marker. */\n beginning: string;\n /** Highlighted message (/r/:id/m/:msgId). */\n targetId: string | null;\n /** The first unread message: a \"New\" line goes over it (\u00A718.5). */\n unreadId: string | null;\n /** The selected messages while selecting (\u00A721.1), else null. */\n selected: ReadonlySet<string> | null;\n}\n\nexport interface MessageList {\n readonly el: HTMLOListElement;\n readonly topSentinel: HTMLElement;\n readonly bottomSentinel: HTMLElement;\n /** `anchor`: keep the message at the top of the viewport in place (content changed above it). */\n render(opts?: { anchor?: boolean }): void;\n startEdit(id: string): void;\n /** Close the edit box (no render). */\n stopEdit(): void;\n /** Show or clear an inline error under a message (no render). */\n setError(id: string, error: MsgError | null): void;\n /**\n * Focus the first of `selectors` found in message `id`: now, or after the next render (`later`), since a\n * message's element is rebuilt when what it shows changes.\n */\n focusIn(id: string, selectors: readonly string[], later?: boolean): void;\n /** A sending message's attachments are this far uploaded, 0 to 1 (\u00A717.4): its progress bar moves (no render). */\n setUpload(id: string, fraction: number): void;\n}\n\n/** At most this many characters of a quote are in its accessible name. */\nconst QUOTE_SPOKEN = 80;\n\nconst byId = (id: string) => `li.msg[data-id=\"${CSS.escape(id)}\"]`;\n\n/** A message toolbar's buttons, in order: label, class (and `data-act`), icon. \"react\" is the reactions' own. */\nconst TOOLS = [\n [\"\", \"react\", \"\"],\n [\"Reply\", \"reply\", \"reply\"],\n [\"Forward\", \"forward\", \"fwd\"],\n [\"Select\", \"select\", \"check\"],\n [\"Edit\", \"edit\", \"edit\"],\n [\"Delete\", \"delete\", \"trash\"],\n] as const;\n\nexport function createMessageList(opts: {\n state: () => ListState;\n me: () => User | null;\n /** Does the message get an Edit button? */\n editable: (m: Message) => boolean;\n /** Does the message get a Delete button? */\n deletable: (m: Message) => boolean;\n /** Does the message get a Reply button? (\u00A719) */\n repliable: (m: Message) => boolean;\n /** Reply on a message. */\n onReply: (id: string) => void;\n /** Can the message be selected (and forwarded)? (\u00A721) */\n selectable: (m: Message) => boolean;\n /** Select or unselect a message; the first one starts selecting. */\n onSelect: (id: string) => void;\n /** Forward on a message. */\n onForward: (id: string) => void;\n /** Can I react to the message? (\u00A720) */\n reactable: (m: Message) => boolean;\n /** The message's reactions as they should show (with my changes on their way). */\n reactions: (m: Message) => readonly Reaction[];\n /** A reaction chip was clicked: add (`on`) or take back my `emoji`. */\n onReact: (id: string, emoji: string, on: boolean) => void;\n /** React (or a reactions row's +) was clicked: offer the emoji picker next to `opener`. */\n onPickReaction: (id: string, opener: HTMLElement) => void;\n /** The name of someone not in the window (who reacted), if known yet. */\n nameOf: (userId: string) => string | undefined;\n /** The quote in reply `from` was clicked: show the message it answers (`id`). */\n onOpenQuote: (id: string, from: string) => void;\n onSaveEdit: (id: string, text: string) => void;\n /** Escape in the edit box (after it has closed). */\n onCancelEdit: () => void;\n onDelete: (id: string) => void;\n onRetrySend: (id: string) => void;\n onDiscard: (id: string) => void;\n /** Retry button of a failed first load. */\n onRetryLoad: () => void;\n avatarUrl: AvatarUrl;\n /** \"Message\" in an author's menu (\u00A716.5). */\n onMessageUser: (userId: string) => void;\n /** A moderator's author menu (\u00A736): whether they are banned, and Ban or Unban. */\n isBanned?: (userId: string) => Promise<boolean>;\n onBan?: (userId: string, banned: boolean) => void;\n /** URL of an attachment (\u00A737.3). */\n fileUrl: (m: Message, filename: string, thumb?: string) => string;\n /** URL of a video's poster frame (\u00A730.1). */\n posterUrl: (m: Message, filename: string) => string;\n /** A thumbnail was clicked: show the image or video in the viewer (\u00A717.7). */\n onOpenImage: (m: Message, file: string, opener: HTMLElement) => void;\n /** What the badge of a file from collection `id` says (\u00A731); undefined until known. */\n badge?: (id: string) => Badge | undefined;\n /** Save to collection on a tile (\u00A731). */\n onSave?: (m: Message, file: string, opener: HTMLElement) => void;\n signal: AbortSignal;\n}): MessageList {\n const { signal } = opts;\n const el = h(\"ol\", { class: \"messages\", \"aria-live\": \"polite\", \"aria-busy\": \"true\", \"aria-label\": \"Messages\" });\n const topSentinel = h(\"li\", { class: \"sentinel\", dataset: { sentinel: \"top\" }, \"aria-hidden\": \"true\" });\n const bottomSentinel = h(\"li\", { class: \"sentinel\", dataset: { sentinel: \"bottom\" }, \"aria-hidden\": \"true\" });\n const beginning = h(\"li\", { class: \"beginning\" });\n const newLine = h(\"li\", { class: \"new-line\" }, h(\"span\", {}, \"New\"));\n const loadError = h(\"li\", { class: \"load-error\", role: \"alert\" }, [\n \"Couldn't load this room. Check your connection. \",\n h(\"button\", { type: \"button\", class: \"link\", on: { click: () => opts.onRetryLoad() }, signal }, \"Retry\"),\n ]);\n\n // Day dividers (\"Today\") and time-only stamps depend on the current date: redraw when it changes.\n let midnight: ReturnType<typeof setTimeout> | undefined;\n const scheduleMidnight = () => {\n const next = new Date();\n next.setHours(24, 0, 1, 0);\n midnight = setTimeout(() => {\n render({ anchor: true });\n scheduleMidnight();\n }, next.getTime() - Date.now());\n };\n scheduleMidnight();\n signal.addEventListener(\"abort\", () => clearTimeout(midnight), { once: true });\n\n // Selecting (\u00A721.1): a click anywhere on a message selects it, rather than following a link or pressing a button.\n el.addEventListener(\n \"click\",\n (e) => {\n const t = e.target as Element;\n const li = opts.state().selected && !t.matches(\"input.select\") ? t.closest<HTMLElement>(\"li.msg\") : null;\n if (!li?.querySelector(\"input.select\")) return;\n e.preventDefault();\n e.stopPropagation();\n // Focus would stay on the page itself (the message isn't focusable), out of reach of Escape (\u00A721.1).\n focusAfter = { id: li.dataset.id!, selector: \"input.select\" };\n opts.onSelect(li.dataset.id!);\n },\n { capture: true, signal },\n );\n\n // Touch screens have no hover: tapping a message shows its actions (like hovering it does), tapping it again or\n // anywhere else hides them. Taps on its links and buttons don't count, but pressing an action hides them. A message\n // without actions (deleted, read-only room\u2026) doesn't light up. A tap is a click right after a touch: a touch screen\n // with a mouse too (a laptop's, desktop Safari's) matches (hover:hover), and its taps still have no hover. Timed by\n // performance.now(): WebKit's synthesized touches have their own timeStamp clock.\n let touched: string | null = null;\n let touchedAt = -Infinity;\n // Where the finger came down (a touch's events all go there). WebKit and Chrome on Android move a tap's click onto a\n // link or button near it (touch adjustment): a tap on a short message's text went to its time's permalink above it.\n let fingerOn: Element | null = null;\n const touchNow = () => (touchedAt = performance.now());\n const touchEnd = (e: TouchEvent) => {\n touchNow();\n fingerOn = e.target as Element;\n // WebKit (iOS Safari too) sends no click for a tap on what takes none, such as the room's name: hide them here.\n if (!el.contains(fingerOn)) touch(null);\n };\n document.addEventListener(\"touchend\", touchEnd, { capture: true, passive: true, signal });\n document.addEventListener(\"pointerdown\", (e) => e.pointerType === \"touch\" && touchNow(), { capture: true, signal });\n const interactive = \"a, button, input, textarea, summary, label, [contenteditable]\";\n const touch = (li: HTMLElement | null) => {\n if (touched) el.querySelector(`li.msg[data-id=\"${CSS.escape(touched)}\"]`)?.classList.remove(\"touched\");\n touched = li?.dataset.id ?? null;\n if (!li) return;\n li.classList.add(\"touched\");\n // The buttons show below it: on the last message they would be under the composer.\n li.scrollIntoView({ block: \"nearest\" });\n };\n document.addEventListener(\n \"click\",\n (e) => {\n const tap = performance.now() - touchedAt < 1000;\n el.classList.toggle(\"by-touch\", tap);\n if ((!touched && !tap && !matchMedia(\"(hover:none)\").matches) || opts.state().selected) return;\n let t = e.target as Element;\n // A tap on a message's text is a tap on the message, wherever the browser moved the click (a link in the text\n // still gets that help).\n const text = tap ? fingerOn?.closest(\".body\") : null;\n if (text && el.contains(text) && !text.contains(t) && t.closest(interactive)) {\n e.preventDefault();\n e.stopPropagation();\n t = fingerOn!;\n }\n const li = t.closest<HTMLElement>(\"li.msg\");\n if (!li || !el.contains(li) || t.closest(\".actions button\")) return touch(null);\n const open = li.dataset.id === touched;\n if (t.closest(interactive)) return open || touch(null);\n touch(open || !li.querySelector(\".actions\") ? null : li);\n },\n // Before the tapped button's own handler, which may redraw the message (a reaction chip) and take it off the page.\n { capture: true, signal },\n );\n\n /**\n * Each timestamp parsed and formatted once: every change redraws the whole window, and this was most of its cost.\n * Keyed by `created`; the stamps depend on today's date (time only for today), so a new day starts afresh.\n */\n let times = new Map<string, { ms: number; day: string; time: string }>();\n let timesDay = \"\";\n const timeOf = (created: string) => {\n let t = times.get(created);\n if (!t) {\n const ms = parsePb(created);\n t = { ms, day: new Date(ms).toDateString(), time: formatTime(ms) };\n times.set(created, t);\n }\n return t;\n };\n\n let editing: string | null = null;\n /**\n * What is typed in the open edit box, once it differs from the message (null: not yet). The box is rebuilt whenever\n * its message is redrawn (a highlight fading, the quoted message edited\u2026), and must keep it (QA BUG-43).\n */\n let editText: string | null = null;\n let confirmDelete: string | null = null;\n const errors = new Map<string, MsgError>();\n const cache = new Map<string, { sig: string; el: HTMLElement }>();\n const dividers = new Map<string, HTMLElement>();\n /** Focus to apply after the next render: message elements are rebuilt when they change. The first selector found wins. */\n let focusAfter: { id: string; selector: string | readonly string[]; caretToEnd?: boolean } | null = null;\n /** Names of the people in the window, for who reacted (rebuilt every render). */\n let names = new Map<string, string>();\n\n /** Upload progress of sending messages, by id. */\n const uploads = new Map<string, number>();\n const attachments = createAttachments({ ...opts, uploadProgress: (id) => uploads.get(id) ?? 0 });\n\n /** A button whose click `onAct` handles as `act`. */\n const btn = (label: string, act: string, cls?: string) =>\n h(\"button\", { type: \"button\", ...(cls ? { class: cls } : {}), dataset: { act } }, label);\n /** The toolbars built so far, by which of TOOLS they have (\"101001\"): each message gets a clone. */\n const toolbars = new Map<string, HTMLElement>();\n function toolbar(has: readonly boolean[]): Node {\n const key = has.map(Number).join(\"\");\n let bar = toolbars.get(key);\n if (!bar) {\n bar = h(\n \"div\",\n { class: \"actions\" },\n TOOLS.map(([label, act, icon], i) =>\n !has[i]\n ? null\n : act === \"react\"\n ? addReactionButton(act)\n : h(\"button\", { type: \"button\", class: `${act} ic i-${icon}`, \"aria-label\": label, title: label, dataset: { act } }),\n ),\n );\n toolbars.set(key, bar);\n }\n return bar.cloneNode(true);\n }\n\n /** The clicks on messages' buttons, by their `data-act`. */\n function onAct(b: HTMLElement, id: string) {\n switch (b.dataset.act) {\n case \"react\":\n case \"add-reaction\":\n return opts.onPickReaction(id, b);\n case \"reaction\":\n return opts.onReact(id, b.dataset.emoji!, b.getAttribute(\"aria-pressed\") !== \"true\");\n case \"reply\":\n return opts.onReply(id);\n case \"forward\":\n return opts.onForward(id);\n case \"select\":\n return opts.onSelect(id);\n case \"edit\":\n return list.startEdit(id);\n case \"delete\":\n return askDelete(id);\n case \"quote\":\n return opts.onOpenQuote(b.dataset.quote!, id);\n case \"send\":\n return opts.onRetrySend(id);\n case \"discard\":\n return opts.onDiscard(id);\n case \"confirm\":\n confirmDelete = null;\n return opts.onDelete(id);\n case \"cancel\":\n return cancelDelete(id);\n case \"retry\":\n return errors.get(id)?.retry?.();\n }\n }\n /** The message (its id) of an event in it, and the button with a `data-act` it is on, if any. */\n const at = (e: Event) => {\n const t = e.target as Element;\n const id = t.closest<HTMLElement>(\"li.msg\")?.dataset.id;\n return id && el.contains(t) ? { t, id, b: t.closest<HTMLElement>(\"[data-act]\") } : null;\n };\n el.addEventListener(\n \"click\",\n (e) => {\n const hit = at(e);\n if (hit?.b) onAct(hit.b, hit.id);\n },\n { signal },\n );\n // Selecting (\u00A721.1): shows what is selected, not what was clicked: a refused one (the limit) stays unchecked.\n el.addEventListener(\n \"change\",\n (e) => {\n const hit = at(e);\n if (!hit || !(hit.t instanceof HTMLInputElement) || !hit.t.matches(\"input.select\")) return;\n hit.t.checked = !!opts.state().selected?.has(hit.id);\n opts.onSelect(hit.id);\n },\n { signal },\n );\n // Escape in a delete confirm cancels it.\n el.addEventListener(\n \"keydown\",\n (e) => {\n const hit = e.key === \"Escape\" ? at(e) : null;\n if (!hit?.t.closest(\".confirm\")) return;\n e.preventDefault();\n cancelDelete(hit.id);\n },\n { signal },\n );\n // An author's menu (authorEl) works once it is first opened. (`toggle` doesn't bubble: caught on its way down.) A\n // moderator's then offers Ban or Unban, as they are each time it opens (\u00A736).\n const authorMenus = new WeakMap<HTMLDetailsElement, ActionMenu>();\n el.addEventListener(\n \"toggle\",\n (e) => {\n const d = e.target;\n if (!(d instanceof HTMLDetailsElement) || !d.open || !d.matches(\".author-menu\")) return;\n const name = d.querySelector(\"summary\")?.textContent ?? \"\";\n let menu = authorMenus.get(d);\n if (!menu) {\n d.classList.add(\"made\");\n menu = createActionMenu({ label: name, note: d.dataset.note, el: d, signal });\n authorMenus.set(d, menu);\n }\n const user = d.dataset.user!;\n const items: MenuItem[] = d.dataset.nodm ? [] : [{ label: \"Message\", run: () => opts.onMessageUser(user) }];\n menu.update(items);\n const { isBanned, onBan } = opts;\n if (!d.dataset.ban || !isBanned || !onBan) return;\n isBanned(user).then(\n (banned) => {\n if (signal.aborted) return;\n menu.update([\n ...items,\n banned\n ? { label: \"Unban\", run: () => onBan(user, false), sep: true }\n : {\n label: \"Ban\u2026\",\n confirm: { text: `Ban ${name}? They are signed out everywhere and can't sign in until unbanned.`, action: \"Ban\" },\n run: () => onBan(user, true),\n sep: true,\n },\n ]);\n },\n () => {}, // not known: no item\n );\n },\n { capture: true, signal },\n );\n\n function askDelete(id: string) {\n confirmDelete = id;\n focusAfter = { id, selector: \".confirm .cancel\" };\n render();\n }\n\n function cancelDelete(id: string) {\n confirmDelete = null;\n focusAfter = { id, selector: \".actions .delete\" };\n render();\n }\n\n function editBox(m: Message): HTMLElement[] {\n const hintText = \"Enter to save \u00B7 Esc to cancel\";\n const hint = h(\"p\", { class: \"hint\", \"aria-live\": \"polite\" }, hintText);\n const box = h(\"textarea\", {\n class: \"edit-input\",\n rows: rowsFor(m.text),\n \"aria-label\": \"Edit message\",\n value: editText ?? m.text,\n on: {\n input: (e) => {\n editText = (e.currentTarget as HTMLTextAreaElement).value;\n fitRows(e.currentTarget as HTMLTextAreaElement);\n hint.textContent = hintText;\n hint.classList.remove(\"error\");\n },\n keydown: (e) => {\n if (e.key === \"Enter\" && !e.shiftKey && !composing(e)) {\n e.preventDefault();\n const value = (e.currentTarget as HTMLTextAreaElement).value;\n const problem = editProblem(value, !!m.files?.length);\n if (problem) {\n // Say why nothing happens (an empty edit is not a delete; over-long text can't be saved).\n hint.textContent = problem;\n hint.classList.add(\"error\");\n return;\n }\n opts.onSaveEdit(m.id, value);\n } else if (e.key === \"Escape\" && !composing(e)) {\n e.preventDefault();\n editing = null;\n editText = null;\n render();\n opts.onCancelEdit();\n }\n },\n },\n signal,\n });\n return [box, hint];\n }\n\n /**\n * What a reply shows of the message it answers: the copy in the window when there is one (it follows edits and\n * deletes live), else the one the server expanded. Null when it isn't a reply. A live reply to a message beyond the\n * window has neither until the controller has fetched it: \"\u2026\" meanwhile, not \"Message deleted\" (QA BUG-180).\n */\n function quotedOf(m: Message, win: MessageWindow): Quoted | null {\n if (!m.reply_to) return null;\n const inWindow = win.items.find((x) => x.id === m.reply_to);\n return inWindow ?? m.expand?.reply_to ?? { id: m.reply_to, author: \"\", text: \"\u2026\", deleted: false };\n }\n\n /** A sent message's time links to it (/r/:id/m/:msgId); one still sending, or failed, isn't on the server yet. */\n function permalink(m: Message, time: HTMLElement): HTMLElement {\n if (m.status) return time;\n return h(\"a\", { class: \"permalink\", href: `/r/${m.room}/m/${m.id}` }, [time]);\n }\n\n function messageNode(\n m: Message,\n groupStart: boolean,\n targetId: string | null,\n quoted: Quoted | null,\n selected: ReadonlySet<string> | null,\n ): HTMLElement {\n const err = errors.get(m.id);\n const selectable = opts.selectable(m);\n /** Selecting: whether this message is one of them (null: it can't be). */\n const picked = selected && selectable ? selected.has(m.id) : null;\n const editable = opts.editable(m);\n const deletable = opts.deletable(m);\n const repliable = opts.repliable(m);\n const reactable = opts.reactable(m);\n const me = opts.me();\n const reactions = m.deleted\n ? []\n : opts.reactions(m).map((r) => ({ ...r, who: reactors(r.users, me?.id ?? \"\", (id) => names.get(id) ?? opts.nameOf(id)) }));\n const { ms, time } = timeOf(m.created);\n /** Someone else's reply to one of my messages, or a mention of me (\u00A741): highlighted, so that I notice it (\u00A719.3). */\n const toMe = !!me && m.author !== me.id && (quoted?.author === me.id || !!m.mentions?.includes(me.id));\n const sig = JSON.stringify([\n m.text,\n m.deleted,\n m.edited_at,\n m.status ?? \"\",\n m.created,\n time, // changes at midnight (\"7:36 PM\" \u2192 \"Oct 10, 7:36 PM\")\n groupStart,\n editable,\n deletable,\n repliable,\n reactable,\n selectable,\n !!selected,\n picked,\n m.forwarded_from ? (m.expand?.forwarded_from?.name ?? \"\") : \"\",\n reactions.map((r) => [r.emoji, r.users.length, r.users.includes(me?.id ?? \"\"), r.who]),\n quoted ? [quoted.expand?.author?.name ?? \"\", quoteText(quoted)] : null,\n editing === m.id,\n confirmDelete === m.id,\n err?.text ?? \"\",\n targetId === m.id,\n toMe,\n m.expand?.author?.name ?? \"\",\n m.expand?.author?.avatar ?? \"\",\n (m.files ?? []).join(\"/\"),\n (m.previews ?? []).map((p) => [p.url, p.title, p.icon.length]),\n (m.localFiles ?? []).map((f) => f.url || f.file.name).join(\"/\"),\n Object.values(m.file_sources ?? {}).map((c) => opts.badge?.(c) ?? null),\n ]);\n const hit = cache.get(m.id);\n if (hit && hit.sig === sig) return hit.el;\n\n const author: User = m.expand?.author ?? (me && m.author === me.id ? me : { id: m.author, name: \"Unknown\" });\n const cls = [\n \"msg\",\n groupStart && \"group-start\",\n m.status,\n m.deleted && \"deleted\",\n toMe && \"to-me\",\n targetId === m.id && \"target\",\n picked && \"selected\",\n ]\n .filter(Boolean)\n .join(\" \");\n\n const parts: (HTMLElement | null)[] = [];\n if (picked !== null) {\n parts.push(\n h(\"input\", {\n type: \"checkbox\",\n class: \"select\",\n checked: picked,\n \"aria-label\": `Select message from ${author.name}, ${formatFull(ms)}`,\n }),\n );\n }\n // Above the author's name, from where the avatar is.\n if (quoted) parts.push(quote(quoted));\n if (groupStart) {\n parts.push(avatar(author, 32, opts.avatarUrl));\n parts.push(\n h(\"div\", { class: \"meta\" }, [\n authorEl(author, me, !!m.expand?.author, m.room),\n permalink(m, h(\"time\", { datetime: new Date(ms).toISOString(), title: formatFull(ms) }, time)),\n ]),\n );\n }\n if (m.forwarded_from && !m.deleted) {\n parts.push(h(\"div\", { class: \"forwarded\" }, S.forwardedFrom(m.expand?.forwarded_from?.name)));\n }\n if (editing === m.id) {\n parts.push(...editBox(m));\n } else {\n // A forward with nothing to show: its original was deleted (\u00A721.3).\n const gone = m.deleted || emptyForward(m);\n parts.push(\n gone\n ? h(\"div\", { class: \"body placeholder\" }, m.deleted ? \"Message deleted\" : \"The original message was deleted\")\n : h(\"div\", { class: \"body\" }, bodyText(m.text, me && m.mentions?.includes(me.id) ? (me.handle ?? \"\") : \"\")),\n );\n if (m.edited_at && !m.deleted)\n parts.push(h(\"span\", { class: \"edited\", title: `Edited ${formatFull(parsePb(m.edited_at))}` }, \"(edited)\"));\n }\n if (!m.deleted) parts.push(attachments(m));\n if (!m.deleted && m.previews?.length) parts.push(previewList(m.previews));\n if (reactions.length) parts.push(reactionRow(reactions, reactable, me?.id ?? \"\"));\n if (m.status === \"failed\") {\n // The original went away while this reply was sending: Retry sends it without the quote (\u00A719).\n const replyGone = !!quoted?.deleted;\n parts.push(\n h(\"div\", { class: \"send-error\" }, [\n replyGone ? \"Not sent: the message you replied to was deleted. \" : \"Not sent. \",\n btn(replyGone ? \"Send without quote\" : \"Retry\", \"send\"),\n btn(\"Discard\", \"discard\"),\n ]),\n );\n }\n if (selected) {\n // Selecting: no actions on single messages.\n } else if (confirmDelete === m.id) {\n parts.push(\n h(\"div\", { class: \"confirm\", role: \"group\", \"aria-label\": \"Confirm delete\" }, [\n \"Delete this message? \",\n // Together, so that a narrow screen wraps both under the question rather than Cancel alone.\n h(\"span\", { class: \"bar-actions\" }, [btn(\"Delete message\", \"confirm\", \"danger\"), btn(\"Cancel\", \"cancel\", \"cancel\")]),\n ]),\n );\n } else if (editing !== m.id && (reactable || repliable || deletable || selectable)) {\n parts.push(toolbar([reactable, repliable, selectable && !emptyForward(m), selectable, editable, deletable]) as HTMLElement);\n }\n if (err) parts.push(h(\"div\", { class: \"msg-error\", role: \"alert\" }, err.retry ? [`${err.text} `, btn(\"Retry\", \"retry\")] : err.text));\n\n const li = h(\"li\", { class: cls, dataset: { id: m.id } }, parts);\n if (touched === m.id) li.classList.add(\"touched\");\n cache.set(m.id, { sig, el: li });\n return li;\n }\n\n /** A service message (\u00A75.3): one line of the app's own, nobody's, with no buttons (so no reply, reaction or select). */\n function serviceNode(m: Message): HTMLElement {\n const sig = `${m.text} \u00B7 ${timeOf(m.created).time}`;\n const hit = cache.get(m.id);\n if (hit?.sig === sig) return hit.el;\n const li = h(\"li\", { class: \"service\", dataset: { id: m.id } }, sig);\n cache.set(m.id, { sig, el: li });\n return li;\n }\n\n /**\n * Message text with its links clickable (\u00A77.6.3), which open in a new tab (the router leaves them alone), and its\n * \"@handle\"s marked (\u00A741), yours more: `mine`, your handle when the server says it mentions you. A handle given up\n * and taken by you since is someone else's in older messages (QA BUG-265).\n */\n function bodyText(text: string, mine: string): (string | HTMLElement)[] {\n return linkify(text).flatMap((part) =>\n typeof part === \"string\"\n ? splitMentions(part).map((t) =>\n typeof t === \"string\" ? t : h(\"span\", { class: t.handle === mine ? \"mention me\" : \"mention\" }, t.text),\n )\n : h(\"a\", { href: part.href, target: \"_blank\", rel: \"noopener noreferrer nofollow\" }, part.text),\n );\n }\n\n /** A line for each link (\u00A728): its favicon and title, opening it like the link in the text. Only http(s), data: icons. */\n function previewList(previews: readonly LinkPreview[]): HTMLElement {\n return h(\n \"ul\",\n { class: \"previews\" },\n previews\n .filter((p) => /^https?:\\/\\//i.test(p.url))\n .map((p) =>\n h(\n \"li\",\n {},\n h(\"a\", { href: p.url, target: \"_blank\", rel: \"noopener noreferrer nofollow\", title: p.url }, [\n p.icon.startsWith(\"data:image/\") ? h(\"img\", { src: p.icon, alt: \"\", width: 16, height: 16 }) : null,\n h(\"span\", {}, p.title),\n ]),\n ),\n ),\n );\n }\n\n /** A reply's quote of the message it answers (\u00A719): clicking it shows that message. */\n function quote(q: Quoted): HTMLElement {\n const name = q.expand?.author?.name ?? \"\";\n const text = quoteText(q);\n // Spoken as one line, like it is shown: never the whole of a long message. Not \"Reply \u2026\" either, which is\n // what the Reply button next to it is called.\n const chars = [...text];\n const spoken = chars.length > QUOTE_SPOKEN ? `${chars.slice(0, QUOTE_SPOKEN).join(\"\").trimEnd()}\u2026` : text;\n return h(\n \"button\",\n {\n type: \"button\",\n class: `reply-quote${q.deleted ? \" deleted\" : \"\"}`,\n title: \"Show the original message\",\n \"aria-label\": S.quotingShowTheOriginalMessage(name, spoken),\n dataset: { act: \"quote\", quote: q.id },\n },\n [name ? h(\"span\", { class: \"reply-author\" }, name) : null, h(\"span\", { class: \"reply-text\" }, text)],\n );\n }\n\n /**\n * The author's name: for other (known) users a menu offering \"Message\" (\u00A716.5), unless they take no DMs (\u00A716.7), and\n * to a moderator Ban (\u00A736). Guests can't message (\u00A723.3). The menu is drawn as ui/menu.ts draws it, and made to work\n * when first opened (the `toggle` listener above).\n */\n function authorEl(author: User, me: User | null, known: boolean, room: string): HTMLElement {\n // Someone on a linked instance says where (\u00A733.4).\n const where = author.instance ? `On ${author.instance}` : undefined;\n if (!me || author.id === me.id || !known) return h(\"span\", { class: \"author\", title: where }, author.name);\n // A moderator bans this instance's people (\u00A736), those who take no DMs too (QA BUG-230); an anonymous room's author\n // is the room (\u00A735), no one to ban.\n const ban = me.moderator && !author.instance && author.id !== room;\n if (author.no_dms && !ban) return h(\"span\", { class: \"author\", title: where }, author.name);\n const data = {\n user: author.id,\n ...(where ? { note: where } : {}),\n ...(ban ? { ban: \"1\" } : {}),\n ...(author.no_dms ? { nodm: \"1\" } : {}),\n };\n return h(\"details\", { class: \"menu author-menu\", dataset: data }, [\n h(\"summary\", { class: \"author\" }, author.name),\n h(\"div\", { class: \"menu-items\" }, [\n where ? h(\"p\", {}, where) : null,\n author.no_dms ? null : h(\"button\", { type: \"button\" }, \"Message\"),\n ]),\n ]);\n }\n\n function divider(ms: number): HTMLElement {\n const label = dayLabel(ms);\n const key = `${new Date(ms).toDateString()}|${label}`;\n let d = dividers.get(key);\n if (!d) {\n d = h(\"li\", { class: \"day\" }, h(\"span\", {}, label));\n dividers.set(key, d);\n }\n return d;\n }\n\n function render(o: { anchor?: boolean } = {}) {\n if (signal.aborted) return;\n const { win, ready, failed, beginning: beginningText, targetId, unreadId, selected } = opts.state();\n el.classList.toggle(\"selecting\", !!selected);\n if (failed) {\n reconcile(el, [loadError]);\n return;\n }\n // An edit box or delete confirm only stays open while its message can still be changed (it may have been\n // deleted in another tab, or the room archived, meanwhile).\n const canChange = (id: string | null, can: (m: Message) => boolean) => !!id && win.items.some((m) => m.id === id && can(m));\n if (selected || !canChange(editing, opts.editable)) {\n editing = null;\n editText = null;\n }\n if (selected || !canChange(confirmDelete, opts.deletable)) confirmDelete = null;\n beginning.textContent = beginningText;\n names = new Map();\n const me = opts.me();\n if (me) names.set(me.id, me.name);\n for (const m of win.items) {\n const a = m.expand?.author;\n if (a) names.set(a.id, a.name);\n }\n const nodes: Node[] = [];\n if (win.hasOlder) nodes.push(topSentinel);\n else if (ready) nodes.push(beginning);\n let prev: Message | undefined;\n let prevDay = \"\";\n const today = new Date().toDateString();\n if (today !== timesDay || times.size > 2000) {\n times = new Map();\n timesDay = today;\n }\n for (const m of win.items) {\n const { ms, day } = timeOf(m.created);\n const newDay = day !== prevDay;\n if (newDay) nodes.push(divider(ms));\n if (m.id === unreadId) nodes.push(newLine);\n nodes.push(m.author ? messageNode(m, newDay || startsGroup(prev, m), targetId, quotedOf(m, win), selected) : serviceNode(m));\n prev = m;\n prevDay = day;\n }\n if (win.hasNewer) nodes.push(bottomSentinel);\n\n const anchor = o.anchor ? captureAnchor(el, \"li.msg\") : null;\n // A redrawn edit box is a new element: give it back the focus and caret the old one had (QA BUG-43).\n const box = document.activeElement;\n const typing = box instanceof HTMLTextAreaElement && box.matches(\"textarea.edit-input\") && el.contains(box) ? box : null;\n const caret = typing && ([typing.selectionStart, typing.selectionEnd, typing.selectionDirection] as const);\n // Likewise a button or checkbox in a redrawn message (it changes whenever someone reacts, \u00A720.3, or it is\n // selected, \u00A721.1): focus its replacement.\n const held =\n !typing && (box instanceof HTMLButtonElement || box instanceof HTMLInputElement) && el.contains(box) ? sameButton(box) : null;\n reconcile(el, nodes);\n if (anchor) restoreAnchor(el, anchor);\n if (typing && caret && !typing.isConnected && editing && !focusAfter) {\n const next = el.querySelector<HTMLTextAreaElement>(`${byId(editing)} textarea.edit-input`);\n if (next) fitRows(next);\n next?.focus();\n next?.setSelectionRange(...caret);\n }\n if (held && box instanceof HTMLElement && !box.isConnected && !focusAfter)\n find(held.id, held.selectors)?.focus({ preventScroll: true });\n\n // forget elements for messages no longer in the window\n const live = new Set(win.items.map((m) => m.id));\n for (const id of cache.keys()) if (!live.has(id)) cache.delete(id);\n attachments.prune();\n\n if (focusAfter) {\n const target = find(focusAfter.id, focusAfter.selector);\n target?.focus();\n if (focusAfter.caretToEnd && target instanceof HTMLTextAreaElement) {\n // rowsFor() counts only newlines: a long line wrapped in a narrow window (or zoomed in) needs its wrapped rows.\n fitRows(target);\n target.setSelectionRange(target.value.length, target.value.length);\n // The whole message, its \"Enter to save\" line too: focus only scrolls the box into view (QA BUG-187).\n target.closest(\"li\")?.scrollIntoView?.({ block: \"nearest\" });\n }\n focusAfter = null;\n }\n }\n\n /** Where the focused button `b` will be once its message is redrawn: the same button, or the nearest one left. */\n function sameButton(b: HTMLButtonElement | HTMLInputElement): { id: string; selectors: readonly string[] } | null {\n const id = b.closest<HTMLElement>(\"li.msg\")?.dataset.id;\n if (!id) return null;\n if (b instanceof HTMLInputElement) return { id, selectors: [\"input.select\"] };\n const emoji = b.closest<HTMLElement>(\".reactions [data-emoji]\")?.dataset.emoji;\n if (emoji) return { id, selectors: reactionFocus(emoji) };\n const cls = b.classList[0];\n const parent = b.parentElement?.classList[0];\n return cls && parent ? { id, selectors: [`.${parent} > .${cls}`] } : null;\n }\n\n function find(id: string, selector: string | readonly string[]): HTMLElement | null {\n for (const s of typeof selector === \"string\" ? [selector] : selector) {\n const found = el.querySelector<HTMLElement>(`${byId(id)} ${s}`);\n if (found) return found;\n }\n return null;\n }\n\n const list: MessageList = {\n el,\n topSentinel,\n bottomSentinel,\n render,\n startEdit(id) {\n editing = id;\n editText = null;\n confirmDelete = null;\n focusAfter = { id, selector: \"textarea.edit-input\", caretToEnd: true };\n render();\n },\n stopEdit() {\n editing = null;\n editText = null;\n },\n setError(id, error) {\n if (error) errors.set(id, error);\n else errors.delete(id);\n },\n focusIn(id, selectors, later) {\n if (later) focusAfter = { id, selector: selectors };\n else find(id, selectors)?.focus();\n },\n setUpload(id, fraction) {\n uploads.set(id, fraction);\n const bar = el.querySelector<HTMLProgressElement>(`${byId(id)} progress.att-progress`);\n if (bar) bar.value = fraction;\n },\n };\n return list;\n}\n", "// Names of people who reacted but aren't in the window (\u00A720.3): looked up in batches, one request for every name a\n// render asks for. Looking people up needs an account (\u00A723.3): a guest sees \"3 people\".\n\nimport type { User } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-names.ts\";\n\n/** Most users one request asks for (`usersById`). */\nconst BATCH = 50;\n\n/** A user's name if known; otherwise undefined, and `onFound` is called once it is. */\nexport type NameOf = (id: string) => string | undefined;\n\nexport function createNameLookup(opts: {\n usersById: (ids: readonly string[], signal: AbortSignal) => Promise<User[]>;\n signedIn: () => boolean;\n /** New names arrived: render again. */\n onFound: () => void;\n signal: AbortSignal;\n}): NameOf {\n const { signal } = opts;\n const people = new Map<string, string>();\n /** Ids to look up, or being looked up. */\n const asking = new Set<string>();\n let lookingUp = false;\n\n async function lookUp() {\n const ids = [...asking].filter((id) => !people.has(id)).slice(0, BATCH);\n let ok = true;\n try {\n const found = await opts.usersById(ids, signal);\n for (const u of found) people.set(u.id, u.name);\n for (const id of ids) if (!people.has(id)) people.set(id, \"Unknown\"); // e.g. a deleted account\n } catch {\n ok = false;\n for (const id of ids) asking.delete(id); // asked again by the next render (not this one: no retry loop offline)\n }\n if (signal.aborted || !ok) {\n lookingUp = false;\n return;\n }\n if ([...asking].some((id) => !people.has(id))) return void lookUp(); // more than one batch\n lookingUp = false;\n opts.onFound();\n }\n\n return (id) => {\n if (!opts.signedIn()) return undefined;\n const name = people.get(id);\n if (name !== undefined || asking.has(id)) return name;\n asking.add(id);\n if (!lookingUp) {\n lookingUp = true;\n queueMicrotask(() => void lookUp());\n }\n return undefined;\n };\n}\n", "// The room's status line (\u00A722.6): an error stays until something else is said; a confirmation goes away by itself.\n\nimport { h } from \"../../dom.ts\";\n\n/** How long a confirmation such as \"Message forwarded.\" stays on screen (\u00A722.6). */\nexport const NOTICE_MS = 4000;\n\nexport interface Notice {\n readonly el: HTMLElement;\n /** Say `text` until something else is said (\"\" clears it). */\n say(text: string): void;\n /** Say `text` for NOTICE_MS, unless something else is said meanwhile. */\n flash(text: string): void;\n /** Clear it, if it still says `text`. */\n unsay(text: string): void;\n}\n\nexport function createNotice(signal: AbortSignal): Notice {\n const el = h(\"p\", { class: \"room-notice\", role: \"status\" });\n let timer: ReturnType<typeof setTimeout> | undefined;\n signal.addEventListener(\"abort\", () => clearTimeout(timer));\n const unsay = (text: string) => {\n if (el.textContent === text) el.textContent = \"\";\n };\n return {\n el,\n say(text) {\n el.textContent = text;\n },\n flash(text) {\n el.textContent = text;\n clearTimeout(timer);\n timer = setTimeout(() => unsay(text), NOTICE_MS);\n },\n unsay,\n };\n}\n", "// A room kept out of the page after you left it (park), until you come back (resume): still live and drawn, never\n// measured. A scroll asked for meanwhile waits for the resume. At the live bottom (`pinned`), the list stays there;\n// else where it was: the message at the top goes back where it was. (In views/room.ts until REFACTOR item 53.)\n\nimport { isNearBottom } from \"../../lib/scroll.ts\";\nimport type { Change } from \"./controller.ts\";\n\nexport interface Parking {\n readonly parked: boolean;\n /** The list is at its live bottom (as of its last scroll), and stays there when it gets shorter. */\n readonly pinned: boolean;\n /** Ends when the room is left (parked, or the view's signal): what shows over the page for it (grid, viewer). */\n readonly screen: AbortSignal;\n /** While parked, keep a scroll for the resume (true: kept, don't scroll now). */\n hold(scroll: Change[\"scroll\"]): boolean;\n /** Leave the page: note where the list is. */\n park(): void;\n /** Back on the page: the scroll asked for meanwhile, if any (taken). */\n unpark(): Change[\"scroll\"];\n /** Put the list back where it was, unless something else was brought into view (`moved`). */\n restore(moved: boolean, scroll: Change[\"scroll\"], draw: (scroll: NonNullable<Change[\"scroll\"]>) => void, toBottom: () => void): void;\n}\n\nexport function createParking(list: HTMLElement, signal: AbortSignal): Parking {\n let parked = false;\n let held: Change[\"scroll\"];\n let at: { id: string; dy: number; top: number } | undefined;\n let pinned = true;\n let screen = new AbortController();\n signal.addEventListener(\"abort\", () => screen.abort(), { once: true });\n // When the list gets shorter while at the live bottom it is kept there (BUG-31, room.ts).\n list.addEventListener(\"scroll\", () => (pinned = isNearBottom(list)), { signal });\n\n return {\n get parked() {\n return parked;\n },\n get pinned() {\n return pinned;\n },\n get screen() {\n return screen.signal;\n },\n hold(scroll) {\n if (!parked) return false;\n held = scroll ?? held;\n return true;\n },\n park() {\n const top = list.scrollTop;\n const first = [...list.querySelectorAll<HTMLElement>(\"li.msg\")].find((el) => el.offsetTop + el.offsetHeight > top);\n at = { id: first?.dataset.id ?? \"\", dy: (first?.offsetTop ?? 0) - top, top };\n parked = true;\n screen.abort();\n screen = new AbortController();\n },\n unpark() {\n parked = false;\n const scroll = held;\n held = undefined;\n return scroll;\n },\n restore(moved, scroll, draw, toBottom) {\n // The first message that came meanwhile was brought into view; else a scroll asked for meanwhile, or the bottom.\n if (!moved) {\n if (scroll) draw(scroll);\n else if (pinned) toBottom();\n else if (at) {\n const el = at.id && list.querySelector<HTMLElement>(`li.msg[data-id=\"${CSS.escape(at.id)}\"]`);\n list.scrollTop = el ? el.offsetTop - at.dy : at.top;\n }\n }\n at = undefined;\n },\n };\n}\n", "// The room's emoji picker, one for the composer and every message's reactions (\u00A720), and the composer's suggestions:\n// emoji by name (\u00A720.6) and people by handle (\u00A741). Each is a lazy chunk, loaded the first time it is needed.\n// (In views/room.ts until REFACTOR item 53.)\n\nimport type { Api } from \"../../api.ts\";\nimport type { Scope } from \"../../scope.ts\";\nimport * as S from \"../../strings/room-pickers.ts\";\nimport { avatar } from \"../../ui/avatar.ts\";\nimport type { EmojiPicker, PickerRequest } from \"../../ui/emoji-picker.ts\";\nimport type { EmojiSuggest } from \"../../ui/emoji-suggest.ts\";\n\nexport interface Pickers {\n /** The message the open picker reacts to (\"\": the composer's, or none). */\n readonly reactingTo: string;\n readonly isOpen: boolean;\n /**\n * Open the emoji picker next to `opener`, to react to message `reactingTo` (\"\" for the composer). If the chunk can't\n * be loaded (offline, or a new version was deployed), say so. Not if the opener went meanwhile.\n */\n open(opener: HTMLElement, req: PickerRequest, reactingTo?: string): Promise<void>;\n close(): void;\n /** Emoji by name in the composer: once loaded they follow the textarea. Quietly not, offline. */\n suggestEmoji(textarea: HTMLTextAreaElement): void;\n /** People by handle in the composer: once loaded it follows the textarea. Quietly not, offline. */\n suggestPeople(textarea: HTMLTextAreaElement): void;\n}\n\nexport function createPickers({\n api,\n roomId,\n shell,\n scope,\n say,\n}: {\n api: Api;\n roomId: () => string;\n /** Where the picker goes, once made. */\n shell: HTMLElement;\n scope: Scope;\n say: (text: string) => void;\n}): Pickers {\n const { signal } = scope;\n let picker: EmojiPicker | null = null;\n let reactingTo = \"\";\n let suggest: EmojiSuggest | Promise<unknown> | null = null;\n let people = false;\n\n return {\n get reactingTo() {\n return reactingTo;\n },\n get isOpen() {\n return !!picker?.isOpen;\n },\n async open(opener, req, to = \"\") {\n reactingTo = to;\n try {\n const { createEmojiPicker, loadStylesheet } = await import(\"../../ui/emoji-picker.ts\");\n await loadStylesheet();\n if (!scope.active || !opener.isConnected) return;\n if (!picker) {\n picker = createEmojiPicker({ signal });\n shell.append(picker.el);\n }\n picker.open(opener, req);\n } catch {\n if (scope.active) say(\"Couldn't open the emoji. Check your connection.\");\n }\n },\n close() {\n picker?.close();\n },\n suggestEmoji(textarea) {\n suggest ??= import(\"../../ui/emoji-picker.ts\").then(\n async ({ createEmojiSuggest, loadStylesheet }) => {\n await loadStylesheet();\n if (!scope.active) return;\n suggest = createEmojiSuggest({ textarea, signal });\n suggest.update(true);\n },\n () => {\n suggest = null;\n },\n );\n },\n suggestPeople(textarea) {\n if (people) return;\n people = true;\n void import(\"../../ui/mention-suggest.ts\").then(\n ({ createMentionSuggest }) =>\n scope.active &&\n createMentionSuggest({ api, textarea, room: roomId, avatar: (u) => avatar(u, 24, api.avatarUrl), signal }).update(),\n () => {\n people = false;\n },\n );\n },\n };\n}\n", "// What is on screen is read (\u00A718.3): up to the newest saved message shown whole, or everything once the newest\n// messages are on screen. Scrolling down through what is unread reads it as it comes into view. Nothing in a hidden\n// tab, or while a kept window shows before the server has said where the unread messages start (QA BUG-102).\n// (In views/room.ts until REFACTOR item 53.)\n\nimport { lastSaved } from \"../../lib/messages.ts\";\nimport { isNearBottom } from \"../../lib/scroll.ts\";\nimport type { Message } from \"../../lib/types.ts\";\nimport type { Scope } from \"../../scope.ts\";\nimport type { RoomReader } from \"../../unread.ts\";\nimport type { RoomState } from \"./controller.ts\";\n\nexport interface Reading {\n /** Start reporting to `reader` (unread.ts): on mount, and on coming back to a parked room. */\n open(reader: RoomReader): void;\n /** Stop (leaving, or parked). Left before the first page was in, the server may have more than the kept window\n * showed: it says what is unread. */\n leave(): void;\n /** Watch the rows a render added; forget those it took away. */\n watchRows(): void;\n /** Report what is on screen now. */\n markRead(): void;\n /** markRead after the next frame's layout: what a render changed may not cross a row's edge (a first page\n * replacing the kept one). */\n readSoon(): void;\n}\n\nexport function createReading(list: HTMLElement, state: () => RoomState, scope: Scope): Reading {\n let reader: RoomReader | null = null;\n /**\n * The messages shown whole or scrolled past, as the browser tells it (PERF.md \u00A75): their bottom is above the list's.\n * By id, the element that is. Measuring them ourselves after a render made the browser lay the list out at once,\n * and again for every scroll event.\n */\n const above = new Map<string, Element>();\n const rows = new IntersectionObserver(\n (entries) => {\n for (const e of entries) {\n const id = (e.target as HTMLElement).dataset.id!;\n if (e.intersectionRatio >= 0.999) above.set(id, e.target);\n else if (above.get(id) === e.target) above.delete(id);\n }\n markRead();\n },\n // Everything above the list's bottom counts: whole means the bottom is in.\n { root: list, rootMargin: \"1000000px 0px 0px 0px\", threshold: 1 },\n );\n scope.defer(() => rows.disconnect());\n const watched = new Set<Element>();\n let reading = false;\n\n /**\n * The newest messages are on screen: loaded, scrolled to the bottom, in a visible tab. Scrolled up, a new message\n * only shows the pill, and stays unread until you scroll down to it.\n */\n const atLiveEdge = () => {\n const s = state();\n return s.phase === \"ready\" && !s.win.hasNewer && !s.unsure && isNearBottom(list) && document.visibilityState !== \"hidden\";\n };\n\n /** The newest saved message whose bottom is on screen (or scrolled past). */\n function lastShown(): Message | undefined {\n const { items } = state().win;\n for (let i = items.length - 1; i >= 0; i--) {\n const m = items[i]!;\n if (!m.status && above.has(m.id)) return m;\n }\n return undefined;\n }\n\n function markRead() {\n const s = state();\n if (!reader || s.phase !== \"ready\" || s.unsure || document.visibilityState === \"hidden\") return;\n const caughtUp = atLiveEdge();\n const m = caughtUp ? lastSaved(s.win) : lastShown();\n if (m) reader.seen(m.created, caughtUp);\n }\n\n return {\n open(r) {\n reader = r;\n },\n leave() {\n reader?.close(atLiveEdge() && !state().stale);\n reader = null;\n },\n watchRows() {\n for (const el of watched) {\n if (el.parentNode === list) continue;\n rows.unobserve(el);\n watched.delete(el);\n const id = (el as HTMLElement).dataset.id!;\n if (above.get(id) === el) above.delete(id);\n }\n for (const el of list.children) {\n if (!el.classList.contains(\"msg\") || watched.has(el)) continue;\n rows.observe(el);\n watched.add(el);\n }\n },\n markRead,\n readSoon() {\n if (reading) return;\n reading = true;\n requestAnimationFrame(() =>\n setTimeout(() => {\n reading = false;\n if (scope.active) markRead();\n }),\n );\n },\n };\n}\n", "// Replying (\u00A719): the message the composer is replying to, kept in step with it. Edited, the quote shows the new text;\n// deleted (or the room archived), there is nothing left to reply to.\n\nimport { quoteText } from \"../../lib/messages.ts\";\nimport type { Message } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-reply.ts\";\nimport type { Composer } from \"./composer.ts\";\n\nexport interface Reply {\n /** The message being replied to, or null. */\n readonly to: Message | null;\n set(m: Message | null): void;\n /** Reply to message `id`, if it can be replied to, and put the caret in the composer. */\n start(id: string): void;\n /**\n * Ctrl+Up / Ctrl+Down: reply to the repliable message before (-1) or after (1) the current one, or to the newest\n * when not replying; after the newest, stop replying. False when there was nothing to do.\n */\n step(dir: -1 | 1): boolean;\n /** Follow the message after the list changed. Out of the window, it is checked against the room alone. */\n refresh(): void;\n}\n\nexport function createReply(opts: {\n find: (id: string) => Message | undefined;\n /** The messages on screen, oldest first. */\n list: () => readonly Message[];\n repliable: (m: Message) => boolean;\n composer: Pick<Composer, \"setReply\" | \"focus\">;\n /** Bring the message now replied to into view. */\n reveal?: (id: string) => void;\n}): Reply {\n const { composer } = opts;\n let to: Message | null = null;\n\n function set(m: Message | null) {\n to = m;\n composer.setReply(m && { name: m.expand?.author?.name ?? \"Unknown\", text: quoteText(m) });\n }\n\n return {\n get to() {\n return to;\n },\n set,\n start(id) {\n const m = opts.find(id);\n if (!m || !opts.repliable(m)) return;\n set(m);\n composer.focus();\n },\n step(dir) {\n const ms = opts.list().filter(opts.repliable);\n const at = ms.findIndex((m) => m.id === to?.id);\n const next = ms[at < 0 ? ms.length - 1 : at + dir];\n if (!to && (dir > 0 || !next)) return false;\n if (next) opts.reveal?.(next.id);\n if (next || dir > 0) set(next ?? null);\n return true;\n },\n refresh() {\n if (!to) return;\n const now = opts.find(to.id) ?? to;\n if (!opts.repliable(now)) set(null);\n else if (now !== to) set(now);\n },\n };\n}\n", "// Selecting messages (\u00A721.1): which ones are selected, and the bar shown instead of the composer meanwhile: how many,\n// Forward, Delete (only when every one is yours, with a confirm step) and Cancel. Up to MAX_SELECTED at a time.\n\nimport { h } from \"../../dom.ts\";\nimport { MAX_SELECTED } from \"../../lib/limits.ts\";\nimport type { Message } from \"../../lib/types.ts\";\nimport * as S from \"../../strings/room-selection.ts\";\nimport type { Notice } from \"./notice.ts\";\n\nconst LIMIT_NOTICE = `You can select up to ${MAX_SELECTED} messages at a time.`;\n\nexport interface Selection {\n /** The bar to show in place of the composer while selecting. */\n readonly bar: HTMLElement;\n /** The selected messages, or null when not selecting. */\n readonly ids: ReadonlySet<string> | null;\n /** Select or unselect message `id`: the first one starts selecting, unselecting the last one stops. */\n toggle(id: string): void;\n /** Stop selecting; `focus`: put the caret back in the composer. */\n end(focus?: boolean): void;\n /**\n * Unselect messages that left the window or can't be selected any more (deleted meanwhile), and bring the bar up to\n * date. Called before each render of the list; with nothing left selected, selecting stops.\n */\n prune(): void;\n /** Bring the bar's count and buttons up to date. */\n refresh(): void;\n /** Escape: step back out of the delete confirm, or stop selecting. False when not selecting. */\n escape(): boolean;\n}\n\nexport function createSelection(opts: {\n find: (id: string) => Message | undefined;\n selectable: (m: Message) => boolean;\n deletable: (m: Message) => boolean;\n /** Selecting started at message `id`. */\n onStart: (id: string) => void;\n /** Selecting started, changed or stopped: redraw the footer, and with `list`, the messages. */\n onChange: (list: boolean) => void;\n focusComposer: () => void;\n onForward: (ids: string[]) => void;\n /** Delete these messages (selecting has stopped by then). */\n onDelete: (ids: string[]) => void;\n notice: Notice;\n signal: AbortSignal;\n}): Selection {\n const { notice, signal } = opts;\n let selected: Set<string> | null = null;\n /** The bar asks \"Delete these messages?\". */\n let confirming = false;\n\n const bar = h(\"div\", { class: \"selection-bar\", role: \"toolbar\", \"aria-label\": \"Selected messages\" });\n const button = (label: string, run: () => void, cls = \"\") =>\n h(\"button\", { type: \"button\", class: cls, on: { click: run }, signal }, label);\n const count = h(\"span\", { class: \"sel-count\", role: \"status\" });\n const deleteBtn = button(\"Delete\", () => setConfirm(true), \"danger ic i-trash\");\n // The buttons wrap together: on a narrow screen they go under the count, Cancel never on a line of its own.\n const group = (...b: HTMLElement[]) => h(\"div\", { class: \"bar-actions\" }, b);\n const actions = [\n count,\n group(\n button(\"Forward\", () => opts.onForward([...(selected ?? [])]), \"primary ic i-fwd\"),\n deleteBtn,\n button(\"Cancel\", () => end(true)),\n ),\n ];\n const confirmText = h(\"span\");\n const confirmActions = [\n confirmText,\n group(\n button(\n \"Delete\",\n () => {\n const ids = [...(selected ?? [])];\n end(true);\n opts.onDelete(ids);\n },\n \"danger confirm-delete\",\n ),\n button(\"Cancel\", () => setConfirm(false), \"cancel\"),\n ),\n ];\n\n /** Every selected message is mine (and may still be deleted). */\n const allMine = () => !!selected?.size && [...selected].every((id) => opts.deletable(opts.find(id)!));\n\n function update() {\n const n = selected?.size ?? 0;\n if (confirming && allMine()) {\n confirmText.textContent = n === 1 ? \"Delete this message? \" : `Delete these ${n} messages? `;\n if (bar.firstChild !== confirmText) bar.replaceChildren(...confirmActions);\n return;\n }\n confirming = false;\n count.textContent = `${n} selected`;\n deleteBtn.hidden = !allMine();\n if (bar.firstChild !== count) bar.replaceChildren(...actions);\n }\n\n function setConfirm(on: boolean) {\n confirming = on;\n update();\n bar.querySelector<HTMLElement>(on ? \".cancel\" : \".danger\")?.focus();\n }\n\n function end(focus = false) {\n if (!selected) return;\n selected = null;\n confirming = false;\n notice.unsay(LIMIT_NOTICE);\n opts.onChange(true);\n if (focus) opts.focusComposer();\n }\n\n return {\n bar,\n get ids() {\n return selected;\n },\n toggle(id) {\n const m = opts.find(id);\n if (!m || !opts.selectable(m)) return;\n if (!selected) {\n selected = new Set();\n opts.onStart(id);\n }\n if (selected.has(id)) selected.delete(id);\n else if (selected.size >= MAX_SELECTED) return notice.say(LIMIT_NOTICE);\n else selected.add(id);\n confirming = false;\n if (!selected.size) return end(true);\n opts.onChange(true);\n },\n end,\n refresh: update,\n prune() {\n if (!selected) return;\n for (const id of selected) {\n const m = opts.find(id);\n if (!m || !opts.selectable(m)) selected.delete(id);\n }\n if (selected.size) return update();\n selected = null;\n opts.onChange(false);\n },\n escape() {\n if (!selected) return false;\n if (confirming) setConfirm(false);\n else end(true);\n return true;\n },\n };\n}\n", "// Room view (\u00A77.5, \u00A77.6): windowed message history, optimistic send, edit, soft delete, replies (\u00A719), reactions and\n// the emoji picker (\u00A720), selecting messages to forward or delete them (\u00A721), archived mode, read state (\u00A718.3).\n// The message window and everything that changes it live in room/controller.ts (no DOM). This module puts the\n// controller's changes on screen and wires the parts in room/: header (title + actions menu), search (\u00A729), messages (the list),\n// composer and footer (what shows instead of it), selection (the bar while selecting), reply, notice (the status line),\n// names (who reacted), pickers (emoji, suggestions), reading (read state), parking (kept while away), gallery (viewer\n// and media grid), badges (collections), forward dialog, access dialog (\u00A723.2). A guest reads an Open Air room without\n// a composer (\u00A723.3). Images and videos can be saved to collections and attached from them (\u00A731): the save menu and\n// the picker are the collections' lazy chunk.\n\nimport { errorMessage, reasonOf } from \"../api.ts\";\nimport type { Ctx } from \"../context.ts\";\nimport { clear, h, holdKeys, typeInto, uniqueId } from \"../dom.ts\";\nimport { PAGE_SIZE } from \"../lib/cursor.ts\";\nimport { emptyForward } from \"../lib/messages.ts\";\nimport { canManage, canPost, dmClosed, isDm, otherMember, roomTitle } from \"../lib/rooms.ts\";\nimport { isNearBottom } from \"../lib/scroll.ts\";\nimport { formatTime, parsePb } from \"../lib/time.ts\";\nimport type { View } from \"../router.ts\";\nimport { createScope } from \"../scope.ts\";\nimport { roomSections } from \"../store.ts\";\nimport * as S from \"../strings/room.ts\";\nimport { avatar } from \"../ui/avatar.ts\";\nimport { createLoadbar } from \"../ui/loadbar.ts\";\nimport type { AccessDialog } from \"./room/access.ts\";\nimport { createRoomCollections } from \"./room/badges.ts\";\nimport { createComposer, validEdit } from \"./room/composer.ts\";\nimport { type Change, createRoomController, type Phase, type RoomController } from \"./room/controller.ts\";\nimport { createFooter } from \"./room/footer.ts\";\nimport type { ForwardDialog } from \"./room/forward.ts\";\nimport { createGallery } from \"./room/gallery.ts\";\nimport { createRoomHeader } from \"./room/header.ts\";\nimport { createMessageList } from \"./room/messages.ts\";\nimport { createNameLookup } from \"./room/names.ts\";\nimport { createNotice } from \"./room/notice.ts\";\nimport { createParking } from \"./room/parking.ts\";\nimport { createPickers } from \"./room/pickers.ts\";\nimport { reactionFocus } from \"./room/reactions.ts\";\nimport { createReading } from \"./room/reading.ts\";\nimport { createReply } from \"./room/reply.ts\";\nimport { createSelection } from \"./room/selection.ts\";\n\n/**\n * Two changes as one: the later scroll and notice, and a render if either asked for one, keeping the anchor if either\n * did (content changed above what is on screen).\n */\nexport function mergeChanges(a: Change, b: Change): Change {\n const c = { ...a, ...b };\n if (a.render?.anchor) c.render = a.render;\n return c;\n}\n\n/** What the room view uses of the app shell's services. */\nexport type RoomCtx = Pick<\n Ctx,\n \"api\" | \"store\" | \"unread\" | \"actions\" | \"navigate\" | \"reopen\" | \"drafts\" | \"cache\" | \"collections\" | \"notify\" | \"early\"\n>;\n\nexport function createRoomView({\n api,\n store,\n unread,\n actions,\n navigate,\n reopen,\n drafts,\n cache,\n collections,\n notify,\n early,\n}: RoomCtx): View {\n const vid = uniqueId(\"room\");\n const scope = createScope();\n const { signal } = scope;\n let root: HTMLElement;\n let roomId = \"\";\n /** Created on mount, when the room id is known. */\n let ctl: RoomController;\n /** The phase the header, footer and list were last drawn for. */\n let shown: Phase = \"loading\";\n /** The messages the forward dialog is open for. */\n let forwarding: string[] = [];\n\n const room = () => store.get().rooms.get(roomId);\n const me = () => store.get().user;\n const state = () => ctl.state();\n\n // ---------------------------------------------------------------- parts\n\n const notice = createNotice(signal);\n const say = (text: string) => notice.say(text);\n const nameOf = createNameLookup({\n usersById: (ids, sig) => api.usersById(ids, sig),\n signedIn: () => !!me(),\n onFound: () => render({ anchor: true }),\n signal,\n });\n const colls = createRoomCollections({\n api,\n store,\n collections,\n scope,\n rerender: () => render({ anchor: true }),\n addItems: (items) => composer.addItems(items),\n say,\n });\n const header = createRoomHeader({\n titleId: `${vid}-title`,\n actions,\n avatarUrl: api.avatarUrl,\n onJumpToBeginning: () => void now(() => ctl.jump(\"first\")),\n onSearch: () => void openSearch(),\n onMedia: () => gallery.openGrid(),\n onAccess: () => void openAccess(),\n onClosed: () => navigate(\"/\"),\n onNotify: notify,\n signal,\n });\n /** The access dialog (\u00A723.2), once opened: a lazy chunk. */\n let accessDialog: AccessDialog | null = null;\n async function openAccess() {\n try {\n const { createAccessDialog } = await import(\"./room/access.ts\");\n if (!scope.active) return;\n accessDialog ??= newAccessDialog(createAccessDialog);\n let r = room();\n // A moderator's in someone else's room (\u00A736): its creator by name, who isn't expanded unless a member.\n const u = me();\n if (r && u && r.created_by !== u.id && !r.expand?.members?.some((x) => x.id === r!.created_by)) {\n const found = await api.usersById([r.created_by]).catch(() => []);\n if (!scope.active) return;\n r = room() ?? r;\n r = { ...r, expand: { ...r.expand, members: [...(r.expand?.members ?? []), ...found] } };\n }\n if (r) accessDialog.open(r, canManage(r, me()), me());\n } catch {\n if (scope.active) say(\"Couldn't open room access. Check your connection.\");\n }\n }\n const newAccessDialog = (create: typeof import(\"./room/access.ts\").createAccessDialog) => {\n const dialog = create({\n searchUsers: (q, sig) => api.searchUsers(q, sig),\n remoteUser: (address, room) => api.remoteUser(address, room),\n avatarUrl: api.avatarUrl,\n invites: () => api.invites(),\n inviteUrl: (token) => `${location.origin}/invite/${encodeURIComponent(token)}`,\n onSave: async (visibility, members, posting, writers) => {\n try {\n await actions.setAccess(roomId, visibility, members, posting, writers);\n return null;\n } catch (e) {\n return `Couldn't save. ${errorMessage(e)}`;\n }\n },\n signal,\n });\n shell.append(dialog.el);\n return dialog;\n };\n /** \"Beginning of #general\" / \"Beginning of your conversation with Bob\". */\n const beginningLabel = () => {\n const r = room();\n if (!r) return \"Beginning of the room\";\n return isDm(r) ? S.beginningOfYourConversationWith(otherMember(r, me())?.name) : `Beginning of #${r.name}`;\n };\n const messages = createMessageList({\n state: () => {\n const s = state();\n return {\n win: s.win,\n ready: s.phase === \"ready\",\n failed: s.phase === \"failed\",\n beginning: beginningLabel(),\n targetId: s.targetId,\n unreadId: s.unreadId,\n selected: selection.ids,\n };\n },\n me,\n editable: (m) => ctl.editable(m),\n deletable: (m) => ctl.deletable(m),\n repliable: (m) => ctl.repliable(m),\n onReply: (id) => reply.start(id),\n selectable: (m) => ctl.selectable(m),\n onSelect: (id) => selection.toggle(id),\n onForward: (id) => void openForward([id]),\n reactable: (m) => ctl.reactable(m),\n reactions: (m) => ctl.reactions(m),\n onReact: (id, emoji, on) => void react(id, emoji, on),\n onPickReaction: (id, opener) => pickReaction(id, opener),\n nameOf,\n onOpenQuote: (id, from) => void now(() => ctl.goTo(id, from)),\n onRetryLoad: () => now(() => ctl.retry()),\n onSaveEdit: (id, text) => void saveEdit(id, text),\n onCancelEdit: () => composer.focus(),\n onDelete: (id) => void doDelete(id),\n onRetrySend: (id) => void now(() => ctl.retrySend(id)),\n onDiscard: (id) => now(() => ctl.discard(id)),\n fileUrl: api.fileUrl,\n posterUrl: api.posterUrl,\n onOpenImage: (m, file, opener) => void gallery.view(m, file, opener),\n badge: colls.badge,\n ...(me() ? { onSave: colls.saveFile } : {}),\n avatarUrl: api.avatarUrl,\n onMessageUser: (userId) => void messageUser(userId),\n isBanned: (userId) => api.isBanned(userId),\n onBan: (userId, banned) => void setBanned(userId, banned),\n signal,\n });\n const composer = createComposer({\n id: `${vid}-text`,\n onSend: (text, files) => {\n if (!now(() => ctl.send(text, files, reply.to ?? undefined))) return false;\n reply.set(null);\n return true;\n },\n onEditLast: () => {\n const mine = ctl.lastEditable();\n if (mine) messages.startEdit(mine.id);\n return !!mine;\n },\n onStepReply: (dir) => reply.step(dir),\n onCancelReply: () => reply.set(null),\n onEmoji: (opener, insert) => void pickers.open(opener, { label: \"Insert emoji\", onPick: insert, restoreFocus: () => composer.focus() }),\n onEmojiName: (textarea) => pickers.suggestEmoji(textarea),\n onMention: (textarea) => pickers.suggestPeople(textarea),\n // Kept as you type, so a reload doesn't lose it (\u00A722.3).\n onChange: (text) => {\n if (roomId) drafts.set(roomId, text);\n },\n onCollections: colls.pickItems,\n signal,\n });\n /** The forward dialog (\u00A721.3), once Forward was chosen: a lazy chunk. */\n let forwardDialog: ForwardDialog | null = null;\n const newForwardDialog = (create: typeof import(\"./room/forward.ts\").createForwardDialog) =>\n create({\n rooms: () => {\n const s = roomSections(store.get());\n // Only where you may post (\u00A723.6), and not into a DM that takes no messages (\u00A716.7).\n return [...s.dms, ...s.rooms, ...s.hidden].filter((r) => canPost(r, me()) && !dmClosed(r, me()));\n },\n me,\n searchUsers: (q, sig) => api.searchUsers(q, sig),\n avatarUrl: api.avatarUrl,\n onPick: async (to) => {\n // Not those deleted since the dialog opened: one would fail the whole forward.\n const ids = forwarding.filter((id) => {\n const m = ctl.find(id);\n return !m || !(m.deleted || emptyForward(m));\n });\n if (!ids.length) return \"Couldn't forward. A message was deleted.\";\n try {\n const target = \"room\" in to ? to.room : await actions.openDm(to.user.id);\n const n = (await api.forward(ids, target.id)).length;\n if (!scope.active) return null;\n selection.end();\n if (target.id !== roomId) navigate(`/r/${target.id}`);\n else notice.flash(n === 1 ? \"Message forwarded.\" : `${n} messages forwarded.`);\n return null;\n } catch (e) {\n return `Couldn't forward. ${reasonOf(e)}`;\n }\n },\n signal,\n });\n const list = messages.el;\n const pill = h(\"button\", { type: \"button\", class: \"new-messages ic i-down\", hidden: true });\n const parking = createParking(list, signal);\n const reading = createReading(list, state, scope);\n const bar = createLoadbar();\n scope.defer(() => bar.set(false));\n\n const reply = createReply({\n find: (id) => ctl.find(id),\n list: () => state().win.items,\n repliable: (m) => ctl.repliable(m),\n composer,\n reveal: (id) => list.querySelector(`li[data-id=\"${CSS.escape(id)}\"]`)?.scrollIntoView?.({ block: \"nearest\" }),\n });\n\n // ---------------------------------------------------------------- selecting (\u00A721)\n\n const selection = createSelection({\n find: (id) => ctl.find(id),\n selectable: (m) => ctl.selectable(m),\n deletable: (m) => ctl.deletable(m),\n onStart: (id) => {\n pickers.close();\n messages.focusIn(id, [\"input.select\"], true);\n },\n onChange: (list) => {\n renderFooter();\n if (list) render({ anchor: true });\n },\n focusComposer: () => composer.focus(),\n onForward: (ids) => void openForward(ids),\n onDelete: (ids) => void deleteSelected(ids),\n notice,\n signal,\n });\n const footer = createFooter({\n composer,\n selection,\n room,\n me,\n closePicker: () => pickers.close(),\n parked: () => parking.parked,\n active: () => scope.active,\n signal,\n });\n const shell = h(\"section\", { class: \"room\", \"aria-labelledby\": `${vid}-title` }, [\n header.el,\n notice.el,\n h(\"div\", { class: \"room-body\" }, [bar.el, list, pill]),\n footer.el,\n ]);\n const pickers = createPickers({ api, roomId: () => roomId, shell, scope, say });\n const gallery = createGallery({\n api,\n roomId: () => roomId,\n room,\n win: () => state().win,\n goTo: (id) => now(() => ctl.goTo(id)),\n saveFile: colls.saveFile,\n signedIn: () => !!me(),\n screen: () => parking.screen,\n scope,\n say,\n });\n\n /** Render the list, then mark what it shows as read (once it is laid out). */\n function render(o?: { anchor?: boolean }) {\n selection.prune();\n messages.render(o);\n // Deleted (or gone from the list) meanwhile: nothing left to react to (QA BUG-121).\n if (pickers.reactingTo && pickers.isOpen) {\n const m = ctl.find(pickers.reactingTo);\n if (!m || !ctl.reactable(m)) pickers.close();\n }\n reading.watchRows();\n reading.readSoon();\n }\n\n async function deleteSelected(ids: string[]) {\n const failed = await now(() => ctl.removeMany(ids));\n // Say why: network trouble, rate limiting or the server's reason (QA BUG-58).\n if (failed && scope.active) say(`Couldn't delete those messages. ${reasonOf(failed)}`);\n }\n\n async function openForward(ids: string[]) {\n if (!ids.length) return;\n forwarding = ids;\n pickers.close();\n try {\n const { createForwardDialog } = await import(\"./room/forward.ts\");\n if (!scope.active || forwarding !== ids) return;\n if (!forwardDialog) {\n forwardDialog = newForwardDialog(createForwardDialog);\n shell.append(forwardDialog.el);\n }\n forwardDialog.open(ids.length);\n } catch {\n if (scope.active) say(\"Couldn't open Forward. Check your connection.\");\n }\n }\n\n /**\n * Changes are drawn at most once a frame. The first one is drawn right away (a message, a send or a click shows at\n * once); those that come in before the next frame are merged and drawn together in it. A burst of realtime events\n * then costs one render and one layout, not one each: every render ends by measuring the list (markRead,\n * renderPill), which makes the browser lay it out again.\n */\n let queued: Change | null = null;\n let frame = 0;\n /** Set while the user's own action runs: what it changes is drawn at once, never left for the next frame. */\n let direct = false;\n function apply(c: Change) {\n queued = queued ? mergeChanges(queued, c) : c;\n if (!frame || direct) flush();\n }\n\n /**\n * Draw what is queued, then keep merging until the next frame. Also called when the tab comes back: a hidden tab\n * has no frames.\n */\n function flush() {\n const q = queued;\n queued = null;\n if (!q || !scope.active) return;\n draw(q);\n frame ||= requestAnimationFrame(() => {\n frame = 0;\n flush();\n });\n }\n\n /** Run a controller call the user made (a click, a key): its changes show right away (see apply). */\n function now<T>(fn: () => T): T {\n direct = true;\n try {\n return fn();\n } finally {\n direct = false;\n }\n }\n\n /** Put a controller change on screen. */\n function draw(c: Change) {\n const s = state();\n if (s.phase !== shown) {\n shown = s.phase;\n if (s.phase === \"not-found\") return renderNotFound();\n list.setAttribute(\"aria-busy\", String(s.phase === \"loading\"));\n renderHeader();\n renderFooter();\n }\n if (c.notice !== undefined) say(c.notice);\n if (c.render) {\n render(c.render);\n reply.refresh();\n }\n if (parking.hold(c.scroll)) return;\n if (c.scroll === \"bottom\") scrollToBottom();\n else if (c.scroll === \"top\") list.scrollTop = 0;\n else if (c.scroll === \"target\") {\n // A message gone to is centred; the first unread one goes near the top, with what follows it below.\n const id = s.targetId ?? s.unreadId;\n const el = id && list.querySelector<HTMLElement>(`li[data-id=\"${CSS.escape(id)}\"]`);\n if (el) list.scrollTop = el.offsetTop - list.clientHeight / (s.targetId ? 2 : 4);\n }\n if (c.scroll) reading.markRead(); // what the scroll brought into view (render read where the list was before it)\n renderPill();\n }\n\n /**\n * The button over the bottom of the list: \"Back to reply\" after following quotes, one step back per click (\u00A719.5);\n * else \"New messages\" when some arrived out of sight (\u00A77.5), else \"Jump to latest\" whenever the newest messages\n * aren't on screen: scrolled up, or the window is back in history (\u00A722.7).\n */\n function renderPill() {\n const s = state();\n const away = s.phase === \"ready\" && (s.win.hasNewer || !isNearBottom(list));\n const back = s.phase === \"ready\" && s.back !== null;\n pill.hidden = s.pill === null && !away && !back;\n pill.classList.toggle(\"jump\", back || s.pill === null);\n pill.textContent = back\n ? \"Back to reply\"\n : s.pill === \"history\"\n ? \"New messages \u00B7 Jump to latest\"\n : s.pill === \"below\"\n ? \"New messages\"\n : \"Jump to latest\";\n }\n\n function scrollToBottom() {\n list.scrollTop = list.scrollHeight;\n reading.markRead();\n }\n\n function renderHeader() {\n header.update({ room: room(), hidden: store.get().hidden.has(roomId), me: me() });\n }\n\n const renderFooter = () => footer.render(shown === \"failed\");\n\n /** \"Message\" on an author: open the DM with them (\u00A716.5). */\n async function messageUser(userId: string) {\n try {\n const dm = await actions.openDm(userId);\n if (scope.active) navigate(`/r/${dm.id}`);\n } catch (e) {\n if (scope.active) say(`Couldn't open that conversation. ${errorMessage(e)}`);\n }\n }\n\n /** A moderator's Ban or Unban on an author (\u00A736). */\n async function setBanned(userId: string, banned: boolean) {\n try {\n await api.setBanned(userId, banned);\n if (scope.active) say(banned ? \"Banned. They can't sign in until unbanned.\" : \"Unbanned.\");\n } catch (e) {\n if (scope.active) say(S.couldntBan(banned, errorMessage(e)));\n }\n }\n\n /**\n * Shown \"not found\" or \"gone\": once the room is yours to see (again), the page starts over and shows it (\u00A723.4, QA\n * BUG-60). Clicking it in the room list couldn't: it is the same URL.\n */\n let offReturn: (() => void) | null = null;\n function awaitReturn() {\n offReturn ??= store.subscribe((s, prev) => {\n // Parked, it is made afresh when you come back (resume can't show it).\n if (s.rooms.has(roomId) && !prev.rooms.has(roomId) && s.user === prev.user && !parking.parked) reopen();\n });\n }\n\n /** The page's heading says it, as a room's name would (QA BUG-90). */\n const notFound = (title: string, rest: (Node | string)[]) => h(\"div\", { class: \"not-found\" }, [h(\"h1\", {}, title), h(\"p\", {}, rest)]);\n\n function renderNotFound() {\n awaitReturn();\n // A guest may have followed a link to a room that needs an account (\u00A723.3).\n const why = me() ? [] : [h(\"a\", { href: \"/login\" }, \"Log in\"), \" to see more rooms, or \"];\n const back = h(\"a\", { href: \"/\" }, me() ? \"Back to rooms\" : \"go back to the Open Air rooms\");\n shell.replaceChildren(notFound(\"This room doesn't exist.\", [...why, back]));\n }\n\n /**\n * The room went from the list while open (\u00A723.4): you were taken out of a private room, or it is no longer open to\n * guests. What was on screen goes too.\n */\n function renderGone() {\n shown = \"not-found\";\n awaitReturn();\n pickers.close();\n forwardDialog?.close();\n accessDialog?.close();\n const back = h(\"a\", { href: \"/\" }, \"Back to rooms\");\n shell.replaceChildren(notFound(\"You can't see this room any more.\", [back]));\n scope.dispose();\n }\n\n /** The search bar (\u00A729), while open. */\n let search: { el: HTMLElement; focus(): void } | null = null;\n\n /**\n * Open the search bar under the header, or focus it when open. A lazy chunk, loaded the first time; if it can't be\n * (offline, or a new version was deployed), say so.\n */\n async function openSearch() {\n if (search) return search.focus();\n // While the chunk loads: what is typed meanwhile, for the field once it shows, as Jump to keeps it (QA BUG-243).\n const held = holdKeys(signal);\n try {\n const { createSearch } = await import(\"./room/search.ts\");\n const toggle = shell.querySelector<HTMLElement>(\".search-toggle\");\n if (!scope.active || search) return; // opened meanwhile (it has focus)\n const r = room();\n search = createSearch({\n room: roomId,\n label: r ? roomTitle(r, me()) : \"this room\",\n page: (q, sig) => api.page(q, sig),\n pageSize: PAGE_SIZE,\n when: (m) => formatTime(parsePb(m.created)),\n avatar: (u) => avatar(u, 24, api.avatarUrl),\n onPick: (id) => void now(() => ctl.goTo(id)),\n onClose: () => {\n search = null;\n toggle?.setAttribute(\"aria-expanded\", \"false\");\n toggle?.focus();\n },\n signal,\n });\n header.el.after(search.el);\n toggle?.setAttribute(\"aria-expanded\", \"true\");\n search.focus();\n typeInto(search.el.querySelector(\"input\"), held.take());\n } catch {\n if (scope.active) say(\"Couldn't open search. Check your connection.\");\n } finally {\n held.take();\n }\n }\n\n // ---------------------------------------------------------------- edit / delete\n\n async function saveEdit(id: string, raw: string) {\n const m = ctl.find(id);\n const text = m ? validEdit(raw, !!m.files?.length) : null;\n if (text === null) return; // the edit box says what is wrong (messages.ts)\n messages.stopEdit();\n messages.setError(id, null);\n const saving = now(() => ctl.edit(id, text)); // renders the new text right away\n if (!saving) render(); // nothing to save: just close the box\n composer.focus();\n if ((await saving) !== false || !scope.active) return;\n messages.setError(id, { text: \"Couldn't save your edit.\", retry: () => void saveEdit(id, text) });\n render({ anchor: true });\n }\n\n async function doDelete(id: string) {\n messages.setError(id, null);\n if ((await now(() => ctl.remove(id))) !== false || !scope.active) return;\n messages.setError(id, { text: \"Couldn't delete this message.\", retry: () => void doDelete(id) });\n render({ anchor: true });\n }\n\n // ---------------------------------------------------------------- reactions\n\n /** Add or take back my reaction; focus stays on it (its message is redrawn). Failing, say so under the message. */\n async function react(id: string, emoji: string, on: boolean) {\n messages.setError(id, null);\n messages.focusIn(id, reactionFocus(emoji), true);\n const saving = now(() => ctl.react(id, emoji, on));\n if (!saving) return render({ anchor: true });\n const done = await saving;\n if (done === true || !scope.active) return;\n messages.setError(id, {\n text: done || (on ? `Couldn't add your ${emoji} reaction.` : `Couldn't remove your ${emoji} reaction.`),\n ...(done ? {} : { retry: () => void react(id, emoji, on) }),\n });\n render({ anchor: true });\n }\n\n /** The picker for a reaction to message `id`: picking an emoji I already reacted with takes it back. */\n function pickReaction(id: string, opener: HTMLElement) {\n const m = ctl.find(id);\n const user = me();\n if (!m || !user || !ctl.reactable(m)) return;\n const mine = new Set(ctl.reactions(m).flatMap((r) => (r.users.includes(user.id) ? [r.emoji] : [])));\n void pickers.open(\n opener,\n {\n label: \"Add reaction\",\n chosen: mine,\n onPick: (emoji) => void react(id, emoji, !mine.has(emoji)),\n restoreFocus: () => messages.focusIn(id, [\".actions .react\", \".reactions .add-reaction\"]),\n },\n id,\n );\n }\n\n // ---------------------------------------------------------------- lifecycle\n\n /** Single use: the router and the sidebar layout create a fresh view for every mount. */\n return {\n mount(el, params) {\n root = el;\n roomId = params.id!;\n ctl = createRoomController({\n api,\n store,\n roomId,\n msgId: params.msgId,\n scope,\n nearBottom: () => (parking.parked ? parking.pinned : isNearBottom(list)),\n onChange: apply,\n onUpload: (id, fraction) => messages.setUpload(id, fraction),\n onBusy: bar.set,\n cache,\n early: params.msgId ? undefined : early?.take(roomId),\n onEvent: gallery.changed,\n });\n\n pill.addEventListener(\n \"click\",\n () => {\n const s = state();\n if (s.back !== null) return void now(() => ctl.goBack());\n if (s.pill === \"history\" || s.win.hasNewer) return void now(() => ctl.jump(\"latest\"));\n scrollToBottom();\n ctl.dismissPill();\n renderPill();\n },\n { signal },\n );\n list.addEventListener(\"scroll\", () => isNearBottom(list) && ctl.dismissPill(), { signal });\n list.addEventListener(\"scroll\", renderPill, { signal });\n // Escape stops selecting (the forward dialog handles its own Escape).\n shell.addEventListener(\n \"keydown\",\n (e) => {\n if (e.key !== \"Escape\" || e.defaultPrevented || forwardDialog?.el.open) return;\n if (selection.escape()) e.preventDefault();\n },\n { signal },\n );\n document.addEventListener(\n \"visibilitychange\",\n () => {\n flush();\n reading.markRead();\n },\n { signal },\n );\n footer.bind(shell);\n // When the list gets shorter (the attachment tray opens, the textarea grows, the keyboard opens) while it is\n // at the live bottom, keep it there instead of letting the newest messages slide under the composer (BUG-31).\n if (typeof ResizeObserver === \"function\") {\n const resizes = new ResizeObserver(() => {\n const s = state();\n if (parking.pinned && !parking.parked && s.phase === \"ready\" && !s.win.hasNewer) scrollToBottom();\n });\n resizes.observe(list);\n scope.defer(() => resizes.disconnect());\n }\n\n const observer = new IntersectionObserver(\n (entries) => {\n for (const e of entries) {\n if (!e.isIntersecting || !list.contains(e.target)) continue;\n if (e.target === messages.topSentinel) void ctl.loadEdge(\"top\");\n if (e.target === messages.bottomSentinel) void ctl.loadEdge(\"bottom\");\n }\n },\n { root: list, rootMargin: \"300px 0px\" },\n );\n observer.observe(messages.topSentinel);\n observer.observe(messages.bottomSentinel);\n scope.defer(() => observer.disconnect());\n\n clear(root);\n root.append(shell);\n renderHeader();\n renderFooter();\n // What you were writing here before visiting another room (QA BUG-50) or reloading the page (\u00A722.3).\n composer.setText(drafts.get(roomId));\n\n store.set({ activeRoomId: roomId });\n // Not if another room is open by now (this one was kept, and goes).\n scope.defer(() => store.get().activeRoomId === roomId && store.set({ activeRoomId: null }));\n reading.open(unread.open(roomId));\n scope.defer(reading.leave);\n scope.defer(\n store.subscribe((s, prev) => {\n // Lost while you were in it (\u00A723.4). Not on logging out: the views start over then anyway.\n if (prev.rooms.has(roomId) && !s.rooms.has(roomId) && s.user === prev.user && shown !== \"not-found\") return renderGone();\n const roomChanged = s.rooms.get(roomId) !== prev.rooms.get(roomId);\n if (roomChanged || s.hidden !== prev.hidden || s.user !== prev.user) {\n renderHeader();\n renderFooter();\n if (roomChanged) {\n render();\n reply.refresh(); // archived: the reply bar closes\n }\n }\n }),\n );\n ctl.start();\n },\n park() {\n reading.leave();\n parking.park();\n pickers.close();\n forwardDialog?.close();\n accessDialog?.close();\n ctl.park();\n },\n resume() {\n if (!scope.active || shown === \"not-found\" || shown === \"failed\" || offReturn) return false;\n const scroll = parking.unpark();\n store.set({ activeRoomId: roomId });\n reading.open(unread.open(roomId));\n footer.focusNext();\n renderHeader();\n renderFooter();\n parking.restore(\n now(() => ctl.resume()),\n scroll,\n (s) => draw({ scroll: s }),\n scrollToBottom,\n );\n renderPill();\n reading.readSoon();\n return true;\n },\n unmount() {\n offReturn?.();\n scope.dispose();\n clear(root);\n },\n };\n}\n", "// The user-facing text of views/rooms.ts (docs/REFACTOR.md item 56): one module per source file, so a lazy\n// screen's text stays in its own chunk. Copy changes here; a translation would replace these.\n\nexport const ROOMS = \"Rooms\";\nexport const YOUR_PROFILE = \"Your profile\";\nexport const SETTINGS = \"Settings\";\nexport const YOURE_READING_AS_A_GUEST_ONLY = \"You're reading as a guest. Only Open Air rooms are listed.\";\nexport const LOG_IN = \"Log in\";\nexport const SIGN_UP = \"Sign up\";\nexport const COULDNT_LOAD_ROOMS_CHECK_YOUR_CONNECTION = \"Couldn't load rooms. Check your connection. \";\nexport const RETRY = \"Retry\";\nexport const couldntUnhide = (room: string, why: string) => `Couldn't unhide \u201C${room}\u201D. ${why}`;\nexport const couldntArchive = (archived: boolean, room: string, why: string) =>\n `Couldn't ${archived ? \"archive\" : \"unarchive\"} \u201C${room}\u201D. ${why}`;\nexport const COULDNT_OPEN_THE_PEOPLE_SEARCH_CHECK = \"Couldn't open the people search. Check your connection.\";\nexport const COULDNT_OPEN_COLLECTIONS_CHECK_YOUR_CONNECTION = \"Couldn't open collections. Check your connection.\";\nexport const couldntOpenTheConversationWith = (name: string | number, why: string | number) =>\n `Couldn't open the conversation with \u201C${name}\u201D. ${why}`;\nexport const UNHIDE = \"Unhide\";\nexport const UNARCHIVE = \"Unarchive\";\nexport const MENTIONS_YOU = \"Mentions you\";\nexport const HIDDEN_ARCHIVED = \"Hidden & archived\";\nexport const HIDDEN = \"Hidden\";\nexport const ARCHIVED = \"Archived\";\nexport const NOTHING_HIDDEN_OR_ARCHIVED = \"Nothing hidden or archived\";\nexport const NEW_ROOM = \"New room\";\nexport const NEW_MESSAGE = \"New message\";\nexport const NEW_COLLECTION = \"New collection\";\nexport const DIRECT_MESSAGES = \"Direct messages\";\nexport const COLLECTIONS = \"Collections\";\nexport const MENTIONS_REPLIES = \"Mentions & replies\";\nexport const NO_OTHER_ROOMS_HIDDEN_AND_ARCHIVED = \"No other rooms. Hidden and archived ones are listed below.\";\nexport const NO_ROOMS_YET_CREATE_THE_FIRST = \"No rooms yet. Create the first one.\";\nexport const OPEN_AIR_ROOMS = \"Open Air rooms\";\nexport const NO_OPEN_AIR_ROOMS_YET_LOG = \"No Open Air rooms yet. Log in to see the others.\";\nexport const CREATE_ROOM = \"Create room\";\nexport const WHO_CAN_SEE_IT = \"Who can see it\";\nexport const mustBeNoMoreThanCharacters = (roomName: string | number) => `Must be no more than ${roomName} characters.`;\nexport const ROOM_NAME = \"Room name\";\nexport const CANCEL = \"Cancel\";\nexport const A_ROOM_WITH_THIS_NAME_ALREADY = \"A room with this name already exists.\";\nexport const NEW = \" new\";\nexport const ITEM = \" item\";\nexport const ITEMS = \" items\";\nexport const MENTIONS_YOU_HIDDEN = \" mentions you,\";\nexport const UNREAD = \" unread\";\n", "// Room list (\u00A77.1, \u00A716.5): the site's name and \"Jump to\" (\u00A732) on top, Rooms / Direct messages / Collections (\u00A731) /\n// Hidden & archived sections, new-room form, user search, Unhide / Unarchive buttons, unread badges (\u00A718.4) and new items in\n// collections you follow, private and Open Air markers (\u00A723.1), and who you are (or the way in) at the foot. A guest\n// gets only the Open Air rooms, to read (\u00A723.3).\n// The data comes from the store, kept live by sync.ts; this view only renders it and issues commands.\n\nimport { ApiError, errorMessage, reasonOf } from \"../api.ts\";\nimport type { Ctx } from \"../context.ts\";\nimport { clear, h, holdKeys, reconcile, typeInto, uniqueId } from \"../dom.ts\";\nimport { brand, jumpButton } from \"../header.ts\";\nimport { LIMITS, textLength } from \"../lib/limits.ts\";\nimport { canManage, isAddress, otherMember, roomTitle, VISIBILITY, visibilityOf } from \"../lib/rooms.ts\";\nimport type { Collection, Room, User, Visibility } from \"../lib/types.ts\";\nimport { HOVER_MS } from \"../prefetch.ts\";\nimport type { View } from \"../router.ts\";\nimport { createScope, type Scope } from \"../scope.ts\";\nimport { mentioned, roomSections, unreadCount } from \"../store.ts\";\nimport * as S from \"../strings/rooms.ts\";\nimport { avatar } from \"../ui/avatar.ts\";\nimport { collectionIcon } from \"../ui/icon.ts\";\nimport { createLoadbar } from \"../ui/loadbar.ts\";\nimport type { MenuItem } from \"../ui/menu.ts\";\nimport type { UserSearch } from \"../ui/user-search.ts\";\nimport { chunkContext, collectionChunk } from \"./collection.ts\";\n\ntype Section = \"rooms\" | \"dms\" | \"hidden\" | \"archived\";\n\nconst FOLD_KEY = \"chat.folded\";\n/** Sections folded by their heading (Rooms, Direct messages, Collections), remembered in this browser. */\nconst folded = new Set<string>();\ntry {\n for (const s of JSON.parse(localStorage.getItem(FOLD_KEY) ?? \"[]\")) folded.add(s);\n} catch {}\n\nfunction nameError(err: unknown): string {\n if (err instanceof ApiError && err.codes.name === \"validation_not_unique\") return \"A room with this name already exists.\";\n if (err instanceof ApiError && err.fields.name) return err.fields.name;\n return errorMessage(err);\n}\n\n/** A private or Open Air room's marker next to its name (public rooms have none: they are the usual kind). */\nexport function visibilityMark(v: Visibility): HTMLElement | null {\n if (v === \"public\") return null;\n const { label } = VISIBILITY[v];\n return h(\"span\", { class: `vis ic ${v === \"open\" ? \"i-globe\" : \"i-lock\"}`, title: label }, [\n h(\"span\", { class: \"visually-hidden\" }, ` (${label})`),\n ]);\n}\n\n/** What the room list uses of the app shell's services. */\nexport type RoomsCtx = Pick<Ctx, \"api\" | \"store\" | \"sync\" | \"unread\" | \"actions\" | \"navigate\" | \"collections\" | \"early\">;\n\nexport function createRoomsView({ api, store, sync, unread, actions, navigate, collections, early }: RoomsCtx): View {\n const id = uniqueId(\"rooms\");\n let root: HTMLElement;\n let scope: Scope;\n\n // UI state that must survive re-renders.\n let moreOpen = false;\n /** Room rows by room id, with what they were drawn from (roomRow). */\n const rows = new Map<string, { sig: unknown[]; el: HTMLElement }>();\n /** The sections, built on mount (skeleton). */\n let parts: ReturnType<typeof skeleton>;\n /** The last failed action, shown until the next action or a successful one. */\n let actionError = \"\";\n /** The \"New message\" user search, while open (kept across renders, so typing and focus survive). */\n let search: UserSearch | null = null;\n /** The new-room form, built once per mount and shown while `creating` (so a half-typed name survives). */\n let newRoom: { form: HTMLFormElement; input: HTMLInputElement; reset: () => void };\n const guest = () => !store.get().user;\n let creating = false;\n /** Collection rows by id, with what they were drawn from. */\n const collRows = new Map<string, { sig: unknown[]; el: HTMLElement }>();\n\n const alert = h(\"p\", { role: \"alert\", class: \"list-error\" });\n const nav = h(\"nav\", { \"aria-label\": \"Rooms\" });\n const shell = h(\"section\", { class: \"rooms\", \"aria-busy\": \"true\" });\n const top = h(\"div\", { class: \"side-top\" });\n const foot = h(\"div\", { class: \"side-foot\" });\n const bar = createLoadbar();\n /** What top and foot were drawn for. */\n let drawn: unknown[] = [];\n\n /** The site's name; at the foot, who you are and your settings, or (a guest) the way in. */\n function renderEnds() {\n const { site, user } = store.get();\n if (drawn[0] === site && drawn[1] === user) return;\n drawn = [site, user];\n top.replaceChildren(brand(site, true));\n foot.replaceChildren(\n ...(user\n ? [\n h(\"a\", { href: \"/me\", class: \"me-link\", title: \"Your profile\", \"aria-current\": location.pathname === \"/me\" ? \"page\" : null }, [\n avatar(user, 32, api.avatarUrl),\n h(\"span\", { class: \"who\" }, user.name),\n ]),\n h(\"a\", { href: \"/me\", class: \"icon-button ic i-gear\", \"aria-label\": \"Settings\", title: \"Settings\" }),\n ]\n : [\n h(\"p\", {}, \"You're reading as a guest. Only Open Air rooms are listed.\"),\n h(\"a\", { href: \"/login\", class: \"button\" }, \"Log in\"),\n h(\"a\", { href: \"/signup\", class: \"button primary\" }, \"Sign up\"),\n ]),\n );\n }\n\n function renderAlert() {\n clear(alert);\n if (store.get().roomsStatus === \"error\") {\n alert.append(\n \"Couldn't load rooms. Check your connection. \",\n h(\n \"button\",\n {\n type: \"button\",\n class: \"link\",\n on: {\n click: () => {\n void sync.reload();\n unread.refresh();\n },\n },\n signal: scope.signal,\n },\n \"Retry\",\n ),\n );\n } else {\n alert.append(actionError);\n }\n }\n\n const title = (r: Room) => roomTitle(r, store.get().user);\n\n async function act(failed: (room: string, why: string) => string, room: Room, fn: () => Promise<void>) {\n try {\n await fn();\n actionError = \"\";\n } catch (e) {\n // Say why: network trouble, rate limiting or the server's reason (QA BUG-39).\n actionError = failed(room.kind === \"dm\" ? title(room) : room.name, errorMessage(e));\n }\n if (scope.active) renderAlert();\n }\n\n /** The people search's chunk, once asked for; and a search is on its way (New message pressed while it loads). */\n let searchChunk: Promise<typeof import(\"../ui/user-search.ts\")> | null = null;\n let opening = false;\n /** What is typed while the chunk loads goes in the field once it shows (QA BUG-252). */\n let held: { take(): string } | null = null;\n\n function toggleSearch(open: boolean) {\n if (open === (!!search || opening)) return;\n if (!open) {\n held?.take();\n held = null;\n opening = false;\n search = null;\n render();\n return;\n }\n opening = true;\n held = holdKeys(scope.signal);\n searchChunk ??= import(\"../ui/user-search.ts\");\n searchChunk.then(\n (m) => {\n const early = held?.take() ?? \"\";\n held = null;\n if (!opening || !scope.active) return;\n opening = false;\n showSearch(m, early);\n },\n () => {\n held?.take();\n held = null;\n searchChunk = null;\n if (!opening) return;\n opening = false;\n actionError = \"Couldn't open the people search. Check your connection.\";\n if (scope.active) renderAlert();\n },\n );\n }\n\n function showSearch({ createUserSearch, SearchError }: typeof import(\"../ui/user-search.ts\"), early = \"\") {\n search = createUserSearch({\n // Not those who take no direct messages (\u00A716.7). \"ann@b.example\" is someone on a linked instance (\u00A733.5).\n search: async (q, signal) => {\n if (!isAddress(q)) return (await api.searchUsers(q, signal)).filter((u) => !u.no_dms);\n try {\n return [await api.remoteUser(q)];\n } catch (e) {\n throw new SearchError(reasonOf(e));\n }\n },\n avatarUrl: api.avatarUrl,\n onPick: (u) => void message(u),\n onClose: () => {\n toggleSearch(false);\n nav.querySelector<HTMLElement>(\"button.new-dm\")?.focus();\n },\n signal: scope.signal,\n });\n render();\n search.focus();\n typeInto(search.el.querySelector(\"input\"), early);\n }\n\n function toggleNewRoom(open: boolean) {\n if (open === creating) return;\n creating = open;\n if (!open) newRoom.reset();\n render();\n if (open) newRoom.input.focus();\n else nav.querySelector<HTMLElement>(\"button.new-room-toggle\")?.focus();\n }\n\n /** \"+\" in Collections (\u00A731): the new-collection dialog, from the collections' chunk. */\n function newCollection(opener: HTMLElement) {\n collectionChunk().then(\n (c) =>\n scope.active &&\n void c.openCreate({\n ...chunkContext({ api, store, collections }),\n signal: scope.signal,\n opener,\n onCreated: (cid) => navigate(`/c/${cid}`),\n }),\n () => {\n actionError = \"Couldn't open collections. Check your connection.\";\n if (scope.active) renderAlert();\n },\n );\n }\n\n /** A collection's row (\u00A731): yours (a lock when private), or one you follow with whose it is and what is new. */\n function collectionRow(c: Collection): HTMLElement {\n const current = store.get().activeCollectionId === c.id;\n const n = c.owner ? (c.new ?? 0) : 0;\n const sig = [c.name, c.public, c.owner?.name, n, current, c.items];\n const hit = collRows.get(c.id);\n if (hit?.sig.every((v, i) => v === sig[i])) return hit.el;\n const el = h(\n \"li\",\n // t0..t3: the icon's tint, by id, so it stays put as collections come and go.\n { class: `t${c.id.charCodeAt(0) % 4}`, dataset: { collectionId: c.id } },\n h(\"a\", { href: `/c/${c.id}`, class: n ? \"unread\" : \"\", \"aria-current\": current ? \"page\" : null }, [\n collectionIcon(),\n h(\"span\", {}, c.name),\n c.owner ? h(\"span\", { class: \"owner\" }, c.owner.name) : null,\n c.public ? null : visibilityMark(\"private\"),\n n\n ? h(\"span\", { class: \"badge\" }, [n > 99 ? \"99+\" : n, h(\"span\", { class: \"visually-hidden\" }, \" new\")])\n : h(\"span\", { class: \"n\" }, [c.items, h(\"span\", { class: \"visually-hidden\" }, c.items === 1 ? \" item\" : \" items\")]),\n ]),\n );\n collRows.set(c.id, { sig, el });\n return el;\n }\n\n async function message(user: User) {\n try {\n const room = await actions.openDm(user.id);\n actionError = \"\";\n if (!scope.active) return;\n toggleSearch(false);\n navigate(`/r/${room.id}`);\n } catch (e) {\n actionError = `Couldn't open the conversation with \u201C${user.name}\u201D. ${errorMessage(e)}`;\n }\n if (scope.active) renderAlert();\n }\n\n const unhide = (r: Room) => act(S.couldntUnhide, r, () => actions.unhide(r.id));\n const setArchived = (r: Room, archived: boolean) =>\n act(\n (name, why) => S.couldntArchive(archived, name, why),\n r,\n () => actions.setArchived(r.id, archived),\n );\n\n // ---- rendering ----\n\n /**\n * A hidden or archived room's button: Unhide, else Unarchive for its owner or a moderator (\u00A736). Everything else (Hide, Archive, Close\n * conversation) is in the room's own menu; the list has no per-row menus.\n */\n function rowAction(r: Room, section: Section): MenuItem | null {\n if (guest() || section === \"rooms\" || section === \"dms\") return null;\n // An archived room you had hidden is listed under Archived; it can still be unhidden from there.\n if (section === \"hidden\" || store.get().hidden.has(r.id)) return { label: \"Unhide\", run: () => void unhide(r) };\n if (canManage(r, store.get().user)) return { label: \"Unarchive\", run: () => void setArchived(r, false) };\n return null;\n }\n\n /**\n * A room's row. Rows are kept and reused while everything they show is the same (rooms are replaced, never mutated,\n * in the store): a message in some room changes one badge, not all the rows (\u00A718.4).\n */\n function roomRow(r: Room, section: Section): HTMLElement {\n const s = store.get();\n const current = s.activeRoomId === r.id;\n const n = unreadCount(s, r);\n const at = mentioned(s, r);\n // What the row and its button depend on (rowAction reads the user and, when archived, hidden).\n const sig = [r, section, n, current, s.user, section === \"archived\" && s.hidden.has(r.id), at];\n const hit = rows.get(r.id);\n if (hit?.sig.every((v, i) => v === sig[i])) return hit.el;\n const other = r.kind === \"dm\" ? otherMember(r, s.user) : undefined;\n const one = rowAction(r, section);\n const label = [\n other ? avatar(other, 24, api.avatarUrl) : null,\n h(\"span\", {}, other ? other.name : r.kind === \"dm\" ? title(r) : r.name),\n r.kind === \"dm\" ? null : visibilityMark(visibilityOf(r)),\n // Unread mentions of you or replies to you (\u00A741).\n at\n ? h(\"span\", { class: \"badge\", title: \"Mentions you\" }, [\"@\", h(\"span\", { class: \"visually-hidden\" }, \" mentions you,\")])\n : null,\n n ? h(\"span\", { class: \"badge\" }, [n > 99 ? \"99+\" : n, h(\"span\", { class: \"visually-hidden\" }, \" unread\")]) : null,\n ];\n const el = h(\"li\", { class: r.kind === \"dm\" ? \"dm\" : \"\", dataset: { roomId: r.id } }, [\n h(\"a\", { href: `/r/${r.id}`, class: n ? \"unread\" : \"\", \"aria-current\": current ? \"page\" : null }, label),\n one\n ? h(\n \"button\",\n { type: \"button\", class: \"row-action\", \"aria-label\": `${one.label} ${r.name}`, on: { click: one.run }, signal: scope.signal },\n one.label,\n )\n : null,\n ]);\n rows.set(r.id, { sig, el });\n return el;\n }\n\n /** Hidden & archived (\u00A77.1): folded, with how many there are; inside, a part for each. */\n function collapsible() {\n const count = h(\"span\", { class: \"count\" });\n const summary = h(\"summary\", { class: \"ic i-chev\" }, [h(\"span\", {}, \"Hidden & archived\"), count]);\n const part = (section: \"hidden\" | \"archived\", title: string, icon: string) => {\n const list = h(\"ul\");\n const el = h(\"div\", { class: \"more-part\", dataset: { section } }, [h(\"h3\", { class: `ic ${icon}` }, title), list]);\n return { el, list };\n };\n const hidden = part(\"hidden\", \"Hidden\", \"i-eyeoff\");\n const archived = part(\"archived\", \"Archived\", \"i-archive\");\n const empty = h(\"p\", { class: \"empty\" }, \"Nothing hidden or archived\");\n const body = h(\"div\", { class: \"more-body\" });\n const el = h(\n \"details\",\n {\n class: \"room-section\",\n dataset: { section: \"more\" },\n open: moreOpen,\n on: { toggle: (e) => (moreOpen = (e.currentTarget as HTMLDetailsElement).open) },\n signal: scope.signal,\n },\n [summary, body],\n );\n return { el, count, body, empty, hidden, archived };\n }\n\n /**\n * The list's sections, built once per mount and then only updated (the rows in them are reused too, see roomRow):\n * the room list is redrawn on every unread change, so for every message in any room.\n */\n function skeleton() {\n const newRoomToggle = h(\"button\", {\n type: \"button\",\n class: \"icon-button ic i-plus new-room-toggle\",\n \"aria-label\": \"New room\",\n title: \"New room\",\n on: { click: () => toggleNewRoom(!creating) },\n signal: scope.signal,\n });\n const newDm = h(\"button\", {\n type: \"button\",\n class: \"icon-button ic i-plus new-dm\",\n \"aria-label\": \"New message\",\n title: \"New message\",\n on: { click: () => toggleSearch(!(search || opening)) },\n signal: scope.signal,\n });\n const newColl = h(\"button\", {\n type: \"button\",\n class: \"icon-button ic i-plus new-coll\",\n \"aria-label\": \"New collection\",\n title: \"New collection\",\n \"aria-haspopup\": \"dialog\",\n on: { click: () => newCollection(newColl) },\n signal: scope.signal,\n });\n // A section's heading folds it: then only its unread rows and the open one stay listed.\n const head = (section: string, title: string, add: HTMLElement) =>\n h(\"div\", { class: \"section-head\" }, [\n h(\n \"h2\",\n {},\n h(\n \"button\",\n {\n type: \"button\",\n class: \"fold ic i-chev\",\n dataset: { fold: section },\n on: {\n click: () => {\n if (!folded.delete(section)) folded.add(section);\n try {\n localStorage.setItem(FOLD_KEY, JSON.stringify([...folded]));\n } catch {}\n render();\n },\n },\n signal: scope.signal,\n },\n title,\n ),\n ),\n add,\n ]);\n return {\n newRoomToggle,\n newDm,\n main: h(\"div\", { class: \"room-section\", dataset: { section: \"rooms\" } }),\n mainHead: head(\"rooms\", \"Rooms\", newRoomToggle),\n rooms: h(\"ul\"),\n empty: h(\"p\", { class: \"empty\" }),\n direct: h(\"div\", { class: \"room-section\", dataset: { section: \"dms\" } }),\n directHead: head(\"dms\", \"Direct messages\", newDm),\n dms: h(\"ul\"),\n newColl,\n collHead: head(\"collections\", \"Collections\", newColl),\n colls: h(\"div\", { class: \"room-section\", dataset: { section: \"collections\" } }),\n collList: h(\"ul\"),\n more: collapsible(),\n inbox: h(\"div\", { class: \"room-section\", dataset: { section: \"inbox\" } }),\n inboxList: h(\"ul\"),\n /** \"Jump to\u2026\" (\u00A732): the first row, a search icon and its shortcut, rather than a search field. */\n jump: h(\"li\", { class: \"jump-row\" }, jumpButton(true)),\n /** The \"Mentions & replies\" row, rebuilt when its count or the page changes. */\n inboxItem: null as HTMLElement | null,\n };\n }\n\n /** \"Mentions & replies\" (\u00A741), right after Jump to, with how many you haven't seen. */\n function inboxRow(n: number) {\n return h(\n \"li\",\n {},\n h(\"a\", { href: \"/inbox\", class: n ? \"unread\" : \"\", \"aria-current\": location.pathname === \"/inbox\" ? \"page\" : null }, [\n h(\"span\", {}, \"Mentions & replies\"),\n n ? h(\"span\", { class: \"badge\" }, [n > 99 ? \"99+\" : n, h(\"span\", { class: \"visually-hidden\" }, \" new\")]) : null,\n ]),\n );\n }\n\n function render() {\n if (!scope.active) return;\n if (guest()) return renderGuest();\n const s = store.get();\n const { rooms, dms, hidden, archived } = roomSections(s);\n const loading = s.roomsStatus === \"idle\" || s.roomsStatus === \"loading\";\n // Rows whose room changed are rebuilt; the focused control, when it is kept, gets its focus back below.\n const focused = nav.contains(document.activeElement) ? (document.activeElement as HTMLElement) : null;\n shell.setAttribute(\"aria-busy\", String(loading));\n const p = parts;\n const keep = (r: Room) => unreadCount(s, r) || s.activeRoomId === r.id;\n const shown = <T>(section: string, list: T[], keep: (x: T) => unknown) => (folded.has(section) ? list.filter(keep) : list);\n p.newRoomToggle.setAttribute(\"aria-expanded\", String(creating));\n reconcile(\n p.rooms,\n shown(\"rooms\", rooms, keep).map((r) => roomRow(r, \"rooms\")),\n );\n // Rooms you hid (or that were archived) are still there, under their own sections (QA BUG-44).\n p.empty.textContent = hidden.length || archived.length ? \"No other rooms. Hidden and archived ones are listed below.\" : \"No rooms yet. Create the first one.\";\n const mainList = rooms.length ? p.rooms : s.roomsStatus === \"ready\" ? p.empty : null;\n reconcile(\n p.main,\n [p.mainHead, creating ? newRoom.form : null, mainList].filter((n) => n !== null),\n );\n p.newDm.setAttribute(\"aria-expanded\", String(!!search));\n reconcile(\n p.dms,\n shown(\"dms\", dms, keep).map((r) => roomRow(r, \"dms\")),\n );\n reconcile(\n p.direct,\n [p.directHead, search?.el ?? null, dms.length ? p.dms : null].filter((n) => n !== null),\n );\n const c = s.collections;\n const all = c ? [...c.mine, ...c.subs] : [];\n reconcile(p.collList, shown(\"collections\", all, (x) => (x.owner && x.new) || s.activeCollectionId === x.id).map(collectionRow));\n for (const id of collRows.keys()) if (!all.some((x) => x.id === id)) collRows.delete(id);\n reconcile(\n p.colls,\n [p.collHead, all.length ? p.collList : null].filter((n) => n !== null),\n );\n const m = p.more;\n m.count.textContent = String(hidden.length + archived.length);\n for (const [section, list] of [\n [\"hidden\", hidden],\n [\"archived\", archived],\n ] as const)\n reconcile(\n m[section].list,\n list.map((r) => roomRow(r, section)),\n );\n reconcile(\n m.body,\n [\n hidden.length ? m.hidden.el : null,\n archived.length ? m.archived.el : null,\n hidden.length || archived.length ? null : m.empty,\n ].filter((n) => n !== null),\n );\n const key = `${s.inbox} ${location.pathname}`;\n if (p.inbox.dataset.k !== key) {\n p.inbox.dataset.k = key;\n p.inboxItem = inboxRow(s.inbox);\n }\n // Jump to is kept (not redrawn with the count), so it keeps focus.\n reconcile(p.inboxList, [p.jump, p.inboxItem!]);\n reconcile(p.inbox, [p.inboxList]);\n reconcile(nav, [p.inbox, p.main, p.direct, p.colls, m.el]);\n for (const b of nav.querySelectorAll<HTMLElement>(\"[data-fold]\"))\n b.setAttribute(\"aria-expanded\", String(!folded.has(b.dataset.fold as string)));\n if (focused?.isConnected && document.activeElement !== focused) focused.focus();\n forget();\n reveal(s.activeRoomId ?? s.activeCollectionId ?? null);\n }\n\n /**\n * The open room's (or collection's) row is brought into sight once when that changes: opened from a link, Jump to or\n * Back, it may be far down the list (QA BUG-228). Not listed yet, or out of sight (a folded section, the narrow\n * layout's room page), it is tried again on the next render.\n */\n let revealed: string | null = null;\n function reveal(id: string | null) {\n if (id === revealed) return;\n const row = nav.querySelector<HTMLElement>('a[aria-current=\"page\"]');\n if (id && !row?.offsetParent) return;\n revealed = id;\n if (!row) return;\n const r = row.getBoundingClientRect();\n const n = nav.getBoundingClientRect();\n nav.scrollTop += Math.min(0, r.top - n.top) || Math.max(0, r.bottom - n.bottom);\n }\n\n /** Drop the rows of rooms no longer listed. */\n function forget() {\n for (const [id, row] of rows) if (!nav.contains(row.el)) rows.delete(id);\n }\n\n /** A guest's list (\u00A723.3): the Open Air rooms, which are all the server gives them. */\n function renderGuest() {\n const s = store.get();\n const { rooms } = roomSections(s);\n const loading = s.roomsStatus === \"idle\" || s.roomsStatus === \"loading\";\n shell.setAttribute(\"aria-busy\", String(loading));\n nav.replaceChildren(\n h(\"div\", { class: \"room-section\", dataset: { section: \"jump\" } }, h(\"ul\", {}, parts.jump)),\n h(\"div\", { class: \"room-section\", dataset: { section: \"rooms\" } }, [\n h(\"div\", { class: \"section-head\" }, h(\"h2\", { class: \"section-title\" }, \"Open Air rooms\")),\n rooms.length\n ? h(\n \"ul\",\n {},\n rooms.map((r) => roomRow(r, \"rooms\")),\n )\n : s.roomsStatus === \"ready\"\n ? h(\"p\", { class: \"empty\" }, \"No Open Air rooms yet. Log in to see the others.\")\n : null,\n ]),\n );\n forget();\n }\n\n function newRoomForm(): typeof newRoom {\n const inputId = `${id}-name`;\n const errId = `${inputId}-error`;\n const err = h(\"p\", { id: errId, class: \"field-error\" });\n const input = h(\"input\", {\n id: inputId,\n name: \"name\",\n required: true,\n // No `maxlength`: it counts UTF-16 units (an emoji is 2), the server counts characters. Checked on submit.\n autocomplete: \"off\",\n placeholder: \"room-name\",\n \"aria-describedby\": errId,\n });\n const submit = h(\"button\", { type: \"submit\" }, \"Create room\");\n // Who can see it (\u00A723.1): public unless chosen otherwise; members of a private room are added from the room.\n const hint = h(\"p\", { class: \"hint\" });\n const choices = ([\"public\", \"private\", \"open\"] as const).map((v) =>\n h(\"input\", { type: \"radio\", name: \"visibility\", value: v, class: \"visually-hidden\" }),\n );\n const chosen = () => (choices.find((c) => c.checked)?.value ?? \"public\") as Visibility;\n const showHint = () => {\n hint.textContent = VISIBILITY[chosen()].hint;\n };\n const choose = (v: Visibility) => {\n for (const c of choices) c.checked = c.value === v;\n showHint();\n };\n const seg = h(\"fieldset\", { class: \"seg\", on: { change: showHint }, signal: scope.signal }, [\n h(\"legend\", { class: \"visually-hidden\" }, \"Who can see it\"),\n ...choices.map((c) =>\n h(\"label\", { class: c.value === \"public\" ? \"\" : `ic ${c.value === \"private\" ? \"i-lock\" : \"i-globe\"}` }, [\n c,\n VISIBILITY[c.value as Visibility].label,\n ]),\n ),\n ]);\n choose(\"public\");\n const setError = (msg: string) => {\n err.textContent = msg;\n if (msg) input.setAttribute(\"aria-invalid\", \"true\");\n else input.removeAttribute(\"aria-invalid\");\n };\n const form = h(\n \"form\",\n {\n class: \"new-room\",\n on: {\n keydown: (e) => {\n if (e.key === \"Escape\") toggleNewRoom(false);\n },\n submit: async (e) => {\n e.preventDefault();\n if (submit.disabled) return;\n if (textLength(input.value.trim()) > LIMITS.roomName) {\n setError(`Must be no more than ${LIMITS.roomName} characters.`);\n return;\n }\n submit.disabled = true;\n setError(\"\");\n try {\n const room = await actions.create(input.value, chosen());\n if (!scope.active) return;\n toggleNewRoom(false);\n navigate(`/r/${room.id}`);\n } catch (e) {\n if (scope.active) setError(nameError(e));\n } finally {\n submit.disabled = false;\n }\n },\n },\n signal: scope.signal,\n },\n [\n h(\"label\", { class: \"name-field\" }, [\n h(\"span\", { \"aria-hidden\": \"true\" }, \"#\"),\n h(\"span\", { class: \"visually-hidden\" }, \"Room name\"),\n input,\n ]),\n err,\n seg,\n hint,\n h(\"div\", { class: \"form-buttons\" }, [\n h(\"button\", { type: \"button\", class: \"cancel\", on: { click: () => toggleNewRoom(false) }, signal: scope.signal }, \"Cancel\"),\n submit,\n ]),\n ],\n );\n return {\n form,\n input,\n reset() {\n input.value = \"\";\n choose(\"public\");\n setError(\"\");\n },\n };\n }\n\n return {\n mount(el) {\n root = el;\n scope = createScope();\n rows.clear();\n search = null;\n opening = false;\n creating = false;\n collRows.clear();\n newRoom = newRoomForm();\n parts = skeleton();\n drawn = [];\n renderEnds();\n shell.replaceChildren(top, bar.el, alert, nav, foot);\n bar.set(store.get().listLoads > 0);\n scope.defer(() => bar.set(false));\n clear(root);\n root.append(shell);\n\n scope.defer(\n store.subscribe((s, prev) => {\n if (s.roomsStatus !== prev.roomsStatus) renderAlert();\n if (s.listLoads !== prev.listLoads) bar.set(s.listLoads > 0);\n if (\n s.rooms !== prev.rooms ||\n s.hidden !== prev.hidden ||\n s.unread !== prev.unread ||\n s.inbox !== prev.inbox ||\n s.mentions !== prev.mentions ||\n s.activeRoomId !== prev.activeRoomId ||\n s.collections !== prev.collections ||\n s.activeCollectionId !== prev.activeCollectionId ||\n s.user !== prev.user ||\n s.roomsStatus !== prev.roomsStatus\n )\n render();\n if (s.site !== prev.site || s.user !== prev.user) renderEnds();\n }),\n );\n // A room's page is asked for as its link is pressed, or once the pointer rests on it (PERF.md \u00A75).\n const roomOf = (e: Event) => (e.target as Element).closest?.<HTMLAnchorElement>('a[href^=\"/r/\"]')?.pathname.slice(3);\n let resting: ReturnType<typeof setTimeout> | undefined;\n const on = { signal: scope.signal };\n nav.addEventListener(\n \"pointerdown\",\n (e) => {\n const id = roomOf(e);\n if (id) early?.hint(id);\n },\n on,\n );\n nav.addEventListener(\n \"pointerover\",\n (e) => {\n clearTimeout(resting);\n const id = e.pointerType === \"mouse\" && roomOf(e);\n if (id) resting = setTimeout(() => early?.hint(id), HOVER_MS);\n },\n on,\n );\n nav.addEventListener(\"pointerout\", () => clearTimeout(resting), on);\n scope.defer(() => clearTimeout(resting));\n renderAlert();\n render();\n },\n unmount() {\n scope.dispose();\n clear(root);\n },\n };\n}\n", "// App shell and boot (\u00A77.1): restores the session, starts the room sync and unread counts and the tab's unread badge\n// (\u00A722.4), wires the router, header and logout (offered on the profile page, \u00A722.2). Without a session the app is open\n// to guests, who read the Open Air rooms and can log in or sign up from the header (\u00A723.3).\n\nimport { createRoomActions } from \"./actions.ts\";\nimport type { Api } from \"./api.ts\";\nimport { type Cache, createCache, forgetGone } from \"./cache.ts\";\nimport { createCollections } from \"./collections.ts\";\nimport type { Ctx } from \"./context.ts\";\nimport { clear, h } from \"./dom.ts\";\nimport { createDrafts } from \"./drafts.ts\";\nimport { startFavicon } from \"./favicon.ts\";\nimport { createHeader } from \"./header.ts\";\nimport { startJumpTo } from \"./jump.ts\";\nimport { lazyView } from \"./lazy.ts\";\nimport { roomTitle } from \"./lib/rooms.ts\";\nimport { formatTime, parsePb } from \"./lib/time.ts\";\nimport type { User } from \"./lib/types.ts\";\nimport { createPrefetch } from \"./prefetch.ts\";\nimport { createRenewal } from \"./renewal.ts\";\nimport { createRouter, here, type Router, type View } from \"./router.ts\";\nimport { startSite } from \"./site.ts\";\nimport { type AppState, createStore, initialState, type Store } from \"./store.ts\";\nimport * as S from \"./strings/app.ts\";\nimport { createSync } from \"./sync.ts\";\nimport { avatar } from \"./ui/avatar.ts\";\nimport { createUnread } from \"./unread.ts\";\nimport { startUpdates } from \"./update.ts\";\nimport { createCollectionView } from \"./views/collection.ts\";\nimport { createHomeView } from \"./views/home.ts\";\nimport { createRoomView } from \"./views/room.ts\";\nimport { createRoomsView } from \"./views/rooms.ts\";\n\nexport interface App {\n store: Store<AppState>;\n router: Router;\n /** End the session and go home, as a guest (what the profile page's Log out does). */\n logOut(): void;\n stop(): void;\n}\n\n/** notify.ts's NOTIFY_KEY (\u00A734): someone here turned notifications on. */\nexport const NOTIFY_KEY = \"chat.notify\";\n\n/**\n * The pages for logging in, signing up, and the emailed link that sets a new password (\u00A739): never where to go back\n * to after logging in.\n */\nconst isAuthPage = (path: string) => path === \"/login\" || path === \"/signup\" || path.startsWith(\"/reset-password/\");\n\n/** Starts the main view of the mounted layout over (a room that came back, \u00A723.4): one per app. */\ninterface Panes {\n reload: () => void;\n}\n\n/**\n * Page layout (\u00A77.1): the room list as a sidebar next to the main view. New params remount only the\n * main view, so switching rooms keeps the sidebar (and anything typed into it).\n */\n/** Rooms kept after you leave them (`keeps`), the latest first out of these many. */\nconst KEPT_ROOMS = 3;\n\n/**\n * The sidebar and a pane beside it. With `keeps` (rooms), a room you leave for another is kept out of the page, live\n * (View.park), for the last KEPT_ROOMS: going back puts it back as it was, with what came meanwhile, nothing fetched or\n * built again (PERF.md \u00A75). Not one opened at a message (/r/:id/m/:msgId), which goes to it.\n */\nfunction withSidebar(panes: Panes, sidebar: () => View, main: () => View, layoutClass = \"\", keeps = false): () => View {\n return () => {\n const side = sidebar();\n let pane = main();\n const content = h(\"div\", { class: \"pane\" });\n /** Where `pane` is mounted: `content`, or with `keeps` an element of its own in it, which goes with it when parked. */\n let at: HTMLElement = content;\n const place = () => {\n if (!keeps) return content;\n const el = content.appendChild(h(\"div\", { class: \"kept\" }));\n el.style.height = \"100%\"; // as the pane, for the room's own scrolling (here: the CSS budget is full)\n return el;\n };\n /** Parked rooms by id, the longest parked first. */\n const parked = new Map<string, { view: View; at: HTMLElement }>();\n const drop = (p: { view: View; at: HTMLElement }) => {\n p.view.unmount();\n if (p.at !== content) p.at.remove();\n };\n let root: HTMLElement;\n let current: Record<string, string> = {};\n // A fresh view rather than a remount: late async work of the old one must not see itself as active.\n const fresh = () => {\n drop({ view: pane, at });\n pane = main();\n at = place();\n pane.mount(at, current);\n };\n const keepable = (p: Record<string, string>) => keeps && !!p.id && !p.msgId;\n return {\n mount(el, params) {\n root = el;\n current = params;\n panes.reload = fresh;\n const aside = h(\"aside\", { class: \"sidebar\" });\n el.replaceChildren(h(\"div\", { class: `layout ${layoutClass}`.trim() }, [aside, content]));\n side.mount(aside, {});\n at = place();\n pane.mount(at, params);\n },\n update(params) {\n const left = current;\n current = params;\n if (!keepable(left) || !keepable(params) || left.id === params.id || !pane.park) return fresh();\n pane.park();\n at.remove();\n parked.set(left.id!, { view: pane, at });\n const back = parked.get(params.id!);\n parked.delete(params.id!);\n if (back) {\n content.append(back.at);\n pane = back.view;\n at = back.at;\n }\n if (!back?.view.resume?.()) {\n if (back) drop(back);\n pane = main();\n at = place();\n pane.mount(at, params);\n }\n for (const [id, p] of parked) {\n if (parked.size <= KEPT_ROOMS) break;\n parked.delete(id);\n drop(p);\n }\n },\n unmount() {\n if (panes.reload === fresh) panes.reload = () => {};\n for (const p of parked.values()) drop(p);\n parked.clear();\n pane.unmount();\n side.unmount();\n clear(root);\n },\n };\n };\n}\n\n/** The rooms kept for opening fast (\u00A77.5), and the thumbnails the service worker kept (sw.ts, FILES). */\nfunction forgetCached(cache: Cache) {\n cache.clear();\n void globalThis.caches?.delete(\"chat-files\").catch(() => {});\n}\n\nexport function startApp(deps: { api: Api; root: HTMLElement }): App {\n const { api, root } = deps;\n // A session that ran out while the app was closed was never ended (endSession): what it left goes now.\n const expired = api.forgetExpired();\n const store = createStore<AppState>({ ...initialState(), user: api.currentUser(), away: document.visibilityState === \"hidden\" });\n const sync = createSync({ api, store });\n const unread = createUnread({ api, store });\n const collections = createCollections({ api, store });\n const drafts = createDrafts(() => store.get().user?.id ?? \"\");\n const cache = createCache();\n if (expired) {\n drafts.clear(expired);\n forgetCached(cache);\n }\n const offGone = forgetGone(cache, store);\n const prefetch = createPrefetch({ api, store, cache });\n const panes: Panes = { reload: () => {} };\n /** Notifications (\u00A734), a lazy chunk loaded only once they are on: its stop. */\n let notify: Promise<() => void> | null = null;\n const startNotify = () => {\n try {\n if (notify || !store.get().user || !localStorage.getItem(NOTIFY_KEY)) return;\n } catch {\n return;\n }\n const loading = import(\"./notify.ts\").then(\n (m) => m.startNotify({ api, store, title: roomTitle, navigate: (path) => router.navigate(path) }),\n () => {\n if (notify === loading) notify = null; // tried again next time\n return () => {};\n },\n );\n notify = loading;\n };\n const stopNotify = () => {\n void notify?.then((stop) => stop());\n notify = null;\n };\n /** Start following the rooms (and, signed in, the unread counts and prefetching, \u00A77.5) as whoever is logged in now, or as a guest. */\n let running = false;\n const startSession = () => {\n running = true;\n sync.start();\n if (!store.get().user) return;\n unread.start();\n collections.start();\n prefetch.start();\n startNotify();\n };\n /** The page a guest was on before going to log in or sign up: where logging in takes them back to (\u00A723.3). */\n let lastPage = isAuthPage(here()) ? \"/\" : here();\n const onNavigate = (path: string) => {\n if (!isAuthPage(path)) lastPage = path;\n // Who you are, at the sidebar's foot and in the app bar: lit while on your settings.\n for (const a of root.querySelectorAll(\"a.me-link\")) {\n if (path === \"/me\") a.setAttribute(\"aria-current\", \"page\");\n else a.removeAttribute(\"aria-current\");\n }\n };\n\n const header = createHeader({ api, store });\n const main = h(\"main\", { class: \"app-main\" });\n clear(root);\n root.append(header.el, main);\n\n /** Drop everything that belonged to the logged-in user. The session itself is left as it is. */\n function endSession() {\n if (!running) return; // logging out ends it before the auth change would (QA BUG-62)\n running = false;\n // Reads still waiting go out now, while the session is there. After another tab switched it to someone else,\n // this sends nothing: a reader only sends as the user it was opened for.\n unread.flush();\n unread.stop();\n collections.stop();\n prefetch.stop();\n stopNotify();\n sync.stop();\n void api.unsubscribeAll().catch(() => {});\n drafts.clear(store.get().user?.id ?? \"\");\n forgetCached(cache);\n // Loads still out count themselves back down as they end.\n store.set({ ...initialState(), site: store.get().site, listLoads: store.get().listLoads });\n }\n\n /**\n * Someone else is logged in now (or nobody): everything that belonged to the previous one goes, the rooms are\n * followed again as the new one (or as a guest), and the views start over.\n */\n function switchTo(next: User | null, after = \"/\") {\n const fromAuthPage = isAuthPage(here());\n endSession();\n if (next) store.set({ user: next });\n startSession();\n // Logged in from the login page: back to the room you were reading. Logged out: home (or `after`).\n if (next && fromAuthPage) history.replaceState(null, \"\", lastPage);\n if (!next) {\n history.replaceState(null, \"\", after);\n // After a logout, whoever logs in next starts from home, not from the page the previous user was on (their\n // profile, a room; QA BUG-59). An expired session is logged back into where it was.\n if (!isAuthPage(after)) lastPage = \"/\";\n }\n router.remount();\n }\n\n /** `after`: where to go, as a guest. */\n function logOut(after = \"/\") {\n // End the session before clearing it, so the auth-change listener below sees nothing left to do.\n endSession();\n api.logOut();\n switchTo(null, after);\n }\n /** The session ran out or was revoked: the login page, and back to this page once logged in again. */\n const expire = () => logOut(\"/login\");\n\n const renewal = createRenewal({ api, store, expire });\n const onVisible = () => {\n // Before the room view's own listener (registered later) reads what is on screen.\n store.set({ away: document.visibilityState === \"hidden\" });\n if (document.visibilityState === \"visible\") renewal.visible();\n };\n\n /**\n * The session is shared by every tab of this browser. When another tab logs out or logs in as someone else,\n * follow it: otherwise this tab would keep showing one user while its requests go out as another (or as nobody).\n */\n function onAuthChange() {\n const next = api.currentUser();\n const cur = store.get().user;\n if (next?.id === cur?.id) {\n // Same user: our own login/refresh, or a profile change (here or in another tab, BUG-33): follow name and avatar.\n if (next && cur && (next.name !== cur.name || (next.avatar ?? \"\") !== (cur.avatar ?? \"\"))) store.set({ user: next });\n return;\n }\n // Views mounted for the previous user (or the guest) hold its subscriptions and state: they start over.\n switchTo(next);\n }\n\n const ctx: Ctx = {\n api,\n store,\n sync,\n unread,\n collections,\n actions: createRoomActions({ api, store }),\n navigate: (hash) => router.navigate(hash),\n reopen: () => panes.reload(),\n drafts,\n cache,\n logOut,\n notify: startNotify,\n early: prefetch,\n };\n const rooms = () => createRoomsView(ctx);\n /** \"Mentions & replies\" (\u00A741): a lazy chunk, given what it needs of app.js. */\n const inboxPage = (): View => {\n let stop = new AbortController();\n return {\n mount(el) {\n stop = new AbortController();\n const { signal } = stop;\n el.replaceChildren(h(\"p\", { class: \"empty\", role: \"status\" }, \"Loading\u2026\"));\n import(\"./views/inbox.ts\").then(\n (m) =>\n void (\n !signal.aborted &&\n m.mountInbox(el, {\n api,\n store,\n signal,\n avatar: (u) => avatar(u, 32, api.avatarUrl),\n roomName: (id) => {\n const r = store.get().rooms.get(id);\n return r ? roomTitle(r, store.get().user) : \"\";\n },\n when: (c) => formatTime(parsePb(c)),\n })\n ),\n () => {\n if (!signal.aborted) el.textContent = \"Couldn't open your mentions and replies. Check your connection.\";\n },\n );\n },\n unmount() {\n stop.abort();\n },\n };\n };\n const roomPage = withSidebar(panes, rooms, () => createRoomView(ctx), \"\", true);\n\n /** The login and signup page (a lazy chunk), started at once for someone not signed in: it is what they may want first. */\n let loginChunk: Promise<typeof import(\"./views/login.ts\")> | null = null;\n const loadLogin = () => {\n loginChunk ??= import(\"./views/login.ts\").catch((e: unknown) => {\n loginChunk = null;\n throw e;\n });\n return loginChunk;\n };\n if (!store.get().user) void loadLogin().catch(() => {});\n const authPage = (mode: \"login\" | \"signup\" | \"reset\") => () =>\n lazyView(\n () =>\n loadLogin().then((m) =>\n m.createLoginView({\n api,\n store,\n mode,\n onLogin: (user) => {\n // Usually followed already: logging in changed the session (onAuthChange).\n if (store.get().user?.id !== user.id) switchTo(user);\n router.navigate(lastPage);\n },\n }),\n ),\n \"Couldn't open this page. Check your connection.\",\n );\n /** Settings (a lazy chunk). */\n const profilePage = () =>\n lazyView(() => import(\"./views/profile.ts\").then((m) => m.createProfileView(ctx)), \"Couldn't open Settings. Check your connection.\");\n /** An invite link's page (\u00A744, a lazy chunk). */\n const invitePage = () =>\n lazyView(() => import(\"./views/invite.ts\").then((m) => m.createInviteView(ctx)), \"Couldn't open this page. Check your connection.\");\n const router = createRouter({\n onNavigate,\n root: main,\n isAuthed: () => store.get().user !== null,\n routes: [\n { pattern: \"/login\", public: true, guestOnly: true, view: authPage(\"login\") },\n { pattern: \"/signup\", public: true, guestOnly: true, view: authPage(\"signup\") },\n // The emailed link (\u00A739): logged in or not, it sets that account's password.\n { pattern: \"/reset-password/:token\", public: true, view: authPage(\"reset\") },\n // Guests see the Open Air rooms (\u00A723.3); a room they can't see says it doesn't exist.\n { pattern: \"/\", public: true, view: withSidebar(panes, rooms, () => createHomeView(ctx), \"home\") },\n { pattern: \"/r/:id\", public: true, view: roomPage },\n { pattern: \"/r/:id/m/:msgId\", public: true, view: roomPage },\n { pattern: \"/c/:id\", public: true, view: withSidebar(panes, rooms, () => createCollectionView(ctx)) },\n // A private room's invite link (\u00A744): guests are asked to log in or sign up, and come back to it.\n { pattern: \"/invite/:token\", public: true, view: withSidebar(panes, rooms, invitePage) },\n { pattern: \"/me\", view: withSidebar(panes, rooms, profilePage) },\n { pattern: \"/inbox\", view: withSidebar(panes, rooms, inboxPage) },\n ],\n });\n\n const stopJumpTo = startJumpTo({ api, store, root, navigate: (path) => router.navigate(path) });\n const offAuth = api.onAuthChange(onAuthChange);\n // A file dropped where nothing takes it must not make the browser open it and leave the app (QA BUG-27).\n // The room and the profile picture handle their own drops; this only cancels the browser's default.\n const swallowFileDrag = (e: DragEvent) => {\n if (e.dataTransfer?.types.includes(\"Files\")) e.preventDefault();\n };\n window.addEventListener(\"dragover\", swallowFileDrag);\n window.addEventListener(\"drop\", swallowFileDrag);\n document.addEventListener(\"visibilitychange\", onVisible);\n const onStorage = (e: StorageEvent) => (e.key === NOTIFY_KEY || e.key === null) && startNotify();\n window.addEventListener(\"storage\", onStorage);\n const stopSite = startSite(api, store);\n const stopFavicon = startFavicon(store);\n const stopUpdates = startUpdates(api, root);\n startSession();\n router.start();\n\n // A restored session is checked (and renewed) once the room list is in.\n renewal.renewSoon();\n // A live connection the server closed may have been a ban's (\u00A736) or a revoked session's: checked again.\n const offConnect = api.onConnect((reconnect) => reconnect && renewal.renew());\n\n return {\n store,\n router,\n logOut,\n stop() {\n offAuth();\n offConnect();\n renewal.stop();\n window.removeEventListener(\"dragover\", swallowFileDrag);\n window.removeEventListener(\"drop\", swallowFileDrag);\n document.removeEventListener(\"visibilitychange\", onVisible);\n stopJumpTo();\n window.removeEventListener(\"storage\", onStorage);\n stopNotify();\n header.stop();\n stopFavicon();\n stopUpdates();\n stopSite();\n offGone();\n router.stop();\n unread.stop();\n collections.stop();\n prefetch.stop();\n sync.stop();\n clear(root);\n },\n };\n}\n", "import { createApi } from \"./api.ts\";\nimport { startApp } from \"./app.ts\";\nimport { closeDialogsOnBackdrop } from \"./dom.ts\";\nimport { createAuthStore, createClient } from \"./pb.ts\";\nimport { startTheme } from \"./theme.ts\";\n\n// The theme index.html's inline script set, and another tab's changes (\u00A77.8).\nstartTheme();\n\n// A click beside any modal dialog closes it, as Escape does.\ncloseDialogsOnBackdrop();\n\nstartApp({\n api: createApi(createClient(location.origin, createAuthStore(localStorage))),\n root: document.getElementById(\"app\")!,\n});\n\n// The offline shell and installing the app (DESIGN.md \u00A727).\nvoid navigator.serviceWorker?.register(\"/sw.js\");\n"],
|
|
5
|
+
"mappings": "+xBAwBO,SAASA,GAAkB,CAAE,IAAAC,EA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,MAAO,CACL,MAAAtC,EACA,OAAAqB,GACA,OAAAgB,EACA,MAAO,CACLmC,GAAQ,EACRS,GAAW,EACX3C,EAAQ,KAAK,EACb,OAAO,oBAAoB,WAAYmC,EAAe,EACtD,OAAO,oBAAoB,OAAQA,EAAe,EAClD,SAAS,oBAAoB,mBAAoBjC,CAAS,EAC1D8B,GAAW,EACX,OAAO,oBAAoB,UAAWI,EAAS,EAC/CpD,EAAW,EACXQ,EAAO,KAAK,EACZ+C,GAAY,EACZE,GAAY,EACZJ,GAAS,EACT/D,EAAQ,EACRS,GAAO,KAAK,EACZhB,EAAO,KAAK,EACZE,EAAY,KAAK,EACjBO,EAAS,KAAK,EACdX,EAAK,KAAK,EACVV,GAAMT,CAAI,CACZ,CACF,CACF,CCrbAmG,GAAW,EAGXC,GAAuB,EAEvBC,GAAS,CACP,IAAKC,GAAUC,GAAa,SAAS,OAAQC,GAAgB,YAAY,CAAC,CAAC,EAC3E,KAAM,SAAS,eAAe,KAAK,CACrC,CAAC,EAGI,UAAU,eAAe,SAAS,QAAQ",
|
|
6
|
+
"names": ["createRoomActions", "api", "store", "name", "visibility", "room", "upsertRoom", "roomId", "row", "markHidden", "rowId", "unmarkHidden", "archived", "members", "posting", "writers", "userId", "rooms", "hidden", "user", "r", "unmarkHiddenRoom", "STORE", "done", "req", "resolve", "reject", "createCache", "name", "db", "opened", "open", "d", "mem", "LEFT", "leaving", "left", "row", "go", "mode", "op", "tx", "result", "run", "roomId", "s", "user", "kept", "forgetGone", "cache", "store", "prev", "id", "REFRESH_MS", "createCollections", "api", "store", "scope", "timer", "live", "issued", "load", "s", "seq", "res", "follow", "ids", "c", "key", "old", "off", "refresh", "mine", "createScope", "reconnect", "id", "at", "x", "PREFIX", "createDrafts", "user", "storage", "safeLocalStorage", "key", "roomId", "attempt", "fn", "fallback", "s", "text", "userId", "mine", "keys", "i", "k", "totalUnread", "s", "n", "r", "unreadCount", "badgeLabel", "ICON", "icon", "badgedIcon", "label", "c", "g", "w", "tabTitle", "room", "title", "roomTitle", "startFavicon", "store", "doc", "shown", "setIcon", "href", "link", "old", "render", "t", "off", "prev", "lazyView", "load", "failed", "inner", "gone", "el", "params", "h", "v", "WINDOW_MAX", "GROUP_GAP_MS", "emptyWindow", "compare", "a", "b", "newest", "current", "incoming", "merge", "win", "byId", "m", "cur", "remove", "id", "i", "_", "j", "trim", "side", "max", "extra", "applyPage", "page", "kind", "full", "startsGroup", "prev", "parsePb", "lastSaved", "win", "i", "lastOwnEditable", "me", "m", "emptyForward", "quoteOf", "quoteText", "q", "text", "n", "EARLY_MS", "HOVER_MS", "DELAY_MS", "GAP_MS", "WARM", "REFETCH_MS", "createPrefetch", "api", "store", "cache", "delayMs", "gapMs", "refetchMs", "scope", "early", "id", "user", "s", "was", "kept", "tag", "items", "compare", "page", "latest", "t", "p", "createScope", "due", "cold", "timer", "fetched", "later", "ready", "drain", "unread", "same", "r", "schedule", "add", "now", "warmed", "warm", "st", "dms", "rooms", "roomSections", "prev", "n", "m", "AUTH_REJECTED", "RENEW_MAX_MS", "RENEW_RETRY_MS", "CHECK_MIN_MS", "CHECK_STALE_MS", "START_WAIT_MS", "createRenewal", "api", "store", "expire", "timer", "checkedAt", "starting", "schedule", "ms", "renew", "user", "fresh", "err", "ApiError", "offRejected", "wait", "offStore", "s", "prev", "listed", "go", "off", "LOGIN", "here", "fromLegacyHash", "matchRoute", "routes", "path", "parts", "route", "pp", "params", "seg", "i", "part", "createRouter", "opts", "root", "isAuthed", "current", "running", "listening", "unmountCurrent", "redirect", "resolve", "m", "target", "view", "go", "skipViewerEntry", "s", "onPopState", "onHashChange", "onClick", "e", "a", "signal", "KEY", "cachedSite", "storage", "v", "startSite", "api", "store", "safeLocalStorage", "cached", "ac", "site", "cur", "DEFAULT_SITE", "createSync", "api", "store", "scope", "guest", "issued", "applied", "apply", "s", "update", "inFlight", "changed", "track", "st", "prev", "k", "id", "settle", "answer", "now", "ids", "load", "seq", "listLoad", "rooms", "hidden", "x", "createScope", "action", "room", "removeRoom", "upsertRoom", "row", "unmarkHidden", "markHidden", "reconnect", "TIMING", "MAX_RETRY_MS", "createUnread", "api", "store", "timing", "scope", "recent", "accounted", "inFlight", "countedAt", "refreshTimer", "following", "pending", "load", "s", "listLoad", "res", "unread", "b", "mentions", "refresh", "open", "roomId", "reader", "readAt", "timer", "closed", "failures", "caughtUpNow", "live", "self", "at", "e", "status", "ApiError", "created", "caughtUp", "clearUnread", "sent", "createScope", "action", "m", "user", "away", "bumpUnread", "_action", "row", "reconnect", "st", "prev", "id", "r", "MIN_GAP", "EVERY", "SPREAD", "appScript", "html", "startUpdates", "api", "root", "current", "load", "last", "timer", "shown", "check", "force", "next", "h", "e", "onVisible", "every", "offConnect", "reconnect", "chunk", "collectionChunk", "chunkContext", "api", "store", "collections", "h", "fn", "s", "prev", "created", "formatFull", "parsePb", "createCollectionView", "ctx", "scope", "createScope", "root", "el", "params", "id", "status", "m", "clear", "firstName", "name", "createHomeView", "store", "scope", "createScope", "root", "title", "h", "text", "render", "user", "el", "clear", "s", "prev", "isNearBottom", "el", "captureAnchor", "container", "selector", "top", "candidate", "restoreAnchor", "anchor", "beginningOfYourConversationWith", "name", "couldntBan", "banned", "why", "LOADBAR_MS", "createLoadbar", "el", "h", "timer", "busy", "createRoomCollections", "api", "store", "collections", "scope", "rerender", "addItems", "say", "signal", "badges", "asking", "listening", "badge", "id", "ask", "re", "askBadges", "ids", "i", "some", "got", "lazy", "chunkContext", "failed", "m", "file", "opener", "collectionChunk", "c", "max", "items", "it", "collectionIcon", "h", "createActionMenu", "opts", "signal", "items", "shape", "confirming", "summary", "h", "body", "el", "watchOutside", "place", "outside", "setConfirming", "e", "close", "away", "button", "label", "onClick", "cls", "item", "find", "i", "runItem", "focused", "render", "cancel", "clip", "p", "at", "next", "nextShape", "stale", "MAX_LEN", "LIMITS", "COUNTER_FROM", "MAX_ROWS", "INVISIBLE", "isBlank", "t", "validText", "raw", "textLength", "validEdit", "hasFiles", "IMAGE_EDGE", "previewable", "f", "editProblem", "len", "composing", "rowsFor", "text", "fitRows", "style", "line", "padding", "wrapped", "createComposer", "opts", "signal", "mac", "textarea", "h", "placeholder", "measure", "fitPlaceholder", "width", "css", "resizes", "counter", "sendBtn", "fileInput", "onCollections", "attachMenu", "createActionMenu", "files", "attach", "emojiBtn", "insertEmoji", "tray", "trayError", "replyLabel", "replyBar", "cancelReply", "emoji", "onInput", "preparing", "sendable", "renderTray", "collectionIcon", "isVideo", "formatBytes", "removeFile", "x", "addFiles", "added", "prepared", "prepareImage", "accepted", "rejected", "checkFiles", "file", "r", "addItems", "items", "fresh", "it", "room", "submit", "picked", "e", "pasted", "before", "el", "reply", "ALPHABET", "LIMIT", "ALPHABET", "newId", "id", "buf", "b", "others", "n", "people", "setReaction", "list", "emoji", "user", "on", "x", "u", "reactors", "users", "me", "names", "known", "others", "id", "name", "shown", "people", "strays", "stray", "m", "files", "f", "takeStrays", "roomId", "out", "revokeLocal", "createWrites", "ctx", "api", "scope", "me", "find", "patchLocal", "emit", "inPlace", "unsent", "reacting", "queues", "inTurn", "key", "write", "run", "done", "reactSeq", "send", "text", "replyTo", "user", "quoted", "quoteOf", "last", "created", "toPb", "parsePb", "msg", "newId", "trim", "merge", "deliver", "saved", "failed", "items", "fraction", "e", "recovered", "ApiError", "replyGone", "retrySend", "id", "discard", "remove", "optimistic", "patch", "before", "request", "ok", "edit", "removeMessage", "removeMany", "ids", "ms", "deleteAll", "failure", "reactions", "list", "mine", "emoji", "p", "setReaction", "react", "on", "seq", "latest", "queue", "reasonOf", "HIGHLIGHT_MS", "UNREAD_LINE_MS", "BACK_MAX", "createRoomController", "opts", "api", "store", "roomId", "msgId", "scope", "nearBottom", "signal", "follows", "inPlace", "win", "emptyWindow", "phase", "targetId", "targetTimer", "unreadId", "pill", "back", "stale", "retarget", "asking", "wanted", "keepTimer", "pageTag", "early", "parked", "firstNew", "gen", "buffer", "unsent", "loading", "live", "liveReady", "fetching", "track", "p", "ready", "room", "me", "owner", "find", "id", "m", "posting", "r", "canPost", "moderates", "isDm", "deletable", "editable", "reactable", "repliable", "emit", "change", "keep", "saved", "items", "patchLocal", "patch", "setWin", "next", "kept", "merge", "setTarget", "setUnread", "applyLoaded", "kind", "page", "g", "applyPage", "loadEdge", "side", "more", "older", "newer", "jump", "latest", "first", "goTo", "from", "remember", "around", "windowAround", "target", "e", "ApiError", "windowAt", "c", "before", "after", "open", "roomP", "upsertRoom", "unread", "firstP", "UNCOUNTED", "pageP", "asked", "latestP", "compare", "t", "f", "showKept", "loaded", "current", "a", "z", "meanwhile", "pending", "action", "onMessage", "catchUp", "shown", "n", "theirs", "guess", "follow", "last", "lastSaved", "retry", "refreshWindow", "known", "oldest", "newest", "since", "max", "changed", "changedIn", "inWindow", "gapFill", "wasNear", "onReconnect", "quoteOf", "author", "text", "deleted", "files", "expand", "withQuote", "q", "quoted", "x", "event", "remove", "trim", "writes", "createWrites", "stray", "revokeLocal", "takeStrays", "sub", "reconnect", "forget", "mine", "lastOwnEditable", "emoji", "on", "noHover", "createFooter", "composer", "selection", "room", "me", "closePicker", "parked", "active", "signal", "el", "h", "banner", "guestBanner", "readerBanner", "closedBanner", "focusComposer", "composing", "show", "child", "failed", "r", "canPost", "dmClosed", "roomTitle", "shell", "e", "hasFiles", "media", "x", "isMedia", "f", "isVideo", "createGallery", "api", "roomId", "room", "win", "goTo", "saveFile", "signedIn", "screen", "scope", "say", "viewing", "gridding", "view", "m", "file", "opener", "images", "more", "leave", "w", "id", "start", "i", "openViewer", "back", "edge", "messages", "withFiles", "older", "newer", "attachmentName", "formatFull", "parsePb", "fn", "g", "gone", "createRoomHeader", "opts", "actions", "signal", "title", "h", "error", "shared", "menu", "createActionMenu", "search", "media", "members", "el", "shown", "last", "setNotifyAll", "id", "on", "p", "notifyPrefs", "rooms", "r", "v", "NOTIFY_KEY", "update", "act", "fn", "e", "errorMessage", "dmItems", "room", "hidden", "ok", "items", "mine", "guest", "out", "visibilityOf", "VISIBILITY", "notifyAll", "state", "me", "other", "otherMember", "text", "roomTitle", "vis", "key", "badge", "avatar", "people", "faces", "u", "note", "sharedNote", "canManage", "CANDIDATE", "TRAILING", "OPENING", "linkify", "text", "out", "at", "match", "url", "last", "open", "count", "www", "href", "s", "ch", "MENTION", "splitMentions", "text", "out", "at", "m", "start", "UNKNOWN", "forwardedFrom", "name", "UNKNOWN", "quotingShowTheOriginalMessage", "name", "spoken", "couldntLoad", "video", "MAX_TILES", "createAttachments", "opts", "signal", "sentRatios", "players", "prune", "all", "el", "key", "btn", "label", "onClick", "h", "attachments", "m", "local", "names", "shown", "f", "isMedia", "imageCount", "more", "tile", "images", "thumb", "others", "i", "preview", "w", "ht", "ratios", "playBadge", "name", "dims", "ratio", "mediaTile", "cell", "chip", "fileLink", "attachmentName", "isAudio", "player", "progress", "from", "b", "onSave", "save", "collectionIcon", "badge", "cls", "children", "kept", "src", "isVideo", "video", "poster", "isGif", "e", "load", "failed", "was", "broken", "couldntLoad", "reactionFocus", "emoji", "addReactionButton", "cls", "label", "h", "reactionRow", "reactions", "reactable", "me", "chips", "mine", "n", "content", "attrs", "QUOTE_SPOKEN", "byId", "id", "TOOLS", "createMessageList", "opts", "signal", "el", "h", "topSentinel", "bottomSentinel", "beginning", "newLine", "loadError", "midnight", "scheduleMidnight", "next", "render", "e", "t", "li", "focusAfter", "touched", "touchedAt", "fingerOn", "touchNow", "touchEnd", "touch", "interactive", "tap", "text", "open", "times", "timesDay", "timeOf", "created", "ms", "parsePb", "formatTime", "editing", "editText", "confirmDelete", "errors", "cache", "dividers", "names", "uploads", "attachments", "createAttachments", "btn", "label", "act", "cls", "toolbars", "toolbar", "has", "key", "bar", "icon", "i", "addReactionButton", "onAct", "b", "list", "askDelete", "cancelDelete", "at", "hit", "authorMenus", "d", "name", "menu", "createActionMenu", "user", "items", "isBanned", "onBan", "banned", "editBox", "hintText", "hint", "rowsFor", "fitRows", "composing", "value", "problem", "editProblem", "quotedOf", "win", "x", "permalink", "time", "messageNode", "groupStart", "targetId", "quoted", "selected", "err", "selectable", "picked", "editable", "deletable", "repliable", "reactable", "me", "reactions", "r", "reactors", "toMe", "sig", "quoteText", "p", "f", "c", "author", "parts", "formatFull", "quote", "avatar", "authorEl", "forwardedFrom", "gone", "emptyForward", "bodyText", "previewList", "reactionRow", "replyGone", "serviceNode", "mine", "linkify", "part", "splitMentions", "previews", "q", "chars", "spoken", "quotingShowTheOriginalMessage", "known", "room", "where", "ban", "data", "divider", "dayLabel", "o", "ready", "failed", "beginningText", "unreadId", "reconcile", "canChange", "can", "m", "nodes", "prev", "prevDay", "today", "day", "newDay", "startsGroup", "anchor", "captureAnchor", "box", "typing", "caret", "held", "sameButton", "restoreAnchor", "find", "live", "target", "emoji", "reactionFocus", "parent", "selector", "s", "found", "error", "selectors", "later", "fraction", "BATCH", "createNameLookup", "opts", "signal", "people", "asking", "lookingUp", "lookUp", "ids", "id", "ok", "found", "u", "name", "NOTICE_MS", "createNotice", "signal", "el", "h", "timer", "unsay", "text", "createParking", "list", "signal", "parked", "held", "at", "pinned", "screen", "isNearBottom", "scroll", "top", "first", "el", "moved", "draw", "toBottom", "createPickers", "api", "roomId", "shell", "scope", "say", "signal", "picker", "reactingTo", "suggest", "people", "opener", "req", "to", "createEmojiPicker", "loadStylesheet", "textarea", "createEmojiSuggest", "createMentionSuggest", "u", "avatar", "createReading", "list", "state", "scope", "reader", "above", "rows", "entries", "e", "id", "markRead", "watched", "reading", "atLiveEdge", "s", "isNearBottom", "lastShown", "items", "i", "m", "caughtUp", "lastSaved", "r", "el", "createReply", "opts", "composer", "to", "set", "m", "quoteText", "id", "dir", "ms", "at", "next", "now", "LIMIT_NOTICE", "MAX_SELECTED", "createSelection", "opts", "notice", "signal", "selected", "confirming", "bar", "h", "button", "label", "run", "cls", "count", "deleteBtn", "setConfirm", "group", "b", "actions", "end", "confirmText", "confirmActions", "ids", "allMine", "id", "update", "n", "on", "focus", "m", "mergeChanges", "a", "b", "c", "createRoomView", "api", "store", "unread", "actions", "navigate", "reopen", "drafts", "cache", "collections", "notify", "early", "vid", "uniqueId", "scope", "createScope", "signal", "root", "roomId", "ctl", "shown", "forwarding", "room", "me", "state", "notice", "createNotice", "say", "text", "nameOf", "createNameLookup", "ids", "sig", "render", "colls", "createRoomCollections", "items", "composer", "header", "createRoomHeader", "now", "openSearch", "gallery", "openAccess", "accessDialog", "createAccessDialog", "newAccessDialog", "r", "u", "x", "found", "canManage", "create", "dialog", "q", "address", "token", "visibility", "members", "posting", "writers", "e", "errorMessage", "shell", "beginningLabel", "isDm", "beginningOfYourConversationWith", "otherMember", "messages", "createMessageList", "s", "selection", "m", "id", "reply", "openForward", "emoji", "on", "react", "opener", "pickReaction", "from", "saveEdit", "doDelete", "file", "userId", "messageUser", "banned", "setBanned", "createComposer", "files", "mine", "dir", "insert", "pickers", "textarea", "forwardDialog", "newForwardDialog", "roomSections", "canPost", "dmClosed", "to", "emptyForward", "target", "n", "reasonOf", "list", "pill", "h", "parking", "createParking", "reading", "createReading", "bar", "createLoadbar", "createReply", "createSelection", "renderFooter", "deleteSelected", "footer", "createFooter", "createPickers", "createGallery", "o", "failed", "createForwardDialog", "queued", "frame", "direct", "apply", "flush", "draw", "fn", "renderNotFound", "renderHeader", "scrollToBottom", "el", "renderPill", "away", "isNearBottom", "back", "dm", "couldntBan", "offReturn", "awaitReturn", "prev", "notFound", "title", "rest", "why", "renderGone", "search", "held", "holdKeys", "createSearch", "toggle", "roomTitle", "formatTime", "parsePb", "avatar", "typeInto", "raw", "validEdit", "saving", "reactionFocus", "done", "user", "params", "createRoomController", "fraction", "resizes", "observer", "entries", "clear", "roomChanged", "scroll", "couldntUnhide", "room", "why", "couldntArchive", "archived", "FOLD_KEY", "folded", "s", "nameError", "err", "ApiError", "errorMessage", "visibilityMark", "v", "label", "VISIBILITY", "h", "createRoomsView", "api", "store", "sync", "unread", "actions", "navigate", "collections", "early", "id", "uniqueId", "root", "scope", "moreOpen", "rows", "parts", "actionError", "search", "newRoom", "guest", "creating", "collRows", "alert", "nav", "shell", "top", "foot", "bar", "createLoadbar", "drawn", "renderEnds", "site", "user", "brand", "avatar", "renderAlert", "clear", "title", "r", "roomTitle", "act", "failed", "room", "fn", "e", "searchChunk", "opening", "held", "toggleSearch", "open", "render", "holdKeys", "m", "showSearch", "createUserSearch", "SearchError", "q", "signal", "isAddress", "u", "reasonOf", "message", "typeInto", "toggleNewRoom", "newCollection", "opener", "collectionChunk", "c", "chunkContext", "cid", "collectionRow", "current", "n", "sig", "hit", "i", "el", "collectionIcon", "unhide", "couldntUnhide", "setArchived", "archived", "name", "why", "couldntArchive", "rowAction", "section", "canManage", "roomRow", "unreadCount", "at", "mentioned", "other", "otherMember", "one", "visibilityOf", "collapsible", "count", "summary", "part", "icon", "list", "hidden", "empty", "body", "skeleton", "newRoomToggle", "newDm", "newColl", "head", "add", "jumpButton", "inboxRow", "renderGuest", "rooms", "dms", "roomSections", "loading", "focused", "p", "keep", "shown", "reconcile", "mainList", "all", "x", "key", "b", "forget", "reveal", "revealed", "row", "newRoomForm", "inputId", "errId", "input", "submit", "hint", "choices", "chosen", "showHint", "choose", "seg", "setError", "msg", "textLength", "LIMITS", "createScope", "prev", "roomOf", "resting", "on", "HOVER_MS", "NOTIFY_KEY", "isAuthPage", "path", "KEPT_ROOMS", "withSidebar", "panes", "sidebar", "main", "layoutClass", "keeps", "side", "pane", "content", "h", "at", "place", "el", "parked", "drop", "p", "root", "current", "fresh", "keepable", "params", "aside", "left", "back", "id", "clear", "forgetCached", "cache", "startApp", "deps", "api", "expired", "store", "createStore", "initialState", "sync", "createSync", "unread", "createUnread", "collections", "createCollections", "drafts", "createDrafts", "createCache", "offGone", "forgetGone", "prefetch", "createPrefetch", "notify", "startNotify", "loading", "m", "roomTitle", "router", "stopNotify", "stop", "running", "startSession", "lastPage", "here", "onNavigate", "a", "header", "createHeader", "endSession", "switchTo", "next", "after", "fromAuthPage", "logOut", "renewal", "createRenewal", "onVisible", "onAuthChange", "cur", "ctx", "createRoomActions", "hash", "rooms", "createRoomsView", "inboxPage", "signal", "u", "avatar", "r", "c", "formatTime", "parsePb", "roomPage", "createRoomView", "loginChunk", "loadLogin", "e", "authPage", "mode", "lazyView", "user", "profilePage", "invitePage", "createRouter", "createHomeView", "createCollectionView", "stopJumpTo", "startJumpTo", "offAuth", "swallowFileDrag", "onStorage", "stopSite", "startSite", "stopFavicon", "startFavicon", "stopUpdates", "startUpdates", "offConnect", "reconnect", "startTheme", "closeDialogsOnBackdrop", "startApp", "createApi", "createClient", "createAuthStore"]
|
|
7
|
+
}
|