primordial-soup/viewer/activity.js

204 lines
7.4 KiB
JavaScript

import { mountChat } from "@boardgamers/protocol/chat/dom";
import { amoeba, colors, icon } from "./art.js";
import { journalHtml } from "./journal.js";
let sequence = 0;
export function mountActivity(target, { chat, openPlayer, backToBoard } = {}) {
const id = `soup-activity-${++sequence}`;
const section = document.createElement("section");
section.className = "soup-activity";
section.setAttribute("aria-label", "Chat and journal");
section.innerHTML = `<header class="activity-header"><div class="activity-tabs" role="tablist" aria-label="Chat and journal">
<button type="button" role="tab" id="${id}-chat-tab" aria-controls="${id}-chat" data-tab="chat" ${chat ? "" : "hidden"}>${icon("chat")} Chat <span class="chat-count" hidden></span></button>
<button type="button" role="tab" id="${id}-journal-tab" aria-controls="${id}-journal" data-tab="journal">${icon("history")} Journal</button>
</div><button type="button" class="text-button activity-back">Back to board ↑</button></header>
<div id="${id}-chat" class="activity-chat" role="tabpanel" aria-labelledby="${id}-chat-tab" hidden></div>
<div id="${id}-journal" class="activity-journal" role="tabpanel" aria-labelledby="${id}-journal-tab" hidden><ol class="journal-list" tabindex="0" aria-label="Game journal"></ol></div>`;
let chatNotifications = true;
const shortcut = document.createElement("button");
shortcut.type = "button";
shortcut.className = "soup-chat-shortcut";
shortcut.hidden = true;
target.append(section, shortcut);
const tabs = [...section.querySelectorAll("[data-tab]")];
const tabList = section.querySelector(".activity-tabs");
const desktop = matchMedia("(min-width: 1001px)");
const chatPanel = section.querySelector(".activity-chat");
const journalPanel = section.querySelector(".activity-journal");
const journal = journalPanel.querySelector("ol");
const count = section.querySelector(".chat-count");
let active = chat ? "chat" : "journal";
let analysis = false;
let split = false;
let players = [];
let identity = "";
let journalKey;
let following = true;
let journalFrame;
const events = new AbortController();
const eventOptions = { signal: events.signal };
const chatView =
chat &&
mountChat(chatPanel, {
chat,
styles: false,
openPlayer,
renderAuthor(message) {
const author = document.createElement(
message.playerIndex !== undefined && openPlayer ? "button" : "strong",
);
author.className = "chat-author";
const player = players[message.playerIndex];
if (player && colors[player.color]) {
const portrait = document.createElement("span");
portrait.className = "chat-portrait";
portrait.innerHTML = amoeba(player.color);
author.append(portrait);
}
author.append(
document.createTextNode(message.author ?? player?.name ?? "Game"),
);
if (author.tagName === "BUTTON") {
author.type = "button";
author.onclick = () => openPlayer(message.playerIndex);
}
return author;
},
});
if (chatView) {
const body = document.createElement("div");
body.className = "chat-body";
body.append(
...[...chatView.element.children].filter(
(child) => child.tagName !== "SUMMARY",
),
);
chatView.element.append(body);
}
function followJournal() {
cancelAnimationFrame(journalFrame);
journalFrame = requestAnimationFrame(() => {
if (!journalPanel.hidden && following)
journal.scrollTop = journal.scrollHeight;
});
}
function select(kind) {
active = kind === "chat" && chat && !analysis ? "chat" : "journal";
split = desktop.matches && !!chat && !analysis;
section.classList.toggle("is-split", split);
tabList.setAttribute("role", split ? "group" : "tablist");
for (const tab of tabs) {
tab.setAttribute("role", split ? "button" : "tab");
if (split) tab.removeAttribute("aria-selected");
else
tab.setAttribute("aria-selected", String(tab.dataset.tab === active));
tab.tabIndex = split || tab.dataset.tab === active ? 0 : -1;
}
chatPanel.setAttribute("role", split ? "region" : "tabpanel");
journalPanel.setAttribute("role", split ? "region" : "tabpanel");
chatPanel.hidden = !split && active !== "chat";
journalPanel.hidden = !split && active !== "journal";
chat?.setOpen(!chatPanel.hidden);
followJournal();
}
function open(kind) {
select(kind);
section.scrollIntoView({ block: "center" });
if (active === "chat") chatView.open();
else journal.focus({ preventScroll: true });
}
for (const tab of tabs) {
tab.addEventListener(
"click",
() => (split ? open(tab.dataset.tab) : select(tab.dataset.tab)),
eventOptions,
);
tab.addEventListener(
"keydown",
(event) => {
if (split) return;
const shown = tabs.filter((item) => !item.hidden);
const index = shown.indexOf(tab);
const next = {
ArrowRight: (index + 1) % shown.length,
ArrowLeft: (index + shown.length - 1) % shown.length,
Home: 0,
End: shown.length - 1,
}[event.key];
if (next === undefined) return;
event.preventDefault();
select(shown[next].dataset.tab);
shown[next].focus();
},
eventOptions,
);
}
desktop.addEventListener("change", () => select(active), eventOptions);
section
.querySelector(".activity-back")
.addEventListener("click", backToBoard, eventOptions);
shortcut.addEventListener("click", () => open("chat"), eventOptions);
journal.addEventListener(
"scroll",
() => {
if (journal.clientHeight)
following =
journal.scrollHeight - journal.scrollTop - journal.clientHeight <= 1;
},
{ ...eventOptions, passive: true },
);
const unsubscribe = chat?.subscribe((snapshot) => {
const unread = snapshot.unreadIds.length;
count.hidden = !unread;
count.textContent = unread;
count.setAttribute("aria-label", `${unread} unread messages`);
shortcut.hidden = !chatNotifications || analysis || !unread;
shortcut.innerHTML = `${icon("chat")} Chat <span>${unread}</span>`;
shortcut.setAttribute(
"aria-label",
`Open chat, ${unread} unread message${unread === 1 ? "" : "s"}`,
);
});
select(active);
return {
open,
setChatNotifications(enabled) {
chatNotifications = enabled;
shortcut.hidden = !chatNotifications || analysis || !chat?.unread;
},
setAnalysisMode(value) {
analysis = value;
tabs.find((tab) => tab.dataset.tab === "chat").hidden = analysis || !chat;
select(analysis ? "journal" : active);
shortcut.hidden = !chatNotifications || analysis || !chat?.unread;
},
update(state) {
players = state.players;
const nextIdentity = JSON.stringify(
players.map(({ name, color }) => [name, color, colors[color]]),
);
if (nextIdentity !== identity) {
identity = nextIdentity;
chatView?.refresh();
}
const lines = state.log.slice(-150);
const key = nextIdentity + JSON.stringify(lines);
if (key === journalKey) return;
journalKey = key;
journal.innerHTML = journalHtml(lines, players);
followJournal();
},
destroy() {
events.abort();
cancelAnimationFrame(journalFrame);
unsubscribe?.();
chatView?.destroy();
section.remove();
shortcut.remove();
},
};
}