1
0
Fork 0

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
This commit is contained in:
Jason Fraley 2026-11-18 13:10:26 -05:00
parent 1bb5cdde60
commit 34c0d5681f
35 changed files with 466 additions and 229 deletions

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,
@ -280,8 +280,8 @@ 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>
)}

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

@ -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

@ -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

@ -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;
},
});

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;

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";
@ -112,7 +112,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";
@ -511,11 +511,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

@ -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

@ -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");
});
});