import { playerColorInk } from "./player-colors.js";
import { assets } from "./assets.js";
import { createRenderer } from "./dom.js";
import { tilePreviewSvg } from "./board.js";
import { blockingHtml } from "./blocking.js";
import { translateText } from "./localization/index.js";
import { mountChat } from "@boardgamers/protocol/chat/dom";
import {
icon as renderIcon,
token as renderToken,
iconLabel,
esc,
} from "./art.js";
import { translator } from "./labels.js";
import { journalRows, eventCells } from "./journal.js";
import { ACTIONS, CHARACTERS, COLORS } from "../engine/catalog.js";
export function mountActivity(
target,
{
chat,
openPlayer,
avatarForPlayer,
onBack,
onHighlight,
language = "en",
} = {},
) {
let colorBlind = false,
lang = language;
const icon = (name) =>
renderIcon(name, translateText(iconLabel(name), lang), false, colorBlind);
const token = (name, n) =>
renderToken(
name,
n,
`${translateText(iconLabel(name), lang)}: ${n}`,
colorBlind,
);
const markerToken = (action, n) =>
renderToken(
action,
n,
`${translateText("Markers", lang)}: ${n} · ${translateText(translator(lang)(action), lang)}`,
colorBlind,
);
const root = document.createElement("section");
root.className = "activity";
root.innerHTML = `
`;
const shortcut = document.createElement("button");
shortcut.className = "chat-shortcut";
shortcut.hidden = true;
shortcut.type = "button";
target.append(root, shortcut);
const list = root.querySelector("ol"),
journal = root.querySelector(".journal-panel"),
panel = root.querySelector(".chat-panel");
const wide = window.matchMedia("(min-width: 1100px)");
const patch = createRenderer("li");
let mode = "journal",
analysis = false,
state,
t = translator(lang),
following = true,
followFrame,
unreadKey,
labelsLanguage,
rowSources = [],
key = "";
const view = chat
? mountChat(panel, {
chat,
openPlayer,
styles: true,
labels: undefined,
renderAuthor(message) {
const index = message.playerIndex;
if (index === undefined) return undefined;
const author = document.createElement(
openPlayer ? "button" : "strong",
);
author.className = "chat-author";
author.dataset.bgsPlayer = index;
const color = state?.players[index]?.color ?? COLORS[index];
if (color)
author.style.setProperty(
"--chat-player-ink",
playerColorInk(color),
);
const avatar = avatarForPlayer?.(index);
if (avatar) {
const img = document.createElement("img");
img.className = "player-avatar";
img.src = avatar;
img.alt = "";
author.append(img);
}
author.append(
document.createTextNode(
message.author ?? state?.players[index]?.name ?? "",
),
);
if (openPlayer) {
author.type = "button";
author.onclick = () => openPlayer(index);
}
return author;
},
})
: null;
if (view) {
// Keep the composer outside the scrolling feed, within the fixed tab height.
const body = document.createElement("div");
body.className = "chat-body";
for (const child of [...view.element.children]) {
if (!child.matches("summary, style")) body.append(child);
}
view.element.append(body);
}
function select(kind) {
mode = kind === "chat" && chat && !analysis ? "chat" : "journal";
const split = wide.matches && !!chat && !analysis;
root.classList.toggle("split", split);
root
.querySelector(".activity-tabs")
.setAttribute("role", split ? "group" : "tablist");
journal.hidden = !split && mode !== "journal";
panel.hidden = !split && mode !== "chat";
for (const p of [journal, panel])
p.setAttribute("role", split ? "region" : "tabpanel");
for (const b of root.querySelectorAll("[data-tab]")) {
b.setAttribute("role", split ? "button" : "tab");
if (split) b.removeAttribute("aria-selected");
else b.setAttribute("aria-selected", String(b.dataset.tab === mode));
b.tabIndex = split || b.dataset.tab === mode ? 0 : -1;
}
// The shared feed tracks which messages are actually visible. Closing its
// details when offscreen would collapse the panel and move the page.
chat?.setOpen(split || (mode === "chat" && !analysis));
view?.refresh();
}
const resize = () => select(mode);
wide.addEventListener("change", resize);
function open(kind) {
select(kind);
root.scrollIntoView({ behavior: "smooth", block: "start" });
if (kind === "journal") list.focus({ preventScroll: true });
}
const text = (source) => esc(translateText(source, lang));
const playerName = (p) =>
state?.players[p]
? `${esc(state.players[p].name)}`
: "";
const chip = (html, kind = "") =>
`${html}`;
const gain = (name, n) => chip(token(name, `+${n}`), "event-gain");
const cost = (n) =>
chip(n ? token("coin", `−${n}`) : text("Free"), "event-cost");
const location = (cell) =>
cell
? `${esc(cell)}`
: "";
function portrait(character) {
const c = CHARACTERS[character];
return c
? `
`
: "";
}
function heading(e, label, symbol, character) {
return `${playerName(e.p)}${portrait(character)} ${symbol ? icon(symbol) : ""}${label}`;
}
const details = (html) =>
html ? `${html}` : "";
function eventHtml(e) {
const d = e.details ?? {};
switch (e.type) {
case "restock":
return (
heading(e, text("Goods replenished"), "buy") +
details(
Object.entries(e.goods)
.filter(([, n]) => n > 0)
.map(([good, n]) => gain(good, n))
.join(""),
) +
location(e.cell)
);
case "touristDraw":
return (
heading(e, text("Tourist tile")) +
details(chip(token("tourist", e.tourists)))
);
case "action": {
const parts = [];
if (d.cost !== undefined) parts.push(cost(d.cost));
if (e.path) parts.push(chip(token("sail", e.path.length)));
if (e.action === "sell") {
const fish = token(
"fish",
e.fish.reduce((a, b) => a + b, 0),
);
parts.push(
chip(
d.price === undefined
? fish
: `${fish} × ${token("coin", d.price)} → ${token("coin", `+${d.income}`)}`,
"event-gain",
),
);
}
if (d.fish !== undefined) parts.push(gain("fish", d.fish));
if (d.treasure !== undefined) parts.push(gain("explore", d.treasure));
if (e.good) parts.push(chip(token(e.good, d.shipments?.length ?? 1)));
if (e.hut) parts.push(chip(token("build", 1)));
if (e.dike) parts.push(chip(token("dike", 1)));
if (e.action === "tourist") parts.push(chip(token("tourist", 1)));
if (
d.income !== undefined &&
!(e.action === "sell" && d.price !== undefined)
)
parts.push(gain("coin", d.income));
if (d.points !== undefined) parts.push(gain("point", d.points));
const route = e.path
? `${location(d.from)} → ${location(e.path.at(-1))}`
: location(d.cell ?? e.cell);
const completions =
d.shipments
?.filter((s) => s.complete)
.map((s) =>
chip(`${icon("check")}${text("Ship completed (+2 included)")}`),
)
.join("") ?? "";
const role =
d.character ??
(e.preach
? "preacher"
: e.bonus
? Object.keys(CHARACTERS).find(
(c) => CHARACTERS[c].action === e.action,
)
: null);
const rest =
e.action === "rest" && e.restToken && e.restToken !== "hidden"
? restReward(e.restToken, false)
: "";
return (
heading(
e,
text(
e.action === "rest" && e.restToken
? "Rest token chosen"
: t(e.action),
),
e.action,
role,
) +
details(parts.join("") + rest) +
(route || completions
? `${route}${completions}`
: "")
);
}
case "plan":
case "neutral": {
const counts = Object.fromEntries(
ACTIONS.map((a) => [a, e.actions.filter((v) => v === a).length]),
);
const added = ACTIONS.filter((a) => counts[a])
.map((a) => chip(markerToken(a, `+${counts[a]}`)))
.join("");
const totals = e.totals
? `${text("Planned")}${ACTIONS.filter(
(a) => e.totals[a],
)
.map((a) => markerToken(a, e.totals[a]))
.join("")}`
: "";
return (
heading(
e,
text(e.type === "neutral" ? t("neutral") : "Place markers"),
"marker",
) +
details(added) +
totals
);
}
case "character":
return heading(
e,
`${portrait(e.character)}${text(CHARACTERS[e.character]?.name ?? e.character)}`,
);
case "conversion":
return (
heading(e, "") +
details(
chip(
`${token("coin", `−${e.points * 2}`)} → ${token("point", `+${e.points}`)}`,
),
)
);
case "treasure": {
const n = e.values.reduce((a, b) => a + b, 0);
return (
heading(e, text(t("treasure")), "explore") +
details(chip(`${token("explore", n)} → ${token("coin", `+${n}`)}`))
);
}
case "beg":
return (
heading(e, text(t("beg"))) +
details(
chip(
`${token("point", `−${e.amount}`)} → ${token("coin", `+${e.amount}`)}`,
) + portrait("beggar"),
)
);
case "discard":
return (
heading(e, text("Retrieve without acting"), "warning") +
details(chip(markerToken(e.action, e.markers ?? ""), "event-cost")) +
(e.blockers
? `${blockingHtml(state, e.p, e.action, lang, e, colorBlind)}`
: "")
);
case "governor":
return (
heading(e, text(t("governor"))) +
details(
chip(
`${markerToken(e.from, e.markers ?? "")} → ${markerToken(e.to, e.markers ?? "")}`,
) + portrait("governor"),
)
);
case "rest":
return (
heading(e, text("Rest token chosen"), "rest") +
details(e.token !== "hidden" ? restReward(e.token, false) : "")
);
case "restBonus":
return (
heading(e, text(t("rest")), "rest") + details(restReward(e.token))
);
case "place":
return (
heading(e, "") +
`${tilePreviewSvg(e.tile, { colorBlind, t, language: lang, prefix: "event-" + e.cell })}${location(e.cell)}`
);
case "flood":
return heading(e, text(t("water")), "water");
case "submerged":
return heading(e, text("Submerged"), "water") + location(e.cell);
case "lost":
return `${text(t("lost"))}`;
case "end":
return `${text(t("finished"))}${details((e.scores ?? []).map((score, p) => chip(`${playerName(p)} ${token("point", score)}`)).join(""))}`;
default:
return "";
}
}
function restReward(value, awarded = true) {
const reward = (name) => (awarded ? gain(name, 1) : chip(token(name, 1)));
if (value === "first") return chip(`${icon("first")}${text(t("first"))}`);
if (value === "both") return reward("coin") + reward("point");
return ["coin", "point"].includes(value) ? reward(value) : "";
}
function rowHtml(row) {
if (row.kind === "round")
return `${text(t("round"))} ${row.round}/8${row.first !== undefined ? `${icon("first")}${playerName(row.first)}` : ""}`;
if (row.kind === "phase") {
const label =
{
plan: "Marker placement",
actions: "Actions",
restBonus: "Rest bonuses",
}[row.phase] ?? t(row.phase);
const symbol = {
plan: "marker",
actions: "check",
restBonus: "rest",
character: "eye",
expand: "overview",
neutral: "marker",
ended: "point",
}[row.phase];
return `${symbol ? icon(symbol) : ""}${text(label)}${row.pass ? `${row.pass}/3` : ""}`;
}
const html = eventHtml(row.event);
const cells = eventCells(row.event);
const button = cells.length
? ``
: html;
return html
? `${button}`
: "";
}
function refresh() {
if (!state) return;
const next =
JSON.stringify(state.events ?? state.lastEvents ?? []) +
lang +
colorBlind +
JSON.stringify(state.players.map(({ name, color }) => [name, color])) +
state.boardLayout;
if (next === key) return;
key = next;
const rows = journalRows(state).map(rowHtml).filter(Boolean);
const mounted = [...list.children];
for (let i = 0; i < Math.min(mounted.length, rows.length); i++)
if (rowSources[i] !== rows[i]) patch(mounted[i], rows[i]);
for (const row of mounted.slice(rows.length)) row.remove();
if (rows.length > mounted.length)
list.insertAdjacentHTML("beforeend", rows.slice(mounted.length).join(""));
rowSources = rows;
cancelAnimationFrame(followFrame);
if (following)
followFrame = requestAnimationFrame(() => {
if (following) list.scrollTop = list.scrollHeight;
});
}
const interactions = new AbortController(),
listener = { signal: interactions.signal };
let pinned, hovered, focused;
function highlight() {
const row = hovered ?? focused ?? pinned;
for (const button of list.querySelectorAll("[data-journal-cells]")) {
button.classList.toggle("inspected", button === row);
button.setAttribute("aria-pressed", String(button === pinned));
}
onHighlight?.(row?.dataset.journalCells.split(" ") ?? []);
}
function clearHighlight() {
pinned = hovered = focused = null;
highlight();
}
list.addEventListener(
"pointerover",
(e) => {
if (e.pointerType === "touch") return;
const row = e.target.closest("[data-journal-cells]");
if (row !== hovered) {
hovered = row;
highlight();
}
},
listener,
);
list.addEventListener(
"pointerleave",
() => {
hovered = null;
highlight();
},
listener,
);
list.addEventListener(
"focusin",
(e) => {
focused = e.target.closest("[data-journal-cells]");
highlight();
},
listener,
);
list.addEventListener(
"focusout",
() => {
focused = null;
highlight();
},
listener,
);
list.addEventListener(
"click",
(e) => {
const row = e.target.closest("[data-journal-cells]");
if (!row) return;
pinned = pinned === row ? null : row;
hovered = focused = null;
highlight();
if (pinned) onBack?.();
},
listener,
);
document.addEventListener(
"pointerdown",
(e) => {
if (pinned && !e.target.closest("[data-journal-cells]")) clearHighlight();
},
listener,
);
document.addEventListener(
"keydown",
(e) => {
if (e.key === "Escape") clearHighlight();
},
listener,
);
root.addEventListener("click", (e) => {
const b = e.target.closest("button");
if (!b) return;
if (b.dataset.tab) select(b.dataset.tab);
if ("back" in b.dataset) onBack?.();
});
shortcut.onclick = () => open("chat");
list.addEventListener("scroll", () => {
following = list.scrollHeight - list.scrollTop - list.clientHeight <= 1;
});
select("journal");
return {
open,
update(s, isAnalysis, isColorBlind = false) {
colorBlind = isColorBlind;
if (state && s.historyLength < state.historyLength) clearHighlight();
state = s;
const changed = analysis !== isAnalysis;
analysis = isAnalysis;
root.querySelector('[data-tab="chat"]').hidden = !chat || analysis;
if (changed) select(mode);
refresh();
},
refreshAvatars() {
view?.refresh();
},
setUnread(n, notifications = true) {
const next = `${n}:${notifications}:${analysis}:${lang}:${colorBlind}`;
if (unreadKey === next) return;
unreadKey = next;
const badge = root.querySelector(".unread");
badge.textContent = n;
badge.hidden = !n;
shortcut.hidden = !notifications || !n || analysis;
shortcut.innerHTML = `${icon("chat")} ${n}`;
shortcut.setAttribute("aria-label", `${t("chat")}: ${n}`);
},
setLanguage(l) {
if (labelsLanguage === l) return;
labelsLanguage = l;
lang = l;
t = translator(l);
root.querySelector("[data-back] span").textContent = t("board");
root.querySelector('[data-tab="chat"] span').textContent = t("chat");
journal.setAttribute("aria-label", t("journal"));
panel.setAttribute("aria-label", t("chat"));
refresh();
},
destroy() {
interactions.abort();
cancelAnimationFrame(followFrame);
wide.removeEventListener("change", resize);
view?.destroy();
root.remove();
shortcut.remove();
},
};
}