fix(viewer): replace embedded chat with integrated chat control

This commit is contained in:
coyotte508 2026-10-31 01:44:57 +01:00
commit 5b9bc73391
13 changed files with 273 additions and 233 deletions

View file

@ -9,3 +9,5 @@ BGS compresses JS, CSS, JSON and WASM automatically during upload. Send the orig
The BGS admin's **Upload folder** control handles multi-file builds. For scripted releases, use BGS's `scripts/publish-viewer.mjs` with `--dir`, `--entry` and `--style`; it verifies every uploaded file, records the previous viewer, and activates only with `--apply --activate`. The full command and API contract are in the [BGS viewer documentation](https://docs.boardgamers.space/guide/viewer-api#publishing-a-viewer-with-multiple-files).
English needs no language download; other languages load when selected. Test a cold load and a language change after publishing. Also check the browser Network panel for missing relative assets.
Keep `"chat"` in both viewers’ `integratedControls` metadata. Gaia supplies the chat button and unread badge; this prevents BGS from adding a duplicate chat shortcut.

View file

@ -1,6 +1,6 @@
{
"name": "@gaia-project/old-ui",
"version": "1.2.16",
"version": "1.2.17",
"scripts": {
"serve": "vite --port 5193",
"build": "vite build",

View file

@ -4,6 +4,7 @@
<Charts />
</b-modal>
<Rules id="rules" />
<div class="game-chat-button-host game-chat-button-host--fallback"></div>
<div v-if="analysisNotice || analysisPendingRestore" class="row">
<div class="col-12">
@ -276,7 +277,7 @@
<Table :players="orderedPlayers" />
<AdvancedLog :currentMove="currentMove" :hideLog.sync="hideLog" v-if="logPlacement === 'bottom'" />
</div>
<div class="chat-host" :style="{ '--chat-footer-height': totalStickyFooterHeight + 'px' }"></div>
<div
class="mobile-sticky-actions-spacer"
:style="{ '--sticky-bar-height': totalStickyFooterHeight + 'px' }"

View file

@ -90,6 +90,7 @@ terrans booster booster3`)
? new Engine(["init 3 old-test", "p1 faction terrans", "p2 faction nevlas", "p3 faction firaks"])
: loadScenarioEngine(id);
viewer.emit("state", JSON.parse(JSON.stringify(engine)));
viewer.emit("preferences", { platformChat: true });
viewer.emit("chat:state", { canSend: true });
viewer.emit("chat:messages", [{ type: "text", author: "Teammate", text: "Ready to explore" }]);
await vi.waitFor(() => expect(viewer.app.$el.querySelector(".old-map-canvas")).not.toBeNull());
@ -113,7 +114,13 @@ terrans booster booster3`)
for (const action of viewer.app.$el.querySelectorAll(".old-board-action")) {
expect(action.getAttribute("transform")).toMatch(/^translate\(/);
}
expect(document.querySelector(".bgs-game-chat")?.textContent).toContain("Ready to explore");
expect(document.querySelector(".bgs-game-chat, .chat-shortcut")).toBeNull();
const openChat = vi.fn();
viewer.on("chat:open", openChat);
const chatButton = document.querySelector<HTMLButtonElement>(".game-chat-button")!;
expect(chatButton.hidden).toBe(false);
chatButton.click();
expect(openChat).toHaveBeenCalledOnce();
const fedFixture = federationFixture();
viewer.emit("state", fedFixture);

11
pnpm-lock.yaml generated
View file

@ -173,8 +173,8 @@ importers:
viewer:
dependencies:
'@boardgamers/protocol':
specifier: 0.10.0
version: 0.10.0
specifier: file:vendor/boardgamers-protocol-0.11.0.tgz
version: file:viewer/vendor/boardgamers-protocol-0.11.0.tgz
'@gaia-project/engine':
specifier: workspace:../engine
version: link:../engine
@ -433,8 +433,9 @@ packages:
resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}
engines: {node: '>=18'}
'@boardgamers/protocol@0.10.0':
resolution: {integrity: sha512-U+nOK8xeQANvjzwacHirBW+ItDf9AOmHLtkoyTI/XYFCOpL6lPsEgCbmcxnmkXv2a1/lgtVN3WpSERHUqkQkXw==}
'@boardgamers/protocol@file:viewer/vendor/boardgamers-protocol-0.11.0.tgz':
resolution: {integrity: sha512-WmLTORnjHONvGjx24DzDylB1EQV9EO53rHKlouVX+Y59fIYAVkR1TZ9YbUo1es+jS7YYb0iFSHB3c8aOGxAgKQ==, tarball: file:viewer/vendor/boardgamers-protocol-0.11.0.tgz}
version: 0.11.0
'@bramus/specificity@2.4.2':
resolution: {integrity: sha512-ctxtJ/eA+t+6q2++vj5j7FYX3nRu311q1wfYH3xjlLOsczhlhxAg2FWNUXhpGvAw3BWo1xBcvOV6/YLc2r5FJw==}
@ -7084,7 +7085,7 @@ snapshots:
'@bcoe/v8-coverage@1.0.2': {}
'@boardgamers/protocol@0.10.0':
'@boardgamers/protocol@file:viewer/vendor/boardgamers-protocol-0.11.0.tgz':
dependencies:
zod: 4.6.2

1
viewer/.gitignore vendored
View file

@ -50,6 +50,7 @@ typings/
# Output of 'npm pack'
*.tgz
!vendor/*.tgz
# Yarn Integrity file
.yarn-integrity

View file

@ -1,6 +1,6 @@
{
"name": "@gaia-project/viewer",
"version": "5.22.16",
"version": "5.22.17",
"description": "Functions to visualize the map and boards for gaia project inside html canvas",
"contributors": [
"coyotte508",
@ -34,6 +34,7 @@
"src",
"README.md",
"public",
"vendor",
"dist/package/viewer.umd.js",
"dist/package/viewer.umd.*.js",
"dist/package/viewer.css",
@ -43,7 +44,7 @@
"dist/package/*.jpg"
],
"dependencies": {
"@boardgamers/protocol": "0.10.0",
"@boardgamers/protocol": "file:vendor/boardgamers-protocol-0.11.0.tgz",
"@gaia-project/engine": "workspace:../engine",
"bootstrap": "^4.4.1",
"bootstrap-vue": "^2.12.0",

View file

@ -65,6 +65,7 @@
@commit="requestAnalysisCommit"
@exit="$emit('analysis-exit')"
/>
<span class="game-chat-button-host game-chat-button-host--desktop"></span>
</div>
<AnalysisMoves
v-if="analysisMode && (analysisEntries.length || analysisPlayed.length) && !analysisEditActive"
@ -133,7 +134,7 @@
>
<RichTextView v-else :content="statusLine" />
</h5>
<span class="chat-shortcut-host"></span>
<span class="game-chat-button-host game-chat-button-host--mobile"></span>
<!-- Kept out of the ⋯ menu: a misclick is best taken back with one press. -->
<TakeBackButton v-if="takeBackOffered" compact />
<PremoveHistoryButton v-if="!analysisMode" :plan="premovePlan" />
@ -2078,7 +2079,9 @@ $mobile-sticky-actions-max-height: 40vh;
margin-bottom: 0;
padding-right: calc(78px + env(safe-area-inset-right, 0px));
}
&.mobile-sticky-actions--collapsed .sticky-bar-title > :not(h5):not(.chat-shortcut-host):not(.mobile-tray-handle) {
&.mobile-sticky-actions--collapsed
.sticky-bar-title
> :not(h5):not(.game-chat-button-host):not(.mobile-tray-handle) {
display: none !important;
}
}

View file

@ -4,6 +4,7 @@
<Charts />
</b-modal>
<Rules id="rules" />
<div class="game-chat-button-host game-chat-button-host--fallback"></div>
<!-- Show planning and queue details above the board; own-turn simulation starts beside the actions. -->
<div v-if="analysisNotice || analysisPendingRestore" class="row">
@ -348,11 +349,7 @@
<Table :players="orderedPlayers" />
<AdvancedLog :currentMove="currentMove" :hideLog.sync="hideLog" v-if="logPlacement === 'bottom'" />
</div>
<div
v-show="!$store.state.preferences.analysis"
class="chat-host"
:style="{ '--chat-footer-height': totalStickyFooterHeight + 'px' }"
></div>
<div
class="mobile-sticky-actions-spacer"
:style="{ '--sticky-bar-height': totalStickyFooterHeight + 'px' }"

View file

@ -4,53 +4,30 @@ import { mountGameChat } from "./game-chat";
import { catalogs } from "./localization";
import frenchCatalog from "./localization/fr.json";
describe("chat beside the mobile action bar", () => {
describe("game chat icon", () => {
let emitter: ViewerEmitter;
let dispose: () => void;
let panel: HTMLElement;
let list: HTMLElement;
let shortcut: HTMLButtonElement;
function rect(top: number, height: number): DOMRect {
return { top, bottom: top + height, left: 0, right: 390, width: 390, height } as DOMRect;
}
let host: HTMLElement;
let button: HTMLButtonElement;
const message = {
_id: "6ae5d8400000000000000001",
type: "text" as const,
author: "Nevlas",
text: "Hello",
createdAt: "2026-10-31T12:00:00Z",
};
const next = { ...message, _id: "6ae5d87c0000000000000001", createdAt: "2026-10-31T12:01:00Z" };
const badge = () => button.querySelector<HTMLElement>(".game-chat-unread")!;
beforeEach(() => {
catalogs.fr = frenchCatalog;
vi.useFakeTimers();
vi.stubGlobal("innerWidth", 1280);
vi.stubGlobal(
"IntersectionObserver",
class {
targets = new Set<Element>();
constructor(private callback: IntersectionObserverCallback) {
this.refresh = this.refresh.bind(this);
window.addEventListener("scroll", this.refresh);
}
refresh() {
this.callback(
Array.from(
this.targets,
(target) =>
({
target,
isIntersecting: true,
intersectionRect: target.getBoundingClientRect(),
}) as IntersectionObserverEntry
),
this as unknown as IntersectionObserver
);
}
observe(target: Element) {
this.targets.add(target);
this.refresh();
}
unobserve(target: Element) {
this.targets.delete(target);
}
disconnect() {
window.removeEventListener("scroll", this.refresh);
this.targets.clear();
}
observe() {}
disconnect() {}
unobserve() {}
}
);
vi.stubGlobal(
@ -58,148 +35,157 @@ describe("chat beside the mobile action bar", () => {
class {
observe() {}
disconnect() {}
unobserve() {}
}
);
vi.stubGlobal("innerHeight", 800);
vi.spyOn(document, "hasFocus").mockReturnValue(false);
Object.defineProperty(HTMLElement.prototype, "checkVisibility", { value: () => true, configurable: true });
document.body.innerHTML =
'<div id="host"><div class="chat-host"></div><div class="mobile-sticky-actions-spacer"></div></div>';
const host = document.querySelector("#host")!;
vi.spyOn(host.querySelector(".mobile-sticky-actions-spacer")!, "getBoundingClientRect").mockReturnValue(
rect(900, 180)
);
'<div id="host"><div class="game-chat-button-host--fallback"></div><div id="move-title"><span class="game-chat-button-host--desktop"></span></div></div>';
host = document.querySelector("#host")!;
emitter = new ViewerEmitter();
dispose = mountGameChat(emitter, host);
panel = host.querySelector(".bgs-game-chat")!;
list = host.querySelector(".chat-messages")!;
shortcut = host.querySelector(".chat-shortcut")!;
emitter.emit("preferences", { platformChat: true });
emitter.emit("chat:state", { canSend: true });
button = host.querySelector(".game-chat-button")!;
});
afterEach(() => {
dispose();
emitter.destroy();
vi.clearAllTimers();
vi.useRealTimers();
vi.restoreAllMocks();
vi.unstubAllGlobals();
document.body.innerHTML = "";
document.body.replaceChildren();
});
it("keeps the localized shortcut stable when its action-bar location changes", async () => {
emitter.emit("preferences", { locale: "fr" });
expect(shortcut.textContent).toBe("Discussion");
expect(shortcut.getAttribute("translate")).toBe("no");
document.querySelector("#host")!.append(document.createElement("span"));
it("opens the native chat even with no unread messages, without an embedded panel or floating shortcut", () => {
const open = vi.fn();
emitter.on("chat:open", open);
expect(button.hidden).toBe(false);
expect(badge().hidden).toBe(true);
button.click();
expect(open).toHaveBeenCalledOnce();
expect(document.querySelector(".bgs-game-chat, .chat-shortcut, .game-chat-dialog")).toBeNull();
});
it("keeps translated accessible labels when moving between header slots", async () => {
emitter.emit("preferences", { platformChat: true, locale: "fr" });
expect(button.title).toBe("Discussion");
expect(button.getAttribute("translate")).toBe("no");
expect(button.querySelector("svg")).not.toBeNull();
host.append(document.createElement("span"));
await Promise.resolve();
expect(shortcut.textContent).toBe("Discussion");
emitter.emit("preferences", { locale: "en" });
expect(shortcut.textContent).toBe("Chat");
expect(button.title).toBe("Discussion");
emitter.emit("preferences", { platformChat: true, locale: "en" });
expect(button.title).toBe("Chat");
});
it("does not count replacement history as unread", () => {
vi.spyOn(panel, "getBoundingClientRect").mockReturnValue(rect(900, 130));
vi.spyOn(list, "getBoundingClientRect").mockReturnValue(rect(920, 60));
const message = { _id: "000000000000000000000001", type: "text" as const, author: "Nevlas", text: "Hello" };
emitter.emit("chat:messages", [message]);
expect(shortcut.textContent).toBe("Chat");
expect(shortcut.hidden).toBe(true);
const next = { ...message, _id: "000000000000000000000002" };
emitter.emit("chat:appended", [next]);
expect(shortcut.textContent).toContain("1 unread");
expect(shortcut.hidden).toBe(false);
emitter.emit("preferences", { chatNotifications: false });
expect(shortcut.hidden).toBe(true);
expect(shortcut.textContent).toContain("1 unread");
emitter.emit("preferences", { chatNotifications: true });
expect(shortcut.hidden).toBe(false);
emitter.emit("chat:messages", [message, next]);
expect(shortcut.textContent).toContain("1 unread");
});
it("keeps a message unread while the action bar covers it", () => {
it("shows only a badge for unread messages and lets the host acknowledge native-chat reads", () => {
const read = vi.fn();
emitter.on("chat:read", read);
vi.spyOn(panel, "getBoundingClientRect").mockReturnValue(rect(650, 130));
vi.spyOn(list, "getBoundingClientRect").mockReturnValue(rect(680, 60));
emitter.emit("chat:appended", [
{ _id: "000000000000000000000001", type: "text" as const, author: "Nevlas", text: "Hello" },
]);
const row = list.querySelector("[data-message-id]")!;
const rowBounds = vi.spyOn(row, "getBoundingClientRect").mockReturnValue(rect(690, 40));
window.dispatchEvent(new Event("scroll"));
vi.advanceTimersByTime(600);
emitter.emit("chat:state", {
canSend: true,
readState: { userId: "local", lastReadAt: Date.parse(message.createdAt) },
});
emitter.emit("chat:messages", [message, next]);
expect(badge().hidden).toBe(false);
expect(badge().textContent).toBe("1");
expect(button.getAttribute("aria-label")).toBe("Open Chat · 1 unread");
button.click();
expect(read).not.toHaveBeenCalled();
expect(shortcut.hidden).toBe(false);
expect(shortcut.textContent).toContain("1 unread");
vi.mocked(panel.getBoundingClientRect).mockReturnValue(rect(350, 130));
vi.mocked(list.getBoundingClientRect).mockReturnValue(rect(380, 60));
rowBounds.mockReturnValue(rect(390, 40));
window.dispatchEvent(new Event("scroll"));
vi.advanceTimersByTime(600);
expect(read).toHaveBeenCalledExactlyOnceWith({ messageId: "000000000000000000000001" });
expect(shortcut.hidden).toBe(true);
expect(shortcut.textContent).toBe("Chat");
window.dispatchEvent(new Event("scroll"));
vi.advanceTimersByTime(600);
expect(read).toHaveBeenCalledTimes(1);
expect(badge().hidden).toBe(false);
emitter.emit("chat:state", {
canSend: true,
readState: { userId: "local", lastReadAt: Date.parse(next.createdAt) },
});
expect(badge().hidden).toBe(true);
expect(button.hidden).toBe(false);
expect(button.getAttribute("aria-label")).toBe("Open Chat");
});
it("moves the same unread shortcut into the action bar and restores it off turn", async () => {
it("does not treat replacement history as new and clears deleted unread messages", () => {
emitter.emit("chat:messages", [message]);
expect(badge().hidden).toBe(true);
emitter.emit("chat:appended", [next]);
expect(badge().textContent).toBe("1");
expect(badge().hidden).toBe(false);
emitter.emit("chat:messages", [message, next]);
expect(badge().textContent).toBe("1");
emitter.emit("chat:deleted", [next._id]);
expect(badge().hidden).toBe(true);
expect(button.hidden).toBe(false);
});
it("keeps chat accessible when notifications are suppressed, but hides it in standalone analyses", () => {
emitter.emit("chat:appended", [message]);
emitter.emit("preferences", { platformChat: true, chatNotifications: false });
expect(badge().hidden).toBe(true);
expect(button.hidden).toBe(false);
emitter.emit("preferences", { platformChat: true, chatNotifications: true });
expect(badge().hidden).toBe(false);
emitter.emit("preferences", { platformChat: true, analysis: true });
expect(button.hidden).toBe(true);
emitter.emit("preferences", { platformChat: true, analysis: false });
expect(button.hidden).toBe(false);
});
it("moves one icon between desktop, mobile and fallback headers when controls remount", async () => {
const desktop = host.querySelector(".game-chat-button-host--desktop")!;
const mobile = document.createElement("div");
mobile.className = "mobile-sticky-actions mobile-sticky-actions--collapsed";
mobile.innerHTML = '<span class="game-chat-button-host--mobile"></span>';
host.append(mobile);
vi.stubGlobal("innerWidth", 390);
vi.spyOn(panel, "getBoundingClientRect").mockReturnValue(rect(900, 130));
vi.spyOn(list, "getBoundingClientRect").mockReturnValue(rect(930, 60));
emitter.emit("chat:appended", [
{ _id: "000000000000000000000001", type: "text" as const, author: "Nevlas", text: "Hello" },
]);
const bar = document.createElement("div");
bar.className = "mobile-sticky-actions";
bar.innerHTML = '<span class="chat-shortcut-host"></span>';
document.querySelector("#host")!.prepend(bar);
await Promise.resolve();
expect(bar.contains(shortcut)).toBe(true);
expect(shortcut.textContent).toBe("Chat · 1");
expect(shortcut.getAttribute("aria-label")).toBe("Open Chat · 1 unread");
expect(shortcut.hidden).toBe(false);
emitter.emit("preferences", { chatNotifications: false });
expect(shortcut.hidden).toBe(true);
emitter.emit("preferences", { chatNotifications: true });
expect(shortcut.hidden).toBe(false);
window.dispatchEvent(new Event("resize"));
expect(mobile.contains(button)).toBe(true);
vi.stubGlobal("innerWidth", 1280);
window.dispatchEvent(new Event("resize"));
expect(bar.contains(shortcut)).toBe(false);
expect(shortcut.textContent).toBe("Chat · 1 unread");
expect(desktop.contains(button)).toBe(true);
vi.stubGlobal("innerWidth", 390);
window.dispatchEvent(new Event("resize"));
expect(bar.contains(shortcut)).toBe(true);
bar.remove();
mobile.remove();
await Promise.resolve();
expect(shortcut.parentElement!.className).toBe("chat-host");
expect(shortcut.textContent).toBe("Chat · 1 unread");
expect(document.querySelectorAll(".chat-shortcut")).toHaveLength(1);
expect(desktop.contains(button)).toBe(true);
desktop.remove();
await Promise.resolve();
expect(host.querySelector(".game-chat-button-host--fallback")!.contains(button)).toBe(true);
expect(host.querySelectorAll(".game-chat-button")).toHaveLength(1);
});
it("hides the action-bar shortcut without unread messages, including after deletion", async () => {
vi.stubGlobal("innerWidth", 390);
vi.spyOn(panel, "getBoundingClientRect").mockReturnValue(rect(900, 130));
vi.spyOn(list, "getBoundingClientRect").mockReturnValue(rect(930, 60));
const bar = document.createElement("div");
bar.className = "mobile-sticky-actions";
bar.innerHTML = '<span class="chat-shortcut-host"></span>';
document.querySelector("#host")!.prepend(bar);
await Promise.resolve();
it("opens a local dialog on hosts without system chat and removes it when system chat becomes available", () => {
const createElement = document.createElement.bind(document);
vi.spyOn(document, "createElement").mockImplementation((tag, options) => {
const element = createElement(tag, options);
if (tag === "dialog")
Object.assign(element, {
showModal(this: HTMLDialogElement) {
this.open = true;
},
close(this: HTMLDialogElement) {
this.open = false;
this.dispatchEvent(new Event("close"));
},
});
return element;
});
emitter.emit("preferences", { platformChat: false });
emitter.emit("chat:messages", [message]);
expect(document.querySelector(".bgs-game-chat")).toBeNull();
button.click();
const dialog = document.querySelector<HTMLDialogElement>(".game-chat-dialog")!;
expect(dialog.open).toBe(true);
expect(dialog.textContent).toContain("Hello");
expect(dialog.querySelector("input")).not.toBeNull();
(dialog.querySelector(".game-chat-close") as HTMLButtonElement).click();
expect(dialog.open).toBe(false);
emitter.emit("preferences", { platformChat: true });
expect(document.querySelector(".game-chat-dialog, .bgs-game-chat")).toBeNull();
});
expect(bar.contains(shortcut)).toBe(true);
expect(shortcut.hidden).toBe(true);
emitter.emit("chat:appended", [{ _id: "000000000000000000000001", type: "text", author: "Nevlas", text: "Hello" }]);
expect(shortcut.hidden).toBe(false);
emitter.emit("chat:deleted", ["000000000000000000000001"]);
expect(shortcut.hidden).toBe(true);
it("removes the button and its listeners on disposal", async () => {
dispose();
host.append(document.createElement("span"));
emitter.emit("chat:appended", [message]);
window.dispatchEvent(new Event("resize"));
await Promise.resolve();
expect(document.querySelector(".game-chat-button, .game-chat-dialog")).toBeNull();
});
});

View file

@ -11,12 +11,9 @@ type ChatEmitter = Pick<ViewerEmitter<any, any>, "on" | "emit">;
export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element): () => void {
const chat = new ChatController();
const detach = attachChat(emitter, chat);
const slot = host.querySelector<HTMLElement>(".chat-host") || document.createElement("div");
if (!slot.parentElement) host.insertAdjacentElement("afterend", slot);
const style = document.createElement("style");
style.textContent = `
.bgs-game-chat{box-sizing:border-box;font-family:inherit;font-size:14px;line-height:1.45;width:calc(100% - 30px);max-width:760px;border:1px solid var(--ui-border);border-radius:2px;margin:8px 15px;padding:0 8px 8px;background:var(--ui-surface);color:var(--ui-text)}
.chat-host .bgs-game-chat{width:100%;margin:8px 0}
.bgs-game-chat summary{cursor:pointer;font-weight:600;border-bottom:1px solid var(--ui-border);padding:5px 8px;margin:0 -8px;background:var(--ui-surface-muted)}
.bgs-game-chat summary:hover{color:#126778}
.bgs-game-chat summary:focus-visible,.bgs-game-chat button:focus-visible{outline:2px solid #247d8c;outline-offset:3px}
@ -60,47 +57,84 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
.bgs-game-chat .chat-edit-cancel{display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;min-height:0;padding:0;border:0;background:transparent;color:inherit;cursor:pointer}
.bgs-game-chat .chat-status{font-size:12px;margin-top:6px}
.bgs-game-chat .chat-status:empty{display:none}
.chat-shortcut{position:fixed;left:16px;bottom:max(16px,env(safe-area-inset-bottom));z-index:900;padding:7px 12px;border:1px solid #6a8589;border-radius:3px;background:#203a45;color:#fff;font:600 14px Arial,sans-serif;cursor:pointer;box-shadow:0 2px 6px #0003}
.chat-shortcut[hidden]{display:none}
.chat-shortcut:hover{background:#315966}
.chat-shortcut:focus-visible{outline:2px solid #fff;outline-offset:2px}
.chat-shortcut-host{margin-left:auto;padding-left:8px;flex-shrink:0}
.chat-shortcut.chat-shortcut--inline{position:static;padding:3px 8px;border-color:#ffffff66;background:#ffffff15;color:inherit;box-shadow:none;font-size:12px;line-height:20px;white-space:nowrap}
.game-chat-button-host{display:inline-flex;flex-shrink:0;margin-left:auto}
.game-chat-button-host:empty{display:none}
.game-chat-button-host--desktop{margin-left:.4rem}
.game-chat-button-host--fallback{display:flex;justify-content:flex-end}
.game-chat-button{position:relative;display:inline-grid;place-items:center;flex-shrink:0;width:40px;height:40px;padding:7px;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--ui-text-muted);cursor:pointer;line-height:1}
.game-chat-button[hidden],.game-chat-unread[hidden]{display:none}
.game-chat-button:hover,.game-chat-button:focus-visible{background:var(--ui-surface-hover);border-color:var(--ui-border);color:var(--ui-text)}
.game-chat-button:focus-visible{outline:2px solid #97c8ff;outline-offset:2px}
.game-chat-unread{position:absolute;right:0;top:0;min-width:17px;height:17px;padding:0 3px;border:2px solid var(--ui-bg);border-radius:10px;background:#f1c457;color:#18202a;font:700 10px/13px system-ui;text-align:center}
.game-chat-dialog{margin:auto;padding:16px;width:min(600px,calc(100vw - 24px));max-height:calc(100dvh - 24px);border:1px solid var(--ui-border);border-radius:12px;background:var(--ui-surface);color:var(--ui-text)}
.game-chat-dialog::backdrop{background:#0a172580}
.game-chat-dialog h2{margin:0 40px 12px 0;font-size:1.1rem}
.game-chat-dialog .game-chat-close{position:absolute;top:8px;right:8px;width:36px;height:36px;background:transparent;color:inherit;border:0;font-size:24px;cursor:pointer}
.game-chat-dialog .bgs-game-chat{width:100%;max-width:none;margin:0;padding:0;border:0}
.game-chat-dialog .bgs-game-chat summary{display:none}
.game-chat-dialog .chat-messages{max-height:min(440px,50dvh)}
@media(max-width:767px){
.chat-shortcut{bottom:calc(var(--chat-footer-height,0px) + max(16px,env(safe-area-inset-bottom)))}
.bgs-game-chat .chat-messages{max-height:clamp(48px,calc(100dvh - var(--chat-footer-height,0px) - 120px),250px)}
.game-chat-button-host--mobile .game-chat-button{width:42px;height:42px;margin:-7px 0;color:inherit}
.game-chat-button-host--mobile .game-chat-unread{border-color:var(--ui-banner-end)}
}
`;
slot.append(style);
document.head.append(style);
let locale = "en";
let disposed = false;
let players: { id: number; name: string; color?: string; faction?: string }[] = [];
let localPlayer: number | undefined;
let avatars: string[] = [];
let chatVisible = false;
let chatNotifications = true;
let analysis = false;
const shortcut = document.createElement("button");
shortcut.type = "button";
shortcut.className = "chat-shortcut";
shortcut.hidden = true;
slot.append(shortcut);
const footer = host.querySelector(".mobile-sticky-actions-spacer");
function viewport() {
return { bottom: Math.max(0, window.innerHeight - (footer?.getBoundingClientRect().height || 0)) };
let platformChat = false;
let view: ReturnType<typeof mountChat> | undefined;
let dialog: HTMLDialogElement | undefined;
const button = document.createElement("button");
button.type = "button";
button.className = "game-chat-button";
button.setAttribute("translate", "no");
button.hidden = true;
button.innerHTML = `<svg viewBox="0 0 16 16" width="23" height="23" fill="currentColor" aria-hidden="true"><path d="M2.678 11.894a1 1 0 0 1 .287.801a10.97 10.97 0 0 1-.398 2c1.395-.323 2.247-.697 2.634-.893a1 1 0 0 1 .71-.074A8.06 8.06 0 0 0 8 14c3.996 0 7-2.807 7-6c0-3.192-3.004-6-7-6S1 4.808 1 8c0 1.468.617 2.83 1.678 3.894zm-.493 3.905a21.682 21.682 0 0 1-.713.129c-.2.032-.352-.176-.273-.362a9.68 9.68 0 0 1 .244-.637l.003-.01c.248-.72.45-1.548.524-2.319C.743 11.37 0 9.76 0 8c0-3.866 3.582-7 8-7s8 3.134 8 7s-3.582 7-8 7a9.06 9.06 0 0 1-2.347-.306c-.52.263-1.639.742-3.468 1.105z"/></svg>`;
const badge = document.createElement("span");
badge.className = "game-chat-unread";
badge.setAttribute("aria-hidden", "true");
badge.hidden = true;
button.append(badge);
function closeLocalChat() {
dialog?.close();
chat.setOpen(false);
}
function openLocalChat() {
if (!dialog) {
dialog = document.createElement("dialog");
dialog.className = "game-chat-dialog";
const title = document.createElement("h2");
const close = document.createElement("button");
close.type = "button";
close.className = "game-chat-close";
close.textContent = "×";
close.onclick = closeLocalChat;
dialog.append(title, close);
host.append(dialog);
dialog.addEventListener("close", () => chat.setOpen(false));
dialog.addEventListener("keydown", (event) => event.stopPropagation());
view = mountChat(dialog, {
chat,
styles: false,
openPlayer: (index) => emitter.emit("player:clicked", { index }),
renderAuthor,
});
}
dialog.setAttribute("aria-label", translateText("Chat", locale));
const title = dialog.querySelector("h2");
if (title) title.textContent = translateText("Chat", locale);
dialog.querySelector(".game-chat-close")?.setAttribute("aria-label", translateText("Close", locale));
dialog.showModal();
chat.setOpen(true);
view?.refresh();
}
const view = mountChat(slot, {
chat,
styles: false,
openPlayer: (index) => emitter.emit("player:clicked", { index }),
renderAuthor,
onVisibilityChange(visible) {
chatVisible = visible;
updateShortcut();
},
viewport,
});
function renderAuthor(message: ChatMessage): Node {
const author = document.createElement("strong");
author.textContent = message.author || "Game";
@ -136,22 +170,26 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
wrapper.append(author);
return wrapper;
}
function updateShortcut() {
shortcut.setAttribute("translate", "no");
const count = chat.unread;
function updateButton() {
const count = chatNotifications ? chat.unread : 0;
const sourceLabel = count ? `Chat · ${count} unread` : "Chat";
const label = translateText(sourceLabel, locale);
const barSlot = window.innerWidth < 768 ? host.querySelector(".mobile-sticky-actions .chat-shortcut-host") : null;
const destination = barSlot || slot;
if (shortcut.parentElement !== destination) destination.append(shortcut);
shortcut.classList.toggle("chat-shortcut--inline", !!barSlot);
const text = barSlot && count ? translateText(`Chat · ${count}`, locale) : label;
if (shortcut.textContent !== text) shortcut.textContent = text;
shortcut.hidden = !chatNotifications || analysis || count === 0 || (!barSlot && chatVisible);
shortcut.setAttribute("aria-label", translateText(`Open ${sourceLabel}`, locale));
const mobileSlot =
window.innerWidth < 768 ? host.querySelector(".mobile-sticky-actions .game-chat-button-host--mobile") : null;
const destination =
mobileSlot ||
host.querySelector(".game-chat-button-host--desktop") ||
host.querySelector(".game-chat-button-host--fallback");
if (destination && button.parentElement !== destination) destination.append(button);
button.hidden = analysis || !chat.snapshot.enabled;
const text = String(count);
if (badge.textContent !== text) badge.textContent = text;
badge.hidden = count === 0;
button.title = translateText(sourceLabel, locale);
button.setAttribute("aria-label", translateText(`Open ${sourceLabel}`, locale));
}
shortcut.onclick = () => {
view.open();
button.onclick = () => {
if (platformChat) emitter.emit("chat:open");
else openLocalChat();
};
const dispose = [
detach,
@ -160,54 +198,54 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
locale = resolveLocale(preferences.locale);
void loadLocale(locale)
.then(() => {
if (!disposed) updateShortcut();
if (!disposed) updateButton();
})
.catch(() => {});
analysis = preferences.analysis === true;
slot.style.display = analysis ? "none" : "";
updateShortcut();
platformChat = preferences.platformChat === true;
if (analysis || platformChat) closeLocalChat();
if (platformChat && dialog) {
view?.destroy();
view = undefined;
dialog.remove();
dialog = undefined;
}
updateButton();
}),
chat.subscribe(updateShortcut),
chat.subscribe(updateButton),
emitter.on("state", (state) => {
players = (state?.players || []).map((player: any, index: number) => ({ ...player, id: index }));
view.refresh();
view?.refresh();
}),
emitter.on("gamelog", ({ data }: any) => {
if (data?.state) {
players = (data.state.players || []).map((player: any, index: number) => ({ ...player, id: index }));
view.refresh();
view?.refresh();
}
}),
emitter.on("player", (player) => {
localPlayer = player?.index;
view.refresh();
view?.refresh();
}),
];
dispose.push(
emitter.on("avatars", (data) => {
avatars = data;
view.refresh();
view?.refresh();
})
);
// The action bar is mounted and removed as turns change.
window.addEventListener("resize", updateShortcut);
dispose.push(() => window.removeEventListener("resize", updateShortcut));
const mutation = new MutationObserver(updateShortcut);
window.addEventListener("resize", updateButton);
dispose.push(() => window.removeEventListener("resize", updateButton));
const mutation = new MutationObserver(updateButton);
mutation.observe(host, { childList: true, subtree: true });
const resize = new ResizeObserver(() => {
view.refresh();
updateShortcut();
});
if (footer) resize.observe(footer);
dispose.push(
() => mutation.disconnect(),
() => resize.disconnect()
);
dispose.push(() => mutation.disconnect());
return () => {
disposed = true;
dispose.forEach((cleanup) => cleanup());
view.destroy();
shortcut.remove();
view?.destroy();
dialog?.remove();
button.remove();
style.remove();
};
}

3
viewer/vendor/README.md vendored Normal file
View file

@ -0,0 +1,3 @@
# BGS protocol
This pins the BGS protocol 0.11.0 package already used by the Puerto Rico viewer. It adds the `chat:open` event that opens the platform chat. Version 0.11.0 is not yet on npm; switch back to the registry dependency once it is published.

Binary file not shown.