diff --git a/CHANGELOG.md b/CHANGELOG.md index a1c3f8a8..568040cb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,25 @@ # Changelog +# v0.13.1 + +Officers now review logistics extractions before they reach HQ, vehicle cards show their stats, and ribbon devices are brass-embossed with a Valor "V" in place of the arrow. + +### Features + +- **Extraction review.** Logistics extractions wait for an officer decision on a new Extractions page. Each line can be kept, scrapped, or expelled before anything reaches HQ storage. If HQ is full, the extraction stays pending so the officer can drop a line and retry. +- **Vehicle cargo blacklist.** Each vehicle can list items it may not carry on virtual shipments. A matching shipment is rejected before any stock is deducted. +- **Ribbon devices.** Devices are brass-embossed vectors and centered automatically. The number shown follows the award's advancement tier. The arrow is replaced by the Valor "V" device. +- **Vehicle catalog.** Vehicle cards use the dossier style, with a registry strip, category pills, and a readout footer. +- **Vehicle categories.** Added "static" and "drone" categories. + +### Fixes + +- **Vehicles.** Card stats (integrity, road speed, materials, build time) now show; they were always empty before. Category colors and labels now match between the card grid and the detail page. +- **Modlist downloads.** Modlist files download instead of opening inline. +- **Ribbon remove buttons.** The remove buttons now show a multiplication sign instead of a raw escape code. + +--- + # v0.13.0 Leadership ratings now follow the unit's rank structure instead of squad assignments. diff --git a/docs/map-system.md b/docs/map-system.md index 94faad46..8be72ade 100644 --- a/docs/map-system.md +++ b/docs/map-system.md @@ -286,7 +286,35 @@ Those markers belong to the one mission and never appear on `/map`. `worldSizeWidth`/`worldSizeHeight` must match the terrain's real size for exported markers to land in the right place in-game. - The base layers come from `GET /api/map-features?mapId=&layers=base`, - which skips the structure, node and shipment queries. + which skips the structure, node and shipment queries until a reference layer + is switched on in the Layers popover (structures are on by default, so the + full feed normally loads). +- Objectives (below) are always included in the feed, independent of + `layers=base`. - Icons, colors and brushes come from the game config via `bun run markers:arma`. See the "Mission Planning Map" section in AGENTS.md for the full wiring. + +## Strategic objectives + +`map-objectives` holds Arma-style command markers that belong to a terrain map +and are shared by every mission planned on it, so the command picture stays +consistent between the world map and mission planning maps. + +- Fields: `map` (required), `name` (the designation shown under the marker, + e.g. `OBJ ALPHA`), `description`, `markerType` (CfgMarkers class, default + `mil_objective`), `status` (`active` / `secured` / `failed`), `redacted`, + `position` ([x, y] meters), `createdBy`. +- Status drives the colour: `active` = `ColorRed`, `secured` = `ColorGreen`, + `failed` = `ColorGrey`. There is no free colour picker on purpose. +- Writes require the superuser tier (`system:admin-access`). Every logged-in + user reads objectives, but `redacted` rows are stripped for anyone without + the tier; superusers see them dimmed with a `REDACTED` tag so they can stage + an objective before revealing it. +- Creation, status flips, reveals and deletes emit `map:objective-*` events + targeting `map-objectives`. +- Authoring is available on both surfaces: `/map/[id]` ("Add objective" in Map + Control) and a mission's planning map (Layers popover, superusers only). + Deleting a map removes its objectives through the Maps `beforeDelete` hook, + because the relationship is NOT NULL. + diff --git a/src/app/(frontend)/intelligence/missions/[id]/page.tsx b/src/app/(frontend)/intelligence/missions/[id]/page.tsx index 8325f1bd..61596d0b 100644 --- a/src/app/(frontend)/intelligence/missions/[id]/page.tsx +++ b/src/app/(frontend)/intelligence/missions/[id]/page.tsx @@ -52,6 +52,7 @@ import { listMissionMarkers, planningMapDelegateIds, } from "@/lib/intelligence/missionMap"; +import { listMapObjectives } from "@/lib/map/objectives"; interface MissionDetailPageProps { params: Promise<{ id: string }>; @@ -280,9 +281,16 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro const canCuratePlan = canControlSideOp && !planLocked; const canDelegate = canManage && !planLocked; const canEditPlan = (canControlSideOp || isPlanDelegate) && !planLocked; + const canManageObjectives = currentUser + ? await hasPermission(payload, currentUser, "system:admin-access") + : false; const planningMapEnabled = mission.classification.planningMapEnabled === true; const planMarkers = map && planningMapEnabled ? await listMissionMarkers(payload, mission.id) : []; + const planObjectives = + map && (planningMapEnabled || canEditPlan) + ? await listMapObjectives(payload, map.id, { includeRedacted: canManageObjectives }) + : []; const showPlanningMap = map !== null && (planningMapEnabled || canEditPlan); let planningUsers: PlanningUserOption[] = []; @@ -470,6 +478,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro enabled={planningMapEnabled} canEdit={canEditPlan} canCurate={canCuratePlan} + canManageObjectives={canManageObjectives} locked={planLocked} map={{ id: map.id, @@ -478,6 +487,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro worldHeight: Number(map.worldSizeHeight ?? 8192), }} initialMarkers={planMarkers} + initialObjectives={planObjectives} /> )} {/* Attendance sits right under the hero on stacked (below-xl) layouts */} diff --git a/src/app/(frontend)/map/[id]/page.tsx b/src/app/(frontend)/map/[id]/page.tsx index 3456cfb3..9a5389d4 100644 --- a/src/app/(frontend)/map/[id]/page.tsx +++ b/src/app/(frontend)/map/[id]/page.tsx @@ -31,17 +31,19 @@ export default async function MapViewPage({ params }: MapViewPageProps) { if (!map) notFound(); - const [canPlace, canAuthorRoads, canAuthorZones, canAuthorNodes] = await Promise.all([ - user - ? Promise.all([ - hasPermission(payload, user, "maps:place"), - hasLogisticsQualification(payload, user), - ]).then(([place, logistics]) => place && logistics) - : Promise.resolve(false), - user ? hasPermission(payload, user, "map-roads:author") : Promise.resolve(false), - user ? hasPermission(payload, user, "map-zones:author") : Promise.resolve(false), - user ? hasPermission(payload, user, "resource-nodes:author") : Promise.resolve(false), - ]); + const [canPlace, canAuthorRoads, canAuthorZones, canAuthorNodes, canManageObjectives] = + await Promise.all([ + user + ? Promise.all([ + hasPermission(payload, user, "maps:place"), + hasLogisticsQualification(payload, user), + ]).then(([place, logistics]) => place && logistics) + : Promise.resolve(false), + user ? hasPermission(payload, user, "map-roads:author") : Promise.resolve(false), + user ? hasPermission(payload, user, "map-zones:author") : Promise.resolve(false), + user ? hasPermission(payload, user, "resource-nodes:author") : Promise.resolve(false), + user ? hasPermission(payload, user, "system:admin-access") : Promise.resolve(false), + ]); // Inactive maps stay reachable for editors previewing them, but are hidden // from everyone else. @@ -67,6 +69,7 @@ export default async function MapViewPage({ params }: MapViewPageProps) { map={{ id: map.id, name: map.name }} canAuthor={{ roads: canAuthorRoads, zones: canAuthorZones, nodes: canAuthorNodes }} canPlace={canPlace} + canManageObjectives={canManageObjectives} /> ); diff --git a/src/app/(frontend)/map/actions.ts b/src/app/(frontend)/map/actions.ts new file mode 100644 index 00000000..b866484e --- /dev/null +++ b/src/app/(frontend)/map/actions.ts @@ -0,0 +1,146 @@ +"use server"; + +import config from "@payload-config"; +import { getPayload } from "payload"; +import { hasPermission } from "@/utils/access-control/hasPermission"; +import { + createMapObjective, + deleteMapObjective, + listMapObjectives, + objectiveFromDoc, + updateMapObjective, + type MapObjectiveDoc, +} from "@/lib/map/objectives"; +import type { MapObjectiveStatus } from "@/lib/map/objectiveTypes"; +import type { MapObjectiveFeature } from "@/lib/map/types"; + +export interface ActionResult { + success: boolean; + error?: string; + data?: T; +} + +async function authenticate() { + const payloadConfig = await config; + const payload = await getPayload({ config: payloadConfig }); + const { headers } = await import("next/headers"); + const hdrs = await headers(); + const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false }); + + if (!user) { + throw new Error("Unauthorized"); + } + + return { payload, user }; +} + +/** Objectives are managed by the superuser tier only (admin + superuser roles). */ +async function authorizedActor() { + const { payload, user } = await authenticate(); + if (!(await hasPermission(payload, user, "system:admin-access"))) { + throw new Error("Only superusers can manage strategic objectives."); + } + return { payload, user }; +} + +function failure(error: unknown): { success: false; error: string } { + const message = error instanceof Error ? error.message : "Unknown error"; + return message === "Unauthorized" + ? { success: false, error: "You must be logged in." } + : { success: false, error: message }; +} + +/** Create (no id, needs mapId) or update (id) one objective. */ +export async function saveMapObjective(input: { + mapId?: number; + id?: number | null; + objective: unknown; +}): Promise> { + try { + const { payload, user } = await authorizedActor(); + if (input.id) { + const objective = await updateMapObjective(payload, input.id, input.objective); + return { success: true, data: objective }; + } + if (!input.mapId) return { success: false, error: "Map is required." }; + const objective = await createMapObjective( + payload, + input.mapId, + input.objective, + Number(user.id), + ); + return { success: true, data: objective }; + } catch (error) { + return failure(error); + } +} + +/** Status flips from the map popup (active / secured / failed). */ +export async function setMapObjectiveStatus(input: { + id: number; + status: MapObjectiveStatus; +}): Promise> { + try { + const { payload } = await authorizedActor(); + const existing = await payload + .findByID({ collection: "map-objectives", id: input.id, depth: 0, overrideAccess: true }) + .catch(() => null); + const current = existing ? objectiveFromDoc(existing as unknown as MapObjectiveDoc) : null; + if (!current) return { success: false, error: "Objective not found." }; + const objective = await updateMapObjective(payload, input.id, { + ...current, + status: input.status, + }); + return { success: true, data: objective }; + } catch (error) { + return failure(error); + } +} + +/** Reveal or hide an objective from players. */ +export async function setMapObjectiveRedacted(input: { + id: number; + redacted: boolean; +}): Promise> { + try { + const { payload } = await authorizedActor(); + const existing = await payload + .findByID({ collection: "map-objectives", id: input.id, depth: 0, overrideAccess: true }) + .catch(() => null); + const current = existing ? objectiveFromDoc(existing as unknown as MapObjectiveDoc) : null; + if (!current) return { success: false, error: "Objective not found." }; + const objective = await updateMapObjective(payload, input.id, { + ...current, + redacted: Boolean(input.redacted), + }); + return { success: true, data: objective }; + } catch (error) { + return failure(error); + } +} + +export async function removeMapObjective(input: { id: number }): Promise { + try { + const { payload } = await authorizedActor(); + await deleteMapObjective(payload, input.id); + return { success: true }; + } catch (error) { + return failure(error); + } +} + +/** Read path for the planning map's background refresh (any mission viewer). */ +export async function getMapObjectives(input: { + mapId: number; +}): Promise> { + try { + const { payload, user } = await authenticate(); + const includeRedacted = await hasPermission(payload, user, "system:admin-access"); + return { + success: true, + data: await listMapObjectives(payload, input.mapId, { includeRedacted }), + }; + } catch (error) { + return failure(error); + } +} diff --git a/src/app/(frontend)/styles.css b/src/app/(frontend)/styles.css index 049fe612..f8a43e62 100644 --- a/src/app/(frontend)/styles.css +++ b/src/app/(frontend)/styles.css @@ -3976,6 +3976,37 @@ outline-offset: 3px; } +/* Strategic objectives: persistent designation plate under the Arma glyph. */ +.leaflet-container .objective-marker-label { + background: transparent; + border: none; + box-shadow: none; + padding: 0; +} + +.leaflet-container .objective-marker-label::before { + display: none; +} + +.objective-marker-name { + display: block; + width: max-content; + max-width: 220px; + transform: translateX(-50%); + padding: 1px 4px; + background: rgb(0 0 0 / 45%); + border: 1px solid rgb(255 255 255 / 20%); + font-family: var(--font-mono, ui-monospace, monospace); + font-size: 9px; + font-weight: 600; + letter-spacing: 0.12em; + line-height: 1.4; + text-transform: uppercase; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + .leaflet-container .mission-map-handle { background: transparent; border: none; diff --git a/src/app/api/map-features/route.ts b/src/app/api/map-features/route.ts index 77ca668b..9d73b9f7 100644 --- a/src/app/api/map-features/route.ts +++ b/src/app/api/map-features/route.ts @@ -11,6 +11,8 @@ import { import { isPointArray, type MapPoint } from "@/lib/map/points"; import { gridConfigFromMapDoc } from "@/lib/map/grid"; import type { MapFeaturesResponse, StructureFeature } from "@/lib/map/types"; +import { listMapObjectives } from "@/lib/map/objectives"; +import { hasPermission } from "@/utils/access-control/hasPermission"; export const dynamic = "force-dynamic"; export const runtime = "nodejs"; @@ -71,56 +73,61 @@ export async function GET(req: NextRequest) { const worldH = Number(mapDoc.worldSizeHeight ?? 8192); // layers=base: basemap + roads + zones only (mission planning maps). Skips - // the logistics queries (structures/nodes/shipments) entirely. + // the logistics queries (structures/nodes/shipments) entirely. Objectives are + // cheap and belong to every surface, so they are always included. const baseOnly = req.nextUrl.searchParams.get("layers") === "base"; + const includeRedacted = await hasPermission(payload, user, "system:admin-access"); const none = { docs: [] as never[] }; - const [structuresRes, nodesRes, roadsRes, zonesRes, shipmentsRes] = await Promise.all([ - baseOnly - ? none - : payload.find({ - collection: "game-structures", - where: { map: { equals: mapId } }, - depth: 2, - limit: 1000, - overrideAccess: true, - }), - baseOnly - ? none - : payload.find({ - collection: "resource-nodes", - where: { map: { equals: mapId } }, - depth: 1, - limit: 5000, - overrideAccess: true, - }), - payload.find({ - collection: "map-roads", - where: { map: { equals: mapId } }, - depth: 0, - limit: 5000, - overrideAccess: true, - }), - payload.find({ - collection: "map-zones", - where: { map: { equals: mapId } }, - depth: 1, - limit: 5000, - overrideAccess: true, - }), - baseOnly - ? none - : payload.find({ - collection: "shipments", - where: { - and: [{ map: { equals: mapId } }, { status: { in: ["dispatched", "in_transit"] } }], - }, - depth: 2, - limit: 200, - sort: "-dispatchedAt", - overrideAccess: true, - }), - ]); + const [structuresRes, nodesRes, roadsRes, zonesRes, shipmentsRes, objectives] = await Promise.all( + [ + baseOnly + ? none + : payload.find({ + collection: "game-structures", + where: { map: { equals: mapId } }, + depth: 2, + limit: 1000, + overrideAccess: true, + }), + baseOnly + ? none + : payload.find({ + collection: "resource-nodes", + where: { map: { equals: mapId } }, + depth: 1, + limit: 5000, + overrideAccess: true, + }), + payload.find({ + collection: "map-roads", + where: { map: { equals: mapId } }, + depth: 0, + limit: 5000, + overrideAccess: true, + }), + payload.find({ + collection: "map-zones", + where: { map: { equals: mapId } }, + depth: 1, + limit: 5000, + overrideAccess: true, + }), + baseOnly + ? none + : payload.find({ + collection: "shipments", + where: { + and: [{ map: { equals: mapId } }, { status: { in: ["dispatched", "in_transit"] } }], + }, + depth: 2, + limit: 200, + sort: "-dispatchedAt", + overrideAccess: true, + }), + listMapObjectives(payload, mapId, { includeRedacted }), + ], + ); const structures: StructureFeature[] = []; for (const doc of structuresRes.docs) { @@ -296,6 +303,7 @@ export async function GET(req: NextRequest) { roads, zones, shipments, + objectives, }; return NextResponse.json(response); diff --git a/src/collections/AGENTS.md b/src/collections/AGENTS.md index 824fb396..e6d13a90 100644 --- a/src/collections/AGENTS.md +++ b/src/collections/AGENTS.md @@ -28,7 +28,7 @@ collections/ # GameVehicles, GameNpcs, GameHardResources, GameEventLogs, # NpcStaffing, LaborClassifications (+ shared staffingFields.ts factory) server/ 5 files # MissionFiles, ModLists, GameServers, ArmaCommands, ArmaSyncEvents - world/ 5 files # Maps (basemap config), MapRoads/MapZones/ResourceNodes (map features), NarrativeEvents + world/ 6 files # Maps (basemap config), MapRoads/MapZones/ResourceNodes (map features), MapObjectives (superuser strategic objectives), NarrativeEvents projects/ 4 files # Projects, Labels, Releases, Sprints (Jira-like) tickets/ 2 files # Tickets (Lexical rich text; `archived` hides from all front-ends, admin panel only), TicketVotes wiki/ 3 files # WikiPages, WikiRevisions, WikiTemplates diff --git a/src/collections/game/GameEventLogs.ts b/src/collections/game/GameEventLogs.ts index f7e46acf..f12a1fb3 100644 --- a/src/collections/game/GameEventLogs.ts +++ b/src/collections/game/GameEventLogs.ts @@ -36,6 +36,7 @@ const TARGET_COLLECTIONS = [ { label: "Wiki Templates", value: "wiki-templates" }, { label: "Survey Submissions", value: "form-submissions" }, { label: "Mission Map Markers", value: "mission-map-markers" }, + { label: "Map Objectives", value: "map-objectives" }, { label: "Contribution Entries", value: "contribution-entries" }, { label: "Game Servers", value: "game-servers" }, { label: "Assignment Transfers", value: "assignment-transfers" }, @@ -190,7 +191,8 @@ export const GameEventLogs: CollectionConfig = { type: "date", admin: { readOnly: true, - description: "Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.", + description: + "Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.", }, }, { diff --git a/src/collections/world/MapObjectives.ts b/src/collections/world/MapObjectives.ts new file mode 100644 index 00000000..b0b0ecc0 --- /dev/null +++ b/src/collections/world/MapObjectives.ts @@ -0,0 +1,207 @@ +import type { CollectionConfig } from "payload"; +import { hasPermission, requirePermission } from "@/utils/access-control/hasPermission"; +import { emitGameEvent } from "@/utils/event-log/emit"; +import { EventTypes } from "@/utils/event-log/eventTypes"; +import { validatePosition } from "@/lib/map/points"; +import { + DEFAULT_OBJECTIVE_MARKER_TYPE, + MAP_OBJECTIVE_STATUSES, + OBJECTIVE_STATUS_META, + objectiveStatusLabel, +} from "@/lib/map/objectiveTypes"; + +/** Payload's loose doc shape inside hooks (avoids a generated-types dependency). */ +interface ObjectiveHookDoc { + id: number; + map?: number | { id: number } | null; + name?: string | null; + status?: string | null; + redacted?: boolean | null; +} + +function mapIdOf(doc: ObjectiveHookDoc): number | null { + const value = doc.map; + if (typeof value === "number") return value; + if (value && typeof value === "object") return value.id; + return null; +} + +/** + * Strategic objectives: Arma-style command markers that belong to a terrain + * map and are visible to every mission planned on it. + * + * - Read: any logged-in user, except `redacted` rows which Payload filters out + * for anyone without the superuser tier. + * - Write: `system:admin-access` only (built-in admin role + superuser roles). + * Division roles are never granted this tier. + * + * Frontend authoring flows through `src/app/(frontend)/map/actions.ts`; this + * collection-level gate governs the REST API and the admin panel. + */ +export const MapObjectives: CollectionConfig = { + slug: "map-objectives", + admin: { + group: "World", + useAsTitle: "name", + defaultColumns: ["name", "map", "status", "redacted", "position"], + description: + "Strategic objectives shown on the world map and mission planning maps. Superuser-authored.", + }, + access: { + read: async ({ req }) => { + if (!req.user) return false; + if (await hasPermission(req.payload, req.user, "system:admin-access")) return true; + return { redacted: { equals: false } }; + }, + create: requirePermission("system:admin-access"), + update: requirePermission("system:admin-access"), + delete: requirePermission("system:admin-access"), + }, + hooks: { + afterChange: [ + async ({ doc, previousDoc, operation, req }) => { + const current = doc as unknown as ObjectiveHookDoc; + const previous = previousDoc as unknown as ObjectiveHookDoc | undefined; + const mapId = mapIdOf(current) ?? (previous ? mapIdOf(previous) : null); + if (!mapId) return; + const name = current.name ?? previous?.name ?? `Objective #${current.id}`; + const actor = req.user?.id; + + if (operation === "create") { + await emitGameEvent(req.payload, { + type: EventTypes.MapObjectiveCreate, + message: `Added objective ${name}`, + actor, + targetCollection: "map-objectives", + targetId: current.id, + data: { mapId, objectiveId: current.id }, + }); + return; + } + + if (previous && previous.status !== current.status) { + await emitGameEvent(req.payload, { + type: EventTypes.MapObjectiveStatus, + message: `Objective ${name} is now ${objectiveStatusLabel(current.status).toLowerCase()}`, + actor, + targetCollection: "map-objectives", + targetId: current.id, + data: { mapId, objectiveId: current.id, status: current.status }, + }); + return; + } + + if (previous && previous.redacted !== current.redacted) { + await emitGameEvent(req.payload, { + type: EventTypes.MapObjectiveReveal, + message: `${current.redacted ? "Hid" : "Revealed"} objective ${name}`, + actor, + targetCollection: "map-objectives", + targetId: current.id, + data: { mapId, objectiveId: current.id, redacted: current.redacted }, + }); + return; + } + + await emitGameEvent(req.payload, { + type: EventTypes.MapObjectiveUpdate, + message: `Updated objective ${name}`, + actor, + targetCollection: "map-objectives", + targetId: current.id, + data: { mapId, objectiveId: current.id }, + }); + }, + ], + afterDelete: [ + async ({ doc, req }) => { + const deleted = doc as unknown as ObjectiveHookDoc; + const mapId = mapIdOf(deleted); + await emitGameEvent(req.payload, { + type: EventTypes.MapObjectiveDelete, + message: `Removed objective ${deleted.name ?? `#${deleted.id}`}`, + actor: req.user?.id, + targetCollection: "map-objectives", + targetId: deleted.id, + data: mapId ? { mapId, objectiveId: deleted.id } : { objectiveId: deleted.id }, + }); + }, + ], + }, + fields: [ + { + name: "name", + type: "text", + required: true, + maxLength: 80, + admin: { + description: 'Map label, e.g. "OBJ ALPHA". Shown under the marker on every map.', + }, + }, + { + name: "description", + type: "textarea", + maxLength: 500, + admin: { + description: "Planning note shown in the marker popup.", + }, + }, + { + name: "map", + type: "relationship", + relationTo: "maps", + required: true, + index: true, + }, + { + name: "markerType", + type: "text", + defaultValue: DEFAULT_OBJECTIVE_MARKER_TYPE, + admin: { + description: "CfgMarkers class name, e.g. mil_objective, o_objective, hd_objective.", + }, + }, + { + name: "status", + type: "select", + required: true, + defaultValue: "active", + options: MAP_OBJECTIVE_STATUSES.map((status) => ({ + label: OBJECTIVE_STATUS_META[status].label, + value: status, + })), + admin: { + description: + "Drives the marker colour: red for active, green for secured, grey for failed.", + }, + }, + { + name: "redacted", + type: "checkbox", + label: "Redacted", + defaultValue: false, + admin: { + description: + "Hidden from everyone except superusers (and drawn dimmed for them) until revealed.", + }, + }, + { + name: "position", + type: "json", + required: true, + validate: validatePosition, + admin: { + description: "[x, y] in map meters (origin top-left, y south).", + }, + }, + { + name: "createdBy", + type: "relationship", + relationTo: "users", + admin: { + readOnly: true, + position: "sidebar", + }, + }, + ], +}; diff --git a/src/collections/world/Maps.ts b/src/collections/world/Maps.ts index 716ccf8d..ac239ab5 100644 --- a/src/collections/world/Maps.ts +++ b/src/collections/world/Maps.ts @@ -13,6 +13,31 @@ export const Maps: CollectionConfig = { delete: requirePermission("maps:delete"), read: requirePermission("maps:read"), }, + hooks: { + beforeDelete: [ + // Strategic objectives belong to exactly one map. Their FK is NOT NULL + // (required), so the default ON DELETE SET NULL would make the map + // delete fail; remove them first, inside the same request. + async ({ id, req }) => { + const objectives = await req.payload.find({ + collection: "map-objectives", + where: { map: { equals: id } }, + depth: 0, + pagination: false, + overrideAccess: true, + req, + }); + for (const objective of objectives.docs) { + await req.payload.delete({ + collection: "map-objectives", + id: objective.id, + overrideAccess: true, + req, + }); + } + }, + ], + }, fields: [ { name: "name", diff --git a/src/components/frontend/intelligence/missionMap/MarkerToolPanel.tsx b/src/components/frontend/intelligence/missionMap/MarkerToolPanel.tsx index be7eb550..0709d15f 100644 --- a/src/components/frontend/intelligence/missionMap/MarkerToolPanel.tsx +++ b/src/components/frontend/intelligence/missionMap/MarkerToolPanel.tsx @@ -36,7 +36,7 @@ import { type MissionMarker, } from "@/lib/arma-markers/missionMarkers"; import { cn } from "@/lib/utils"; -import { MarkerTypePicker } from "./MarkerTypePicker"; +import { MarkerTypePicker } from "@/components/frontend/markers/MarkerTypePicker"; import type { MarkerStyle, PlanTool } from "./types"; const TOOLS: { value: PlanTool; label: string; icon: typeof MapPinIcon; hint: string }[] = [ diff --git a/src/components/frontend/intelligence/missionMap/MissionMapCanvas.tsx b/src/components/frontend/intelligence/missionMap/MissionMapCanvas.tsx index 8fe4c0be..20a902c0 100644 --- a/src/components/frontend/intelligence/missionMap/MissionMapCanvas.tsx +++ b/src/components/frontend/intelligence/missionMap/MissionMapCanvas.tsx @@ -19,7 +19,15 @@ import type { MapPoint } from "@/lib/map/points"; import { dashArrayFor, metersPerPx, splinePolyline } from "@/lib/map/style"; import type { MapFeaturesResponse } from "@/lib/map/types"; import type { MapGridConfig } from "@/lib/map/grid"; +import type { MapObjectiveFeature } from "@/lib/map/types"; import { GridLayer } from "@/components/frontend/map/GridLayer"; +import { ObjectiveLayer } from "@/components/frontend/map/objectives/ObjectiveLayer"; +import { + NodeReferenceLayer, + RangeReferenceLayer, + ShipmentReferenceLayer, + StructureReferenceLayer, +} from "./PlanningFeatureLayers"; import { markerBrushOf, resolveMarkerRgba, rgbaToHex } from "@/lib/arma-markers"; import { areaOutline, @@ -28,24 +36,37 @@ import { type MissionMarker, type MissionMarkerData, } from "@/lib/arma-markers/missionMarkers"; -import { markerDivIcon } from "./markerIcon"; +import { markerDivIcon } from "@/components/frontend/markers/markerIcon"; import type { MarkerStyle, PlanTool } from "./types"; export interface MissionMapCanvasProps { mapId: number; markers: MissionMarker[]; + objectives: MapObjectiveFeature[]; selectedId: number | null; tool: PlanTool; style: MarkerStyle; canEdit: boolean; + /** Superuser tier: objectives are editable from this canvas too. */ + canManageObjectives: boolean; + /** Armed objective placement mode: the next map click picks a position. */ + objectiveArmed: boolean; showRoads: boolean; showZones: boolean; showGrid: boolean; + showStructures: boolean; + showNodes: boolean; + showShipments: boolean; + showRanges: boolean; onSelect: (id: number | null) => void; onCreate: (data: MissionMarkerData) => void; /** persist=false for live drag previews, true on drag end. */ onChange: (marker: MissionMarker, persist: boolean) => void; onCursor: (point: MapPoint | null) => void; + onObjectivePlace: (point: MapPoint) => void; + onEditObjective: (objective: MapObjectiveFeature) => void; + onObjectiveUpdated: (objective: MapObjectiveFeature) => void; + onObjectiveDeleted: (id: number) => void; onLoaded: (info: { worldWidth: number; worldHeight: number; @@ -519,29 +540,54 @@ function LineHandles({ ); } +/** Objective placement: the next map click picks the marker position. */ +function ObjectivePlaceHandler({ onPick }: { onPick: (point: MapPoint) => void }) { + useMapEvents({ + click: (event) => { + onPick([Math.round(event.latlng.lng), Math.round(-event.latlng.lat)]); + }, + }); + return null; +} + export function MissionMapCanvas({ mapId, markers, + objectives, selectedId, tool, style, canEdit, + canManageObjectives, + objectiveArmed, showRoads, showZones, showGrid, + showStructures, + showNodes, + showShipments, + showRanges, onSelect, onCreate, onChange, onCursor, + onObjectivePlace, + onEditObjective, + onObjectiveUpdated, + onObjectiveDeleted, onLoaded, }: MissionMapCanvasProps) { const [features, setFeatures] = useState(null); const [error, setError] = useState(null); const layerClickAt = useRef(0); + // Reference layers (structures/nodes/shipments/ranges) need the heavy + // logistics queries; base-only keeps the planning map fast until asked. + const includeLogistics = showStructures || showNodes || showShipments || showRanges; useEffect(() => { let cancelled = false; - fetch(`/api/map-features?mapId=${mapId}&layers=base`, { cache: "no-store" }) + const suffix = includeLogistics ? "" : "&layers=base"; + fetch(`/api/map-features?mapId=${mapId}${suffix}`, { cache: "no-store" }) .then(async (response) => { if (!response.ok) { const body = (await response.json().catch(() => null)) as { error?: string } | null; @@ -568,7 +614,7 @@ export function MissionMapCanvas({ return () => { cancelled = true; }; - }, [mapId, onLoaded]); + }, [mapId, onLoaded, includeLogistics]); const mapConfig = features?.map ?? null; const worldW = mapConfig?.worldSizeWidth ?? 8192; @@ -692,6 +738,11 @@ export function MissionMapCanvas({ ))} + {features && showStructures && } + {features && showNodes && } + {features && showShipments && } + {features && showRanges && } + {markers.map((marker) => { if (marker.shape === "rectangle" || marker.shape === "ellipse") { return ( @@ -764,6 +815,16 @@ export function MissionMapCanvas({ )} + + + {objectiveArmed && } + ; + const next = { ...DEFAULT_LAYERS }; + for (const key of Object.keys(DEFAULT_LAYERS) as (keyof PlanLayers)[]) { + if (typeof parsed[key] === "boolean") next[key] = parsed[key] as boolean; + } + return next; + } catch { + return DEFAULT_LAYERS; + } +} const DEFAULT_STYLE: MarkerStyle = { markerType: DEFAULT_MARKER_TYPE, @@ -107,22 +172,28 @@ export function MissionPlanningMap({ enabled, canEdit, canCurate = canEdit, + canManageObjectives = false, locked = false, map, initialMarkers, + initialObjectives = [], }: MissionPlanningMapProps) { const router = useRouter(); const [markers, setMarkers] = useState(initialMarkers); + const [objectives, setObjectives] = useState(initialObjectives); const [selectedId, setSelectedId] = useState(null); const [tool, setTool] = useState("select"); const [style, setStyle] = useState(DEFAULT_STYLE); const [cursor, setCursor] = useState(null); - const [showRoads, setShowRoads] = useState(true); - const [showZones, setShowZones] = useState(true); - const [showGrid, setShowGrid] = useState(true); + const [layers, setLayers] = useState(DEFAULT_LAYERS); const [world, setWorld] = useState({ width: map.worldWidth, height: map.worldHeight }); const [gridConfig, setGridConfig] = useState(DEFAULT_MAP_GRID); const [toggling, setToggling] = useState(false); + // Objective authoring (superuser tier only). + const [objectiveArmed, setObjectiveArmed] = useState(false); + const [objectiveDialogOpen, setObjectiveDialogOpen] = useState(false); + const [objectivePoint, setObjectivePoint] = useState(null); + const [editingObjective, setEditingObjective] = useState(null); const timers = useRef(new Map>()); const inflight = useRef(new Map>()); @@ -137,6 +208,24 @@ export function MissionPlanningMap({ } }, [missionId]); + const refreshObjectives = useCallback(async () => { + const result = await getMapObjectives({ mapId: map.id }); + if (result.success && result.data) setObjectives(result.data); + }, [map.id]); + + // Layer choices survive reloads: planning sessions tend to repeat. + useEffect(() => { + setLayers(readStoredLayers()); + }, []); + + useEffect(() => { + try { + window.localStorage.setItem(LAYERS_KEY, JSON.stringify(layers)); + } catch { + // Private mode / blocked storage: layer choices simply do not persist. + } + }, [layers]); + // Background refresh picks up other editors' changes, but never while a // local edit is pending (it would snap the marker back mid-edit). useEffect(() => { @@ -148,10 +237,11 @@ export function MissionPlanningMap({ document.visibilityState === "visible" ) { void refresh(); + void refreshObjectives(); } }, POLL_MS); return () => clearInterval(timer); - }, [enabled, refresh]); + }, [enabled, refresh, refreshObjectives]); useEffect(() => { const pending = timers.current; @@ -308,8 +398,15 @@ export function MissionPlanningMap({ const exportSqf = async () => { try { - await navigator.clipboard.writeText(markersToSqf(markers, world.height)); - toast.success(`Copied ${markers.length} markers as SQF.`, { + const exportMarkers: MissionMarker[] = [ + ...markers, + ...objectives.map((objective) => ({ + ...objectiveToMarker(objective), + text: objective.name, + })), + ]; + await navigator.clipboard.writeText(markersToSqf(exportMarkers, world.height)); + toast.success(`Copied ${exportMarkers.length} markers as SQF.`, { description: "Paste into the debug console or an init script.", }); } catch { @@ -334,8 +431,9 @@ export function MissionPlanningMap({ areas: markers.filter((marker) => marker.shape === "rectangle" || marker.shape === "ellipse") .length, lines: markers.filter((marker) => marker.shape === "polyline").length, + objectives: objectives.length, }), - [markers], + [markers, objectives], ); const selected = markers.find((marker) => marker.id === selectedId) ?? null; const ref = String((missionId * 37) % 1000).padStart(3, "0"); @@ -373,33 +471,58 @@ export function MissionPlanningMap({ Planning map // {missionLabel}
- - - + + + + + +
+ {LAYER_ROWS.map(({ key, label }) => ( + + ))} +
+ {canManageObjectives && ( +
+ + {objectiveArmed && ( +

+ Click the map to place the objective marker. +

+ )} +
+ )} +
+
{map.name} // REF {ref} @@ -409,23 +532,49 @@ export function MissionPlanningMap({
void handleCreate(data)} onChange={handleChange} onCursor={setCursor} + onObjectivePlace={(point) => { + setEditingObjective(null); + setObjectivePoint(point); + setObjectiveDialogOpen(true); + setObjectiveArmed(false); + }} + onEditObjective={(objective) => { + setEditingObjective(objective); + setObjectivePoint(null); + setObjectiveDialogOpen(true); + }} + onObjectiveUpdated={(objective) => + setObjectives((list) => + list.map((entry) => (entry.id === objective.id ? objective : entry)), + ) + } + onObjectiveDeleted={(id) => + setObjectives((list) => list.filter((entry) => entry.id !== id)) + } onLoaded={handleLoaded} />
@@ -450,38 +599,38 @@ export function MissionPlanningMap({ {canCurate && ( <> - - + + + + Clear the planning map? + + This removes all {markers.length} markers from this mission. It cannot be + undone. + + + + Cancel + void clearAll()}> + Clear markers + + + + + - - - - Clear the planning map? - - This removes all {markers.length} markers from this mission. It cannot be - undone. - - - - Cancel - void clearAll()}> - Clear markers - - - - - )}
@@ -500,6 +649,7 @@ export function MissionPlanningMap({ + void exportSqf()} - disabled={markers.length === 0} + disabled={markers.length === 0 && objectives.length === 0} title="Copy a createMarker script that recreates this plan in Arma 3" > @@ -522,6 +672,29 @@ export function MissionPlanningMap({
+ + {canManageObjectives && ( + { + setObjectiveDialogOpen(open); + if (!open) { + setObjectivePoint(null); + setEditingObjective(null); + } + }} + mapId={map.id} + objective={editingObjective} + position={objectivePoint} + onSaved={(objective, created) => + setObjectives((list) => + created + ? [...list, objective] + : list.map((entry) => (entry.id === objective.id ? objective : entry)), + ) + } + /> + )} ); } diff --git a/src/components/frontend/intelligence/missionMap/PlanningFeatureLayers.tsx b/src/components/frontend/intelligence/missionMap/PlanningFeatureLayers.tsx new file mode 100644 index 00000000..f52e6193 --- /dev/null +++ b/src/components/frontend/intelligence/missionMap/PlanningFeatureLayers.tsx @@ -0,0 +1,252 @@ +"use client"; + +import Link from "next/link"; +import type * as L from "leaflet"; +import { Circle, Marker, Polyline, Popup, Tooltip } from "react-leaflet"; +import { Button } from "@/components/ui/button"; +import { + STRUCTURE_STATUS, + nodeIconFor, + shipmentIcon, + structureStatusIcon, + toLatLng, +} from "@/components/frontend/map/mapIcons"; +import { interpolateAlong, type MapPoint } from "@/lib/map/points"; +import { splinePolyline } from "@/lib/map/style"; +import type { NodeFeature, ShipmentFeature, StructureFeature } from "@/lib/map/types"; + +const RANGE_RESOURCE_PATH: L.PathOptions = { + color: "#2dd4bf", + dashArray: "4 4", + fillOpacity: 0.03, + weight: 1, +}; + +const RANGE_STRUCTURE_PATH: L.PathOptions = { + color: "#a78bfa", + dashArray: "4 4", + fillOpacity: 0.03, + weight: 1, +}; + +const SHIPMENT_PATH: L.PathOptions = { + color: "#22d3ee", + weight: 2, + dashArray: "6 6", + opacity: 0.8, +}; + +function tonnes(kg: number): string { + return `${Math.round(kg / 100) / 10} t`; +} + +/** + * Compact reference layers for mission planning maps. The planning surface is + * read-only for logistics: pins, names and links back to the owning record, + * without the world map's authoring/ribbon machinery. + */ +export function StructureReferenceLayer({ structures }: { structures: StructureFeature[] }) { + return ( + <> + {structures.map((structure) => { + const statusKey = structure.constructionStatus ?? "complete"; + const label = STRUCTURE_STATUS[statusKey]?.label ?? "Structure"; + return ( + + +
{structure.name}
+
+ {label} + {structure.storageCapacityKg != null + ? ` // ${tonnes(structure.storageUsedKg)} / ${tonnes(structure.storageCapacityKg)}` + : ""} +
+
+ +
+
{structure.name}
+
{label}
+ {structure.blueprintName && ( +
{structure.blueprintName}
+ )} + {structure.storageCapacityKg != null && ( +
+ Storage {tonnes(structure.storageUsedKg)} /{" "} + {tonnes(structure.storageCapacityKg)} +
+ )} + {structure.factionName && ( +
Faction {structure.factionName}
+ )} +
+ +
+
+
+
+ ); + })} + + ); +} + +export function NodeReferenceLayer({ nodes }: { nodes: NodeFeature[] }) { + return ( + <> + {nodes.map((node) => ( + + +
{node.name}
+ {node.resources.length > 0 && ( +
+ {node.resources.map((entry) => entry.name).join(", ")} +
+ )} +
+ +
+
{node.name}
+ {node.resources.length > 0 ? ( +
+ Resources: {node.resources.map((entry) => entry.name).join(", ")} +
+ ) : ( +
Plain marker node
+ )} + {node.richness != null && node.resources.length > 0 && ( +
Richness {node.richness}
+ )} + {node.description &&

{node.description}

} +
+
+
+ ))} + + ); +} + +function shipmentPoint(shipment: ShipmentFeature): { + point: MapPoint; + bearing: number; +} | null { + const path = shipment.routePath; + if (!path || path.length < 2) return null; + const start = shipment.dispatchedAt ? new Date(shipment.dispatchedAt).getTime() : NaN; + const end = shipment.estimatedArrival ? new Date(shipment.estimatedArrival).getTime() : NaN; + const now = Date.now(); + const fraction = + Number.isFinite(start) && Number.isFinite(end) && end > start + ? Math.min(1, Math.max(0, (now - start) / (end - start))) + : 0.5; + return interpolateAlong(path, fraction); +} + +export function ShipmentReferenceLayer({ shipments }: { shipments: ShipmentFeature[] }) { + return ( + <> + {shipments.map((shipment) => { + const path = shipment.routePath; + const position = shipmentPoint(shipment); + return ( + + ); + })} + + ); +} + +function FragmentizedShipment({ + shipment, + path, + position, +}: { + shipment: ShipmentFeature; + path: MapPoint[] | null; + position: { point: MapPoint; bearing: number } | null; +}) { + return ( + <> + {path && path.length > 1 && ( + + )} + {position && ( + + +
{shipment.name ?? `Shipment #${shipment.id}`}
+
+ {shipment.originName ?? "unknown"} to {shipment.destinationName ?? "unknown"} +
+
+ +
+
{shipment.name ?? `Shipment #${shipment.id}`}
+
{shipment.status}
+
+ {shipment.originName ?? "unknown"} to {shipment.destinationName ?? "unknown"} +
+ {shipment.vehicleName && ( +
Vehicle {shipment.vehicleName}
+ )} +
+ +
+
+
+
+ )} + + ); +} + +/** Resource/structure range circles for structures on this map. */ +export function RangeReferenceLayer({ structures }: { structures: StructureFeature[] }) { + return ( + <> + {structures.flatMap((structure) => + [ + ...structure.resourcesInRange.map((requirement) => ({ + kind: "resource" as const, + range: requirement.range ?? 0, + })), + ...structure.structuresInRange.map((requirement) => ({ + kind: "structure" as const, + range: requirement.range ?? 0, + })), + ] + .filter((requirement) => requirement.range > 0) + .map((requirement, index) => ( + + )), + )} + + ); +} diff --git a/src/components/frontend/map/MapClient.tsx b/src/components/frontend/map/MapClient.tsx index db2d21a8..259b7d26 100644 --- a/src/components/frontend/map/MapClient.tsx +++ b/src/components/frontend/map/MapClient.tsx @@ -19,7 +19,7 @@ import { useMapEvents, } from "react-leaflet"; import Link from "next/link"; -import { Hammer, Pencil, RefreshCw } from "lucide-react"; +import { Hammer, Pencil, RefreshCw, Target } from "lucide-react"; import { Button } from "@/components/ui/button"; import { useGameTick } from "@/hooks/useGameTick"; import { @@ -51,15 +51,29 @@ import { GridLayer } from "./GridLayer"; import { PlacementDialog } from "./PlacementDialog"; import { AuthoringToolbar, useMapAuthoring } from "./AuthoringToolbar"; import { StructureDetailDrawer } from "./StructureDetailDrawer"; -import { nodeIconOption } from "@/lib/map/nodeIcons"; +import { + STRUCTURE_STATUS, + STRUCTURE_SVG_PATHS, + dossierSvg, + escapeHtml, + nodeIconFor, + shipmentIcon, + toLatLng, +} from "./mapIcons"; +import { ObjectiveLayer } from "./objectives/ObjectiveLayer"; +import { ObjectiveDialog } from "./objectives/ObjectiveDialog"; +import type { MapObjectiveFeature } from "@/lib/map/types"; export interface MapClientProps { map: { id: number; name: string }; canAuthor: { roads: boolean; zones: boolean; nodes: boolean }; canPlace: boolean; + /** Superuser tier: may add, move, retitle and reveal strategic objectives. */ + canManageObjectives: boolean; } type LayerToggles = { + objectives: boolean; structures: boolean; nodes: boolean; roads: boolean; @@ -69,12 +83,6 @@ type LayerToggles = { grid: boolean; }; -const STRUCTURE_STATUS: Record = { - complete: { color: "#34d399", label: "Operational" }, - building: { color: "#60a5fa", label: "Building" }, - awaiting_materials: { color: "#fbbf24", label: "Awaiting materials" }, -}; - // Layer styling is hoisted to module constants: react-leaflet re-applies // pathOptions by reference, and a fresh object literal every render forces a // canvas redraw that glitches mid-zoom-animation. @@ -146,14 +154,6 @@ const RIBBON_HEIGHT_PX = 32; const RIBBON_GAP_PX = 6; const RIBBON_PIN_HALF_PX = STRUCTURE_PIN_SIZES.lg / 2; -function escapeHtml(text: string): string { - return text - .replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - .replaceAll('"', """); -} - const zoneLabelIconCache = new Map(); function zoneLabelIcon(name: string): L.DivIcon { @@ -245,65 +245,6 @@ function roadLabelSvgIcon( }); } -const toLatLng = (p: MapPoint): [number, number] => [-p[1], p[0]]; - -const NODE_SVG_PATH = ''; - -const SHIPMENT_SVG_PATH = ''; - -const STRUCTURE_SVG_PATHS: Record = { - complete: - '', - building: - '', - awaiting_materials: - '', -}; - -function dossierSvg(paths: string, color: string, bearingDeg?: number, size = 13): string { - const rotate = bearingDeg != null ? ` transform="rotate(${bearingDeg} 12 12)"` : ""; - return `${paths}`; -} - -const nodeIconCache = new Map(); - -function nodeIconFor(icon: string | null | undefined): L.DivIcon { - const key = icon ?? "marker"; - let cached = nodeIconCache.get(key); - if (!cached) { - const option = nodeIconOption(key); - cached = L.divIcon({ - className: "map-structure-icon", - html: `
${dossierSvg(option.path, "#22d3ee")}
`, - iconSize: [20, 20], - iconAnchor: [10, 10], - }); - nodeIconCache.set(key, cached); - } - return cached; -} - -const shipmentIconCache = new Map(); - -function shipmentIcon(bearing: number): L.DivIcon { - const bucket = Math.round(bearing / 5) * 5; - let icon = shipmentIconCache.get(bucket); - if (!icon) { - icon = L.divIcon({ - className: "map-structure-icon", - html: `
${dossierSvg( - SHIPMENT_SVG_PATH, - "#22d3ee", - bucket, - )}
`, - iconSize: [26, 26], - iconAnchor: [13, 13], - }); - shipmentIconCache.set(bucket, icon); - } - return icon; -} - const structureIconCache = new Map(); interface StructureRibbon { @@ -356,13 +297,7 @@ function formatEta(estimatedArrival: string | null, nowMs: number): string | nul return `ETA ${Math.floor(minutes / 60)}h ${minutes % 60}m`; } -function MousePosition({ - grid, - worldHeight, -}: { - grid: MapGridConfig | null; - worldHeight: number; -}) { +function MousePosition({ grid, worldHeight }: { grid: MapGridConfig | null; worldHeight: number }) { const [position, setPosition] = useState(null); useMapEvents({ mousemove: (event) => { @@ -1163,12 +1098,13 @@ function ShipmentLayer({ shipments }: { shipments: ShipmentFeature[] }) { ); } -export function MapClient({ map, canAuthor, canPlace }: MapClientProps) { +export function MapClient({ map, canAuthor, canPlace, canManageObjectives }: MapClientProps) { const canEdit = canAuthor.roads || canAuthor.zones || canAuthor.nodes; const selectedMapId = map.id; const [features, setFeatures] = useState(null); const [error, setError] = useState(null); const [toggles, setToggles] = useState({ + objectives: true, structures: true, nodes: true, roads: true, @@ -1181,6 +1117,11 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) { const [mode, setMode] = useState<"view" | "place" | "edit">("view"); const [pendingPoint, setPendingPoint] = useState(null); const [previewId, setPreviewId] = useState(null); + // Strategic objective authoring (superuser tier only). + const [objectiveArmed, setObjectiveArmed] = useState(false); + const [objectiveDialogOpen, setObjectiveDialogOpen] = useState(false); + const [objectivePoint, setObjectivePoint] = useState(null); + const [editingObjective, setEditingObjective] = useState(null); const fetchFeatures = useCallback(async (mapId: number) => { if (fetchingRef.current) return; @@ -1329,6 +1270,7 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) { const layerToggleKeys: { key: keyof LayerToggles; label: string }[] = [ ...(mapConfig?.grid.enabled ? [{ key: "grid" as const, label: "Grid" }] : []), + { key: "objectives", label: "Objectives" }, { key: "structures", label: "Structures" }, { key: "nodes", label: "Nodes" }, { key: "roads", label: "Roads" }, @@ -1340,7 +1282,9 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) { return (
)} + {features && toggles.objectives && ( + { + setEditingObjective(objective); + setObjectivePoint(null); + setObjectiveDialogOpen(true); + }} + onUpdated={(objective) => + setFeatures((current) => + current + ? { + ...current, + objectives: current.objectives.map((entry) => + entry.id === objective.id ? objective : entry, + ), + } + : current, + ) + } + onDeleted={(id) => + setFeatures((current) => + current + ? { + ...current, + objectives: current.objectives.filter((entry) => entry.id !== id), + } + : current, + ) + } + /> + )} + )} {mode === "place" && } + {objectiveArmed && ( + { + setEditingObjective(null); + setObjectivePoint(point); + setObjectiveDialogOpen(true); + setObjectiveArmed(false); + }} + /> + )} {mode === "edit" && authoring.kind != null && ( (current === "place" ? "view" : "place")); authoring.setKind(null); setPendingPoint(null); + setObjectiveArmed(false); }} > @@ -1724,6 +1713,23 @@ export function MapClient({ map, canAuthor, canPlace }: MapClientProps) { )} + {canManageObjectives && ( + + )} + {canEdit && (