feat(npc-dialogue): mark contacts whose conversation has unread content
The only unread signal was the NEW badge inside a conversation, so players had no way to see who had something to say. The directory now carries that signal: a cyan NEW chip on the card for any contact whose offered conversation has a node this player has never read. Unread is derived from the per-node read markers that already existed. Two gates run first so the chip never lies: the contact must have canMessage true, and the loader resolves the offered conversation with the same selectDialogueForUser gate the contact page uses (testing conversations filtered by dialogueVisibleTo). Cost is two queries for the whole directory rather than one per card. A branch added after a player finished a conversation brings the chip back, which is the point; a partially explored conversation stays marked until every branch is read. Measured on the live directory: three contacts chipped (the two with canMessage and unread flows, plus a seeded probe on a third), the probe's chip cleared after all its nodes were read, and a canMessage:false contact never chipped. Pure derivation covered by 6 tests.
This commit is contained in:
parent
4bfa34a775
commit
4dc82c0d5d
6 changed files with 265 additions and 5 deletions
|
|
@ -4,6 +4,8 @@ import { headers as nextHeaders } from "next/headers";
|
||||||
import type { GameNpc } from "@/payload-types";
|
import type { GameNpc } from "@/payload-types";
|
||||||
import { UsersIcon } from "lucide-react";
|
import { UsersIcon } from "lucide-react";
|
||||||
import { NpcDirectory } from "@/components/frontend/personnel/NpcDirectory";
|
import { NpcDirectory } from "@/components/frontend/personnel/NpcDirectory";
|
||||||
|
import { loadUnreadNpcIds } from "@/lib/npc-dialogue/unread";
|
||||||
|
import { canSeeTestingDialogues } from "@/lib/npc-dialogue/visibility";
|
||||||
import { ClassificationStrip, CornerBrackets, DOSSIER } from "@/components/frontend/operations";
|
import { ClassificationStrip, CornerBrackets, DOSSIER } from "@/components/frontend/operations";
|
||||||
|
|
||||||
export const metadata = {
|
export const metadata = {
|
||||||
|
|
@ -24,6 +26,18 @@ export default async function ContactsPage() {
|
||||||
});
|
});
|
||||||
const npcs = npcsRes.docs as unknown as GameNpc[];
|
const npcs = npcsRes.docs as unknown as GameNpc[];
|
||||||
|
|
||||||
|
// Which contacts have conversation content this player has never opened. Two
|
||||||
|
// queries for the whole page, not one per card, and the same gates the offer
|
||||||
|
// uses: `canMessage` first, because a contact that cannot start a
|
||||||
|
// conversation should not advertise one, then the entry gate and testing
|
||||||
|
// flag inside the loader.
|
||||||
|
const canSeeTesting = await canSeeTestingDialogues(payload, user);
|
||||||
|
const unreadNpcIds = await loadUnreadNpcIds(payload, {
|
||||||
|
npcIds: npcs.filter((npc) => npc.canMessage === true).map((npc) => npc.id),
|
||||||
|
userId: user?.id ?? null,
|
||||||
|
canSeeTesting,
|
||||||
|
}).catch(() => []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-6 p-5">
|
<div className="flex flex-col gap-6 p-5">
|
||||||
<header className="group relative overflow-hidden rounded-none border border-border/70 bg-card">
|
<header className="group relative overflow-hidden rounded-none border border-border/70 bg-card">
|
||||||
|
|
@ -49,7 +63,7 @@ export default async function ContactsPage() {
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<NpcDirectory npcs={npcs} />
|
<NpcDirectory npcs={npcs} unreadNpcIds={unreadNpcIds} />
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,9 +9,11 @@ import { initialsOf } from "@/components/frontend/personnel/initials";
|
||||||
|
|
||||||
interface NpcCardProps {
|
interface NpcCardProps {
|
||||||
readonly npc: GameNpc;
|
readonly npc: GameNpc;
|
||||||
|
/** This contact offers conversation content the player has never read. */
|
||||||
|
readonly unread?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NpcCard({ npc }: NpcCardProps) {
|
export function NpcCard({ npc, unread = false }: NpcCardProps) {
|
||||||
const factionName =
|
const factionName =
|
||||||
typeof npc.faction === "object" && npc.faction !== null ? npc.faction.name : null;
|
typeof npc.faction === "object" && npc.faction !== null ? npc.faction.name : null;
|
||||||
const locationName =
|
const locationName =
|
||||||
|
|
@ -33,7 +35,7 @@ export function NpcCard({ npc }: NpcCardProps) {
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
href={`/personnel/contacts/${npc.id}`}
|
href={`/personnel/contacts/${npc.id}`}
|
||||||
aria-label={`Open contact ${npc.name}`}
|
aria-label={`Open contact ${npc.name}${unread ? ", unread conversation" : ""}`}
|
||||||
className="block rounded-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
className="block rounded-none focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
|
||||||
>
|
>
|
||||||
<article className="group relative flex aspect-[4/5] flex-col overflow-hidden rounded-none border border-border/70 bg-card transition-colors duration-300 hover:border-foreground/30 motion-reduce:transition-none">
|
<article className="group relative flex aspect-[4/5] flex-col overflow-hidden rounded-none border border-border/70 bg-card transition-colors duration-300 hover:border-foreground/30 motion-reduce:transition-none">
|
||||||
|
|
@ -41,6 +43,18 @@ export function NpcCard({ npc }: NpcCardProps) {
|
||||||
<ClassificationStrip left="Contact" right={`REF ${refCode}`} />
|
<ClassificationStrip left="Contact" right={`REF ${refCode}`} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* New conversation content. Positioned over the portrait rather than in
|
||||||
|
the readout footer, which is already three cells wide. */}
|
||||||
|
{unread && (
|
||||||
|
<span
|
||||||
|
aria-hidden="true"
|
||||||
|
className="absolute right-2 top-10 z-30 flex items-center gap-1 rounded-sm bg-cyan-400 px-1 py-0.5 font-mono text-[8px] font-bold uppercase leading-tight tracking-widest text-black shadow-[0_0_8px_rgba(34,211,238,0.55)]"
|
||||||
|
>
|
||||||
|
<span className="size-1 rounded-full bg-black/70" />
|
||||||
|
New
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||||
{imageUrl ? (
|
{imageUrl ? (
|
||||||
<img src={imageUrl} alt="" className="absolute inset-0 size-full object-cover" />
|
<img src={imageUrl} alt="" className="absolute inset-0 size-full object-cover" />
|
||||||
|
|
|
||||||
|
|
@ -12,9 +12,12 @@ import { DOSSIER, NoticeState } from "@/components/frontend/operations";
|
||||||
|
|
||||||
interface NpcDirectoryProps {
|
interface NpcDirectoryProps {
|
||||||
readonly npcs: GameNpc[];
|
readonly npcs: GameNpc[];
|
||||||
|
/** Contacts with conversation content this player has never read. */
|
||||||
|
readonly unreadNpcIds?: readonly number[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NpcDirectory({ npcs }: NpcDirectoryProps) {
|
export function NpcDirectory({ npcs, unreadNpcIds = [] }: NpcDirectoryProps) {
|
||||||
|
const unread = new Set(unreadNpcIds);
|
||||||
const [search, setSearch] = useState("");
|
const [search, setSearch] = useState("");
|
||||||
const [inGameOnly, setInGameOnly] = useState(false);
|
const [inGameOnly, setInGameOnly] = useState(false);
|
||||||
const [vendorsOnly, setVendorsOnly] = useState(false);
|
const [vendorsOnly, setVendorsOnly] = useState(false);
|
||||||
|
|
@ -117,7 +120,7 @@ export function NpcDirectory({ npcs }: NpcDirectoryProps) {
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||||
{filteredNpcs.map((npc) => (
|
{filteredNpcs.map((npc) => (
|
||||||
<NpcCard key={npc.id} npc={npc} />
|
<NpcCard key={npc.id} npc={npc} unread={unread.has(npc.id)} />
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
|
||||||
|
|
@ -272,6 +272,30 @@ state, keyed by log entry id, so only the line actually playing shows it). The
|
||||||
element reports progress and clears on `ended`; muting and closing clear it
|
element reports progress and clears on `ended`; muting and closing clear it
|
||||||
immediately.
|
immediately.
|
||||||
|
|
||||||
|
### Unread markers
|
||||||
|
|
||||||
|
A contact card shows a `NEW` chip when the conversation that would be offered has
|
||||||
|
a node with no read marker for this player (`src/lib/npc-dialogue/unread.ts`). The
|
||||||
|
read markers already existed for the in-conversation badge; this surfaces them
|
||||||
|
where they decide anything, on the directory.
|
||||||
|
|
||||||
|
Definition: any unread node in the offered flow counts, so a branch added after a
|
||||||
|
player finished a conversation brings the chip back. That is deliberate (the
|
||||||
|
content is new to them), but it means a partially explored conversation stays
|
||||||
|
marked until every branch is read. Do not "fix" that by only checking the start
|
||||||
|
node without asking, and do not check nodes that are no longer in the flow: stale
|
||||||
|
markers for deleted nodes are ignored.
|
||||||
|
|
||||||
|
Two gates come before the chip, matching the offer: callers pass only contacts with
|
||||||
|
`game-npcs.canMessage` true, and the loader runs the same `selectDialogueForUser`
|
||||||
|
gate the contact page runs, so a chip never advertises a conversation the entry
|
||||||
|
gate hides. `testing` conversations are filtered by `dialogueVisibleTo`.
|
||||||
|
|
||||||
|
Cost is two queries for the whole directory (conversations for the NPCs, read
|
||||||
|
markers for the offered ones), plus one flag evaluation per NPC that has a gated
|
||||||
|
conversation. The page swallows loader errors and renders no chips rather than
|
||||||
|
failing the directory.
|
||||||
|
|
||||||
### The conversation frame
|
### The conversation frame
|
||||||
|
|
||||||
The dialog is a **fixed-height frame** (`h-[min(80dvh,36rem)]`), not a box that
|
The dialog is a **fixed-height frame** (`h-[min(80dvh,36rem)]`), not a box that
|
||||||
|
|
|
||||||
154
src/lib/npc-dialogue/unread.ts
Normal file
154
src/lib/npc-dialogue/unread.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
||||||
|
/**
|
||||||
|
* Which contacts have conversation content this player has never read.
|
||||||
|
*
|
||||||
|
* The read markers `markNpcDialogueNodeRead` writes are per node id, and node
|
||||||
|
* ids live inside `flowData` JSON, so "unread" has to be derived rather than
|
||||||
|
* stored. A conversation counts as unread while any node it can offer has no
|
||||||
|
* marker for this player, which also covers a branch an author added later: the
|
||||||
|
* dot comes back rather than the conversation silently staying "read".
|
||||||
|
*
|
||||||
|
* The directory needs this for every contact at once, so the caller resolves
|
||||||
|
* *which* conversation would be offered (the same selector the offer uses) and
|
||||||
|
* this module answers the per-conversation question. Two queries total, not one
|
||||||
|
* per NPC.
|
||||||
|
*
|
||||||
|
* Server only, in the same sense as `visibility.ts`: the query helper takes a
|
||||||
|
* Payload instance.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { Payload } from "payload";
|
||||||
|
|
||||||
|
import { evaluateCondition } from "./flags";
|
||||||
|
import { gateCondition, selectDialogueForUser, type GateCandidate } from "./selection";
|
||||||
|
import { dialogueVisibleTo, type TestingAwareDialogue } from "./visibility";
|
||||||
|
|
||||||
|
/** Node ids in a stored flow, defensively: flowData is author JSON. */
|
||||||
|
export function dialogueNodeIds(flowData: unknown): string[] {
|
||||||
|
const nodes = (flowData as { nodes?: unknown } | null | undefined)?.nodes;
|
||||||
|
if (!Array.isArray(nodes)) return [];
|
||||||
|
const ids: string[] = [];
|
||||||
|
for (const node of nodes) {
|
||||||
|
const id = (node as { id?: unknown } | null | undefined)?.id;
|
||||||
|
if (typeof id === "string" && id.length > 0) ids.push(id);
|
||||||
|
}
|
||||||
|
return ids;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Node ids in `nodeIds` that this player has not read. */
|
||||||
|
export function unreadNodeIds(
|
||||||
|
nodeIds: readonly string[],
|
||||||
|
readIds: ReadonlySet<string>,
|
||||||
|
): string[] {
|
||||||
|
return nodeIds.filter((id) => !readIds.has(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether a conversation still has something this player has not read. */
|
||||||
|
export function isDialogueUnread(
|
||||||
|
nodeIds: readonly string[],
|
||||||
|
readIds: ReadonlySet<string>,
|
||||||
|
): boolean {
|
||||||
|
// An empty conversation cannot be read, so it cannot be unread either.
|
||||||
|
if (nodeIds.length === 0) return false;
|
||||||
|
return unreadNodeIds(nodeIds, readIds).length > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The part of a conversation doc this module needs. */
|
||||||
|
interface UnreadCandidate extends GateCandidate, TestingAwareDialogue {
|
||||||
|
id: number;
|
||||||
|
npc?: number | { id: number } | null;
|
||||||
|
flowData?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
function npcIdOf(value: UnreadCandidate["npc"]): number | null {
|
||||||
|
if (typeof value === "number") return value;
|
||||||
|
if (value && typeof value === "object" && "id" in value) {
|
||||||
|
const id = (value as { id: unknown }).id;
|
||||||
|
return typeof id === "number" ? id : null;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* NPC ids (from `npcIds`) whose offered conversation has unread nodes.
|
||||||
|
*
|
||||||
|
* Callers pass only contacts that may start a conversation at all
|
||||||
|
* (`game-npcs.canMessage`, the same switch the contact page checks before it
|
||||||
|
* offers Converse); a contact that cannot be talked to must not show a dot.
|
||||||
|
*
|
||||||
|
* The offered conversation is resolved exactly as the contact page resolves it
|
||||||
|
* (`selectDialogueForUser` against the player's flags), so the dot agrees with
|
||||||
|
* the Converse button rather than advertising a conversation the gate hides.
|
||||||
|
*/
|
||||||
|
export async function loadUnreadNpcIds(
|
||||||
|
payload: Payload,
|
||||||
|
options: {
|
||||||
|
npcIds: readonly number[];
|
||||||
|
userId?: number | null;
|
||||||
|
canSeeTesting: boolean;
|
||||||
|
},
|
||||||
|
): Promise<number[]> {
|
||||||
|
const { npcIds, userId, canSeeTesting } = options;
|
||||||
|
if (!userId || npcIds.length === 0) return [];
|
||||||
|
|
||||||
|
const dialogues = await payload.find({
|
||||||
|
collection: "npc-dialogues",
|
||||||
|
where: { npc: { in: [...npcIds] } },
|
||||||
|
limit: 400,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const candidates = (dialogues.docs as unknown as UnreadCandidate[]).filter((doc) =>
|
||||||
|
dialogueVisibleTo(doc, canSeeTesting),
|
||||||
|
);
|
||||||
|
if (candidates.length === 0) return [];
|
||||||
|
|
||||||
|
const byNpc = new Map<number, UnreadCandidate[]>();
|
||||||
|
for (const doc of candidates) {
|
||||||
|
const npcId = npcIdOf(doc.npc);
|
||||||
|
if (npcId === null) continue;
|
||||||
|
const list = byNpc.get(npcId) ?? [];
|
||||||
|
list.push(doc);
|
||||||
|
byNpc.set(npcId, list);
|
||||||
|
}
|
||||||
|
|
||||||
|
const offered = new Map<number, UnreadCandidate>();
|
||||||
|
for (const [npcId, docs] of byNpc) {
|
||||||
|
const chosen = await selectDialogueForUser(docs, async (condition) => {
|
||||||
|
return evaluateCondition(payload, userId, condition);
|
||||||
|
});
|
||||||
|
if (chosen) offered.set(npcId, chosen);
|
||||||
|
}
|
||||||
|
if (offered.size === 0) return [];
|
||||||
|
|
||||||
|
const states = await payload.find({
|
||||||
|
collection: "npc-dialogue-states",
|
||||||
|
where: {
|
||||||
|
user: { equals: userId },
|
||||||
|
dialogue: { in: [...offered.values()].map((doc) => doc.id) },
|
||||||
|
},
|
||||||
|
limit: 2000,
|
||||||
|
depth: 0,
|
||||||
|
pagination: false,
|
||||||
|
overrideAccess: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const readByDialogue = new Map<number, Set<string>>();
|
||||||
|
for (const state of states.docs as unknown as { dialogue?: unknown; nodeId?: unknown }[]) {
|
||||||
|
const dialogue =
|
||||||
|
typeof state.dialogue === "number"
|
||||||
|
? state.dialogue
|
||||||
|
: (state.dialogue as { id?: unknown } | null)?.id;
|
||||||
|
if (typeof dialogue !== "number" || typeof state.nodeId !== "string") continue;
|
||||||
|
const set = readByDialogue.get(dialogue) ?? new Set<string>();
|
||||||
|
set.add(state.nodeId);
|
||||||
|
readByDialogue.set(dialogue, set);
|
||||||
|
}
|
||||||
|
|
||||||
|
const unread: number[] = [];
|
||||||
|
for (const [npcId, doc] of offered) {
|
||||||
|
const readIds = readByDialogue.get(doc.id) ?? new Set<string>();
|
||||||
|
if (isDialogueUnread(dialogueNodeIds(doc.flowData), readIds)) unread.push(npcId);
|
||||||
|
}
|
||||||
|
return unread;
|
||||||
|
}
|
||||||
51
tests/int/npc-dialogue-unread.int.spec.ts
Normal file
51
tests/int/npc-dialogue-unread.int.spec.ts
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
// @vitest-environment node
|
||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
|
||||||
|
import { dialogueNodeIds, isDialogueUnread, unreadNodeIds } from "@/lib/npc-dialogue/unread";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Unread" is derived from per-node read markers inside flowData JSON. These
|
||||||
|
* cover the shapes an author's canvas can actually produce, including a
|
||||||
|
* half-written flow, since the directory reads every conversation's flow.
|
||||||
|
*/
|
||||||
|
describe("conversation unread derivation", () => {
|
||||||
|
it("reads node ids out of a stored flow", () => {
|
||||||
|
const flow = {
|
||||||
|
nodes: [{ id: "n1" }, { id: "n2" }, { id: "" }, { notAnId: true }, null],
|
||||||
|
edges: [],
|
||||||
|
};
|
||||||
|
expect(dialogueNodeIds(flow)).toEqual(["n1", "n2"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("treats a missing or broken flow as having no nodes", () => {
|
||||||
|
expect(dialogueNodeIds(null)).toEqual([]);
|
||||||
|
expect(dialogueNodeIds(undefined)).toEqual([]);
|
||||||
|
expect(dialogueNodeIds({})).toEqual([]);
|
||||||
|
expect(dialogueNodeIds({ nodes: "nope" })).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("reports the nodes this player has not read", () => {
|
||||||
|
const nodeIds = ["n1", "n2", "n3"];
|
||||||
|
expect(unreadNodeIds(nodeIds, new Set(["n1", "n3"]))).toEqual(["n2"]);
|
||||||
|
expect(unreadNodeIds(nodeIds, new Set(["n1", "n2", "n3"]))).toEqual([]);
|
||||||
|
expect(unreadNodeIds(nodeIds, new Set())).toEqual(["n1", "n2", "n3"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is unread while any node is unread, and clean once all are", () => {
|
||||||
|
const nodeIds = ["n1", "n2"];
|
||||||
|
expect(isDialogueUnread(nodeIds, new Set(["n1"]))).toBe(true);
|
||||||
|
expect(isDialogueUnread(nodeIds, new Set(["n1", "n2"]))).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("never calls an empty conversation unread", () => {
|
||||||
|
expect(isDialogueUnread([], new Set())).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("counts read markers for nodes that no longer exist as harmless", () => {
|
||||||
|
// An author deleted a branch after the player read it. The stale marker
|
||||||
|
// must not make the conversation look read, and must not make it look
|
||||||
|
// unread either: only node ids still in the flow are considered.
|
||||||
|
expect(isDialogueUnread(["n1"], new Set(["deleted-node"]))).toBe(true);
|
||||||
|
expect(isDialogueUnread(["n1"], new Set(["n1", "deleted-node"]))).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue