Add chat mentions, rich messages and scenario labels

This commit is contained in:
coyotte508 2026-09-13 17:15:36 +02:00
commit c1d2738f5c
10 changed files with 367 additions and 10 deletions

View file

@ -4,7 +4,7 @@
Engine entry point: `dist/wrapper.js` from `fuji-engine`. The wrapper exports init, move, ended, scores, rankings, currentPlayer, dropPlayer, logLength, logSlice, stripSecret, round, replay and setPlayerMetaData, plus the optional isLiveUpdate hook. `hashSeed = true`; the seed never appears in a stripped view. `moveAI(state, player)` returns a new state using the shared baseline bot; the harness and simulations use the same implementation.
Viewer: self-contained IIFE, global `fuji`, function `launch(selector)` returning an emitter. The bridge consumes state/player events, requests fresh state on state updates and game logs, forwards moves without double wrapping, and announces readiness after rendering the initial state. The host provides chat transport and storage, clocks, identity and iframe messaging. Set `viewer.chat: true`: Fuji renders chat during and after the expedition, including lobby history. The bridge handles `chat:messages`, `chat:appended`, `chat:updated`, `chat:deleted`, `chat:state`, `chat:disabled` and `chat:result`; sends carry a request ID and visible messages emit `chat:read`. Chat drafts and updates are independent of game animation playback. The local harness keeps its chat separately in local storage; switch seats to test multiple authors. Source assets are bundled as data URLs, so the initial viewer has no independent asset-hosting requirement.
Viewer: self-contained IIFE, global `fuji`, function `launch(selector)` returning an emitter. The bridge consumes state/player events, requests fresh state on state updates and game logs, forwards moves without double wrapping, and announces readiness after rendering the initial state. The host provides chat transport and storage, clocks, identity and iframe messaging. Set `viewer.chat: true`: Fuji renders chat during and after the expedition, including lobby history. The bridge handles `chat:messages`, `chat:appended`, `chat:updated`, `chat:deleted`, `chat:state`, `chat:disabled` and `chat:result`; sends carry a request ID and visible messages emit `chat:read`. Chat drafts and updates are independent of game animation playback. The `chat:state` roster supplies mention suggestions. Messages use BGS-provided text, link and mention segments, with plain text as a fallback; outgoing mentions use `@name` or `@"Full Name"`. Links follow platform trust rules, and reading the chat clears the platform mention badge. The local harness keeps its chat separately in local storage; switch seats to test multiple authors. Source assets are bundled as data URLs, so the initial viewer has no independent asset-hosting requirement.
```sh
pnpm check

View file

@ -10,7 +10,7 @@
"fmt": "oxfmt",
"fmt:check": "oxfmt --check",
"simulate": "pnpm --filter fuji-engine build && node scripts/simulate.mjs",
"test:browser": "node tests/browser-smoke.mjs && node tests/bgs-bundle-smoke.mjs && node tests/presentation-smoke.mjs && node tests/chat-smoke.mjs && node tests/mobile-readiness-smoke.mjs && node tests/chat-tabs-smoke.mjs"
"test:browser": "node tests/browser-smoke.mjs && node tests/bgs-bundle-smoke.mjs && node tests/presentation-smoke.mjs && node tests/chat-smoke.mjs && node tests/mobile-readiness-smoke.mjs && node tests/chat-tabs-smoke.mjs && node tests/chat-mentions-smoke.mjs"
},
"devDependencies": {
"oxfmt": "0.61.0",

View file

@ -438,6 +438,7 @@
? "Preparation"
: s.phase}</span
>
<span class="difficulty-label">Scenario {s.scenario ?? 1}</span>
<button
type="button"
class="difficulty-label"
@ -1047,7 +1048,13 @@
disabled={store.waiting || !canReopenChoice(s, seat!)}>Change my choice</button
>{/if}
{:else if s.phase === "movement"}
{#if s.activeResolution === null}<p class="instruction">
{#if s.players.some((p) => p.pendingInjuries)}<p class="instruction">
Waiting for {s.players
.filter((p) => p.pendingInjuries)
.map((p) => p.name)
.join(", ")} to choose an injury.
</p>
{:else if s.activeResolution === null}<p class="instruction">
Choose who moves next. A route that triggers extra lava is often best resolved last.
</p>
{#if !me.resolved}<button class="primary" onclick={() => store.dispatch({ action: "beginMovement" })}
@ -1111,9 +1118,9 @@
disabled={store.waiting}
onclick={() => store.dispatch({ action: "help", count: 0 })}>Don't use bars</button
>
{:else}<p class="instruction">
Waiting for {s.pendingHelpers?.map((i) => s.players[i]!.name).join(", ") || "the Gatherer"} to decide whether
to use power bars.
{:else if s.pendingHelpers?.length}<p class="instruction">
Waiting for {s.pendingHelpers.map((i) => s.players[i]!.name).join(", ")} to decide whether to use power
bars.
</p>{/if}
{/if}
{:else if s.phase === "eruption"}

View file

@ -1,4 +1,6 @@
import { mount } from "svelte";
import { parseMentions } from "./lib/mentions";
import type { ChatSegment } from "./lib/chat.svelte";
import App from "./App.svelte";
import { Store } from "./lib/store.svelte";
import { initGame, applyMove, moveAI, stripSecret, activePlayers, type State } from "fuji-engine";
@ -21,6 +23,15 @@ store.chat.send = ({ text, requestId }) => {
author: store.state?.players[playerIndex]?.name ?? `Player ${playerIndex + 1}`,
playerIndex,
text,
segments: parseMentions(text, new Map(store.chat.mentions.map((p) => [p.id, p.name]))).flatMap(
(segment): ChatSegment[] =>
segment.kind === "mention"
? [segment]
: segment.text
.split(/(https?:\/\/[^\s<>"'`]+)/g)
.filter(Boolean)
.map((text) => (/^https?:\/\//.test(text) ? { kind: "link", url: text, text } : { kind: "text", text }))
),
type: "text",
createdAt: new Date().toISOString(),
},
@ -77,6 +88,11 @@ if (import.meta.hot)
function publish() {
localStorage.setItem("fuji-dev-v1", JSON.stringify(game));
store.receive(stripSecret(game, store.seat));
store.chat.mentions = game.players.map((p, playerIndex) => ({
id: `local-${playerIndex}`,
name: p.name,
playerIndex,
}));
scheduleTeammate();
}
store.send = (move) => {

View file

@ -1,8 +1,28 @@
<script lang="ts">
import { tick } from "svelte";
import type { Store } from "./store.svelte";
import { mentionQueryAt, filterMentionCandidates, applyMention } from "./mentions";
let { store }: { store: Store } = $props();
const chat = $derived(store.chat);
let composer: HTMLInputElement | undefined = $state();
let caret = $state(0);
let choice = $state(0);
let dismissed = $state(false);
const query = $derived(dismissed ? null : mentionQueryAt(chat.draft, caret));
const candidates = $derived(query ? filterMentionCandidates(chat.mentions, query.query) : []);
async function chooseMention(name: string) {
if (!query) return;
const next = applyMention(chat.draft, query, name);
chat.draft = next.text;
caret = next.caret + 1;
dismissed = true;
await tick();
composer?.focus();
composer?.setSelectionRange(caret, caret);
}
function safeLink(url: string) {
return /^https?:\/\//i.test(url);
}
let list: HTMLDivElement | undefined = $state();
let contents: HTMLDivElement | undefined = $state();
@ -123,19 +143,74 @@
{#if message.editedAt}<span title={new Date(message.editedAt).toLocaleString()}>edited</span>{/if}
</div>
{/if}
<p>{message.text}</p>
<p>
{#each message.segments ?? [{ kind: "text" as const, text: message.text }] as segment}
{#if segment.kind === "link" && safeLink(segment.url)}<a
href={segment.url}
target="_blank"
rel="noopener noreferrer">{segment.text}</a
>
{:else if segment.kind === "mention"}{@const player = chat.mentions.find((p) => p.id === segment.id)}
{#if player?.playerIndex !== undefined}<button
class="chat-mention"
onclick={() => store.clickPlayer(player.playerIndex!)}>@{segment.name}</button
>
{:else}<a
class="chat-mention"
href={`https://boardgamers.space/user/${encodeURIComponent(segment.name)}`}
target="_blank"
rel="noopener noreferrer">@{segment.name}</a
>{/if}
{:else}{segment.text}{/if}
{/each}
</p>
</article>
{/each}
</div>
</div>
{#if chat.canSend && !chat.disabled}
{#if candidates.length}<div class="mention-choices" aria-label="Mention a teammate">
{#each candidates as candidate, i}<button
type="button"
class:selected={i === choice}
onmousedown={(e) => e.preventDefault()}
onclick={() => chooseMention(candidate.name)}>@{candidate.name}</button
>{/each}
</div>{/if}
<div class="chat-composer">
<input
type="text"
aria-label="Chat message"
placeholder="Message your teammates…"
bind:value={chat.draft}
bind:this={composer}
oninput={() => {
caret = composer?.selectionStart ?? 0;
choice = 0;
dismissed = false;
}}
onclick={() => {
caret = composer?.selectionStart ?? 0;
dismissed = false;
}}
onkeydown={(event) => {
if (!event.isComposing && candidates.length) {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
choice = (choice + (event.key === "ArrowDown" ? 1 : candidates.length - 1)) % candidates.length;
return;
}
if (event.key === "Escape") {
event.preventDefault();
dismissed = true;
return;
}
if (event.key === "Enter" || event.key === "Tab") {
event.preventDefault();
void chooseMention(candidates[choice]?.name ?? candidates[0]!.name);
return;
}
}
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
event.preventDefault();
chat.submit();
@ -156,6 +231,37 @@
{/if}
<style>
.chat-mention {
color: var(--gold, #e6c780);
font: inherit;
font-weight: 600;
padding: 0 2px;
background: #e6c78015;
border: 0;
cursor: pointer;
}
.mention-choices {
display: flex;
flex-wrap: wrap;
gap: 4px;
padding: 6px 0;
}
.mention-choices button {
color: #f1e6bf;
background: #203b32;
border: 1px solid #e6c78055;
padding: 5px 8px;
}
.mention-choices button.selected {
border-color: #e6c780;
background: #365348;
}
article p a {
color: #9ed9ea;
text-decoration: underline;
overflow-wrap: anywhere;
}
.expedition-chat {
border-top: 1px solid #e6c78030;
padding: 12px;

View file

@ -1,3 +1,8 @@
export type ChatSegment =
| { kind: "text"; text: string }
| { kind: "link"; text: string; url: string }
| { kind: "mention"; id: string; name: string };
export type ChatMention = { id: string; name: string; playerIndex?: number };
export type ChatMessage = {
_id?: string;
author?: string;
@ -5,11 +10,13 @@ export type ChatMessage = {
playerIndex?: number;
createdAt?: string;
text: string;
segments?: ChatSegment[];
type: "text" | "system";
editedAt?: string;
};
export class Chat {
enabled = $state(false);
mentions: ChatMention[] = $state([]);
open = $state(true);
messages: ChatMessage[] = $state([]);
canSend = $state(false);

View file

@ -0,0 +1,153 @@
// Mention parsing for chat (@username): rendering + autocomplete query state.
//
// Syntax: `@name` for plain-word usernames ([A-Za-z0-9_.-]+), and `@"name with
// spaces"` when the name isn't a plain word (the autocomplete always inserts the
// right form). Usernames forbid "@" by schema (packages/models user.ts), so "@"
// is an unambiguous trigger. The quote form never spans a line break.
//
// Rendering is roster-based: segments resolve against the room's known users, so
// an "@foo" that matches nobody stays plain text (no dead profile link). The
// roster is assembled per room by ChatRoom (game players + chat authors).
export type MentionCandidate = {
/** User id — the rendered link routes to the profile. */
id: string;
/** The username exactly as stored (mention text matches this). */
name: string;
};
export type MentionSegment = { kind: "text"; text: string } | { kind: "mention"; name: string; id: string };
// Plain-word usernames: letters, digits, underscore, dot, hyphen. Everything
// else (spaces, unicode, …) needs the quoted form.
const PLAIN_NAME = /^[A-Za-z0-9_.-]+$/;
// Matches a mention anywhere: `@word` or `@"quoted name"`.
const MENTION_RE = /@([A-Za-z0-9_.-]+)|@"([^"\n]+)"/g;
/**
* Split message text into text and mention segments, resolving mentions against
* the roster (id by name). Unresolvable @-references stay plain text — no dead
* links, and no way for a message author to fabricate a link to an arbitrary
* profile that isn't in the room.
*/
export function parseMentions(text: string, roster: Map<string, string>): MentionSegment[] {
const byName = new Map<string, string>();
for (const [id, name] of roster) {
byName.set(name.toLowerCase(), id);
}
const segments: MentionSegment[] = [];
let last = 0;
for (const match of text.matchAll(MENTION_RE)) {
const name = match[1] ?? match[2]!;
const id = byName.get(name.toLowerCase());
// A word char before the @ (emails, emoji codes) disqualifies the mention.
if (!id || (match.index > 0 && /\S/.test(text[match.index - 1]!))) continue;
if (match.index > last) {
segments.push({ kind: "text", text: text.slice(last, match.index) });
}
segments.push({ kind: "mention", name, id });
last = match.index + match[0].length;
}
if (last < text.length) {
segments.push({ kind: "text", text: text.slice(last) });
}
return segments;
}
/**
* Whether a username needs the quoted mention form (anything outside
* [A-Za-z0-9_.-] — spaces, unicode, …).
*/
export function needsQuotedMention(name: string): boolean {
return !PLAIN_NAME.test(name);
}
/**
* The literal text for a mention of `name` — `@name` or `@"full name"`, with a
* trailing space so typing continues right after it.
*/
export function mentionText(name: string): string {
return needsQuotedMention(name) ? `@"${name}" ` : `@${name} `;
}
/** A live autocomplete query: the mention being typed at the caret, if any. */
export type MentionQuery = {
/** Text typed after the @ (or inside the quotes) so far. */
query: string;
/** Index where the whole reference starts (the @). */
start: number;
/** Index where the reference ends (== caret). */
end: number;
/** Quote form: the reference started as `@"` and is not closed yet. */
quoted: boolean;
};
/**
* Find the mention being typed at `caret`, or null when the caret is not inside
* a @-reference. Trigger rules:
* - caret right after a fresh `@` (empty query), or
* - caret inside/after `@word…` plain-name chars, or
* - caret inside an unclosed `@"…`.
* A non-space char before the @ disqualifies the trigger — a mid-word @ (emails,
* emoji codes) is not a mention.
*/
export function mentionQueryAt(text: string, caret: number): MentionQuery | null {
// Quote form: an `@"` opened before the caret and not yet closed — the next
// quote (if any) is at/after the caret. indexOf === -1 means no closer at all
// (still being typed), which counts as open.
const open = text.lastIndexOf('@"', caret);
const closer = open >= 0 ? text.indexOf('"', open + 2) : -2;
if (open >= 0 && (closer === -1 || closer >= caret)) {
if (open > 0 && /\S/.test(text[open - 1]!)) return null;
return { query: text.slice(open + 2, caret), start: open, end: caret, quoted: true };
}
// Plain form: scan back over name chars, then require the @ before them.
let i = caret;
while (i > 0 && PLAIN_NAME.test(text[i - 1]!)) {
i--;
}
// The @ must be followed immediately by the caret's name chars — but a plain
// name can't contain "l" then space… the scan is over PLAIN_NAME chars only.
if (i === caret && i > 0 && text[i - 1]! === "@") {
return { query: "", start: i - 1, end: caret, quoted: false };
}
if (i === 0 || text[i - 1]! !== "@") {
return null;
}
const start = i - 1;
if (start > 0 && /\S/.test(text[start - 1]!)) {
return null;
}
return { query: text.slice(start + 1, caret), start, end: caret, quoted: false };
}
/**
* Filter the roster for the autocomplete list: prefix match, case-insensitive,
* exact match first, then alphabetical. Caller decides who's in the roster
* (bots are not offered).
*/
export function filterMentionCandidates(roster: MentionCandidate[], query: string, limit = 8): MentionCandidate[] {
const q = query.toLowerCase();
return roster
.filter((c) => c.name.toLowerCase().startsWith(q))
.sort((a, b) => {
const ax = a.name.toLowerCase();
const bx = b.name.toLowerCase();
if (ax === q) return -1;
if (bx === q) return 1;
return ax < bx ? -1 : ax > bx ? 1 : 0;
})
.slice(0, limit);
}
/**
* Replace the query being typed (the [start, end) span from mentionQueryAt) with
* the chosen mention's literal text, returning the new full text and the caret
* position right after the inserted mention (before its trailing space).
*/
export function applyMention(text: string, q: MentionQuery, name: string): { text: string; caret: number } {
const literal = needsQuotedMention(name) ? `@"${name}"` : `@${name}`;
const next = text.slice(0, q.start) + literal + " " + text.slice(q.end);
return { text: next, caret: q.start + literal.length };
}

View file

@ -2,7 +2,7 @@ import { mount, tick } from "svelte";
import App from "./App.svelte";
import { Store } from "./lib/store.svelte";
import { Emitter } from "./lib/emitter";
import type { ChatMessage } from "./lib/chat.svelte";
import type { ChatMessage, ChatMention } from "./lib/chat.svelte";
import type { View } from "fuji-engine";
import "./lib/theme.css";
export function launch(selector: string) {
@ -25,10 +25,11 @@ export function launch(selector: string) {
events.on<boolean>("chat:disabled", (disabled) => {
chat.disabled = disabled;
});
events.on<{ canSend: boolean; reason?: string }>("chat:state", (state) => {
events.on<{ canSend: boolean; reason?: string; mentions?: ChatMention[] }>("chat:state", (state) => {
chat.enabled = true;
chat.canSend = state.canSend;
chat.reason = state.reason ?? "";
chat.mentions = state.mentions ?? [];
});
events.on<{ requestId: string; ok: boolean; error?: string }>("chat:result", (result) => chat.result(result));

View file

@ -0,0 +1,67 @@
import { chromium } from "playwright";
import { initGame, stripSecret } from "../packages/engine/dist/index.js";
import assert from "node:assert/strict";
const root = new URL("../", import.meta.url).pathname;
const browser = await chromium.launch({ headless: true, executablePath: process.env.FUJI_CHROMIUM_EXECUTABLE });
for (const width of [390, 1400]) {
const p = await browser.newPage({ viewport: { width, height: 950 } });
const errors = [];
p.on("pageerror", (e) => errors.push(e.message));
await p.setContent('<div id="app"></div>');
await p.addStyleTag({ path: root + "/packages/viewer/dist/fuji-viewer.css" });
await p.addScriptTag({ path: root + "/packages/viewer/dist/fuji-viewer.iife.js" });
const s = initGame(3, { skillAssignment: "fixed", scenario: 7, difficulty: 2 }, "mention-preview");
s.phase = "movement";
s.activeResolution = 1;
s.players.forEach((x, i) => {
x.skill = "buddy";
x.setupDone = true;
x.pendingInjuries = i === 1 ? 1 : 0;
x.name = ["You", "Full Name", "Other"][i];
});
await p.evaluate(
(s) => {
window.e = fuji.launch("#app");
window.sent = [];
e.on("chat:send", (m) => sent.push(m));
e.emit("player", { index: 0 });
e.emit("state", s);
e.emit("chat:state", { canSend: true, mentions: [{ id: "u1", name: "Full Name", playerIndex: 1 }] });
e.emit("chat:messages", [
{
_id: "000000000000000000000001",
author: "Full Name",
playerIndex: 1,
type: "text",
text: "Hi @You https://example.com",
segments: [
{ kind: "text", text: "Hi " },
{ kind: "mention", id: "u1", name: "Full Name" },
{ kind: "text", text: " — " },
{ kind: "link", url: "https://example.com", text: "Rules" },
{ kind: "text", text: " <script>alert(1)</script>" },
],
},
]);
},
stripSecret(s, 0)
);
await p.getByRole("textbox", { name: "Chat message" }).fill("@F");
await p.getByRole("textbox", { name: "Chat message" }).press("Enter");
assert.equal(await p.getByRole("textbox", { name: "Chat message" }).inputValue(), '@"Full Name" ');
await p.getByRole("textbox", { name: "Chat message" }).press("End");
await p.getByRole("textbox", { name: "Chat message" }).press("Enter");
assert.equal(await p.evaluate(() => sent[0].text), '@"Full Name"');
assert.equal(await p.getByRole("link", { name: "Rules", exact: true }).getAttribute("href"), "https://example.com");
assert.equal(await p.locator("article script").count(), 0);
assert.equal(await p.getByText(/Waiting for Full Name to choose an injury/).count(), 1);
assert.equal(await p.getByText(/Gatherer.*decide/).count(), 0);
assert.equal(await p.getByText("Scenario 7", { exact: true }).isVisible(), true);
assert.equal(await p.getByRole("button", { name: "Difficulty level 2: stamina costs" }).isVisible(), true);
assert.deepEqual(errors, []);
await p.close();
}
await browser.close();
console.log(
"Fuji desktop/mobile: mention autocomplete, plain send, rich safe rendering and injury waiting prompt passed."
);

View file

@ -6,7 +6,7 @@ try {
await page.goto("http://127.0.0.1:5187/");
await page.locator(".map").waitFor();
await page.locator(".equipment-chip").first().hover();
await page.locator(".equipment-preview").first().waitFor({ state: "visible" });
await page.locator(".equipment-chip + .equipment-preview").first().waitFor({ state: "visible" });
await page.screenshot({ path: "work/browser/fuji-equipment-preview.png", fullPage: true });
const result = await page.evaluate(
async (initial) => {