1
0
Fork 0

Compare commits

..

No commits in common. "528bf83f3077e4e693fc124e54e0f36c6df47f98" and "35bb0842c5e595022cdef3c01dc235aff2494e49" have entirely different histories.

9 changed files with 45 additions and 318 deletions

View file

@ -1,13 +1,5 @@
# Changelog
# v0.21.1
### Fixes
- Various bug fixes and improvements.
---
# v0.21.0
A conversation can now put a question to the whole unit, and the answer is tallied in one place for everyone.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.21.1",
"version": "0.21.0",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -23,7 +23,6 @@ import type { DialogueCondition, DialogueNode, FlowData } from "@/lib/npc-dialog
import { findStartNode, waitsForContinue } from "@/lib/npc-dialogue/dialogue";
import {
automaticTarget,
conditionBranches,
describeCondition,
isTerminal,
nodeForTarget,
@ -66,11 +65,8 @@ export function DialoguePreviewDialog({
const [gateErrors, setGateErrors] = useState<string | null>(null);
const [checking, setChecking] = useState(false);
/** Gate answers for conditional choices, keyed `<nodeId>:<index>`, so the
* preview can mark a choice the runtime would hide. */
* preview disables a choice the runtime would hide. */
const [choiceGates, setChoiceGates] = useState<Record<string, boolean>>({});
/** Steps taken against the author's own flags, reported in the footer so an
* override walk is never mistaken for what a player would see. */
const [overrides, setOverrides] = useState(0);
const reset = useCallback(() => {
setCurrentId(findStartNode(flow.nodes as DialogueNode[])?.id ?? null);
@ -78,7 +74,6 @@ export function DialoguePreviewDialog({
setTrail([]);
setGates({});
setGateErrors(null);
setOverrides(0);
}, [flow.nodes]);
// Reopening starts a fresh walk rather than resuming wherever it stopped.
@ -153,9 +148,8 @@ export function DialoguePreviewDialog({
const gateAnswer = node && node.id in gates ? gates[node.id] : null;
const auto = node ? automaticTarget(node, gateAnswer) : { target: null, waitingOnGate: false };
const go = (target: string | null, options: { override?: boolean } = {}) => {
const go = (target: string | null) => {
if (!target) return;
if (options.override) setOverrides((current) => current + 1);
setTrail((current) => (currentId ? [...current, currentId] : current));
setVisited((current) => (current.includes(target) ? current : [...current, target]));
setCurrentId(target);
@ -176,17 +170,11 @@ export function DialoguePreviewDialog({
const choiceAvailable = (index: number) => {
const choice = node?.data.choices?.[index];
if (!choice) return false;
// A spent `once` choice is bookkeeping, not a flag, so it stays unavailable.
if (choice.once === true && choice.target && visited.includes(choice.target)) return false;
return true;
};
/** True when the choice's own gate fails for this author. It stays clickable
* so the branch behind it can be walked anyway, and reads as an override. */
const choiceOverridesFlags = (index: number) => {
const choice = node?.data.choices?.[index];
if (!choice?.condition || !node) return false;
return choiceGates[`${node.id}:${index}`] === false;
if (!choice.condition) return true;
const answer = node ? choiceGates[`${node.id}:${index}`] : undefined;
// Not answered yet: keep it clickable rather than flashing disabled.
return answer === undefined ? true : answer;
};
return (
@ -284,8 +272,8 @@ export function DialoguePreviewDialog({
{gateErrors && <div className="text-red-300">{gateErrors}</div>}
{gateAnswer !== null && (
<div className="text-cyan-300">
{gateAnswer ? "true" : "false"} for you, so a player matching your flags takes
the {gateAnswer ? "true" : "false"} branch
{gateAnswer ? "true" : "false"} for you, so this draft continues{" "}
{gateAnswer ? "true" : "false"}
</div>
)}
</div>
@ -298,21 +286,15 @@ export function DialoguePreviewDialog({
)}
{step.choices.map((choice) => {
const available = choiceAvailable(choice.index);
const overriding = available && choiceOverridesFlags(choice.index);
const gateKnown = node
? choiceGates[`${node.id}:${choice.index}`]
: undefined;
return (
<button
key={choice.index}
type="button"
disabled={!choice.target || !available}
onClick={() => go(choice.target, { override: overriding })}
onClick={() => go(choice.target)}
className={`w-full cursor-pointer rounded-sm border px-2.5 py-1.5 text-left text-sm transition-colors disabled:cursor-not-allowed ${
choice.target && available
? overriding
? "border-amber-700/60 bg-amber-950/30 text-amber-100/90 hover:border-amber-500/70 hover:text-amber-50"
: "border-white/20 bg-black/40 text-white/85 hover:border-cyan-500/60 hover:text-white"
? "border-white/20 bg-black/40 text-white/85 hover:border-cyan-500/60 hover:text-white"
: "border-white/10 bg-black/20 text-white/35"
}`}
>
@ -323,11 +305,9 @@ export function DialoguePreviewDialog({
{choice.conditionNote && (
<span className="mt-0.5 block font-mono text-[9px] text-amber-200/70">
gate: {choice.conditionNote}
{gateKnown === undefined
? ""
: overriding
? " (fails for you, click to take it anyway)"
: " (passes for you)"}
{node && choiceGates[`${node.id}:${choice.index}`] === false
? " (hidden for you)"
: ""}
</span>
)}
{!choice.target && (
@ -346,48 +326,15 @@ export function DialoguePreviewDialog({
</div>
)}
{node.type === "condition" &&
gateAnswer !== null &&
(() => {
const branches = conditionBranches(node, gateAnswer);
if (!branches) return null;
return (
<div className="flex flex-col gap-1.5">
<button
type="button"
onClick={() => go(branches.actual.target)}
disabled={!branches.actual.target}
className="w-fit cursor-pointer rounded-sm border border-white/20 bg-black/40 px-2.5 py-1 text-xs text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white disabled:cursor-not-allowed disabled:opacity-40"
>
Continue down the {branches.actual.label} branch
<span className="ml-1.5 font-mono text-[9px] uppercase tracking-wider text-white/35">
your flags
</span>
</button>
<button
type="button"
onClick={() => go(branches.override.target, { override: true })}
disabled={!branches.override.target}
className="w-fit cursor-pointer rounded-sm border border-amber-700/60 bg-amber-950/30 px-2.5 py-1 text-xs text-amber-100/90 transition-colors hover:border-amber-500/70 hover:text-amber-50 disabled:cursor-not-allowed disabled:opacity-40"
>
Take the {branches.override.label} branch anyway
<span className="ml-1.5 font-mono text-[9px] uppercase tracking-wider text-amber-200/50">
override
</span>
</button>
{!branches.actual.target && (
<span className="font-mono text-[9px] uppercase tracking-wider text-red-300/80">
the {branches.actual.label} branch is not wired
</span>
)}
{!branches.override.target && (
<span className="font-mono text-[9px] uppercase tracking-wider text-red-300/80">
the {branches.override.label} branch is not wired either
</span>
)}
</div>
);
})()}
{node.type === "condition" && gateAnswer !== null && auto.target && (
<button
type="button"
onClick={() => go(auto.target)}
className="w-fit cursor-pointer rounded-sm border border-white/20 bg-black/40 px-2.5 py-1 text-xs text-white/80 transition-colors hover:border-cyan-500/60 hover:text-white"
>
Continue down the {gateAnswer ? "true" : "false"} branch
</button>
)}
{node.type !== "choice" && node.type !== "condition" && !isTerminal(node) && (
<div className="flex items-center gap-2">
@ -427,13 +374,8 @@ export function DialoguePreviewDialog({
<div className="border-t border-white/10 px-4 py-2 font-mono text-[9px] uppercase tracking-widest text-white/35">
{trail.length} step{trail.length === 1 ? "" : "s"} deep, {visited.length} card
{visited.length === 1 ? "" : "s"} visited
{overrides > 0 && (
<span className="text-amber-200/70">
, {overrides} override{overrides === 1 ? "" : "s"} against your flags
</span>
)}
. Text shows tokens as authored; the player sees them resolved.
{visited.length === 1 ? "" : "s"} visited. Text shows tokens as
authored; the player sees them resolved.
</div>
</div>
</div>

View file

@ -1,10 +1,8 @@
"use client";
import { memo, useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import { clampMenuPosition } from "@/lib/npc-dialogue/markupMenu";
/** Friendly color names offered by the color picker (mirrors DialogueText). */
const COLOR_CHOICES = [
@ -31,66 +29,6 @@ const COLOR_CHOICES = [
*/
const PREVIEW_DEBOUNCE_MS = 220;
/**
* The markup menu, portalled to the document body.
*
* The editor lives inside a Radix dialog, whose content carries a transform for
* its open animation. A transformed ancestor becomes the containing block for
* `position: fixed`, so a menu positioned at the cursor's viewport coordinates
* landed at those coordinates *inside the dialog* instead: off to one side, and
* widening the panel as it overflowed. Portalling detaches it from that ancestor.
*/
function MarkupMenu({
x,
y,
items,
onPick,
}: {
x: number;
y: number;
items: { label: string; run: () => void }[];
onPick: () => void;
}) {
if (typeof document === "undefined") return null;
// Pulled inside the viewport: a right-click near an edge would otherwise open
// a menu the author cannot reach.
const { left, top } = clampMenuPosition(x, y, {
width: window.innerWidth,
height: window.innerHeight,
});
return createPortal(
<div
role="menu"
// Above every admin layer: the dialog sits at 1300 and Payload's own
// overlays go as high as 9999, so a portalled menu below them would be
// painted underneath the panel it belongs to.
// `pointer-events-auto` is required: a Radix modal puts `pointer-events:
// none` on the body while it is open, and a portal to the body inherits it,
// which left the menu visible but unclickable.
className="pointer-events-auto fixed z-[10000] flex min-w-40 flex-col rounded border border-zinc-700 bg-zinc-900 py-1 text-white shadow-xl"
style={{ left, top }}
onMouseDown={(event) => event.stopPropagation()}
>
{items.map((item) => (
<button
key={item.label}
type="button"
onClick={() => {
item.run();
onPick();
}}
// `bg-transparent` is not redundant: the admin styles every button
// with a light surface, which painted pale blocks over this dark menu.
className="cursor-pointer border-0 bg-transparent px-3 py-1 text-left font-mono text-xs text-white/70 shadow-none hover:bg-zinc-800 hover:text-cyan-300"
>
{item.label}
</button>
))}
</div>,
document.body,
);
}
/** The rendered preview, memoised so an unchanged line never re-parses. */
const MarkupPreview = memo(function MarkupPreview({ text }: { text: string }) {
return (
@ -139,21 +77,16 @@ export function MarkupEditor({
return () => clearTimeout(timer);
}, [value, previewText]);
// Close the menu on an outside click, Escape, or anything that would move the
// box out from under it. Scroll is captured so the dialog's own scroller counts.
// Close the context menu on any outside click or Escape.
useEffect(() => {
if (!menu) return;
const close = () => setMenu(null);
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMenu(null);
window.addEventListener("mousedown", close);
window.addEventListener("keydown", onKey);
window.addEventListener("resize", close);
window.addEventListener("scroll", close, true);
return () => {
window.removeEventListener("mousedown", close);
window.removeEventListener("keydown", onKey);
window.removeEventListener("resize", close);
window.removeEventListener("scroll", close, true);
};
}, [menu]);
@ -273,7 +206,25 @@ export function MarkupEditor({
</div>
)}
{menu && (
<MarkupMenu x={menu.x} y={menu.y} items={menuItems} onPick={() => setMenu(null)} />
<div
className="fixed z-[120] flex min-w-40 flex-col rounded border border-zinc-700 bg-zinc-900 py-1 shadow-xl"
style={{ left: menu.x, top: menu.y }}
onMouseDown={(e) => e.stopPropagation()}
>
{menuItems.map((item) => (
<button
key={item.label}
type="button"
onClick={() => {
item.run();
setMenu(null);
}}
className="px-3 py-1 text-left font-mono text-xs text-white/70 hover:bg-zinc-800 hover:text-cyan-300"
>
{item.label}
</button>
))}
</div>
)}
</div>
);

View file

@ -302,12 +302,6 @@ Two traps specific to this component, both costs of rendering inside the admin:
editor's depth. It falls back to `contact <id>`, which is honest; do not try to
fetch the name here.
**Overrides.** A condition node offers both exits: the branch the author's own
flags take (labelled "your flags") and the other one ("override"). So can a
choice whose gate fails. `conditionBranches` in `preview.ts` is what pairs them,
and the footer counts overrides so an override walk is never mistaken for what a
player would see. A missing branch is shown as unwired rather than invented.
The panel is centred vertically and keeps a `trail` of the cards walked through:
`Back` pops it. `visited` is deliberately separate, so stepping back rewinds the
walk without un-spending a `once` choice the player already took.

View file

@ -1,44 +0,0 @@
/**
* Placement for the dialogue editor's markup menu.
*
* The menu is portalled to the document body (the edit dialog's transform would
* otherwise become the containing block for `position: fixed`), and it is placed
* at the pointer. That means a right-click near an edge would open it partly off
* screen, where the author cannot reach the last items, so the point is pulled
* back inside the viewport first.
*
* Pure and size-aware on purpose: the menu's own size is fixed by its contents,
* so there is nothing to measure after mounting.
*/
/** Roughly the menu's size: its widest label plus padding, and six rows. */
export const MENU_WIDTH = 176;
export const MENU_HEIGHT = 188;
/** Smallest gap kept between the menu and an edge. */
export const MENU_MARGIN = 8;
export interface MenuPoint {
left: number;
top: number;
}
/**
* The point to draw the menu at, given the pointer position and the viewport.
* Never negative: on a viewport smaller than the menu, the margin wins over the
* right and bottom clamps.
*/
export function clampMenuPosition(
x: number,
y: number,
viewport: { width: number; height: number },
): MenuPoint {
const left = Math.max(
MENU_MARGIN,
Math.min(x, viewport.width - MENU_WIDTH - MENU_MARGIN),
);
const top = Math.max(
MENU_MARGIN,
Math.min(y, viewport.height - MENU_HEIGHT - MENU_MARGIN),
);
return { left, top };
}

View file

@ -177,39 +177,6 @@ export function automaticTarget(
return { target: node.data.next?.target ?? null, waitingOnGate: false };
}
/** The two ways out of a condition node, for the preview's branching step. */
export interface ConditionBranches {
/** The branch a player with these flags would really take. */
readonly actual: { readonly label: "true" | "false"; readonly target: string | null };
/**
* The other branch. The preview offers it so an author can reach a path their
* own account cannot: a conversation gated on a flag they have not earned is
* otherwise untestable without granting themselves the flag for real.
*/
readonly override: { readonly label: "true" | "false"; readonly target: string | null };
}
/**
* Both branches of a condition node, labelled. `conditionPassed` is the real
* answer for this author, so `actual` is what the runtime would do and
* `override` is the walk the preview can take instead.
*/
export function conditionBranches(
node: DialogueNode,
conditionPassed: boolean,
): ConditionBranches | null {
if (node.type !== "condition") return null;
return conditionPassed
? {
actual: { label: "true", target: node.data.trueTarget ?? null },
override: { label: "false", target: node.data.falseTarget ?? null },
}
: {
actual: { label: "false", target: node.data.falseTarget ?? null },
override: { label: "true", target: node.data.trueTarget ?? null },
};
}
/** Node types the preview can continue through without the player picking. */
export function isTerminal(node: DialogueNode): boolean {
return node.type === "end";

View file

@ -1,39 +0,0 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import {
MENU_HEIGHT,
MENU_MARGIN,
MENU_WIDTH,
clampMenuPosition,
} from "@/lib/npc-dialogue/markupMenu";
const viewport = { width: 1500, height: 1000 };
describe("markup menu placement", () => {
it("sits exactly at the pointer away from the edges", () => {
expect(clampMenuPosition(750, 308, viewport)).toEqual({ left: 750, top: 308 });
});
it("pulls back from the right and bottom edges so every item stays reachable", () => {
const point = clampMenuPosition(1499, 999, viewport);
expect(point.left).toBe(viewport.width - MENU_WIDTH - MENU_MARGIN);
expect(point.top).toBe(viewport.height - MENU_HEIGHT - MENU_MARGIN);
expect(point.left + MENU_WIDTH).toBeLessThanOrEqual(viewport.width);
expect(point.top + MENU_HEIGHT).toBeLessThanOrEqual(viewport.height);
});
it("keeps the margin when the viewport is smaller than the menu", () => {
const small = { width: 120, height: 100 };
expect(clampMenuPosition(119, 99, small)).toEqual({
left: MENU_MARGIN,
top: MENU_MARGIN,
});
});
it("never returns a negative offset for a pointer outside the window", () => {
const point = clampMenuPosition(-40, -40, viewport);
expect(point.left).toBeGreaterThanOrEqual(MENU_MARGIN);
expect(point.top).toBeGreaterThanOrEqual(MENU_MARGIN);
});
});

View file

@ -4,7 +4,6 @@ import { describe, expect, it } from "vitest";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
import {
automaticTarget,
conditionBranches,
describeCondition,
isTerminal,
nodeForTarget,
@ -129,38 +128,3 @@ describe("draft preview reading the graph", () => {
expect(nodeForTarget(nodes, undefined)).toBeNull();
});
});
describe("condition branches in the preview", () => {
const gate = node({
id: "gate",
type: "condition",
data: { trueTarget: "yes", falseTarget: "no" },
});
it("labels the real branch and the override one", () => {
expect(conditionBranches(gate, true)).toEqual({
actual: { label: "true", target: "yes" },
override: { label: "false", target: "no" },
});
expect(conditionBranches(gate, false)).toEqual({
actual: { label: "false", target: "no" },
override: { label: "true", target: "yes" },
});
});
it("reports an unwired branch as no target instead of inventing one", () => {
const halfWired = node({
id: "half",
type: "condition",
data: { trueTarget: "yes" },
});
// The condition is false for this author, and only the true side is wired.
expect(conditionBranches(halfWired, false)?.actual.target).toBeNull();
expect(conditionBranches(halfWired, false)?.override.target).toBe("yes");
});
it("is null for a node that is not a condition", () => {
const line = node({ id: "line", type: "dialogue", data: { next: { target: "next" } } });
expect(conditionBranches(line, true)).toBeNull();
});
});