1
0
Fork 0

Compare commits

...

4 commits

Author SHA1 Message Date
7003a321f9 v0.16.8 - add tech tree notes, fix awards without a tier 2026-11-24 10:05:57 -05:00
441dd1e535 docs: add v0.16.8 changelog entry 2026-11-24 09:55:53 -05:00
74b116b9cf fix(awards): save awards without an advancement tier
The beforeChange hook compared advancement values against undefined, but the admin form always submits the group, so an award outside a lineup arrived as { seriesKey: null, tier: null }. Null counted as set, which tripped the duplicate tier check for standalone ribbons and the ribbons-only guard for medals and commendations.

Normalize null, empty, and non-finite values to "not set" before validating. Non-ribbon awards clear leftover lineup values on a type change instead of throwing on a hidden field, and partial API updates that omit advancement keep the stored lineup.
2026-11-24 08:03:30 -05:00
48556c3688 feat(tech-tree): add note nodes with optional frontend visibility
Planners can now drop annotation cards on the Tech Tree canvas without inventing fake technologies. Notes live in their own tech-tree-notes collection (title, body, treePosition) and carry no prerequisites, costs, approval workflow or research state, so the layout engine, edge builder and research rules never see them.

showOnFrontend defaults to false, making notes a backend authoring aid; ticking it publishes the amber card read-only to the member tech tree, which queries showOnFrontend = true.

Canvas work: amber NoteNode card with no connection handles, NoteDialog for create/edit/delete, a New Note toolbar button (technologies:create gated), viewport-centre placement, and namespaced note-<id> React Flow ids so note and technology ids can never collide. Note drags, Save positions and Auto-arrange reuse the single-statement bulk /api/tech-tree/positions write by sending collection: "tech-tree-notes"; no PATCH-per-note path was added.

Also fixes the note card body being clipped by the inherited line-height: the classification strip and footer now have fixed heights with leading-none, and the body takes the remaining flex space instead of line-clamp.

Tests: tech-tree-notes.int.spec.ts (defaults, required title, publication filter, in-place edits, note layout and id namespacing) plus note coverage in tech-tree-positions.int.spec.ts. Migration 20261123_073019_add_tech_tree_notes must be run on prod after deploy.
2026-11-23 03:11:36 -05:00
26 changed files with 48174 additions and 110 deletions

View file

@ -1,5 +1,17 @@
# Changelog
# v0.16.8
### Features
- **Tech tree notes.** The tech tree now shows note cards beside technologies, so you can read a note about a tech without leaving the page.
### Fixes
- Various bug fixes and improvements.
---
# v0.16.7
### Fixes

View file

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

@ -3,7 +3,7 @@ import { getPayload } from "payload";
import { headers as nextHeaders } from "next/headers";
import type { Metadata } from "next";
import { mapCategoryDoc, mapTechDoc } from "@/components/admin/tech-tree/mappers";
import { mapCategoryDoc, mapNoteDoc, mapTechDoc } from "@/components/admin/tech-tree/mappers";
import { TechTreeClient } from "@/components/frontend/techTree/TechTreeClient";
import type {
ActiveResearchView,
@ -30,7 +30,7 @@ export default async function FrontendTechTreePage() {
const { user } = await payload.auth({ headers: await nextHeaders(), canSetHeaders: false });
if (!user) return null; // type-guard only; the layout gate handles guests
const [capacity, techsRes, categoriesRes, resourcesRes, researchesRes, ballotsRes] =
const [capacity, techsRes, categoriesRes, notesRes, resourcesRes, researchesRes, ballotsRes] =
await Promise.all([
loadResearchCapacity(payload),
payload.find({
@ -50,6 +50,17 @@ export default async function FrontendTechTreePage() {
user,
overrideAccess: false,
}),
payload.find({
collection: "tech-tree-notes",
// Backend-only notes never reach members: the collection defaults the
// flag to false, so this WHERE is the only publication gate.
where: { showOnFrontend: { equals: true } },
depth: 0,
limit: 0,
sort: "createdAt",
user,
overrideAccess: false,
}),
payload.find({
collection: "resources",
depth: 0,
@ -226,6 +237,7 @@ export default async function FrontendTechTreePage() {
<TechTreeClient
techs={techDocs.map((doc) => mapTechDoc(doc))}
categories={categoriesRes.docs.map((doc) => mapCategoryDoc(doc as unknown as Record<string, unknown>))}
notes={notesRes.docs.map((doc) => mapNoteDoc(doc as unknown as Record<string, unknown>))}
statuses={statuses}
details={details}
activeResearch={activeResearch}

View file

@ -10,16 +10,21 @@ export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/**
* Bulk Tech Tree position write: `{ positions: [{ id, x, y, ifUnmodifiedAt? }] }`,
* where a null x/y returns a technology to the automatic layout and
* Bulk Tech Tree position write: `{ collection?, positions: [{ id, x, y, ifUnmodifiedAt? }] }`,
* where a null x/y returns a node to the automatic layout and
* `ifUnmodifiedAt` (the loaded `updatedAt`) makes that row conditional: one
* mismatched precondition rejects the whole batch with HTTP 409 and the
* conflicting ids. Used by every canvas position write (drags, Save positions,
* Auto-arrange, freeze pins) so they cost one request and one SQL statement
* instead of a PATCH per node.
*
* `collection` defaults to `technologies`; note nodes on the same canvas send
* `tech-tree-notes` and share the exact same write path.
*
* Access mirrors the technologies collection's update rule: the
* `technologies:update` permission OR Intelligence division membership.
* `technologies:update` permission OR Intelligence division membership. Note
* nodes reuse the technologies permissions on purpose (they are a canvas
* annotation, not a separate domain).
*/
export async function POST(req: NextRequest) {
const payload = await getPayload({ config: await config });
@ -46,12 +51,12 @@ export async function POST(req: NextRequest) {
}
try {
const result = await writeTreePositions(payload, parsed.updates);
const result = await writeTreePositions(payload, parsed.updates, parsed.collection);
if (result.conflicts.length > 0) {
return NextResponse.json(
{
error:
"Some positions could not be saved: those technologies changed since you loaded them.",
"Some positions could not be saved: those nodes changed since you loaded them.",
conflicts: result.conflicts,
},
{ status: 409 },

View file

@ -0,0 +1,88 @@
import type { CollectionConfig } from "payload";
import { requireIntelligencePermission } from "@/utils/access-control/divisionAccess";
import { requirePermission } from "@/utils/access-control/hasPermission";
/**
* Free-standing annotation cards on the Tech Tree canvas.
*
* These are deliberately NOT technologies: they carry no prerequisites, costs,
* approval workflow or research state, so they never enter the research engine
* or the member-facing progression rules. They exist so planners can leave
* explanations, goals or caveats next to the tree without inventing fake
* technologies for them.
*
* `showOnFrontend` is off by default: notes are an authoring aid first, and are
* only published to the member tech tree when someone ticks the box.
*
* The collection is hidden from the admin sidebar on purpose. Notes are created,
* edited, dragged and deleted on the `/admin/tech-tree` canvas, so their write
* access reuses the `technologies` permissions instead of introducing a parallel
* permission group that would also need its own admin-page gate.
*/
export const TechTreeNotes: CollectionConfig = {
slug: "tech-tree-notes",
labels: {
singular: "Tech Tree Note",
plural: "Tech Tree Notes",
},
admin: {
group: "Intelligence",
useAsTitle: "title",
hidden: true,
description:
"Annotation cards on the Tech Tree canvas. Edited from /admin/tech-tree; hidden from the sidebar.",
},
access: {
create: requireIntelligencePermission("technologies:create"),
update: requireIntelligencePermission("technologies:update"),
delete: requireIntelligencePermission("technologies:delete"),
read: requirePermission("technologies:read"),
},
fields: [
{
name: "title",
type: "text",
required: true,
admin: {
description: "Short heading shown on the note card.",
},
},
{
name: "body",
type: "textarea",
admin: {
description: "Free text shown under the title. Line breaks are preserved.",
},
},
{
name: "showOnFrontend",
type: "checkbox",
label: "Show on Frontend",
defaultValue: false,
admin: {
description:
"Tick to publish this note on the member-facing Tech Tree. Notes are backend-only until this is enabled.",
},
},
{
name: "treePosition",
type: "group",
label: "Tech Tree Position",
admin: {
description:
"Manual position on the Tech Tree canvas (set by dragging a note). Leave empty to park the note in the notes column beside the tree.",
},
fields: [
{
name: "x",
type: "number",
},
{
name: "y",
type: "number",
},
],
},
],
};

View file

@ -184,51 +184,59 @@ export const Awards: CollectionConfig = {
hooks: {
beforeChange: [
async ({ req, data, operation, originalDoc }) => {
const advancement = data.advancement;
if (
advancement &&
typeof advancement.seriesKey === "string" &&
advancement.seriesKey.trim() !== ""
) {
advancement.seriesKey = advancement.seriesKey.trim().toLowerCase().replace(/\s+/g, "-");
const effectiveType = data.type ?? originalDoc?.type;
const advancementProvided = data.advancement !== undefined;
const rawAdvancement = data.advancement;
// Normalize before validating: the admin form submits the advancement group even
// when it is hidden or empty, so a standalone award arrives as
// `{ seriesKey: null, tier: null }` and a cleared text input as "". Treat all of
// those as "not set" instead of as real values (the old `!== undefined` checks
// treated null as set, which rejected saving any award without a tier).
const rawSeriesKey =
typeof rawAdvancement?.seriesKey === "string" ? rawAdvancement.seriesKey.trim() : "";
const seriesKey =
rawSeriesKey === "" ? null : rawSeriesKey.toLowerCase().replace(/\s+/g, "-");
const rawTier = rawAdvancement?.tier;
const tier = typeof rawTier === "number" && Number.isFinite(rawTier) ? rawTier : null;
// Partial API updates that omit the field leave the stored lineup untouched.
if (!advancementProvided) {
return data;
}
const seriesKey = advancement?.seriesKey;
const tier = advancement?.tier;
if (operation === "create" || operation === "update") {
const effectiveType = data.type ?? originalDoc?.type;
if (
(seriesKey !== undefined && tier === undefined) ||
(seriesKey === undefined && tier !== undefined)
) {
throw new Error("Advancement requires both a series key and a tier.");
}
if (effectiveType !== "ribbon") {
// Advancement lineups only exist for ribbons. Clear leftovers when an award is
// switched to another type, since the field is hidden and cannot be cleared there.
data.advancement = { seriesKey: null, tier: null };
return data;
}
if ((seriesKey !== undefined || tier !== undefined) && effectiveType !== "ribbon") {
throw new Error("Advancement lineups are only supported for ribbons.");
}
if ((seriesKey === null) !== (tier === null)) {
throw new Error("Advancement requires both a series key and a tier.");
}
if (seriesKey !== undefined && tier !== undefined) {
const result = await req.payload.count({
collection: "awards",
where: {
and: [
{ "advancement.seriesKey": { equals: seriesKey } },
{ "advancement.tier": { equals: tier } },
...(operation === "update" && originalDoc?.id
? [{ id: { not_equals: originalDoc.id } }]
: []),
],
},
overrideAccess: true,
});
if (seriesKey !== null && tier !== null) {
const result = await req.payload.count({
collection: "awards",
where: {
and: [
{ "advancement.seriesKey": { equals: seriesKey } },
{ "advancement.tier": { equals: tier } },
...(operation === "update" && originalDoc?.id
? [{ id: { not_equals: originalDoc.id } }]
: []),
],
},
overrideAccess: true,
});
if (result.totalDocs > 0) {
throw new Error(`Tier ${tier} of this series already exists.`);
}
if (result.totalDocs > 0) {
throw new Error(`Tier ${tier} of this series already exists.`);
}
}
data.advancement = { seriesKey, tier };
return data;
},
],

View file

@ -6,9 +6,10 @@
`/admin/tech-tree` — visual tech tree editor over `technologies`, built on `@xyflow/react` v12 following the narrative-flow patterns. Custom admin view (root view) + a "Tech Tree" nav entry injected under the Intelligence group; the Technologies list/edit views are untouched.
- **Schema**: `tech-categories` collection (`src/collections/intelligence/TechCategories.ts`: `name` unique, `position` number = timeline order, optional hex `color`) + `Technologies.category` relationship (FK `ON DELETE set null`, so deleting a category just unfiles its techs) + `Technologies.treePosition` group (`x`/`y` numbers; manual canvas position from dragging, empty = automatic). Permissions mirror technologies (`tech-categories:*` + `admin:tech-categories:manage`, registered in `src/permissions/index.ts`); `tech-categories` is in `DIVISION_ADMIN_QUALIFICATIONS`, so Intelligence division members get admin-panel access exactly like `technologies`. Migrations: `20260930_230747_add_tech_categories`, `20261001_000320_add_tech_tree_position`.
- **Note nodes**: `tech-tree-notes` (`src/collections/intelligence/TechTreeNotes.ts`, `admin.hidden`, no sidebar page) are amber annotation cards on the canvas, deliberately NOT technologies: no prerequisites, cost rows, approval workflow or research state, so `computeLayout`, edge building and the research rules never see them. Fields: `title` (required), `body` (textarea, line breaks preserved), `showOnFrontend` (checkbox, **false by default**), `treePosition` group. Access reuses the `technologies` permissions (`read`/`create`/`update`/`delete`), so no permission group or admin-page gate was added; notes are created, edited and deleted only from the canvas (`NoteDialog`, "+ New Note" toolbar button) and the delete button is hidden without `technologies:delete`. A new note lands at the viewport centre; untouched notes park in an automatic column one step right of the tree (`notes.ts` `computeNoteLayout`). Note React Flow ids are namespaced `note-<id>` (`noteNodeId`/`parseNoteNodeId`) so they can never collide with technology ids, and note cards have no handles, so they can never become prerequisite endpoints. Note drags, Save positions and Auto-arrange reuse the bulk `/api/tech-tree/positions` write by sending `collection: "tech-tree-notes"` (the route swaps the target table and the token source); never add a PATCH-per-note path. Ticking `showOnFrontend` publishes the note to the member tech tree, which queries `showOnFrontend: { equals: true }` and renders the same amber card read-only; unpublished notes never reach members. Notes are edge-routing obstacles in both canvases.
- **View wiring**: `payload.config.ts` `admin.components.views.techTree` (path `/tech-tree`, component `src/components/admin/tech-tree/TechTreeView.tsx`) and `admin.components.Nav` → `TechTreeNav.tsx`. Custom root views are public by default, so the view gates itself (logged-in + `technologies:read` OR Intelligence qualification). The nav replica injects the entry into the group containing `technologies` and reuses public exports (`NavWrapper`/`NavHamburger`/`DefaultNavClient` from `@payloadcms/next/client`, `groupNavItems` from `@payloadcms/ui/shared`); registered admin components must be **default exports** (importMap convention in this repo).
- **Layout** (`layout.ts`, pure): a **propagating left-to-right tree**. A technology WITH prerequisites is placed one column to the right of its parents, at their average row, so linking A -> B drops B immediately beside A and B's dependents continue further right; nothing is teleported to a distant column when its depth changes. Technologies in a category stay pinned to that category's column (the category contract); uncategorized roots fill a catalog grid whose slots come from each tech's rank among ALL uncategorized technologies (`MAX_ROWS_PER_COLUMN` = 10 rows, spilling into more columns) so promoting a tech into the tree leaves an empty slot rather than re-shuffling the grid; uncategorized dependents follow their parents inside the uncategorized zone. Collisions search rows outward from the desired row (dependents may also grow upward, and their columns are not height-capped, so a link from a full column still lands beside its parent rather than far right). Category bands are the bounding box of their members' final positions. Prerequisites placed to the RIGHT of their dependent surface as amber warnings (toolbar chip + node icon + preview panel section).
- **Edges**: AND prerequisites solid slate, OR prerequisites dashed cyan with an OR label. Connections are editable on the canvas: drag from a node's right handle onto another node (the target card OR its handle) to add it as an AND prerequisite; the drop-on-card case is resolved by an `onConnectEnd` fallback because React Flow only resolves drops onto a handle. Select an edge and press Backspace to remove the prerequisite. Duplicates, self-references, and cycles (direct or transitive) are rejected by the pure `prereqEdits.ts` helpers with an inline error in the toolbar. Lines are also manually routable: selecting an edge reveals a "+" handle at each segment's midpoint (click to add a bend), bends drag to move, and double-clicking a bend removes it (`RoutedEdge.tsx` + `edgeRoutes.ts`). Routes are stored per browser in `localStorage`; making them shared would need a persisted field on the target technology. Edges also route around technologies they are not connected to: `edgeRouting.ts` detours each segment around the node rectangles it would cross (inflated by a clearance margin) and `buildRoutePath` rounds every corner. An unrouted edge keeps its automatic out/across/in shape unless that path would cut through a node, in which case it falls back to a direct line the router can bend around.
- **Interactions**: nodes are draggable; dropping one PATCHes its `treePosition` (persisted, survives reload) and the toolbar shows an "Auto-arrange" button (technologies:update gated) that clears every manual position and restores the ordered layout. A **Save positions** button (technologies:update gated), next to Auto-arrange, commits the current on-screen position of every node to `treePosition` in one pass (matching what React Flow rendered, not just dragged/pinned cards) so the exact arrangement survives a reload; Auto-arrange then clears them. Dragging one card of a multi-selection moves and persists the whole selection (React Flow hands the full dragged set to `onNodeDragStop`), and a category band is draggable by its header (`dragHandle`), which moves every technology in that band. A **Snap: On/Off** toggle (default on, remembered per browser, 46px grid that divides `COLUMN_STEP`/`ROW_STEP`) snaps dragged cards to the grid. **Every canvas position write is one bulk request**: drags, Save positions, Auto-arrange, and freeze pins all POST `{ positions: [{ id, x, y }] }` to `/api/tech-tree/positions` (null x/y clears a pin), which `writeTreePositions` (`src/lib/tech-tree/positions.ts`) applies as a single `UPDATE ... FROM (VALUES ...)` on the `tree_position_x/y` columns (access = `technologies:update` or Intelligence membership, the collection's own update rule; batches capped at 2000). Never persist positions with a PATCH per node: firing dozens of concurrent document updates exhausted the database pool and could crash the server on Auto-arrange. Auto-arrange is optimistic (the canvas re-lays out on click, pins are restored if the save fails) and a spinner status chip plus disabled layout controls and node dragging cover the save. **Connecting does not move anything**: if the ordered layout would relocate the connected technology, the canvas pins it to its current spot (`treePosition` written in the same PATCH as the prerequisite) so the edge appears without the card jumping; the catalog grid also uses stable slots (each tech's rank among all uncategorized technologies, so a tech promoted into the tree leaves its slot empty instead of re-shuffling every other root). Pressing "Auto-arrange" clears those pins and moves everything, including the connected node, to its ordered position. Node click opens the side panel, which is a **lite editor** over the fields it shows (name, type, approval status, summary, category with inline create, prerequisites with AND/OR grouping and add/remove, research costs with resource rows and min/max durations): dirty tracking, Save/Reset, and an "Edit in full view" jump to the standard admin edit route. Final approval states stay superuser-only (`canSetFinalApproval` = `system:admin-access`), mirroring the field access. Quick-create dialog (name, type, summary, category, research durations) creates via REST; the category picker is a native input + suggestion list (existing values selectable, new values creatable inline) because Radix Popover inside the admin Dialog proved layer-unstable. New categories get `position = max + 1`. The canvas uses React Flow's `<Background variant="lines">` so the grid scales with zoom (a CSS-background grid does not, and looked broken at low zoom), and `fitView` is capped at `maxZoom: 0.85`. Panel and toolbar controls carry dark tactical chrome (the admin panel's light shadcn defaults would render as white slabs on the dark surface; bare `<button>` elements in the admin additionally inherit a global light background AND border, so list rows need explicit `bg-transparent` + `border-0`), and the panel's dropdowns use the in-house `PanelSelect` listbox rather than native `<select>`: a native popup is browser/OS chrome that ignores dark styling (only `color-scheme` influences it) and cannot be screenshotted, whereas `PanelSelect` renders its list through a portal as a fixed-position overlay above the panel (so it never pushes the panel's content down), flips upward when there is more room above, closes on scroll/resize so it cannot detach from its trigger, and offers a search field for long lists. Both it and the panel's category picker use a mono header strip, hairline row separators, a cyan left accent on the selected row, and the `.tech-tree-scroll` dark scrollbar rules from `custom.scss`.
- **Styling**: tactical dossier (dark `#05070a` canvas + 28px grid via inline styles, squared corners, classification strips, mono readouts); shadcn form controls in the dialog stay conventional. React Flow controls/attribution are darkened via `.tech-tree-canvas` rules in `src/app/(payload)/custom.scss`.
- **Gotchas**: React Flow in controlled mode needs `useNodesState` AND `useEdgesState` with change handlers that forward everything except `remove` (a no-op edge handler silently breaks edge selection, and a passed-through remove lets Backspace delete nodes that only exist in the data layer); category band nodes must be `pointerEvents: "none"` or they swallow edge/pane clicks; node handles must live OUTSIDE the card's `overflow-hidden` box or they become un-draggable; a second `next dev` for the same directory is impossible (Next 16 lock) so e2e verification either frees port 3000 or uses a copied repo (whose file watcher is unreliable: restart the copied server after every source change). technologies create requires `approvalStatus` + `researchCosts.minimumResearchDuration` (the field's `defaultValue: 0` violates its own `min: 1`, so creates must pass it explicitly); clearing `treePosition` means sending `{ x: null, y: null }` (a group cannot be nulled wholesale). The e2e seeds via cookie-authed REST (`page.request`) after frontend login, so it MUST run against the test DB: a dev server left on port 3000 is silently reused (`reuseExistingServer: true`) and its DEV database 403s every seed (the dev user has no create permission). Free the port first. Tests: `tests/int/tech-tree-layout.int.spec.ts` (pure layout: wrapping, overrides, band bboxes, warnings, cycles), `tests/int/tech-tree-prereq-edits.int.spec.ts` (pure add/remove/switch with cycle rejection), `tests/int/tech-categories.int.spec.ts` (CRUD, RBAC, division gating, FK set-null, position round-trip), `tests/int/tech-tree-edge-routes.int.spec.ts` (rounded route path + obstacle avoidance), `tests/int/tech-tree-positions.int.spec.ts` (bulk position validation + single-statement write/clear) + `tests/e2e/tech-tree.e2e.spec.ts` (nav, render, panel, edit nav, both quick-create paths, drag persistence + Auto-arrange, save positions + reload survival, multi-select drag, category-band drag, snap-to-grid, edge routing, connect/disconnect + lite-editor saves, wrapping at scale). Vivaldi crashes under automation in this suite; run with `E2E_BROWSER_PATH=<playwright chromium>`.
- **Gotchas**: React Flow in controlled mode needs `useNodesState` AND `useEdgesState` with change handlers that forward everything except `remove` (a no-op edge handler silently breaks edge selection, and a passed-through remove lets Backspace delete nodes that only exist in the data layer); category band nodes must be `pointerEvents: "none"` or they swallow edge/pane clicks; node handles must live OUTSIDE the card's `overflow-hidden` box or they become un-draggable; a second `next dev` for the same directory is impossible (Next 16 lock) so e2e verification either frees port 3000 or uses a copied repo (whose file watcher is unreliable: restart the copied server after every source change). technologies create requires `approvalStatus` + `researchCosts.minimumResearchDuration` (the field's `defaultValue: 0` violates its own `min: 1`, so creates must pass it explicitly); clearing `treePosition` means sending `{ x: null, y: null }` (a group cannot be nulled wholesale). The e2e seeds via cookie-authed REST (`page.request`) after frontend login, so it MUST run against the test DB: a dev server left on port 3000 is silently reused (`reuseExistingServer: true`) and its DEV database 403s every seed (the dev user has no create permission). Free the port first. Tests: `tests/int/tech-tree-layout.int.spec.ts` (pure layout: wrapping, overrides, band bboxes, warnings, cycles), `tests/int/tech-tree-prereq-edits.int.spec.ts` (pure add/remove/switch with cycle rejection), `tests/int/tech-categories.int.spec.ts` (CRUD, RBAC, division gating, FK set-null, position round-trip), `tests/int/tech-tree-edge-routes.int.spec.ts` (rounded route path + obstacle avoidance), `tests/int/tech-tree-positions.int.spec.ts` (bulk position validation + single-statement write/clear for both technologies and notes) + `tests/int/tech-tree-notes.int.spec.ts` (pure note layout/id namespacing + note defaults, required title, publication filter, in-place edits) + `tests/e2e/tech-tree.e2e.spec.ts` (nav, render, panel, edit nav, both quick-create paths, drag persistence + Auto-arrange, save positions + reload survival, multi-select drag, category-band drag, snap-to-grid, edge routing, connect/disconnect + lite-editor saves, wrapping at scale). Vivaldi crashes under automation in this suite; run with `E2E_BROWSER_PATH=<playwright chromium>`.

View file

@ -0,0 +1,249 @@
"use client";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { PlusIcon, SaveIcon, Trash2Icon } from "lucide-react";
import React from "react";
import { mapNoteDoc } from "./mappers";
import type { TreeNote } from "./types";
interface NoteDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
/** null = create a new note. */
note: TreeNote | null;
/**
* Canvas position for a newly created note (the viewport centre). Null parks
* the note in the automatic notes column beside the tree.
*/
createPosition: { x: number; y: number } | null;
/** Hidden when the viewer lacks technologies:delete (notes have no admin page). */
canDelete: boolean;
onSaved: (note: TreeNote) => void;
onDeleted: (noteId: number) => void;
}
/**
* Create / edit / delete a canvas note. Deliberately a dialog rather than a
* lite side panel: a note has exactly three editable fields, so a modal keeps
* the canvas readable and the edit surface in one place.
*
* `showOnFrontend` maps straight to the collection field, which defaults to
* false: a note is backend-only unless the author publishes it.
*/
export function NoteDialog({
open,
onOpenChange,
note,
createPosition,
canDelete,
onSaved,
onDeleted,
}: NoteDialogProps) {
const [title, setTitle] = React.useState("");
const [body, setBody] = React.useState("");
const [showOnFrontend, setShowOnFrontend] = React.useState(false);
const [busy, setBusy] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
React.useEffect(() => {
if (!open) return;
setTitle(note?.title ?? "");
setBody(note?.body ?? "");
setShowOnFrontend(note?.showOnFrontend ?? false);
setError(null);
}, [open, note]);
const isEdit = note !== null;
const submit = async () => {
setError(null);
if (!title.trim()) {
setError("A note needs a title.");
return;
}
setBusy(true);
try {
const payload: Record<string, unknown> = {
title: title.trim(),
body,
showOnFrontend,
};
// Only a create positions the node: an edit must not move the note.
if (!isEdit && createPosition) payload.treePosition = createPosition;
const res = await fetch(
isEdit ? `/api/tech-tree-notes/${note.id}` : "/api/tech-tree-notes",
{
method: isEdit ? "PATCH" : "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
},
);
if (!res.ok) {
const responseBody = await res.json().catch(() => null);
throw new Error(
responseBody?.errors?.[0]?.message ||
`Could not ${isEdit ? "save" : "create"} the note (HTTP ${res.status}).`,
);
}
const responseBody = await res.json();
const doc = responseBody?.doc;
if (!doc?.id) throw new Error("The note was saved but no id came back.");
onSaved(mapNoteDoc(doc as Record<string, unknown>));
onOpenChange(false);
} catch (e) {
setError(e instanceof Error ? e.message : "Unknown error.");
} finally {
setBusy(false);
}
};
const remove = async () => {
if (!note) return;
setError(null);
setBusy(true);
try {
const res = await fetch(`/api/tech-tree-notes/${note.id}`, { method: "DELETE" });
if (!res.ok) {
const responseBody = await res.json().catch(() => null);
throw new Error(
responseBody?.errors?.[0]?.message || `Could not delete the note (HTTP ${res.status}).`,
);
}
onDeleted(note.id);
onOpenChange(false);
} catch (e) {
setError(e instanceof Error ? e.message : "Unknown error.");
} finally {
setBusy(false);
}
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className="border-amber-400/25 rounded-none bg-[#070a0e] sm:max-w-[440px]"
data-testid="tech-note-dialog"
>
<DialogHeader>
<DialogTitle className="font-mono text-xs tracking-widest text-amber-200/80 uppercase">
{isEdit ? "Edit Note" : "New Note"} // Canvas Annotation
</DialogTitle>
</DialogHeader>
<div className="space-y-3">
<div className="space-y-1.5">
<Label
htmlFor="tech-note-title"
className="font-mono text-[10px] tracking-widest text-white/60 uppercase"
>
Title
</Label>
<Input
id="tech-note-title"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="e.g. Tier 3 opens after the next campaign"
data-testid="tech-note-title"
className="rounded-none border-white/20 bg-black/40 text-white placeholder:text-white/30 focus-visible:border-amber-400/60 focus-visible:ring-0"
/>
</div>
<div className="space-y-1.5">
<Label
htmlFor="tech-note-body"
className="font-mono text-[10px] tracking-widest text-white/60 uppercase"
>
Body
</Label>
<Textarea
id="tech-note-body"
value={body}
onChange={(e) => setBody(e.target.value)}
placeholder="Optional detail. Line breaks are preserved."
rows={5}
data-testid="tech-note-body"
className="rounded-none border-white/20 bg-black/40 text-white placeholder:text-white/30 focus-visible:border-amber-400/60 focus-visible:ring-0"
/>
</div>
<label
htmlFor="tech-note-frontend"
className="flex cursor-pointer items-start gap-2 border border-white/10 bg-white/[0.03] px-3 py-2"
>
<input
id="tech-note-frontend"
type="checkbox"
checked={showOnFrontend}
onChange={(e) => setShowOnFrontend(e.target.checked)}
className="mt-0.5 size-4 shrink-0 accent-amber-400"
data-testid="tech-note-frontend"
/>
<span className="space-y-0.5">
<span className="block text-sm text-white/90">Show on frontend</span>
<span className="block text-xs text-white/45">
Off by default. Unpublished notes only appear in this editor.
</span>
</span>
</label>
{error ? (
<p
className="border border-red-400/40 bg-red-400/10 px-2 py-1.5 text-xs text-red-300"
data-testid="tech-note-error"
>
{error}
</p>
) : null}
</div>
<DialogFooter className="gap-2 sm:justify-between">
{isEdit && canDelete ? (
<Button
variant="outline"
onClick={remove}
disabled={busy}
className="border-red-400/40 bg-transparent text-red-300 hover:bg-red-400/10 hover:text-red-200"
data-testid="tech-note-delete"
>
<Trash2Icon className="size-4" />
Delete
</Button>
) : (
<span />
)}
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={busy}
className="border-white/25 bg-transparent text-white/80 hover:bg-white/10 hover:text-white"
>
Cancel
</Button>
<Button
onClick={submit}
disabled={busy}
className="bg-amber-400 text-black hover:bg-amber-300"
data-testid="tech-note-save"
>
{isEdit ? <SaveIcon className="size-4" /> : <PlusIcon className="size-4" />}
{busy ? "Saving..." : isEdit ? "Save" : "Create"}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
);
}

View file

@ -0,0 +1,82 @@
"use client";
import type { Node, NodeProps } from "@xyflow/react";
import React from "react";
import type { TreeNote } from "./types";
export type NoteNodeData = {
note: TreeNote;
/** Editor-only controls are handled by the canvas; the card stays read-only. */
connectable?: boolean;
};
export type NoteNodeModel = Node<NoteNodeData, "noteCard">;
/**
* Amber annotation card. Fixed chrome on purpose: a note must never be
* mistaken for a technology (cyan) or a category band (category accent), in the
* admin editor or on the member-facing tree. It has no handles, so it can never
* become a prerequisite endpoint.
*/
export function NoteNodeCard({ data, selected }: NodeProps<NoteNodeModel>) {
const { note } = data;
return (
<div
data-testid={`tech-note-${note.id}`}
className="relative h-full w-full"
>
<div
className={`flex h-full w-full flex-col overflow-hidden rounded-none border bg-black/70 backdrop-blur-sm transition-colors ${
selected
? "border-amber-300/80 shadow-[0_0_18px_rgba(251,191,36,0.18)]"
: "border-amber-400/40 hover:border-amber-300/70"
}`}
style={{ borderTopWidth: 2 }}
>
{/* Classification strip */}
<div className="flex h-7 shrink-0 items-center justify-between gap-2 border-b border-amber-400/25 bg-amber-400/10 px-3.5">
<span className="truncate leading-none font-mono text-[8px] tracking-widest text-amber-200/80 uppercase">
NOTE // ANNOTATION
</span>
<span
className={`shrink-0 leading-none font-mono text-[8px] tracking-widest uppercase ${
note.showOnFrontend ? "text-emerald-300" : "text-white/35"
}`}
>
{note.showOnFrontend ? "PUBLISHED" : "INTERNAL"}
</span>
</div>
{/* Body: the title keeps a fixed two-line slot and the detail text takes
whatever height is left, so a long title can never clip the body to
nothing (the card height is fixed by the canvas). */}
<div className="flex min-h-0 flex-1 flex-col overflow-hidden px-3.5 py-2">
<div className="line-clamp-2 shrink-0 text-[13px] leading-tight font-semibold text-amber-50">
{note.title}
</div>
{note.body.trim() ? (
<p className="mt-1 min-h-0 flex-1 overflow-hidden text-[10px] leading-snug whitespace-pre-wrap text-white/60">
{note.body}
</p>
) : (
<p className="mt-1 shrink-0 leading-none font-mono text-[8px] tracking-widest text-white/25 uppercase">
No details
</p>
)}
</div>
{/* Footer readout */}
<div className="flex h-6 shrink-0 items-center justify-between border-t border-amber-400/25 bg-black/60 px-3.5">
<span className="leading-none font-mono text-[8px] tracking-widest text-amber-200/60 uppercase">
Annotation
</span>
<span className="leading-none font-mono text-[8px] tracking-widest text-white/35 uppercase">
NOT RESEARCHABLE
</span>
</div>
</div>
</div>
);
}

View file

@ -8,6 +8,7 @@ import {
ReactFlow,
useEdgesState,
useNodesState,
useReactFlow,
type Edge,
type EdgeChange,
type EdgeTypes,
@ -23,6 +24,7 @@ import {
MagnetIcon,
PlusIcon,
SaveIcon,
StickyNoteIcon,
TriangleAlertIcon,
} from "lucide-react";
import { useRouter } from "next/navigation";
@ -46,7 +48,10 @@ import { type RouteRect } from "./edgeRouting";
import { edgeVisuals, type EdgeRef } from "./edgeVisuals";
import { applyPins, pinsToFreeze, type CanvasPosition } from "./freeze";
import { computeLayout } from "./layout";
import { mapCategoryDoc, mapTechDoc } from "./mappers";
import { mapCategoryDoc, mapNoteDoc, mapTechDoc } from "./mappers";
import { NoteDialog } from "./NoteDialog";
import { NoteNodeCard, type NoteNodeData, type NoteNodeModel } from "./NoteNode";
import { computeNoteLayout, noteNodeId, parseNoteNodeId } from "./notes";
import { addPrerequisite, buildPrereqRows, removePrerequisite, withPrereqs } from "./prereqEdits";
import { QuickCreateDialog, type QuickCreateResult } from "./QuickCreateDialog";
import { RoutedEdge } from "./RoutedEdge";
@ -57,6 +62,7 @@ import {
NODE_HEIGHT,
NODE_WIDTH,
type TreeCategory,
type TreeNote,
type TreeTech,
} from "./types";
@ -65,10 +71,13 @@ type ResourceEntry = { id: number; name: string };
export interface TechTreeData {
techs: TreeTech[];
categories: TreeCategory[];
/** Canvas annotations (separate documents from technologies). */
notes: TreeNote[];
resources: ResourceEntry[];
canCreate: boolean;
canCreateCategories: boolean;
canUpdate: boolean;
canDelete: boolean;
canSetFinalApproval: boolean;
}
@ -86,6 +95,7 @@ const SNAP_STORAGE_KEY = "ptf:tech-tree:snap-to-grid";
const nodeTypes: NodeTypes = {
techCard: TechNodeCard,
techBand: CategoryBand,
noteCard: NoteNodeCard,
};
const edgeTypes: EdgeTypes = {
@ -99,6 +109,7 @@ function refLabel(id: number): string {
function buildFlowNodes(
techs: TreeTech[],
categories: TreeCategory[],
notes: TreeNote[],
layout: ReturnType<typeof computeLayout>,
connectable: boolean,
conflictIds: Set<number>,
@ -156,7 +167,39 @@ function buildFlowNodes(
};
});
return [...bandNodes, ...techNodes];
return [...bandNodes, ...techNodes, ...buildNoteNodes(notes, layout, connectable)];
}
/**
* Note nodes: amber annotation cards with NO handles. They sit outside the
* technology layout (their own column unless dragged) and are not selectable,
* so a selection drag can never move one without persisting its position.
*/
function buildNoteNodes(
notes: TreeNote[],
layout: ReturnType<typeof computeLayout>,
draggable: boolean,
): NoteNodeModel[] {
const positions = computeNoteLayout(notes, layout);
const noteById = new Map(notes.map((note) => [note.id, note]));
return positions.flatMap((position) => {
const note = noteById.get(position.noteId);
if (!note) return [];
const data: NoteNodeData = { note };
return [
{
id: noteNodeId(note.id),
type: "noteCard",
position: { x: position.x, y: position.y },
zIndex: 1,
draggable,
selectable: false,
deletable: false,
style: { width: NODE_WIDTH, height: NODE_HEIGHT },
data,
},
];
});
}
function withAlpha(hex: string, alpha: number): string {
@ -174,6 +217,7 @@ function withAlpha(hex: string, alpha: number): string {
*/
function buildFlowEdges(
techs: TreeTech[],
notes: TreeNote[],
layout: ReturnType<typeof computeLayout>,
selectedId: string | null,
edgeRoutes: EdgeRouteMap,
@ -202,13 +246,25 @@ function buildFlowEdges(
const focus = selectedId ? Number(selectedId) : null;
// Node rectangles for obstacle avoidance; each edge excludes its own ends.
const obstacles: RouteRect[] = layout.nodes.map((n) => ({
id: n.techId,
x: n.x,
y: n.y,
width: NODE_WIDTH,
height: NODE_HEIGHT,
}));
// Notes are obstacles too (string ids so they can never be mistaken for a
// technology id), so edges route around annotation cards instead of through
// them.
const obstacles: RouteRect[] = [
...layout.nodes.map((n) => ({
id: n.techId,
x: n.x,
y: n.y,
width: NODE_WIDTH,
height: NODE_HEIGHT,
})),
...computeNoteLayout(notes, layout).map((n) => ({
id: `note-${n.noteId}`,
x: n.x,
y: n.y,
width: NODE_WIDTH,
height: NODE_HEIGHT,
})),
];
return refs.map((ref) => {
const visual = visuals.get(ref.id)!;
@ -273,17 +329,22 @@ class StaleWriteClientError extends Error {
}
}
/** Canvas collections that store a `treePosition` group. */
type CanvasCollection = "technologies" | "tech-tree-notes";
/**
* Persist canvas positions in ONE request (one SQL statement server-side).
* Each entry carries the `updatedAt` the client loaded as an optimistic
* concurrency precondition; the whole batch is rejected (HTTP 409) when any
* guarded row has since changed. Never PATCH per node: dozens of concurrent
* document updates exhausted the database pool and could take the server down.
* Null x/y clears a pin.
* Null x/y clears a pin. `collection` defaults to technologies; note nodes
* write to their own table through the same endpoint.
*/
async function saveTreePositions(
updates: PositionWrite[],
tokens: Map<number, string>,
collection: CanvasCollection = "technologies",
): Promise<Record<string, string>> {
if (updates.length === 0) return {};
const res = await fetch("/api/tech-tree/positions", {
@ -291,6 +352,7 @@ async function saveTreePositions(
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
collection,
positions: updates.map((u) => ({ ...u, ifUnmodifiedAt: tokens.get(u.id) ?? null })),
}),
});
@ -323,11 +385,26 @@ async function fetchCollection<T>(slug: string): Promise<T[]> {
function CanvasInner({ data }: { data: TechTreeData }) {
const router = useRouter();
const { screenToFlowPosition } = useReactFlow<Node, Edge>();
// The canvas surface, used to centre a new note in the current viewport.
const canvasRef = React.useRef<HTMLDivElement>(null);
const [techs, setTechs] = React.useState(data.techs);
const [categories, setCategories] = React.useState(data.categories);
const [notes, setNotes] = React.useState(data.notes);
const [resources, setResources] = React.useState(data.resources);
const [selectedId, setSelectedId] = React.useState<string | null>(null);
const [createOpen, setCreateOpen] = React.useState(false);
// Note editor: null `dialogNote` = create. A create lands at the viewport
// centre (captured when the toolbar button is pressed), an edit never moves
// the node.
const [noteDialogOpen, setNoteDialogOpen] = React.useState(false);
const [dialogNote, setDialogNote] = React.useState<TreeNote | null>(null);
const [noteCreatePosition, setNoteCreatePosition] = React.useState<{
x: number;
y: number;
} | null>(null);
// Label of the layout write in flight ("Arranging...", "Saving positions...");
// null when idle. Drives the toolbar status chip and locks layout controls.
const [layoutBusy, setLayoutBusy] = React.useState<string | null>(null);
@ -338,13 +415,19 @@ function CanvasInner({ data }: { data: TechTreeData }) {
const [positionConflicts, setPositionConflicts] = React.useState<{ id: number; name: string }[]>(
[],
);
const lastFailedWrite = React.useRef<PositionWrite[] | null>(null);
const lastFailedWrite = React.useRef<{
collection: CanvasCollection;
updates: PositionWrite[];
} | null>(null);
// Bumped to reseed the preview panel's draft after a conflict "load latest".
const [panelReseedNonce, setPanelReseedNonce] = React.useState(0);
// Latest technologies list, read by stable callbacks to build concurrency tokens.
const techsRef = React.useRef(techs);
techsRef.current = techs;
// Same for notes: their drag writes take tokens from here.
const notesRef = React.useRef(notes);
notesRef.current = notes;
// Manual edge routing, loaded from this browser's storage on mount. Empty =
// the edge draws its automatic path.
@ -371,13 +454,21 @@ function CanvasInner({ data }: { data: TechTreeData }) {
[positionConflicts],
);
const flowNodes = React.useMemo(
() => buildFlowNodes(techs, categories, layout, data.canUpdate, conflictIds),
[techs, categories, layout, data.canUpdate, conflictIds],
() => buildFlowNodes(techs, categories, notes, layout, data.canUpdate, conflictIds),
[techs, categories, notes, layout, data.canUpdate, conflictIds],
);
const flowEdges = React.useMemo(
() =>
buildFlowEdges(techs, layout, selectedId, edgeRoutes, data.canUpdate, handleRouteChange),
[techs, layout, selectedId, edgeRoutes, data.canUpdate, handleRouteChange],
buildFlowEdges(
techs,
notes,
layout,
selectedId,
edgeRoutes,
data.canUpdate,
handleRouteChange,
),
[techs, notes, layout, selectedId, edgeRoutes, data.canUpdate, handleRouteChange],
);
// Controlled nodes/edges: React Flow needs the change handlers to apply
@ -421,25 +512,52 @@ function CanvasInner({ data }: { data: TechTreeData }) {
});
}, []);
/** Same as applyServerTokens, for the note documents. */
const applyNoteServerTokens = React.useCallback((fresh: Record<string, string>) => {
setNotes((prev) => {
let touched = false;
const next = prev.map((note) => {
const iso = fresh[String(note.id)];
if (!iso || iso === note.updatedAt) return note;
touched = true;
return { ...note, updatedAt: iso };
});
return touched ? next : prev;
});
}, []);
/**
* Bulk position write guarded by optimistic concurrency tokens taken from
* the current tree (or an explicit fresher source during a freeze refresh).
* On a version conflict the failed batch is recorded and the toolbar banner
* offers refresh / force-overwrite; the error is rethrown so callers keep
* their existing failure handling (pin restoration, chips).
*
* `collection` selects which canvas documents the ids belong to: note nodes
* live in their own table and take their tokens from the note list.
*/
const writePositions = React.useCallback(
async (updates: PositionWrite[], tokenSource?: TreeTech[]) => {
async (
updates: PositionWrite[],
tokenSource?: TreeTech[],
collection: CanvasCollection = "technologies",
) => {
if (updates.length === 0) return;
const source = tokenSource ?? techsRef.current;
const tokens = new Map(source.map((t) => [t.id, t.updatedAt]));
const tokens =
collection === "technologies"
? new Map((tokenSource ?? techsRef.current).map((t) => [t.id, t.updatedAt]))
: new Map(notesRef.current.map((note) => [note.id, note.updatedAt]));
try {
const fresh = await saveTreePositions(updates, tokens);
applyServerTokens(fresh);
const fresh = await saveTreePositions(updates, tokens, collection);
if (collection === "technologies") applyServerTokens(fresh);
else applyNoteServerTokens(fresh);
} catch (e) {
if (e instanceof PositionConflictError) {
lastFailedWrite.current = updates;
const nameById = new Map(techsRef.current.map((t) => [t.id, t.name]));
lastFailedWrite.current = { collection, updates };
const nameById = new Map<number, string>([
...techsRef.current.map((t) => [t.id, t.name] as const),
...notesRef.current.map((note) => [note.id, note.title] as const),
]);
setPositionConflicts(
e.conflicts.map((c) => ({ id: c.id, name: nameById.get(c.id) ?? `#${c.id}` })),
);
@ -447,7 +565,7 @@ function CanvasInner({ data }: { data: TechTreeData }) {
throw e;
}
},
[applyServerTokens],
[applyServerTokens, applyNoteServerTokens],
);
/** Persist freeze pins (skipping ids whose own PATCH already carries one). */
@ -492,7 +610,8 @@ function CanvasInner({ data }: { data: TechTreeData }) {
return () => window.clearTimeout(timer);
}, [connectError]);
const hasManualPositions = techs.some((t) => t.treePosition !== null);
const hasManualPositions =
techs.some((t) => t.treePosition !== null) || notes.some((n) => n.treePosition !== null);
const [saveStatus, setSaveStatus] = React.useState<string | null>(null);
React.useEffect(() => {
@ -674,6 +793,34 @@ function CanvasInner({ data }: { data: TechTreeData }) {
[writePositions],
);
/**
* Persist note-node positions. Notes live in their own collection, so the
* write targets `tech-tree-notes` while the endpoint and concurrency guard
* stay identical to technology drags.
*/
const persistNotePositions = React.useCallback(
async (positions: { id: number; x: number; y: number }[]) => {
if (positions.length === 0) return;
const byId = new Map(positions.map((p) => [p.id, p]));
setNotes((prev) =>
prev.map((note) => {
const p = byId.get(note.id);
return p ? { ...note, treePosition: { x: p.x, y: p.y } } : note;
}),
);
try {
await writePositions(positions, undefined, "tech-tree-notes");
} catch (e) {
// Same contract as technology cards: the optimistic position stays on
// screen, a reload shows what is stored, conflicts use the banner.
if (!(e instanceof PositionConflictError)) {
setConnectError(e instanceof Error ? e.message : "Could not save the note position.");
}
}
},
[writePositions],
);
// Live session for a category-band drag: the header moves the band and every
// member card moves with it (positions are committed on drag stop).
const bandDragRef = React.useRef<{
@ -739,6 +886,17 @@ function CanvasInner({ data }: { data: TechTreeData }) {
}
// A card drag can move a whole multi-selection: persist every dragged card
// (React Flow hands us the full set, not just the one under the pointer).
const noteCards = allNodes.filter((n) => n.type === "noteCard");
if (noteCards.length > 0) {
void persistNotePositions(
noteCards.map((n) => ({
id: Number(parseNoteNodeId(n.id)),
x: snapValue(n.position.x),
y: snapValue(n.position.y),
})),
);
return;
}
const cards = allNodes.filter((n) => n.type === "techCard");
if (cards.length === 0) return;
void persistPositions(
@ -749,14 +907,15 @@ function CanvasInner({ data }: { data: TechTreeData }) {
})),
);
},
[persistPositions, snapValue],
[persistPositions, persistNotePositions, snapValue],
);
const handleSavePositions = React.useCallback(async () => {
// Commit the current on-screen position of every node to treePosition, so
// the exact arrangement survives a reload. Unlike a drag (one node) or a
// connection (only what would move), this pins the whole tree to whatever
// React Flow actually rendered.
// React Flow actually rendered. Notes are pinned too, through their own
// collection write.
const pins = new Map<number, CanvasPosition>();
const current = currentPositions();
for (const tech of techs) {
@ -765,7 +924,17 @@ function CanvasInner({ data }: { data: TechTreeData }) {
pins.set(tech.id, { x: Math.round(pos.x), y: Math.round(pos.y) });
}
}
if (pins.size === 0) {
const notePins = new Map<number, CanvasPosition>();
for (const node of nodesRef.current) {
if (node.type !== "noteCard") continue;
const noteId = parseNoteNodeId(node.id);
if (noteId === null) continue;
notePins.set(noteId, {
x: Math.round(node.position.x),
y: Math.round(node.position.y),
});
}
if (pins.size === 0 && notePins.size === 0) {
setSaveStatus("Nothing to save.");
return;
}
@ -776,11 +945,24 @@ function CanvasInner({ data }: { data: TechTreeData }) {
return pin ? { ...t, treePosition: pin } : t;
}),
);
setNotes((prev) =>
prev.map((note) => {
const pin = notePins.get(note.id);
return pin ? { ...note, treePosition: pin } : note;
}),
);
setLayoutBusy("Saving positions...");
setConnectError(null);
try {
await persistPins(pins);
setSaveStatus(`Positions saved. ${pins.size} node(s).`);
await writePositions(
[...notePins].map(([id, pin]) => ({ id, x: pin.x, y: pin.y })),
undefined,
"tech-tree-notes",
);
setSaveStatus(
`Positions saved. ${pins.size + notePins.size} node(s).`,
);
} catch (e) {
if (!(e instanceof PositionConflictError)) {
setConnectError(e instanceof Error ? e.message : "Could not save positions.");
@ -788,33 +970,49 @@ function CanvasInner({ data }: { data: TechTreeData }) {
} finally {
setLayoutBusy(null);
}
}, [techs, currentPositions, persistPins, layoutBusy]);
}, [techs, currentPositions, persistPins, layoutBusy, writePositions]);
const handleAutoArrange = React.useCallback(async () => {
const pinned = techs.filter((t) => t.treePosition !== null);
if (pinned.length === 0 || layoutBusy) return;
const pinnedNotes = notes.filter((n) => n.treePosition !== null);
if ((pinned.length === 0 && pinnedNotes.length === 0) || layoutBusy) return;
const previous = new Map(pinned.map((t) => [t.id, t.treePosition]));
const previousNotes = new Map(pinnedNotes.map((n) => [n.id, n.treePosition]));
// Optimistic: re-lay the canvas out at once so the click visibly does
// something, then persist every cleared pin in a single request.
// something, then persist every cleared pin in a single request per
// collection (technologies, then note nodes).
setLayoutBusy("Arranging...");
setConnectError(null);
setTechs((prev) => prev.map((t) => (t.treePosition ? { ...t, treePosition: null } : t)));
setNotes((prev) => prev.map((n) => (n.treePosition ? { ...n, treePosition: null } : n)));
try {
await writePositions(pinned.map((t) => ({ id: t.id, x: null, y: null })));
setSaveStatus(`Layout reset. ${pinned.length} node(s) re-arranged.`);
await writePositions(
pinnedNotes.map((n) => ({ id: n.id, x: null, y: null })),
undefined,
"tech-tree-notes",
);
setSaveStatus(
`Layout reset. ${pinned.length + pinnedNotes.length} node(s) re-arranged.`,
);
} catch (e) {
// Put the pins back so the canvas matches what is actually stored.
setTechs((prev) =>
prev.map((t) => (previous.has(t.id) ? { ...t, treePosition: previous.get(t.id) ?? null } : t)),
);
setNotes((prev) =>
prev.map((n) =>
previousNotes.has(n.id) ? { ...n, treePosition: previousNotes.get(n.id) ?? null } : n,
),
);
if (!(e instanceof PositionConflictError)) {
setConnectError(e instanceof Error ? e.message : "Could not reset the layout.");
}
} finally {
setLayoutBusy(null);
}
}, [techs, layoutBusy, writePositions]);
}, [techs, notes, layoutBusy, writePositions]);
const techById = React.useMemo(
() => new Map(techs.map((t) => [String(t.id), t])),
@ -829,9 +1027,10 @@ function CanvasInner({ data }: { data: TechTreeData }) {
*/
const refresh = React.useCallback(
async (options: { freeze?: boolean } = {}) => {
const [techDocs, categoryDocs, resourceDocs] = await Promise.all([
const [techDocs, categoryDocs, noteDocs, resourceDocs] = await Promise.all([
fetchCollection<Record<string, unknown>>("technologies"),
fetchCollection<Record<string, unknown>>("tech-categories"),
fetchCollection<Record<string, unknown>>("tech-tree-notes"),
fetchCollection<Record<string, unknown>>("resources"),
]);
let nextTechs = techDocs.map(mapTechDoc);
@ -843,6 +1042,7 @@ function CanvasInner({ data }: { data: TechTreeData }) {
}
setTechs(nextTechs);
setCategories(nextCategories);
setNotes(noteDocs.map(mapNoteDoc));
setResources(resourceDocs.map((d) => ({ id: d.id as number, name: String(d.name ?? "") })));
if (freezePins) {
// Persist AFTER setTechs and with the freshly fetched docs as the token
@ -868,15 +1068,16 @@ function CanvasInner({ data }: { data: TechTreeData }) {
const batch = lastFailedWrite.current;
if (!batch) return;
try {
const fresh = await saveTreePositions(batch, new Map());
applyServerTokens(fresh);
const fresh = await saveTreePositions(batch.updates, new Map(), batch.collection);
if (batch.collection === "technologies") applyServerTokens(fresh);
else applyNoteServerTokens(fresh);
setPositionConflicts([]);
lastFailedWrite.current = null;
setSaveStatus(`Positions overwritten. ${batch.length} node(s).`);
setSaveStatus(`Positions overwritten. ${batch.updates.length} node(s).`);
} catch (e) {
setConnectError(e instanceof Error ? e.message : "Could not overwrite positions.");
}
}, [applyServerTokens]);
}, [applyServerTokens, applyNoteServerTokens]);
const handleCreated = React.useCallback(
async (result: QuickCreateResult) => {
@ -887,6 +1088,54 @@ function CanvasInner({ data }: { data: TechTreeData }) {
[refresh, router],
);
/**
* New notes land at the viewport centre (captured here, while the canvas
* rect is known) and are freely draggable afterwards. Falls back to the
* automatic notes column when the canvas is not measurable.
*/
const openNewNote = React.useCallback(() => {
const rect = canvasRef.current?.getBoundingClientRect();
if (rect) {
const centre = screenToFlowPosition({
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2,
});
setNoteCreatePosition({
x: snapValue(centre.x - NODE_WIDTH / 2),
y: snapValue(centre.y - NODE_HEIGHT / 2),
});
} else {
setNoteCreatePosition(null);
}
setDialogNote(null);
setNoteDialogOpen(true);
}, [screenToFlowPosition, snapValue]);
const openEditNote = React.useCallback((note: TreeNote) => {
setDialogNote(note);
setNoteCreatePosition(null);
setNoteDialogOpen(true);
}, []);
const handleNoteSaved = React.useCallback((saved: TreeNote) => {
setNotes((prev) =>
prev.some((note) => note.id === saved.id)
? prev.map((note) => (note.id === saved.id ? saved : note))
: [...prev, saved],
);
setSaveStatus("Note saved.");
}, []);
const handleNoteDeleted = React.useCallback((noteId: number) => {
setNotes((prev) => prev.filter((note) => note.id !== noteId));
setSaveStatus("Note deleted.");
}, []);
const selectedNote = React.useMemo(
() => (dialogNote ? notes.find((note) => note.id === dialogNote.id) ?? dialogNote : null),
[dialogNote, notes],
);
const selectedWarnings = React.useMemo(
() =>
selectedTech
@ -897,6 +1146,7 @@ function CanvasInner({ data }: { data: TechTreeData }) {
return (
<div
ref={canvasRef}
className="relative tech-tree-canvas"
style={{
height: "calc(100dvh - 56px)",
@ -938,6 +1188,8 @@ function CanvasInner({ data }: { data: TechTreeData }) {
const nodeElement = element?.closest?.(".react-flow__node") as HTMLElement | null;
const targetId = nodeElement?.getAttribute("data-id");
if (!targetId || targetId === sourceId) return;
// Notes are annotations, never prerequisite endpoints.
if (parseNoteNodeId(targetId) !== null) return;
void handleConnect({ source: sourceId, target: targetId });
}}
onEdgesDelete={(deleted) => {
@ -948,6 +1200,10 @@ function CanvasInner({ data }: { data: TechTreeData }) {
// pop the side panel, which would cover the canvas mid-selection.
if (event.ctrlKey || event.metaKey) return;
if (node.type === "techCard") setSelectedId(node.id);
if (node.type === "noteCard") {
const note = (node.data as NoteNodeData).note;
if (note) openEditNote(note);
}
}}
onNodeDragStart={(_, node) => handleNodeDragStart(node)}
onNodeDrag={(_, node) => handleNodeDrag(node)}
@ -1088,6 +1344,19 @@ function CanvasInner({ data }: { data: TechTreeData }) {
New Technology
</Button>
) : null}
{data.canCreate ? (
<Button
size="sm"
variant="ghost"
onClick={openNewNote}
title="Add an annotation card to the canvas. Notes are backend-only unless you tick Show on frontend."
data-testid="tech-tree-create-note"
className={`${TACTICAL_BUTTON} border-amber-400/40 text-amber-200 hover:border-amber-300/70 hover:bg-amber-400/10 hover:text-amber-100`}
>
<StickyNoteIcon className="size-3.5" />
New Note
</Button>
) : null}
{data.canUpdate ? (
<span className="hidden font-mono text-[9px] tracking-widest text-white/35 uppercase lg:inline">
DRAG NODE EDGE TO LINK A PREREQUISITE · SELECT AN EDGE + BACKSPACE TO REMOVE
@ -1096,7 +1365,7 @@ function CanvasInner({ data }: { data: TechTreeData }) {
</div>
{/* Empty state */}
{techs.length === 0 ? (
{techs.length === 0 && notes.length === 0 ? (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center">
<div className="pointer-events-auto rounded-none border border-white/15 bg-black/70 px-6 py-5 text-center backdrop-blur-sm">
<p className="font-mono text-[10px] tracking-widest text-white/50 uppercase">
@ -1155,6 +1424,16 @@ function CanvasInner({ data }: { data: TechTreeData }) {
canCreateCategories={data.canCreateCategories}
onCreated={handleCreated}
/>
<NoteDialog
open={noteDialogOpen}
onOpenChange={setNoteDialogOpen}
note={selectedNote}
createPosition={noteCreatePosition}
canDelete={data.canDelete}
onSaved={handleNoteSaved}
onDeleted={handleNoteDeleted}
/>
</div>
);
}

View file

@ -5,7 +5,7 @@ import { hasPermission } from "@/utils/access-control/hasPermission";
import { hasIntelligenceQualification } from "@/utils/access-control/hasIntelligenceQualification";
import { TechTreeCanvas, type TechTreeData } from "./TechTreeCanvas";
import { mapCategoryDoc, mapTechDoc } from "./mappers";
import { mapCategoryDoc, mapNoteDoc, mapTechDoc } from "./mappers";
/**
* Root admin view at /admin/tech-tree. Custom views are public by default, so
@ -65,9 +65,10 @@ export async function TechTreeView({
);
}
const [techDocs, categoryDocs, resourceDocs] = await Promise.all([
const [techDocs, categoryDocs, noteDocs, resourceDocs] = await Promise.all([
payload.find({ collection: "technologies", depth: 0, limit: 0, sort: "name" }),
payload.find({ collection: "tech-categories", depth: 0, limit: 0, sort: "name" }),
payload.find({ collection: "tech-tree-notes", depth: 0, limit: 0, sort: "createdAt" }),
payload.find({ collection: "resources", depth: 0, limit: 0, sort: "name" }),
]);
@ -76,12 +77,14 @@ export async function TechTreeView({
categories: categoryDocs.docs.map((doc) =>
mapCategoryDoc(doc as unknown as Record<string, unknown>),
),
notes: noteDocs.docs.map((doc) => mapNoteDoc(doc as unknown as Record<string, unknown>)),
resources: resourceDocs.docs.map((doc) => ({ id: doc.id, name: doc.name })),
canCreate:
(await hasPermission(payload, user, "technologies:create")) || intelQualified,
canCreateCategories:
(await hasPermission(payload, user, "tech-categories:create")) || intelQualified,
canUpdate: (await hasPermission(payload, user, "technologies:update")) || intelQualified,
canDelete: (await hasPermission(payload, user, "technologies:delete")) || intelQualified,
canSetFinalApproval: await hasPermission(payload, user, "system:admin-access"),
};

View file

@ -1,4 +1,4 @@
import type { TreeCategory, TreeTech } from "./types";
import type { TreeCategory, TreeNote, TreeTech } from "./types";
/**
* Project a `technologies` REST/local API doc (depth 0: relationships are
@ -66,3 +66,29 @@ export function mapCategoryDoc(doc: Record<string, unknown>): TreeCategory {
color: typeof doc.color === "string" && doc.color ? doc.color : null,
};
}
/**
* Project a `tech-tree-notes` doc (depth 0) into the TreeNote shape. The
* frontend visibility flag is strict (`=== true`) so an unset value keeps the
* collection's "backend only" default instead of leaking a note to members.
*/
export function mapNoteDoc(doc: Record<string, unknown>): TreeNote {
const manualPosition = doc.treePosition as { x?: unknown; y?: unknown } | null | undefined;
const treePosition =
manualPosition &&
typeof manualPosition.x === "number" &&
typeof manualPosition.y === "number" &&
Number.isFinite(manualPosition.x) &&
Number.isFinite(manualPosition.y)
? { x: manualPosition.x, y: manualPosition.y }
: null;
return {
id: doc.id as number,
title: String(doc.title ?? ""),
body: typeof doc.body === "string" ? doc.body : "",
showOnFrontend: doc.showOnFrontend === true,
treePosition,
updatedAt: String(doc.updatedAt ?? ""),
};
}

View file

@ -0,0 +1,55 @@
import { COLUMN_STEP, ROW_STEP, type TreeNote, type TechTreeLayout } from "./types";
/**
* Pure layout helpers for Tech Tree note nodes.
*
* Notes are annotations, not technologies: they never enter `computeLayout`,
* never affect edges, and are not counted as prerequisites or columns. A note
* only owns a canvas position:
* - dragged notes use their manual `treePosition`;
* - untouched notes stack in a dedicated notes column to the right of the
* technology columns, in creation order.
*
* Note node ids are prefixed so a note id can never collide with a technology
* id in the React Flow node list (both are independent auto-increment integers).
*/
export const NOTE_NODE_PREFIX = "note-";
export function noteNodeId(noteId: number): string {
return `${NOTE_NODE_PREFIX}${noteId}`;
}
/** Returns the note id for a note node id, or null for any other node. */
export function parseNoteNodeId(nodeId: string): number | null {
if (!nodeId.startsWith(NOTE_NODE_PREFIX)) return null;
const id = Number(nodeId.slice(NOTE_NODE_PREFIX.length));
return Number.isInteger(id) && id > 0 ? id : null;
}
export type NoteLayoutNode = {
noteId: number;
x: number;
y: number;
};
/**
* Positions for every note. `tree.columns` is the number of technology
* columns in use, so the fallback notes column sits one step to its right
* (column 0 when the tree is empty).
*/
export function computeNoteLayout(
notes: TreeNote[],
tree: Pick<TechTreeLayout, "columns">,
): NoteLayoutNode[] {
const fallbackColumn = Math.max(0, tree.columns);
let nextRow = 0;
return notes.map((note) => {
if (note.treePosition) {
return { noteId: note.id, x: note.treePosition.x, y: note.treePosition.y };
}
const row = nextRow;
nextRow += 1;
return { noteId: note.id, x: fallbackColumn * COLUMN_STEP, y: row * ROW_STEP };
});
}

View file

@ -34,6 +34,27 @@ export type TreeCategory = {
color: string | null;
};
/**
* Annotation card on the canvas. Deliberately separate from `TreeTech`:
* notes carry no prerequisites, costs, approval workflow or research state, so
* they are invisible to the layout engine and the research rules. They only
* share the canvas geometry and the bulk position write path.
*/
export type TreeNote = {
id: number;
title: string;
body: string;
/**
* Published to the member-facing tech tree. Defaults to false in the
* collection, so a note is an authoring aid until someone opts it in.
*/
showOnFrontend: boolean;
/** Manual canvas position (dragged note); null = notes column beside the tree. */
treePosition: { x: number; y: number } | null;
/** Optimistic concurrency token for bulk position writes. */
updatedAt: string;
};
export type LayoutWarning = {
techId: number;
message: string;

View file

@ -19,6 +19,8 @@ import { CategoryBand } from "@/components/admin/tech-tree/CategoryBand";
import { computeLayout } from "@/components/admin/tech-tree/layout";
import { edgeVisuals, type EdgeRef } from "@/components/admin/tech-tree/edgeVisuals";
import { type RouteRect } from "@/components/admin/tech-tree/edgeRouting";
import { NoteNodeCard, type NoteNodeData, type NoteNodeModel } from "@/components/admin/tech-tree/NoteNode";
import { computeNoteLayout, noteNodeId } from "@/components/admin/tech-tree/notes";
import { RoutedEdge } from "@/components/admin/tech-tree/RoutedEdge";
import { TechNodeCard, type TechNodeModel } from "@/components/admin/tech-tree/TechNode";
import {
@ -26,6 +28,7 @@ import {
NODE_HEIGHT,
NODE_WIDTH,
type TreeCategory,
type TreeNote,
type TreeTech,
} from "@/components/admin/tech-tree/types";
@ -47,6 +50,7 @@ const nodeTypes: NodeTypes = {
techCard: TechNodeCard,
techBand: CategoryBand,
veilCard: VeilNodeCard,
noteCard: NoteNodeCard,
};
const edgeTypes: EdgeTypes = {
@ -126,6 +130,7 @@ function StatusOverlay({ status }: { status: TechViewState }) {
function buildNodes(
techs: TreeTech[],
categories: TreeCategory[],
notes: TreeNote[],
statuses: Record<number, TechViewState>,
layout: ReturnType<typeof computeLayout>,
): Node[] {
@ -186,11 +191,38 @@ function buildNodes(
} satisfies TechNodeModel;
});
return [...bandNodes, ...techNodes];
return [...bandNodes, ...techNodes, ...buildNoteNodes(notes, layout)];
}
/**
* Published notes reuse the admin amber annotation card, so the two views stay
* visually identical. Read-only here: no dragging, no handles.
*/
function buildNoteNodes(notes: TreeNote[], layout: ReturnType<typeof computeLayout>): NoteNodeModel[] {
const noteById = new Map(notes.map((note) => [note.id, note]));
return computeNoteLayout(notes, layout).flatMap((position) => {
const note = noteById.get(position.noteId);
if (!note) return [];
const data: NoteNodeData = { note };
return [
{
id: noteNodeId(note.id),
type: "noteCard",
position: { x: position.x, y: position.y },
zIndex: 1,
draggable: false,
selectable: false,
deletable: false,
style: { width: NODE_WIDTH, height: NODE_HEIGHT },
data,
},
];
});
}
function buildEdges(
techs: TreeTech[],
notes: TreeNote[],
layout: ReturnType<typeof computeLayout>,
selectedId: string | null,
): Edge[] {
@ -215,13 +247,23 @@ function buildEdges(
const visuals = edgeVisuals(techs, refs, positions, COLUMN_STEP);
const focus = selectedId ? Number(selectedId) : null;
const obstacles: RouteRect[] = layout.nodes.map((n) => ({
id: n.techId,
x: n.x,
y: n.y,
width: NODE_WIDTH,
height: NODE_HEIGHT,
}));
const obstacles: RouteRect[] = [
...layout.nodes.map((n) => ({
id: n.techId,
x: n.x,
y: n.y,
width: NODE_WIDTH,
height: NODE_HEIGHT,
})),
// Published notes are obstacles too, so no edge is drawn through them.
...computeNoteLayout(notes, layout).map((n) => ({
id: `note-${n.noteId}`,
x: n.x,
y: n.y,
width: NODE_WIDTH,
height: NODE_HEIGHT,
})),
];
return refs.map((ref) => {
const visual = visuals.get(ref.id)!;
@ -269,17 +311,28 @@ function buildEdges(
export interface FrontendTechTreeCanvasProps {
techs: TreeTech[];
categories: TreeCategory[];
notes: TreeNote[];
statuses: Record<number, TechViewState>;
selectedId: number | null;
onSelect: (technologyId: number) => void;
}
function CanvasInner({ techs, categories, statuses, selectedId, onSelect }: FrontendTechTreeCanvasProps) {
function CanvasInner({
techs,
categories,
notes,
statuses,
selectedId,
onSelect,
}: FrontendTechTreeCanvasProps) {
const layout = React.useMemo(() => computeLayout(techs, categories), [techs, categories]);
const nodes = React.useMemo(() => buildNodes(techs, categories, statuses, layout), [techs, categories, statuses, layout]);
const nodes = React.useMemo(
() => buildNodes(techs, categories, notes, statuses, layout),
[techs, categories, notes, statuses, layout],
);
const edges = React.useMemo(
() => buildEdges(techs, layout, selectedId != null ? String(selectedId) : null),
[techs, layout, selectedId],
() => buildEdges(techs, notes, layout, selectedId != null ? String(selectedId) : null),
[techs, notes, layout, selectedId],
);
return (

View file

@ -15,12 +15,15 @@ import type {
TechDetailView,
TechViewState,
TreeCategory,
TreeNote,
TreeTech,
} from "./types";
export interface TechTreeClientProps {
techs: TreeTech[];
categories: TreeCategory[];
/** Published annotation cards (showOnFrontend = true). */
notes: TreeNote[];
statuses: Record<number, TechViewState>;
details: Record<number, TechDetailView>;
activeResearch: ActiveResearchView[];
@ -37,6 +40,7 @@ export interface TechTreeClientProps {
export function TechTreeClient({
techs,
categories,
notes,
statuses,
details,
activeResearch,
@ -59,6 +63,7 @@ export function TechTreeClient({
<FrontendTechTreeCanvas
techs={techs}
categories={categories}
notes={notes}
statuses={statuses}
selectedId={selectedId}
onSelect={setSelectedId}

View file

@ -1,6 +1,6 @@
import type { TreeCategory, TreeTech } from "@/components/admin/tech-tree/types";
import type { TreeCategory, TreeNote, TreeTech } from "@/components/admin/tech-tree/types";
export type { TreeCategory, TreeTech };
export type { TreeCategory, TreeNote, TreeTech };
/** Per-technology view state for the member-facing tree. */
export type TechViewState = {

View file

@ -1,4 +1,5 @@
import { sql } from "@payloadcms/db-postgres";
import type { PgTable } from "drizzle-orm/pg-core";
import type { Payload } from "payload";
import type { PositionConflict } from "@/lib/tech-tree/concurrency";
@ -30,6 +31,27 @@ import type { PositionConflict } from "@/lib/tech-tree/concurrency";
/** Hard cap per request so a malformed client cannot build a giant statement. */
export const MAX_POSITION_UPDATES = 2000;
/**
* Canvas collections that persist a `treePosition` group, mapped to their real
* table names. A note node is a separate document (`tech-tree-notes`) that lives
* on the same canvas, so both collections share this one bulk write path.
*/
export const POSITION_COLLECTION_TABLES = {
technologies: "technologies",
"tech-tree-notes": "tech_tree_notes",
} as const;
export type TreePositionCollection = keyof typeof POSITION_COLLECTION_TABLES;
const DEFAULT_POSITION_COLLECTION: TreePositionCollection = "technologies";
function isPositionCollection(value: unknown): value is TreePositionCollection {
return (
typeof value === "string" &&
Object.prototype.hasOwnProperty.call(POSITION_COLLECTION_TABLES, value)
);
}
export type TreePositionUpdate = {
id: number;
/** Both numbers to pin a node, both null to return it to the automatic layout. */
@ -54,11 +76,27 @@ export type PositionWriteResult = {
};
export type ParseResult =
| { ok: true; updates: TreePositionUpdate[] }
| { ok: true; collection: TreePositionCollection; updates: TreePositionUpdate[] }
| { ok: false; error: string };
/** Validate a `{ positions: [...] }` request body. Pure. */
/**
* Validate a `{ collection?, positions: [...] }` request body. Pure.
*
* `collection` defaults to `technologies` so every existing caller keeps
* working; note drags send `tech-tree-notes`.
*/
export function parsePositionUpdates(body: unknown): ParseResult {
const rawCollection = (body as { collection?: unknown } | null)?.collection;
if (rawCollection !== undefined && !isPositionCollection(rawCollection)) {
return {
ok: false,
error: `collection must be one of: ${Object.keys(POSITION_COLLECTION_TABLES).join(", ")}.`,
};
}
const collection = isPositionCollection(rawCollection)
? rawCollection
: DEFAULT_POSITION_COLLECTION;
const positions = (body as { positions?: unknown } | null)?.positions;
if (!Array.isArray(positions)) return { ok: false, error: "positions must be an array." };
if (positions.length > MAX_POSITION_UPDATES) {
@ -97,7 +135,7 @@ export function parsePositionUpdates(body: unknown): ParseResult {
: { id, x: Math.round(x as number), y: Math.round(y as number), expectedUpdatedAt },
);
}
return { ok: true, updates: [...byId.values()] };
return { ok: true, collection, updates: [...byId.values()] };
}
/** The pg driver hands timestamps back as Dates; the API speaks ISO strings. */
@ -107,19 +145,36 @@ function toIsoString(value: unknown): string | null {
return String(value);
}
/** Resolve the drizzle table for a canvas collection (fails loudly if unregistered). */
function resolvePositionTable(payload: Payload, collection: TreePositionCollection): PgTable {
const tableName = POSITION_COLLECTION_TABLES[collection];
const tables = (payload.db as unknown as { tables?: Record<string, PgTable> }).tables;
const table = tables?.[tableName];
if (!table) {
throw new Error(`Tech Tree positions: table "${tableName}" is not registered.`);
}
return table;
}
/**
* Write every position in a single conditional UPDATE. Rows whose
* `expectedUpdatedAt` is set only match while the stored `updated_at` still
* equals it; one mismatch aborts the whole statement (all-or-nothing). When
* fewer rows were touched than requested, a follow-up read classifies which
* ids conflicted (missing ids stay silently ignored, as before).
*
* `collection` selects the target table: technologies (default) or the
* note-node documents that share the same canvas.
*/
export async function writeTreePositions(
payload: Payload,
updates: TreePositionUpdate[],
collection: TreePositionCollection = DEFAULT_POSITION_COLLECTION,
): Promise<PositionWriteResult> {
if (updates.length === 0) return { updated: 0, conflicts: [], tokens: {} };
const target = resolvePositionTable(payload, collection);
const values = sql.join(
updates.map((u) => sql`(${u.id}::integer, ${u.x}::numeric, ${u.y}::numeric, ${
u.expectedUpdatedAt === null ? sql`NULL` : sql`${u.expectedUpdatedAt}`
@ -133,10 +188,10 @@ export async function writeTreePositions(
conflicts AS (
SELECT i.id
FROM input i
JOIN technologies t ON t.id = i.id
JOIN ${target} t ON t.id = i.id
WHERE i.expected IS NOT NULL AND t.updated_at <> i.expected
)
UPDATE technologies AS t
UPDATE ${target} AS t
SET tree_position_x = i.x, tree_position_y = i.y, updated_at = now()
FROM input i
WHERE t.id = i.id
@ -157,7 +212,7 @@ export async function writeTreePositions(
// Cold path: some ids are missing or a precondition failed. Classify with
// one read so the caller gets actionable conflict data in the same round trip.
const check = await payload.db.drizzle.execute(sql`
SELECT id, updated_at FROM technologies
SELECT id, updated_at FROM ${target}
WHERE id IN (${sql.join(
updates.map((u) => sql`${u.id}::integer`),
sql`, `,

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,39 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TABLE "tech_tree_notes" (
"id" serial PRIMARY KEY NOT NULL,
"title" varchar NOT NULL,
"body" varchar,
"show_on_frontend" boolean DEFAULT false,
"tree_position_x" numeric,
"tree_position_y" numeric,
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
);
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_tree_notes_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_tree_notes_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_tree_notes_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "tech_tree_notes_delete" boolean DEFAULT false;
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "tech_tree_notes_id" integer;
CREATE INDEX "tech_tree_notes_updated_at_idx" ON "tech_tree_notes" USING btree ("updated_at");
CREATE INDEX "tech_tree_notes_created_at_idx" ON "tech_tree_notes" USING btree ("created_at");
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_tech_tree_notes_fk" FOREIGN KEY ("tech_tree_notes_id") REFERENCES "public"."tech_tree_notes"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "payload_locked_documents_rels_tech_tree_notes_id_idx" ON "payload_locked_documents_rels" USING btree ("tech_tree_notes_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "tech_tree_notes" DISABLE ROW LEVEL SECURITY;
DROP TABLE "tech_tree_notes" CASCADE;
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_tech_tree_notes_fk";
DROP INDEX "payload_locked_documents_rels_tech_tree_notes_id_idx";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_tree_notes_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_tree_notes_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_tree_notes_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "tech_tree_notes_delete";
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "tech_tree_notes_id";`)
}

View file

@ -163,6 +163,7 @@ import * as migration_20261118_184813_add_faction_relation_entries from './20261
import * as migration_20261118_184851_drop_factions_relationships_array from './20261118_184851_drop_factions_relationships_array';
import * as migration_20261120_234950_add_locker_unlimited from './20261120_234950_add_locker_unlimited';
import * as migration_20261121_015435_add_mission_attendance_unlocks from './20261121_015435_add_mission_attendance_unlocks';
import * as migration_20261123_073019_add_tech_tree_notes from './20261123_073019_add_tech_tree_notes';
export const migrations = [
{
@ -988,6 +989,11 @@ export const migrations = [
{
up: migration_20261121_015435_add_mission_attendance_unlocks.up,
down: migration_20261121_015435_add_mission_attendance_unlocks.down,
name: '20261121_015435_add_mission_attendance_unlocks'
name: '20261121_015435_add_mission_attendance_unlocks',
},
{
up: migration_20261123_073019_add_tech_tree_notes.up,
down: migration_20261123_073019_add_tech_tree_notes.down,
name: '20261123_073019_add_tech_tree_notes'
},
];

View file

@ -110,6 +110,7 @@ export interface Config {
'faction-relation-entries': FactionRelationEntry;
technologies: Technology;
'tech-categories': TechCategory;
'tech-tree-notes': TechTreeNote;
'tech-researches': TechResearch;
'tech-ballots': TechBallot;
'tech-ballot-votes': TechBallotVote;
@ -227,6 +228,7 @@ export interface Config {
'faction-relation-entries': FactionRelationEntriesSelect<false> | FactionRelationEntriesSelect<true>;
technologies: TechnologiesSelect<false> | TechnologiesSelect<true>;
'tech-categories': TechCategoriesSelect<false> | TechCategoriesSelect<true>;
'tech-tree-notes': TechTreeNotesSelect<false> | TechTreeNotesSelect<true>;
'tech-researches': TechResearchesSelect<false> | TechResearchesSelect<true>;
'tech-ballots': TechBallotsSelect<false> | TechBallotsSelect<true>;
'tech-ballot-votes': TechBallotVotesSelect<false> | TechBallotVotesSelect<true>;
@ -5169,6 +5171,36 @@ export interface FactionRelationEntry {
updatedAt: string;
createdAt: string;
}
/**
* Annotation cards on the Tech Tree canvas. Edited from /admin/tech-tree; hidden from the sidebar.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "tech-tree-notes".
*/
export interface TechTreeNote {
id: number;
/**
* Short heading shown on the note card.
*/
title: string;
/**
* Free text shown under the title. Line breaks are preserved.
*/
body?: string | null;
/**
* Tick to publish this note on the member-facing Tech Tree. Notes are backend-only until this is enabled.
*/
showOnFrontend?: boolean | null;
/**
* Manual position on the Tech Tree canvas (set by dragging a note). Leave empty to park the note in the notes column beside the tree.
*/
treePosition?: {
x?: number | null;
y?: number | null;
};
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "tech-researches".
@ -8296,6 +8328,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
techTreeNotes?: {
/**
* Allow clients to find tech-tree-notes.
*/
find?: boolean | null;
/**
* Allow clients to create tech-tree-notes.
*/
create?: boolean | null;
/**
* Allow clients to update tech-tree-notes.
*/
update?: boolean | null;
/**
* Allow clients to delete tech-tree-notes.
*/
delete?: boolean | null;
};
techResearches?: {
/**
* Allow clients to find tech-researches.
@ -9521,6 +9571,10 @@ export interface PayloadLockedDocument {
relationTo: 'tech-categories';
value: number | TechCategory;
} | null)
| ({
relationTo: 'tech-tree-notes';
value: number | TechTreeNote;
} | null)
| ({
relationTo: 'tech-researches';
value: number | TechResearch;
@ -11154,6 +11208,23 @@ export interface TechCategoriesSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "tech-tree-notes_select".
*/
export interface TechTreeNotesSelect<T extends boolean = true> {
title?: T;
body?: T;
showOnFrontend?: T;
treePosition?:
| T
| {
x?: T;
y?: T;
};
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "tech-researches_select".
@ -13242,6 +13313,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
techTreeNotes?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
techResearches?:
| T
| {

View file

@ -52,6 +52,7 @@ import { Assignments } from "@/collections/users/Assignments";
import { AssignmentTransfers } from "@/collections/users/AssignmentTransfers";
import { Technologies } from "@/collections/intelligence/Technologies";
import { TechCategories } from "@/collections/intelligence/TechCategories";
import { TechTreeNotes } from "@/collections/intelligence/TechTreeNotes";
import { TechResearches } from "@/collections/intelligence/TechResearches";
import { TechBallots } from "@/collections/intelligence/TechBallots";
import { TechBallotVotes } from "@/collections/intelligence/TechBallotVotes";
@ -279,6 +280,7 @@ const collections = [
FactionRelationEntries,
Technologies,
TechCategories,
TechTreeNotes,
TechResearches,
TechBallots,
TechBallotVotes,

View file

@ -16,6 +16,40 @@ let authSpy: MockInstance;
const RUN = `award-${Date.now().toString(36)}`;
function simpleRichText(text: string): Award["description"] {
return {
root: {
type: "root",
children: [
{
type: "paragraph",
children: [
{
type: "text",
text,
format: 0,
style: "",
mode: "normal",
detail: 0,
version: 1,
},
],
direction: "ltr",
format: "",
indent: 0,
textFormat: 0,
textStyle: "",
version: 1,
},
],
direction: "ltr",
format: "",
indent: 0,
version: 1,
},
};
}
describe("Award Advancement Series", () => {
let adminUser: User;
let adminUserId: number;
@ -733,4 +767,104 @@ describe("Award Advancement Series", () => {
}),
).rejects.toThrow("Tier 1 of this series already exists.");
});
describe("saving awards without an advancement tier", () => {
// The admin form submits every field in form state, including the hidden
// "Advancement Series" group, so untouched awards arrive with explicit nulls
// (and a cleared text input as an empty string).
async function createAward(type: "ribbon" | "commendation" | "medal", label: string) {
return (await payload.create({
collection: "awards",
data: {
name: `${label}-${RUN}`,
description: simpleRichText(label),
type,
},
overrideAccess: true,
depth: 0,
})) as unknown as Award;
}
it("saves a standalone ribbon when advancement is submitted as nulls", async () => {
const award = await createAward("ribbon", "Null Advancement Ribbon");
const updated = (await payload.update({
collection: "awards",
id: award.id,
data: { advancement: { seriesKey: null, tier: null } },
overrideAccess: true,
depth: 0,
})) as unknown as Award;
expect(updated.advancement?.seriesKey ?? null).toBeNull();
expect(updated.advancement?.tier ?? null).toBeNull();
});
it("saves a standalone ribbon when the series key is submitted as an empty string", async () => {
const award = await createAward("ribbon", "Empty Series Key Ribbon");
const updated = (await payload.update({
collection: "awards",
id: award.id,
data: { advancement: { seriesKey: "", tier: null } },
overrideAccess: true,
depth: 0,
})) as unknown as Award;
expect(updated.advancement?.seriesKey ?? null).toBeNull();
expect(updated.advancement?.tier ?? null).toBeNull();
});
it("saves a medal whose hidden advancement group arrives as nulls", async () => {
const award = await createAward("medal", "Null Advancement Medal");
await expect(
payload.update({
collection: "awards",
id: award.id,
data: { advancement: { seriesKey: null, tier: null } },
overrideAccess: true,
depth: 0,
}),
).resolves.toBeTruthy();
});
it("clears a leftover lineup when an award is switched off the ribbon type", async () => {
const award = await createAward("ribbon", "Type Switch Ribbon");
const seriesKey = `${RUN}-type-switch`;
await payload.update({
collection: "awards",
id: award.id,
data: { advancement: { seriesKey, tier: 1 } },
overrideAccess: true,
depth: 0,
});
const updated = (await payload.update({
collection: "awards",
id: award.id,
data: { type: "commendation", advancement: { seriesKey, tier: 1 } },
overrideAccess: true,
depth: 0,
})) as unknown as Award;
expect(updated.advancement?.seriesKey ?? null).toBeNull();
expect(updated.advancement?.tier ?? null).toBeNull();
});
it("still rejects a lineup with only one of the two fields", async () => {
const award = await createAward("ribbon", "One Sided Ribbon");
await expect(
payload.update({
collection: "awards",
id: award.id,
data: { advancement: { seriesKey: null, tier: 2 } },
overrideAccess: true,
depth: 0,
}),
).rejects.toThrow("Advancement requires both a series key and a tier.");
});
});
});

View file

@ -0,0 +1,182 @@
import { getTestPayload } from "../helpers/get-test-payload";
import type { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
computeNoteLayout,
noteNodeId,
parseNoteNodeId,
} from "@/components/admin/tech-tree/notes";
import { COLUMN_STEP, ROW_STEP } from "@/components/admin/tech-tree/types";
const RUN = `ttnote-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
describe("tech tree note node layout (pure)", () => {
const note = (
id: number,
treePosition: { x: number; y: number } | null = null,
): Parameters<typeof computeNoteLayout>[0][number] => ({
id,
title: `note ${id}`,
body: "",
showOnFrontend: false,
treePosition,
updatedAt: "",
});
it("parks untouched notes in a column one step right of the tree", () => {
const layout = computeNoteLayout([note(1), note(2)], { columns: 3 });
expect(layout).toEqual([
{ noteId: 1, x: 3 * COLUMN_STEP, y: 0 },
{ noteId: 2, x: 3 * COLUMN_STEP, y: ROW_STEP },
]);
});
it("uses dragged positions without shifting the automatic stack", () => {
const layout = computeNoteLayout(
[note(1, { x: 40, y: 400 }), note(2), note(3)],
{ columns: 2 },
);
expect(layout).toEqual([
{ noteId: 1, x: 40, y: 400 },
{ noteId: 2, x: 2 * COLUMN_STEP, y: 0 },
{ noteId: 3, x: 2 * COLUMN_STEP, y: ROW_STEP },
]);
});
it("starts at column 0 when the tree has no technologies", () => {
expect(computeNoteLayout([note(9)], { columns: 0 })).toEqual([
{ noteId: 9, x: 0, y: 0 },
]);
});
it("note node ids can never collide with technology ids", () => {
expect(noteNodeId(4)).toBe("note-4");
expect(parseNoteNodeId("note-4")).toBe(4);
expect(parseNoteNodeId("4")).toBeNull();
expect(parseNoteNodeId("note-x")).toBeNull();
expect(parseNoteNodeId("note-0")).toBeNull();
});
});
describe("tech-tree-notes collection", () => {
let payload: Payload;
const ids: number[] = [];
beforeAll(async () => {
payload = await getTestPayload();
}, TIMEOUT);
afterAll(async () => {
for (const id of ids) {
await payload
.delete({ collection: "tech-tree-notes", id, overrideAccess: true })
.catch(() => undefined);
}
}, TIMEOUT);
it(
"defaults to a backend-only note with no canvas position",
async () => {
const created = await payload.create({
collection: "tech-tree-notes",
data: { title: `${RUN}-default` },
overrideAccess: true,
depth: 0,
});
ids.push(created.id);
expect(created.showOnFrontend).toBe(false);
expect(created.body ?? null).toBeNull();
expect(created.treePosition?.x ?? null).toBeNull();
expect(created.treePosition?.y ?? null).toBeNull();
},
TIMEOUT,
);
it(
"requires a title",
async () => {
await expect(
payload.create({
collection: "tech-tree-notes",
// Deliberately missing the required title.
data: {} as never,
overrideAccess: true,
}),
).rejects.toThrow();
},
TIMEOUT,
);
it(
"publishes only the notes flagged for the frontend",
async () => {
const hidden = await payload.create({
collection: "tech-tree-notes",
data: { title: `${RUN}-hidden`, showOnFrontend: false },
overrideAccess: true,
depth: 0,
});
const shown = await payload.create({
collection: "tech-tree-notes",
data: { title: `${RUN}-shown`, showOnFrontend: true },
overrideAccess: true,
depth: 0,
});
ids.push(hidden.id, shown.id);
const published = await payload.find({
collection: "tech-tree-notes",
where: {
and: [
{ title: { like: RUN } },
// The member-facing page's exact publication gate.
{ showOnFrontend: { equals: true } },
],
},
depth: 0,
limit: 0,
overrideAccess: true,
});
const publishedIds = published.docs.map((doc) => doc.id);
expect(publishedIds).toContain(shown.id);
expect(publishedIds).not.toContain(hidden.id);
},
TIMEOUT,
);
it(
"keeps body line breaks and updates in place",
async () => {
const created = await payload.create({
collection: "tech-tree-notes",
data: {
title: `${RUN}-edit`,
body: "line one\nline two",
showOnFrontend: true,
},
overrideAccess: true,
depth: 0,
});
ids.push(created.id);
const updated = await payload.update({
collection: "tech-tree-notes",
id: created.id,
data: { showOnFrontend: false, title: `${RUN}-edit-renamed` },
overrideAccess: true,
depth: 0,
});
expect(updated.showOnFrontend).toBe(false);
expect(updated.title).toBe(`${RUN}-edit-renamed`);
// An unrelated field update must not drop the body.
expect(updated.body).toBe("line one\nline two");
},
TIMEOUT,
);
});

View file

@ -22,6 +22,7 @@ describe("tech tree position bulk-write validation", () => {
});
expect(result).toEqual({
ok: true,
collection: "technologies",
updates: [
{ id: 1, x: 10, y: 21, expectedUpdatedAt: null },
{ id: 2, x: null, y: null, expectedUpdatedAt: null },
@ -38,6 +39,7 @@ describe("tech tree position bulk-write validation", () => {
});
expect(result).toEqual({
ok: true,
collection: "technologies",
updates: [{ id: 3, x: null, y: null, expectedUpdatedAt: null }],
});
});
@ -48,12 +50,17 @@ describe("tech tree position bulk-write validation", () => {
});
expect(accepted).toEqual({
ok: true,
collection: "technologies",
updates: [{ id: 1, x: 5, y: 5, expectedUpdatedAt: "2026-10-15T12:00:00.000Z" }],
});
// Null means unconditional; malformed values are rejected.
expect(
parsePositionUpdates({ positions: [{ id: 1, x: 5, y: 5, ifUnmodifiedAt: null }] }),
).toEqual({ ok: true, updates: [{ id: 1, x: 5, y: 5, expectedUpdatedAt: null }] });
).toEqual({
ok: true,
collection: "technologies",
updates: [{ id: 1, x: 5, y: 5, expectedUpdatedAt: null }],
});
expect(
parsePositionUpdates({ positions: [{ id: 1, x: 5, y: 5, ifUnmodifiedAt: "soon" }] }).ok,
).toBe(false);
@ -72,6 +79,24 @@ describe("tech tree position bulk-write validation", () => {
expect(parsePositionUpdates({ positions: [{ id: 1, x: Number.NaN, y: 1 }] }).ok).toBe(false);
});
it("routes the batch to the requested canvas collection", () => {
// Omitted collection keeps every existing caller on technologies.
expect(parsePositionUpdates({ positions: [{ id: 1, x: 1, y: 1 }] })).toMatchObject({
ok: true,
collection: "technologies",
});
expect(
parsePositionUpdates({ collection: "tech-tree-notes", positions: [{ id: 1, x: 1, y: 1 }] }),
).toMatchObject({ ok: true, collection: "tech-tree-notes" });
// Anything outside the whitelist is a validation error, not a fallback.
expect(
parsePositionUpdates({ collection: "users", positions: [{ id: 1, x: 1, y: 1 }] }).ok,
).toBe(false);
expect(parsePositionUpdates({ collection: 7, positions: [{ id: 1, x: 1, y: 1 }] }).ok).toBe(
false,
);
});
it("caps the batch size", () => {
const positions = Array.from({ length: MAX_POSITION_UPDATES + 1 }, (_, i) => ({
id: i + 1,
@ -150,6 +175,70 @@ describe("tech tree position bulk write (database)", () => {
TIMEOUT,
);
it(
"writes note-node positions through the same bulk path",
async () => {
const note = await payload.create({
collection: "tech-tree-notes",
data: { title: `${RUN}-note` },
overrideAccess: true,
depth: 0,
});
try {
// A fresh note starts unpinned and unpublished.
expect(note.treePosition?.x ?? null).toBeNull();
expect(note.showOnFrontend).toBe(false);
const pinned = await writeTreePositions(
payload,
[{ id: note.id, x: 46, y: 92, expectedUpdatedAt: null }],
"tech-tree-notes",
);
expect(pinned.updated).toBe(1);
expect(pinned.conflicts).toEqual([]);
const afterPin = await payload.findByID({
collection: "tech-tree-notes",
id: note.id,
overrideAccess: true,
depth: 0,
});
expect(afterPin.treePosition).toMatchObject({ x: 46, y: 92 });
// A stale token from before the pin conflicts instead of overwriting.
const stale = await writeTreePositions(
payload,
[{ id: note.id, x: 0, y: 0, expectedUpdatedAt: note.updatedAt }],
"tech-tree-notes",
);
expect(stale.updated).toBe(0);
expect(stale.conflicts).toContainEqual({
id: note.id,
currentUpdatedAt: expect.any(String),
});
// Auto-arrange clears note pins exactly like technology pins.
const cleared = await writeTreePositions(
payload,
[{ id: note.id, x: null, y: null, expectedUpdatedAt: null }],
"tech-tree-notes",
);
expect(cleared.updated).toBe(1);
const afterClear = await payload.findByID({
collection: "tech-tree-notes",
id: note.id,
overrideAccess: true,
depth: 0,
});
expect(afterClear.treePosition?.x ?? null).toBeNull();
expect(afterClear.treePosition?.y ?? null).toBeNull();
} finally {
await payload.delete({ collection: "tech-tree-notes", id: note.id, overrideAccess: true });
}
},
TIMEOUT,
);
it(
"ignores ids that do not exist",
async () => {