1
0
Fork 0

feat(intelligence): export mission briefings to SQF

Add a briefing export dialog with a diary script and a structured text array. Convert Lexical formatting, including bold, code, underline, colors, headings, lists, and quotes, into Arma Structured Text. Scope the shared color palette to the briefing editors and render colors on the mission page.
This commit is contained in:
Jason Fraley 2026-10-20 14:22:17 -04:00
parent 3c774279aa
commit f62f5265fa
11 changed files with 966 additions and 33 deletions

View file

@ -512,7 +512,10 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
missionId={mission.id}
/>
<MissionBriefingSection briefing={mission.briefing ?? null} />
<MissionBriefingSection
briefing={mission.briefing ?? null}
missionName={mission.name}
/>
<MissionObjectives
objectives={objectives}

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'
@ -59,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,

View file

@ -1,14 +1,14 @@
import type { CollectionConfig, Payload, PayloadRequest, Where } from "payload";
import { FixedToolbarFeature, lexicalEditor, TextStateFeature } from "@payloadcms/richtext-lexical";
import { PayloadAiPluginLexicalEditorFeature } from "@ai-stack/payloadcms";
import {
requirePermission,
hasPermission,
isSuperuser,
} from "@/utils/access-control/hasPermission";
import {
expireQueuedEntriesForMission,
grantQueuedEntriesForMission,
} from "@/lib/contributions";
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;
@ -87,6 +87,29 @@ async function missionReadFilter(req: PayloadRequest): Promise<boolean | Where>
return { or };
}
/**
* 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.
*/
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(),
],
});
export const Missions: CollectionConfig = {
slug: "missions",
admin: {
@ -655,6 +678,7 @@ export const Missions: CollectionConfig = {
name: "details",
type: "richText",
required: true,
editor: briefingDetailsEditor,
},
],
defaultValue: [

View file

@ -0,0 +1,131 @@
"use client";
import { useMemo, useState } from "react";
import { ClipboardCopyIcon } from "lucide-react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Textarea } from "@/components/ui/textarea";
import {
briefingEntryHasContent,
briefingToDiarySqf,
briefingToStructuredTextSqf,
type BriefingSqfEntry,
} from "@/lib/intelligence/briefingSqf";
type ExportMode = "script" | "text";
interface BriefingSqfExportProps {
entries: BriefingSqfEntry[];
missionName?: string | null;
/** "all" is the header button; "entry" is the icon button on one card. */
scope?: "all" | "entry";
}
export function BriefingSqfExport({ entries, missionName, scope = "all" }: BriefingSqfExportProps) {
const [mode, setMode] = useState<ExportMode>("script");
const exportable = useMemo(() => entries.filter(briefingEntryHasContent), [entries]);
const preview = useMemo(
() =>
mode === "script"
? briefingToDiarySqf(exportable, { missionName })
: briefingToStructuredTextSqf(exportable),
[exportable, missionName, mode],
);
const disabled = exportable.length === 0;
const count = exportable.length;
const copy = async () => {
try {
await navigator.clipboard.writeText(preview);
toast.success(`Copied ${count} briefing ${count === 1 ? "section" : "sections"} as SQF.`, {
description:
mode === "script"
? "Paste into the debug console or an init script."
: "Structured Text bodies for your own diary or hint code.",
});
} catch {
toast.error("Clipboard access was blocked by the browser.");
}
};
return (
<Dialog>
<DialogTrigger asChild>
{scope === "entry" ? (
<Button
variant="ghost"
size="icon"
className="size-7 shrink-0"
disabled={disabled}
title="Export this briefing entry as SQF"
aria-label="Export this briefing entry as SQF"
>
<ClipboardCopyIcon className="size-3.5" />
</Button>
) : (
<Button
variant="outline"
size="sm"
className="h-7 gap-1.5 px-2 text-xs"
disabled={disabled}
title="Copy this briefing as Arma 3 Structured Text"
>
<ClipboardCopyIcon className="size-3.5" />
SQF
</Button>
)}
</DialogTrigger>
<DialogContent className="sm:max-w-3xl">
<DialogHeader>
<DialogTitle>Export briefing to SQF</DialogTitle>
<DialogDescription>
{count} {count === 1 ? "section" : "sections"}
{missionName ? ` from "${missionName}"` : ""}. Bold, color, headings, lists, and quotes
are preserved where Arma 3 Structured Text supports them.
</DialogDescription>
</DialogHeader>
<Tabs value={mode} onValueChange={(value) => setMode(value as ExportMode)}>
<TabsList>
<TabsTrigger value="script">Diary script</TabsTrigger>
<TabsTrigger value="text">Structured text</TabsTrigger>
</TabsList>
</Tabs>
<Textarea
readOnly
value={preview}
spellCheck={false}
wrap="off"
aria-label="SQF preview"
className="h-72 resize-none font-mono text-xs leading-relaxed"
/>
<p className="text-xs text-muted-foreground">
Italic, strikethrough, subscript, and superscript have no Structured Text equivalent and
export as plain text. Images and links become readable placeholders.
</p>
<DialogFooter>
<Button onClick={() => void copy()}>
<ClipboardCopyIcon className="size-4" />
Copy SQF
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View file

@ -149,12 +149,15 @@ export interface LexicalRichTextEditorProps {
onChange: (json: LexicalJson) => void;
placeholder?: string;
disabled?: boolean;
/** Briefings only: adds the color palette used by the SQF exporter. */
showTextColor?: boolean;
}
export function LexicalRichTextEditor({
disabled = false,
onChange,
placeholder = "Write the operation details...",
showTextColor = false,
value,
}: LexicalRichTextEditorProps) {
const lastEmittedJsonRef = useRef<string | null>(null);
@ -175,7 +178,7 @@ export function LexicalRichTextEditor({
disabled && "cursor-not-allowed opacity-60",
)}
>
<LexicalRichTextToolbar disabled={disabled} />
<LexicalRichTextToolbar disabled={disabled} showTextColor={showTextColor} />
<div className="relative min-h-[120px]">
<RichTextPlugin
contentEditable={

View file

@ -1,10 +1,11 @@
"use client";
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import {
$createParagraphNode,
$getSelection,
$isRangeSelection,
$setSelection,
COMMAND_PRIORITY_LOW,
FORMAT_TEXT_COMMAND,
mergeRegister,
@ -19,7 +20,7 @@ import {
$isHeadingNode,
$isQuoteNode,
} from "@lexical/rich-text";
import { $setBlocksType } from "@lexical/selection";
import { $patchStyleText, $setBlocksType } from "@lexical/selection";
import {
$isListNode,
INSERT_CHECK_LIST_COMMAND,
@ -35,6 +36,7 @@ import {
ListChecks,
ListOrdered,
Minus,
Palette,
Quote,
Strikethrough,
Underline,
@ -42,7 +44,17 @@ import {
} from "lucide-react";
import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";
import { INSERT_HORIZONTAL_RULE_COMMAND } from "@lexical/extension";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Separator } from "@/components/ui/separator";
import { BRIEFING_TEXT_COLORS } from "@/lib/intelligence/briefingSqf";
import { LexicalRichTextToolbarButton } from "./LexicalRichTextToolbarButton";
type BlockType = "paragraph" | "h2" | "h3" | "h4" | "quote";
@ -86,11 +98,15 @@ function getListType(selection: RangeSelection): ListType | null {
return null;
}
function readToolbarState(editor: LexicalEditor): ToolbarState {
function readToolbarState(
editor: LexicalEditor,
selectionRef?: { current: RangeSelection | null },
): ToolbarState {
let state = DEFAULT_TOOLBAR_STATE;
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) return;
if (selectionRef) selectionRef.current = selection.clone();
state = {
blockType: getBlockType(selection),
bold: selection.hasFormat("bold"),
@ -104,12 +120,19 @@ function readToolbarState(editor: LexicalEditor): ToolbarState {
return state;
}
export function LexicalRichTextToolbar({ disabled }: { disabled: boolean }) {
export function LexicalRichTextToolbar({
disabled,
showTextColor = false,
}: {
disabled: boolean;
showTextColor?: boolean;
}) {
const [editor] = useLexicalComposerContext();
const [state, setState] = useState(DEFAULT_TOOLBAR_STATE);
const colorSelectionRef = useRef<RangeSelection | null>(null);
useEffect(() => {
const update = () => setState(readToolbarState(editor));
const update = () => setState(readToolbarState(editor, colorSelectionRef));
update();
return mergeRegister(
editor.registerUpdateListener(update),
@ -124,6 +147,19 @@ export function LexicalRichTextToolbar({ disabled }: { disabled: boolean }) {
);
}, [editor]);
function setTextColor(color: string | null) {
editor.update(() => {
let selection = $getSelection();
if (!$isRangeSelection(selection) && colorSelectionRef.current) {
$setSelection(colorSelectionRef.current);
selection = $getSelection();
}
if (!$isRangeSelection(selection)) return;
$patchStyleText(selection, { color });
colorSelectionRef.current = selection.clone();
});
}
function formatText(format: "bold" | "italic" | "underline" | "strikethrough" | "code") {
editor.dispatchCommand(FORMAT_TEXT_COMMAND, format);
}
@ -215,6 +251,52 @@ export function LexicalRichTextToolbar({ disabled }: { disabled: boolean }) {
{inlineButtons.map((button) => (
<LexicalRichTextToolbarButton key={button.label} {...button} disabled={disabled} />
))}
{showTextColor && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
type="button"
size="sm"
variant="outline"
className="size-8 p-0"
disabled={disabled}
aria-label="Text color"
title="Text color"
>
<Palette aria-hidden="true" />
<span className="sr-only">Text color</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="start"
className="max-h-80 w-44 overflow-y-auto"
onCloseAutoFocus={(event) => {
event.preventDefault();
requestAnimationFrame(() => editor.focus());
}}
>
<DropdownMenuLabel>Text color</DropdownMenuLabel>
<DropdownMenuItem onSelect={() => setTextColor(null)}>
<span
className="size-3 rounded-full border border-border bg-background"
aria-hidden="true"
/>
Default
</DropdownMenuItem>
<DropdownMenuSeparator />
{Object.entries(BRIEFING_TEXT_COLORS).map(([key, color]) => (
<DropdownMenuItem key={key} onSelect={() => setTextColor(color.hex)}>
<span
className="size-3 rounded-full"
style={{ backgroundColor: color.hex }}
aria-hidden="true"
/>
{color.label}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
)}
</div>
<Separator orientation="vertical" className="mx-1 hidden h-6 sm:block" />
<div className="flex flex-wrap items-center gap-1" aria-label="Block style">

View file

@ -1,31 +1,23 @@
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 { BriefingSqfExport } from "./BriefingSqfExport";
type BriefingDetails = ComponentProps<typeof RichText>["data"];
interface BriefingEntry {
sectionName: string;
details: {
root: {
type: string;
children: {
type: any;
version: number;
[k: string]: unknown;
}[];
direction: ("ltr" | "rtl") | null;
format: "left" | "start" | "center" | "right" | "end" | "justify" | "";
indent: number;
version: number;
};
[k: string]: unknown;
};
details: BriefingDetails | null;
}
interface MissionBriefingSectionProps {
briefing: BriefingEntry[] | null;
missionName?: string | null;
}
export function MissionBriefingSection({ briefing }: MissionBriefingSectionProps) {
export function MissionBriefingSection({ briefing, missionName }: MissionBriefingSectionProps) {
if (!briefing || briefing.length === 0) {
return (
<Item variant="outline">
@ -44,19 +36,27 @@ export function MissionBriefingSection({ briefing }: MissionBriefingSectionProps
return (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<FileTextIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Briefing
</h2>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<FileTextIcon className="size-4 text-muted-foreground" />
<h2 className="text-sm font-semibold uppercase tracking-wider text-muted-foreground">
Briefing
</h2>
</div>
<BriefingSqfExport entries={briefing} missionName={missionName} />
</div>
{briefing.map((entry, index) => (
<Item key={index} variant="outline">
<ItemHeader>
<ItemTitle>{entry.sectionName}</ItemTitle>
<BriefingSqfExport entries={[entry]} missionName={missionName} scope="entry" />
</ItemHeader>
<ItemContent className="flex flex-col justify-start items-start lexical-content">
<RichText data={entry.details} />
{entry.details ? (
<RichText data={entry.details} converters={briefingConverters} />
) : (
<p className="text-sm text-muted-foreground italic">No details.</p>
)}
</ItemContent>
</Item>
))}

View file

@ -102,6 +102,7 @@ export function SideOpNarrativeFields({ value, onChange }: SideOpNarrativeFields
setBriefing(next);
}}
placeholder="Briefing text for this section"
showTextColor
/>
</div>
))}

View file

@ -0,0 +1,17 @@
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

@ -0,0 +1,420 @@
/**
* Converts Payload Lexical briefing content into Arma 3 Structured Text and
* ready-to-paste SQF. Pure module (client-safe, no Payload imports).
*
* Formatting map:
* bold -> <t font='PuristaBold'>
* underline -> <t underline='1'>
* inline code -> <t font='EtelkaMonospacePro'>
* color -> <t color='#RRGGBB'>
* italic -> plain text (Arma 3 ships no italic face)
* strike -> plain text (no Structured Text equivalent)
* sub/sup -> plain text (no Structured Text equivalent)
*
* Blocks: paragraphs and headings, ordered/bullet/check lists (including
* nesting), quotes, horizontal rules, and block alignment/indent. Images and
* links become readable placeholders rather than tags Arma cannot load.
*/
export interface BriefingSqfEntry {
sectionName: string;
details: unknown;
}
export interface BriefingTextColor {
hex: string;
label: string;
}
/**
* Palette shared by the Lexical editor (TextStateFeature) and the exporter.
* Keep the keys stable: they are persisted inside briefing JSON.
*/
export const BRIEFING_TEXT_COLORS = {
red: { hex: "#ff5c5c", label: "Red" },
orange: { hex: "#ff9f43", label: "Orange" },
yellow: { hex: "#ffd93d", label: "Yellow" },
green: { hex: "#4ade80", label: "Green" },
blue: { hex: "#60a5fa", label: "Blue" },
purple: { hex: "#c084fc", label: "Purple" },
pink: { hex: "#f472b6", label: "Pink" },
gray: { hex: "#9ca3af", label: "Gray" },
white: { hex: "#ffffff", label: "White" },
} as const satisfies Record<string, BriefingTextColor>;
type BriefingTextColorKey = keyof typeof BRIEFING_TEXT_COLORS;
interface LexicalNode {
type?: string;
text?: unknown;
children?: unknown;
format?: unknown;
indent?: unknown;
listType?: unknown;
tag?: unknown;
start?: unknown;
checked?: unknown;
color?: unknown;
style?: unknown;
fields?: unknown;
url?: unknown;
value?: unknown;
relationTo?: unknown;
[key: string]: unknown;
}
const FORMAT_BOLD = 1;
const FORMAT_UNDERLINE = 8;
const FORMAT_CODE = 16;
const MUTED = "#9ca3af";
const RULE = "#6b7280";
/** CSS named colors Arma can render, for legacy/AI-authored `style` values. */
const NAMED_COLORS: Record<string, string> = {
red: "#ff0000",
orange: "#ff8c00",
yellow: "#ffff00",
green: "#00ff00",
blue: "#0000ff",
purple: "#800080",
pink: "#ffc0cb",
gray: "#808080",
grey: "#808080",
white: "#ffffff",
black: "#000000",
cyan: "#00ffff",
};
function isNode(value: unknown): value is LexicalNode {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function childrenOf(node: LexicalNode | null | undefined): unknown[] {
return Array.isArray(node?.children) ? node.children : [];
}
function stringOf(value: unknown): string | null {
return typeof value === "string" && value.length > 0 ? value : null;
}
/** Escape characters that would otherwise be parsed as Structured Text tags. */
function escapeText(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/\r\n?/g, "\n")
.replace(/\n/g, "<br/>");
}
/** Escape a value for the inside of a SQF double-quoted string. */
function sqfString(value: string): string {
return `"${value.replace(/"/g, '""')}"`;
}
function normalizeHex(value: string): string | null {
const trimmed = value.trim().toLowerCase();
if (!/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/.test(trimmed)) return null;
if (trimmed.length === 4) {
return `#${trimmed[1]}${trimmed[1]}${trimmed[2]}${trimmed[2]}${trimmed[3]}${trimmed[3]}`;
}
return trimmed;
}
/** Browsers serialize inline styles as `rgb()` / `rgba()`, so accept those too. */
function rgbToHex(value: string): string | null {
const match = value
.trim()
.match(
/^rgba?\(\s*(\d{1,3})\s*[, ]\s*(\d{1,3})\s*[, ]\s*(\d{1,3})(?:\s*[,/]\s*[\d.]+%?)?\s*\)$/i,
);
if (!match) return null;
const channels = match.slice(1, 4).map(Number);
if (channels.some((channel) => channel < 0 || channel > 255)) return null;
return `#${channels.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
}
function colorFromStyle(style: string): string | null {
const match = style.match(/(?:^|;)\s*color\s*:\s*([^;]+)/i);
if (!match) return null;
const value = match[1].trim();
return normalizeHex(value) ?? rgbToHex(value) ?? NAMED_COLORS[value.toLowerCase()] ?? null;
}
/**
* Resolves a text node's color from the inline `style` string (front-end
* editor), the top-level `color` key, or Payload's TextStateFeature state,
* which Lexical serializes under `$` (admin editor). Only colors Arma
* understands are returned; everything else falls back to default.
*/
export function briefingTextColor(node: {
color?: unknown;
style?: unknown;
$?: unknown;
}): string | null {
const style = stringOf(node.style);
const styleColor = style ? colorFromStyle(style) : null;
if (styleColor) return styleColor;
const state = isNode(node.$) ? node.$ : null;
const raw = stringOf(node.color) ?? (state ? stringOf(state.color) : null);
if (!raw) return null;
const palette = BRIEFING_TEXT_COLORS[raw as BriefingTextColorKey];
if (palette) return palette.hex;
const hex = normalizeHex(raw);
if (hex) return hex;
return NAMED_COLORS[raw.toLowerCase()] ?? null;
}
function textAttributes(node: LexicalNode): string[] {
const attrs: string[] = [];
const format = typeof node.format === "number" ? node.format : 0;
const bold = (format & FORMAT_BOLD) !== 0;
const code = (format & FORMAT_CODE) !== 0;
if (code) attrs.push("font='EtelkaMonospacePro'");
else if (bold) attrs.push("font='PuristaBold'");
if ((format & FORMAT_UNDERLINE) !== 0) attrs.push("underline='1'");
const color = briefingTextColor(node);
if (color) attrs.push(`color='${color}'`);
return attrs;
}
function wrapText(value: string, attrs: string[]): string {
if (attrs.length === 0) return value;
return `<t ${attrs.join(" ")}>${value}</t>`;
}
function renderText(node: LexicalNode): string {
const text = typeof node.text === "string" ? node.text : "";
if (text.length === 0) return "";
return wrapText(escapeText(text), textAttributes(node));
}
function renderInline(nodes: unknown[]): string {
return nodes.map((child) => renderNode(child)).join("");
}
function indentFor(node: LexicalNode): string {
const indent = typeof node.indent === "number" ? Math.max(0, node.indent) : 0;
return "\u00a0".repeat(indent * 4);
}
/** Wrap a block in alignment/indent attributes when it asks for them. */
function renderBlock(node: LexicalNode, content: string): string {
if (content.length === 0) return "";
const indent = indentFor(node);
const align = typeof node.format === "string" ? node.format : "";
if (align === "center" || align === "right") {
return `${indent}<t align='${align}'>${content}</t>`;
}
return `${indent}${content}`;
}
const HEADING_SIZES: Record<string, string> = {
h1: "1.5",
h2: "1.35",
h3: "1.2",
h4: "1.1",
h5: "1.0",
h6: "0.95",
};
function renderHeading(node: LexicalNode): string {
const content = renderInline(childrenOf(node));
if (content.length === 0) return "";
const tag = typeof node.tag === "string" ? node.tag : "h2";
const size = HEADING_SIZES[tag] ?? "1.2";
return renderBlock(node, wrapText(content, ["font='PuristaBold'", `size='${size}'`]));
}
function renderList(node: LexicalNode, depth = 0): string {
const items = childrenOf(node).filter(
(child): child is LexicalNode => isNode(child) && child.type === "listitem",
);
if (items.length === 0) return "";
const ordered = node.listType === "number" || node.tag === "ol";
const check = node.listType === "check" || node.listType === "checklist";
const start = typeof node.start === "number" && node.start > 0 ? node.start : 1;
const indent = "\u00a0".repeat(depth * 4);
return items
.map((item, index) => {
const itemChildren = childrenOf(item);
const nested = itemChildren.filter(
(child): child is LexicalNode => isNode(child) && child.type === "list",
);
const inline = renderInline(
itemChildren.filter((child) => !isNode(child) || child.type !== "list"),
);
const marker = check
? item.checked === true
? "[x] "
: "[ ] "
: ordered
? `${start + index}. `
: "\u2022 ";
const line = `${indent}${marker}${inline}`;
const nestedText = nested
.map((child) => renderList(child, depth + 1))
.filter((text) => text.length > 0)
.join("<br/>");
return nestedText.length > 0 ? `${line}<br/>${nestedText}` : line;
})
.join("<br/>");
}
function renderUpload(node: LexicalNode): string {
const value = isNode(node.value) ? node.value : null;
const label =
(value ? stringOf(value.filename) : null) ??
(value ? stringOf(value.url) : null) ??
stringOf(node.relationTo) ??
"embedded media";
return wrapText(`[Image: ${escapeText(label)}]`, [`color='${MUTED}'`]);
}
function renderLink(node: LexicalNode): string {
const fields = isNode(node.fields) ? node.fields : null;
const url = (fields ? stringOf(fields.url) : null) ?? stringOf(node.url);
const label = renderInline(childrenOf(node));
const text = label.length > 0 ? label : url ? escapeText(url) : "";
if (!url || text.includes(escapeText(url))) return text;
return `${text} <t color='${MUTED}'>(${escapeText(url)})</t>`;
}
function renderNode(value: unknown): string {
if (!isNode(value)) return "";
const type = typeof value.type === "string" ? value.type : "";
switch (type) {
case "text":
return renderText(value);
case "linebreak":
return "<br/>";
case "tab":
return "\u00a0\u00a0\u00a0\u00a0";
case "paragraph":
return renderBlock(value, renderInline(childrenOf(value)));
case "heading":
return renderHeading(value);
case "list":
return renderList(value);
case "listitem":
return renderInline(childrenOf(value));
case "quote":
case "blockquote":
return renderBlock(
value,
wrapText(`| ${renderBlockChildren(childrenOf(value))}`, [`color='${MUTED}'`]),
);
case "horizontalrule":
return wrapText("-----", [`color='${RULE}'`]);
case "link":
case "autolink":
return renderLink(value);
case "upload":
return renderUpload(value);
case "relationship":
return wrapText("[Reference]", [`color='${MUTED}'`]);
case "root":
return renderBlockChildren(childrenOf(value));
default:
return childrenOf(value).length > 0 ? renderInline(childrenOf(value)) : "";
}
}
function renderBlockChildren(nodes: unknown[]): string {
return nodes
.map((child) => renderNode(child))
.filter((text) => text.length > 0)
.join("<br/><br/>");
}
function renderRoot(details: unknown): string {
if (!isNode(details)) return "";
const root = isNode(details.root) ? details.root : null;
return root ? renderBlockChildren(childrenOf(root)) : "";
}
function entryTitle(entry: BriefingSqfEntry): string {
return wrapText(escapeText(entry.sectionName), ["font='PuristaBold'", "size='1.2'"]);
}
/**
* Structured Text body for one briefing entry. Titles are optional because the
* diary script already carries the section name as the record title.
*/
export function briefingEntryToStructuredText(
entry: BriefingSqfEntry,
options: { includeTitle?: boolean } = {},
): string {
const body = renderRoot(entry.details);
if (options.includeTitle !== true) return body;
const title = entryTitle(entry);
return body.length > 0 ? `${title}<br/><br/>${body}` : title;
}
export function briefingEntryHasContent(entry: BriefingSqfEntry): boolean {
return renderRoot(entry.details).trim().length > 0;
}
function commentSafe(value: string): string {
return value.replace(/\*\//g, "* /");
}
/**
* A `createDiaryRecord` script that recreates every briefing entry in the
* player's diary. Records are emitted in reverse because Arma inserts each new
* record above the previous one, so the script reads top-to-bottom in order.
*/
export function briefingToDiarySqf(
entries: BriefingSqfEntry[],
options: { missionName?: string | null } = {},
): string {
const mission = options.missionName?.trim();
const lines: string[] = [
`// Generated by Polaris Task Force${mission ? ` - briefing for "${commentSafe(mission)}"` : " - mission briefing"}.`,
"// Paste into the debug console or a mission init file. Records are added",
"// bottom-up so they read in order in the game's diary.",
"",
];
for (const entry of [...entries].reverse()) {
const body = briefingEntryToStructuredText(entry);
lines.push(
`player createDiaryRecord ["Diary", [${sqfString(entry.sectionName)}, ${sqfString(body)}]];`,
);
}
return `${lines.join("\n")}\n`;
}
/**
* A `_briefing` array of Structured Text bodies (titles included), one element
* per entry, ready to feed into your own diary or hint code.
*/
export function briefingToStructuredTextSqf(entries: BriefingSqfEntry[]): string {
const lines: string[] = [
`// Generated by Polaris Task Force (${entries.length} briefing section${entries.length === 1 ? "" : "s"}).`,
"// Each element is a Structured Text body, ready for createDiaryRecord.",
"",
"private _briefing = [",
];
entries.forEach((entry, index) => {
const body = briefingEntryToStructuredText(entry, { includeTitle: true });
const comma = index < entries.length - 1 ? "," : "";
lines.push(` /* ${commentSafe(entry.sectionName)} */`);
lines.push(` ${sqfString(body)}${comma}`);
});
lines.push("];");
return `${lines.join("\n")}\n`;
}

View file

@ -0,0 +1,250 @@
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 {
briefingEntryHasContent,
briefingEntryToStructuredText,
briefingToDiarySqf,
briefingToStructuredTextSqf,
type BriefingSqfEntry,
} from "@/lib/intelligence/briefingSqf";
function text(value: string, format = 0, extra: Record<string, unknown> = {}) {
return { type: "text", version: 1, text: value, format, ...extra };
}
function paragraph(children: unknown[], extra: Record<string, unknown> = {}) {
return { type: "paragraph", version: 1, children, ...extra };
}
function entry(sectionName: string, children: unknown[]): BriefingSqfEntry {
return {
sectionName,
details: {
root: { type: "root", version: 1, children },
},
};
}
describe("briefing Structured Text conversion", () => {
it("maps bold, underline, code, and color formats", () => {
const result = briefingEntryToStructuredText(
entry("Situation", [
paragraph([
text("bold", 1),
text(" "),
text("under", 8),
text(" "),
text("code", 16),
text(" "),
text("red", 0, { color: "red" }),
text(" "),
text("both", 1, { color: "blue" }),
]),
]),
);
expect(result).toContain("<t font='PuristaBold'>bold</t>");
expect(result).toContain("<t underline='1'>under</t>");
expect(result).toContain("<t font='EtelkaMonospacePro'>code</t>");
expect(result).toContain("<t color='#ff5c5c'>red</t>");
expect(result).toContain("<t font='PuristaBold' color='#60a5fa'>both</t>");
});
it("keeps text Arma cannot style as plain text", () => {
const result = briefingEntryToStructuredText(
entry("Situation", [paragraph([text("italic", 2), text(" "), text("crossed", 4)])]),
);
expect(result).toBe("italic crossed");
});
it("resolves legacy CSS style colors and ignores unknowns", () => {
const result = briefingEntryToStructuredText(
entry("Situation", [
paragraph([
text("style", 0, { style: "color: #ff0000;" }),
text(" "),
text("browser", 0, { style: "color: rgb(255, 159, 67)" }),
text(" "),
text("state", 0, { $: { color: "red" } }),
text(" "),
text("unknown", 0, { color: "chartreuse" }),
]),
]),
);
expect(result).toBe(
"<t color='#ff0000'>style</t> <t color='#ff9f43'>browser</t> <t color='#ff5c5c'>state</t> unknown",
);
});
it("escapes Structured Text metacharacters", () => {
const result = briefingEntryToStructuredText(
entry("Situation", [paragraph([text("<Alpha> & Bravo")])]),
);
expect(result).toBe("&lt;Alpha&gt; &amp; Bravo");
});
it("renders headings with size and alignment", () => {
const heading = {
type: "heading",
version: 1,
tag: "h2",
children: [text("Orders")],
};
const centered = paragraph([text("Centered")], { format: "center" });
const result = briefingEntryToStructuredText(entry("Mission", [heading, centered]));
expect(result).toContain("<t font='PuristaBold' size='1.35'>Orders</t>");
expect(result).toContain("<t align='center'>Centered</t>");
});
it("renders bullet, numbered, checklist, and nested lists", () => {
const list = {
type: "list",
version: 1,
listType: "number",
tag: "ol",
start: 3,
children: [
{
type: "listitem",
version: 1,
value: 1,
children: [
text("First"),
{
type: "list",
version: 1,
listType: "bullet",
tag: "ul",
children: [{ type: "listitem", version: 1, value: 1, children: [text("Nested")] }],
},
],
},
{ type: "listitem", version: 1, value: 2, children: [text("Second")] },
],
};
const checklist = {
type: "list",
version: 1,
listType: "check",
tag: "ul",
children: [
{ type: "listitem", version: 1, checked: true, children: [text("Done")] },
{ type: "listitem", version: 1, checked: false, children: [text("Todo")] },
],
};
const result = briefingEntryToStructuredText(entry("Execution", [list, checklist]));
expect(result).toContain("3. First<br/>\u00a0\u00a0\u00a0\u00a0\u2022 Nested");
expect(result).toContain("4. Second");
expect(result).toContain("[x] Done<br/>[ ] Todo");
});
it("renders quotes, rules, links, and images as readable placeholders", () => {
const quote = {
type: "quote",
version: 1,
children: [text("Hold the line")],
};
const rule = { type: "horizontalrule", version: 1 };
const link = {
type: "link",
version: 1,
fields: { url: "https://example.test/opord" },
children: [text("OPORD")],
};
const image = {
type: "upload",
version: 1,
relationTo: "media",
value: { filename: "map.jpg", url: "/media/map.jpg" },
};
const result = briefingEntryToStructuredText(entry("Signals", [quote, rule, link, image]));
expect(result).toContain("<t color='#9ca3af'>| Hold the line</t>");
expect(result).toContain("<t color='#6b7280'>-----</t>");
expect(result).toContain("OPORD <t color='#9ca3af'>(https://example.test/opord)</t>");
expect(result).toContain("<t color='#9ca3af'>[Image: map.jpg]</t>");
});
it("detects entries with no body text", () => {
expect(briefingEntryHasContent(entry("Empty", [paragraph([])]))).toBe(false);
expect(briefingEntryHasContent(entry("Full", [paragraph([text("Hi")])]))).toBe(true);
expect(briefingEntryHasContent({ sectionName: "Bad", details: null })).toBe(false);
});
it("renders colors on the mission page", () => {
const data = {
root: {
type: "root",
version: 1,
direction: null,
format: "",
indent: 0,
children: [
{
type: "paragraph",
version: 1,
direction: null,
format: "",
indent: 0,
textFormat: 0,
children: [
text("Red alert", 1, { $: { color: "red" } }),
text(" and "),
text("styled", 0, { style: "color: rgb(96, 165, 250)" }),
],
},
],
},
};
const html = renderToStaticMarkup(
createElement(RichText, { data: data as never, converters: briefingConverters }),
);
expect(html).toMatch(/<span style="color:\s*#ff5c5c"><strong>Red alert<\/strong><\/span>/);
expect(html).toMatch(/<span style="color:\s*#60a5fa">styled<\/span>/);
});
});
describe("briefing SQF export", () => {
const situation = entry("Situation", [paragraph([text("Enemy to the north.")])]);
const mission = entry("Mission", [paragraph([text("Take the ridge.")])]);
it("creates diary records bottom-up so they read in order", () => {
const sqf = briefingToDiarySqf([situation, mission], { missionName: "The Pale" });
expect(sqf).toContain('player createDiaryRecord ["Diary", ["Situation",');
expect(sqf).toContain('player createDiaryRecord ["Diary", ["Mission",');
expect(sqf.indexOf('["Mission"')).toBeLessThan(sqf.indexOf('["Situation"'));
expect(sqf).toContain('briefing for "The Pale"');
});
it("doubles quotes inside SQF strings", () => {
const quoted = entry('Signals "Main"', [paragraph([text('Say "hello".')])]);
const sqf = briefingToDiarySqf([quoted]);
expect(sqf).toContain('["Signals ""Main"""');
expect(sqf).toContain('""hello""');
});
it("exports an array of Structured Text bodies with titles", () => {
const sqf = briefingToStructuredTextSqf([situation, mission]);
expect(sqf).toContain("private _briefing = [");
expect(sqf).toContain("<t font='PuristaBold' size='1.2'>Situation</t>");
expect(sqf).toContain("<t font='PuristaBold' size='1.2'>Mission</t>");
expect(sqf).toMatch(/take the ridge\."\n\]/i);
expect(sqf).toContain("Take the ridge.");
});
});