1
0
Fork 0

Compare commits

...

7 commits

Author SHA1 Message Date
de60e5d3e0 v0.16.0 - add faction relations ledger and relations overview, fix rich text and wiki editor rendering 2026-11-18 14:15:00 -05:00
b3bf5c8a46 docs: add v0.16.0 changelog entry 2026-11-18 14:14:31 -05:00
9e6cd55fe6 refactor(intelligence): drop the factions.relationships array in favour of the ledger
Nothing stores a pairwise score on a faction any more, so remove the array
field, its admin UI and the masking line that blanked it for undiscovered
factions. The disposal-mask doc comment now points at the ledger, which
applies the same rule by filtering entries that name an undiscovered faction.

The second migration converts every non-zero legacy value into an
opening-balance entry (custom delta, dated at the owning faction's last update
so it does not read as a fresh event, legacy note preserved) and then drops
the table. Zero rows are skipped because a stored 0 and no entries mean the
same thing.

Two integration specs that created or asserted `relationships` now use the
ledger instead.
2026-11-18 14:13:29 -05:00
cb06ba79c0 feat(intelligence): show derived faction relations on the faction and relations pages
The faction dossier's Relationships block only ever showed one direction, and
only the directions someone had bothered to type by hand.

Read both directions from the ledger instead: each row now carries "they see
us" and "we see them" meters, and a Recent Developments list under them spells
out the events behind those numbers in plain language. Hidden entries move the
meters without appearing in that list.

Add /intelligence/factions/relations, a full cross-table of every faction
against every other, player faction first, with the existing band labels as a
legend. Rows and headers link back to dossiers, and the table scrolls sideways
rather than truncating scores. A Relations entry in the Intelligence sidebar
points at it.
2026-11-18 14:13:20 -05:00
2384c7f5a4 feat(intelligence): add the faction relation ledger collection and score math
Pairwise faction attitudes were hand-typed into a per-faction array, so the
two directions of one relationship lived in different documents and could
disagree with each other.

Add `faction-relation-entries`: one row per event that moved one faction's
attitude toward another, with the score computed on read instead of stored.
Entries are directed by default with a mutual flag for shared events; severity
tiers set the delta with a custom override; decaying entries halve per
half-life (new GameRules knob, 30 days default) while lasting shifts never
fade; voiding retires an entry with a stamped reason instead of deleting it;
hidden entries still move the score but never explain it to players.

`factionRelations.ts` holds the pure math (severity presets, decay, directed
and mutual scores, bands), and `factionRelationLedger.ts` is the single read
path so the voided, hidden and undiscovered-faction rules exist in one place.
Reads run as the caller, never with `overrideAccess`; GM notes are gated by
field read access, and hidden rows are censored by an `afterRead` hook.

Includes the permission group, the `admin:faction-relation-entries:manage`
page gate, the integration spec, and the migration that creates the table and
its enums.
2026-11-18 14:13:20 -05:00
e15b0923ad fix(wiki): align highlight overlay and textarea wrapping so caret/click match painted text
The markdown overlay shared the wrapper's inset-0 box with the transparent-text
textarea, but its inner div added a 1px transparent border while the textarea is
border-0, shrinking its text width by ~2px; Firefox/Safari classic scrollbars
reserve another ~15px inside the scrolled textarea that the overflow-hidden
overlay never sees. Either gutter makes long unbreakable tokens (e.g. image
markdown URLs) wrap differently between the two layers, so the overlay text
drifts vertically under the caret/click math and editing feels like it's one or
more lines off right after inserting an image.

Compose both layers' classes from a shared WIKI_EDITOR_METRICS constant, drop
the overlay border, hide the textarea scrollbar so its content width matches the
overlay in every browser, and lock class parity with a jsdom RTL spec.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-11-18 13:56:10 -05:00
34c0d5681f fix(rich-text): render full lexical formatting incl. colours across all fields
RichText authored in the admin panel was rendered as plain text on the
public site: headings/lists/quotes were flattened by Tailwind preflight
(no @tailwindcss/typography installed), and Payload's default JSX
converter ignored text colours.

- src/lib/lexical: shared editor factory (ptfLexicalEditor) + shared
  colour palette (textState) + colour converter (richTextConverters)
- RichTextView: canonical .lexical-content renderer (colour-aware),
  swapped into every frontend render site
- All rich-text editors route through the factory, so every field
  inherits the coloured editor (incl. the previously-unedited ones)
- .lexical-content CSS extended with checklist/table/heading rules,
  wrapped in @layer components so per-page utilities still override;
  dropped the now-dead per-page prose hacks
- Remove the now-dead briefingConverters in favour of the shared
  converter; add tests/int/rich-text-view.int.spec.ts
2026-11-18 13:10:26 -05:00
62 changed files with 95505 additions and 408 deletions

View file

@ -1,5 +1,22 @@
# Changelog
# v0.16.0
Faction attitudes now build up from what actually happened between them, and you can see the whole web of relations at a glance.
### Features
- **Faction relations.** A faction dossier now shows how each side regards the other, so a faction that resents the unit while the unit holds no grudge reads as exactly that. Under the numbers, recent developments explain what moved them, newest first.
- **Relations overview.** A new Relations page in Intelligence lays every faction against every other in one table, colour-coded from allied down to hostile. Each row reads across: what that faction currently thinks of each column.
### Fixes
- Rich text now shows all of its formatting, including colours, everywhere it appears.
- Wiki editor highlighting lines up with the text, so clicking and the caret land where they look like they should.
- Various bug fixes and improvements.
---
# v0.15.3
Wiki articles can now be saved as drafts, visible only to their author until they are published.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.15.3",
"version": "0.16.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

@ -4,7 +4,7 @@ import { notFound } from "next/navigation";
import Link from "next/link";
import { headers as nextHeaders } from "next/headers";
import type { Faction, Media, Mission } from "@/payload-types";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { ClientDate } from "@/components/frontend/ClientDate";
import {
ArrowLeftIcon,
@ -217,8 +217,8 @@ export default async function CampaignDetailPage({ params }: CampaignDetailPageP
<ItemHeader>
<ItemTitle>Description</ItemTitle>
</ItemHeader>
<ItemContent className="prose-invert prose-sm max-w-none [&_p]:mb-2 [&_ul]:list-disc [&_ul]:ml-4 [&_ol]:list-decimal [&_ol]:ml-4 [&_strong]:text-foreground [&_em]:italic">
<RichText data={campaign.description} />
<ItemContent>
<RichTextView data={campaign.description} />
</ItemContent>
</Item>
)}

View file

@ -4,7 +4,7 @@ import { notFound } from "next/navigation";
import Link from "next/link";
import { headers as nextHeaders } from "next/headers";
import type { BankAccount, Campaign, Faction, Media, Mission } from "@/payload-types";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import {
ArrowLeftIcon,
@ -23,6 +23,14 @@ import {
canViewUndiscoveredFactions,
UNDISCOVERED_FACTION_SUMMARY,
} from "@/lib/intelligence/factionDiscovery";
import {
formatScore,
pairKey,
relationBand,
relationCategoryLabel,
RELATION_BAND_CLASSES,
} from "@/lib/intelligence/factionRelations";
import { getRelationContext, historyFor } from "@/lib/intelligence/factionRelationLedger";
interface FactionDetailPageProps {
params: Promise<{ id: string }>;
@ -67,13 +75,41 @@ function reputationLabel(rep: number): string {
}
function relationshipTone(value: number): { bar: string; text: string; label: string } {
// 50..100 allied (green), 20..49 friendly (green-soft), -19..20 neutral, -20..-49 tense, -50..-100 hostile
if (value >= 50) return { bar: "bg-emerald-500", text: "text-emerald-400", label: "Allied" };
if (value >= 20) return { bar: "bg-green-500", text: "text-green-400", label: "Friendly" };
if (value > -20)
return { bar: "bg-muted-foreground", text: "text-muted-foreground", label: "Neutral" };
if (value > -50) return { bar: "bg-amber-500", text: "text-amber-400", label: "Tense" };
return { bar: "bg-red-500", text: "text-red-400", label: "Hostile" };
const band = relationBand(value);
const classes = RELATION_BAND_CLASSES[band.key];
return { bar: classes.bar, text: classes.text, label: band.label };
}
/** One labelled bar for a single direction of a relationship. */
function RelationMeter({ label, value }: { label: string; value: number }) {
const tone = relationshipTone(value);
const width = Math.min(Math.abs(value), 100) / 2;
return (
<div className="flex flex-col gap-1">
<div className="flex items-center justify-between gap-2 text-xs">
<span className="text-muted-foreground">{label}</span>
<span className={`font-mono ${tone.text}`}>
{formatScore(value)} · {tone.label}
</span>
</div>
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
<div
className={`absolute top-0 h-full ${tone.bar}`}
style={{ left: value < 0 ? "50%" : `${50 - width}%`, width: `${width}%` }}
/>
<div className="absolute left-1/2 top-0 h-full w-px bg-border" />
</div>
</div>
);
}
function formatOccurred(value: string): string {
return new Date(value).toLocaleDateString("en-US", {
month: "short",
day: "numeric",
year: "numeric",
timeZone: "UTC",
});
}
export default async function FactionDetailPage({ params }: FactionDetailPageProps) {
@ -171,12 +207,37 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
(c): c is Campaign => typeof c === "object" && c !== null,
) ?? []);
// Relationships (targetFaction populated at depth 2)
const relationships = redacted
? []
: (faction.relationships ?? []).filter(
(r) => typeof r.targetFaction === "object" && r.targetFaction !== null,
);
// Relationships are computed from the relation ledger, never stored on the
// faction. Redacted readers get nothing at all (the classified stub below
// renders instead), so the ledger is never queried for them.
const relations = redacted ? null : await getRelationContext(payload, user);
const relationRows = relations
? relations.factions
.filter((other) => other.id !== faction.id)
.map((other) => ({
faction: other,
inbound: relations.scores.get(pairKey(other.id, faction.id)) ?? 0,
outbound: relations.scores.get(pairKey(faction.id, other.id)) ?? 0,
hasRecords: relations.rows.some(
(row) =>
(row.subjectId === other.id && row.targetId === faction.id) ||
(row.subjectId === faction.id && row.targetId === other.id),
),
}))
.filter((entry) => entry.inbound !== 0 || entry.outbound !== 0 || entry.hasRecords)
: [];
// Player-facing timeline: every live entry touching this faction, newest
// first. A mutual entry appears once.
const developments = (() => {
if (!relations) return [];
const { inbound, outbound } = historyFor(relations, faction.id);
return [...inbound, ...outbound]
.filter((row, index, all) => all.findIndex((candidate) => candidate.id === row.id) === index)
.sort((a, b) => new Date(b.occurredAt).getTime() - new Date(a.occurredAt).getTime())
.slice(0, 8);
})();
return (
<div className="flex flex-col">
@ -280,62 +341,82 @@ export default async function FactionDetailPage({ params }: FactionDetailPagePro
<ItemHeader>
<ItemTitle>Description</ItemTitle>
</ItemHeader>
<ItemContent className="prose-invert prose-sm max-w-none [&_p]:mb-2 [&_ul]:list-disc [&_ul]:ml-4 [&_ol]:list-decimal [&_ol]:ml-4 [&_strong]:text-foreground [&_em]:italic">
<RichText data={faction.description} />
<ItemContent>
<RichTextView data={faction.description} />
</ItemContent>
</Item>
)}
{relationships.length > 0 && (
{relationRows.length > 0 && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScaleIcon className="size-4 text-muted-foreground" />
<ItemTitle>Relationships</ItemTitle>
</div>
<Link
href="/intelligence/factions/relations"
className="py-1 text-xs text-muted-foreground transition-colors hover:text-primary"
>
All relations
</Link>
</ItemHeader>
<ItemContent>
<div className="flex flex-col gap-3">
{relationships.map((r) => {
const target = r.targetFaction as Faction;
const value = r.value;
const tone = relationshipTone(value);
const barWidth = Math.min(Math.abs(value), 100);
return (
{relationRows.map(({ faction: other, inbound, outbound }) => (
<div
key={other.id}
className="flex flex-col gap-2 rounded-md border border-border/50 p-3"
>
<Link
key={r.id ?? target.id}
href={`/intelligence/factions/${target.id}`}
className="flex flex-col gap-1 rounded-md border border-border/50 p-3 transition-colors hover:border-primary/40 hover:bg-muted/30"
href={`/intelligence/factions/${other.id}`}
className="flex w-fit items-center gap-2 py-1 text-sm font-medium transition-colors hover:text-primary"
>
<div className="flex items-center justify-between gap-2">
<Link
href={`/intelligence/factions/${target.id}`}
className="flex items-center gap-2 py-1 text-sm font-medium hover:text-primary transition-colors"
>
<ShieldIcon className="size-4 text-muted-foreground" />
<span>{target.name}</span>
</Link>
<span className={`text-xs font-mono ${tone.text}`}>
{value >= 0 ? `+${value}` : value} · {tone.label}
<ShieldIcon className="size-4 text-muted-foreground" />
<span>{other.name}</span>
</Link>
<div className="grid grid-cols-1 gap-2 sm:grid-cols-2">
<RelationMeter label="They see us" value={inbound} />
<RelationMeter label="We see them" value={outbound} />
</div>
</div>
))}
</div>
</ItemContent>
</Item>
)}
{developments.length > 0 && (
<Item variant="outline">
<ItemHeader>
<div className="flex items-center gap-2">
<ScaleIcon className="size-4 text-muted-foreground" />
<ItemTitle>Recent Developments</ItemTitle>
</div>
</ItemHeader>
<ItemContent>
<ul className="divide-y divide-border/50">
{developments.map((row) => {
const tone = relationshipTone(row.delta);
return (
<li
key={row.id}
className="flex flex-col gap-1 py-2 first:pt-0 last:pb-0"
>
<div className="flex items-center justify-between gap-2 text-xs">
<span className="text-muted-foreground">
{formatOccurred(row.occurredAt)} ·{" "}
{relationCategoryLabel(row.category)}
</span>
<span className={`shrink-0 font-mono ${tone.text}`}>
{formatScore(row.delta)}
</span>
</div>
<div className="relative h-1.5 w-full overflow-hidden rounded-full bg-muted">
<div
className={`absolute top-0 h-full ${tone.bar}`}
style={{
left: value < 0 ? "50%" : `${50 - barWidth / 2}%`,
width: `${barWidth / 2}%`,
}}
/>
<div className="absolute left-1/2 top-0 h-full w-px bg-border" />
</div>
{r.notes && (
<p className="text-xs text-muted-foreground mt-1">{r.notes}</p>
)}
</Link>
<p className="text-sm">{row.summary}</p>
</li>
);
})}
</div>
</ul>
</ItemContent>
</Item>
)}

View file

@ -0,0 +1,160 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import Link from "next/link";
import { ArrowLeftIcon, ScaleIcon } from "lucide-react";
import { getRelationContext } from "@/lib/intelligence/factionRelationLedger";
import {
formatScore,
pairKey,
relationBand,
RELATION_BANDS,
RELATION_BAND_CLASSES,
} from "@/lib/intelligence/factionRelations";
export const metadata = {
title: "Faction Relations | Polaris Task Force",
};
const TYPE_ORDER: Record<string, number> = {
playerFaction: 0,
majorFaction: 1,
minorFaction: 2,
corporation: 3,
special: 4,
};
export default async function FactionRelationsPage() {
const payload = await getPayload({ config });
const { user } = await payload.auth({
headers: await nextHeaders(),
canSetHeaders: false,
});
const context = await getRelationContext(payload, user);
// Player faction first, then majors down to specials, so the matrix reads in
// the same order the faction list uses.
const factions = [...context.factions].sort(
(a, b) => (TYPE_ORDER[a.type] ?? 99) - (TYPE_ORDER[b.type] ?? 99),
);
return (
<div className="p-5 flex flex-col gap-6 max-w-[96rem] mx-auto w-full">
<div className="flex flex-col gap-1">
<Link
href="/intelligence/factions"
className="flex w-fit items-center gap-1 py-1 text-sm text-muted-foreground transition-colors hover:text-primary"
>
<ArrowLeftIcon className="size-3" />
Back to Factions
</Link>
<div className="flex items-center gap-2">
<ScaleIcon className="size-5 text-muted-foreground" />
<h1 className="text-lg font-semibold">Faction Relations</h1>
</div>
<p className="text-sm text-muted-foreground">
Each row reads how that faction currently regards each column, accumulated from recorded
events. The two directions of a relationship are independent, so one faction can respect
another that despises it.
</p>
</div>
<div className="flex flex-wrap items-center gap-3 text-xs text-muted-foreground">
<span className="uppercase tracking-wider">Scale</span>
{RELATION_BANDS.map((band) => (
<span key={band.key} className="flex items-center gap-1.5">
<span
className={`inline-block size-2 rounded-full ${RELATION_BAND_CLASSES[band.key].bar}`}
aria-hidden
/>
<span>{band.label}</span>
</span>
))}
</div>
{factions.length === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-muted-foreground">
<p className="text-sm">No factions found.</p>
</div>
) : (
<div className="overflow-x-auto rounded-lg border border-border">
<table className="w-full min-w-[720px] border-collapse text-sm">
<thead>
<tr className="border-b border-border">
<th className="sticky left-0 z-10 bg-card px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-muted-foreground">
Regards
</th>
{factions.map((faction) => (
<th
key={faction.id}
scope="col"
className="px-3 py-3 text-center text-xs font-medium uppercase tracking-wider text-muted-foreground"
>
<Link
href={`/intelligence/factions/${faction.id}`}
className="mx-auto block max-w-[9rem] truncate transition-colors hover:text-primary"
title={faction.name}
>
{faction.name}
</Link>
</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-border">
{factions.map((subject) => (
<tr key={subject.id}>
<th
scope="row"
className="sticky left-0 z-10 bg-card px-4 py-3 text-left font-medium"
>
<Link
href={`/intelligence/factions/${subject.id}`}
className="block max-w-[14rem] truncate transition-colors hover:text-primary"
title={subject.name}
>
{subject.name}
</Link>
</th>
{factions.map((target) => {
if (target.id === subject.id) {
return (
<td
key={target.id}
className="px-3 py-3 text-center text-muted-foreground/40"
>
<span aria-label="not applicable">-</span>
</td>
);
}
const score = context.scores.get(pairKey(subject.id, target.id)) ?? 0;
const band = relationBand(score);
return (
<td
key={target.id}
className="px-3 py-3 text-center"
title={`${subject.name} toward ${target.name}: ${band.label}`}
>
<span
className={`font-mono tabular-nums ${score === 0 ? "text-muted-foreground" : RELATION_BAND_CLASSES[band.key].text}`}
>
{formatScore(score)}
</span>
</td>
);
})}
</tr>
))}
</tbody>
</table>
</div>
)}
<p className="text-xs text-muted-foreground">
Entries are recorded from the admin panel under Intelligence, Relation Entries. Scores are
clamped to -100..100, and a zero can mean a clean slate or events that cancelled out.
</p>
</div>
);
}

View file

@ -3,7 +3,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import Link from "next/link";
import { notFound } from "next/navigation";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { ArrowLeftIcon } from "lucide-react";
import type { Journal, Mission, User } from "@/payload-types";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
@ -138,7 +138,7 @@ export default async function JournalDetailPage({
<ChronicleArticle kind="journal" articleId={String(journal.id)}>
<article className={cn("mt-8", BEAT_BODY_CLASSES)}>
<RichText data={journal.body} />
<RichTextView data={journal.body} />
</article>
</ChronicleArticle>
</div>

View file

@ -3,7 +3,7 @@ import { getPayload } from "payload";
import { notFound } from "next/navigation";
import Link from "next/link";
import type { Asset, Structure } from "@/payload-types";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import {
ArrowLeftIcon,
@ -145,8 +145,8 @@ export default async function ResourceDetailPage({ params }: ResourceDetailPageP
<ItemHeader>
<ItemTitle>Description</ItemTitle>
</ItemHeader>
<ItemContent className="prose-invert prose-sm max-w-none [&_p]:mb-2 [&_ul]:list-disc [&_ul]:ml-4 [&_ol]:list-decimal [&_ol]:ml-4 [&_strong]:text-foreground [&_em]:italic">
<RichText data={resource.description} />
<ItemContent>
<RichTextView data={resource.description} />
</ItemContent>
</Item>
)}

View file

@ -1,6 +1,6 @@
import { getPayload, type Payload } from "payload";
import type { Faction, GameStructure, Structure } from "@/payload-types";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import type { RichTextData } from "@/components/frontend/RichTextView";
import { calculateStoredMass, calculateUtilization, getGridSlots } from "@/lib/logistics";
import type { LaborClassificationOption, StructureStaffingOption } from "@/lib/base";
import { effectiveCrew } from "@/lib/base/constructionSpeed";
@ -12,7 +12,8 @@ import { isSuperuser } from "@/utils/access-control/hasPermission";
export interface StructureDetailData {
structure: DetailStructure;
blueprint: Structure;
description: string | null;
/** Serialized Lexical from the structures catalog entry; render via RichTextView. */
description: RichTextData | null;
imageUrl: string | null;
derived: {
currentMass: number;
@ -102,9 +103,7 @@ export async function fetchStructureDetail(
moduleEffects.capacityMass,
);
const gridSlots = getGridSlots(structureType, moduleEffects.storageSlots);
const description = structureType.description
? convertLexicalToPlaintext({ data: structureType.description })
: null;
const description = (structureType.description ?? null) as RichTextData | null;
const image =
typeof structureType.image === "object" && structureType.image !== null

View file

@ -4,7 +4,7 @@ import { notFound } from "next/navigation";
import { headers as nextHeaders } from "next/headers";
import Link from "next/link";
import { Faction, GameStructure, Resource, Structure } from "@/payload-types";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import { RichTextView } from "@/components/frontend/RichTextView";
import { CapacityBar } from "@/components/frontend/storage/CapacityBar";
import { StorageRules } from "@/components/frontend/storage/StorageRules";
import { StructureStorageView } from "@/components/frontend/storage/StructureStorageView";
@ -107,9 +107,6 @@ export default async function StructureDetailPage({ params }: StructureDetailPag
);
const gridSlots = getGridSlots(structureType, moduleEffects.storageSlots);
const functionLabel = getFunctionTypeLabel(structureType.functionType);
const description = structureType.description
? convertLexicalToPlaintext({ data: structureType.description })
: null;
const image =
typeof structureType.image === "object" && structureType.image !== null
@ -403,7 +400,9 @@ export default async function StructureDetailPage({ params }: StructureDetailPag
</div>
</header>
{description && <p className="text-sm text-muted-foreground">{description}</p>}
{structureType.description ? (
<RichTextView data={structureType.description} className="text-sm text-muted-foreground" />
) : null}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<Item variant="outline">

View file

@ -3,7 +3,7 @@ import { getPayload } from "payload";
import { notFound } from "next/navigation";
import Link from "next/link";
import type { Resource, Structure, Technology } from "@/payload-types";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import { categoryLabel, categoryPillClasses } from "@/lib/vehicles/categories";
import {
@ -111,8 +111,8 @@ export default async function VehicleDetailPage({ params }: VehicleDetailPagePro
<ItemHeader>
<ItemTitle>Description</ItemTitle>
</ItemHeader>
<ItemContent className="prose-invert prose-sm max-w-none [&_p]:mb-2 [&_ul]:list-disc [&_ul]:ml-4 [&_ol]:list-decimal [&_ol]:ml-4 [&_strong]:text-foreground [&_em]:italic">
<RichText data={vehicle.description} />
<ItemContent>
<RichTextView data={vehicle.description} />
</ItemContent>
</Item>
)}

View file

@ -1,7 +1,7 @@
import config from "@payload-config";
import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import type { StoryBeat, StoryBeatState, StoryVoiceover } from "@/payload-types";
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
import hasRoles from "@/utils/access-control/hasRoles";
@ -185,7 +185,7 @@ export default async function StoryPage() {
</div>
)}
<div className="mt-4">
<RichText data={beat.body} className={cn(BEAT_BODY_CLASSES)} />
<RichTextView data={beat.body} className={cn(BEAT_BODY_CLASSES)} />
</div>
{!isDraft && (
<BeatReactions

View file

@ -695,124 +695,211 @@
outline: 1px solid color-mix(in oklch, var(--color-primary) 45%, transparent);
}
/* Lexical rich-text typography (scoped to .lexical-content); Tailwind preflight resets headings */
.lexical-content {
font-size: 0.875rem;
line-height: 1.7;
color: var(--color-muted-foreground);
}
/* Lexical rich-text typography (scoped to .lexical-content); Tailwind preflight resets
element defaults, so this is the shared front-end style for serialized Lexical content.
Render every rich text through <RichTextView>, which applies this class plus the saved
text-colour converter; hand-wrapped .lexical-content divs remain supported. */
.lexical-content > :first-child {
margin-top: 0;
}
@layer components {
.lexical-content {
font-size: 0.875rem;
line-height: 1.7;
}
.lexical-content > :last-child {
margin-bottom: 0;
}
.lexical-content > :first-child {
margin-top: 0;
}
.lexical-content h1,
.lexical-content h2,
.lexical-content h3,
.lexical-content h4 {
font-weight: 600;
line-height: 1.3;
color: var(--color-foreground);
}
.lexical-content > :last-child {
margin-bottom: 0;
}
.lexical-content h1 {
font-size: 1.25rem;
margin: 1.25rem 0 0.5rem;
}
.lexical-content h1,
.lexical-content h2,
.lexical-content h3,
.lexical-content h4 {
font-weight: 600;
line-height: 1.3;
color: var(--color-foreground);
}
.lexical-content h2 {
font-size: 1.125rem;
margin: 1.125rem 0 0.4375rem;
}
.lexical-content h1 {
font-size: 1.25rem;
margin: 1.25rem 0 0.5rem;
}
.lexical-content h3 {
font-size: 1rem;
margin: 1rem 0 0.375rem;
}
.lexical-content h2 {
font-size: 1.125rem;
margin: 1.125rem 0 0.4375rem;
}
.lexical-content h4 {
font-size: 0.9375rem;
margin: 0.875rem 0 0.25rem;
}
.lexical-content h3 {
font-size: 1rem;
margin: 1rem 0 0.375rem;
}
.lexical-content p {
margin: 0.5rem 0;
}
.lexical-content h4 {
font-size: 0.9375rem;
margin: 0.875rem 0 0.25rem;
}
.lexical-content ul,
.lexical-content ol {
margin: 0.5rem 0;
padding-left: 1.5rem;
}
.lexical-content p {
margin: 0.5rem 0;
}
.lexical-content ul {
list-style: disc;
}
.lexical-content ul,
.lexical-content ol {
margin: 0.5rem 0;
padding-left: 1.5rem;
}
.lexical-content ol {
list-style: decimal;
}
.lexical-content ul {
list-style: disc;
}
.lexical-content li + li {
margin-top: 0.25rem;
}
.lexical-content ol {
list-style: decimal;
}
.lexical-content li > ul,
.lexical-content li > ol {
margin: 0.25rem 0;
}
.lexical-content li + li {
margin-top: 0.25rem;
}
.lexical-content blockquote {
margin: 0.75rem 0;
border-left: 3px solid var(--color-border);
padding-left: 1rem;
color: var(--color-muted-foreground);
}
.lexical-content li > ul,
.lexical-content li > ol {
margin: 0.25rem 0;
}
.lexical-content hr {
margin: 1.25rem 0;
border: 0;
border-top: 1px solid var(--color-border);
}
.lexical-content blockquote {
margin: 0.75rem 0;
border-left: 3px solid var(--color-border);
padding-left: 1rem;
color: var(--color-muted-foreground);
}
.lexical-content strong {
color: var(--color-foreground);
}
.lexical-content hr {
margin: 1.25rem 0;
border: 0;
border-top: 1px solid var(--color-border);
}
.lexical-content a {
color: var(--color-primary);
text-decoration: underline;
text-underline-offset: 2px;
}
.lexical-content strong {
color: var(--color-foreground);
}
.lexical-content a:hover {
text-decoration-color: var(--color-primary);
}
/* Authored text colours reach us as an inline style on the wrapping span. Inherit within
coloured runs so a bolded or linked word keeps its colour (strong/a above would win). */
.lexical-content [style*="color"] :is(strong, b, i, em, a) {
color: inherit;
}
.lexical-content :not(pre) > code {
background: var(--color-muted);
border-radius: 0.25rem;
padding: 0.125rem 0.375rem;
font-size: 0.8125rem;
}
.lexical-content a {
color: var(--color-primary);
text-decoration: underline;
text-underline-offset: 2px;
}
.lexical-content pre {
background: var(--color-muted);
border: 1px solid var(--color-border);
border-radius: 0.5rem;
padding: 0.875rem 1rem;
overflow-x: auto;
margin: 0.75rem 0;
}
.lexical-content a:hover {
text-decoration-color: var(--color-primary);
}
.lexical-content pre code {
background: transparent;
padding: 0;
font-size: 0.8125rem;
.lexical-content :not(pre) > code {
background: var(--color-muted);
border-radius: 0.25rem;
padding: 0.125rem 0.375rem;
font-size: 0.8125rem;
}
.lexical-content pre {
background: var(--color-muted);
border: 1px solid var(--color-border);
border-radius: 0.5rem;
padding: 0.875rem 1rem;
overflow-x: auto;
margin: 0.75rem 0;
}
.lexical-content pre code {
background: transparent;
padding: 0;
font-size: 0.8125rem;
}
.lexical-content h5,
.lexical-content h6 {
font-weight: 600;
line-height: 1.3;
color: var(--color-foreground);
}
.lexical-content h5 {
font-size: 0.875rem;
margin: 0.875rem 0 0.25rem;
}
.lexical-content h6 {
font-size: 0.8125rem;
margin: 0.875rem 0 0.25rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--color-muted-foreground);
}
.lexical-content li::marker {
color: var(--color-muted-foreground);
}
/* Checklist items render as lis wrapping checkbox inputs */
.lexical-content li:has(> input[type="checkbox"]) {
list-style: none;
display: flex;
align-items: baseline;
gap: 0.5em;
margin-left: -1.25rem;
}
.lexical-content input[type="checkbox"] {
accent-color: var(--color-primary);
width: 0.95em;
height: 0.95em;
}
.lexical-content img {
border-radius: var(--radius);
display: block;
height: auto;
max-width: 100%;
margin: 0.75rem 0;
}
.lexical-content figcaption {
color: var(--color-muted-foreground);
font-size: 0.8125rem;
margin-top: -0.375rem;
margin-bottom: 0.75rem;
}
.lexical-content table {
border-collapse: collapse;
display: block;
margin: 0.75rem 0;
overflow-x: auto;
width: 100%;
}
.lexical-content th,
.lexical-content td {
border: 1px solid var(--color-border);
padding: 0.35rem 0.65rem;
text-align: left;
vertical-align: top;
}
.lexical-content th {
background: color-mix(in oklch, var(--color-muted) 60%, transparent);
font-weight: 600;
}
}
/* Wiki prose-article typography (scoped to .wiki-markdown) */

View file

@ -2,6 +2,7 @@ import { RscEntryLexicalCell as RscEntryLexicalCell_44fe37237e0ebf4470c9990d8cb7
import { RscEntryLexicalField as RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { LexicalDiffComponent as LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e } from '@payloadcms/richtext-lexical/rsc'
import { LexicalEditorFeatureClient as LexicalEditorFeatureClient_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { TextStateFeatureClient as TextStateFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { FixedToolbarFeatureClient as FixedToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { InlineToolbarFeatureClient as InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { HorizontalRuleFeatureClient as HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
@ -32,7 +33,6 @@ import { default as default_c3ea68702b5e5f8f2f98055e01c43c8d } from '@/component
import { default as default_2f2033acccb3be245f1a85f7b4271dac } from '@/components/admin/awards/MedalDesigner'
import { default as default_701da9bef3b3cc3d8567adf41fa08aa3 } from '@/components/admin/awards/AwardAutomationView'
import { default as default_4b88a624e9f0b376cffcc6814d459adb } from '@/components/admin/assignments/AssignmentMembersField'
import { TextStateFeatureClient as TextStateFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client'
import { default as default_0edde40a6ccd30c893b1227360f69360 } from '@/components/static/TickDurationDescription'
import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/components/static/WarningMessage'
import { default as default_8e873aa39584420378774e6c9c4ac54b } from '@/components/admin/VehicleLibraryPicker'
@ -60,6 +60,7 @@ export const importMap = {
"@payloadcms/richtext-lexical/rsc#RscEntryLexicalField": RscEntryLexicalField_44fe37237e0ebf4470c9990d8cb7b07e,
"@payloadcms/richtext-lexical/rsc#LexicalDiffComponent": LexicalDiffComponent_44fe37237e0ebf4470c9990d8cb7b07e,
"@ai-stack/payloadcms/client#LexicalEditorFeatureClient": LexicalEditorFeatureClient_4490b89d4413c1ffaecdacfe72efaf73,
"@payloadcms/richtext-lexical/client#TextStateFeatureClient": TextStateFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#FixedToolbarFeatureClient": FixedToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#InlineToolbarFeatureClient": InlineToolbarFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@payloadcms/richtext-lexical/client#HorizontalRuleFeatureClient": HorizontalRuleFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
@ -90,7 +91,6 @@ export const importMap = {
"@/components/admin/awards/MedalDesigner#default": default_2f2033acccb3be245f1a85f7b4271dac,
"@/components/admin/awards/AwardAutomationView#default": default_701da9bef3b3cc3d8567adf41fa08aa3,
"@/components/admin/assignments/AssignmentMembersField#default": default_4b88a624e9f0b376cffcc6814d459adb,
"@payloadcms/richtext-lexical/client#TextStateFeatureClient": TextStateFeatureClient_e70f5e05f09f93e00b997edb1ef0c864,
"@/components/static/TickDurationDescription#default": default_0edde40a6ccd30c893b1227360f69360,
"@/components/static/WarningMessage#default": default_2d468cc5cf0b647ffca3201592c20825,
"@/components/admin/VehicleLibraryPicker#default": default_8e873aa39584420378774e6c9c4ac54b,

View file

@ -74,7 +74,7 @@ Permission tiers and panel gates:
## Hooks with side effects
- `Factions` `afterRead`: masks undiscovered factions (name, description, standing, relationships, campaigns, cover image, playable/starting) for readers without `factions:view-undiscovered` or `system:admin-access`. Admin panel reads are exempt; see `src/lib/intelligence/factionDiscovery.ts`
- `Factions` `afterRead`: masks undiscovered factions (name, description, standing, campaigns, cover image, playable/starting) for readers without `factions:view-undiscovered` or `system:admin-access`. Admin panel reads are exempt; see `src/lib/intelligence/factionDiscovery.ts`. Pairwise relationships are not on the faction record at all: they are computed from `faction-relation-entries`, and the ledger read module (`src/lib/intelligence/factionRelationLedger.ts`) filters the same way.
- `Structures` `beforeChange`: emits `structure:resize`; blueprint "Staffing Defaults" group via `staffingFields.ts`
- `GameStructures` `afterChange`: emits storage edit events; `beforeChange` copies blueprint staffing defaults on create
- `Users` `afterChange`: maintains profile sync

View file

@ -313,6 +313,27 @@ export const GameRules: GlobalConfig = {
},
],
},
{
name: "factionRelations",
type: "group",
label: "Faction Relations",
admin: {
description:
"Tunables for the faction relations ledger (faction-relation-entries). Every pairwise score is computed on read from the ledger; nothing is stored on the faction records.",
},
fields: [
{
name: "decayHalfLifeDays",
type: "number",
min: 1,
defaultValue: 30,
admin: {
description:
"Half-life, in days, of a decaying relation entry. A decaying entry keeps full weight until one period elapses, then halves per completed period. Entries without the Decays flag never fade.",
},
},
],
},
{
name: "zonePressureEnabled",
type: "checkbox",

View file

@ -0,0 +1,374 @@
import type { CollectionConfig, Payload, PayloadRequest, Where } from "payload";
import { hasPermission, requirePermission } from "@/utils/access-control/hasPermission";
import {
RELATION_POLARITIES,
RELATION_SEVERITY_DELTAS,
relationCategoryOptions,
relationSeverityOptions,
} from "@/lib/intelligence/factionRelations";
const readOnly = { admin: { readOnly: true } } as const;
/** Ledger managers: the admin-page permission holder or a superuser tier user. */
async function canManageLedger(
payload: Payload,
user: PayloadRequest["user"],
): Promise<boolean> {
if (!user) return false;
const [manages, adminTier] = await Promise.all([
hasPermission(payload, user, "admin:faction-relation-entries:manage"),
hasPermission(payload, user, "system:admin-access"),
]);
return manages || adminTier;
}
/**
* Field-level read gate for GM-only columns. Payload hides a field whose read
* access denies, which is what keeps `notes` out of every non-manager response
* (REST, local API and the ledger module).
*/
const managerOnlyField = {
access: {
read: async ({ req }: { req: PayloadRequest }) => canManageLedger(req.payload, req.user),
},
};
function relationId(value: unknown): 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;
}
/**
* Append-only ledger of events that move faction relationships.
*
* Nothing on the faction records stores a pairwise score any more: every
* relationship value shown anywhere is computed from these rows by
* `src/lib/intelligence/factionRelations.ts`. That keeps a single source of
* truth, so a score can never disagree with the history that produced it.
*
* Write semantics:
* - Entries are editable, because fixing a wrong delta should not cost two
* rows.
* - Deletion is denied outright. An event that never happened is voided: the
* row stays visible in the admin panel, is excluded from every sum, and is
* hidden from players.
*
* Visibility:
* - `summary` is player-facing. `notes` is GM-only and never leaves the admin
* panel.
* - `hiddenFromPlayers` entries still move the score; they are excluded from
* the player-facing list only, which is how a covert cause can have a
* visible effect.
*/
export const FactionRelationEntries: CollectionConfig = {
slug: "faction-relation-entries",
labels: { singular: "Relation Entry", plural: "Relation Entries" },
admin: {
group: "Intelligence",
useAsTitle: "summary",
defaultColumns: ["subject", "target", "delta", "severity", "category", "occurredAt", "voided"],
description:
"Ledger behind every faction relationship score. Add an entry for each thing that changed one faction's attitude toward another; scores are computed from these rows, never typed in.",
},
access: {
// Managers (and the superuser tier) see the whole ledger, voided rows
// included, which is also the admin-panel path. Everyone else sees live
// entries only; the Factions collection is readable by any logged-in user,
// so this matches it.
//
// Hidden entries are NOT filtered here: they have to reach the score, since
// a covert cause is supposed to move a score the players can see. The
// `afterRead` hook censors their content instead, and the read module keeps
// them out of the player-facing timeline.
read: async ({ req }): Promise<boolean | Where> => {
if (!req.user) return false;
if (await canManageLedger(req.payload, req.user)) return true;
return { voided: { not_equals: true } };
},
create: requirePermission("faction-relation-entries:create"),
update: requirePermission("faction-relation-entries:update"),
// Voiding is the only removal path: an audit trail is the point of a ledger.
delete: () => false,
},
hooks: {
// Strip a hidden entry down to what the score needs for anyone who is not a
// ledger manager. The faction pair, delta, date and decay flag stay (all of
// them are needed for an identical score on both sides, and the score is
// public anyway); everything that explains the event goes: summary, notes,
// category, mission, campaign and the admin-only audit stamps.
afterRead: [
async ({ doc, req }) => {
if (!doc || doc.hiddenFromPlayers !== true) return doc;
if (await canManageLedger(req.payload, req.user)) return doc;
return {
...doc,
summary: "",
notes: null,
category: "other",
mission: null,
campaign: null,
voidedReason: null,
voidedAt: null,
voidedBy: null,
recordedBy: null,
};
},
],
beforeValidate: [
async ({ data, originalDoc }) => {
if (!data) return data;
const merged = { ...(originalDoc ?? {}), ...data } as Record<string, unknown>;
const subjectId = relationId(merged.subject);
const targetId = relationId(merged.target);
if (subjectId != null && targetId != null && subjectId === targetId) {
throw new Error(
"A relation entry needs two different factions: the one whose attitude changes and the one it is about.",
);
}
const severity = merged.severity as string | undefined;
const polarity = merged.polarity as string | undefined;
if (severity && severity !== "custom") {
const magnitude = RELATION_SEVERITY_DELTAS[severity as keyof typeof RELATION_SEVERITY_DELTAS];
if (magnitude == null) return data;
data.delta = polarity === "detrimental" ? -magnitude : magnitude;
return data;
}
if (severity === "custom") {
const delta = Number(merged.delta);
if (!Number.isFinite(delta) || delta === 0) {
throw new Error("A custom severity needs a non-zero delta.");
}
// Keep the two fields honest: the sign of the number IS the polarity.
data.polarity = delta > 0 ? "beneficial" : "detrimental";
}
return data;
},
],
beforeChange: [
async ({ data, originalDoc, operation, req }) => {
const wasVoided = Boolean((originalDoc as { voided?: boolean } | undefined)?.voided);
const isVoided = Boolean(data.voided);
if (!wasVoided && isVoided) {
data.voidedAt = new Date().toISOString();
data.voidedBy = req.user?.id ?? null;
} else if (wasVoided && !isVoided) {
data.voidedAt = null;
data.voidedBy = null;
data.voidedReason = null;
}
if (operation === "create" && req.user) {
data.recordedBy = req.user.id;
}
return data;
},
],
},
fields: [
{
type: "row",
fields: [
{
name: "subject",
type: "relationship",
relationTo: "factions",
required: true,
index: true,
admin: {
width: "50%",
description: "The faction whose attitude changes.",
},
},
{
name: "target",
type: "relationship",
relationTo: "factions",
required: true,
index: true,
admin: {
width: "50%",
description: "The faction the attitude is about.",
},
},
],
},
{
name: "mutual",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Count this event for both directions (a shared battle, a treaty both sides signed). Leave unchecked when only the subject's attitude moves.",
},
},
{
type: "row",
fields: [
{
name: "polarity",
type: "select",
required: true,
defaultValue: "detrimental",
options: [
{ label: "Beneficial (improves the relationship)", value: RELATION_POLARITIES[0] },
{ label: "Detrimental (worsens the relationship)", value: RELATION_POLARITIES[1] },
],
admin: {
width: "50%",
description: "Which way the attitude moves. Ignored for a custom delta, derived from its sign.",
},
},
{
name: "severity",
type: "select",
required: true,
defaultValue: "notable",
options: relationSeverityOptions(),
admin: {
width: "50%",
description:
"How large the move is. The tier sets the delta; pick Custom to type an exact number.",
},
},
],
},
{
name: "delta",
type: "number",
required: true,
min: -100,
max: 100,
admin: {
condition: (data) => data?.severity === "custom",
description:
"Signed exact amount for a custom entry, -100 to 100. Positive improves the relationship.",
},
},
{
name: "category",
type: "select",
required: true,
index: true,
defaultValue: "other",
options: relationCategoryOptions(),
admin: {
description: "What kind of event this was. Labels the entry; never changes the score.",
},
},
{
name: "summary",
type: "text",
required: true,
admin: {
description:
"One line the players will read, in plain language. This is the explanation attached to the score change.",
},
},
{
name: "notes",
type: "textarea",
...managerOnlyField,
admin: {
description:
"GM-only reasoning. Never shown to players, so it is safe for speculation and spoilers.",
},
},
{
name: "occurredAt",
type: "date",
required: true,
index: true,
defaultValue: () => new Date().toISOString(),
admin: {
date: { pickerAppearance: "dayAndTime" },
description:
"When it happened in the fiction. Drives the timeline order and, for decaying entries, how far it has faded.",
},
},
{
name: "decays",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Transient events fade: the delta halves per half-life (GameRules > Faction Relations). Leave unchecked for lasting shifts like a treaty or a betrayal.",
},
},
{
name: "hiddenFromPlayers",
type: "checkbox",
defaultValue: false,
admin: {
description:
"Counts toward the score but never appears in the player-facing list. Use it when the effect is visible but the cause is not.",
},
},
{
type: "row",
fields: [
{
name: "mission",
type: "relationship",
relationTo: "missions",
index: true,
admin: { width: "50%", description: "Optional: the operation that caused it." },
},
{
name: "campaign",
type: "relationship",
relationTo: "campaigns",
index: true,
admin: { width: "50%", description: "Optional: the campaign arc it belongs to." },
},
],
},
{
type: "collapsible",
label: "Voiding",
admin: {
description:
"Void an entry that should never have counted. It stays here for the record, struck through, and is excluded from every score.",
},
fields: [
{
name: "voided",
type: "checkbox",
defaultValue: false,
index: true,
admin: { description: "Excluded from every score and hidden from players." },
},
{ name: "voidedAt", type: "date", ...readOnly, ...managerOnlyField },
{
name: "voidedBy",
type: "relationship",
relationTo: "users",
...readOnly,
...managerOnlyField,
},
{
name: "voidedReason",
type: "textarea",
...managerOnlyField,
admin: { description: "Why it was voided." },
},
],
},
{
name: "recordedBy",
type: "relationship",
relationTo: "users",
...readOnly,
...managerOnlyField,
},
],
};

View file

@ -99,7 +99,7 @@ export const Factions: CollectionConfig = {
index: true,
admin: {
description:
"Uncheck while players should not know this faction yet. The entry still appears in lists as UNDISCOVERED; name, description, standing, relationships, campaign links, cover image and the playable/starting flags are hidden from anyone without the View Undiscovered Factions permission.",
"Uncheck while players should not know this faction yet. The entry still appears in lists as UNDISCOVERED; name, description, standing, campaign links, cover image and the playable/starting flags are hidden from anyone without the View Undiscovered Factions permission.",
},
},
{
@ -117,47 +117,6 @@ export const Factions: CollectionConfig = {
min: -100,
max: 100,
},
{
name: "relationships",
type: "array",
labels: {
singular: "Relationship",
plural: "Relationships",
},
admin: {
description:
"Pairwise standing between this faction and another faction, from -100 (hostile) to 100 (allied). 0 is neutral. One entry per counterpart faction.",
},
fields: [
{
name: "targetFaction",
type: "relationship",
relationTo: "factions",
required: true,
admin: {
description: "The other faction in this pairwise relationship.",
},
},
{
name: "value",
type: "number",
required: true,
defaultValue: 0,
min: -100,
max: 100,
admin: {
description: "Standing from -100 (hostile) to 100 (allied). 0 is neutral.",
},
},
{
name: "notes",
type: "textarea",
admin: {
description: "Optional context for why this relationship stands where it does.",
},
},
],
},
{
name: "playableFaction",
type: "checkbox",

View file

@ -1,6 +1,5 @@
import type { CollectionConfig, Payload, PayloadRequest, Where } from "payload";
import { FixedToolbarFeature, lexicalEditor, TextStateFeature } from "@payloadcms/richtext-lexical";
import { PayloadAiPluginLexicalEditorFeature } from "@ai-stack/payloadcms";
import { ptfLexicalEditor } from "@/lib/lexical/editor";
import {
requirePermission,
hasPermission,
@ -8,7 +7,6 @@ import {
} from "@/utils/access-control/hasPermission";
import { expireQueuedEntriesForMission, grantQueuedEntriesForMission } from "@/lib/contributions";
import { nextSaturdayStart } from "@/lib/intelligence/fridayTime";
import { BRIEFING_TEXT_COLORS } from "@/lib/intelligence/briefingSqf";
type AssignmentRef = { id: number } | number;
@ -88,27 +86,11 @@ async function missionReadFilter(req: PayloadRequest): Promise<boolean | Where>
}
/**
* Briefings are the only field that exports to Arma Structured Text, so only
* this editor gets the color palette. Keeping it field-scoped avoids offering
* colors on rich text surfaces that do not render them.
* Briefings share the app-wide rich-text setup (fixed toolbar, shared text-colour palette,
* AI assist). Their colours additionally survive export to Arma Structured Text via
* lib/intelligence/briefingSqf.
*/
const briefingDetailsEditor = lexicalEditor({
features: ({ defaultFeatures }) => [
...defaultFeatures,
FixedToolbarFeature(),
TextStateFeature({
state: {
color: Object.fromEntries(
Object.entries(BRIEFING_TEXT_COLORS).map(([key, { hex, label }]) => [
key,
{ css: { color: hex }, label },
]),
),
},
}),
PayloadAiPluginLexicalEditorFeature(),
],
});
const briefingDetailsEditor = ptfLexicalEditor();
export const Missions: CollectionConfig = {
slug: "missions",

View file

@ -1,5 +1,5 @@
import type { CollectionConfig, Where } from "payload";
import { FixedToolbarFeature, lexicalEditor } from "@payloadcms/richtext-lexical";
import { ptfLexicalEditor } from "@/lib/lexical/editor";
import { hasPermission } from "@/utils/access-control/hasPermission";
/**
@ -97,9 +97,7 @@ export const Journals: CollectionConfig = {
name: "body",
type: "richText",
required: true,
editor: lexicalEditor({
features: ({ defaultFeatures }) => [...defaultFeatures, FixedToolbarFeature()],
}),
editor: ptfLexicalEditor(),
admin: {
description: "Rich text body of the entry, rendered on /journals with the Lexical renderer.",
},

View file

@ -1,5 +1,5 @@
import type { CollectionConfig } from "payload";
import { FixedToolbarFeature, lexicalEditor } from "@payloadcms/richtext-lexical";
import { ptfLexicalEditor } from "@/lib/lexical/editor";
import hasRoles from "@/utils/access-control/hasRoles";
function isStoryAuthor(user: Parameters<typeof hasRoles>[1]): boolean {
@ -69,9 +69,7 @@ export const StoryBeats: CollectionConfig = {
name: "body",
type: "richText",
required: true,
editor: lexicalEditor({
features: ({ defaultFeatures }) => [...defaultFeatures, FixedToolbarFeature()],
}),
editor: ptfLexicalEditor(),
admin: {
description: "Rich text body of the entry, rendered on /story with the Lexical renderer.",
},

View file

@ -50,6 +50,9 @@ Pages are server components that fetch via `getPayload()`, then pass data as pro
### Item compound component
`storage/` uses a compound `<Item>` component for grid cells with slots: `<Item.Slot name="icon">`, `<Item.Slot name="stats">`, `<Item.Menu>`. Attachments render as stacked badges on the grid cell; popover shows full detail on hover.
### Rich-text rendering
Front-end surfaces render serialized Lexical with the shared `RichTextView` (`src/components/frontend/RichTextView.tsx`): it applies `.lexical-content` typography and paints saved text colours (TextStateFeature state or inline styles), both of which Payload's default JSX renderer drops. Briefings render through this component too (mission briefing sections use it directly). Editors come from `ptfLexicalEditor()` (`src/lib/lexical/editor.ts`) so every rich-text field gets the fixed toolbar + colour palette by default.
### SSE consumers
- `GameTickRealtime` mounts in `(frontend)/layout.tsx` for all authed users.
- `ShipmentToasts` mounts only for logistics-qualified users.
@ -106,6 +109,7 @@ Whenever creating a new component or refactoring an existing component's styling
| Minigame game rules | `src/lib/aim-trainer.ts` etc. — pure libs, components consume them |
| Keyboard shortcuts | `src/components/command-palette/` |
| Admin custom fields | `src/components/admin/` (awards designers, CollapsibleGroupField, narrative-flow, shims) |
| Render Lexical rich text | `src/components/frontend/RichTextView.tsx` (shared) + `src/lib/lexical/` (editor factory, colour palette) |
## Anti-patterns

View file

@ -0,0 +1,24 @@
"use client";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { cn } from "@/lib/utils";
import { richTextConverters } from "@/lib/lexical/richTextConverters";
type RichTextData = Parameters<typeof RichText>[0]["data"];
export type { RichTextData };
interface RichTextViewProps {
data?: RichTextData | null;
className?: string;
}
/**
* Shared front-end renderer for serialized Lexical rich-text fields. Applies `.lexical-content`
* typography (Tailwind preflight otherwise strips headings/lists/quotes) and the shared colour
* converter, so formatting and authored colours survive to the public site. Rendered as the
* `.lexical-content` container itself (no extra wrapper); `className` merges onto that node.
*/
export function RichTextView({ data, className }: RichTextViewProps) {
if (!data) return null;
return <RichText data={data} converters={richTextConverters} className={cn("lexical-content", className)} />;
}

View file

@ -19,7 +19,8 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { RichText } from "@payloadcms/richtext-lexical/react";
import type { RichTextData } from "@/components/frontend/RichTextView";
import { RichTextView } from "@/components/frontend/RichTextView";
import { cn } from "@/lib/utils";
import {
isAnnouncementActive,
@ -66,7 +67,7 @@ const BUTTON_VARIANTS: Record<AnnouncementButtonStyle, "default" | "outline" | "
destructive: "destructive",
};
type LexicalData = Parameters<typeof RichText>[0]["data"];
type LexicalData = RichTextData;
function AnnouncementRichText({ description }: { description: unknown }) {
if (typeof description === "string") {
@ -74,9 +75,7 @@ function AnnouncementRichText({ description }: { description: unknown }) {
}
if (!description || typeof description !== "object") return null;
return (
<div className="lexical-content mt-2">
<RichText data={description as LexicalData} />
</div>
<RichTextView data={description as LexicalData} className="mt-2" />
);
}

View file

@ -21,6 +21,7 @@ import {
NotebookText,
Package,
Radar,
Scale,
ScrollText,
Search,
Store,
@ -71,6 +72,11 @@ export const sidebarData = {
url: "/intelligence/factions",
icon: Flag,
},
{
title: "Relations",
url: "/intelligence/factions/relations",
icon: Scale,
},
{
title: "Tech Tree",
url: "/intelligence/tech-tree",

View file

@ -1,7 +1,7 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
@ -259,9 +259,9 @@ export function TicketDetail({
Description
</h3>
</div>
<div className="rounded-md border bg-muted/20 p-4 text-sm leading-relaxed text-muted-foreground [&_p]:mb-2 [&_p:last-child]:mb-0 [&_strong]:text-foreground [&_em]:italic">
<div className="rounded-md border bg-muted/20 p-4 text-sm leading-relaxed text-muted-foreground">
{descriptionText ? (
<RichText data={ticket.description} />
<RichTextView data={ticket.description} />
) : (
<p>No description provided.</p>
)}

View file

@ -1,6 +1,6 @@
"use client";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { convertLexicalToPlaintext } from "@payloadcms/richtext-lexical/plaintext";
import type { Ticket, User } from "@/payload-types";
import { cn } from "@/lib/utils";
@ -99,7 +99,7 @@ export function TicketTimeline({ ticket, currentUserId }: TicketTimelineProps) {
isClientMessage ? "text-blue-100/90" : "text-amber-100/90",
)}
>
<RichText data={activity.content} />
<RichTextView data={activity.content} />
</div>
<div className="text-[10px] text-muted-foreground">
{authorName} · {formatDate(activity.created_at)}

View file

@ -1,11 +1,10 @@
import { RichText } from "@payloadcms/richtext-lexical/react";
import { FileTextIcon } from "lucide-react";
import type { ComponentProps } from "react";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
import { briefingConverters } from "@/lib/intelligence/briefingConverters";
import type { RichTextData } from "@/components/frontend/RichTextView";
import { RichTextView } from "@/components/frontend/RichTextView";
import { BriefingSqfExport } from "./BriefingSqfExport";
type BriefingDetails = ComponentProps<typeof RichText>["data"];
type BriefingDetails = RichTextData;
interface BriefingEntry {
sectionName: string;
@ -45,9 +44,9 @@ export function MissionBriefingSection({ briefing, missionName }: MissionBriefin
<ItemTitle>{entry.sectionName}</ItemTitle>
<BriefingSqfExport entries={[entry]} missionName={missionName} scope="entry" />
</ItemHeader>
<ItemContent className="flex flex-col justify-start items-start lexical-content">
<ItemContent className="flex flex-col justify-start items-start">
{entry.details ? (
<RichText data={entry.details} converters={briefingConverters} />
<RichTextView data={entry.details} />
) : (
<p className="text-sm text-muted-foreground italic">No details.</p>
)}

View file

@ -1,4 +1,4 @@
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { RadioIcon } from "lucide-react";
import { Item, ItemContent, ItemHeader, ItemTitle } from "@/components/ui/item";
@ -59,9 +59,7 @@ export function MissionComms({ commsAndDocs }: MissionCommsProps) {
<span className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Radio Plan
</span>
<div className="lexical-content">
<RichText data={radioPlan} />
</div>
<RichTextView data={radioPlan} className="text-muted-foreground" />
</div>
)}
{hasFrequencies && (

View file

@ -1,7 +1,8 @@
import { RichText } from "@payloadcms/richtext-lexical/react";
import type { RichTextData } from "@/components/frontend/RichTextView";
import { RichTextView } from "@/components/frontend/RichTextView";
import { cn } from "@/lib/utils";
type LexicalData = Parameters<typeof RichText>[0]["data"];
type LexicalData = RichTextData;
export type RoleDescriptionData = LexicalData | string | null;
@ -24,8 +25,6 @@ export function RoleDescription({ description, className }: RoleDescriptionProps
}
if (!description || typeof description !== "object") return null;
return (
<div className={cn("lexical-content", className)}>
<RichText data={description as LexicalData} />
</div>
<RichTextView data={description as LexicalData} className={cn("text-muted-foreground", className)} />
);
}

View file

@ -14,6 +14,7 @@ import { ProductionPanel } from "@/components/frontend/baseManagement/Production
import { SlotsPanel } from "@/components/frontend/baseManagement/SlotsPanel";
import { getStructureDetail } from "@/app/(frontend)/logistics/structures/[id]/detail";
import type { StructureDetailData } from "@/app/(frontend)/logistics/structures/[id]/detail-data";
import { RichTextView } from "@/components/frontend/RichTextView";
import { useGameTick } from "@/hooks/useGameTick";
import { BoxIcon, CoinsIcon, MapPinIcon, WrenchIcon } from "lucide-react";
import {
@ -102,9 +103,9 @@ export function StructureDetailDrawer({
{data.gates.canManage ? " // managed by you" : ""}
</div>
<div className="text-base font-semibold text-white/95">{structure.name}</div>
{data.description && (
<p className="text-xs text-muted-foreground">{data.description}</p>
)}
{data.description ? (
<RichTextView data={data.description} className="text-xs text-muted-foreground" />
) : null}
<div className="flex gap-2">
<Button
asChild

View file

@ -3,7 +3,8 @@
import { Fragment, type ComponentType, type ReactNode } from "react";
import Link from "next/link";
import { ArrowLeftIcon, MapPinIcon, ShieldIcon, StoreIcon } from "lucide-react";
import { RichText } from "@payloadcms/richtext-lexical/react";
import type { RichTextData } from "@/components/frontend/RichTextView";
import { RichTextView } from "@/components/frontend/RichTextView";
import type { Asset, GameNpc, MarketListing } from "@/payload-types";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
@ -54,7 +55,7 @@ function Field({
);
}
type LexicalData = Parameters<typeof RichText>[0]["data"];
type LexicalData = RichTextData;
/** Renders the NPC's Lexical richText bio, falling back to a placeholder when empty. */
function NpcBio({ bio }: { bio: GameNpc["bio"] }) {
@ -63,9 +64,7 @@ function NpcBio({ bio }: { bio: GameNpc["bio"] }) {
return <p className="text-sm text-white/60">No bio on file.</p>;
}
return (
<div className="lexical-content">
<RichText data={bio as LexicalData} />
</div>
<RichTextView data={bio as LexicalData} className="text-muted-foreground" />
);
}
@ -76,7 +75,7 @@ function LevelDescription({ data }: { data: GameNpc["levelDescription"] }) {
if (!data || !Array.isArray(children) || children.length === 0) {
return <p className="text-sm text-white/60">No capabilities on file.</p>;
}
return <div className="lexical-content"><RichText data={data as LexicalData} /></div>;
return <RichTextView data={data as LexicalData} className="text-muted-foreground" />;
}
export function NpcProfile({ npc, listings, employmentSlot, conversationSlot }: NpcProfileProps) {

View file

@ -4,7 +4,7 @@ import { useCallback, useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { HourglassIcon, PencilIcon, Save, ShieldCheck, X } from "lucide-react";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { LexicalComposer } from "@payloadcms/richtext-lexical/lexical/react/LexicalComposer";
import { ContentEditable } from "@payloadcms/richtext-lexical/lexical/react/LexicalContentEditable";
import { LexicalErrorBoundary } from "@payloadcms/richtext-lexical/lexical/react/LexicalErrorBoundary";
@ -241,7 +241,7 @@ function ExcerptCard({
</div>
</div>
) : value ? (
<RichText data={value} />
<RichTextView data={value} />
) : (
<p>{emptyMessage}</p>
)}

View file

@ -2,7 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { BookOpenText, ChevronLeft, ChevronRight, X } from "lucide-react";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { Button } from "@/components/ui/button";
import { BeatReadMarker } from "@/components/frontend/story/BeatReadMarker";
import { BeatVoiceover } from "@/components/frontend/story/BeatVoiceover";
@ -285,7 +285,7 @@ export function BookView({ beats }: { readonly beats: readonly StoryViewerBeat[]
</div>
)}
<div className="book-view-body mt-8">
<RichText data={beat.body} className={cn(READER_BODY_CLASSES)} />
<RichTextView data={beat.body} className={cn(READER_BODY_CLASSES)} />
</div>
</article>
))}

View file

@ -2,7 +2,7 @@
import { useEffect, useRef, useState } from "react";
import { BookOpen, X } from "lucide-react";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { Button } from "@/components/ui/button";
import { BeatReadMarker } from "@/components/frontend/story/BeatReadMarker";
import { BeatVoiceover } from "@/components/frontend/story/BeatVoiceover";
@ -123,7 +123,7 @@ export function StoryViewer({ beats }: { readonly beats: readonly StoryViewerBea
</div>
)}
<div className="mt-8">
<RichText data={beat.body} className={cn(READER_BODY_CLASSES)} />
<RichTextView data={beat.body} className={cn(READER_BODY_CLASSES)} />
</div>
</li>
))}

View file

@ -1,7 +1,7 @@
"use client";
import { useState } from "react";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import { Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
@ -106,8 +106,8 @@ export function SurveyForm({
<Card>
<CardContent className="py-10 text-center">
{confirmationMessage ? (
<div className="lexical-content text-sm [&_p]:my-2">
<RichText data={confirmationMessage} />
<div className="text-sm [&_p]:my-2">
<RichTextView data={confirmationMessage} />
</div>
) : (
<p className="text-emerald-400">Your response has been recorded. Thank you!</p>
@ -122,8 +122,8 @@ export function SurveyForm({
{fields.map((field, index) => {
if (field.blockType === "message") {
return field.message ? (
<div key={field.id ?? index} className="lexical-content text-sm">
<RichText data={field.message} />
<div key={field.id ?? index} className="text-sm">
<RichTextView data={field.message} />
</div>
) : null;
}

View file

@ -1,6 +1,6 @@
"use client";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { RichTextView } from "@/components/frontend/RichTextView";
import React from "react";
import { Badge } from "@/components/ui/badge";
@ -56,7 +56,7 @@ export function TechDetailDialog({
{detail.description ? (
<div className="prose prose-sm prose-invert max-w-none text-sm text-white/70 [&_a]:text-cyan-400">
<RichText data={detail.description as never} />
<RichTextView data={detail.description as never} />
</div>
) : null}

View file

@ -25,6 +25,8 @@ import {
import { toast } from "sonner";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { cn } from "@/lib/utils";
import { WIKI_EDITOR_METRICS, WIKI_EDITOR_SCROLLBAR_NONE } from "./editorMetrics";
import { WikiLinkDialog } from "@/components/frontend/wiki/WikiLinkDialog";
import { WikiEditorHighlightLayer } from "@/components/frontend/wiki/WikiEditorHighlightLayer";
import { WikiTemplateDialog } from "@/components/frontend/wiki/WikiTemplateDialog";
@ -448,7 +450,14 @@ export function WikiEditorBody({
onKeyDown={handleBodyKeyDown}
placeholder="Write the field guide entry in Markdown."
disabled={pending}
className="absolute inset-0 h-full w-full resize-none border-0 bg-transparent font-mono text-sm text-transparent caret-foreground shadow-none selection:bg-primary/30 focus-visible:outline-none focus-visible:ring-0"
className={cn(
// Must stay identical to the overlay metrics (editorMetrics.ts), plus no
// scrollbar gutter: a reserved classic scrollbar (Firefox/Safari) would
// shrink the textarea's content width vs the overlay and re-introduce wrap drift.
WIKI_EDITOR_METRICS,
WIKI_EDITOR_SCROLLBAR_NONE,
"absolute inset-0 h-full w-full resize-none border-0 bg-transparent text-transparent caret-foreground shadow-none selection:bg-primary/30 focus-visible:outline-none focus-visible:ring-0",
)}
/>
</div>
</div>

View file

@ -3,6 +3,7 @@
import { forwardRef, useMemo, type HTMLAttributes, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { highlightMarkdownLines } from "@/lib/wiki/editorHighlight";
import { WIKI_EDITOR_METRICS } from "./editorMetrics";
interface WikiEditorHighlightLayerProps extends HTMLAttributes<HTMLDivElement> {
readonly body: string;
@ -10,9 +11,11 @@ interface WikiEditorHighlightLayerProps extends HTMLAttributes<HTMLDivElement> {
/**
* Colored text layer rendered underneath the editor textarea (which uses
* transparent text). Sizing must mirror the textarea exactly: same padding,
* font, and a transparent border so text starts at the same 1px + padding
* offset inside the shared wrapper's border.
* transparent text). Sizing must mirror the textarea exactly — identical
* metrics/padding (`WIKI_EDITOR_METRICS`) and NO border of its own: children
* of the editor wrapper are absolutely positioned, so `inset-0` already places
* them inside the wrapper border; an extra transparent border here would just
* shrink the overlay by 2px and desynchronize where long lines wrap.
*/
export const WikiEditorHighlightLayer = forwardRef<
HTMLDivElement,
@ -41,7 +44,7 @@ export const WikiEditorHighlightLayer = forwardRef<
className={cn("pointer-events-none absolute inset-0 overflow-hidden", className)}
{...rest}
>
<div className="whitespace-pre-wrap break-words border border-transparent px-3 py-2 font-mono text-sm text-foreground/90">
<div className={cn(WIKI_EDITOR_METRICS, "whitespace-pre-wrap break-words text-foreground/90")}>
{nodes}
</div>
</div>

View file

@ -0,0 +1,25 @@
/**
* Typography + box-model classes that MUST stay identical between the editor
* textarea and the painted highlight overlay underneath it.
*
* The overlay is positioned `absolute inset-0` over the textarea and paints the
* visible text while the textarea keeps `text-transparent`. If the two layers
* ever differ in font size, line height, padding or available content width,
* soft-wrapped lines break at different columns; every difference shifts the
* overlay text vertically against the caret/click geometry of the textarea
* below it. Inserting an image markdown token (`![alt](/media/...png)`, one
* giant unbreakable word) maximizes wrap-point sensitivity, which is why the
* drift becomes obvious right after an upload. Both components import these
* classes from here instead of duplicating them; keep new shared metrics here,
* not inline in either component (see tests/int/wiki-editor-metrics.int.spec.ts).
*/
export const WIKI_EDITOR_METRICS = "px-3 py-2 font-mono text-sm";
/**
* Classic scrollbars (Firefox, Safari, non-overlay Chrome) reserve layout width
* inside the scrolling textarea, shrinking its content width relative to the
* overflow-hidden overlay. Hiding the scrollbar keeps both boxes exactly the
* same width everywhere; wheel/keyboard scrolling and the existing
* caret-into-view logic still work without a draggable thumb.
*/
export const WIKI_EDITOR_SCROLLBAR_NONE = "[scrollbar-width:none] [&::-webkit-scrollbar]:hidden";

View file

@ -76,7 +76,7 @@ base-tick script ── lib/base/tick.ts (processBaseTick: salaries, maintenance
`redactText()` replaces every non-space glyph with a block character, for spoilered copy (mission objectives, voiceover scripts).
### `intelligence/factionDiscovery.ts`
Faction discovery gate. `canViewUndiscoveredFactions(payload, user)` checks `factions:view-undiscovered` **or** `system:admin-access`; `maskUndiscoveredFaction(doc)` blanks name, description, standing, relationships, campaign links, cover image and the playable/starting flags. Consumed by the Factions `afterRead` hook, so masking applies to every reader (pages, REST, populated relationships) without per-page work. Admin panel reads are exempt so a masked edit form can never write a placeholder name back over a record.
Faction discovery gate. `canViewUndiscoveredFactions(payload, user)` checks `factions:view-undiscovered` **or** `system:admin-access`; `maskUndiscoveredFaction(doc)` blanks name, description, standing, campaign links, cover image and the playable/starting flags. Consumed by the Factions `afterRead` hook, so masking applies to every reader (pages, REST, populated relationships) without per-page work. Admin panel reads are exempt so a masked edit form can never write a placeholder name back over a record. Pairwise relations moved off the faction record: `factionRelations.ts` (pure math) and `factionRelationLedger.ts` (access-respecting reads) derive them from the `faction-relation-entries` ledger, and the ledger module filters entries naming an undiscovered faction for the same readers.
### `storageRules.ts`
Enforcement order: **prohibited → whitelist → per-item cap**. Functions: `checkStorageDeposit`, `isResourceProhibited`, `isResourceWhitelisted`, `getResourceStorageCap`, `storageViolationMessage`. Used in structure actions, shipment creation, and arrival processing.

View file

@ -1,17 +0,0 @@
import type { JSXConvertersFunction } from "@payloadcms/richtext-lexical/react";
import { briefingTextColor } from "./briefingSqf";
/**
* Payload's default text converter ignores both TextStateFeature state and the
* inline `style` string, so briefing colors would silently disappear on the
* page. Wrap the default converter in a colored span when the node has one.
*/
export const briefingConverters: JSXConvertersFunction = ({ defaultConverters }) => ({
...defaultConverters,
text: (args) => {
const base = defaultConverters.text;
const rendered = typeof base === "function" ? base(args) : null;
const color = briefingTextColor(args.node);
return color && rendered !== null ? <span style={{ color }}>{rendered}</span> : rendered;
},
});

View file

@ -40,7 +40,6 @@ export function maskUndiscoveredFaction<T extends object>(doc: T): T {
name: UNDISCOVERED_FACTION_NAME,
description: null,
reputation: null,
relationships: [],
playableFaction: false,
startingFaction: false,
associatedCampaigns: [],

View file

@ -0,0 +1,237 @@
/**
* Server-side reads over the faction relation ledger.
*
* Every surface that shows a relationship goes through here so the visibility
* rules exist in exactly one place:
* - Reads run with the caller's user (never `overrideAccess: true`), so the
* collection's own read access drops voided entries, and its afterRead hook
* censors hidden ones.
* - Undiscovered factions are masked on the Factions collection, not on this
* ledger, so entries naming an undiscovered faction are filtered here for
* readers without `factions:view-undiscovered`.
*
* The math itself lives in `./factionRelations` and stays pure.
*/
import type { Payload } from "payload";
import { canViewUndiscoveredFactions } from "@/lib/intelligence/factionDiscovery";
import {
DEFAULT_DECAY_HALF_LIFE_DAYS,
directedScoreMap,
effectiveDelta,
type RelationEntryLike,
} from "@/lib/intelligence/factionRelations";
type UserLike = { id: number | string; roleDocs?: unknown } | null | undefined;
export interface RelationFactionRef {
id: number;
name: string;
type: string;
discovered: boolean;
}
export interface RelationLedgerRow {
id: number;
subjectId: number;
targetId: number;
/** Effective amount right now, decayed when the entry fades. */
delta: number;
mutual: boolean;
severity: string;
category: string;
summary: string;
occurredAt: string;
decays: boolean;
missionId: number | null;
campaignId: number | null;
}
export interface RelationContext {
factions: RelationFactionRef[];
/** Player-safe entries, newest first. Voided and hidden rows excluded. */
rows: RelationLedgerRow[];
/** Directed scores keyed by `subjectId:targetId`. */
scores: Map<string, number>;
halfLifeDays: number;
}
const EMPTY: RelationContext = {
factions: [],
rows: [],
scores: new Map(),
halfLifeDays: DEFAULT_DECAY_HALF_LIFE_DAYS,
};
function relId(value: unknown): 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;
}
interface RawEntry {
id: number;
subject: unknown;
target: unknown;
delta: number;
mutual?: boolean | null;
severity?: string | null;
category?: string | null;
summary?: string | null;
occurredAt?: string | null;
decays?: boolean | null;
hiddenFromPlayers?: boolean | null;
voided?: boolean | null;
mission?: unknown;
campaign?: unknown;
}
interface RawFaction {
id: number;
name?: string | null;
type?: string | null;
discovered?: boolean | null;
}
/** Configured decay half-life, falling back to the documented default. */
export async function getRelationHalfLifeDays(payload: Payload): Promise<number> {
const rules = await payload
.findGlobal({ slug: "game-rules", depth: 0 })
.catch(() => null);
const configured = (rules as { factionRelations?: { decayHalfLifeDays?: number | null } } | null)
?.factionRelations?.decayHalfLifeDays;
const value = Number(configured);
return Number.isFinite(value) && value >= 1 ? value : DEFAULT_DECAY_HALF_LIFE_DAYS;
}
/**
* One read for both relation surfaces: the faction list, the player-safe
* entries, and every directed score computed from them.
*/
export async function getRelationContext(
payload: Payload,
user: UserLike,
now: Date = new Date(),
): Promise<RelationContext> {
if (!user) return EMPTY;
const [halfLifeDays, factionsRes, entriesRes, canSeeUndiscovered] = await Promise.all([
getRelationHalfLifeDays(payload),
payload.find({
collection: "factions",
limit: 200,
depth: 0,
sort: "name",
pagination: false,
user,
overrideAccess: false,
}),
payload.find({
collection: "faction-relation-entries",
limit: 500,
depth: 0,
sort: "-occurredAt",
pagination: false,
user,
overrideAccess: false,
}),
canViewUndiscoveredFactions(payload, user),
]);
const factions: RelationFactionRef[] = (factionsRes.docs as RawFaction[]).map((doc) => ({
id: doc.id,
name: doc.name ?? `Faction #${doc.id}`,
type: doc.type ?? "minorFaction",
discovered: doc.discovered !== false,
}));
const undiscoveredIds = new Set(
factions.filter((faction) => !faction.discovered).map((faction) => faction.id),
);
const displayRows: RelationLedgerRow[] = [];
const mathEntries: RelationEntryLike[] = [];
for (const doc of entriesRes.docs as RawEntry[]) {
const voided = doc.voided === true;
if (voided) continue;
// Hidden entries still move the score; they are censored by the
// collection's afterRead hook and excluded here from the list the players
// read, so the effect shows up while the cause does not.
const hidden = doc.hiddenFromPlayers === true;
const subjectId = relId(doc.subject);
const targetId = relId(doc.target);
if (subjectId == null || targetId == null) continue;
// Never let the ledger name a faction the reader has not discovered.
if (!canSeeUndiscovered && (undiscoveredIds.has(subjectId) || undiscoveredIds.has(targetId))) {
continue;
}
const occurredAt = doc.occurredAt ?? new Date(0).toISOString();
const entry: RelationEntryLike = {
subjectId,
targetId,
delta: doc.delta,
mutual: doc.mutual === true,
decays: doc.decays === true,
occurredAt,
voided,
};
mathEntries.push(entry);
if (!hidden) {
displayRows.push({
id: doc.id,
subjectId,
targetId,
delta: effectiveDelta(entry, now, halfLifeDays),
mutual: entry.mutual === true,
severity: doc.severity ?? "custom",
category: doc.category ?? "other",
summary: doc.summary ?? "",
occurredAt,
decays: entry.decays === true,
missionId: relId(doc.mission),
campaignId: relId(doc.campaign),
});
}
}
return {
factions,
rows: displayRows,
scores: directedScoreMap(mathEntries, now, halfLifeDays),
halfLifeDays,
};
}
export interface FactionRelationHistory {
inbound: RelationLedgerRow[];
outbound: RelationLedgerRow[];
}
/**
* Entries touching one faction, split by direction: what others did to this
* faction's standing with them, and what this faction's own events were.
* Mutual entries appear in both lists.
*/
export function historyFor(
context: RelationContext,
factionId: number,
): FactionRelationHistory {
const inbound: RelationLedgerRow[] = [];
const outbound: RelationLedgerRow[] = [];
for (const row of context.rows) {
if (row.subjectId === factionId) outbound.push(row);
if (row.targetId === factionId) inbound.push(row);
}
return { inbound, outbound };
}
/** Faction display names by id, for entry rendering. */
export function factionNameMap(context: RelationContext): Map<number, string> {
return new Map(context.factions.map((faction) => [faction.id, faction.name]));
}

View file

@ -0,0 +1,240 @@
/**
* Faction relation math (pure, client-safe).
*
* Pairwise faction attitudes are derived, never stored: every value rendered
* anywhere comes from summing the live entries of `faction-relation-entries`
* for one direction. This module holds the whole model so both read surfaces
* (the faction detail page and the relations matrix) agree by construction.
*
* Two axes that must not be confused:
* - `factions.reputation` is a faction's standing in the world at large. It is
* still hand-edited and does not appear here.
* - A relation entry moves ONE faction's attitude toward ONE other faction
* (or both, when the entry is flagged `mutual`).
*
* Deltas are signed: positive means the attitude improved (more favorable),
* negative means it worsened. Scores are clamped to +/-100 so the existing bar
* and badge treatments keep meaning what they meant.
*/
/** Magnitude applied by each severity tier. `custom` takes a typed number. */
export const RELATION_SEVERITY_DELTAS = {
minor: 5,
notable: 10,
major: 20,
decisive: 40,
} as const;
export type RelationSeverityTier = keyof typeof RELATION_SEVERITY_DELTAS;
export const RELATION_SEVERITIES = [
"minor",
"notable",
"major",
"decisive",
"custom",
] as const;
export type RelationSeverity = (typeof RELATION_SEVERITIES)[number];
export const RELATION_POLARITIES = ["beneficial", "detrimental"] as const;
export type RelationPolarity = (typeof RELATION_POLARITIES)[number];
/**
* What kind of event moved the score. Bookkeeping only: the category never
* changes the number, it exists so the ledger can be filtered and so the
* player-facing list can show a meaningful chip.
*/
export const RELATION_CATEGORIES = [
"aid",
"betrayal",
"combat",
"diplomacy",
"espionage",
"trade",
"other",
] as const;
export type RelationCategory = (typeof RELATION_CATEGORIES)[number];
export const RELATION_MIN = -100;
export const RELATION_MAX = 100;
/** Fallback when the GameRules global has no value set. */
export const DEFAULT_DECAY_HALF_LIFE_DAYS = 30;
/** The minimum shape the math needs. Payload documents are adapted to this. */
export interface RelationEntryLike {
subjectId: number;
targetId: number;
delta: number;
mutual?: boolean | null;
decays?: boolean | null;
occurredAt: string;
voided?: boolean | null;
}
export interface RelationBand {
key: "allied" | "friendly" | "neutral" | "tense" | "hostile";
label: string;
}
export const RELATION_BANDS: RelationBand[] = [
{ key: "allied", label: "Allied" },
{ key: "friendly", label: "Friendly" },
{ key: "neutral", label: "Neutral" },
{ key: "tense", label: "Tense" },
{ key: "hostile", label: "Hostile" },
];
/** Tailwind classes per band, shared so both surfaces look the same. */
export const RELATION_BAND_CLASSES: Record<RelationBand["key"], { bar: string; text: string }> =
{
allied: { bar: "bg-emerald-500", text: "text-emerald-400" },
friendly: { bar: "bg-green-500", text: "text-green-400" },
neutral: { bar: "bg-muted-foreground", text: "text-muted-foreground" },
tense: { bar: "bg-amber-500", text: "text-amber-400" },
hostile: { bar: "bg-red-500", text: "text-red-400" },
};
/** Clamp a computed score into the documented range. */
export function clampScore(value: number): number {
if (!Number.isFinite(value)) return 0;
return Math.max(RELATION_MIN, Math.min(RELATION_MAX, value));
}
/**
* Weight of a decaying entry: full until one half-life period has elapsed, then
* halved per completed period. Same shape as the zone-pressure decay so the two
* systems age the same way.
*/
export function decayWeight(
occurredAt: string,
now: Date,
halfLifeDays: number = DEFAULT_DECAY_HALF_LIFE_DAYS,
): number {
const period = Math.max(1, halfLifeDays);
const occurred = new Date(occurredAt).getTime();
if (!Number.isFinite(occurred)) return 1;
const elapsedDays = Math.max(0, (now.getTime() - occurred) / 86_400_000);
const periods = Math.floor(elapsedDays / period);
return 1 / 2 ** periods;
}
/**
* The amount one entry contributes to a score right now. Voided entries
* contribute nothing at all; non-decaying entries keep their full delta.
*/
export function effectiveDelta(
entry: RelationEntryLike,
now: Date,
halfLifeDays: number = DEFAULT_DECAY_HALF_LIFE_DAYS,
): number {
if (entry.voided) return 0;
if (!entry.decays) return entry.delta;
return entry.delta * decayWeight(entry.occurredAt, now, halfLifeDays);
}
/**
* How `subjectId` currently regards `targetId`, clamped to the documented
* range. Mutual entries count for both directions, so a shared event moves
* both attitudes by the same amount.
*/
export function directedScore(
entries: RelationEntryLike[],
subjectId: number,
targetId: number,
now: Date,
halfLifeDays: number = DEFAULT_DECAY_HALF_LIFE_DAYS,
): number {
if (subjectId === targetId) return 0;
let total = 0;
for (const entry of entries) {
const forward = entry.subjectId === subjectId && entry.targetId === targetId;
const backward =
entry.mutual === true && entry.subjectId === targetId && entry.targetId === subjectId;
if (!forward && !backward) continue;
total += effectiveDelta(entry, now, halfLifeDays);
}
return Math.round(clampScore(total) * 10) / 10;
}
/** Stable key for the directed pair map. */
export function pairKey(subjectId: number, targetId: number): string {
return `${subjectId}:${targetId}`;
}
/**
* Every directed score in one pass, keyed by `subjectId:targetId`. Used by the
* matrix so it never issues a query (or a nested loop) per pair.
*/
export function directedScoreMap(
entries: RelationEntryLike[],
now: Date,
halfLifeDays: number = DEFAULT_DECAY_HALF_LIFE_DAYS,
): Map<string, number> {
const totals = new Map<string, number>();
const add = (subjectId: number, targetId: number, amount: number) => {
if (subjectId === targetId) return;
const key = pairKey(subjectId, targetId);
totals.set(key, (totals.get(key) ?? 0) + amount);
};
for (const entry of entries) {
const amount = effectiveDelta(entry, now, halfLifeDays);
if (amount === 0) continue;
add(entry.subjectId, entry.targetId, amount);
if (entry.mutual === true) add(entry.targetId, entry.subjectId, amount);
}
for (const [key, value] of totals) {
totals.set(key, Math.round(clampScore(value) * 10) / 10);
}
return totals;
}
/** Band label for a score. Thresholds match the pre-ledger UI. */
export function relationBand(score: number): RelationBand {
if (score >= 50) return RELATION_BANDS[0];
if (score >= 20) return RELATION_BANDS[1];
if (score > -20) return RELATION_BANDS[2];
if (score > -50) return RELATION_BANDS[3];
return RELATION_BANDS[4];
}
/** Select options for the ledger form, with the magnitude spelled out. */
export function relationSeverityOptions(): { label: string; value: RelationSeverity }[] {
return [
{ label: `Minor (+/-${RELATION_SEVERITY_DELTAS.minor})`, value: "minor" },
{ label: `Notable (+/-${RELATION_SEVERITY_DELTAS.notable})`, value: "notable" },
{ label: `Major (+/-${RELATION_SEVERITY_DELTAS.major})`, value: "major" },
{ label: `Decisive (+/-${RELATION_SEVERITY_DELTAS.decisive})`, value: "decisive" },
{ label: "Custom (type a number)", value: "custom" },
];
}
const CATEGORY_LABELS: Record<RelationCategory, string> = {
aid: "Aid",
betrayal: "Betrayal",
combat: "Combat",
diplomacy: "Diplomacy",
espionage: "Espionage",
trade: "Trade",
other: "Other",
};
export function relationCategoryOptions(): { label: string; value: RelationCategory }[] {
return RELATION_CATEGORIES.map((value) => ({ label: CATEGORY_LABELS[value], value }));
}
export function relationCategoryLabel(value: string | null | undefined): string {
if (!value) return CATEGORY_LABELS.other;
return CATEGORY_LABELS[value as RelationCategory] ?? value;
}
/** Signed score for display: `+12`, `-100`, `0`. */
export function formatScore(score: number): string {
const rounded = Math.round(score * 10) / 10;
return rounded > 0 ? `+${rounded}` : `${rounded}`;
}

22
src/lib/lexical/editor.ts Normal file
View file

@ -0,0 +1,22 @@
/**
* The single factory behind every rich-text editor in the app. Use it for the global
* payload.config `editor` and for any field-scoped editor, so "full formatting including
* colours" is guaranteed everywhere instead of being assembled per-field by hand.
*
* Bundled features: Payload defaults + fixed toolbar + the shared text-colour palette
* (TextStateFeature) + the AI writing assistant (@ai-stack/payloadcms).
*/
import { PayloadAiPluginLexicalEditorFeature } from "@ai-stack/payloadcms";
import { FixedToolbarFeature, lexicalEditor, TextStateFeature } from "@payloadcms/richtext-lexical";
import { PTF_TEXT_STATE_CONFIG } from "./textState";
export function ptfLexicalEditor() {
return lexicalEditor({
features: ({ defaultFeatures }) => [
...defaultFeatures,
FixedToolbarFeature(),
TextStateFeature(PTF_TEXT_STATE_CONFIG),
PayloadAiPluginLexicalEditorFeature(),
],
});
}

View file

@ -0,0 +1,23 @@
import { createElement } from "react";
import type { JSXConvertersFunction } from "@payloadcms/richtext-lexical/react";
import { resolveLexicalTextColor } from "./textState";
/**
* Shared front-end colour converter for serialized Lexical.
*
* Payload's default text converter ignores both TextStateFeature state (`$: { color }`) and
* inline `style` colours, so authored colours would silently vanish on the public site. This
* wraps the default output in a styled span when a resolvable colour is present. Used by
* `RichTextView` on every field, including mission briefings.
*/
export const richTextConverters: JSXConvertersFunction = ({ defaultConverters }) => {
const base = defaultConverters.text;
return {
...defaultConverters,
text: (args) => {
const rendered = typeof base === "function" ? base(args) : null;
const color = resolveLexicalTextColor(args.node);
return color ? createElement("span", { style: { color } }, rendered) : rendered;
},
};
};

View file

@ -0,0 +1,34 @@
/**
* Shared colour support for every Lexical rich-text field.
*
* The palette originated as the Arma briefing colour set (its keys are persisted inside
* mission briefing JSON), which is why the source of truth lives in lib/intelligence/briefingSqf.
* Re-exported here so any rich-text surface edits AND renders the same palette: a colour picked
* in one field survives export to the front-end render path instead of silently dropping.
*/
import { BRIEFING_TEXT_COLORS, briefingTextColor } from "@/lib/intelligence/briefingSqf";
/**
* Config passed to TextStateFeature so admin editors get the colour dropdown.
* Kept as data (not inline at each editor) so every lexicalEditor built through
* ptfLexicalEditor shares identical state keys.
*/
export const PTF_TEXT_STATE_CONFIG: {
state: { color: Record<string, { css: { color: string }; label: string }> };
} = {
state: {
color: Object.fromEntries(
Object.entries(BRIEFING_TEXT_COLORS).map(([key, { hex, label }]) => [
key,
{ css: { color: hex }, label },
]),
),
},
};
/**
* Resolve a serialized Lexical text node to its display colour: inline `style` strings first
* (e.g. pasted colours), then the TextStateFeature state key, then named colours.
* Returns null when the node carries no colour.
*/
export const resolveLexicalTextColor = briefingTextColor;

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,86 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
/**
* Retire the hand-typed `factions.relationships[]` array.
*
* Pairwise faction attitudes are now derived from `faction_relation_entries`,
* so the old array is the only place those numbers could disagree with the
* ledger. Before the table goes away, every non-zero legacy value becomes an
* "opening balance" entry: it is dated at the owning faction's last update (not
* at migration time, so it does not look like a fresh event), carries the
* legacy note, and is a custom-delta entry because the old values were typed
* by hand rather than picked from a severity tier.
*
* Zero rows are skipped: the ledger treats "no entries" as the neutral default,
* so a stored 0 is the same thing with extra noise.
*/
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
DO $$
BEGIN
IF to_regclass('public.factions_relationships') IS NULL THEN
RETURN;
END IF;
INSERT INTO "faction_relation_entries" (
"subject_id",
"target_id",
"mutual",
"polarity",
"severity",
"delta",
"category",
"summary",
"notes",
"occurred_at",
"decays",
"hidden_from_players",
"voided"
)
SELECT
r."_parent_id",
r."target_faction_id",
false,
CASE WHEN r."value" > 0 THEN 'beneficial'::"public"."enum_faction_relation_entries_polarity"
ELSE 'detrimental'::"public"."enum_faction_relation_entries_polarity" END,
'custom'::"public"."enum_faction_relation_entries_severity",
r."value",
'other'::"public"."enum_faction_relation_entries_category",
'Opening balance carried over from the legacy relationship record.',
r."notes",
COALESCE(f."updated_at", now()),
false,
false,
false
FROM "factions_relationships" r
JOIN "factions" f ON f."id" = r."_parent_id"
WHERE r."value" <> 0
AND r."_parent_id" <> r."target_faction_id";
END $$;`)
await db.execute(sql`
DROP TABLE "factions_relationships" CASCADE;`)
}
/**
* The old array comes back empty on a down migration: the ledger is the source
* of truth now, so there is nothing to write back into it and inventing values
* from ledger sums would be lossy in the other direction.
*/
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
CREATE TABLE "factions_relationships" (
"_order" integer NOT NULL,
"_parent_id" integer NOT NULL,
"id" varchar PRIMARY KEY NOT NULL,
"target_faction_id" integer NOT NULL,
"value" numeric DEFAULT 0 NOT NULL,
"notes" varchar
);
ALTER TABLE "factions_relationships" ADD CONSTRAINT "factions_relationships_target_faction_id_factions_id_fk" FOREIGN KEY ("target_faction_id") REFERENCES "public"."factions"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "factions_relationships" ADD CONSTRAINT "factions_relationships_parent_id_fk" FOREIGN KEY ("_parent_id") REFERENCES "public"."factions"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "factions_relationships_order_idx" ON "factions_relationships" USING btree ("_order");
CREATE INDEX "factions_relationships_parent_id_idx" ON "factions_relationships" USING btree ("_parent_id");
CREATE INDEX "factions_relationships_target_faction_idx" ON "factions_relationships" USING btree ("target_faction_id");`)
}

View file

@ -159,6 +159,8 @@ import * as migration_20261101_210013_add_mission_command_links from './20261101
import * as migration_20261112_171955_add_npc_dialogue_generation_provenance from './20261112_171955_add_npc_dialogue_generation_provenance';
import * as migration_20261117_212337_add_faction_discovered_field from './20261117_212337_add_faction_discovered_field';
import * as migration_20261118_143000_add_wiki_pages_draft_and_created_by from './20261118_143000_add_wiki_pages_draft_and_created_by';
import * as migration_20261118_184813_add_faction_relation_entries from './20261118_184813_add_faction_relation_entries';
import * as migration_20261118_184851_drop_factions_relationships_array from './20261118_184851_drop_factions_relationships_array';
export const migrations = [
{
@ -959,11 +961,21 @@ export const migrations = [
{
up: migration_20261117_212337_add_faction_discovered_field.up,
down: migration_20261117_212337_add_faction_discovered_field.down,
name: '20261117_212337_add_faction_discovered_field'
name: '20261117_212337_add_faction_discovered_field',
},
{
up: migration_20261118_143000_add_wiki_pages_draft_and_created_by.up,
down: migration_20261118_143000_add_wiki_pages_draft_and_created_by.down,
name: '20261118_143000_add_wiki_pages_draft_and_created_by'
name: '20261118_143000_add_wiki_pages_draft_and_created_by',
},
{
up: migration_20261118_184813_add_faction_relation_entries.up,
down: migration_20261118_184813_add_faction_relation_entries.down,
name: '20261118_184813_add_faction_relation_entries',
},
{
up: migration_20261118_184851_drop_factions_relationships_array.up,
down: migration_20261118_184851_drop_factions_relationships_array.down,
name: '20261118_184851_drop_factions_relationships_array'
},
];

View file

@ -208,9 +208,14 @@ export const enum_game_event_logs_required_permissions = pgEnum(
"campaigns:manage",
"factions:create",
"factions:read",
"factions:view-undiscovered",
"factions:update",
"factions:delete",
"admin:factions:manage",
"faction-relation-entries:create",
"faction-relation-entries:read",
"faction-relation-entries:update",
"admin:faction-relation-entries:manage",
"technologies:create",
"technologies:read",
"technologies:update",
@ -773,9 +778,14 @@ export const enum_roles_permissions = pgEnum("enum_roles_permissions", [
"campaigns:manage",
"factions:create",
"factions:read",
"factions:view-undiscovered",
"factions:update",
"factions:delete",
"admin:factions:manage",
"faction-relation-entries:create",
"faction-relation-entries:read",
"faction-relation-entries:update",
"admin:faction-relation-entries:manage",
"technologies:create",
"technologies:read",
"technologies:update",
@ -1253,6 +1263,18 @@ export const enum_factions_type = pgEnum("enum_factions_type", [
"corporation",
"special",
]);
export const enum_faction_relation_entries_polarity = pgEnum(
"enum_faction_relation_entries_polarity",
["beneficial", "detrimental"],
);
export const enum_faction_relation_entries_severity = pgEnum(
"enum_faction_relation_entries_severity",
["minor", "notable", "major", "decisive", "custom"],
);
export const enum_faction_relation_entries_category = pgEnum(
"enum_faction_relation_entries_category",
["aid", "betrayal", "combat", "diplomacy", "espionage", "trade", "other"],
);
export const enum_technologies_approval_status = pgEnum("enum_technologies_approval_status", [
"in_progress",
"ready_for_review",
@ -2514,6 +2536,15 @@ export const npc_dialogues = pgTable(
entryGate_op: enum_npc_dialogues_entry_gate_op("entry_gate_op").default("is_true"),
entryGate_amount: numeric("entry_gate_amount", { mode: "number" }),
flowData: jsonb("flow_data").notNull(),
generation_model: varchar("generation_model"),
generation_promptVersion: varchar("generation_prompt_version"),
generation_attempts: numeric("generation_attempts", { mode: "number" }),
generation_generatedAt: timestamp("generation_generated_at", {
mode: "string",
withTimezone: true,
precision: 3,
}),
generation_brief: jsonb("generation_brief"),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
@ -4832,38 +4863,13 @@ export const campaigns = pgTable(
],
);
export const factions_relationships = pgTable(
"factions_relationships",
{
_order: integer("_order").notNull(),
_parentID: integer("_parent_id").notNull(),
id: varchar("id").primaryKey(),
targetFaction: integer("target_faction_id")
.notNull()
.references(() => factions.id, {
onDelete: "set null",
}),
value: numeric("value", { mode: "number" }).notNull().default(0),
notes: varchar("notes"),
},
(columns) => [
index("factions_relationships_order_idx").on(columns._order),
index("factions_relationships_parent_id_idx").on(columns._parentID),
index("factions_relationships_target_faction_idx").on(columns.targetFaction),
foreignKey({
columns: [columns["_parentID"]],
foreignColumns: [factions.id],
name: "factions_relationships_parent_id_fk",
}).onDelete("cascade"),
],
);
export const factions = pgTable(
"factions",
{
id: serial("id").primaryKey(),
name: varchar("name").notNull(),
type: enum_factions_type("type").notNull().default("minorFaction"),
discovered: boolean("discovered").default(true),
description: jsonb("description"),
reputation: numeric("reputation", { mode: "number" }).default(0),
playableFaction: boolean("playable_faction"),
@ -4880,6 +4886,7 @@ export const factions = pgTable(
},
(columns) => [
uniqueIndex("factions_name_idx").on(columns.name),
index("factions_discovered_idx").on(columns.discovered),
index("factions_cover_image_idx").on(columns.coverImage),
index("factions_updated_at_idx").on(columns.updatedAt),
index("factions_created_at_idx").on(columns.createdAt),
@ -4913,6 +4920,71 @@ export const factions_rels = pgTable(
],
);
export const faction_relation_entries = pgTable(
"faction_relation_entries",
{
id: serial("id").primaryKey(),
subject: integer("subject_id")
.notNull()
.references(() => factions.id, {
onDelete: "set null",
}),
target: integer("target_id")
.notNull()
.references(() => factions.id, {
onDelete: "set null",
}),
mutual: boolean("mutual").default(false),
polarity: enum_faction_relation_entries_polarity("polarity").notNull().default("detrimental"),
severity: enum_faction_relation_entries_severity("severity").notNull().default("notable"),
delta: numeric("delta", { mode: "number" }),
category: enum_faction_relation_entries_category("category").notNull().default("other"),
summary: varchar("summary").notNull(),
notes: varchar("notes"),
occurredAt: timestamp("occurred_at", {
mode: "string",
withTimezone: true,
precision: 3,
}).notNull(),
decays: boolean("decays").default(false),
hiddenFromPlayers: boolean("hidden_from_players").default(false),
mission: integer("mission_id").references(() => missions.id, {
onDelete: "set null",
}),
campaign: integer("campaign_id").references(() => campaigns.id, {
onDelete: "set null",
}),
voided: boolean("voided").default(false),
voidedAt: timestamp("voided_at", { mode: "string", withTimezone: true, precision: 3 }),
voidedBy: integer("voided_by_id").references(() => users.id, {
onDelete: "set null",
}),
voidedReason: varchar("voided_reason"),
recordedBy: integer("recorded_by_id").references(() => users.id, {
onDelete: "set null",
}),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
createdAt: timestamp("created_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
},
(columns) => [
index("faction_relation_entries_subject_idx").on(columns.subject),
index("faction_relation_entries_target_idx").on(columns.target),
index("faction_relation_entries_category_idx").on(columns.category),
index("faction_relation_entries_occurred_at_idx").on(columns.occurredAt),
index("faction_relation_entries_mission_idx").on(columns.mission),
index("faction_relation_entries_campaign_idx").on(columns.campaign),
index("faction_relation_entries_voided_idx").on(columns.voided),
index("faction_relation_entries_voided_by_idx").on(columns.voidedBy),
index("faction_relation_entries_recorded_by_idx").on(columns.recordedBy),
index("faction_relation_entries_updated_at_idx").on(columns.updatedAt),
index("faction_relation_entries_created_at_idx").on(columns.createdAt),
],
);
export const technologies_requirements_prerequisite_technologies = pgTable(
"technologies_requirements_prerequisite_technologies",
{
@ -7221,6 +7293,10 @@ export const wiki_pages = pgTable(
}),
curation_featured: boolean("curation_featured").default(false),
curation_featuredOrder: numeric("curation_featured_order", { mode: "number" }),
draft: boolean("draft").default(false),
createdBy: integer("created_by_id").references(() => users.id, {
onDelete: "set null",
}),
updatedAt: timestamp("updated_at", { mode: "string", withTimezone: true, precision: 3 })
.defaultNow()
.notNull(),
@ -7233,6 +7309,7 @@ export const wiki_pages = pgTable(
index("wiki_pages_category_idx").on(columns.category),
index("wiki_pages_locked_by_idx").on(columns.lockedBy),
index("wiki_pages_last_editor_idx").on(columns.lastEditor),
index("wiki_pages_created_by_idx").on(columns.createdBy),
index("wiki_pages_updated_at_idx").on(columns.updatedAt),
index("wiki_pages_created_at_idx").on(columns.createdAt),
],
@ -9288,6 +9365,10 @@ export const payload_mcp_api_keys = pgTable(
factions_create: boolean("factions_create").default(false),
factions_update: boolean("factions_update").default(false),
factions_delete: boolean("factions_delete").default(false),
factionRelationEntries_find: boolean("faction_relation_entries_find").default(false),
factionRelationEntries_create: boolean("faction_relation_entries_create").default(false),
factionRelationEntries_update: boolean("faction_relation_entries_update").default(false),
factionRelationEntries_delete: boolean("faction_relation_entries_delete").default(false),
technologies_find: boolean("technologies_find").default(false),
technologies_create: boolean("technologies_create").default(false),
technologies_update: boolean("technologies_update").default(false),
@ -9616,6 +9697,7 @@ export const payload_locked_documents_rels = pgTable(
"mission-command-linksID": integer("mission_command_links_id"),
campaignsID: integer("campaigns_id"),
factionsID: integer("factions_id"),
"faction-relation-entriesID": integer("faction_relation_entries_id"),
technologiesID: integer("technologies_id"),
"tech-categoriesID": integer("tech_categories_id"),
"tech-researchesID": integer("tech_researches_id"),
@ -9751,6 +9833,9 @@ export const payload_locked_documents_rels = pgTable(
),
index("payload_locked_documents_rels_campaigns_id_idx").on(columns.campaignsID),
index("payload_locked_documents_rels_factions_id_idx").on(columns.factionsID),
index("payload_locked_documents_rels_faction_relation_entries_i_idx").on(
columns["faction-relation-entriesID"],
),
index("payload_locked_documents_rels_technologies_id_idx").on(columns.technologiesID),
index("payload_locked_documents_rels_tech_categories_id_idx").on(columns["tech-categoriesID"]),
index("payload_locked_documents_rels_tech_researches_id_idx").on(columns["tech-researchesID"]),
@ -10056,6 +10141,11 @@ export const payload_locked_documents_rels = pgTable(
foreignColumns: [factions.id],
name: "payload_locked_documents_rels_factions_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["faction-relation-entriesID"]],
foreignColumns: [faction_relation_entries.id],
name: "payload_locked_documents_rels_faction_relation_entries_fk",
}).onDelete("cascade"),
foreignKey({
columns: [columns["technologiesID"]],
foreignColumns: [technologies.id],
@ -10501,6 +10591,9 @@ export const game_rules = pgTable(
interior_decayEnabled: boolean("interior_decay_enabled").default(false),
interior_decayMultiplier: numeric("interior_decay_multiplier", { mode: "number" }).default(1),
interior_assetOutputsEnabled: boolean("interior_asset_outputs_enabled").default(false),
factionRelations_decayHalfLifeDays: numeric("faction_relations_decay_half_life_days", {
mode: "number",
}).default(30),
zonePressureEnabled: boolean("zone_pressure_enabled").default(true),
statisticsEnabled: boolean("statistics_enabled").default(true),
helpdeskEnabled: boolean("helpdesk_enabled").default(true),
@ -11904,18 +11997,6 @@ export const relations_campaigns = relations(campaigns, ({ one }) => ({
relationName: "owner",
}),
}));
export const relations_factions_relationships = relations(factions_relationships, ({ one }) => ({
_parentID: one(factions, {
fields: [factions_relationships._parentID],
references: [factions.id],
relationName: "relationships",
}),
targetFaction: one(factions, {
fields: [factions_relationships.targetFaction],
references: [factions.id],
relationName: "targetFaction",
}),
}));
export const relations_factions_rels = relations(factions_rels, ({ one }) => ({
parent: one(factions, {
fields: [factions_rels.parent],
@ -11929,9 +12010,6 @@ export const relations_factions_rels = relations(factions_rels, ({ one }) => ({
}),
}));
export const relations_factions = relations(factions, ({ one, many }) => ({
relationships: many(factions_relationships, {
relationName: "relationships",
}),
coverImage: one(media, {
fields: [factions.coverImage],
references: [media.id],
@ -11941,6 +12019,41 @@ export const relations_factions = relations(factions, ({ one, many }) => ({
relationName: "_rels",
}),
}));
export const relations_faction_relation_entries = relations(
faction_relation_entries,
({ one }) => ({
subject: one(factions, {
fields: [faction_relation_entries.subject],
references: [factions.id],
relationName: "subject",
}),
target: one(factions, {
fields: [faction_relation_entries.target],
references: [factions.id],
relationName: "target",
}),
mission: one(missions, {
fields: [faction_relation_entries.mission],
references: [missions.id],
relationName: "mission",
}),
campaign: one(campaigns, {
fields: [faction_relation_entries.campaign],
references: [campaigns.id],
relationName: "campaign",
}),
voidedBy: one(users, {
fields: [faction_relation_entries.voidedBy],
references: [users.id],
relationName: "voidedBy",
}),
recordedBy: one(users, {
fields: [faction_relation_entries.recordedBy],
references: [users.id],
relationName: "recordedBy",
}),
}),
);
export const relations_technologies_requirements_prerequisite_technologies = relations(
technologies_requirements_prerequisite_technologies,
({ one }) => ({
@ -13134,6 +13247,11 @@ export const relations_wiki_pages = relations(wiki_pages, ({ one, many }) => ({
references: [users.id],
relationName: "lastEditor",
}),
createdBy: one(users, {
fields: [wiki_pages.createdBy],
references: [users.id],
relationName: "createdBy",
}),
_texts: many(wiki_pages_texts, {
relationName: "_texts",
}),
@ -14003,6 +14121,11 @@ export const relations_payload_locked_documents_rels = relations(
references: [factions.id],
relationName: "factions",
}),
"faction-relation-entriesID": one(faction_relation_entries, {
fields: [payload_locked_documents_rels["faction-relation-entriesID"]],
references: [faction_relation_entries.id],
relationName: "faction-relation-entries",
}),
technologiesID: one(technologies, {
fields: [payload_locked_documents_rels.technologiesID],
references: [technologies.id],
@ -14500,6 +14623,9 @@ type DatabaseSchema = {
enum_campaigns_status: typeof enum_campaigns_status;
enum_campaigns_campaign_mode: typeof enum_campaigns_campaign_mode;
enum_factions_type: typeof enum_factions_type;
enum_faction_relation_entries_polarity: typeof enum_faction_relation_entries_polarity;
enum_faction_relation_entries_severity: typeof enum_faction_relation_entries_severity;
enum_faction_relation_entries_category: typeof enum_faction_relation_entries_category;
enum_technologies_approval_status: typeof enum_technologies_approval_status;
enum_technologies_type: typeof enum_technologies_type;
enum_tech_researches_status: typeof enum_tech_researches_status;
@ -14676,9 +14802,9 @@ type DatabaseSchema = {
mission_ratings: typeof mission_ratings;
mission_command_links: typeof mission_command_links;
campaigns: typeof campaigns;
factions_relationships: typeof factions_relationships;
factions: typeof factions;
factions_rels: typeof factions_rels;
faction_relation_entries: typeof faction_relation_entries;
technologies_requirements_prerequisite_technologies: typeof technologies_requirements_prerequisite_technologies;
technologies_research_costs_resources: typeof technologies_research_costs_resources;
technologies: typeof technologies;
@ -14917,9 +15043,9 @@ type DatabaseSchema = {
relations_mission_ratings: typeof relations_mission_ratings;
relations_mission_command_links: typeof relations_mission_command_links;
relations_campaigns: typeof relations_campaigns;
relations_factions_relationships: typeof relations_factions_relationships;
relations_factions_rels: typeof relations_factions_rels;
relations_factions: typeof relations_factions;
relations_faction_relation_entries: typeof relations_faction_relation_entries;
relations_technologies_requirements_prerequisite_technologies: typeof relations_technologies_requirements_prerequisite_technologies;
relations_technologies_research_costs_resources: typeof relations_technologies_research_costs_resources;
relations_technologies_rels: typeof relations_technologies_rels;

View file

@ -107,6 +107,7 @@ export interface Config {
'mission-command-links': MissionCommandLink;
campaigns: Campaign;
factions: Faction;
'faction-relation-entries': FactionRelationEntry;
technologies: Technology;
'tech-categories': TechCategory;
'tech-researches': TechResearch;
@ -223,6 +224,7 @@ export interface Config {
'mission-command-links': MissionCommandLinksSelect<false> | MissionCommandLinksSelect<true>;
campaigns: CampaignsSelect<false> | CampaignsSelect<true>;
factions: FactionsSelect<false> | FactionsSelect<true>;
'faction-relation-entries': FactionRelationEntriesSelect<false> | FactionRelationEntriesSelect<true>;
technologies: TechnologiesSelect<false> | TechnologiesSelect<true>;
'tech-categories': TechCategoriesSelect<false> | TechCategoriesSelect<true>;
'tech-researches': TechResearchesSelect<false> | TechResearchesSelect<true>;
@ -746,6 +748,10 @@ export interface Role {
| 'factions:update'
| 'factions:delete'
| 'admin:factions:manage'
| 'faction-relation-entries:create'
| 'faction-relation-entries:read'
| 'faction-relation-entries:update'
| 'admin:faction-relation-entries:manage'
| 'technologies:create'
| 'technologies:read'
| 'technologies:update'
@ -2587,7 +2593,7 @@ export interface Faction {
*/
type: 'playerFaction' | 'majorFaction' | 'minorFaction' | 'corporation' | 'special';
/**
* Uncheck while players should not know this faction yet. The entry still appears in lists as UNDISCOVERED; name, description, standing, relationships, campaign links, cover image and the playable/starting flags are hidden from anyone without the View Undiscovered Factions permission.
* Uncheck while players should not know this faction yet. The entry still appears in lists as UNDISCOVERED; name, description, standing, campaign links, cover image and the playable/starting flags are hidden from anyone without the View Undiscovered Factions permission.
*/
discovered?: boolean | null;
description?: {
@ -2609,26 +2615,6 @@ export interface Faction {
* This faction's standing in the world, from -100 (reviled) to 100 (revered). 0 is neutral. Adjusted manually by admins/GMs as campaign events unfold.
*/
reputation?: number | null;
/**
* Pairwise standing between this faction and another faction, from -100 (hostile) to 100 (allied). 0 is neutral. One entry per counterpart faction.
*/
relationships?:
| {
/**
* The other faction in this pairwise relationship.
*/
targetFaction: number | Faction;
/**
* Standing from -100 (hostile) to 100 (allied). 0 is neutral.
*/
value: number;
/**
* Optional context for why this relationship stands where it does.
*/
notes?: string | null;
id?: string | null;
}[]
| null;
/**
* Whether or not this faction is playable. Some factions may be specifically intended to be unplayable based on narrative requirements.
*/
@ -3316,6 +3302,10 @@ export interface GameEventLog {
| 'factions:update'
| 'factions:delete'
| 'admin:factions:manage'
| 'faction-relation-entries:create'
| 'faction-relation-entries:read'
| 'faction-relation-entries:update'
| 'admin:faction-relation-entries:manage'
| 'technologies:create'
| 'technologies:read'
| 'technologies:update'
@ -5076,6 +5066,84 @@ export interface MissionCommandLink {
updatedAt: string;
createdAt: string;
}
/**
* Ledger behind every faction relationship score. Add an entry for each thing that changed one faction's attitude toward another; scores are computed from these rows, never typed in.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "faction-relation-entries".
*/
export interface FactionRelationEntry {
id: number;
/**
* The faction whose attitude changes.
*/
subject: number | Faction;
/**
* The faction the attitude is about.
*/
target: number | Faction;
/**
* Count this event for both directions (a shared battle, a treaty both sides signed). Leave unchecked when only the subject's attitude moves.
*/
mutual?: boolean | null;
/**
* Which way the attitude moves. Ignored for a custom delta, derived from its sign.
*/
polarity: 'beneficial' | 'detrimental';
/**
* How large the move is. The tier sets the delta; pick Custom to type an exact number.
*/
severity: 'minor' | 'notable' | 'major' | 'decisive' | 'custom';
/**
* Signed exact amount for a custom entry, -100 to 100. Positive improves the relationship.
*/
delta?: number | null;
/**
* What kind of event this was. Labels the entry; never changes the score.
*/
category: 'aid' | 'betrayal' | 'combat' | 'diplomacy' | 'espionage' | 'trade' | 'other';
/**
* One line the players will read, in plain language. This is the explanation attached to the score change.
*/
summary: string;
/**
* GM-only reasoning. Never shown to players, so it is safe for speculation and spoilers.
*/
notes?: string | null;
/**
* When it happened in the fiction. Drives the timeline order and, for decaying entries, how far it has faded.
*/
occurredAt: string;
/**
* Transient events fade: the delta halves per half-life (GameRules > Faction Relations). Leave unchecked for lasting shifts like a treaty or a betrayal.
*/
decays?: boolean | null;
/**
* Counts toward the score but never appears in the player-facing list. Use it when the effect is visible but the cause is not.
*/
hiddenFromPlayers?: boolean | null;
/**
* Optional: the operation that caused it.
*/
mission?: (number | null) | Mission;
/**
* Optional: the campaign arc it belongs to.
*/
campaign?: (number | null) | Campaign;
/**
* Excluded from every score and hidden from players.
*/
voided?: boolean | null;
voidedAt?: string | null;
voidedBy?: (number | null) | User;
/**
* Why it was voided.
*/
voidedReason?: string | null;
recordedBy?: (number | null) | User;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "tech-researches".
@ -8145,6 +8213,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
factionRelationEntries?: {
/**
* Allow clients to find faction-relation-entries.
*/
find?: boolean | null;
/**
* Allow clients to create faction-relation-entries.
*/
create?: boolean | null;
/**
* Allow clients to update faction-relation-entries.
*/
update?: boolean | null;
/**
* Allow clients to delete faction-relation-entries.
*/
delete?: boolean | null;
};
technologies?: {
/**
* Allow clients to find technologies.
@ -9394,6 +9480,10 @@ export interface PayloadLockedDocument {
relationTo: 'factions';
value: number | Faction;
} | null)
| ({
relationTo: 'faction-relation-entries';
value: number | FactionRelationEntry;
} | null)
| ({
relationTo: 'technologies';
value: number | Technology;
@ -10927,14 +11017,6 @@ export interface FactionsSelect<T extends boolean = true> {
discovered?: T;
description?: T;
reputation?: T;
relationships?:
| T
| {
targetFaction?: T;
value?: T;
notes?: T;
id?: T;
};
playableFaction?: T;
startingFaction?: T;
associatedCampaigns?: T;
@ -10942,6 +11024,33 @@ export interface FactionsSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "faction-relation-entries_select".
*/
export interface FactionRelationEntriesSelect<T extends boolean = true> {
subject?: T;
target?: T;
mutual?: T;
polarity?: T;
severity?: T;
delta?: T;
category?: T;
summary?: T;
notes?: T;
occurredAt?: T;
decays?: T;
hiddenFromPlayers?: T;
mission?: T;
campaign?: T;
voided?: T;
voidedAt?: T;
voidedBy?: T;
voidedReason?: T;
recordedBy?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "technologies_select".
@ -13069,6 +13178,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
factionRelationEntries?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
technologies?:
| T
| {
@ -13720,6 +13837,15 @@ export interface GameRule {
*/
assetOutputsEnabled?: boolean | null;
};
/**
* Tunables for the faction relations ledger (faction-relation-entries). Every pairwise score is computed on read from the ledger; nothing is stored on the faction records.
*/
factionRelations?: {
/**
* Half-life, in days, of a decaying relation entry. A decaying entry keeps full weight until one period elapses, then halves per completed period. Entries without the Decays flag never fade.
*/
decayHalfLifeDays?: number | null;
};
/**
* When off, the Zone Pressure feature is hidden from the Operations feed (the overview card and the AAR section).
*/
@ -13933,6 +14059,11 @@ export interface GameRulesSelect<T extends boolean = true> {
decayMultiplier?: T;
assetOutputsEnabled?: T;
};
factionRelations?:
| T
| {
decayHalfLifeDays?: T;
};
zonePressureEnabled?: T;
statisticsEnabled?: T;
helpdeskEnabled?: T;

View file

@ -1,6 +1,6 @@
import { migrations } from "./migrations";
import { postgresAdapter } from "@payloadcms/db-postgres";
import { FixedToolbarFeature, lexicalEditor } from "@payloadcms/richtext-lexical";
import { ptfLexicalEditor } from "@/lib/lexical/editor";
import { nodemailerAdapter } from "@payloadcms/email-nodemailer";
import path from "path";
import { buildConfig, formatLabels } from "payload";
@ -41,6 +41,7 @@ import { OperationReservations } from "@/collections/operations/OperationReserva
import { OperationReadiness } from "@/collections/operations/OperationReadiness";
import { ZonePressure } from "@/collections/operations/ZonePressure";
import { Factions } from "@/collections/intelligence/Factions";
import { FactionRelationEntries } from "@/collections/intelligence/FactionRelationEntries";
import { Assets } from "@/collections/logistics/Assets";
import { NarrativeEvents } from "@/collections/world/NarrativeEvents";
import { Resources } from "@/collections/logistics/Resources";
@ -112,7 +113,7 @@ import { PromotionNominations } from "@/collections/users/PromotionNominations";
import { LeadershipTransfers } from "@/collections/users/LeadershipTransfers";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { scopedAdminPageAccess } from "@/utils/access-control/divisionAccess";
import { payloadAiPlugin, PayloadAiPluginLexicalEditorFeature } from "@ai-stack/payloadcms";
import { payloadAiPlugin } from "@ai-stack/payloadcms";
import type { SeedPromptFunction } from "@ai-stack/payloadcms/types";
import { mcpPlugin } from "@payloadcms/plugin-mcp";
import { formBuilderPlugin } from "@payloadcms/plugin-form-builder";
@ -275,6 +276,7 @@ const collections = [
MissionCommandLinks,
Campaigns,
Factions,
FactionRelationEntries,
Technologies,
TechCategories,
TechResearches,
@ -511,11 +513,7 @@ export default buildConfig({
},
globals: [GameRules, Shims, MinigameRules, DiscordPresence],
collections: scopedCollections,
editor: lexicalEditor({
features: ({ defaultFeatures }) => {
return [...defaultFeatures, FixedToolbarFeature(), PayloadAiPluginLexicalEditorFeature()];
},
}),
editor: ptfLexicalEditor(),
secret: process.env.PAYLOAD_SECRET || "",
typescript: {
outputFile: path.resolve(dirname, "payload-types.ts"),

View file

@ -268,6 +268,15 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
{ value: "admin:factions:manage", label: "Manage Admin Page" },
],
},
{
group: "Faction Relations",
permissions: [
{ value: "faction-relation-entries:create", label: "Create" },
{ value: "faction-relation-entries:read", label: "Read" },
{ value: "faction-relation-entries:update", label: "Update" },
{ value: "admin:faction-relation-entries:manage", label: "Manage Admin Page" },
],
},
{
group: "Technologies",
permissions: [
@ -1012,6 +1021,10 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
"factions:update",
"factions:delete",
"admin:factions:manage",
"faction-relation-entries:create",
"faction-relation-entries:read",
"faction-relation-entries:update",
"admin:faction-relation-entries:manage",
"technologies:create",
"technologies:read",
"technologies:update",

View file

@ -2,7 +2,7 @@ import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { RichText } from "@payloadcms/richtext-lexical/react";
import { describe, expect, it } from "vitest";
import { briefingConverters } from "@/lib/intelligence/briefingConverters";
import { richTextConverters } from "@/lib/lexical/richTextConverters";
import {
briefingEntryHasContent,
briefingEntryToStructuredText,
@ -209,7 +209,7 @@ describe("briefing Structured Text conversion", () => {
};
const html = renderToStaticMarkup(
createElement(RichText, { data: data as never, converters: briefingConverters }),
createElement(RichText, { data: data as never, converters: richTextConverters }),
);
expect(html).toMatch(/<span style="color:\s*#ff5c5c"><strong>Red alert<\/strong><\/span>/);

View file

@ -127,7 +127,6 @@ describe("Faction discovery masking", () => {
description: DESCRIPTION,
playableFaction: true,
startingFaction: true,
relationships: [{ targetFaction: overtId, value: -80, notes: "Black ops history" }],
associatedCampaigns: [],
},
overrideAccess: true,
@ -173,7 +172,6 @@ describe("Faction discovery masking", () => {
expect(masked.name).toBe(UNDISCOVERED_FACTION_NAME);
expect(masked.description).toBeNull();
expect(masked.reputation).toBeNull();
expect(masked.relationships ?? []).toHaveLength(0);
expect(masked.playableFaction).toBe(false);
expect(masked.startingFaction).toBe(false);
expect(masked.coverImage ?? null).toBeNull();
@ -194,7 +192,6 @@ describe("Faction discovery masking", () => {
expect(faction.name).toBe(`${RUN}-Covert Directorate`);
expect(faction.reputation).toBe(64);
expect(faction.description).not.toBeNull();
expect(faction.relationships ?? []).toHaveLength(1);
expect(faction.playableFaction).toBe(true);
});
@ -249,7 +246,6 @@ describe("Faction discovery masking", () => {
discovered: false,
description: DESCRIPTION,
reputation: 90,
relationships: [{ id: "r1", targetFaction: 7, value: 10, notes: "n" }],
associatedCampaigns: [1, 2],
playableFaction: true,
startingFaction: true,
@ -263,7 +259,6 @@ describe("Faction discovery masking", () => {
discovered: false,
description: null,
reputation: null,
relationships: [],
associatedCampaigns: [],
playableFaction: false,
startingFaction: false,

View file

@ -0,0 +1,479 @@
import { getTestPayload } from "../helpers/get-test-payload";
import type { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Faction, FactionRelationEntry, Role, User } from "@/payload-types";
import { invalidatePermissionCache } from "@/utils/access-control/loadUserPermissions";
import {
directedScore,
directedScoreMap,
effectiveDelta,
relationBand,
RELATION_MIN,
RELATION_MAX,
type RelationEntryLike,
} from "@/lib/intelligence/factionRelations";
import { getRelationContext, historyFor } from "@/lib/intelligence/factionRelationLedger";
let payload: Payload;
const RUN = `frel-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const DAY = 86_400_000;
describe("Faction relation ledger", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
const factionIds: number[] = [];
const entryIds: number[] = [];
let reader: User;
let gm: User;
let revealer: User;
// One pair of factions per test keeps every score assertion independent of
// the entries other tests leave behind.
let a: number;
let b: number;
let secret: number;
const makeRole = async (label: string, extra: Partial<Role> = {}): Promise<Role> => {
const role = (await payload.create({
collection: "roles",
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, ...extra },
overrideAccess: true,
depth: 0,
})) as unknown as Role;
roleIds.push(role.id);
return role;
};
const makeUser = async (label: string, roleId: number): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roleDocs: [roleId],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const makeFaction = async (label: string, discovered = true): Promise<number> => {
const faction = (await payload.create({
collection: "factions",
data: { name: `${RUN}-${label}`, type: "minorFaction", discovered },
overrideAccess: true,
depth: 0,
})) as unknown as Faction;
factionIds.push(faction.id);
return faction.id;
};
const makeEntry = async (
data: Record<string, unknown>,
user: User = gm,
): Promise<FactionRelationEntry> => {
const entry = (await payload.create({
collection: "faction-relation-entries",
data: {
severity: "notable",
polarity: "detrimental",
category: "other",
summary: "A test event.",
occurredAt: new Date().toISOString(),
...data,
} as never,
user: user as never,
overrideAccess: false,
depth: 0,
})) as unknown as FactionRelationEntry;
entryIds.push(entry.id);
return entry;
};
/** Live entries for one direction, as the math expects them. */
const entriesFor = async (subjectId: number, targetId: number): Promise<RelationEntryLike[]> => {
const res = await payload.find({
collection: "faction-relation-entries",
where: {
and: [{ subject: { equals: subjectId } }, { target: { equals: targetId } }],
},
limit: 100,
depth: 0,
overrideAccess: true,
});
return (res.docs as FactionRelationEntry[]).map((doc) => ({
subjectId: doc.subject as number,
targetId: doc.target as number,
delta: doc.delta ?? 0,
mutual: doc.mutual,
decays: doc.decays,
occurredAt: doc.occurredAt,
voided: doc.voided,
}));
};
const readEntriesAs = async (
user: User | undefined,
where: Record<string, unknown>,
): Promise<FactionRelationEntry[]> => {
const res = await payload.find({
collection: "faction-relation-entries",
where: where as never,
limit: 100,
depth: 0,
user: user as never,
overrideAccess: false,
});
return res.docs as FactionRelationEntry[];
};
beforeAll(async () => {
payload = await getTestPayload();
invalidatePermissionCache();
const readerRole = await makeRole("reader", {
permissions: ["factions:read", "faction-relation-entries:read"],
});
const gmRole = await makeRole("gm", {
permissions: [
"factions:read",
"faction-relation-entries:read",
"faction-relation-entries:create",
"faction-relation-entries:update",
"admin:faction-relation-entries:manage",
],
});
const revealerRole = await makeRole("revealer", {
permissions: [
"factions:read",
"factions:view-undiscovered",
"faction-relation-entries:read",
],
});
reader = await makeUser("reader", readerRole.id);
gm = await makeUser("gm", gmRole.id);
revealer = await makeUser("revealer", revealerRole.id);
a = await makeFaction("Alpha");
b = await makeFaction("Bravo");
secret = await makeFaction("Covert", false);
}, TIMEOUT);
afterAll(async () => {
for (const id of entryIds) {
await payload
.delete({ collection: "faction-relation-entries", id, overrideAccess: true })
.catch(() => null);
}
for (const id of factionIds) {
await payload.delete({ collection: "factions", id, overrideAccess: true }).catch(() => null);
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => null);
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => null);
}
invalidatePermissionCache();
}, TIMEOUT);
describe("entry model", () => {
it("derives the delta from the severity tier and the polarity", async () => {
const major = await makeEntry({ subject: a, target: b, severity: "major" });
expect(major.delta).toBe(-20);
const decisive = await makeEntry({
subject: a,
target: b,
severity: "decisive",
polarity: "beneficial",
});
expect(decisive.delta).toBe(40);
});
it("keeps a custom delta and derives its polarity from the sign", async () => {
const gain = await makeEntry({
subject: a,
target: b,
severity: "custom",
delta: 7,
polarity: "detrimental",
});
expect(gain.delta).toBe(7);
expect(gain.polarity).toBe("beneficial");
const loss = await makeEntry({ subject: a, target: b, severity: "custom", delta: -3 });
expect(loss.delta).toBe(-3);
expect(loss.polarity).toBe("detrimental");
});
it("refuses a custom severity without a usable delta", async () => {
await expect(
makeEntry({ subject: a, target: b, severity: "custom", delta: 0 }),
).rejects.toThrow();
});
it("refuses an entry whose subject and target are the same faction", async () => {
await expect(makeEntry({ subject: a, target: a })).rejects.toThrow();
});
it("stamps who voided an entry and clears the stamps when unvoided", async () => {
const entry = await makeEntry({ subject: a, target: b });
const voided = (await payload.update({
collection: "faction-relation-entries",
id: entry.id,
data: { voided: true, voidedReason: "Never happened." },
user: gm as never,
overrideAccess: false,
depth: 0,
})) as unknown as FactionRelationEntry;
expect(voided.voided).toBe(true);
expect(voided.voidedAt).toBeTruthy();
expect(typeof voided.voidedBy).toBe("number");
expect(voided.recordedBy).toBe(gm.id);
const restored = (await payload.update({
collection: "faction-relation-entries",
id: entry.id,
data: { voided: false },
user: gm as never,
overrideAccess: false,
depth: 0,
})) as unknown as FactionRelationEntry;
expect(restored.voidedAt ?? null).toBeNull();
expect(restored.voidedBy ?? null).toBeNull();
expect(restored.voidedReason ?? null).toBeNull();
});
it("refuses deletion, so the ledger cannot lose history", async () => {
const entry = await makeEntry({ subject: a, target: b });
await expect(
payload.delete({
collection: "faction-relation-entries",
id: entry.id,
user: gm as never,
overrideAccess: false,
}),
).rejects.toThrow();
});
});
describe("score math", () => {
it("sums directed entries and ignores the opposite direction", () => {
const entries: RelationEntryLike[] = [
{
subjectId: 1,
targetId: 2,
delta: -20,
occurredAt: new Date().toISOString(),
},
{
subjectId: 2,
targetId: 1,
delta: 30,
occurredAt: new Date().toISOString(),
},
];
const now = new Date();
expect(directedScore(entries, 1, 2, now)).toBe(-20);
expect(directedScore(entries, 2, 1, now)).toBe(30);
});
it("counts a mutual entry in both directions", () => {
const now = new Date();
const entries: RelationEntryLike[] = [
{ subjectId: 1, targetId: 2, delta: 15, mutual: true, occurredAt: now.toISOString() },
];
expect(directedScore(entries, 1, 2, now)).toBe(15);
expect(directedScore(entries, 2, 1, now)).toBe(15);
});
it("excludes voided entries from every direction", () => {
const now = new Date();
const entries: RelationEntryLike[] = [
{
subjectId: 1,
targetId: 2,
delta: -60,
voided: true,
mutual: true,
occurredAt: now.toISOString(),
},
{ subjectId: 1, targetId: 2, delta: -10, occurredAt: now.toISOString() },
];
expect(directedScore(entries, 1, 2, now)).toBe(-10);
expect(directedScore(entries, 2, 1, now)).toBe(0);
});
it("clamps the sum to the documented range", () => {
const now = new Date();
const entries: RelationEntryLike[] = Array.from({ length: 5 }, () => ({
subjectId: 1,
targetId: 2,
delta: -40,
occurredAt: now.toISOString(),
}));
expect(directedScore(entries, 1, 2, now)).toBe(RELATION_MIN);
const positive = entries.map((entry) => ({ ...entry, delta: 40 }));
expect(directedScore(positive, 1, 2, now)).toBe(RELATION_MAX);
});
it("halves a decaying entry per half-life and leaves others untouched", () => {
const now = new Date("2026-03-01T00:00:00.000Z");
const fading: RelationEntryLike = {
subjectId: 1,
targetId: 2,
delta: 20,
decays: true,
occurredAt: new Date(now.getTime() - 31 * DAY).toISOString(),
};
const lasting: RelationEntryLike = {
subjectId: 1,
targetId: 2,
delta: 20,
occurredAt: new Date(now.getTime() - 400 * DAY).toISOString(),
};
expect(effectiveDelta(fading, now, 30)).toBe(10);
expect(effectiveDelta(lasting, now, 30)).toBe(20);
// Not a full period yet: decay has not started.
const fresh: RelationEntryLike = {
...fading,
occurredAt: new Date(now.getTime() - 5 * DAY).toISOString(),
};
expect(effectiveDelta(fresh, now, 30)).toBe(20);
});
it("maps every directed pair in one pass, mutuals included", () => {
const now = new Date();
const scores = directedScoreMap(
[
{ subjectId: 1, targetId: 2, delta: -25, occurredAt: now.toISOString() },
{
subjectId: 3,
targetId: 1,
delta: 10,
mutual: true,
occurredAt: now.toISOString(),
},
],
now,
);
expect(scores.get("1:2")).toBe(-25);
expect(scores.get("3:1")).toBe(10);
expect(scores.get("1:3")).toBe(10);
expect(scores.get("2:1")).toBeUndefined();
});
it("labels bands on the thresholds the UI has always used", () => {
expect(relationBand(50).label).toBe("Allied");
expect(relationBand(20).label).toBe("Friendly");
expect(relationBand(0).label).toBe("Neutral");
expect(relationBand(-20).label).toBe("Tense");
expect(relationBand(-50).label).toBe("Hostile");
});
});
describe("visibility", () => {
it("hides a voided entry from a plain reader but keeps it for a manager", async () => {
const entry = await makeEntry({ subject: a, target: b, voided: true });
const asReader = await readEntriesAs(reader, { id: { equals: entry.id } });
expect(asReader).toHaveLength(0);
const asManager = await readEntriesAs(gm, { id: { equals: entry.id } });
expect(asManager).toHaveLength(1);
});
it("still counts a hidden entry while censoring what explains it", async () => {
const hidden = await makeEntry({
subject: a,
target: b,
severity: "major",
hiddenFromPlayers: true,
summary: "Worldmark paid us off.",
notes: "Players must not learn this yet.",
});
const asReader = await readEntriesAs(reader, { id: { equals: hidden.id } });
expect(asReader).toHaveLength(1);
expect(asReader[0].delta).toBe(-20);
expect(asReader[0].summary).toBe("");
expect(asReader[0].notes ?? null).toBeNull();
const asManager = await readEntriesAs(gm, { id: { equals: hidden.id } });
expect(asManager[0].summary).toBe("Worldmark paid us off.");
expect(asManager[0].notes).toBe("Players must not learn this yet.");
});
it("never exposes GM notes on an ordinary entry", async () => {
const entry = await makeEntry({
subject: a,
target: b,
summary: "We helped them.",
notes: "They do not know why yet.",
});
const asReader = await readEntriesAs(reader, { id: { equals: entry.id } });
expect(asReader).toHaveLength(1);
expect(asReader[0].summary).toBe("We helped them.");
expect(asReader[0].notes ?? null).toBeNull();
expect(asReader[0].recordedBy ?? null).toBeNull();
const asManager = await readEntriesAs(gm, { id: { equals: entry.id } });
expect(asManager[0].notes).toBe("They do not know why yet.");
expect(asManager[0].recordedBy).toBe(gm.id);
});
it("gives a player the same score a manager computes from a hidden entry", async () => {
const subject = await makeFaction("HiddenSubject");
const target = await makeFaction("HiddenTarget");
await makeEntry({ subject, target, severity: "major" });
await makeEntry({ subject, target, severity: "decisive", hiddenFromPlayers: true });
const asReader = await getRelationContext(payload, reader as never);
const asManager = await getRelationContext(payload, gm as never);
expect(asReader.scores.get(`${subject}:${target}`)).toBe(-60);
expect(asManager.scores.get(`${subject}:${target}`)).toBe(-60);
// The hidden row moves the number but never appears in the timeline.
expect(asManager.rows.filter((row) => row.subjectId === subject)).toHaveLength(1);
expect(asReader.rows.filter((row) => row.subjectId === subject)).toHaveLength(1);
});
it("keeps entries naming an undiscovered faction away from plain readers", async () => {
const visible = await makeFaction("Discovered");
await makeEntry({ subject: visible, target: secret, severity: "major" });
const asReader = await getRelationContext(payload, reader as never);
expect(asReader.scores.get(`${visible}:${secret}`)).toBeUndefined();
const asRevealer = await getRelationContext(payload, revealer as never);
expect(asRevealer.scores.get(`${visible}:${secret}`)).toBe(-20);
});
it("splits a faction's history into inbound and outbound rows", async () => {
const subject = await makeFaction("HistSubject");
const target = await makeFaction("HistTarget");
await makeEntry({ subject, target, severity: "notable" });
await makeEntry({ subject: target, target: subject, severity: "major", polarity: "beneficial" });
const context = await getRelationContext(payload, gm as never);
const history = historyFor(context, subject);
expect(history.outbound).toHaveLength(1);
expect(history.inbound).toHaveLength(1);
expect(history.outbound[0].delta).toBe(-10);
expect(history.inbound[0].delta).toBe(20);
});
});
});

View file

@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { RichTextView } from "@/components/frontend/RichTextView";
/**
* Guards the shared Lexical front-end render path: the .lexical-content typography hook,
* every structural node type, and author-chosen colours (inline `style`, top-level `color`,
* or TextStateFeature `$` state) must survive into rendered HTML. Payload's default JSX
* converters drop the colour keys, so this component exists only for that; if it ever regresses
* to plain <RichText>, colours silently disappear on every field again.
*/
const richText = (nodes: unknown[]) => ({ root: { type: "root", children: nodes } });
const paragraph = (...children: unknown[]) => ({ type: "paragraph", children });
const heading = (tag: string, text: string) => ({ type: "heading", tag, children: [{ type: "text", text }] });
// Payload's default JSX converter derives the marker class from `listType`
const bullet = (tag: "ul" | "ol", listType: string, ...items: string[]) => ({
type: "list",
tag,
listType,
children: items.map((t) => ({ type: "listitem", value: 1, children: [{ type: "text", text: t }] })),
});
const quote = (...children: unknown[]) => ({ type: "quote", children });
const describeRender = (doc: unknown) => renderToStaticMarkup(createElement(RichTextView, { data: doc as never }));
describe("RichTextView shared render path", () => {
it("applies .lexical-content exactly once and drops the default payload-richtext wrapper", () => {
const html = describeRender(richText([paragraph({ type: "text", text: "hi" })]));
expect(html).toContain('class="lexical-content"');
expect(html.match(/lexical-content/g)).toHaveLength(1);
expect(html).not.toContain("payload-richtext");
});
it("keeps structural elements intact instead of flattening them to spans", () => {
const html = describeRender(
richText([
heading("h2", "Title"),
paragraph(
{ type: "text", format: 1, text: "strong bit" },
{ type: "text", format: 2, text: " italic" },
),
bullet("ul", "bullet", "alpha", "beta"),
bullet("ol", "number", "one"),
quote(paragraph({ type: "text", text: "cited" })),
{ type: "horizontalrule" },
]),
);
for (const fragment of [
"<h2>Title</h2>",
"<strong>strong bit</strong>",
"<em> italic</em>",
"<ul",
"alpha",
"beta",
"<ol",
"<blockquote>",
"<hr/>",
]) {
expect(html).toContain(fragment);
}
});
it("renders the colour stored as an inline style string on a text node", () => {
const html = describeRender(richText([paragraph({ type: "text", style: "color:#4ade80;", text: "green" })]));
expect(html).toContain('style="color:#4ade80"');
});
it("maps palette keys from `$` state and `color` to the shared briefing hexes", () => {
for (const node of [
{ type: "text", $: { color: "blue" }, text: "s" },
{ type: "text", color: "blue", text: "c" },
]) {
const html = describeRender(richText([paragraph(node)]));
expect(html).toContain('style="color:#60a5fa"');
}
});
it("leaves uncoloured and unknown-colour nodes without an injected style span", () => {
const html = describeRender(
richText([
paragraph(
{ type: "text", format: 1, text: "plain strong" },
{ type: "text", style: "color:magenta;", text: " not-in-palette" },
),
]),
);
expect(html).not.toMatch(/style=/);
// magenta is a named colour outside our palette and must be dropped rather than emitted raw
expect(html).toContain("not-in-palette");
});
});

View file

@ -0,0 +1,79 @@
// @vitest-environment jsdom
import { createElement, createRef } from "react";
import { cleanup, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WikiEditorBody } from "@/components/frontend/wiki/WikiEditorBody";
import { WIKI_EDITOR_METRICS, WIKI_EDITOR_SCROLLBAR_NONE } from "@/components/frontend/wiki/editorMetrics";
vi.mock("@/app/(frontend)/wiki/actions", () => ({
uploadWikiImage: vi.fn(),
}));
afterEach(cleanup);
function tokens(className: string | null): Set<string> {
return new Set((className ?? "").trim().split(/\s+/).filter(Boolean));
}
describe("wiki editor overlay/textarea parity", () => {
const body = "# Heading\n\nSome long line ".repeat(10);
function renderEditor() {
const ref = createRef<HTMLTextAreaElement>();
const { container } = render(
createElement(WikiEditorBody, {
body,
bodyRef: ref,
existingPages: [],
linkDialogOpen: false,
onBodyChange: () => {},
onLinkDialogChange: () => {},
pending: false,
templates: {},
}),
);
const textarea = container.querySelector("textarea#wiki-body");
const overlayInner = container.querySelector("div.pointer-events-none > div");
return { textarea, overlayInner };
}
it("renders both layers", () => {
const { textarea, overlayInner } = renderEditor();
expect(textarea).not.toBeNull();
expect(overlayInner).not.toBeNull();
});
it("shares identical padding/typography classes between textarea and overlay", () => {
const { textarea, overlayInner } = renderEditor();
const shared = tokens(WIKI_EDITOR_METRICS);
expect(shared.size).toBeGreaterThan(0);
for (const layer of [textarea, overlayInner]) {
const cls = tokens(layer?.className ?? null);
for (const metric of shared) {
expect(cls.has(metric), `${layer?.id ?? "overlay"} missing "${metric}"`).toBe(true);
}
}
});
it("keeps the overlay borderless (a border shrinks its width and desyncs wrapping)", () => {
const { overlayInner } = renderEditor();
const cls = tokens(overlayInner?.className ?? "");
for (const clsName of cls) expect(clsName).not.toMatch(/^border/);
});
it("hides the textarea scrollbar so its gutter never shrinks the content width", () => {
const { textarea } = renderEditor();
const cls = tokens(textarea?.className ?? "");
for (const token of tokens(WIKI_EDITOR_SCROLLBAR_NONE)) {
expect(cls.has(token), `textarea missing "${token}"`).toBe(true);
}
});
it("keeps the textarea flush and borderless inside the shared wrapper", () => {
const { textarea } = renderEditor();
const cls = tokens(textarea?.className ?? "");
for (const clsName of ["absolute", "inset-0", "border-0"]) {
expect(cls.has(clsName), `textarea missing "${clsName}"`).toBe(true);
}
});
});

View file

@ -114,7 +114,7 @@ describe("world map screen eligibility", () => {
it("persists the optional intel fields", async () => {
const faction = (await payload.create({
collection: "factions",
data: { name: `${RUN} Faction`, type: "minorFaction", reputation: 0, relationships: [] },
data: { name: `${RUN} Faction`, type: "minorFaction", reputation: 0 },
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };